Code

Warning cleanup.
[inkscape.git] / src / dialogs / swatches.cpp
1 /** @file
2  * @brief Color swatches dialog
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  */
14 #include <errno.h>
16 #include <gtk/gtkdialog.h> //for GTK_RESPONSE* types
17 #include <gtk/gtkdnd.h>
18 #include <gtk/gtkmenu.h>
19 #include <gtk/gtkmenuitem.h>
20 #include <gtk/gtkseparatormenuitem.h>
22 #include <glibmm/i18n.h>
23 #include <gdkmm/pixbuf.h>
24 #include "inkscape.h"
25 #include "desktop.h"
26 #include "message-context.h"
27 #include "document.h"
28 #include "desktop-handles.h"
29 #include "extension/db.h"
30 #include "inkscape.h"
31 #include "svg/svg-color.h"
32 #include "desktop-style.h"
33 #include "io/sys.h"
34 #include "path-prefix.h"
35 #include "swatches.h"
36 #include "sp-item.h"
37 #include "preferences.h"
39 #include "eek-preview.h"
41 namespace Inkscape {
42 namespace UI {
43 namespace Dialogs {
45 ColorItem::ColorItem() : _isRemove(true){};
46 ColorItem::ColorItem( unsigned int r, unsigned int g, unsigned int b, Glib::ustring& name ) :
47     def( r, g, b, name ),
48     _isRemove(false),
49     _isLive(false),
50     _linkIsTone(false),
51     _linkPercent(0),
52     _linkGray(0),
53     _linkSrc(0)
54 {
55 }
57 ColorItem::~ColorItem()
58 {
59 }
61 ColorItem::ColorItem(ColorItem const &other) :
62     Inkscape::UI::Previewable()
63 {
64     if ( this != &other ) {
65         *this = other;
66     }
67 }
69 ColorItem &ColorItem::operator=(ColorItem const &other)
70 {
71     if ( this != &other ) {
72         def = other.def;
74         // TODO - correct linkage
75         _linkSrc = other._linkSrc;
76         g_message("Erk!");
77     }
78     return *this;
79 }
82 class JustForNow
83 {
84 public:
85     JustForNow() : _prefWidth(0) {}
87     Glib::ustring _name;
88     int _prefWidth;
89     std::vector<ColorItem*> _colors;
90 };
92 static std::vector<JustForNow*> possible;
96 typedef enum {
97     APP_X_INKY_COLOR_ID = 0,
98     APP_X_INKY_COLOR = 0,
99     APP_X_COLOR,
100     TEXT_DATA
101 } colorFlavorType;
103 static const GtkTargetEntry sourceColorEntries[] = {
104 #if ENABLE_MAGIC_COLORS
105 //    {"application/x-inkscape-color-id", GTK_TARGET_SAME_APP, APP_X_INKY_COLOR_ID},
106     {"application/x-inkscape-color", 0, APP_X_INKY_COLOR},
107 #endif // ENABLE_MAGIC_COLORS
108     {"application/x-color", 0, APP_X_COLOR},
109     {"text/plain", 0, TEXT_DATA},
110 };
112 void ColorItem::_dragGetColorData( GtkWidget *widget,
113                                    GdkDragContext *drag_context,
114                                    GtkSelectionData *data,
115                                    guint info,
116                                    guint time,
117                                    gpointer user_data)
119     (void)widget;
120     (void)drag_context;
121     (void)time;
122     static GdkAtom typeXColor = gdk_atom_intern("application/x-color", FALSE);
123     static GdkAtom typeText = gdk_atom_intern("text/plain", FALSE);
125     ColorItem* item = reinterpret_cast<ColorItem*>(user_data);
126     if ( info == TEXT_DATA ) {
127         gchar* tmp = g_strdup_printf("#%02x%02x%02x", item->def.getR(), item->def.getG(), item->def.getB() );
129         gtk_selection_data_set( data,
130                                 typeText,
131                                 8, // format
132                                 (guchar*)tmp,
133                                 strlen((const char*)tmp) + 1);
134         g_free(tmp);
135         tmp = 0;
136     } else if ( info == APP_X_INKY_COLOR ) {
137         Glib::ustring paletteName;
139         // Find where this thing came from
140         bool found = false;
141         int index = 0;
142         for ( std::vector<JustForNow*>::iterator it = possible.begin(); it != possible.end() && !found; ++it ) {
143             JustForNow* curr = *it;
144             index = 0;
145             for ( std::vector<ColorItem*>::iterator zz = curr->_colors.begin(); zz != curr->_colors.end(); ++zz ) {
146                 if ( item == *zz ) {
147                     found = true;
148                     paletteName = curr->_name;
149                     break;
150                 } else {
151                     index++;
152                 }
153             }
154         }
156 //         if ( found ) {
157 //             g_message("Found the color at entry %d in palette '%s'", index, paletteName.c_str() );
158 //         } else {
159 //             g_message("Unable to find the color");
160 //         }
161         int itemCount = 4 + 2 + 1 + paletteName.length();
163         guint16* tmp = new guint16[itemCount];
164         tmp[0] = (item->def.getR() << 8) | item->def.getR();
165         tmp[1] = (item->def.getG() << 8) | item->def.getG();
166         tmp[2] = (item->def.getB() << 8) | item->def.getB();
167         tmp[3] = 0xffff;
168         tmp[4] = (item->_isLive || !item->_listeners.empty() || (item->_linkSrc != 0) ) ? 1 : 0;
170         tmp[5] = index;
171         tmp[6] = paletteName.length();
172         for ( unsigned int i = 0; i < paletteName.length(); i++ ) {
173             tmp[7 + i] = paletteName[i];
174         }
175         gtk_selection_data_set( data,
176                                 typeXColor,
177                                 16, // format
178                                 reinterpret_cast<const guchar*>(tmp),
179                                 itemCount * 2);
180         delete[] tmp;
181     } else {
182         guint16 tmp[4];
183         tmp[0] = (item->def.getR() << 8) | item->def.getR();
184         tmp[1] = (item->def.getG() << 8) | item->def.getG();
185         tmp[2] = (item->def.getB() << 8) | item->def.getB();
186         tmp[3] = 0xffff;
187         gtk_selection_data_set( data,
188                                 typeXColor,
189                                 16, // format
190                                 reinterpret_cast<const guchar*>(tmp),
191                                 (3+1) * 2);
192     }
195 static void dragBegin( GtkWidget *widget, GdkDragContext* dc, gpointer data )
197     (void)widget;
198     ColorItem* item = reinterpret_cast<ColorItem*>(data);
199     if ( item )
200     {
201         if (item->isRemove()){
202             GError *error = NULL;
203             gchar *filepath = (gchar *) g_strdup_printf("%s/remove-color.png", INKSCAPE_PIXMAPDIR);
204             gsize bytesRead = 0;
205             gsize bytesWritten = 0;
206             gchar *localFilename = g_filename_from_utf8( filepath,
207                                                  -1,
208                                                  &bytesRead,
209                                                  &bytesWritten,
210                                                  &error);
211             GdkPixbuf* pixbuf = gdk_pixbuf_new_from_file_at_scale(localFilename, 32, 24, FALSE, &error);
212             g_free(localFilename);
213             g_free(filepath);
214             gtk_drag_set_icon_pixbuf( dc, pixbuf, 0, 0 );
215             return;
216         }
218         Glib::RefPtr<Gdk::Pixbuf> thumb = Gdk::Pixbuf::create( Gdk::COLORSPACE_RGB, false, 8, 32, 24 );
219         guint32 fillWith = (0xff000000 & (item->def.getR() << 24))
220                          | (0x00ff0000 & (item->def.getG() << 16))
221                          | (0x0000ff00 & (item->def.getB() <<  8));
222         thumb->fill( fillWith );
223         gtk_drag_set_icon_pixbuf( dc, thumb->gobj(), 0, 0 );
224     }
228 //"drag-drop"
229 // gboolean dragDropColorData( GtkWidget *widget,
230 //                             GdkDragContext *drag_context,
231 //                             gint x,
232 //                             gint y,
233 //                             guint time,
234 //                             gpointer user_data)
235 // {
236 // // TODO finish
238 //     return TRUE;
239 // }
241 static void handleClick( GtkWidget* widget, gpointer callback_data ) {
242     (void)widget;
243     ColorItem* item = reinterpret_cast<ColorItem*>(callback_data);
244     if ( item ) {
245         item->buttonClicked(false);
246     }
249 static void handleSecondaryClick( GtkWidget* widget, gint arg1, gpointer callback_data ) {
250     (void)widget;
251     (void)arg1;
252     ColorItem* item = reinterpret_cast<ColorItem*>(callback_data);
253     if ( item ) {
254         item->buttonClicked(true);
255     }
258 static gboolean handleEnterNotify( GtkWidget* /*widget*/, GdkEventCrossing* /*event*/, gpointer callback_data ) {
259     ColorItem* item = reinterpret_cast<ColorItem*>(callback_data);
260     if ( item ) {
261         SPDesktop *desktop = SP_ACTIVE_DESKTOP;
262         if ( desktop ) {
263             gchar* msg = g_strdup_printf(_("Color: <b>%s</b>; <b>Click</b> to set fill, <b>Shift+click</b> to set stroke"),
264                                          item->def.descr.c_str());
265             desktop->tipsMessageContext()->set(Inkscape::INFORMATION_MESSAGE, msg);
266             g_free(msg);
267         }
268     }
269     return FALSE;
272 static gboolean handleLeaveNotify( GtkWidget* /*widget*/, GdkEventCrossing* /*event*/, gpointer callback_data ) {
273     ColorItem* item = reinterpret_cast<ColorItem*>(callback_data);
274     if ( item ) {
275         SPDesktop *desktop = SP_ACTIVE_DESKTOP;
276         if ( desktop ) {
277             desktop->tipsMessageContext()->clear();
278         }
279     }
280     return FALSE;
283 static GtkWidget* popupMenu = 0;
284 static ColorItem* bounceTarget = 0;
286 static void redirClick( GtkMenuItem *menuitem, gpointer user_data )
288     (void)user_data;
289     if ( bounceTarget ) {
290         handleClick( GTK_WIDGET(menuitem), bounceTarget );
291     }
294 static void redirSecondaryClick( GtkMenuItem *menuitem, gpointer user_data )
296     (void)user_data;
297     if ( bounceTarget ) {
298         handleSecondaryClick( GTK_WIDGET(menuitem), 0, bounceTarget );
299     }
302 static gboolean handleButtonPress( GtkWidget* widget, GdkEventButton* event, gpointer user_data)
304     (void)widget;
305     gboolean handled = FALSE;
307     if ( (event->button == 3) && (event->type == GDK_BUTTON_PRESS) ) {
308         if ( !popupMenu ) {
309             popupMenu = gtk_menu_new();
310             GtkWidget* child = 0;
312             //TRANSLATORS: An item in context menu on a colour in the swatches
313             child = gtk_menu_item_new_with_label(_("Set fill"));
314             g_signal_connect( G_OBJECT(child),
315                               "activate",
316                               G_CALLBACK(redirClick),
317                               user_data);
318             gtk_menu_shell_append(GTK_MENU_SHELL(popupMenu), child);
320             //TRANSLATORS: An item in context menu on a colour in the swatches
321             child = gtk_menu_item_new_with_label(_("Set stroke"));
323             g_signal_connect( G_OBJECT(child),
324                               "activate",
325                               G_CALLBACK(redirSecondaryClick),
326                               user_data);
327             gtk_menu_shell_append(GTK_MENU_SHELL(popupMenu), child);
329             gtk_widget_show_all(popupMenu);
330         }
332         ColorItem* item = reinterpret_cast<ColorItem*>(user_data);
333         if ( item ) {
334             bounceTarget = item;
335             if ( popupMenu ) {
336                 gtk_menu_popup(GTK_MENU(popupMenu), NULL, NULL, NULL, NULL, event->button, event->time);
337                 handled = TRUE;
338             }
339         }
340     }
342     return handled;
345 static void dieDieDie( GtkObject *obj, gpointer user_data )
347     g_message("die die die %p  %p", obj, user_data );
350 static const GtkTargetEntry destColorTargets[] = {
351 #if ENABLE_MAGIC_COLORS
352 //    {"application/x-inkscape-color-id", GTK_TARGET_SAME_APP, APP_X_INKY_COLOR_ID},
353     {"application/x-inkscape-color", 0, APP_X_INKY_COLOR},
354 #endif // ENABLE_MAGIC_COLORS
355     {"application/x-color", 0, APP_X_COLOR},
356 };
358 #include "color.h" // for SP_RGBA32_U_COMPOSE
360 void ColorItem::_dropDataIn( GtkWidget *widget,
361                              GdkDragContext *drag_context,
362                              gint x, gint y,
363                              GtkSelectionData *data,
364                              guint info,
365                              guint event_time,
366                              gpointer user_data)
368     (void)widget;
369     (void)drag_context;
370     (void)x;
371     (void)y;
372     (void)event_time;
373 //     g_message("    droppy droppy   %d", info);
374      switch (info) {
375          case APP_X_INKY_COLOR:
376          {
377              if ( data->length >= 8 ) {
378                  // Careful about endian issues.
379                  guint16* dataVals = (guint16*)data->data;
380                  if ( user_data ) {
381                      ColorItem* item = reinterpret_cast<ColorItem*>(user_data);
382                      if ( item->def.isEditable() ) {
383                          // Shove on in the new value
384                          item->def.setRGB( 0x0ff & (dataVals[0] >> 8), 0x0ff & (dataVals[1] >> 8), 0x0ff & (dataVals[2] >> 8) );
385                      }
386                  }
387              }
388              break;
389          }
390          case APP_X_COLOR:
391          {
392              if ( data->length == 8 ) {
393                  // Careful about endian issues.
394                  guint16* dataVals = (guint16*)data->data;
395 //                  {
396 //                      gchar c[64] = {0};
397 //                      sp_svg_write_color( c, 64,
398 //                                          SP_RGBA32_U_COMPOSE(
399 //                                              0x0ff & (dataVals[0] >> 8),
400 //                                              0x0ff & (dataVals[1] >> 8),
401 //                                              0x0ff & (dataVals[2] >> 8),
402 //                                              0xff // can't have transparency in the color itself
403 //                                              //0x0ff & (data->data[3] >> 8),
404 //                                              ));
405 //                  }
406                  if ( user_data ) {
407                      ColorItem* item = reinterpret_cast<ColorItem*>(user_data);
408                      if ( item->def.isEditable() ) {
409                          // Shove on in the new value
410                          item->def.setRGB( 0x0ff & (dataVals[0] >> 8), 0x0ff & (dataVals[1] >> 8), 0x0ff & (dataVals[2] >> 8) );
411                      }
412                  }
413              }
414              break;
415          }
416          default:
417              g_message("unknown drop type");
418      }
422 static bool bruteForce( SPDocument* document, Inkscape::XML::Node* node, Glib::ustring const& match, int r, int g, int b )
424     bool changed = false;
426     if ( node ) {
427         gchar const * val = node->attribute("inkscape:x-fill-tag");
428         if ( val  && (match == val) ) {
429             SPObject *obj = document->getObjectByRepr( node );
431             gchar c[64] = {0};
432             sp_svg_write_color( c, sizeof(c), SP_RGBA32_U_COMPOSE( r, g, b, 0xff ) );
433             SPCSSAttr *css = sp_repr_css_attr_new();
434             sp_repr_css_set_property( css, "fill", c );
436             sp_desktop_apply_css_recursive( (SPItem*)obj, css, true );
437             ((SPItem*)obj)->updateRepr();
439             changed = true;
440         }
442         val = node->attribute("inkscape:x-stroke-tag");
443         if ( val  && (match == val) ) {
444             SPObject *obj = document->getObjectByRepr( node );
446             gchar c[64] = {0};
447             sp_svg_write_color( c, sizeof(c), SP_RGBA32_U_COMPOSE( r, g, b, 0xff ) );
448             SPCSSAttr *css = sp_repr_css_attr_new();
449             sp_repr_css_set_property( css, "stroke", c );
451             sp_desktop_apply_css_recursive( (SPItem*)obj, css, true );
452             ((SPItem*)obj)->updateRepr();
454             changed = true;
455         }
457         Inkscape::XML::Node* first = node->firstChild();
458         changed |= bruteForce( document, first, match, r, g, b );
460         changed |= bruteForce( document, node->next(), match, r, g, b );
461     }
463     return changed;
466 void ColorItem::_colorDefChanged(void* data)
468     ColorItem* item = reinterpret_cast<ColorItem*>(data);
469     if ( item ) {
470         for ( std::vector<Gtk::Widget*>::iterator it =  item->_previews.begin(); it != item->_previews.end(); ++it ) {
471             Gtk::Widget* widget = *it;
472             if ( IS_EEK_PREVIEW(widget->gobj()) ) {
473                 EekPreview * preview = EEK_PREVIEW(widget->gobj());
474                 eek_preview_set_color( preview,
475                                        (item->def.getR() << 8) | item->def.getR(),
476                                        (item->def.getG() << 8) | item->def.getG(),
477                                        (item->def.getB() << 8) | item->def.getB() );
479                 eek_preview_set_linked( preview, (LinkType)((item->_linkSrc ? PREVIEW_LINK_IN:0)
480                                                             | (item->_listeners.empty() ? 0:PREVIEW_LINK_OUT)
481                                                             | (item->_isLive ? PREVIEW_LINK_OTHER:0)) );
483                 widget->queue_draw();
484             }
485         }
487         for ( std::vector<ColorItem*>::iterator it = item->_listeners.begin(); it != item->_listeners.end(); ++it ) {
488             guint r = item->def.getR();
489             guint g = item->def.getG();
490             guint b = item->def.getB();
492             if ( (*it)->_linkIsTone ) {
493                 r = ( ((*it)->_linkPercent * (*it)->_linkGray) + ((100 - (*it)->_linkPercent) * r) ) / 100;
494                 g = ( ((*it)->_linkPercent * (*it)->_linkGray) + ((100 - (*it)->_linkPercent) * g) ) / 100;
495                 b = ( ((*it)->_linkPercent * (*it)->_linkGray) + ((100 - (*it)->_linkPercent) * b) ) / 100;
496             } else {
497                 r = ( ((*it)->_linkPercent * 255) + ((100 - (*it)->_linkPercent) * r) ) / 100;
498                 g = ( ((*it)->_linkPercent * 255) + ((100 - (*it)->_linkPercent) * g) ) / 100;
499                 b = ( ((*it)->_linkPercent * 255) + ((100 - (*it)->_linkPercent) * b) ) / 100;
500             }
502             (*it)->def.setRGB( r, g, b );
503         }
506         // Look for objects using this color
507         {
508             SPDesktop *desktop = SP_ACTIVE_DESKTOP;
509             if ( desktop ) {
510                 SPDocument* document = sp_desktop_document( desktop );
511                 Inkscape::XML::Node *rroot =  sp_document_repr_root( document );
512                 if ( rroot ) {
514                     // Find where this thing came from
515                     Glib::ustring paletteName;
516                     bool found = false;
517                     int index = 0;
518                     for ( std::vector<JustForNow*>::iterator it2 = possible.begin(); it2 != possible.end() && !found; ++it2 ) {
519                         JustForNow* curr = *it2;
520                         index = 0;
521                         for ( std::vector<ColorItem*>::iterator zz = curr->_colors.begin(); zz != curr->_colors.end(); ++zz ) {
522                             if ( item == *zz ) {
523                                 found = true;
524                                 paletteName = curr->_name;
525                                 break;
526                             } else {
527                                 index++;
528                             }
529                         }
530                     }
532                     if ( !paletteName.empty() ) {
533                         gchar* str = g_strdup_printf("%d|", index);
534                         paletteName.insert( 0, str );
535                         g_free(str);
536                         str = 0;
538                         if ( bruteForce( document, rroot, paletteName, item->def.getR(), item->def.getG(), item->def.getB() ) ) {
539                             sp_document_done( document , SP_VERB_DIALOG_SWATCHES, 
540                                               _("Change color definition"));
541                         }
542                     }
543                 }
544             }
545         }
546     }
550 Gtk::Widget* ColorItem::getPreview(PreviewStyle style, ViewType view, ::PreviewSize size, guint ratio)
552     Gtk::Widget* widget = 0;
553     if ( style == PREVIEW_STYLE_BLURB) {
554         Gtk::Label *lbl = new Gtk::Label(def.descr);
555         lbl->set_alignment(Gtk::ALIGN_LEFT, Gtk::ALIGN_CENTER);
556         widget = lbl;
557     } else {
558 //         Glib::ustring blank("          ");
559 //         if ( size == Inkscape::ICON_SIZE_MENU || size == Inkscape::ICON_SIZE_DECORATION ) {
560 //             blank = " ";
561 //         }
563         GtkWidget* eekWidget = eek_preview_new();
564         EekPreview * preview = EEK_PREVIEW(eekWidget);
565         Gtk::Widget* newBlot = Glib::wrap(eekWidget);
567         eek_preview_set_color( preview, (def.getR() << 8) | def.getR(), (def.getG() << 8) | def.getG(), (def.getB() << 8) | def.getB());
568         preview->_isRemove = _isRemove;
570         eek_preview_set_details( preview, (::PreviewStyle)style, (::ViewType)view, (::PreviewSize)size, ratio );
571         eek_preview_set_linked( preview, (LinkType)((_linkSrc ? PREVIEW_LINK_IN:0)
572                                                     | (_listeners.empty() ? 0:PREVIEW_LINK_OUT)
573                                                     | (_isLive ? PREVIEW_LINK_OTHER:0)) );
575         def.addCallback( _colorDefChanged, this );
577         GValue val = {0, {{0}, {0}}};
578         g_value_init( &val, G_TYPE_BOOLEAN );
579         g_value_set_boolean( &val, FALSE );
580         g_object_set_property( G_OBJECT(preview), "focus-on-click", &val );
582 /*
583         Gtk::Button *btn = new Gtk::Button(blank);
584         Gdk::Color color;
585         color.set_rgb((_r << 8)|_r, (_g << 8)|_g, (_b << 8)|_b);
586         btn->modify_bg(Gtk::STATE_NORMAL, color);
587         btn->modify_bg(Gtk::STATE_ACTIVE, color);
588         btn->modify_bg(Gtk::STATE_PRELIGHT, color);
589         btn->modify_bg(Gtk::STATE_SELECTED, color);
591         Gtk::Widget* newBlot = btn;
592 */
594         tips.set_tip((*newBlot), def.descr);
596 /*
597         newBlot->signal_clicked().connect( sigc::mem_fun(*this, &ColorItem::buttonClicked) );
599         sigc::signal<void> type_signal_something;
600 */
602         g_signal_connect( G_OBJECT(newBlot->gobj()),
603                           "clicked",
604                           G_CALLBACK(handleClick),
605                           this);
607         g_signal_connect( G_OBJECT(newBlot->gobj()),
608                           "alt-clicked",
609                           G_CALLBACK(handleSecondaryClick),
610                           this);
612         g_signal_connect( G_OBJECT(newBlot->gobj()),
613                           "button-press-event",
614                           G_CALLBACK(handleButtonPress),
615                           this);
617         gtk_drag_source_set( GTK_WIDGET(newBlot->gobj()),
618                              GDK_BUTTON1_MASK,
619                              sourceColorEntries,
620                              G_N_ELEMENTS(sourceColorEntries),
621                              GdkDragAction(GDK_ACTION_MOVE | GDK_ACTION_COPY) );
623         g_signal_connect( G_OBJECT(newBlot->gobj()),
624                           "drag-data-get",
625                           G_CALLBACK(ColorItem::_dragGetColorData),
626                           this);
628         g_signal_connect( G_OBJECT(newBlot->gobj()),
629                           "drag-begin",
630                           G_CALLBACK(dragBegin),
631                           this );
633         g_signal_connect( G_OBJECT(newBlot->gobj()),
634                           "enter-notify-event",
635                           G_CALLBACK(handleEnterNotify),
636                           this);
638         g_signal_connect( G_OBJECT(newBlot->gobj()),
639                           "leave-notify-event",
640                           G_CALLBACK(handleLeaveNotify),
641                           this);
643 //         g_signal_connect( G_OBJECT(newBlot->gobj()),
644 //                           "drag-drop",
645 //                           G_CALLBACK(dragDropColorData),
646 //                           this);
648         if ( def.isEditable() )
649         {
650             gtk_drag_dest_set( GTK_WIDGET(newBlot->gobj()),
651                                GTK_DEST_DEFAULT_ALL,
652                                destColorTargets,
653                                G_N_ELEMENTS(destColorTargets),
654                                GdkDragAction(GDK_ACTION_COPY | GDK_ACTION_MOVE) );
657             g_signal_connect( G_OBJECT(newBlot->gobj()),
658                               "drag-data-received",
659                               G_CALLBACK(_dropDataIn),
660                               this );
661         }
663         g_signal_connect( G_OBJECT(newBlot->gobj()),
664                           "destroy",
665                           G_CALLBACK(dieDieDie),
666                           this);
669         widget = newBlot;
670     }
672     _previews.push_back( widget );
674     return widget;
677 void ColorItem::buttonClicked(bool secondary)
679     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
680     if (!desktop) return;
681     char const * attrName = secondary ? "stroke" : "fill";
683     gchar c[64];
684     if (!_isRemove){
685         guint32 rgba = (def.getR() << 24) | (def.getG() << 16) | (def.getB() << 8) | 0xff;
686         sp_svg_write_color(c, sizeof(c), rgba);
687     }
689     SPCSSAttr *css = sp_repr_css_attr_new();
690     sp_repr_css_set_property( css, attrName, _isRemove ? "none" : c );
691     sp_desktop_set_style(desktop, css);
692     sp_repr_css_attr_unref(css);
694     if (_isRemove){
695         sp_document_done (sp_desktop_document (desktop), SP_VERB_DIALOG_SWATCHES, 
696                       secondary? _("Remove stroke color") : _("Remove fill color"));
697     } else {
698         sp_document_done (sp_desktop_document (desktop), SP_VERB_DIALOG_SWATCHES, 
699                       secondary? _("Set stroke color from swatch") : _("Set fill color from swatch"));
700     }
703 static char* trim( char* str ) {
704     char* ret = str;
705     while ( *str && (*str == ' ' || *str == '\t') ) {
706         str++;
707     }
708     ret = str;
709     while ( *str ) {
710         str++;
711     }
712     str--;
713     while ( str > ret && ( *str == ' ' || *str == '\t' ) || *str == '\r' || *str == '\n' ) {
714         *str-- = 0;
715     }
716     return ret;
719 void skipWhitespace( char*& str ) {
720     while ( *str == ' ' || *str == '\t' ) {
721         str++;
722     }
725 bool parseNum( char*& str, int& val ) {
726     val = 0;
727     while ( '0' <= *str && *str <= '9' ) {
728         val = val * 10 + (*str - '0');
729         str++;
730     }
731     bool retval = !(*str == 0 || *str == ' ' || *str == '\t' || *str == '\r' || *str == '\n');
732     return retval;
736 static bool getBlock( std::string& dst, guchar ch, std::string const str )
738     bool good = false;
739     std::string::size_type pos = str.find(ch);
740     if ( pos != std::string::npos )
741     {
742         std::string::size_type pos2 = str.find( '(', pos );
743         if ( pos2 != std::string::npos ) {
744             std::string::size_type endPos = str.find( ')', pos2 );
745             if ( endPos != std::string::npos ) {
746                 dst = str.substr( pos2 + 1, (endPos - pos2 - 1) );
747                 good = true;
748             }
749         }
750     }
751     return good;
754 static bool popVal( guint64& numVal, std::string& str )
756     bool good = false;
757     std::string::size_type endPos = str.find(',');
758     if ( endPos == std::string::npos ) {
759         endPos = str.length();
760     }
762     if ( endPos != std::string::npos && endPos > 0 ) {
763         std::string xxx = str.substr( 0, endPos );
764         const gchar* ptr = xxx.c_str();
765         gchar* endPtr = 0;
766         numVal = g_ascii_strtoull( ptr, &endPtr, 10 );
767         if ( (numVal == G_MAXUINT64) && (ERANGE == errno) ) {
768             // overflow
769         } else if ( (numVal == 0) && (endPtr == ptr) ) {
770             // failed conversion
771         } else {
772             good = true;
773             str.erase( 0, endPos + 1 );
774         }
775     }
777     return good;
780 void ColorItem::_wireMagicColors( void* p )
782     JustForNow* onceMore = reinterpret_cast<JustForNow*>(p);
783     if ( onceMore )
784     {
785         for ( std::vector<ColorItem*>::iterator it = onceMore->_colors.begin(); it != onceMore->_colors.end(); ++it )
786         {
787             std::string::size_type pos = (*it)->def.descr.find("*{");
788             if ( pos != std::string::npos )
789             {
790                 std::string subby = (*it)->def.descr.substr( pos + 2 );
791                 std::string::size_type endPos = subby.find("}*");
792                 if ( endPos != std::string::npos )
793                 {
794                     subby.erase( endPos );
795                     //g_message("FOUND MAGIC at '%s'", (*it)->def.descr.c_str());
796                     //g_message("               '%s'", subby.c_str());
798                     if ( subby.find('E') != std::string::npos )
799                     {
800                         (*it)->def.setEditable( true );
801                     }
803                     if ( subby.find('L') != std::string::npos )
804                     {
805                         (*it)->_isLive = true;
806                     }
808                     std::string part;
809                     // Tint. index + 1 more val.
810                     if ( getBlock( part, 'T', subby ) ) {
811                         guint64 colorIndex = 0;
812                         if ( popVal( colorIndex, part ) ) {
813                             guint64 percent = 0;
814                             if ( popVal( percent, part ) ) {
815                                 (*it)->_linkTint( *(onceMore->_colors[colorIndex]), percent );
816                             }
817                         }
818                     }
820                     // Shade/tone. index + 1 or 2 more val.
821                     if ( getBlock( part, 'S', subby ) ) {
822                         guint64 colorIndex = 0;
823                         if ( popVal( colorIndex, part ) ) {
824                             guint64 percent = 0;
825                             if ( popVal( percent, part ) ) {
826                                 guint64 grayLevel = 0;
827                                 if ( !popVal( grayLevel, part ) ) {
828                                     grayLevel = 0;
829                                 }
830                                 (*it)->_linkTone( *(onceMore->_colors[colorIndex]), percent, grayLevel );
831                             }
832                         }
833                     }
835                 }
836             }
837         }
838     }
842 void ColorItem::_linkTint( ColorItem& other, int percent )
844     if ( !_linkSrc )
845     {
846         other._listeners.push_back(this);
847         _linkIsTone = false;
848         _linkPercent = percent;
849         if ( _linkPercent > 100 )
850             _linkPercent = 100;
851         if ( _linkPercent < 0 )
852             _linkPercent = 0;
853         _linkGray = 0;
854         _linkSrc = &other;
856         ColorItem::_colorDefChanged(&other);
857     }
860 void ColorItem::_linkTone( ColorItem& other, int percent, int grayLevel )
862     if ( !_linkSrc )
863     {
864         other._listeners.push_back(this);
865         _linkIsTone = true;
866         _linkPercent = percent;
867         if ( _linkPercent > 100 )
868             _linkPercent = 100;
869         if ( _linkPercent < 0 )
870             _linkPercent = 0;
871         _linkGray = grayLevel;
872         _linkSrc = &other;
874         ColorItem::_colorDefChanged(&other);
875     }
879 void _loadPaletteFile( gchar const *filename )
881     char block[1024];
882     FILE *f = Inkscape::IO::fopen_utf8name( filename, "r" );
883     if ( f ) {
884         char* result = fgets( block, sizeof(block), f );
885         if ( result ) {
886             if ( strncmp( "GIMP Palette", block, 12 ) == 0 ) {
887                 bool inHeader = true;
888                 bool hasErr = false;
890                 JustForNow *onceMore = new JustForNow();
892                 do {
893                     result = fgets( block, sizeof(block), f );
894                     block[sizeof(block) - 1] = 0;
895                     if ( result ) {
896                         if ( block[0] == '#' ) {
897                             // ignore comment
898                         } else {
899                             char *ptr = block;
900                             // very simple check for header versus entry
901                             while ( *ptr == ' ' || *ptr == '\t' ) {
902                                 ptr++;
903                             }
904                             if ( (*ptr == 0) || (*ptr == '\r') || (*ptr == '\n') ) {
905                                 // blank line. skip it.
906                             } else if ( '0' <= *ptr && *ptr <= '9' ) {
907                                 // should be an entry link
908                                 inHeader = false;
909                                 ptr = block;
910                                 Glib::ustring name("");
911                                 int r = 0;
912                                 int g = 0;
913                                 int b = 0;
914                                 skipWhitespace(ptr);
915                                 if ( *ptr ) {
916                                     hasErr = parseNum(ptr, r);
917                                     if ( !hasErr ) {
918                                         skipWhitespace(ptr);
919                                         hasErr = parseNum(ptr, g);
920                                     }
921                                     if ( !hasErr ) {
922                                         skipWhitespace(ptr);
923                                         hasErr = parseNum(ptr, b);
924                                     }
925                                     if ( !hasErr && *ptr ) {
926                                         char* n = trim(ptr);
927                                         if (n != NULL) {
928                                             name = n;
929                                         }
930                                     }
931                                     if ( !hasErr ) {
932                                         // Add the entry now
933                                         Glib::ustring nameStr(name);
934                                         ColorItem* item = new ColorItem( r, g, b, nameStr );
935                                         onceMore->_colors.push_back(item);
936                                     }
937                                 } else {
938                                     hasErr = true;
939                                 }
940                             } else {
941                                 if ( !inHeader ) {
942                                     // Hmmm... probably bad. Not quite the format we want?
943                                     hasErr = true;
944                                 } else {
945                                     char* sep = strchr(result, ':');
946                                     if ( sep ) {
947                                         *sep = 0;
948                                         char* val = trim(sep + 1);
949                                         char* name = trim(result);
950                                         if ( *name ) {
951                                             if ( strcmp( "Name", name ) == 0 )
952                                             {
953                                                 onceMore->_name = val;
954                                             }
955                                             else if ( strcmp( "Columns", name ) == 0 )
956                                             {
957                                                 gchar* endPtr = 0;
958                                                 guint64 numVal = g_ascii_strtoull( val, &endPtr, 10 );
959                                                 if ( (numVal == G_MAXUINT64) && (ERANGE == errno) ) {
960                                                     // overflow
961                                                 } else if ( (numVal == 0) && (endPtr == val) ) {
962                                                     // failed conversion
963                                                 } else {
964                                                     onceMore->_prefWidth = numVal;
965                                                 }
966                                             }
967                                         } else {
968                                             // error
969                                             hasErr = true;
970                                         }
971                                     } else {
972                                         // error
973                                         hasErr = true;
974                                     }
975                                 }
976                             }
977                         }
978                     }
979                 } while ( result && !hasErr );
980                 if ( !hasErr ) {
981                     possible.push_back(onceMore);
982 #if ENABLE_MAGIC_COLORS
983                     ColorItem::_wireMagicColors( onceMore );
984 #endif // ENABLE_MAGIC_COLORS
985                 } else {
986                     delete onceMore;
987                 }
988             }
989         }
991         fclose(f);
992     }
995 static void loadEmUp()
997     static bool beenHere = false;
998     if ( !beenHere ) {
999         beenHere = true;
1001         std::list<gchar *> sources;
1002         sources.push_back( profile_path("palettes") );
1003         sources.push_back( g_strdup(INKSCAPE_PALETTESDIR) );
1004         sources.push_back( g_strdup(CREATE_PALETTESDIR) );
1006         // Use this loop to iterate through a list of possible document locations.
1007         while (!sources.empty()) {
1008             gchar *dirname = sources.front();
1010             if ( Inkscape::IO::file_test( dirname, G_FILE_TEST_EXISTS )
1011                 && Inkscape::IO::file_test( dirname, G_FILE_TEST_IS_DIR )) {
1012                 GError *err = 0;
1013                 GDir *directory = g_dir_open(dirname, 0, &err);
1014                 if (!directory) {
1015                     gchar *safeDir = Inkscape::IO::sanitizeString(dirname);
1016                     g_warning(_("Palettes directory (%s) is unavailable."), safeDir);
1017                     g_free(safeDir);
1018                 } else {
1019                     gchar *filename = 0;
1020                     while ((filename = (gchar *)g_dir_read_name(directory)) != NULL) {
1021                         gchar* lower = g_ascii_strdown( filename, -1 );
1022 //                        if ( g_str_has_suffix(lower, ".gpl") ) {
1023                             gchar* full = g_build_filename(dirname, filename, NULL);
1024                             if ( !Inkscape::IO::file_test( full, G_FILE_TEST_IS_DIR ) ) {
1025                                 _loadPaletteFile(full);
1026                             }
1027                             g_free(full);
1028 //                      }
1029                         g_free(lower);
1030                     }
1031                     g_dir_close(directory);
1032                 }
1033             }
1035             // toss the dirname
1036             g_free(dirname);
1037             sources.pop_front();
1038         }
1039     }
1050 SwatchesPanel& SwatchesPanel::getInstance()
1052     return *new SwatchesPanel();
1056 /**
1057  * Constructor
1058  */
1059 SwatchesPanel::SwatchesPanel(gchar const* prefsPath) :
1060     Inkscape::UI::Widget::Panel("", prefsPath, SP_VERB_DIALOG_SWATCHES, "", true),
1061     _holder(0)
1063     Gtk::RadioMenuItem* hotItem = 0;
1064     _holder = new PreviewHolder();
1065     _remove = new ColorItem();
1066     loadEmUp();
1067     if ( !possible.empty() ) {
1068         JustForNow* first = 0;
1069         Glib::ustring targetName;
1070         if ( !_prefs_path.empty() ) {
1071             Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1072             targetName = prefs->getString(_prefs_path + "/palette");
1073             if (!targetName.empty()) {
1074                 for ( std::vector<JustForNow*>::iterator iter = possible.begin(); iter != possible.end(); ++iter ) {
1075                     if ( (*iter)->_name == targetName ) {
1076                         first = *iter;
1077                         break;
1078                     }
1079                 }
1080             }
1081         }
1083         if ( !first ) {
1084             first = possible.front();
1085         }
1087         if ( first->_prefWidth > 0 ) {
1088             _holder->setColumnPref( first->_prefWidth );
1089         }
1090         _holder->freezeUpdates();
1091         _holder->addPreview(_remove);
1092         for ( std::vector<ColorItem*>::iterator it = first->_colors.begin(); it != first->_colors.end(); it++ ) {
1093             _holder->addPreview(*it);
1094         }
1095         _holder->thawUpdates();
1097         Gtk::RadioMenuItem::Group groupOne;
1099         int i = 0;
1100         for ( std::vector<JustForNow*>::iterator it = possible.begin(); it != possible.end(); it++ ) {
1101             JustForNow* curr = *it;
1102             Gtk::RadioMenuItem* single = manage(new Gtk::RadioMenuItem(groupOne, curr->_name));
1103             if ( curr == first ) {
1104                 hotItem = single;
1105             }
1106             _regItem( single, 3, i );
1107             i++;
1108         }
1109     }
1112     _getContents()->pack_start(*_holder, Gtk::PACK_EXPAND_WIDGET);
1113     _setTargetFillable(_holder);
1115     show_all_children();
1117     restorePanelPrefs();
1118     if ( hotItem ) {
1119         hotItem->set_active();
1120     }
1123 SwatchesPanel::~SwatchesPanel()
1125     if (_remove) delete _remove;
1126     if (_holder) delete _holder;
1129 void SwatchesPanel::setOrientation( Gtk::AnchorType how )
1131     // Must call the parent class or bad things might happen
1132     Inkscape::UI::Widget::Panel::setOrientation( how );
1134     if ( _holder )
1135     {
1136         _holder->setOrientation( Gtk::ANCHOR_SOUTH );
1137     }
1140 void SwatchesPanel::_handleAction( int setId, int itemId )
1142     switch( setId ) {
1143         case 3:
1144         {
1145             if ( itemId >= 0 && itemId < static_cast<int>(possible.size()) ) {
1146                 _holder->clear();
1147                 JustForNow* curr = possible[itemId];
1149                 if ( !_prefs_path.empty() ) {
1150                     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1151                     prefs->setString(_prefs_path + "/palette", curr->_name);
1152                 }
1154                 if ( curr->_prefWidth > 0 ) {
1155                     _holder->setColumnPref( curr->_prefWidth );
1156                 }
1157                 _holder->freezeUpdates();
1158                 _holder->addPreview(_remove);
1159                 for ( std::vector<ColorItem*>::iterator it = curr->_colors.begin(); it != curr->_colors.end(); it++ ) {
1160                     _holder->addPreview(*it);
1161                 }
1162                 _holder->thawUpdates();
1163             }
1164         }
1165         break;
1166     }
1169 } //namespace Dialogs
1170 } //namespace UI
1171 } //namespace Inkscape
1174 /*
1175   Local Variables:
1176   mode:c++
1177   c-file-style:"stroustrup"
1178   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1179   indent-tabs-mode:nil
1180   fill-column:99
1181   End:
1182 */
1183 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :