Code

Fixing preview/swatch sizes.
[inkscape.git] / src / dialogs / swatches.cpp
1 /*
2  * A simple panel for color swatches
3  *
4  * Authors:
5  *   Jon A. Cruz
6  *
7  * Copyright (C) 2005 Jon A. Cruz
8  *
9  * Released under GNU GPL, read the file 'COPYING' for more information
10  */
11 #ifdef HAVE_CONFIG_H
12 # include <config.h>
13 #endif
15 #include <errno.h>
17 #include <gtk/gtkdialog.h> //for GTK_RESPONSE* types
18 #include <gtk/gtkdnd.h>
19 #include <gtk/gtkmenu.h>
20 #include <gtk/gtkmenuitem.h>
21 #include <gtk/gtkseparatormenuitem.h>
23 #include <glibmm/i18n.h>
24 #include <gdkmm/pixbuf.h>
25 #include "inkscape.h"
26 #include "document.h"
27 #include "desktop-handles.h"
28 #include "extension/db.h"
29 #include "inkscape.h"
30 #include "svg/svg-color.h"
31 #include "desktop-style.h"
32 #include "io/sys.h"
33 #include "path-prefix.h"
34 #include "swatches.h"
35 #include "sp-item.h"
36 #include "prefs-utils.h"
38 #include "eek-preview.h"
40 namespace Inkscape {
41 namespace UI {
42 namespace Dialogs {
45 ColorItem::ColorItem( unsigned int r, unsigned int g, unsigned int b, Glib::ustring& name ) :
46     def( r, g, b, name ),
47     _isLive(false),
48     _linkIsTone(false),
49     _linkPercent(0),
50     _linkGray(0),
51     _linkSrc(0)
52 {
53 }
55 ColorItem::~ColorItem()
56 {
57 }
59 ColorItem::ColorItem(ColorItem const &other) :
60     Inkscape::UI::Previewable()
61 {
62     if ( this != &other ) {
63         *this = other;
64     }
65 }
67 ColorItem &ColorItem::operator=(ColorItem const &other)
68 {
69     if ( this != &other ) {
70         def = other.def;
72         // TODO - correct linkage
73         _linkSrc = other._linkSrc;
74         g_message("Erk!");
75     }
76     return *this;
77 }
80 class JustForNow
81 {
82 public:
83     JustForNow() : _prefWidth(0) {}
85     Glib::ustring _name;
86     int _prefWidth;
87     std::vector<ColorItem*> _colors;
88 };
90 static std::vector<JustForNow*> possible;
94 typedef enum {
95     APP_X_INKY_COLOR_ID = 0,
96     APP_X_INKY_COLOR = 0,
97     APP_X_COLOR,
98     TEXT_DATA
99 } colorFlavorType;
101 static const GtkTargetEntry sourceColorEntries[] = {
102 #if ENABLE_MAGIC_COLORS
103 //    {"application/x-inkscape-color-id", GTK_TARGET_SAME_APP, APP_X_INKY_COLOR_ID},
104     {"application/x-inkscape-color", 0, APP_X_INKY_COLOR},
105 #endif // ENABLE_MAGIC_COLORS
106     {"application/x-color", 0, APP_X_COLOR},
107     {"text/plain", 0, TEXT_DATA},
108 };
110 void ColorItem::_dragGetColorData( GtkWidget *widget,
111                                    GdkDragContext *drag_context,
112                                    GtkSelectionData *data,
113                                    guint info,
114                                    guint time,
115                                    gpointer user_data)
117     (void)widget;
118     (void)drag_context;
119     (void)time;
120     static GdkAtom typeXColor = gdk_atom_intern("application/x-color", FALSE);
121     static GdkAtom typeText = gdk_atom_intern("text/plain", FALSE);
123     ColorItem* item = reinterpret_cast<ColorItem*>(user_data);
124     if ( info == TEXT_DATA ) {
125         gchar* tmp = g_strdup_printf("#%02x%02x%02x", item->def.getR(), item->def.getG(), item->def.getB() );
127         gtk_selection_data_set( data,
128                                 typeText,
129                                 8, // format
130                                 (guchar*)tmp,
131                                 strlen((const char*)tmp) + 1);
132         g_free(tmp);
133         tmp = 0;
134     } else if ( info == APP_X_INKY_COLOR ) {
135         Glib::ustring paletteName;
137         // Find where this thing came from
138         bool found = false;
139         int index = 0;
140         for ( std::vector<JustForNow*>::iterator it = possible.begin(); it != possible.end() && !found; ++it ) {
141             JustForNow* curr = *it;
142             index = 0;
143             for ( std::vector<ColorItem*>::iterator zz = curr->_colors.begin(); zz != curr->_colors.end(); ++zz ) {
144                 if ( item == *zz ) {
145                     found = true;
146                     paletteName = curr->_name;
147                     break;
148                 } else {
149                     index++;
150                 }
151             }
152         }
154 //         if ( found ) {
155 //             g_message("Found the color at entry %d in palette '%s'", index, paletteName.c_str() );
156 //         } else {
157 //             g_message("Unable to find the color");
158 //         }
159         int itemCount = 4 + 2 + 1 + paletteName.length();
161         guint16* tmp = new guint16[itemCount];
162         tmp[0] = (item->def.getR() << 8) | item->def.getR();
163         tmp[1] = (item->def.getG() << 8) | item->def.getG();
164         tmp[2] = (item->def.getB() << 8) | item->def.getB();
165         tmp[3] = 0xffff;
166         tmp[4] = (item->_isLive || !item->_listeners.empty() || (item->_linkSrc != 0) ) ? 1 : 0;
168         tmp[5] = index;
169         tmp[6] = paletteName.length();
170         for ( unsigned int i = 0; i < paletteName.length(); i++ ) {
171             tmp[7 + i] = paletteName[i];
172         }
173         gtk_selection_data_set( data,
174                                 typeXColor,
175                                 16, // format
176                                 reinterpret_cast<const guchar*>(tmp),
177                                 itemCount * 2);
178         delete[] tmp;
179     } else {
180         guint16 tmp[4];
181         tmp[0] = (item->def.getR() << 8) | item->def.getR();
182         tmp[1] = (item->def.getG() << 8) | item->def.getG();
183         tmp[2] = (item->def.getB() << 8) | item->def.getB();
184         tmp[3] = 0xffff;
185         gtk_selection_data_set( data,
186                                 typeXColor,
187                                 16, // format
188                                 reinterpret_cast<const guchar*>(tmp),
189                                 (3+1) * 2);
190     }
193 static void dragBegin( GtkWidget *widget, GdkDragContext* dc, gpointer data )
195     (void)widget;
196     ColorItem* item = reinterpret_cast<ColorItem*>(data);
197     if ( item )
198     {
199         Glib::RefPtr<Gdk::Pixbuf> thumb = Gdk::Pixbuf::create( Gdk::COLORSPACE_RGB, false, 8, 32, 24 );
200         guint32 fillWith = (0xff000000 & (item->def.getR() << 24))
201                          | (0x00ff0000 & (item->def.getG() << 16))
202                          | (0x0000ff00 & (item->def.getB() <<  8));
203         thumb->fill( fillWith );
204         gtk_drag_set_icon_pixbuf( dc, thumb->gobj(), 0, 0 );
205     }
209 //"drag-drop"
210 // gboolean dragDropColorData( GtkWidget *widget,
211 //                             GdkDragContext *drag_context,
212 //                             gint x,
213 //                             gint y,
214 //                             guint time,
215 //                             gpointer user_data)
216 // {
217 // // TODO finish
219 //     return TRUE;
220 // }
222 static void handleClick( GtkWidget* widget, gpointer callback_data ) {
223     (void)widget;
224     ColorItem* item = reinterpret_cast<ColorItem*>(callback_data);
225     if ( item ) {
226         item->buttonClicked(false);
227     }
230 static void handleSecondaryClick( GtkWidget* widget, gint arg1, gpointer callback_data ) {
231     (void)widget;
232     (void)arg1;
233     ColorItem* item = reinterpret_cast<ColorItem*>(callback_data);
234     if ( item ) {
235         item->buttonClicked(true);
236     }
239 static GtkWidget* popupMenu = 0;
240 static ColorItem* bounceTarget = 0;
242 static void redirClick( GtkMenuItem *menuitem, gpointer user_data )
244     (void)user_data;
245     if ( bounceTarget ) {
246         handleClick( GTK_WIDGET(menuitem), bounceTarget );
247     }
250 static void redirSecondaryClick( GtkMenuItem *menuitem, gpointer user_data )
252     (void)user_data;
253     if ( bounceTarget ) {
254         handleSecondaryClick( GTK_WIDGET(menuitem), 0, bounceTarget );
255     }
258 static gboolean handleButtonPress( GtkWidget* widget, GdkEventButton* event, gpointer user_data)
260     (void)widget;
261     gboolean handled = FALSE;
263     if ( (event->button == 3) && (event->type == GDK_BUTTON_PRESS) ) {
264         if ( !popupMenu ) {
265             popupMenu = gtk_menu_new();
266             GtkWidget* child = 0;
268             //TRANSLATORS: An item in context menu on a colour in the swatches
269             child = gtk_menu_item_new_with_label(_("Set fill"));
270             g_signal_connect( G_OBJECT(child),
271                               "activate",
272                               G_CALLBACK(redirClick),
273                               user_data);
274             gtk_menu_shell_append(GTK_MENU_SHELL(popupMenu), child);
276             //TRANSLATORS: An item in context menu on a colour in the swatches
277             child = gtk_menu_item_new_with_label(_("Set stroke"));
279             g_signal_connect( G_OBJECT(child),
280                               "activate",
281                               G_CALLBACK(redirSecondaryClick),
282                               user_data);
283             gtk_menu_shell_append(GTK_MENU_SHELL(popupMenu), child);
285             gtk_widget_show_all(popupMenu);
286         }
288         ColorItem* item = reinterpret_cast<ColorItem*>(user_data);
289         if ( item ) {
290             bounceTarget = item;
291             if ( popupMenu ) {
292                 gtk_menu_popup(GTK_MENU(popupMenu), NULL, NULL, NULL, NULL, event->button, event->time);
293                 handled = TRUE;
294             }
295         }
296     }
298     return handled;
301 static void dieDieDie( GtkObject *obj, gpointer user_data )
303     g_message("die die die %p  %p", obj, user_data );
306 static const GtkTargetEntry destColorTargets[] = {
307 #if ENABLE_MAGIC_COLORS
308 //    {"application/x-inkscape-color-id", GTK_TARGET_SAME_APP, APP_X_INKY_COLOR_ID},
309     {"application/x-inkscape-color", 0, APP_X_INKY_COLOR},
310 #endif // ENABLE_MAGIC_COLORS
311     {"application/x-color", 0, APP_X_COLOR},
312 };
314 #include "color.h" // for SP_RGBA32_U_COMPOSE
316 void ColorItem::_dropDataIn( GtkWidget *widget,
317                              GdkDragContext *drag_context,
318                              gint x, gint y,
319                              GtkSelectionData *data,
320                              guint info,
321                              guint event_time,
322                              gpointer user_data)
324     (void)widget;
325     (void)drag_context;
326     (void)x;
327     (void)y;
328     (void)event_time;
329 //     g_message("    droppy droppy   %d", info);
330      switch (info) {
331          case APP_X_INKY_COLOR:
332          {
333              if ( data->length >= 8 ) {
334                  // Careful about endian issues.
335                  guint16* dataVals = (guint16*)data->data;
336                  if ( user_data ) {
337                      ColorItem* item = reinterpret_cast<ColorItem*>(user_data);
338                      if ( item->def.isEditable() ) {
339                          // Shove on in the new value
340                          item->def.setRGB( 0x0ff & (dataVals[0] >> 8), 0x0ff & (dataVals[1] >> 8), 0x0ff & (dataVals[2] >> 8) );
341                      }
342                  }
343              }
344              break;
345          }
346          case APP_X_COLOR:
347          {
348              if ( data->length == 8 ) {
349                  // Careful about endian issues.
350                  guint16* dataVals = (guint16*)data->data;
351 //                  {
352 //                      gchar c[64] = {0};
353 //                      sp_svg_write_color( c, 64,
354 //                                          SP_RGBA32_U_COMPOSE(
355 //                                              0x0ff & (dataVals[0] >> 8),
356 //                                              0x0ff & (dataVals[1] >> 8),
357 //                                              0x0ff & (dataVals[2] >> 8),
358 //                                              0xff // can't have transparency in the color itself
359 //                                              //0x0ff & (data->data[3] >> 8),
360 //                                              ));
361 //                  }
362                  if ( user_data ) {
363                      ColorItem* item = reinterpret_cast<ColorItem*>(user_data);
364                      if ( item->def.isEditable() ) {
365                          // Shove on in the new value
366                          item->def.setRGB( 0x0ff & (dataVals[0] >> 8), 0x0ff & (dataVals[1] >> 8), 0x0ff & (dataVals[2] >> 8) );
367                      }
368                  }
369              }
370              break;
371          }
372          default:
373              g_message("unknown drop type");
374      }
378 static bool bruteForce( SPDocument* document, Inkscape::XML::Node* node, Glib::ustring const& match, int r, int g, int b )
380     bool changed = false;
382     if ( node ) {
383         gchar const * val = node->attribute("inkscape:x-fill-tag");
384         if ( val  && (match == val) ) {
385             SPObject *obj = document->getObjectByRepr( node );
387             gchar c[64] = {0};
388             sp_svg_write_color( c, sizeof(c), SP_RGBA32_U_COMPOSE( r, g, b, 0xff ) );
389             SPCSSAttr *css = sp_repr_css_attr_new();
390             sp_repr_css_set_property( css, "fill", c );
392             sp_desktop_apply_css_recursive( (SPItem*)obj, css, true );
393             ((SPItem*)obj)->updateRepr();
395             changed = true;
396         }
398         val = node->attribute("inkscape:x-stroke-tag");
399         if ( val  && (match == val) ) {
400             SPObject *obj = document->getObjectByRepr( node );
402             gchar c[64] = {0};
403             sp_svg_write_color( c, sizeof(c), SP_RGBA32_U_COMPOSE( r, g, b, 0xff ) );
404             SPCSSAttr *css = sp_repr_css_attr_new();
405             sp_repr_css_set_property( css, "stroke", c );
407             sp_desktop_apply_css_recursive( (SPItem*)obj, css, true );
408             ((SPItem*)obj)->updateRepr();
410             changed = true;
411         }
413         Inkscape::XML::Node* first = node->firstChild();
414         changed |= bruteForce( document, first, match, r, g, b );
416         changed |= bruteForce( document, node->next(), match, r, g, b );
417     }
419     return changed;
422 void ColorItem::_colorDefChanged(void* data)
424     ColorItem* item = reinterpret_cast<ColorItem*>(data);
425     if ( item ) {
426         for ( std::vector<Gtk::Widget*>::iterator it =  item->_previews.begin(); it != item->_previews.end(); ++it ) {
427             Gtk::Widget* widget = *it;
428             if ( IS_EEK_PREVIEW(widget->gobj()) ) {
429                 EekPreview * preview = EEK_PREVIEW(widget->gobj());
430                 eek_preview_set_color( preview,
431                                        (item->def.getR() << 8) | item->def.getR(),
432                                        (item->def.getG() << 8) | item->def.getG(),
433                                        (item->def.getB() << 8) | item->def.getB() );
435                 eek_preview_set_linked( preview, (LinkType)((item->_linkSrc ? PREVIEW_LINK_IN:0)
436                                                             | (item->_listeners.empty() ? 0:PREVIEW_LINK_OUT)
437                                                             | (item->_isLive ? PREVIEW_LINK_OTHER:0)) );
439                 widget->queue_draw();
440             }
441         }
443         for ( std::vector<ColorItem*>::iterator it = item->_listeners.begin(); it != item->_listeners.end(); ++it ) {
444             guint r = item->def.getR();
445             guint g = item->def.getG();
446             guint b = item->def.getB();
448             if ( (*it)->_linkIsTone ) {
449                 r = ( ((*it)->_linkPercent * (*it)->_linkGray) + ((100 - (*it)->_linkPercent) * r) ) / 100;
450                 g = ( ((*it)->_linkPercent * (*it)->_linkGray) + ((100 - (*it)->_linkPercent) * g) ) / 100;
451                 b = ( ((*it)->_linkPercent * (*it)->_linkGray) + ((100 - (*it)->_linkPercent) * b) ) / 100;
452             } else {
453                 r = ( ((*it)->_linkPercent * 255) + ((100 - (*it)->_linkPercent) * r) ) / 100;
454                 g = ( ((*it)->_linkPercent * 255) + ((100 - (*it)->_linkPercent) * g) ) / 100;
455                 b = ( ((*it)->_linkPercent * 255) + ((100 - (*it)->_linkPercent) * b) ) / 100;
456             }
458             (*it)->def.setRGB( r, g, b );
459         }
462         // Look for objects using this color
463         {
464             SPDesktop *desktop = SP_ACTIVE_DESKTOP;
465             if ( desktop ) {
466                 SPDocument* document = sp_desktop_document( desktop );
467                 Inkscape::XML::Node *rroot =  sp_document_repr_root( document );
468                 if ( rroot ) {
470                     // Find where this thing came from
471                     Glib::ustring paletteName;
472                     bool found = false;
473                     int index = 0;
474                     for ( std::vector<JustForNow*>::iterator it2 = possible.begin(); it2 != possible.end() && !found; ++it2 ) {
475                         JustForNow* curr = *it2;
476                         index = 0;
477                         for ( std::vector<ColorItem*>::iterator zz = curr->_colors.begin(); zz != curr->_colors.end(); ++zz ) {
478                             if ( item == *zz ) {
479                                 found = true;
480                                 paletteName = curr->_name;
481                                 break;
482                             } else {
483                                 index++;
484                             }
485                         }
486                     }
488                     if ( !paletteName.empty() ) {
489                         gchar* str = g_strdup_printf("%d|", index);
490                         paletteName.insert( 0, str );
491                         g_free(str);
492                         str = 0;
494                         if ( bruteForce( document, rroot, paletteName, item->def.getR(), item->def.getG(), item->def.getB() ) ) {
495                             sp_document_done( document , SP_VERB_DIALOG_SWATCHES, 
496                                               _("Change color definition"));
497                         }
498                     }
499                 }
500             }
501         }
502     }
506 Gtk::Widget* ColorItem::getPreview(PreviewStyle style, ViewType view, Inkscape::IconSize size)
508     Gtk::Widget* widget = 0;
509     if ( style == PREVIEW_STYLE_BLURB ) {
510         Gtk::Label *lbl = new Gtk::Label(def.descr);
511         lbl->set_alignment(Gtk::ALIGN_LEFT, Gtk::ALIGN_CENTER);
512         widget = lbl;
513     } else {
514 //         Glib::ustring blank("          ");
515 //         if ( size == Inkscape::ICON_SIZE_MENU || size == Inkscape::ICON_SIZE_DECORATION ) {
516 //             blank = " ";
517 //         }
519         GtkWidget* eekWidget = eek_preview_new();
520         EekPreview * preview = EEK_PREVIEW(eekWidget);
521         Gtk::Widget* newBlot = Glib::wrap(eekWidget);
523         eek_preview_set_color( preview, (def.getR() << 8) | def.getR(), (def.getG() << 8) | def.getG(), (def.getB() << 8) | def.getB());
525         eek_preview_set_details( preview, (::PreviewStyle)style, (::ViewType)view, (::GtkIconSize)size );
526         eek_preview_set_linked( preview, (LinkType)((_linkSrc ? PREVIEW_LINK_IN:0)
527                                                     | (_listeners.empty() ? 0:PREVIEW_LINK_OUT)
528                                                     | (_isLive ? PREVIEW_LINK_OTHER:0)) );
530         def.addCallback( _colorDefChanged, this );
532         GValue val = {0, {{0}, {0}}};
533         g_value_init( &val, G_TYPE_BOOLEAN );
534         g_value_set_boolean( &val, FALSE );
535         g_object_set_property( G_OBJECT(preview), "focus-on-click", &val );
537 /*
538         Gtk::Button *btn = new Gtk::Button(blank);
539         Gdk::Color color;
540         color.set_rgb((_r << 8)|_r, (_g << 8)|_g, (_b << 8)|_b);
541         btn->modify_bg(Gtk::STATE_NORMAL, color);
542         btn->modify_bg(Gtk::STATE_ACTIVE, color);
543         btn->modify_bg(Gtk::STATE_PRELIGHT, color);
544         btn->modify_bg(Gtk::STATE_SELECTED, color);
546         Gtk::Widget* newBlot = btn;
547 */
549         tips.set_tip((*newBlot), def.descr);
551 /*
552         newBlot->signal_clicked().connect( sigc::mem_fun(*this, &ColorItem::buttonClicked) );
554         sigc::signal<void> type_signal_something;
555 */
557         g_signal_connect( G_OBJECT(newBlot->gobj()),
558                           "clicked",
559                           G_CALLBACK(handleClick),
560                           this);
562         g_signal_connect( G_OBJECT(newBlot->gobj()),
563                           "alt-clicked",
564                           G_CALLBACK(handleSecondaryClick),
565                           this);
567         g_signal_connect( G_OBJECT(newBlot->gobj()),
568                           "button-press-event",
569                           G_CALLBACK(handleButtonPress),
570                           this);
572         gtk_drag_source_set( GTK_WIDGET(newBlot->gobj()),
573                              GDK_BUTTON1_MASK,
574                              sourceColorEntries,
575                              G_N_ELEMENTS(sourceColorEntries),
576                              GdkDragAction(GDK_ACTION_MOVE | GDK_ACTION_COPY) );
578         g_signal_connect( G_OBJECT(newBlot->gobj()),
579                           "drag-data-get",
580                           G_CALLBACK(ColorItem::_dragGetColorData),
581                           this);
583         g_signal_connect( G_OBJECT(newBlot->gobj()),
584                           "drag-begin",
585                           G_CALLBACK(dragBegin),
586                           this );
588 //         g_signal_connect( G_OBJECT(newBlot->gobj()),
589 //                           "drag-drop",
590 //                           G_CALLBACK(dragDropColorData),
591 //                           this);
593         if ( def.isEditable() )
594         {
595             gtk_drag_dest_set( GTK_WIDGET(newBlot->gobj()),
596                                GTK_DEST_DEFAULT_ALL,
597                                destColorTargets,
598                                G_N_ELEMENTS(destColorTargets),
599                                GdkDragAction(GDK_ACTION_COPY | GDK_ACTION_MOVE) );
602             g_signal_connect( G_OBJECT(newBlot->gobj()),
603                               "drag-data-received",
604                               G_CALLBACK(_dropDataIn),
605                               this );
606         }
608         g_signal_connect( G_OBJECT(newBlot->gobj()),
609                           "destroy",
610                           G_CALLBACK(dieDieDie),
611                           this);
614         widget = newBlot;
615     }
617     _previews.push_back( widget );
619     return widget;
622 void ColorItem::buttonClicked(bool secondary)
624     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
625     if (desktop) {
626         char const * attrName = secondary ? "stroke" : "fill";
627         guint32 rgba = (def.getR() << 24) | (def.getG() << 16) | (def.getB() << 8) | 0xff;
628         gchar c[64];
629         sp_svg_write_color(c, sizeof(c), rgba);
631         SPCSSAttr *css = sp_repr_css_attr_new();
632         sp_repr_css_set_property( css, attrName, c );
633         sp_desktop_set_style(desktop, css);
635         sp_repr_css_attr_unref(css);
636         sp_document_done (sp_desktop_document (desktop), SP_VERB_DIALOG_SWATCHES, 
637                           secondary? _("Set stroke color from swatch") : _("Set fill color from swatch"));
638     }
644 static char* trim( char* str ) {
645     char* ret = str;
646     while ( *str && (*str == ' ' || *str == '\t') ) {
647         str++;
648     }
649     ret = str;
650     while ( *str ) {
651         str++;
652     }
653     str--;
654     while ( str > ret && ( *str == ' ' || *str == '\t' ) || *str == '\r' || *str == '\n' ) {
655         *str-- = 0;
656     }
657     return ret;
660 void skipWhitespace( char*& str ) {
661     while ( *str == ' ' || *str == '\t' ) {
662         str++;
663     }
666 bool parseNum( char*& str, int& val ) {
667     val = 0;
668     while ( '0' <= *str && *str <= '9' ) {
669         val = val * 10 + (*str - '0');
670         str++;
671     }
672     bool retval = !(*str == 0 || *str == ' ' || *str == '\t' || *str == '\r' || *str == '\n');
673     return retval;
677 static bool getBlock( std::string& dst, guchar ch, std::string const str )
679     bool good = false;
680     std::string::size_type pos = str.find(ch);
681     if ( pos != std::string::npos )
682     {
683         std::string::size_type pos2 = str.find( '(', pos );
684         if ( pos2 != std::string::npos ) {
685             std::string::size_type endPos = str.find( ')', pos2 );
686             if ( endPos != std::string::npos ) {
687                 dst = str.substr( pos2 + 1, (endPos - pos2 - 1) );
688                 good = true;
689             }
690         }
691     }
692     return good;
695 static bool popVal( guint64& numVal, std::string& str )
697     bool good = false;
698     std::string::size_type endPos = str.find(',');
699     if ( endPos == std::string::npos ) {
700         endPos = str.length();
701     }
703     if ( endPos != std::string::npos && endPos > 0 ) {
704         std::string xxx = str.substr( 0, endPos );
705         const gchar* ptr = xxx.c_str();
706         gchar* endPtr = 0;
707         numVal = g_ascii_strtoull( ptr, &endPtr, 10 );
708         if ( (numVal == G_MAXUINT64) && (ERANGE == errno) ) {
709             // overflow
710         } else if ( (numVal == 0) && (endPtr == ptr) ) {
711             // failed conversion
712         } else {
713             good = true;
714             str.erase( 0, endPos + 1 );
715         }
716     }
718     return good;
721 void ColorItem::_wireMagicColors( void* p )
723     JustForNow* onceMore = reinterpret_cast<JustForNow*>(p);
724     if ( onceMore )
725     {
726         for ( std::vector<ColorItem*>::iterator it = onceMore->_colors.begin(); it != onceMore->_colors.end(); ++it )
727         {
728             std::string::size_type pos = (*it)->def.descr.find("*{");
729             if ( pos != std::string::npos )
730             {
731                 std::string subby = (*it)->def.descr.substr( pos + 2 );
732                 std::string::size_type endPos = subby.find("}*");
733                 if ( endPos != std::string::npos )
734                 {
735                     subby.erase( endPos );
736                     //g_message("FOUND MAGIC at '%s'", (*it)->def.descr.c_str());
737                     //g_message("               '%s'", subby.c_str());
739                     if ( subby.find('E') != std::string::npos )
740                     {
741                         (*it)->def.setEditable( true );
742                     }
744                     if ( subby.find('L') != std::string::npos )
745                     {
746                         (*it)->_isLive = true;
747                     }
749                     std::string part;
750                     // Tint. index + 1 more val.
751                     if ( getBlock( part, 'T', subby ) ) {
752                         guint64 colorIndex = 0;
753                         if ( popVal( colorIndex, part ) ) {
754                             guint64 percent = 0;
755                             if ( popVal( percent, part ) ) {
756                                 (*it)->_linkTint( *(onceMore->_colors[colorIndex]), percent );
757                             }
758                         }
759                     }
761                     // Shade/tone. index + 1 or 2 more val.
762                     if ( getBlock( part, 'S', subby ) ) {
763                         guint64 colorIndex = 0;
764                         if ( popVal( colorIndex, part ) ) {
765                             guint64 percent = 0;
766                             if ( popVal( percent, part ) ) {
767                                 guint64 grayLevel = 0;
768                                 if ( !popVal( grayLevel, part ) ) {
769                                     grayLevel = 0;
770                                 }
771                                 (*it)->_linkTone( *(onceMore->_colors[colorIndex]), percent, grayLevel );
772                             }
773                         }
774                     }
776                 }
777             }
778         }
779     }
783 void ColorItem::_linkTint( ColorItem& other, int percent )
785     if ( !_linkSrc )
786     {
787         other._listeners.push_back(this);
788         _linkIsTone = false;
789         _linkPercent = percent;
790         if ( _linkPercent > 100 )
791             _linkPercent = 100;
792         if ( _linkPercent < 0 )
793             _linkPercent = 0;
794         _linkGray = 0;
795         _linkSrc = &other;
797         ColorItem::_colorDefChanged(&other);
798     }
801 void ColorItem::_linkTone( ColorItem& other, int percent, int grayLevel )
803     if ( !_linkSrc )
804     {
805         other._listeners.push_back(this);
806         _linkIsTone = true;
807         _linkPercent = percent;
808         if ( _linkPercent > 100 )
809             _linkPercent = 100;
810         if ( _linkPercent < 0 )
811             _linkPercent = 0;
812         _linkGray = grayLevel;
813         _linkSrc = &other;
815         ColorItem::_colorDefChanged(&other);
816     }
820 void _loadPaletteFile( gchar const *filename )
822     char block[1024];
823     FILE *f = Inkscape::IO::fopen_utf8name( filename, "r" );
824     if ( f ) {
825         char* result = fgets( block, sizeof(block), f );
826         if ( result ) {
827             if ( strncmp( "GIMP Palette", block, 12 ) == 0 ) {
828                 bool inHeader = true;
829                 bool hasErr = false;
831                 JustForNow *onceMore = new JustForNow();
833                 do {
834                     result = fgets( block, sizeof(block), f );
835                     block[sizeof(block) - 1] = 0;
836                     if ( result ) {
837                         if ( block[0] == '#' ) {
838                             // ignore comment
839                         } else {
840                             char *ptr = block;
841                             // very simple check for header versus entry
842                             while ( *ptr == ' ' || *ptr == '\t' ) {
843                                 ptr++;
844                             }
845                             if ( *ptr == 0 ) {
846                                 // blank line. skip it.
847                             } else if ( '0' <= *ptr && *ptr <= '9' ) {
848                                 // should be an entry link
849                                 inHeader = false;
850                                 ptr = block;
851                                 Glib::ustring name("");
852                                 int r = 0;
853                                 int g = 0;
854                                 int b = 0;
855                                 skipWhitespace(ptr);
856                                 if ( *ptr ) {
857                                     hasErr = parseNum(ptr, r);
858                                     if ( !hasErr ) {
859                                         skipWhitespace(ptr);
860                                         hasErr = parseNum(ptr, g);
861                                     }
862                                     if ( !hasErr ) {
863                                         skipWhitespace(ptr);
864                                         hasErr = parseNum(ptr, b);
865                                     }
866                                     if ( !hasErr && *ptr ) {
867                                         char* n = trim(ptr);
868                                         if (n != NULL) {
869                                             name = n;
870                                         }
871                                     }
872                                     if ( !hasErr ) {
873                                         // Add the entry now
874                                         Glib::ustring nameStr(name);
875                                         ColorItem* item = new ColorItem( r, g, b, nameStr );
876                                         onceMore->_colors.push_back(item);
877                                     }
878                                 } else {
879                                     hasErr = true;
880                                 }
881                             } else {
882                                 if ( !inHeader ) {
883                                     // Hmmm... probably bad. Not quite the format we want?
884                                     hasErr = true;
885                                 } else {
886                                     char* sep = strchr(result, ':');
887                                     if ( sep ) {
888                                         *sep = 0;
889                                         char* val = trim(sep + 1);
890                                         char* name = trim(result);
891                                         if ( *name ) {
892                                             if ( strcmp( "Name", name ) == 0 )
893                                             {
894                                                 onceMore->_name = val;
895                                             }
896                                             else if ( strcmp( "Columns", name ) == 0 )
897                                             {
898                                                 gchar* endPtr = 0;
899                                                 guint64 numVal = g_ascii_strtoull( val, &endPtr, 10 );
900                                                 if ( (numVal == G_MAXUINT64) && (ERANGE == errno) ) {
901                                                     // overflow
902                                                 } else if ( (numVal == 0) && (endPtr == val) ) {
903                                                     // failed conversion
904                                                 } else {
905                                                     onceMore->_prefWidth = numVal;
906                                                 }
907                                             }
908                                         } else {
909                                             // error
910                                             hasErr = true;
911                                         }
912                                     } else {
913                                         // error
914                                         hasErr = true;
915                                     }
916                                 }
917                             }
918                         }
919                     }
920                 } while ( result && !hasErr );
921                 if ( !hasErr ) {
922                     possible.push_back(onceMore);
923 #if ENABLE_MAGIC_COLORS
924                     ColorItem::_wireMagicColors( onceMore );
925 #endif // ENABLE_MAGIC_COLORS
926                 } else {
927                     delete onceMore;
928                 }
929             }
930         }
932         fclose(f);
933     }
936 static void loadEmUp()
938     static bool beenHere = false;
939     if ( !beenHere ) {
940         beenHere = true;
942         std::list<gchar *> sources;
943         sources.push_back( profile_path("palettes") );
944         sources.push_back( g_strdup(INKSCAPE_PALETTESDIR) );
945         sources.push_back( g_strdup(CREATE_PALETTESDIR) );
947         // Use this loop to iterate through a list of possible document locations.
948         while (!sources.empty()) {
949             gchar *dirname = sources.front();
951             if ( Inkscape::IO::file_test( dirname, (GFileTest)(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR) ) ) {
952                 GError *err = 0;
953                 GDir *directory = g_dir_open(dirname, 0, &err);
954                 if (!directory) {
955                     gchar *safeDir = Inkscape::IO::sanitizeString(dirname);
956                     g_warning(_("Palettes directory (%s) is unavailable."), safeDir);
957                     g_free(safeDir);
958                 } else {
959                     gchar *filename = 0;
960                     while ((filename = (gchar *)g_dir_read_name(directory)) != NULL) {
961                         gchar* lower = g_ascii_strdown( filename, -1 );
962 //                        if ( g_str_has_suffix(lower, ".gpl") ) {
963                             gchar* full = g_build_filename(dirname, filename, NULL);
964                             if ( !Inkscape::IO::file_test( full, (GFileTest)(G_FILE_TEST_IS_DIR ) ) ) {
965                                 _loadPaletteFile(full);
966                             }
967                             g_free(full);
968 //                      }
969                         g_free(lower);
970                     }
971                     g_dir_close(directory);
972                 }
973             }
975             // toss the dirname
976             g_free(dirname);
977             sources.pop_front();
978         }
979     }
990 SwatchesPanel& SwatchesPanel::getInstance()
992     return *new SwatchesPanel();
996 /**
997  * Constructor
998  */
999 SwatchesPanel::SwatchesPanel(gchar const* prefsPath) :
1000     Inkscape::UI::Widget::Panel("", prefsPath, SP_VERB_DIALOG_SWATCHES, "", true),
1001     _holder(0)
1003     Gtk::RadioMenuItem* hotItem = 0;
1004     _holder = new PreviewHolder();
1005     loadEmUp();
1007     if ( !possible.empty() ) {
1008         JustForNow* first = 0;
1009         gchar const* targetName = 0;
1010         if ( _prefs_path ) {
1011             targetName = prefs_get_string_attribute( _prefs_path, "palette" );
1012             if ( targetName ) {
1013                 for ( std::vector<JustForNow*>::iterator iter = possible.begin(); iter != possible.end(); ++iter ) {
1014                     if ( (*iter)->_name == targetName ) {
1015                         first = *iter;
1016                         break;
1017                     }
1018                 }
1019             }
1020         }
1022         if ( !first ) {
1023             first = possible.front();
1024         }
1026         if ( first->_prefWidth > 0 ) {
1027             _holder->setColumnPref( first->_prefWidth );
1028         }
1029         _holder->freezeUpdates();
1030         for ( std::vector<ColorItem*>::iterator it = first->_colors.begin(); it != first->_colors.end(); it++ ) {
1031             _holder->addPreview(*it);
1032         }
1033         _holder->thawUpdates();
1035         Gtk::RadioMenuItem::Group groupOne;
1036         int i = 0;
1037         for ( std::vector<JustForNow*>::iterator it = possible.begin(); it != possible.end(); it++ ) {
1038             JustForNow* curr = *it;
1039             Gtk::RadioMenuItem* single = manage(new Gtk::RadioMenuItem(groupOne, curr->_name));
1040             if ( curr == first ) {
1041                 hotItem = single;
1042             }
1043             _regItem( single, 3, i );
1044             i++;
1045         }
1047     }
1050     _getContents()->pack_start(*_holder, Gtk::PACK_EXPAND_WIDGET);
1051     _setTargetFillable(_holder);
1053     show_all_children();
1055     restorePanelPrefs();
1056     if ( hotItem ) {
1057         hotItem->set_active();
1058     }
1061 SwatchesPanel::~SwatchesPanel()
1065 void SwatchesPanel::setOrientation( Gtk::AnchorType how )
1067     // Must call the parent class or bad things might happen
1068     Inkscape::UI::Widget::Panel::setOrientation( how );
1070     if ( _holder )
1071     {
1072         _holder->setOrientation( Gtk::ANCHOR_SOUTH );
1073     }
1076 void SwatchesPanel::_handleAction( int setId, int itemId )
1078     switch( setId ) {
1079         case 3:
1080         {
1081             if ( itemId >= 0 && itemId < static_cast<int>(possible.size()) ) {
1082                 _holder->clear();
1083                 JustForNow* curr = possible[itemId];
1085                 if ( _prefs_path ) {
1086                     prefs_set_string_attribute( _prefs_path, "palette", curr->_name.c_str() );
1087                 }
1089                 if ( curr->_prefWidth > 0 ) {
1090                     _holder->setColumnPref( curr->_prefWidth );
1091                 }
1092                 _holder->freezeUpdates();
1093                 for ( std::vector<ColorItem*>::iterator it = curr->_colors.begin(); it != curr->_colors.end(); it++ ) {
1094                     _holder->addPreview(*it);
1095                 }
1096                 _holder->thawUpdates();
1097             }
1098         }
1099         break;
1100     }
1103 } //namespace Dialogs
1104 } //namespace UI
1105 } //namespace Inkscape
1108 /*
1109   Local Variables:
1110   mode:c++
1111   c-file-style:"stroustrup"
1112   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1113   indent-tabs-mode:nil
1114   fill-column:99
1115   End:
1116 */
1117 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :