Code

Show the name of the swatch that is currently under the pointer in the status bar...
[inkscape.git] / src / dialogs / swatches.cpp
1 /*
2  * A simple panel for color swatches
3  *
4  * Authors:
5  *   Jon A. Cruz
6  *   John Bintz
7  *
8  * Copyright (C) 2005 Jon A. Cruz
9  * Copyright (C) 2008 John Bintz
10  *
11  * Released under GNU GPL, read the file 'COPYING' for more information
12  */
13 #ifdef HAVE_CONFIG_H
14 # include <config.h>
15 #endif
17 #include <errno.h>
19 #include <gtk/gtkdialog.h> //for GTK_RESPONSE* types
20 #include <gtk/gtkdnd.h>
21 #include <gtk/gtkmenu.h>
22 #include <gtk/gtkmenuitem.h>
23 #include <gtk/gtkseparatormenuitem.h>
25 #include <glibmm/i18n.h>
26 #include <gdkmm/pixbuf.h>
27 #include "inkscape.h"
28 #include "desktop.h"
29 #include "message-stack.h"
30 #include "document.h"
31 #include "desktop-handles.h"
32 #include "extension/db.h"
33 #include "inkscape.h"
34 #include "svg/svg-color.h"
35 #include "desktop-style.h"
36 #include "io/sys.h"
37 #include "path-prefix.h"
38 #include "swatches.h"
39 #include "sp-item.h"
40 #include "prefs-utils.h"
42 #include "eek-preview.h"
44 namespace Inkscape {
45 namespace UI {
46 namespace Dialogs {
49 ColorItem::ColorItem( unsigned int r, unsigned int g, unsigned int b, Glib::ustring& name ) :
50     def( r, g, b, name ),
51     _isLive(false),
52     _linkIsTone(false),
53     _linkPercent(0),
54     _linkGray(0),
55     _linkSrc(0)
56 {
57 }
59 ColorItem::~ColorItem()
60 {
61 }
63 ColorItem::ColorItem(ColorItem const &other) :
64     Inkscape::UI::Previewable()
65 {
66     if ( this != &other ) {
67         *this = other;
68     }
69 }
71 ColorItem &ColorItem::operator=(ColorItem const &other)
72 {
73     if ( this != &other ) {
74         def = other.def;
76         // TODO - correct linkage
77         _linkSrc = other._linkSrc;
78         g_message("Erk!");
79     }
80     return *this;
81 }
84 class JustForNow
85 {
86 public:
87     JustForNow() : _prefWidth(0) {}
89     Glib::ustring _name;
90     int _prefWidth;
91     std::vector<ColorItem*> _colors;
92 };
94 static std::vector<JustForNow*> possible;
98 typedef enum {
99     APP_X_INKY_COLOR_ID = 0,
100     APP_X_INKY_COLOR = 0,
101     APP_X_COLOR,
102     TEXT_DATA
103 } colorFlavorType;
105 static const GtkTargetEntry sourceColorEntries[] = {
106 #if ENABLE_MAGIC_COLORS
107 //    {"application/x-inkscape-color-id", GTK_TARGET_SAME_APP, APP_X_INKY_COLOR_ID},
108     {"application/x-inkscape-color", 0, APP_X_INKY_COLOR},
109 #endif // ENABLE_MAGIC_COLORS
110     {"application/x-color", 0, APP_X_COLOR},
111     {"text/plain", 0, TEXT_DATA},
112 };
114 void ColorItem::_dragGetColorData( GtkWidget *widget,
115                                    GdkDragContext *drag_context,
116                                    GtkSelectionData *data,
117                                    guint info,
118                                    guint time,
119                                    gpointer user_data)
121     (void)widget;
122     (void)drag_context;
123     (void)time;
124     static GdkAtom typeXColor = gdk_atom_intern("application/x-color", FALSE);
125     static GdkAtom typeText = gdk_atom_intern("text/plain", FALSE);
127     ColorItem* item = reinterpret_cast<ColorItem*>(user_data);
128     if ( info == TEXT_DATA ) {
129         gchar* tmp = g_strdup_printf("#%02x%02x%02x", item->def.getR(), item->def.getG(), item->def.getB() );
131         gtk_selection_data_set( data,
132                                 typeText,
133                                 8, // format
134                                 (guchar*)tmp,
135                                 strlen((const char*)tmp) + 1);
136         g_free(tmp);
137         tmp = 0;
138     } else if ( info == APP_X_INKY_COLOR ) {
139         Glib::ustring paletteName;
141         // Find where this thing came from
142         bool found = false;
143         int index = 0;
144         for ( std::vector<JustForNow*>::iterator it = possible.begin(); it != possible.end() && !found; ++it ) {
145             JustForNow* curr = *it;
146             index = 0;
147             for ( std::vector<ColorItem*>::iterator zz = curr->_colors.begin(); zz != curr->_colors.end(); ++zz ) {
148                 if ( item == *zz ) {
149                     found = true;
150                     paletteName = curr->_name;
151                     break;
152                 } else {
153                     index++;
154                 }
155             }
156         }
158 //         if ( found ) {
159 //             g_message("Found the color at entry %d in palette '%s'", index, paletteName.c_str() );
160 //         } else {
161 //             g_message("Unable to find the color");
162 //         }
163         int itemCount = 4 + 2 + 1 + paletteName.length();
165         guint16* tmp = new guint16[itemCount];
166         tmp[0] = (item->def.getR() << 8) | item->def.getR();
167         tmp[1] = (item->def.getG() << 8) | item->def.getG();
168         tmp[2] = (item->def.getB() << 8) | item->def.getB();
169         tmp[3] = 0xffff;
170         tmp[4] = (item->_isLive || !item->_listeners.empty() || (item->_linkSrc != 0) ) ? 1 : 0;
172         tmp[5] = index;
173         tmp[6] = paletteName.length();
174         for ( unsigned int i = 0; i < paletteName.length(); i++ ) {
175             tmp[7 + i] = paletteName[i];
176         }
177         gtk_selection_data_set( data,
178                                 typeXColor,
179                                 16, // format
180                                 reinterpret_cast<const guchar*>(tmp),
181                                 itemCount * 2);
182         delete[] tmp;
183     } else {
184         guint16 tmp[4];
185         tmp[0] = (item->def.getR() << 8) | item->def.getR();
186         tmp[1] = (item->def.getG() << 8) | item->def.getG();
187         tmp[2] = (item->def.getB() << 8) | item->def.getB();
188         tmp[3] = 0xffff;
189         gtk_selection_data_set( data,
190                                 typeXColor,
191                                 16, // format
192                                 reinterpret_cast<const guchar*>(tmp),
193                                 (3+1) * 2);
194     }
197 static void dragBegin( GtkWidget *widget, GdkDragContext* dc, gpointer data )
199     (void)widget;
200     ColorItem* item = reinterpret_cast<ColorItem*>(data);
201     if ( item )
202     {
203         Glib::RefPtr<Gdk::Pixbuf> thumb = Gdk::Pixbuf::create( Gdk::COLORSPACE_RGB, false, 8, 32, 24 );
204         guint32 fillWith = (0xff000000 & (item->def.getR() << 24))
205                          | (0x00ff0000 & (item->def.getG() << 16))
206                          | (0x0000ff00 & (item->def.getB() <<  8));
207         thumb->fill( fillWith );
208         gtk_drag_set_icon_pixbuf( dc, thumb->gobj(), 0, 0 );
209     }
213 //"drag-drop"
214 // gboolean dragDropColorData( GtkWidget *widget,
215 //                             GdkDragContext *drag_context,
216 //                             gint x,
217 //                             gint y,
218 //                             guint time,
219 //                             gpointer user_data)
220 // {
221 // // TODO finish
223 //     return TRUE;
224 // }
226 static void handleClick( GtkWidget* widget, gpointer callback_data ) {
227     (void)widget;
228     ColorItem* item = reinterpret_cast<ColorItem*>(callback_data);
229     if ( item ) {
230         item->buttonClicked(false);
231     }
234 static void handleSecondaryClick( GtkWidget* widget, gint arg1, gpointer callback_data ) {
235     (void)widget;
236     (void)arg1;
237     ColorItem* item = reinterpret_cast<ColorItem*>(callback_data);
238     if ( item ) {
239         item->buttonClicked(true);
240     }
243 static void handleEnterNotify( GtkWidget* widget, GdkEventCrossing* event, gpointer callback_data ) {
244     ColorItem* item = reinterpret_cast<ColorItem*>(callback_data);
245     if ( item ) {
246         SPDesktop *desktop = SP_ACTIVE_DESKTOP;
247         if ( desktop ) {
248             desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, g_strconcat(
249               _("Swatch info: <b>"),
250               item->def.descr.c_str(),
251               _("</b>"),
252               NULL
253             ));
254         }
255     }
258 static GtkWidget* popupMenu = 0;
259 static ColorItem* bounceTarget = 0;
261 static void redirClick( GtkMenuItem *menuitem, gpointer user_data )
263     (void)user_data;
264     if ( bounceTarget ) {
265         handleClick( GTK_WIDGET(menuitem), bounceTarget );
266     }
269 static void redirSecondaryClick( GtkMenuItem *menuitem, gpointer user_data )
271     (void)user_data;
272     if ( bounceTarget ) {
273         handleSecondaryClick( GTK_WIDGET(menuitem), 0, bounceTarget );
274     }
277 static gboolean handleButtonPress( GtkWidget* widget, GdkEventButton* event, gpointer user_data)
279     (void)widget;
280     gboolean handled = FALSE;
282     if ( (event->button == 3) && (event->type == GDK_BUTTON_PRESS) ) {
283         if ( !popupMenu ) {
284             popupMenu = gtk_menu_new();
285             GtkWidget* child = 0;
287             //TRANSLATORS: An item in context menu on a colour in the swatches
288             child = gtk_menu_item_new_with_label(_("Set fill"));
289             g_signal_connect( G_OBJECT(child),
290                               "activate",
291                               G_CALLBACK(redirClick),
292                               user_data);
293             gtk_menu_shell_append(GTK_MENU_SHELL(popupMenu), child);
295             //TRANSLATORS: An item in context menu on a colour in the swatches
296             child = gtk_menu_item_new_with_label(_("Set stroke"));
298             g_signal_connect( G_OBJECT(child),
299                               "activate",
300                               G_CALLBACK(redirSecondaryClick),
301                               user_data);
302             gtk_menu_shell_append(GTK_MENU_SHELL(popupMenu), child);
304             gtk_widget_show_all(popupMenu);
305         }
307         ColorItem* item = reinterpret_cast<ColorItem*>(user_data);
308         if ( item ) {
309             bounceTarget = item;
310             if ( popupMenu ) {
311                 gtk_menu_popup(GTK_MENU(popupMenu), NULL, NULL, NULL, NULL, event->button, event->time);
312                 handled = TRUE;
313             }
314         }
315     }
317     return handled;
320 static void dieDieDie( GtkObject *obj, gpointer user_data )
322     g_message("die die die %p  %p", obj, user_data );
325 static const GtkTargetEntry destColorTargets[] = {
326 #if ENABLE_MAGIC_COLORS
327 //    {"application/x-inkscape-color-id", GTK_TARGET_SAME_APP, APP_X_INKY_COLOR_ID},
328     {"application/x-inkscape-color", 0, APP_X_INKY_COLOR},
329 #endif // ENABLE_MAGIC_COLORS
330     {"application/x-color", 0, APP_X_COLOR},
331 };
333 #include "color.h" // for SP_RGBA32_U_COMPOSE
335 void ColorItem::_dropDataIn( GtkWidget *widget,
336                              GdkDragContext *drag_context,
337                              gint x, gint y,
338                              GtkSelectionData *data,
339                              guint info,
340                              guint event_time,
341                              gpointer user_data)
343     (void)widget;
344     (void)drag_context;
345     (void)x;
346     (void)y;
347     (void)event_time;
348 //     g_message("    droppy droppy   %d", info);
349      switch (info) {
350          case APP_X_INKY_COLOR:
351          {
352              if ( data->length >= 8 ) {
353                  // Careful about endian issues.
354                  guint16* dataVals = (guint16*)data->data;
355                  if ( user_data ) {
356                      ColorItem* item = reinterpret_cast<ColorItem*>(user_data);
357                      if ( item->def.isEditable() ) {
358                          // Shove on in the new value
359                          item->def.setRGB( 0x0ff & (dataVals[0] >> 8), 0x0ff & (dataVals[1] >> 8), 0x0ff & (dataVals[2] >> 8) );
360                      }
361                  }
362              }
363              break;
364          }
365          case APP_X_COLOR:
366          {
367              if ( data->length == 8 ) {
368                  // Careful about endian issues.
369                  guint16* dataVals = (guint16*)data->data;
370 //                  {
371 //                      gchar c[64] = {0};
372 //                      sp_svg_write_color( c, 64,
373 //                                          SP_RGBA32_U_COMPOSE(
374 //                                              0x0ff & (dataVals[0] >> 8),
375 //                                              0x0ff & (dataVals[1] >> 8),
376 //                                              0x0ff & (dataVals[2] >> 8),
377 //                                              0xff // can't have transparency in the color itself
378 //                                              //0x0ff & (data->data[3] >> 8),
379 //                                              ));
380 //                  }
381                  if ( user_data ) {
382                      ColorItem* item = reinterpret_cast<ColorItem*>(user_data);
383                      if ( item->def.isEditable() ) {
384                          // Shove on in the new value
385                          item->def.setRGB( 0x0ff & (dataVals[0] >> 8), 0x0ff & (dataVals[1] >> 8), 0x0ff & (dataVals[2] >> 8) );
386                      }
387                  }
388              }
389              break;
390          }
391          default:
392              g_message("unknown drop type");
393      }
397 static bool bruteForce( SPDocument* document, Inkscape::XML::Node* node, Glib::ustring const& match, int r, int g, int b )
399     bool changed = false;
401     if ( node ) {
402         gchar const * val = node->attribute("inkscape:x-fill-tag");
403         if ( val  && (match == val) ) {
404             SPObject *obj = document->getObjectByRepr( node );
406             gchar c[64] = {0};
407             sp_svg_write_color( c, sizeof(c), SP_RGBA32_U_COMPOSE( r, g, b, 0xff ) );
408             SPCSSAttr *css = sp_repr_css_attr_new();
409             sp_repr_css_set_property( css, "fill", c );
411             sp_desktop_apply_css_recursive( (SPItem*)obj, css, true );
412             ((SPItem*)obj)->updateRepr();
414             changed = true;
415         }
417         val = node->attribute("inkscape:x-stroke-tag");
418         if ( val  && (match == val) ) {
419             SPObject *obj = document->getObjectByRepr( node );
421             gchar c[64] = {0};
422             sp_svg_write_color( c, sizeof(c), SP_RGBA32_U_COMPOSE( r, g, b, 0xff ) );
423             SPCSSAttr *css = sp_repr_css_attr_new();
424             sp_repr_css_set_property( css, "stroke", c );
426             sp_desktop_apply_css_recursive( (SPItem*)obj, css, true );
427             ((SPItem*)obj)->updateRepr();
429             changed = true;
430         }
432         Inkscape::XML::Node* first = node->firstChild();
433         changed |= bruteForce( document, first, match, r, g, b );
435         changed |= bruteForce( document, node->next(), match, r, g, b );
436     }
438     return changed;
441 void ColorItem::_colorDefChanged(void* data)
443     ColorItem* item = reinterpret_cast<ColorItem*>(data);
444     if ( item ) {
445         for ( std::vector<Gtk::Widget*>::iterator it =  item->_previews.begin(); it != item->_previews.end(); ++it ) {
446             Gtk::Widget* widget = *it;
447             if ( IS_EEK_PREVIEW(widget->gobj()) ) {
448                 EekPreview * preview = EEK_PREVIEW(widget->gobj());
449                 eek_preview_set_color( preview,
450                                        (item->def.getR() << 8) | item->def.getR(),
451                                        (item->def.getG() << 8) | item->def.getG(),
452                                        (item->def.getB() << 8) | item->def.getB() );
454                 eek_preview_set_linked( preview, (LinkType)((item->_linkSrc ? PREVIEW_LINK_IN:0)
455                                                             | (item->_listeners.empty() ? 0:PREVIEW_LINK_OUT)
456                                                             | (item->_isLive ? PREVIEW_LINK_OTHER:0)) );
458                 widget->queue_draw();
459             }
460         }
462         for ( std::vector<ColorItem*>::iterator it = item->_listeners.begin(); it != item->_listeners.end(); ++it ) {
463             guint r = item->def.getR();
464             guint g = item->def.getG();
465             guint b = item->def.getB();
467             if ( (*it)->_linkIsTone ) {
468                 r = ( ((*it)->_linkPercent * (*it)->_linkGray) + ((100 - (*it)->_linkPercent) * r) ) / 100;
469                 g = ( ((*it)->_linkPercent * (*it)->_linkGray) + ((100 - (*it)->_linkPercent) * g) ) / 100;
470                 b = ( ((*it)->_linkPercent * (*it)->_linkGray) + ((100 - (*it)->_linkPercent) * b) ) / 100;
471             } else {
472                 r = ( ((*it)->_linkPercent * 255) + ((100 - (*it)->_linkPercent) * r) ) / 100;
473                 g = ( ((*it)->_linkPercent * 255) + ((100 - (*it)->_linkPercent) * g) ) / 100;
474                 b = ( ((*it)->_linkPercent * 255) + ((100 - (*it)->_linkPercent) * b) ) / 100;
475             }
477             (*it)->def.setRGB( r, g, b );
478         }
481         // Look for objects using this color
482         {
483             SPDesktop *desktop = SP_ACTIVE_DESKTOP;
484             if ( desktop ) {
485                 SPDocument* document = sp_desktop_document( desktop );
486                 Inkscape::XML::Node *rroot =  sp_document_repr_root( document );
487                 if ( rroot ) {
489                     // Find where this thing came from
490                     Glib::ustring paletteName;
491                     bool found = false;
492                     int index = 0;
493                     for ( std::vector<JustForNow*>::iterator it2 = possible.begin(); it2 != possible.end() && !found; ++it2 ) {
494                         JustForNow* curr = *it2;
495                         index = 0;
496                         for ( std::vector<ColorItem*>::iterator zz = curr->_colors.begin(); zz != curr->_colors.end(); ++zz ) {
497                             if ( item == *zz ) {
498                                 found = true;
499                                 paletteName = curr->_name;
500                                 break;
501                             } else {
502                                 index++;
503                             }
504                         }
505                     }
507                     if ( !paletteName.empty() ) {
508                         gchar* str = g_strdup_printf("%d|", index);
509                         paletteName.insert( 0, str );
510                         g_free(str);
511                         str = 0;
513                         if ( bruteForce( document, rroot, paletteName, item->def.getR(), item->def.getG(), item->def.getB() ) ) {
514                             sp_document_done( document , SP_VERB_DIALOG_SWATCHES, 
515                                               _("Change color definition"));
516                         }
517                     }
518                 }
519             }
520         }
521     }
525 Gtk::Widget* ColorItem::getPreview(PreviewStyle style, ViewType view, ::PreviewSize size, guint ratio)
527     Gtk::Widget* widget = 0;
528     if ( style == PREVIEW_STYLE_BLURB ) {
529         Gtk::Label *lbl = new Gtk::Label(def.descr);
530         lbl->set_alignment(Gtk::ALIGN_LEFT, Gtk::ALIGN_CENTER);
531         widget = lbl;
532     } else {
533 //         Glib::ustring blank("          ");
534 //         if ( size == Inkscape::ICON_SIZE_MENU || size == Inkscape::ICON_SIZE_DECORATION ) {
535 //             blank = " ";
536 //         }
538         GtkWidget* eekWidget = eek_preview_new();
539         EekPreview * preview = EEK_PREVIEW(eekWidget);
540         Gtk::Widget* newBlot = Glib::wrap(eekWidget);
542         eek_preview_set_color( preview, (def.getR() << 8) | def.getR(), (def.getG() << 8) | def.getG(), (def.getB() << 8) | def.getB());
544         eek_preview_set_details( preview, (::PreviewStyle)style, (::ViewType)view, (::PreviewSize)size, ratio );
545         eek_preview_set_linked( preview, (LinkType)((_linkSrc ? PREVIEW_LINK_IN:0)
546                                                     | (_listeners.empty() ? 0:PREVIEW_LINK_OUT)
547                                                     | (_isLive ? PREVIEW_LINK_OTHER:0)) );
549         def.addCallback( _colorDefChanged, this );
551         GValue val = {0, {{0}, {0}}};
552         g_value_init( &val, G_TYPE_BOOLEAN );
553         g_value_set_boolean( &val, FALSE );
554         g_object_set_property( G_OBJECT(preview), "focus-on-click", &val );
556 /*
557         Gtk::Button *btn = new Gtk::Button(blank);
558         Gdk::Color color;
559         color.set_rgb((_r << 8)|_r, (_g << 8)|_g, (_b << 8)|_b);
560         btn->modify_bg(Gtk::STATE_NORMAL, color);
561         btn->modify_bg(Gtk::STATE_ACTIVE, color);
562         btn->modify_bg(Gtk::STATE_PRELIGHT, color);
563         btn->modify_bg(Gtk::STATE_SELECTED, color);
565         Gtk::Widget* newBlot = btn;
566 */
568         tips.set_tip((*newBlot), def.descr);
570 /*
571         newBlot->signal_clicked().connect( sigc::mem_fun(*this, &ColorItem::buttonClicked) );
573         sigc::signal<void> type_signal_something;
574 */
576         g_signal_connect( G_OBJECT(newBlot->gobj()),
577                           "clicked",
578                           G_CALLBACK(handleClick),
579                           this);
581         g_signal_connect( G_OBJECT(newBlot->gobj()),
582                           "alt-clicked",
583                           G_CALLBACK(handleSecondaryClick),
584                           this);
586         g_signal_connect( G_OBJECT(newBlot->gobj()),
587                           "button-press-event",
588                           G_CALLBACK(handleButtonPress),
589                           this);
591         gtk_drag_source_set( GTK_WIDGET(newBlot->gobj()),
592                              GDK_BUTTON1_MASK,
593                              sourceColorEntries,
594                              G_N_ELEMENTS(sourceColorEntries),
595                              GdkDragAction(GDK_ACTION_MOVE | GDK_ACTION_COPY) );
597         g_signal_connect( G_OBJECT(newBlot->gobj()),
598                           "drag-data-get",
599                           G_CALLBACK(ColorItem::_dragGetColorData),
600                           this);
602         g_signal_connect( G_OBJECT(newBlot->gobj()),
603                           "drag-begin",
604                           G_CALLBACK(dragBegin),
605                           this );
607         g_signal_connect( G_OBJECT(newBlot->gobj()),
608                           "enter-notify-event",
609                           G_CALLBACK(handleEnterNotify),
610                           this);
612 //         g_signal_connect( G_OBJECT(newBlot->gobj()),
613 //                           "drag-drop",
614 //                           G_CALLBACK(dragDropColorData),
615 //                           this);
617         if ( def.isEditable() )
618         {
619             gtk_drag_dest_set( GTK_WIDGET(newBlot->gobj()),
620                                GTK_DEST_DEFAULT_ALL,
621                                destColorTargets,
622                                G_N_ELEMENTS(destColorTargets),
623                                GdkDragAction(GDK_ACTION_COPY | GDK_ACTION_MOVE) );
626             g_signal_connect( G_OBJECT(newBlot->gobj()),
627                               "drag-data-received",
628                               G_CALLBACK(_dropDataIn),
629                               this );
630         }
632         g_signal_connect( G_OBJECT(newBlot->gobj()),
633                           "destroy",
634                           G_CALLBACK(dieDieDie),
635                           this);
638         widget = newBlot;
639     }
641     _previews.push_back( widget );
643     return widget;
646 void ColorItem::buttonClicked(bool secondary)
648     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
649     if (desktop) {
650         char const * attrName = secondary ? "stroke" : "fill";
651         guint32 rgba = (def.getR() << 24) | (def.getG() << 16) | (def.getB() << 8) | 0xff;
652         gchar c[64];
653         sp_svg_write_color(c, sizeof(c), rgba);
655         SPCSSAttr *css = sp_repr_css_attr_new();
656         sp_repr_css_set_property( css, attrName, c );
657         sp_desktop_set_style(desktop, css);
659         sp_repr_css_attr_unref(css);
660         sp_document_done (sp_desktop_document (desktop), SP_VERB_DIALOG_SWATCHES, 
661                           secondary? _("Set stroke color from swatch") : _("Set fill color from swatch"));
662     }
668 static char* trim( char* str ) {
669     char* ret = str;
670     while ( *str && (*str == ' ' || *str == '\t') ) {
671         str++;
672     }
673     ret = str;
674     while ( *str ) {
675         str++;
676     }
677     str--;
678     while ( str > ret && ( *str == ' ' || *str == '\t' ) || *str == '\r' || *str == '\n' ) {
679         *str-- = 0;
680     }
681     return ret;
684 void skipWhitespace( char*& str ) {
685     while ( *str == ' ' || *str == '\t' ) {
686         str++;
687     }
690 bool parseNum( char*& str, int& val ) {
691     val = 0;
692     while ( '0' <= *str && *str <= '9' ) {
693         val = val * 10 + (*str - '0');
694         str++;
695     }
696     bool retval = !(*str == 0 || *str == ' ' || *str == '\t' || *str == '\r' || *str == '\n');
697     return retval;
701 static bool getBlock( std::string& dst, guchar ch, std::string const str )
703     bool good = false;
704     std::string::size_type pos = str.find(ch);
705     if ( pos != std::string::npos )
706     {
707         std::string::size_type pos2 = str.find( '(', pos );
708         if ( pos2 != std::string::npos ) {
709             std::string::size_type endPos = str.find( ')', pos2 );
710             if ( endPos != std::string::npos ) {
711                 dst = str.substr( pos2 + 1, (endPos - pos2 - 1) );
712                 good = true;
713             }
714         }
715     }
716     return good;
719 static bool popVal( guint64& numVal, std::string& str )
721     bool good = false;
722     std::string::size_type endPos = str.find(',');
723     if ( endPos == std::string::npos ) {
724         endPos = str.length();
725     }
727     if ( endPos != std::string::npos && endPos > 0 ) {
728         std::string xxx = str.substr( 0, endPos );
729         const gchar* ptr = xxx.c_str();
730         gchar* endPtr = 0;
731         numVal = g_ascii_strtoull( ptr, &endPtr, 10 );
732         if ( (numVal == G_MAXUINT64) && (ERANGE == errno) ) {
733             // overflow
734         } else if ( (numVal == 0) && (endPtr == ptr) ) {
735             // failed conversion
736         } else {
737             good = true;
738             str.erase( 0, endPos + 1 );
739         }
740     }
742     return good;
745 void ColorItem::_wireMagicColors( void* p )
747     JustForNow* onceMore = reinterpret_cast<JustForNow*>(p);
748     if ( onceMore )
749     {
750         for ( std::vector<ColorItem*>::iterator it = onceMore->_colors.begin(); it != onceMore->_colors.end(); ++it )
751         {
752             std::string::size_type pos = (*it)->def.descr.find("*{");
753             if ( pos != std::string::npos )
754             {
755                 std::string subby = (*it)->def.descr.substr( pos + 2 );
756                 std::string::size_type endPos = subby.find("}*");
757                 if ( endPos != std::string::npos )
758                 {
759                     subby.erase( endPos );
760                     //g_message("FOUND MAGIC at '%s'", (*it)->def.descr.c_str());
761                     //g_message("               '%s'", subby.c_str());
763                     if ( subby.find('E') != std::string::npos )
764                     {
765                         (*it)->def.setEditable( true );
766                     }
768                     if ( subby.find('L') != std::string::npos )
769                     {
770                         (*it)->_isLive = true;
771                     }
773                     std::string part;
774                     // Tint. index + 1 more val.
775                     if ( getBlock( part, 'T', subby ) ) {
776                         guint64 colorIndex = 0;
777                         if ( popVal( colorIndex, part ) ) {
778                             guint64 percent = 0;
779                             if ( popVal( percent, part ) ) {
780                                 (*it)->_linkTint( *(onceMore->_colors[colorIndex]), percent );
781                             }
782                         }
783                     }
785                     // Shade/tone. index + 1 or 2 more val.
786                     if ( getBlock( part, 'S', subby ) ) {
787                         guint64 colorIndex = 0;
788                         if ( popVal( colorIndex, part ) ) {
789                             guint64 percent = 0;
790                             if ( popVal( percent, part ) ) {
791                                 guint64 grayLevel = 0;
792                                 if ( !popVal( grayLevel, part ) ) {
793                                     grayLevel = 0;
794                                 }
795                                 (*it)->_linkTone( *(onceMore->_colors[colorIndex]), percent, grayLevel );
796                             }
797                         }
798                     }
800                 }
801             }
802         }
803     }
807 void ColorItem::_linkTint( ColorItem& other, int percent )
809     if ( !_linkSrc )
810     {
811         other._listeners.push_back(this);
812         _linkIsTone = false;
813         _linkPercent = percent;
814         if ( _linkPercent > 100 )
815             _linkPercent = 100;
816         if ( _linkPercent < 0 )
817             _linkPercent = 0;
818         _linkGray = 0;
819         _linkSrc = &other;
821         ColorItem::_colorDefChanged(&other);
822     }
825 void ColorItem::_linkTone( ColorItem& other, int percent, int grayLevel )
827     if ( !_linkSrc )
828     {
829         other._listeners.push_back(this);
830         _linkIsTone = true;
831         _linkPercent = percent;
832         if ( _linkPercent > 100 )
833             _linkPercent = 100;
834         if ( _linkPercent < 0 )
835             _linkPercent = 0;
836         _linkGray = grayLevel;
837         _linkSrc = &other;
839         ColorItem::_colorDefChanged(&other);
840     }
844 void _loadPaletteFile( gchar const *filename )
846     char block[1024];
847     FILE *f = Inkscape::IO::fopen_utf8name( filename, "r" );
848     if ( f ) {
849         char* result = fgets( block, sizeof(block), f );
850         if ( result ) {
851             if ( strncmp( "GIMP Palette", block, 12 ) == 0 ) {
852                 bool inHeader = true;
853                 bool hasErr = false;
855                 JustForNow *onceMore = new JustForNow();
857                 do {
858                     result = fgets( block, sizeof(block), f );
859                     block[sizeof(block) - 1] = 0;
860                     if ( result ) {
861                         if ( block[0] == '#' ) {
862                             // ignore comment
863                         } else {
864                             char *ptr = block;
865                             // very simple check for header versus entry
866                             while ( *ptr == ' ' || *ptr == '\t' ) {
867                                 ptr++;
868                             }
869                             if ( (*ptr == 0) || (*ptr == '\r') || (*ptr == '\n') ) {
870                                 // blank line. skip it.
871                             } else if ( '0' <= *ptr && *ptr <= '9' ) {
872                                 // should be an entry link
873                                 inHeader = false;
874                                 ptr = block;
875                                 Glib::ustring name("");
876                                 int r = 0;
877                                 int g = 0;
878                                 int b = 0;
879                                 skipWhitespace(ptr);
880                                 if ( *ptr ) {
881                                     hasErr = parseNum(ptr, r);
882                                     if ( !hasErr ) {
883                                         skipWhitespace(ptr);
884                                         hasErr = parseNum(ptr, g);
885                                     }
886                                     if ( !hasErr ) {
887                                         skipWhitespace(ptr);
888                                         hasErr = parseNum(ptr, b);
889                                     }
890                                     if ( !hasErr && *ptr ) {
891                                         char* n = trim(ptr);
892                                         if (n != NULL) {
893                                             name = n;
894                                         }
895                                     }
896                                     if ( !hasErr ) {
897                                         // Add the entry now
898                                         Glib::ustring nameStr(name);
899                                         ColorItem* item = new ColorItem( r, g, b, nameStr );
900                                         onceMore->_colors.push_back(item);
901                                     }
902                                 } else {
903                                     hasErr = true;
904                                 }
905                             } else {
906                                 if ( !inHeader ) {
907                                     // Hmmm... probably bad. Not quite the format we want?
908                                     hasErr = true;
909                                 } else {
910                                     char* sep = strchr(result, ':');
911                                     if ( sep ) {
912                                         *sep = 0;
913                                         char* val = trim(sep + 1);
914                                         char* name = trim(result);
915                                         if ( *name ) {
916                                             if ( strcmp( "Name", name ) == 0 )
917                                             {
918                                                 onceMore->_name = val;
919                                             }
920                                             else if ( strcmp( "Columns", name ) == 0 )
921                                             {
922                                                 gchar* endPtr = 0;
923                                                 guint64 numVal = g_ascii_strtoull( val, &endPtr, 10 );
924                                                 if ( (numVal == G_MAXUINT64) && (ERANGE == errno) ) {
925                                                     // overflow
926                                                 } else if ( (numVal == 0) && (endPtr == val) ) {
927                                                     // failed conversion
928                                                 } else {
929                                                     onceMore->_prefWidth = numVal;
930                                                 }
931                                             }
932                                         } else {
933                                             // error
934                                             hasErr = true;
935                                         }
936                                     } else {
937                                         // error
938                                         hasErr = true;
939                                     }
940                                 }
941                             }
942                         }
943                     }
944                 } while ( result && !hasErr );
945                 if ( !hasErr ) {
946                     possible.push_back(onceMore);
947 #if ENABLE_MAGIC_COLORS
948                     ColorItem::_wireMagicColors( onceMore );
949 #endif // ENABLE_MAGIC_COLORS
950                 } else {
951                     delete onceMore;
952                 }
953             }
954         }
956         fclose(f);
957     }
960 static void loadEmUp()
962     static bool beenHere = false;
963     if ( !beenHere ) {
964         beenHere = true;
966         std::list<gchar *> sources;
967         sources.push_back( profile_path("palettes") );
968         sources.push_back( g_strdup(INKSCAPE_PALETTESDIR) );
969         sources.push_back( g_strdup(CREATE_PALETTESDIR) );
971         // Use this loop to iterate through a list of possible document locations.
972         while (!sources.empty()) {
973             gchar *dirname = sources.front();
975             if ( Inkscape::IO::file_test( dirname, G_FILE_TEST_EXISTS )
976                 && Inkscape::IO::file_test( dirname, G_FILE_TEST_IS_DIR )) {
977                 GError *err = 0;
978                 GDir *directory = g_dir_open(dirname, 0, &err);
979                 if (!directory) {
980                     gchar *safeDir = Inkscape::IO::sanitizeString(dirname);
981                     g_warning(_("Palettes directory (%s) is unavailable."), safeDir);
982                     g_free(safeDir);
983                 } else {
984                     gchar *filename = 0;
985                     while ((filename = (gchar *)g_dir_read_name(directory)) != NULL) {
986                         gchar* lower = g_ascii_strdown( filename, -1 );
987 //                        if ( g_str_has_suffix(lower, ".gpl") ) {
988                             gchar* full = g_build_filename(dirname, filename, NULL);
989                             if ( !Inkscape::IO::file_test( full, G_FILE_TEST_IS_DIR ) ) {
990                                 _loadPaletteFile(full);
991                             }
992                             g_free(full);
993 //                      }
994                         g_free(lower);
995                     }
996                     g_dir_close(directory);
997                 }
998             }
1000             // toss the dirname
1001             g_free(dirname);
1002             sources.pop_front();
1003         }
1004     }
1015 SwatchesPanel& SwatchesPanel::getInstance()
1017     return *new SwatchesPanel();
1021 /**
1022  * Constructor
1023  */
1024 SwatchesPanel::SwatchesPanel(gchar const* prefsPath) :
1025     Inkscape::UI::Widget::Panel("", prefsPath, SP_VERB_DIALOG_SWATCHES, "", true),
1026     _holder(0)
1028     Gtk::RadioMenuItem* hotItem = 0;
1029     _holder = new PreviewHolder();
1030     loadEmUp();
1032     if ( !possible.empty() ) {
1033         JustForNow* first = 0;
1034         gchar const* targetName = 0;
1035         if ( _prefs_path ) {
1036             targetName = prefs_get_string_attribute( _prefs_path, "palette" );
1037             if ( targetName ) {
1038                 for ( std::vector<JustForNow*>::iterator iter = possible.begin(); iter != possible.end(); ++iter ) {
1039                     if ( (*iter)->_name == targetName ) {
1040                         first = *iter;
1041                         break;
1042                     }
1043                 }
1044             }
1045         }
1047         if ( !first ) {
1048             first = possible.front();
1049         }
1051         if ( first->_prefWidth > 0 ) {
1052             _holder->setColumnPref( first->_prefWidth );
1053         }
1054         _holder->freezeUpdates();
1055         for ( std::vector<ColorItem*>::iterator it = first->_colors.begin(); it != first->_colors.end(); it++ ) {
1056             _holder->addPreview(*it);
1057         }
1058         _holder->thawUpdates();
1060         Gtk::RadioMenuItem::Group groupOne;
1061         int i = 0;
1062         for ( std::vector<JustForNow*>::iterator it = possible.begin(); it != possible.end(); it++ ) {
1063             JustForNow* curr = *it;
1064             Gtk::RadioMenuItem* single = manage(new Gtk::RadioMenuItem(groupOne, curr->_name));
1065             if ( curr == first ) {
1066                 hotItem = single;
1067             }
1068             _regItem( single, 3, i );
1069             i++;
1070         }
1072     }
1075     _getContents()->pack_start(*_holder, Gtk::PACK_EXPAND_WIDGET);
1076     _setTargetFillable(_holder);
1078     show_all_children();
1080     restorePanelPrefs();
1081     if ( hotItem ) {
1082         hotItem->set_active();
1083     }
1086 SwatchesPanel::~SwatchesPanel()
1090 void SwatchesPanel::setOrientation( Gtk::AnchorType how )
1092     // Must call the parent class or bad things might happen
1093     Inkscape::UI::Widget::Panel::setOrientation( how );
1095     if ( _holder )
1096     {
1097         _holder->setOrientation( Gtk::ANCHOR_SOUTH );
1098     }
1101 void SwatchesPanel::_handleAction( int setId, int itemId )
1103     switch( setId ) {
1104         case 3:
1105         {
1106             if ( itemId >= 0 && itemId < static_cast<int>(possible.size()) ) {
1107                 _holder->clear();
1108                 JustForNow* curr = possible[itemId];
1110                 if ( _prefs_path ) {
1111                     prefs_set_string_attribute( _prefs_path, "palette", curr->_name.c_str() );
1112                 }
1114                 if ( curr->_prefWidth > 0 ) {
1115                     _holder->setColumnPref( curr->_prefWidth );
1116                 }
1117                 _holder->freezeUpdates();
1118                 for ( std::vector<ColorItem*>::iterator it = curr->_colors.begin(); it != curr->_colors.end(); it++ ) {
1119                     _holder->addPreview(*it);
1120                 }
1121                 _holder->thawUpdates();
1122             }
1123         }
1124         break;
1125     }
1128 } //namespace Dialogs
1129 } //namespace UI
1130 } //namespace Inkscape
1133 /*
1134   Local Variables:
1135   mode:c++
1136   c-file-style:"stroustrup"
1137   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1138   indent-tabs-mode:nil
1139   fill-column:99
1140   End:
1141 */
1142 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :