Code

now that selection description includes style (filtered, clipped), we need to update...
[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 //TODO: warning: deprecated conversion from string constant to ‘gchar*’
104 //
105 //Turn out to be warnings that we should probably leave in place. The
106 // pointers/types used need to be read-only. So until we correct the using
107 // code, those warnings are actually desired. They say "Hey! Fix this". We
108 // definitely don't want to hide/ignore them. --JonCruz
109 static const GtkTargetEntry sourceColorEntries[] = {
110 #if ENABLE_MAGIC_COLORS
111 //    {"application/x-inkscape-color-id", GTK_TARGET_SAME_APP, APP_X_INKY_COLOR_ID},
112     {"application/x-inkscape-color", 0, APP_X_INKY_COLOR},
113 #endif // ENABLE_MAGIC_COLORS
114     {"application/x-color", 0, APP_X_COLOR},
115     {"text/plain", 0, TEXT_DATA},
116 };
118 void ColorItem::_dragGetColorData( GtkWidget *widget,
119                                    GdkDragContext *drag_context,
120                                    GtkSelectionData *data,
121                                    guint info,
122                                    guint time,
123                                    gpointer user_data)
125     (void)widget;
126     (void)drag_context;
127     (void)time;
128     static GdkAtom typeXColor = gdk_atom_intern("application/x-color", FALSE);
129     static GdkAtom typeText = gdk_atom_intern("text/plain", FALSE);
131     ColorItem* item = reinterpret_cast<ColorItem*>(user_data);
132     if ( info == TEXT_DATA ) {
133         gchar* tmp = g_strdup_printf("#%02x%02x%02x", item->def.getR(), item->def.getG(), item->def.getB() );
135         gtk_selection_data_set( data,
136                                 typeText,
137                                 8, // format
138                                 (guchar*)tmp,
139                                 strlen((const char*)tmp) + 1);
140         g_free(tmp);
141         tmp = 0;
142     } else if ( info == APP_X_INKY_COLOR ) {
143         Glib::ustring paletteName;
145         // Find where this thing came from
146         bool found = false;
147         int index = 0;
148         for ( std::vector<JustForNow*>::iterator it = possible.begin(); it != possible.end() && !found; ++it ) {
149             JustForNow* curr = *it;
150             index = 0;
151             for ( std::vector<ColorItem*>::iterator zz = curr->_colors.begin(); zz != curr->_colors.end(); ++zz ) {
152                 if ( item == *zz ) {
153                     found = true;
154                     paletteName = curr->_name;
155                     break;
156                 } else {
157                     index++;
158                 }
159             }
160         }
162 //         if ( found ) {
163 //             g_message("Found the color at entry %d in palette '%s'", index, paletteName.c_str() );
164 //         } else {
165 //             g_message("Unable to find the color");
166 //         }
167         int itemCount = 4 + 2 + 1 + paletteName.length();
169         guint16* tmp = new guint16[itemCount];
170         tmp[0] = (item->def.getR() << 8) | item->def.getR();
171         tmp[1] = (item->def.getG() << 8) | item->def.getG();
172         tmp[2] = (item->def.getB() << 8) | item->def.getB();
173         tmp[3] = 0xffff;
174         tmp[4] = (item->_isLive || !item->_listeners.empty() || (item->_linkSrc != 0) ) ? 1 : 0;
176         tmp[5] = index;
177         tmp[6] = paletteName.length();
178         for ( unsigned int i = 0; i < paletteName.length(); i++ ) {
179             tmp[7 + i] = paletteName[i];
180         }
181         gtk_selection_data_set( data,
182                                 typeXColor,
183                                 16, // format
184                                 reinterpret_cast<const guchar*>(tmp),
185                                 itemCount * 2);
186         delete[] tmp;
187     } else {
188         guint16 tmp[4];
189         tmp[0] = (item->def.getR() << 8) | item->def.getR();
190         tmp[1] = (item->def.getG() << 8) | item->def.getG();
191         tmp[2] = (item->def.getB() << 8) | item->def.getB();
192         tmp[3] = 0xffff;
193         gtk_selection_data_set( data,
194                                 typeXColor,
195                                 16, // format
196                                 reinterpret_cast<const guchar*>(tmp),
197                                 (3+1) * 2);
198     }
201 static void dragBegin( GtkWidget *widget, GdkDragContext* dc, gpointer data )
203     (void)widget;
204     ColorItem* item = reinterpret_cast<ColorItem*>(data);
205     if ( item )
206     {
207         if (item->isRemove()){
208             GError *error = NULL;
209             gchar *filepath = (gchar *) g_strdup_printf("%s/remove-color.png", INKSCAPE_PIXMAPDIR);
210             gsize bytesRead = 0;
211             gsize bytesWritten = 0;
212             gchar *localFilename = g_filename_from_utf8( filepath,
213                                                  -1,
214                                                  &bytesRead,
215                                                  &bytesWritten,
216                                                  &error);
217             GdkPixbuf* pixbuf = gdk_pixbuf_new_from_file_at_scale(localFilename, 32, 24, FALSE, &error);
218             g_free(localFilename);
219             g_free(filepath);
220             gtk_drag_set_icon_pixbuf( dc, pixbuf, 0, 0 );
221             return;
222         }
224         Glib::RefPtr<Gdk::Pixbuf> thumb = Gdk::Pixbuf::create( Gdk::COLORSPACE_RGB, false, 8, 32, 24 );
225         guint32 fillWith = (0xff000000 & (item->def.getR() << 24))
226                          | (0x00ff0000 & (item->def.getG() << 16))
227                          | (0x0000ff00 & (item->def.getB() <<  8));
228         thumb->fill( fillWith );
229         gtk_drag_set_icon_pixbuf( dc, thumb->gobj(), 0, 0 );
230     }
234 //"drag-drop"
235 // gboolean dragDropColorData( GtkWidget *widget,
236 //                             GdkDragContext *drag_context,
237 //                             gint x,
238 //                             gint y,
239 //                             guint time,
240 //                             gpointer user_data)
241 // {
242 // // TODO finish
244 //     return TRUE;
245 // }
247 static void handleClick( GtkWidget* widget, gpointer callback_data ) {
248     (void)widget;
249     ColorItem* item = reinterpret_cast<ColorItem*>(callback_data);
250     if ( item ) {
251         item->buttonClicked(false);
252     }
255 static void handleSecondaryClick( GtkWidget* widget, gint arg1, gpointer callback_data ) {
256     (void)widget;
257     (void)arg1;
258     ColorItem* item = reinterpret_cast<ColorItem*>(callback_data);
259     if ( item ) {
260         item->buttonClicked(true);
261     }
264 static gboolean handleEnterNotify( GtkWidget* /*widget*/, GdkEventCrossing* /*event*/, gpointer callback_data ) {
265     ColorItem* item = reinterpret_cast<ColorItem*>(callback_data);
266     if ( item ) {
267         SPDesktop *desktop = SP_ACTIVE_DESKTOP;
268         if ( desktop ) {
269             gchar* msg = g_strdup_printf(_("Color: <b>%s</b>; <b>Click</b> to set fill, <b>Shift+click</b> to set stroke"),
270                                          item->def.descr.c_str());
271             desktop->tipsMessageContext()->set(Inkscape::INFORMATION_MESSAGE, msg);
272             g_free(msg);
273         }
274     }
275     return FALSE;
278 static gboolean handleLeaveNotify( GtkWidget* /*widget*/, GdkEventCrossing* /*event*/, gpointer callback_data ) {
279     ColorItem* item = reinterpret_cast<ColorItem*>(callback_data);
280     if ( item ) {
281         SPDesktop *desktop = SP_ACTIVE_DESKTOP;
282         if ( desktop ) {
283             desktop->tipsMessageContext()->clear();
284         }
285     }
286     return FALSE;
289 static GtkWidget* popupMenu = 0;
290 static ColorItem* bounceTarget = 0;
292 static void redirClick( GtkMenuItem *menuitem, gpointer user_data )
294     (void)user_data;
295     if ( bounceTarget ) {
296         handleClick( GTK_WIDGET(menuitem), bounceTarget );
297     }
300 static void redirSecondaryClick( GtkMenuItem *menuitem, gpointer user_data )
302     (void)user_data;
303     if ( bounceTarget ) {
304         handleSecondaryClick( GTK_WIDGET(menuitem), 0, bounceTarget );
305     }
308 static gboolean handleButtonPress( GtkWidget* widget, GdkEventButton* event, gpointer user_data)
310     (void)widget;
311     gboolean handled = FALSE;
313     if ( (event->button == 3) && (event->type == GDK_BUTTON_PRESS) ) {
314         if ( !popupMenu ) {
315             popupMenu = gtk_menu_new();
316             GtkWidget* child = 0;
318             //TRANSLATORS: An item in context menu on a colour in the swatches
319             child = gtk_menu_item_new_with_label(_("Set fill"));
320             g_signal_connect( G_OBJECT(child),
321                               "activate",
322                               G_CALLBACK(redirClick),
323                               user_data);
324             gtk_menu_shell_append(GTK_MENU_SHELL(popupMenu), child);
326             //TRANSLATORS: An item in context menu on a colour in the swatches
327             child = gtk_menu_item_new_with_label(_("Set stroke"));
329             g_signal_connect( G_OBJECT(child),
330                               "activate",
331                               G_CALLBACK(redirSecondaryClick),
332                               user_data);
333             gtk_menu_shell_append(GTK_MENU_SHELL(popupMenu), child);
335             gtk_widget_show_all(popupMenu);
336         }
338         ColorItem* item = reinterpret_cast<ColorItem*>(user_data);
339         if ( item ) {
340             bounceTarget = item;
341             if ( popupMenu ) {
342                 gtk_menu_popup(GTK_MENU(popupMenu), NULL, NULL, NULL, NULL, event->button, event->time);
343                 handled = TRUE;
344             }
345         }
346     }
348     return handled;
351 static void dieDieDie( GtkObject *obj, gpointer user_data )
353     g_message("die die die %p  %p", obj, user_data );
356 //TODO: warning: deprecated conversion from string constant to ‘gchar*’
357 //
358 //Turn out to be warnings that we should probably leave in place. The
359 // pointers/types used need to be read-only. So until we correct the using
360 // code, those warnings are actually desired. They say "Hey! Fix this". We
361 // definitely don't want to hide/ignore them. --JonCruz
362 static const GtkTargetEntry destColorTargets[] = {
363 #if ENABLE_MAGIC_COLORS
364 //    {"application/x-inkscape-color-id", GTK_TARGET_SAME_APP, APP_X_INKY_COLOR_ID},
365     {"application/x-inkscape-color", 0, APP_X_INKY_COLOR},
366 #endif // ENABLE_MAGIC_COLORS
367     {"application/x-color", 0, APP_X_COLOR},
368 };
370 #include "color.h" // for SP_RGBA32_U_COMPOSE
372 void ColorItem::_dropDataIn( GtkWidget *widget,
373                              GdkDragContext *drag_context,
374                              gint x, gint y,
375                              GtkSelectionData *data,
376                              guint info,
377                              guint event_time,
378                              gpointer user_data)
380     (void)widget;
381     (void)drag_context;
382     (void)x;
383     (void)y;
384     (void)event_time;
385 //     g_message("    droppy droppy   %d", info);
386      switch (info) {
387          case APP_X_INKY_COLOR:
388          {
389              if ( data->length >= 8 ) {
390                  // Careful about endian issues.
391                  guint16* dataVals = (guint16*)data->data;
392                  if ( user_data ) {
393                      ColorItem* item = reinterpret_cast<ColorItem*>(user_data);
394                      if ( item->def.isEditable() ) {
395                          // Shove on in the new value
396                          item->def.setRGB( 0x0ff & (dataVals[0] >> 8), 0x0ff & (dataVals[1] >> 8), 0x0ff & (dataVals[2] >> 8) );
397                      }
398                  }
399              }
400              break;
401          }
402          case APP_X_COLOR:
403          {
404              if ( data->length == 8 ) {
405                  // Careful about endian issues.
406                  guint16* dataVals = (guint16*)data->data;
407 //                  {
408 //                      gchar c[64] = {0};
409 //                      sp_svg_write_color( c, 64,
410 //                                          SP_RGBA32_U_COMPOSE(
411 //                                              0x0ff & (dataVals[0] >> 8),
412 //                                              0x0ff & (dataVals[1] >> 8),
413 //                                              0x0ff & (dataVals[2] >> 8),
414 //                                              0xff // can't have transparency in the color itself
415 //                                              //0x0ff & (data->data[3] >> 8),
416 //                                              ));
417 //                  }
418                  if ( user_data ) {
419                      ColorItem* item = reinterpret_cast<ColorItem*>(user_data);
420                      if ( item->def.isEditable() ) {
421                          // Shove on in the new value
422                          item->def.setRGB( 0x0ff & (dataVals[0] >> 8), 0x0ff & (dataVals[1] >> 8), 0x0ff & (dataVals[2] >> 8) );
423                      }
424                  }
425              }
426              break;
427          }
428          default:
429              g_message("unknown drop type");
430      }
434 static bool bruteForce( SPDocument* document, Inkscape::XML::Node* node, Glib::ustring const& match, int r, int g, int b )
436     bool changed = false;
438     if ( node ) {
439         gchar const * val = node->attribute("inkscape:x-fill-tag");
440         if ( val  && (match == val) ) {
441             SPObject *obj = document->getObjectByRepr( node );
443             gchar c[64] = {0};
444             sp_svg_write_color( c, sizeof(c), SP_RGBA32_U_COMPOSE( r, g, b, 0xff ) );
445             SPCSSAttr *css = sp_repr_css_attr_new();
446             sp_repr_css_set_property( css, "fill", c );
448             sp_desktop_apply_css_recursive( (SPItem*)obj, css, true );
449             ((SPItem*)obj)->updateRepr();
451             changed = true;
452         }
454         val = node->attribute("inkscape:x-stroke-tag");
455         if ( val  && (match == val) ) {
456             SPObject *obj = document->getObjectByRepr( node );
458             gchar c[64] = {0};
459             sp_svg_write_color( c, sizeof(c), SP_RGBA32_U_COMPOSE( r, g, b, 0xff ) );
460             SPCSSAttr *css = sp_repr_css_attr_new();
461             sp_repr_css_set_property( css, "stroke", c );
463             sp_desktop_apply_css_recursive( (SPItem*)obj, css, true );
464             ((SPItem*)obj)->updateRepr();
466             changed = true;
467         }
469         Inkscape::XML::Node* first = node->firstChild();
470         changed |= bruteForce( document, first, match, r, g, b );
472         changed |= bruteForce( document, node->next(), match, r, g, b );
473     }
475     return changed;
478 void ColorItem::_colorDefChanged(void* data)
480     ColorItem* item = reinterpret_cast<ColorItem*>(data);
481     if ( item ) {
482         for ( std::vector<Gtk::Widget*>::iterator it =  item->_previews.begin(); it != item->_previews.end(); ++it ) {
483             Gtk::Widget* widget = *it;
484             if ( IS_EEK_PREVIEW(widget->gobj()) ) {
485                 EekPreview * preview = EEK_PREVIEW(widget->gobj());
486                 eek_preview_set_color( preview,
487                                        (item->def.getR() << 8) | item->def.getR(),
488                                        (item->def.getG() << 8) | item->def.getG(),
489                                        (item->def.getB() << 8) | item->def.getB() );
491                 eek_preview_set_linked( preview, (LinkType)((item->_linkSrc ? PREVIEW_LINK_IN:0)
492                                                             | (item->_listeners.empty() ? 0:PREVIEW_LINK_OUT)
493                                                             | (item->_isLive ? PREVIEW_LINK_OTHER:0)) );
495                 widget->queue_draw();
496             }
497         }
499         for ( std::vector<ColorItem*>::iterator it = item->_listeners.begin(); it != item->_listeners.end(); ++it ) {
500             guint r = item->def.getR();
501             guint g = item->def.getG();
502             guint b = item->def.getB();
504             if ( (*it)->_linkIsTone ) {
505                 r = ( ((*it)->_linkPercent * (*it)->_linkGray) + ((100 - (*it)->_linkPercent) * r) ) / 100;
506                 g = ( ((*it)->_linkPercent * (*it)->_linkGray) + ((100 - (*it)->_linkPercent) * g) ) / 100;
507                 b = ( ((*it)->_linkPercent * (*it)->_linkGray) + ((100 - (*it)->_linkPercent) * b) ) / 100;
508             } else {
509                 r = ( ((*it)->_linkPercent * 255) + ((100 - (*it)->_linkPercent) * r) ) / 100;
510                 g = ( ((*it)->_linkPercent * 255) + ((100 - (*it)->_linkPercent) * g) ) / 100;
511                 b = ( ((*it)->_linkPercent * 255) + ((100 - (*it)->_linkPercent) * b) ) / 100;
512             }
514             (*it)->def.setRGB( r, g, b );
515         }
518         // Look for objects using this color
519         {
520             SPDesktop *desktop = SP_ACTIVE_DESKTOP;
521             if ( desktop ) {
522                 SPDocument* document = sp_desktop_document( desktop );
523                 Inkscape::XML::Node *rroot =  sp_document_repr_root( document );
524                 if ( rroot ) {
526                     // Find where this thing came from
527                     Glib::ustring paletteName;
528                     bool found = false;
529                     int index = 0;
530                     for ( std::vector<JustForNow*>::iterator it2 = possible.begin(); it2 != possible.end() && !found; ++it2 ) {
531                         JustForNow* curr = *it2;
532                         index = 0;
533                         for ( std::vector<ColorItem*>::iterator zz = curr->_colors.begin(); zz != curr->_colors.end(); ++zz ) {
534                             if ( item == *zz ) {
535                                 found = true;
536                                 paletteName = curr->_name;
537                                 break;
538                             } else {
539                                 index++;
540                             }
541                         }
542                     }
544                     if ( !paletteName.empty() ) {
545                         gchar* str = g_strdup_printf("%d|", index);
546                         paletteName.insert( 0, str );
547                         g_free(str);
548                         str = 0;
550                         if ( bruteForce( document, rroot, paletteName, item->def.getR(), item->def.getG(), item->def.getB() ) ) {
551                             sp_document_done( document , SP_VERB_DIALOG_SWATCHES, 
552                                               _("Change color definition"));
553                         }
554                     }
555                 }
556             }
557         }
558     }
562 Gtk::Widget* ColorItem::getPreview(PreviewStyle style, ViewType view, ::PreviewSize size, guint ratio)
564     Gtk::Widget* widget = 0;
565     if ( style == PREVIEW_STYLE_BLURB) {
566         Gtk::Label *lbl = new Gtk::Label(def.descr);
567         lbl->set_alignment(Gtk::ALIGN_LEFT, Gtk::ALIGN_CENTER);
568         widget = lbl;
569     } else {
570 //         Glib::ustring blank("          ");
571 //         if ( size == Inkscape::ICON_SIZE_MENU || size == Inkscape::ICON_SIZE_DECORATION ) {
572 //             blank = " ";
573 //         }
575         GtkWidget* eekWidget = eek_preview_new();
576         EekPreview * preview = EEK_PREVIEW(eekWidget);
577         Gtk::Widget* newBlot = Glib::wrap(eekWidget);
579         eek_preview_set_color( preview, (def.getR() << 8) | def.getR(), (def.getG() << 8) | def.getG(), (def.getB() << 8) | def.getB());
580         preview->_isRemove = _isRemove;
582         eek_preview_set_details( preview, (::PreviewStyle)style, (::ViewType)view, (::PreviewSize)size, ratio );
583         eek_preview_set_linked( preview, (LinkType)((_linkSrc ? PREVIEW_LINK_IN:0)
584                                                     | (_listeners.empty() ? 0:PREVIEW_LINK_OUT)
585                                                     | (_isLive ? PREVIEW_LINK_OTHER:0)) );
587         def.addCallback( _colorDefChanged, this );
589         GValue val = {0, {{0}, {0}}};
590         g_value_init( &val, G_TYPE_BOOLEAN );
591         g_value_set_boolean( &val, FALSE );
592         g_object_set_property( G_OBJECT(preview), "focus-on-click", &val );
594 /*
595         Gtk::Button *btn = new Gtk::Button(blank);
596         Gdk::Color color;
597         color.set_rgb((_r << 8)|_r, (_g << 8)|_g, (_b << 8)|_b);
598         btn->modify_bg(Gtk::STATE_NORMAL, color);
599         btn->modify_bg(Gtk::STATE_ACTIVE, color);
600         btn->modify_bg(Gtk::STATE_PRELIGHT, color);
601         btn->modify_bg(Gtk::STATE_SELECTED, color);
603         Gtk::Widget* newBlot = btn;
604 */
606         tips.set_tip((*newBlot), def.descr);
608 /*
609         newBlot->signal_clicked().connect( sigc::mem_fun(*this, &ColorItem::buttonClicked) );
611         sigc::signal<void> type_signal_something;
612 */
614         g_signal_connect( G_OBJECT(newBlot->gobj()),
615                           "clicked",
616                           G_CALLBACK(handleClick),
617                           this);
619         g_signal_connect( G_OBJECT(newBlot->gobj()),
620                           "alt-clicked",
621                           G_CALLBACK(handleSecondaryClick),
622                           this);
624         g_signal_connect( G_OBJECT(newBlot->gobj()),
625                           "button-press-event",
626                           G_CALLBACK(handleButtonPress),
627                           this);
629         gtk_drag_source_set( GTK_WIDGET(newBlot->gobj()),
630                              GDK_BUTTON1_MASK,
631                              sourceColorEntries,
632                              G_N_ELEMENTS(sourceColorEntries),
633                              GdkDragAction(GDK_ACTION_MOVE | GDK_ACTION_COPY) );
635         g_signal_connect( G_OBJECT(newBlot->gobj()),
636                           "drag-data-get",
637                           G_CALLBACK(ColorItem::_dragGetColorData),
638                           this);
640         g_signal_connect( G_OBJECT(newBlot->gobj()),
641                           "drag-begin",
642                           G_CALLBACK(dragBegin),
643                           this );
645         g_signal_connect( G_OBJECT(newBlot->gobj()),
646                           "enter-notify-event",
647                           G_CALLBACK(handleEnterNotify),
648                           this);
650         g_signal_connect( G_OBJECT(newBlot->gobj()),
651                           "leave-notify-event",
652                           G_CALLBACK(handleLeaveNotify),
653                           this);
655 //         g_signal_connect( G_OBJECT(newBlot->gobj()),
656 //                           "drag-drop",
657 //                           G_CALLBACK(dragDropColorData),
658 //                           this);
660         if ( def.isEditable() )
661         {
662             gtk_drag_dest_set( GTK_WIDGET(newBlot->gobj()),
663                                GTK_DEST_DEFAULT_ALL,
664                                destColorTargets,
665                                G_N_ELEMENTS(destColorTargets),
666                                GdkDragAction(GDK_ACTION_COPY | GDK_ACTION_MOVE) );
669             g_signal_connect( G_OBJECT(newBlot->gobj()),
670                               "drag-data-received",
671                               G_CALLBACK(_dropDataIn),
672                               this );
673         }
675         g_signal_connect( G_OBJECT(newBlot->gobj()),
676                           "destroy",
677                           G_CALLBACK(dieDieDie),
678                           this);
681         widget = newBlot;
682     }
684     _previews.push_back( widget );
686     return widget;
689 void ColorItem::buttonClicked(bool secondary)
691     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
692     if (!desktop) return;
693     char const * attrName = secondary ? "stroke" : "fill";
695     gchar c[64];
696     if (!_isRemove){
697         guint32 rgba = (def.getR() << 24) | (def.getG() << 16) | (def.getB() << 8) | 0xff;
698         sp_svg_write_color(c, sizeof(c), rgba);
699     }
701     SPCSSAttr *css = sp_repr_css_attr_new();
702     sp_repr_css_set_property( css, attrName, _isRemove ? "none" : c );
703     sp_desktop_set_style(desktop, css);
704     sp_repr_css_attr_unref(css);
706     if (_isRemove){
707         sp_document_done (sp_desktop_document (desktop), SP_VERB_DIALOG_SWATCHES, 
708                       secondary? _("Remove stroke color") : _("Remove fill color"));
709     } else {
710         sp_document_done (sp_desktop_document (desktop), SP_VERB_DIALOG_SWATCHES, 
711                       secondary? _("Set stroke color from swatch") : _("Set fill color from swatch"));
712     }
715 static char* trim( char* str ) {
716     char* ret = str;
717     while ( *str && (*str == ' ' || *str == '\t') ) {
718         str++;
719     }
720     ret = str;
721     while ( *str ) {
722         str++;
723     }
724     str--;
725     while ( str > ret && (( *str == ' ' || *str == '\t' ) || *str == '\r' || *str == '\n') ) {
726         *str-- = 0;
727     }
728     return ret;
731 void skipWhitespace( char*& str ) {
732     while ( *str == ' ' || *str == '\t' ) {
733         str++;
734     }
737 bool parseNum( char*& str, int& val ) {
738     val = 0;
739     while ( '0' <= *str && *str <= '9' ) {
740         val = val * 10 + (*str - '0');
741         str++;
742     }
743     bool retval = !(*str == 0 || *str == ' ' || *str == '\t' || *str == '\r' || *str == '\n');
744     return retval;
748 static bool getBlock( std::string& dst, guchar ch, std::string const str )
750     bool good = false;
751     std::string::size_type pos = str.find(ch);
752     if ( pos != std::string::npos )
753     {
754         std::string::size_type pos2 = str.find( '(', pos );
755         if ( pos2 != std::string::npos ) {
756             std::string::size_type endPos = str.find( ')', pos2 );
757             if ( endPos != std::string::npos ) {
758                 dst = str.substr( pos2 + 1, (endPos - pos2 - 1) );
759                 good = true;
760             }
761         }
762     }
763     return good;
766 static bool popVal( guint64& numVal, std::string& str )
768     bool good = false;
769     std::string::size_type endPos = str.find(',');
770     if ( endPos == std::string::npos ) {
771         endPos = str.length();
772     }
774     if ( endPos != std::string::npos && endPos > 0 ) {
775         std::string xxx = str.substr( 0, endPos );
776         const gchar* ptr = xxx.c_str();
777         gchar* endPtr = 0;
778         numVal = g_ascii_strtoull( ptr, &endPtr, 10 );
779         if ( (numVal == G_MAXUINT64) && (ERANGE == errno) ) {
780             // overflow
781         } else if ( (numVal == 0) && (endPtr == ptr) ) {
782             // failed conversion
783         } else {
784             good = true;
785             str.erase( 0, endPos + 1 );
786         }
787     }
789     return good;
792 void ColorItem::_wireMagicColors( void* p )
794     JustForNow* onceMore = reinterpret_cast<JustForNow*>(p);
795     if ( onceMore )
796     {
797         for ( std::vector<ColorItem*>::iterator it = onceMore->_colors.begin(); it != onceMore->_colors.end(); ++it )
798         {
799             std::string::size_type pos = (*it)->def.descr.find("*{");
800             if ( pos != std::string::npos )
801             {
802                 std::string subby = (*it)->def.descr.substr( pos + 2 );
803                 std::string::size_type endPos = subby.find("}*");
804                 if ( endPos != std::string::npos )
805                 {
806                     subby.erase( endPos );
807                     //g_message("FOUND MAGIC at '%s'", (*it)->def.descr.c_str());
808                     //g_message("               '%s'", subby.c_str());
810                     if ( subby.find('E') != std::string::npos )
811                     {
812                         (*it)->def.setEditable( true );
813                     }
815                     if ( subby.find('L') != std::string::npos )
816                     {
817                         (*it)->_isLive = true;
818                     }
820                     std::string part;
821                     // Tint. index + 1 more val.
822                     if ( getBlock( part, 'T', subby ) ) {
823                         guint64 colorIndex = 0;
824                         if ( popVal( colorIndex, part ) ) {
825                             guint64 percent = 0;
826                             if ( popVal( percent, part ) ) {
827                                 (*it)->_linkTint( *(onceMore->_colors[colorIndex]), percent );
828                             }
829                         }
830                     }
832                     // Shade/tone. index + 1 or 2 more val.
833                     if ( getBlock( part, 'S', subby ) ) {
834                         guint64 colorIndex = 0;
835                         if ( popVal( colorIndex, part ) ) {
836                             guint64 percent = 0;
837                             if ( popVal( percent, part ) ) {
838                                 guint64 grayLevel = 0;
839                                 if ( !popVal( grayLevel, part ) ) {
840                                     grayLevel = 0;
841                                 }
842                                 (*it)->_linkTone( *(onceMore->_colors[colorIndex]), percent, grayLevel );
843                             }
844                         }
845                     }
847                 }
848             }
849         }
850     }
854 void ColorItem::_linkTint( ColorItem& other, int percent )
856     if ( !_linkSrc )
857     {
858         other._listeners.push_back(this);
859         _linkIsTone = false;
860         _linkPercent = percent;
861         if ( _linkPercent > 100 )
862             _linkPercent = 100;
863         if ( _linkPercent < 0 )
864             _linkPercent = 0;
865         _linkGray = 0;
866         _linkSrc = &other;
868         ColorItem::_colorDefChanged(&other);
869     }
872 void ColorItem::_linkTone( ColorItem& other, int percent, int grayLevel )
874     if ( !_linkSrc )
875     {
876         other._listeners.push_back(this);
877         _linkIsTone = true;
878         _linkPercent = percent;
879         if ( _linkPercent > 100 )
880             _linkPercent = 100;
881         if ( _linkPercent < 0 )
882             _linkPercent = 0;
883         _linkGray = grayLevel;
884         _linkSrc = &other;
886         ColorItem::_colorDefChanged(&other);
887     }
891 void _loadPaletteFile( gchar const *filename )
893     char block[1024];
894     FILE *f = Inkscape::IO::fopen_utf8name( filename, "r" );
895     if ( f ) {
896         char* result = fgets( block, sizeof(block), f );
897         if ( result ) {
898             if ( strncmp( "GIMP Palette", block, 12 ) == 0 ) {
899                 bool inHeader = true;
900                 bool hasErr = false;
902                 JustForNow *onceMore = new JustForNow();
904                 do {
905                     result = fgets( block, sizeof(block), f );
906                     block[sizeof(block) - 1] = 0;
907                     if ( result ) {
908                         if ( block[0] == '#' ) {
909                             // ignore comment
910                         } else {
911                             char *ptr = block;
912                             // very simple check for header versus entry
913                             while ( *ptr == ' ' || *ptr == '\t' ) {
914                                 ptr++;
915                             }
916                             if ( (*ptr == 0) || (*ptr == '\r') || (*ptr == '\n') ) {
917                                 // blank line. skip it.
918                             } else if ( '0' <= *ptr && *ptr <= '9' ) {
919                                 // should be an entry link
920                                 inHeader = false;
921                                 ptr = block;
922                                 Glib::ustring name("");
923                                 int r = 0;
924                                 int g = 0;
925                                 int b = 0;
926                                 skipWhitespace(ptr);
927                                 if ( *ptr ) {
928                                     hasErr = parseNum(ptr, r);
929                                     if ( !hasErr ) {
930                                         skipWhitespace(ptr);
931                                         hasErr = parseNum(ptr, g);
932                                     }
933                                     if ( !hasErr ) {
934                                         skipWhitespace(ptr);
935                                         hasErr = parseNum(ptr, b);
936                                     }
937                                     if ( !hasErr && *ptr ) {
938                                         char* n = trim(ptr);
939                                         if (n != NULL) {
940                                             name = n;
941                                         }
942                                     }
943                                     if ( !hasErr ) {
944                                         // Add the entry now
945                                         Glib::ustring nameStr(name);
946                                         ColorItem* item = new ColorItem( r, g, b, nameStr );
947                                         onceMore->_colors.push_back(item);
948                                     }
949                                 } else {
950                                     hasErr = true;
951                                 }
952                             } else {
953                                 if ( !inHeader ) {
954                                     // Hmmm... probably bad. Not quite the format we want?
955                                     hasErr = true;
956                                 } else {
957                                     char* sep = strchr(result, ':');
958                                     if ( sep ) {
959                                         *sep = 0;
960                                         char* val = trim(sep + 1);
961                                         char* name = trim(result);
962                                         if ( *name ) {
963                                             if ( strcmp( "Name", name ) == 0 )
964                                             {
965                                                 onceMore->_name = val;
966                                             }
967                                             else if ( strcmp( "Columns", name ) == 0 )
968                                             {
969                                                 gchar* endPtr = 0;
970                                                 guint64 numVal = g_ascii_strtoull( val, &endPtr, 10 );
971                                                 if ( (numVal == G_MAXUINT64) && (ERANGE == errno) ) {
972                                                     // overflow
973                                                 } else if ( (numVal == 0) && (endPtr == val) ) {
974                                                     // failed conversion
975                                                 } else {
976                                                     onceMore->_prefWidth = numVal;
977                                                 }
978                                             }
979                                         } else {
980                                             // error
981                                             hasErr = true;
982                                         }
983                                     } else {
984                                         // error
985                                         hasErr = true;
986                                     }
987                                 }
988                             }
989                         }
990                     }
991                 } while ( result && !hasErr );
992                 if ( !hasErr ) {
993                     possible.push_back(onceMore);
994 #if ENABLE_MAGIC_COLORS
995                     ColorItem::_wireMagicColors( onceMore );
996 #endif // ENABLE_MAGIC_COLORS
997                 } else {
998                     delete onceMore;
999                 }
1000             }
1001         }
1003         fclose(f);
1004     }
1007 static void loadEmUp()
1009     static bool beenHere = false;
1010     if ( !beenHere ) {
1011         beenHere = true;
1013         std::list<gchar *> sources;
1014         sources.push_back( profile_path("palettes") );
1015         sources.push_back( g_strdup(INKSCAPE_PALETTESDIR) );
1016         sources.push_back( g_strdup(CREATE_PALETTESDIR) );
1018         // Use this loop to iterate through a list of possible document locations.
1019         while (!sources.empty()) {
1020             gchar *dirname = sources.front();
1022             if ( Inkscape::IO::file_test( dirname, G_FILE_TEST_EXISTS )
1023                 && Inkscape::IO::file_test( dirname, G_FILE_TEST_IS_DIR )) {
1024                 GError *err = 0;
1025                 GDir *directory = g_dir_open(dirname, 0, &err);
1026                 if (!directory) {
1027                     gchar *safeDir = Inkscape::IO::sanitizeString(dirname);
1028                     g_warning(_("Palettes directory (%s) is unavailable."), safeDir);
1029                     g_free(safeDir);
1030                 } else {
1031                     gchar *filename = 0;
1032                     while ((filename = (gchar *)g_dir_read_name(directory)) != NULL) {
1033                         gchar* lower = g_ascii_strdown( filename, -1 );
1034 //                        if ( g_str_has_suffix(lower, ".gpl") ) {
1035                             gchar* full = g_build_filename(dirname, filename, NULL);
1036                             if ( !Inkscape::IO::file_test( full, G_FILE_TEST_IS_DIR ) ) {
1037                                 _loadPaletteFile(full);
1038                             }
1039                             g_free(full);
1040 //                      }
1041                         g_free(lower);
1042                     }
1043                     g_dir_close(directory);
1044                 }
1045             }
1047             // toss the dirname
1048             g_free(dirname);
1049             sources.pop_front();
1050         }
1051     }
1062 SwatchesPanel& SwatchesPanel::getInstance()
1064     return *new SwatchesPanel();
1068 /**
1069  * Constructor
1070  */
1071 SwatchesPanel::SwatchesPanel(gchar const* prefsPath) :
1072     Inkscape::UI::Widget::Panel("", prefsPath, SP_VERB_DIALOG_SWATCHES, "", true),
1073     _holder(0)
1075     Gtk::RadioMenuItem* hotItem = 0;
1076     _holder = new PreviewHolder();
1077     _remove = new ColorItem();
1078     loadEmUp();
1079     if ( !possible.empty() ) {
1080         JustForNow* first = 0;
1081         Glib::ustring targetName;
1082         if ( !_prefs_path.empty() ) {
1083             Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1084             targetName = prefs->getString(_prefs_path + "/palette");
1085             if (!targetName.empty()) {
1086                 for ( std::vector<JustForNow*>::iterator iter = possible.begin(); iter != possible.end(); ++iter ) {
1087                     if ( (*iter)->_name == targetName ) {
1088                         first = *iter;
1089                         break;
1090                     }
1091                 }
1092             }
1093         }
1095         if ( !first ) {
1096             first = possible.front();
1097         }
1099         if ( first->_prefWidth > 0 ) {
1100             _holder->setColumnPref( first->_prefWidth );
1101         }
1102         _holder->freezeUpdates();
1103         _holder->addPreview(_remove);
1104         for ( std::vector<ColorItem*>::iterator it = first->_colors.begin(); it != first->_colors.end(); it++ ) {
1105             _holder->addPreview(*it);
1106         }
1107         _holder->thawUpdates();
1109         Gtk::RadioMenuItem::Group groupOne;
1111         int i = 0;
1112         for ( std::vector<JustForNow*>::iterator it = possible.begin(); it != possible.end(); it++ ) {
1113             JustForNow* curr = *it;
1114             Gtk::RadioMenuItem* single = manage(new Gtk::RadioMenuItem(groupOne, curr->_name));
1115             if ( curr == first ) {
1116                 hotItem = single;
1117             }
1118             _regItem( single, 3, i );
1119             i++;
1120         }
1121     }
1124     _getContents()->pack_start(*_holder, Gtk::PACK_EXPAND_WIDGET);
1125     _setTargetFillable(_holder);
1127     show_all_children();
1129     restorePanelPrefs();
1130     if ( hotItem ) {
1131         hotItem->set_active();
1132     }
1135 SwatchesPanel::~SwatchesPanel()
1137     if (_remove) delete _remove;
1138     if (_holder) delete _holder;
1141 void SwatchesPanel::setOrientation( Gtk::AnchorType how )
1143     // Must call the parent class or bad things might happen
1144     Inkscape::UI::Widget::Panel::setOrientation( how );
1146     if ( _holder )
1147     {
1148         _holder->setOrientation( Gtk::ANCHOR_SOUTH );
1149     }
1152 void SwatchesPanel::_handleAction( int setId, int itemId )
1154     switch( setId ) {
1155         case 3:
1156         {
1157             if ( itemId >= 0 && itemId < static_cast<int>(possible.size()) ) {
1158                 _holder->clear();
1159                 JustForNow* curr = possible[itemId];
1161                 if ( !_prefs_path.empty() ) {
1162                     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1163                     prefs->setString(_prefs_path + "/palette", curr->_name);
1164                 }
1166                 if ( curr->_prefWidth > 0 ) {
1167                     _holder->setColumnPref( curr->_prefWidth );
1168                 }
1169                 _holder->freezeUpdates();
1170                 _holder->addPreview(_remove);
1171                 for ( std::vector<ColorItem*>::iterator it = curr->_colors.begin(); it != curr->_colors.end(); it++ ) {
1172                     _holder->addPreview(*it);
1173                 }
1174                 _holder->thawUpdates();
1175             }
1176         }
1177         break;
1178     }
1181 } //namespace Dialogs
1182 } //namespace UI
1183 } //namespace Inkscape
1186 /*
1187   Local Variables:
1188   mode:c++
1189   c-file-style:"stroustrup"
1190   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1191   indent-tabs-mode:nil
1192   fill-column:99
1193   End:
1194 */
1195 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :