Code

1a5ef85210a085192d3020346f4b833275261ad5
[inkscape.git] / src / ui / dialog / 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>
21 #include <glibmm/i18n.h>
22 #include <gdkmm/pixbuf.h>
24 #include "desktop.h"
25 #include "desktop-handles.h"
26 #include "desktop-style.h"
27 #include "document.h"
28 #include "extension/db.h"
29 #include "inkscape.h"
30 #include "inkscape.h"
31 #include "io/sys.h"
32 #include "message-context.h"
33 #include "path-prefix.h"
34 #include "preferences.h"
35 #include "sp-item.h"
36 #include "svg/svg-color.h"
37 #include "swatches.h"
38 #include "widgets/eek-preview.h"
40 namespace Inkscape {
41 namespace UI {
42 namespace Dialogs {
44 // create a None color swatch
45 ColorItem::ColorItem() :
46     def(),
47     _isLive(false),
48     _linkIsTone(false),
49     _linkPercent(0),
50     _linkGray(0),
51     _linkSrc(0)
52 {
53 }
55 ColorItem::ColorItem( unsigned int r, unsigned int g, unsigned int b, Glib::ustring& name ) :
56     def( r, g, b, name ),
57     _isLive(false),
58     _linkIsTone(false),
59     _linkPercent(0),
60     _linkGray(0),
61     _linkSrc(0)
62 {
63 }
65 ColorItem::~ColorItem()
66 {
67 }
69 ColorItem::ColorItem(ColorItem const &other) :
70     Inkscape::UI::Previewable()
71 {
72     if ( this != &other ) {
73         *this = other;
74     }
75 }
77 ColorItem &ColorItem::operator=(ColorItem const &other)
78 {
79     if ( this != &other ) {
80         def = other.def;
82         // TODO - correct linkage
83         _linkSrc = other._linkSrc;
84         g_message("Erk!");
85     }
86     return *this;
87 }
90 class JustForNow
91 {
92 public:
93     JustForNow() : _prefWidth(0) {}
95     Glib::ustring _name;
96     int _prefWidth;
97     std::vector<ColorItem*> _colors;
98 };
100 static std::vector<JustForNow*> possible;
104 typedef enum {
105     APP_X_INKY_COLOR_ID = 0,
106     APP_X_INKY_COLOR = 0,
107     APP_X_COLOR,
108     APP_X_NOCOLOR,
109     TEXT_DATA
110 } colorFlavorType;
112 //TODO: warning: deprecated conversion from string constant to ‘gchar*’
113 //
114 //Turn out to be warnings that we should probably leave in place. The
115 // pointers/types used need to be read-only. So until we correct the using
116 // code, those warnings are actually desired. They say "Hey! Fix this". We
117 // definitely don't want to hide/ignore them. --JonCruz
118 static const GtkTargetEntry sourceColorEntries[] = {
119 #if ENABLE_MAGIC_COLORS
120 //    {"application/x-inkscape-color-id", GTK_TARGET_SAME_APP, APP_X_INKY_COLOR_ID},
121     {"application/x-inkscape-color", 0, APP_X_INKY_COLOR},
122 #endif // ENABLE_MAGIC_COLORS
123     {"application/x-color", 0, APP_X_COLOR},
124     {"text/plain", 0, TEXT_DATA},
125 };
127 static const GtkTargetEntry sourceNoColorEntries[] = {
128     {"application/x-inkscape-nocolor", 0, APP_X_NOCOLOR},
129     {"application/x-color", 0, APP_X_COLOR},
130     {"text/plain", 0, TEXT_DATA},
131 };
133 void ColorItem::_dragGetColorData( GtkWidget */*widget*/,
134                                    GdkDragContext */*drag_context*/,
135                                    GtkSelectionData *data,
136                                    guint info,
137                                    guint /*time*/,
138                                    gpointer user_data)
140     static GdkAtom typeXColor = gdk_atom_intern("application/x-color", FALSE);
141     static GdkAtom typeText = gdk_atom_intern("text/plain", FALSE);
143     ColorItem* item = reinterpret_cast<ColorItem*>(user_data);
144     if ( info == TEXT_DATA ) {
145         gchar* tmp = g_strdup_printf("#%02x%02x%02x", item->def.getR(), item->def.getG(), item->def.getB() );
147         gtk_selection_data_set( data,
148                                 typeText,
149                                 8, // format
150                                 (guchar*)tmp,
151                                 strlen((const char*)tmp) + 1);
152         g_free(tmp);
153         tmp = 0;
154     } else if ( info == APP_X_INKY_COLOR ) {
155         Glib::ustring paletteName;
157         // Find where this thing came from
158         bool found = false;
159         int index = 0;
160         for ( std::vector<JustForNow*>::iterator it = possible.begin(); it != possible.end() && !found; ++it ) {
161             JustForNow* curr = *it;
162             index = 0;
163             for ( std::vector<ColorItem*>::iterator zz = curr->_colors.begin(); zz != curr->_colors.end(); ++zz ) {
164                 if ( item == *zz ) {
165                     found = true;
166                     paletteName = curr->_name;
167                     break;
168                 } else {
169                     index++;
170                 }
171             }
172         }
174 //         if ( found ) {
175 //             g_message("Found the color at entry %d in palette '%s'", index, paletteName.c_str() );
176 //         } else {
177 //             g_message("Unable to find the color");
178 //         }
179         int itemCount = 4 + 2 + 1 + paletteName.length();
181         guint16* tmp = new guint16[itemCount];
182         tmp[0] = (item->def.getR() << 8) | item->def.getR();
183         tmp[1] = (item->def.getG() << 8) | item->def.getG();
184         tmp[2] = (item->def.getB() << 8) | item->def.getB();
185         tmp[3] = 0xffff;
186         tmp[4] = (item->_isLive || !item->_listeners.empty() || (item->_linkSrc != 0) ) ? 1 : 0;
188         tmp[5] = index;
189         tmp[6] = paletteName.length();
190         for ( unsigned int i = 0; i < paletteName.length(); i++ ) {
191             tmp[7 + i] = paletteName[i];
192         }
193         gtk_selection_data_set( data,
194                                 typeXColor,
195                                 16, // format
196                                 reinterpret_cast<const guchar*>(tmp),
197                                 itemCount * 2);
198         delete[] tmp;
199     } else if ( info == APP_X_NOCOLOR ) {
200         Glib::ustring paletteName;
202         // Find where this thing came from
203         bool found = false;
204         int index = 0;
205         for ( std::vector<JustForNow*>::iterator it = possible.begin(); it != possible.end() && !found; ++it ) {
206             JustForNow* curr = *it;
207             index = 0;
208             for ( std::vector<ColorItem*>::iterator zz = curr->_colors.begin(); zz != curr->_colors.end(); ++zz ) {
209                 if ( item == *zz ) {
210                     found = true;
211                     paletteName = curr->_name;
212                     break;
213                 } else {
214                     index++;
215                 }
216             }
217         }
219 //         if ( found ) {
220 //             g_message("Found the color at entry %d in palette '%s'", index, paletteName.c_str() );
221 //         } else {
222 //             g_message("Unable to find the color");
223 //         }
224         int itemCount = 4 + 2 + 1 + paletteName.length();
226         guint16* tmp = new guint16[itemCount];
227         tmp[0] = (item->def.getR() << 8) | item->def.getR();
228         tmp[1] = (item->def.getG() << 8) | item->def.getG();
229         tmp[2] = (item->def.getB() << 8) | item->def.getB();
230         tmp[3] = 0xffff;
231         tmp[4] = (item->_isLive || !item->_listeners.empty() || (item->_linkSrc != 0) ) ? 1 : 0;
233         tmp[5] = index;
234         tmp[6] = paletteName.length();
235         for ( unsigned int i = 0; i < paletteName.length(); i++ ) {
236             tmp[7 + i] = paletteName[i];
237         }
238         gtk_selection_data_set( data,
239                                 typeXColor,
240                                 16, // format
241                                 reinterpret_cast<const guchar*>(tmp),
242                                 itemCount * 2);
243         delete[] tmp;
244     } else {
245         guint16 tmp[4];
246         tmp[0] = (item->def.getR() << 8) | item->def.getR();
247         tmp[1] = (item->def.getG() << 8) | item->def.getG();
248         tmp[2] = (item->def.getB() << 8) | item->def.getB();
249         tmp[3] = 0xffff;
250         gtk_selection_data_set( data,
251                                 typeXColor,
252                                 16, // format
253                                 reinterpret_cast<const guchar*>(tmp),
254                                 (3+1) * 2);
255     }
258 static void dragBegin( GtkWidget */*widget*/, GdkDragContext* dc, gpointer data )
260     ColorItem* item = reinterpret_cast<ColorItem*>(data);
261     if ( item )
262     {
263         if (item->def.getType() != eek::ColorDef::RGB){
264             GError *error = NULL;
265             gchar *filepath = (gchar *) g_strdup_printf("%s/remove-color.png", INKSCAPE_PIXMAPDIR);
266             gsize bytesRead = 0;
267             gsize bytesWritten = 0;
268             gchar *localFilename = g_filename_from_utf8( filepath,
269                                                  -1,
270                                                  &bytesRead,
271                                                  &bytesWritten,
272                                                  &error);
273             GdkPixbuf* pixbuf = gdk_pixbuf_new_from_file_at_scale(localFilename, 32, 24, FALSE, &error);
274             g_free(localFilename);
275             g_free(filepath);
276             gtk_drag_set_icon_pixbuf( dc, pixbuf, 0, 0 );
277             return;
278         }
280         Glib::RefPtr<Gdk::Pixbuf> thumb = Gdk::Pixbuf::create( Gdk::COLORSPACE_RGB, false, 8, 32, 24 );
281         guint32 fillWith = (0xff000000 & (item->def.getR() << 24))
282                          | (0x00ff0000 & (item->def.getG() << 16))
283                          | (0x0000ff00 & (item->def.getB() <<  8));
284         thumb->fill( fillWith );
285         gtk_drag_set_icon_pixbuf( dc, thumb->gobj(), 0, 0 );
286     }
290 //"drag-drop"
291 // gboolean dragDropColorData( GtkWidget *widget,
292 //                             GdkDragContext *drag_context,
293 //                             gint x,
294 //                             gint y,
295 //                             guint time,
296 //                             gpointer user_data)
297 // {
298 // // TODO finish
300 //     return TRUE;
301 // }
303 static void handleClick( GtkWidget* /*widget*/, gpointer callback_data ) {
304     ColorItem* item = reinterpret_cast<ColorItem*>(callback_data);
305     if ( item ) {
306         item->buttonClicked(false);
307     }
310 static void handleSecondaryClick( GtkWidget* /*widget*/, gint /*arg1*/, gpointer callback_data ) {
311     ColorItem* item = reinterpret_cast<ColorItem*>(callback_data);
312     if ( item ) {
313         item->buttonClicked(true);
314     }
317 static gboolean handleEnterNotify( GtkWidget* /*widget*/, GdkEventCrossing* /*event*/, gpointer callback_data ) {
318     ColorItem* item = reinterpret_cast<ColorItem*>(callback_data);
319     if ( item ) {
320         SPDesktop *desktop = SP_ACTIVE_DESKTOP;
321         if ( desktop ) {
322             gchar* msg = g_strdup_printf(_("Color: <b>%s</b>; <b>Click</b> to set fill, <b>Shift+click</b> to set stroke"),
323                                          item->def.descr.c_str());
324             desktop->tipsMessageContext()->set(Inkscape::INFORMATION_MESSAGE, msg);
325             g_free(msg);
326         }
327     }
328     return FALSE;
331 static gboolean handleLeaveNotify( GtkWidget* /*widget*/, GdkEventCrossing* /*event*/, gpointer callback_data ) {
332     ColorItem* item = reinterpret_cast<ColorItem*>(callback_data);
333     if ( item ) {
334         SPDesktop *desktop = SP_ACTIVE_DESKTOP;
335         if ( desktop ) {
336             desktop->tipsMessageContext()->clear();
337         }
338     }
339     return FALSE;
342 static GtkWidget* popupMenu = 0;
343 static ColorItem* bounceTarget = 0;
345 static void redirClick( GtkMenuItem *menuitem, gpointer /*user_data*/ )
347     if ( bounceTarget ) {
348         handleClick( GTK_WIDGET(menuitem), bounceTarget );
349     }
352 static void redirSecondaryClick( GtkMenuItem *menuitem, gpointer /*user_data*/ )
354     if ( bounceTarget ) {
355         handleSecondaryClick( GTK_WIDGET(menuitem), 0, bounceTarget );
356     }
359 static gboolean handleButtonPress( GtkWidget* /*widget*/, GdkEventButton* event, gpointer user_data)
361     gboolean handled = FALSE;
363     if ( (event->button == 3) && (event->type == GDK_BUTTON_PRESS) ) {
364         if ( !popupMenu ) {
365             popupMenu = gtk_menu_new();
366             GtkWidget* child = 0;
368             //TRANSLATORS: An item in context menu on a colour in the swatches
369             child = gtk_menu_item_new_with_label(_("Set fill"));
370             g_signal_connect( G_OBJECT(child),
371                               "activate",
372                               G_CALLBACK(redirClick),
373                               user_data);
374             gtk_menu_shell_append(GTK_MENU_SHELL(popupMenu), child);
376             //TRANSLATORS: An item in context menu on a colour in the swatches
377             child = gtk_menu_item_new_with_label(_("Set stroke"));
379             g_signal_connect( G_OBJECT(child),
380                               "activate",
381                               G_CALLBACK(redirSecondaryClick),
382                               user_data);
383             gtk_menu_shell_append(GTK_MENU_SHELL(popupMenu), child);
385             gtk_widget_show_all(popupMenu);
386         }
388         ColorItem* item = reinterpret_cast<ColorItem*>(user_data);
389         if ( item ) {
390             bounceTarget = item;
391             if ( popupMenu ) {
392                 gtk_menu_popup(GTK_MENU(popupMenu), NULL, NULL, NULL, NULL, event->button, event->time);
393                 handled = TRUE;
394             }
395         }
396     }
398     return handled;
401 static void dieDieDie( GtkObject *obj, gpointer user_data )
403     g_message("die die die %p  %p", obj, user_data );
406 //TODO: warning: deprecated conversion from string constant to ‘gchar*’
407 //
408 //Turn out to be warnings that we should probably leave in place. The
409 // pointers/types used need to be read-only. So until we correct the using
410 // code, those warnings are actually desired. They say "Hey! Fix this". We
411 // definitely don't want to hide/ignore them. --JonCruz
412 static const GtkTargetEntry destColorTargets[] = {
413 #if ENABLE_MAGIC_COLORS
414 //    {"application/x-inkscape-color-id", GTK_TARGET_SAME_APP, APP_X_INKY_COLOR_ID},
415     {"application/x-inkscape-color", 0, APP_X_INKY_COLOR},
416 #endif // ENABLE_MAGIC_COLORS
417     {"application/x-color", 0, APP_X_COLOR},
418 };
420 #include "color.h" // for SP_RGBA32_U_COMPOSE
422 void ColorItem::_dropDataIn( GtkWidget */*widget*/,
423                              GdkDragContext */*drag_context*/,
424                              gint /*x*/, gint /*y*/,
425                              GtkSelectionData *data,
426                              guint info,
427                              guint /*event_time*/,
428                              gpointer user_data)
430 //     g_message("    droppy droppy   %d", info);
431      switch (info) {
432          case APP_X_INKY_COLOR:
433          {
434              if ( data->length >= 8 ) {
435                  // Careful about endian issues.
436                  guint16* dataVals = (guint16*)data->data;
437                  if ( user_data ) {
438                      ColorItem* item = reinterpret_cast<ColorItem*>(user_data);
439                      if ( item->def.isEditable() ) {
440                          // Shove on in the new value
441                          item->def.setRGB( 0x0ff & (dataVals[0] >> 8), 0x0ff & (dataVals[1] >> 8), 0x0ff & (dataVals[2] >> 8) );
442                      }
443                  }
444              }
445              break;
446          }
447          case APP_X_NOCOLOR:
448          {
449 //              g_message("APP_X_NOCOLOR dropping through to x-color");
450          }
451          case APP_X_COLOR:
452          {
453              if ( data->length == 8 ) {
454                  // Careful about endian issues.
455                  guint16* dataVals = (guint16*)data->data;
456 //                  {
457 //                      gchar c[64] = {0};
458 //                      sp_svg_write_color( c, 64,
459 //                                          SP_RGBA32_U_COMPOSE(
460 //                                              0x0ff & (dataVals[0] >> 8),
461 //                                              0x0ff & (dataVals[1] >> 8),
462 //                                              0x0ff & (dataVals[2] >> 8),
463 //                                              0xff // can't have transparency in the color itself
464 //                                              //0x0ff & (data->data[3] >> 8),
465 //                                              ));
466 //                  }
467                  if ( user_data ) {
468                      ColorItem* item = reinterpret_cast<ColorItem*>(user_data);
469                      if ( item->def.isEditable() ) {
470                          // Shove on in the new value
471                          item->def.setRGB( 0x0ff & (dataVals[0] >> 8), 0x0ff & (dataVals[1] >> 8), 0x0ff & (dataVals[2] >> 8) );
472                      }
473                  }
474              }
475              break;
476          }
477          default:
478              g_message("unknown drop type");
479      }
483 static bool bruteForce( SPDocument* document, Inkscape::XML::Node* node, Glib::ustring const& match, int r, int g, int b )
485     bool changed = false;
487     if ( node ) {
488         gchar const * val = node->attribute("inkscape:x-fill-tag");
489         if ( val  && (match == val) ) {
490             SPObject *obj = document->getObjectByRepr( node );
492             gchar c[64] = {0};
493             sp_svg_write_color( c, sizeof(c), SP_RGBA32_U_COMPOSE( r, g, b, 0xff ) );
494             SPCSSAttr *css = sp_repr_css_attr_new();
495             sp_repr_css_set_property( css, "fill", c );
497             sp_desktop_apply_css_recursive( (SPItem*)obj, css, true );
498             ((SPItem*)obj)->updateRepr();
500             changed = true;
501         }
503         val = node->attribute("inkscape:x-stroke-tag");
504         if ( val  && (match == val) ) {
505             SPObject *obj = document->getObjectByRepr( node );
507             gchar c[64] = {0};
508             sp_svg_write_color( c, sizeof(c), SP_RGBA32_U_COMPOSE( r, g, b, 0xff ) );
509             SPCSSAttr *css = sp_repr_css_attr_new();
510             sp_repr_css_set_property( css, "stroke", c );
512             sp_desktop_apply_css_recursive( (SPItem*)obj, css, true );
513             ((SPItem*)obj)->updateRepr();
515             changed = true;
516         }
518         Inkscape::XML::Node* first = node->firstChild();
519         changed |= bruteForce( document, first, match, r, g, b );
521         changed |= bruteForce( document, node->next(), match, r, g, b );
522     }
524     return changed;
527 void ColorItem::_colorDefChanged(void* data)
529     ColorItem* item = reinterpret_cast<ColorItem*>(data);
530     if ( item ) {
531         for ( std::vector<Gtk::Widget*>::iterator it =  item->_previews.begin(); it != item->_previews.end(); ++it ) {
532             Gtk::Widget* widget = *it;
533             if ( IS_EEK_PREVIEW(widget->gobj()) ) {
534                 EekPreview * preview = EEK_PREVIEW(widget->gobj());
535                 eek_preview_set_color( preview,
536                                        (item->def.getR() << 8) | item->def.getR(),
537                                        (item->def.getG() << 8) | item->def.getG(),
538                                        (item->def.getB() << 8) | item->def.getB() );
540                 eek_preview_set_linked( preview, (LinkType)((item->_linkSrc ? PREVIEW_LINK_IN:0)
541                                                             | (item->_listeners.empty() ? 0:PREVIEW_LINK_OUT)
542                                                             | (item->_isLive ? PREVIEW_LINK_OTHER:0)) );
544                 widget->queue_draw();
545             }
546         }
548         for ( std::vector<ColorItem*>::iterator it = item->_listeners.begin(); it != item->_listeners.end(); ++it ) {
549             guint r = item->def.getR();
550             guint g = item->def.getG();
551             guint b = item->def.getB();
553             if ( (*it)->_linkIsTone ) {
554                 r = ( ((*it)->_linkPercent * (*it)->_linkGray) + ((100 - (*it)->_linkPercent) * r) ) / 100;
555                 g = ( ((*it)->_linkPercent * (*it)->_linkGray) + ((100 - (*it)->_linkPercent) * g) ) / 100;
556                 b = ( ((*it)->_linkPercent * (*it)->_linkGray) + ((100 - (*it)->_linkPercent) * b) ) / 100;
557             } else {
558                 r = ( ((*it)->_linkPercent * 255) + ((100 - (*it)->_linkPercent) * r) ) / 100;
559                 g = ( ((*it)->_linkPercent * 255) + ((100 - (*it)->_linkPercent) * g) ) / 100;
560                 b = ( ((*it)->_linkPercent * 255) + ((100 - (*it)->_linkPercent) * b) ) / 100;
561             }
563             (*it)->def.setRGB( r, g, b );
564         }
567         // Look for objects using this color
568         {
569             SPDesktop *desktop = SP_ACTIVE_DESKTOP;
570             if ( desktop ) {
571                 SPDocument* document = sp_desktop_document( desktop );
572                 Inkscape::XML::Node *rroot =  sp_document_repr_root( document );
573                 if ( rroot ) {
575                     // Find where this thing came from
576                     Glib::ustring paletteName;
577                     bool found = false;
578                     int index = 0;
579                     for ( std::vector<JustForNow*>::iterator it2 = possible.begin(); it2 != possible.end() && !found; ++it2 ) {
580                         JustForNow* curr = *it2;
581                         index = 0;
582                         for ( std::vector<ColorItem*>::iterator zz = curr->_colors.begin(); zz != curr->_colors.end(); ++zz ) {
583                             if ( item == *zz ) {
584                                 found = true;
585                                 paletteName = curr->_name;
586                                 break;
587                             } else {
588                                 index++;
589                             }
590                         }
591                     }
593                     if ( !paletteName.empty() ) {
594                         gchar* str = g_strdup_printf("%d|", index);
595                         paletteName.insert( 0, str );
596                         g_free(str);
597                         str = 0;
599                         if ( bruteForce( document, rroot, paletteName, item->def.getR(), item->def.getG(), item->def.getB() ) ) {
600                             sp_document_done( document , SP_VERB_DIALOG_SWATCHES,
601                                               _("Change color definition"));
602                         }
603                     }
604                 }
605             }
606         }
607     }
611 Gtk::Widget* ColorItem::getPreview(PreviewStyle style, ViewType view, ::PreviewSize size, guint ratio)
613     Gtk::Widget* widget = 0;
614     if ( style == PREVIEW_STYLE_BLURB) {
615         Gtk::Label *lbl = new Gtk::Label(def.descr);
616         lbl->set_alignment(Gtk::ALIGN_LEFT, Gtk::ALIGN_CENTER);
617         widget = lbl;
618     } else {
619 //         Glib::ustring blank("          ");
620 //         if ( size == Inkscape::ICON_SIZE_MENU || size == Inkscape::ICON_SIZE_DECORATION ) {
621 //             blank = " ";
622 //         }
624         GtkWidget* eekWidget = eek_preview_new();
625         EekPreview * preview = EEK_PREVIEW(eekWidget);
626         Gtk::Widget* newBlot = Glib::wrap(eekWidget);
628         eek_preview_set_color( preview, (def.getR() << 8) | def.getR(), (def.getG() << 8) | def.getG(), (def.getB() << 8) | def.getB());
629         if ( def.getType() != eek::ColorDef::RGB ) {
630             GError *error = NULL;
631             gchar *filepath = (gchar *) g_strdup_printf("%s/remove-color.png", INKSCAPE_PIXMAPDIR);
632             gsize bytesRead = 0;
633             gsize bytesWritten = 0;
634             gchar *localFilename = g_filename_from_utf8( filepath,
635                                                  -1,
636                                                  &bytesRead,
637                                                  &bytesWritten,
638                                                  &error);
639             GdkPixbuf* pixbuf = gdk_pixbuf_new_from_file(localFilename, &error);
640             if (!pixbuf) {
641                 g_warning("Null pixbuf for %p [%s]", localFilename, localFilename );
642             }
643             g_free(localFilename);
644             g_free(filepath);
646             eek_preview_set_pixbuf( preview, pixbuf );
647         }
649         eek_preview_set_details( preview, (::PreviewStyle)style, (::ViewType)view, (::PreviewSize)size, ratio );
650         eek_preview_set_linked( preview, (LinkType)((_linkSrc ? PREVIEW_LINK_IN:0)
651                                                     | (_listeners.empty() ? 0:PREVIEW_LINK_OUT)
652                                                     | (_isLive ? PREVIEW_LINK_OTHER:0)) );
654         def.addCallback( _colorDefChanged, this );
656         GValue val = {0, {{0}, {0}}};
657         g_value_init( &val, G_TYPE_BOOLEAN );
658         g_value_set_boolean( &val, FALSE );
659         g_object_set_property( G_OBJECT(preview), "focus-on-click", &val );
661 /*
662         Gtk::Button *btn = new Gtk::Button(blank);
663         Gdk::Color color;
664         color.set_rgb((_r << 8)|_r, (_g << 8)|_g, (_b << 8)|_b);
665         btn->modify_bg(Gtk::STATE_NORMAL, color);
666         btn->modify_bg(Gtk::STATE_ACTIVE, color);
667         btn->modify_bg(Gtk::STATE_PRELIGHT, color);
668         btn->modify_bg(Gtk::STATE_SELECTED, color);
670         Gtk::Widget* newBlot = btn;
671 */
673         tips.set_tip((*newBlot), def.descr);
675 /*
676         newBlot->signal_clicked().connect( sigc::mem_fun(*this, &ColorItem::buttonClicked) );
678         sigc::signal<void> type_signal_something;
679 */
681         g_signal_connect( G_OBJECT(newBlot->gobj()),
682                           "clicked",
683                           G_CALLBACK(handleClick),
684                           this);
686         g_signal_connect( G_OBJECT(newBlot->gobj()),
687                           "alt-clicked",
688                           G_CALLBACK(handleSecondaryClick),
689                           this);
691         g_signal_connect( G_OBJECT(newBlot->gobj()),
692                           "button-press-event",
693                           G_CALLBACK(handleButtonPress),
694                           this);
696         gtk_drag_source_set( GTK_WIDGET(newBlot->gobj()),
697                              GDK_BUTTON1_MASK,
698                              (def.getType() != eek::ColorDef::RGB) ? sourceNoColorEntries :
699                              sourceColorEntries,
700                              (def.getType() != eek::ColorDef::RGB) ? G_N_ELEMENTS(sourceNoColorEntries) :
701                              G_N_ELEMENTS(sourceColorEntries),
702                              GdkDragAction(GDK_ACTION_MOVE | GDK_ACTION_COPY) );
704         g_signal_connect( G_OBJECT(newBlot->gobj()),
705                           "drag-data-get",
706                           G_CALLBACK(ColorItem::_dragGetColorData),
707                           this);
709         g_signal_connect( G_OBJECT(newBlot->gobj()),
710                           "drag-begin",
711                           G_CALLBACK(dragBegin),
712                           this );
714         g_signal_connect( G_OBJECT(newBlot->gobj()),
715                           "enter-notify-event",
716                           G_CALLBACK(handleEnterNotify),
717                           this);
719         g_signal_connect( G_OBJECT(newBlot->gobj()),
720                           "leave-notify-event",
721                           G_CALLBACK(handleLeaveNotify),
722                           this);
724 //         g_signal_connect( G_OBJECT(newBlot->gobj()),
725 //                           "drag-drop",
726 //                           G_CALLBACK(dragDropColorData),
727 //                           this);
729         if ( def.isEditable() )
730         {
731             gtk_drag_dest_set( GTK_WIDGET(newBlot->gobj()),
732                                GTK_DEST_DEFAULT_ALL,
733                                destColorTargets,
734                                G_N_ELEMENTS(destColorTargets),
735                                GdkDragAction(GDK_ACTION_COPY | GDK_ACTION_MOVE) );
738             g_signal_connect( G_OBJECT(newBlot->gobj()),
739                               "drag-data-received",
740                               G_CALLBACK(_dropDataIn),
741                               this );
742         }
744         g_signal_connect( G_OBJECT(newBlot->gobj()),
745                           "destroy",
746                           G_CALLBACK(dieDieDie),
747                           this);
750         widget = newBlot;
751     }
753     _previews.push_back( widget );
755     return widget;
758 void ColorItem::buttonClicked(bool secondary)
760     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
761     if (desktop) {
762         char const * attrName = secondary ? "stroke" : "fill";
764         SPCSSAttr *css = sp_repr_css_attr_new();
765         Glib::ustring descr;
766         switch (def.getType()) {
767             case eek::ColorDef::CLEAR: {
768                 // TODO actually make this clear
769                 sp_repr_css_set_property( css, attrName, "none" );
770                 descr = secondary? _("Remove stroke color") : _("Remove fill color");
771                 break;
772             }
773             case eek::ColorDef::NONE: {
774                 sp_repr_css_set_property( css, attrName, "none" );
775                 descr = secondary? _("Set stroke color to none") : _("Set fill color to none");
776                 break;
777             }
778             case eek::ColorDef::RGB: {
779                 gchar c[64];
780                 guint32 rgba = (def.getR() << 24) | (def.getG() << 16) | (def.getB() << 8) | 0xff;
781                 sp_svg_write_color(c, sizeof(c), rgba);
783                 sp_repr_css_set_property( css, attrName, c );
784                 descr = secondary? _("Set stroke color from swatch") : _("Set fill color from swatch");
785                 break;
786             }
787         }
788         sp_desktop_set_style(desktop, css);
789         sp_repr_css_attr_unref(css);
791         sp_document_done( sp_desktop_document(desktop), SP_VERB_DIALOG_SWATCHES, descr.c_str() );
792     }
795 static char* trim( char* str ) {
796     char* ret = str;
797     while ( *str && (*str == ' ' || *str == '\t') ) {
798         str++;
799     }
800     ret = str;
801     while ( *str ) {
802         str++;
803     }
804     str--;
805     while ( str > ret && (( *str == ' ' || *str == '\t' ) || *str == '\r' || *str == '\n') ) {
806         *str-- = 0;
807     }
808     return ret;
811 void skipWhitespace( char*& str ) {
812     while ( *str == ' ' || *str == '\t' ) {
813         str++;
814     }
817 bool parseNum( char*& str, int& val ) {
818     val = 0;
819     while ( '0' <= *str && *str <= '9' ) {
820         val = val * 10 + (*str - '0');
821         str++;
822     }
823     bool retval = !(*str == 0 || *str == ' ' || *str == '\t' || *str == '\r' || *str == '\n');
824     return retval;
828 static bool getBlock( std::string& dst, guchar ch, std::string const str )
830     bool good = false;
831     std::string::size_type pos = str.find(ch);
832     if ( pos != std::string::npos )
833     {
834         std::string::size_type pos2 = str.find( '(', pos );
835         if ( pos2 != std::string::npos ) {
836             std::string::size_type endPos = str.find( ')', pos2 );
837             if ( endPos != std::string::npos ) {
838                 dst = str.substr( pos2 + 1, (endPos - pos2 - 1) );
839                 good = true;
840             }
841         }
842     }
843     return good;
846 static bool popVal( guint64& numVal, std::string& str )
848     bool good = false;
849     std::string::size_type endPos = str.find(',');
850     if ( endPos == std::string::npos ) {
851         endPos = str.length();
852     }
854     if ( endPos != std::string::npos && endPos > 0 ) {
855         std::string xxx = str.substr( 0, endPos );
856         const gchar* ptr = xxx.c_str();
857         gchar* endPtr = 0;
858         numVal = g_ascii_strtoull( ptr, &endPtr, 10 );
859         if ( (numVal == G_MAXUINT64) && (ERANGE == errno) ) {
860             // overflow
861         } else if ( (numVal == 0) && (endPtr == ptr) ) {
862             // failed conversion
863         } else {
864             good = true;
865             str.erase( 0, endPos + 1 );
866         }
867     }
869     return good;
872 void ColorItem::_wireMagicColors( void* p )
874     JustForNow* onceMore = reinterpret_cast<JustForNow*>(p);
875     if ( onceMore )
876     {
877         for ( std::vector<ColorItem*>::iterator it = onceMore->_colors.begin(); it != onceMore->_colors.end(); ++it )
878         {
879             std::string::size_type pos = (*it)->def.descr.find("*{");
880             if ( pos != std::string::npos )
881             {
882                 std::string subby = (*it)->def.descr.substr( pos + 2 );
883                 std::string::size_type endPos = subby.find("}*");
884                 if ( endPos != std::string::npos )
885                 {
886                     subby.erase( endPos );
887                     //g_message("FOUND MAGIC at '%s'", (*it)->def.descr.c_str());
888                     //g_message("               '%s'", subby.c_str());
890                     if ( subby.find('E') != std::string::npos )
891                     {
892                         (*it)->def.setEditable( true );
893                     }
895                     if ( subby.find('L') != std::string::npos )
896                     {
897                         (*it)->_isLive = true;
898                     }
900                     std::string part;
901                     // Tint. index + 1 more val.
902                     if ( getBlock( part, 'T', subby ) ) {
903                         guint64 colorIndex = 0;
904                         if ( popVal( colorIndex, part ) ) {
905                             guint64 percent = 0;
906                             if ( popVal( percent, part ) ) {
907                                 (*it)->_linkTint( *(onceMore->_colors[colorIndex]), percent );
908                             }
909                         }
910                     }
912                     // Shade/tone. index + 1 or 2 more val.
913                     if ( getBlock( part, 'S', subby ) ) {
914                         guint64 colorIndex = 0;
915                         if ( popVal( colorIndex, part ) ) {
916                             guint64 percent = 0;
917                             if ( popVal( percent, part ) ) {
918                                 guint64 grayLevel = 0;
919                                 if ( !popVal( grayLevel, part ) ) {
920                                     grayLevel = 0;
921                                 }
922                                 (*it)->_linkTone( *(onceMore->_colors[colorIndex]), percent, grayLevel );
923                             }
924                         }
925                     }
927                 }
928             }
929         }
930     }
934 void ColorItem::_linkTint( ColorItem& other, int percent )
936     if ( !_linkSrc )
937     {
938         other._listeners.push_back(this);
939         _linkIsTone = false;
940         _linkPercent = percent;
941         if ( _linkPercent > 100 )
942             _linkPercent = 100;
943         if ( _linkPercent < 0 )
944             _linkPercent = 0;
945         _linkGray = 0;
946         _linkSrc = &other;
948         ColorItem::_colorDefChanged(&other);
949     }
952 void ColorItem::_linkTone( ColorItem& other, int percent, int grayLevel )
954     if ( !_linkSrc )
955     {
956         other._listeners.push_back(this);
957         _linkIsTone = true;
958         _linkPercent = percent;
959         if ( _linkPercent > 100 )
960             _linkPercent = 100;
961         if ( _linkPercent < 0 )
962             _linkPercent = 0;
963         _linkGray = grayLevel;
964         _linkSrc = &other;
966         ColorItem::_colorDefChanged(&other);
967     }
971 void _loadPaletteFile( gchar const *filename )
973     char block[1024];
974     FILE *f = Inkscape::IO::fopen_utf8name( filename, "r" );
975     if ( f ) {
976         char* result = fgets( block, sizeof(block), f );
977         if ( result ) {
978             if ( strncmp( "GIMP Palette", block, 12 ) == 0 ) {
979                 bool inHeader = true;
980                 bool hasErr = false;
982                 JustForNow *onceMore = new JustForNow();
984                 do {
985                     result = fgets( block, sizeof(block), f );
986                     block[sizeof(block) - 1] = 0;
987                     if ( result ) {
988                         if ( block[0] == '#' ) {
989                             // ignore comment
990                         } else {
991                             char *ptr = block;
992                             // very simple check for header versus entry
993                             while ( *ptr == ' ' || *ptr == '\t' ) {
994                                 ptr++;
995                             }
996                             if ( (*ptr == 0) || (*ptr == '\r') || (*ptr == '\n') ) {
997                                 // blank line. skip it.
998                             } else if ( '0' <= *ptr && *ptr <= '9' ) {
999                                 // should be an entry link
1000                                 inHeader = false;
1001                                 ptr = block;
1002                                 Glib::ustring name("");
1003                                 int r = 0;
1004                                 int g = 0;
1005                                 int b = 0;
1006                                 skipWhitespace(ptr);
1007                                 if ( *ptr ) {
1008                                     hasErr = parseNum(ptr, r);
1009                                     if ( !hasErr ) {
1010                                         skipWhitespace(ptr);
1011                                         hasErr = parseNum(ptr, g);
1012                                     }
1013                                     if ( !hasErr ) {
1014                                         skipWhitespace(ptr);
1015                                         hasErr = parseNum(ptr, b);
1016                                     }
1017                                     if ( !hasErr && *ptr ) {
1018                                         char* n = trim(ptr);
1019                                         if (n != NULL) {
1020                                             name = n;
1021                                         }
1022                                     }
1023                                     if ( !hasErr ) {
1024                                         // Add the entry now
1025                                         Glib::ustring nameStr(name);
1026                                         ColorItem* item = new ColorItem( r, g, b, nameStr );
1027                                         onceMore->_colors.push_back(item);
1028                                     }
1029                                 } else {
1030                                     hasErr = true;
1031                                 }
1032                             } else {
1033                                 if ( !inHeader ) {
1034                                     // Hmmm... probably bad. Not quite the format we want?
1035                                     hasErr = true;
1036                                 } else {
1037                                     char* sep = strchr(result, ':');
1038                                     if ( sep ) {
1039                                         *sep = 0;
1040                                         char* val = trim(sep + 1);
1041                                         char* name = trim(result);
1042                                         if ( *name ) {
1043                                             if ( strcmp( "Name", name ) == 0 )
1044                                             {
1045                                                 onceMore->_name = val;
1046                                             }
1047                                             else if ( strcmp( "Columns", name ) == 0 )
1048                                             {
1049                                                 gchar* endPtr = 0;
1050                                                 guint64 numVal = g_ascii_strtoull( val, &endPtr, 10 );
1051                                                 if ( (numVal == G_MAXUINT64) && (ERANGE == errno) ) {
1052                                                     // overflow
1053                                                 } else if ( (numVal == 0) && (endPtr == val) ) {
1054                                                     // failed conversion
1055                                                 } else {
1056                                                     onceMore->_prefWidth = numVal;
1057                                                 }
1058                                             }
1059                                         } else {
1060                                             // error
1061                                             hasErr = true;
1062                                         }
1063                                     } else {
1064                                         // error
1065                                         hasErr = true;
1066                                     }
1067                                 }
1068                             }
1069                         }
1070                     }
1071                 } while ( result && !hasErr );
1072                 if ( !hasErr ) {
1073                     possible.push_back(onceMore);
1074 #if ENABLE_MAGIC_COLORS
1075                     ColorItem::_wireMagicColors( onceMore );
1076 #endif // ENABLE_MAGIC_COLORS
1077                 } else {
1078                     delete onceMore;
1079                 }
1080             }
1081         }
1083         fclose(f);
1084     }
1087 static void loadEmUp()
1089     static bool beenHere = false;
1090     if ( !beenHere ) {
1091         beenHere = true;
1093         std::list<gchar *> sources;
1094         sources.push_back( profile_path("palettes") );
1095         sources.push_back( g_strdup(INKSCAPE_PALETTESDIR) );
1096         sources.push_back( g_strdup(CREATE_PALETTESDIR) );
1098         // Use this loop to iterate through a list of possible document locations.
1099         while (!sources.empty()) {
1100             gchar *dirname = sources.front();
1102             if ( Inkscape::IO::file_test( dirname, G_FILE_TEST_EXISTS )
1103                 && Inkscape::IO::file_test( dirname, G_FILE_TEST_IS_DIR )) {
1104                 GError *err = 0;
1105                 GDir *directory = g_dir_open(dirname, 0, &err);
1106                 if (!directory) {
1107                     gchar *safeDir = Inkscape::IO::sanitizeString(dirname);
1108                     g_warning(_("Palettes directory (%s) is unavailable."), safeDir);
1109                     g_free(safeDir);
1110                 } else {
1111                     gchar *filename = 0;
1112                     while ((filename = (gchar *)g_dir_read_name(directory)) != NULL) {
1113                         gchar* lower = g_ascii_strdown( filename, -1 );
1114 //                        if ( g_str_has_suffix(lower, ".gpl") ) {
1115                             gchar* full = g_build_filename(dirname, filename, NULL);
1116                             if ( !Inkscape::IO::file_test( full, G_FILE_TEST_IS_DIR ) ) {
1117                                 _loadPaletteFile(full);
1118                             }
1119                             g_free(full);
1120 //                      }
1121                         g_free(lower);
1122                     }
1123                     g_dir_close(directory);
1124                 }
1125             }
1127             // toss the dirname
1128             g_free(dirname);
1129             sources.pop_front();
1130         }
1131     }
1142 SwatchesPanel& SwatchesPanel::getInstance()
1144     return *new SwatchesPanel();
1148 /**
1149  * Constructor
1150  */
1151 SwatchesPanel::SwatchesPanel(gchar const* prefsPath) :
1152     Inkscape::UI::Widget::Panel("", prefsPath, SP_VERB_DIALOG_SWATCHES, "", true),
1153     _holder(0)
1155     Gtk::RadioMenuItem* hotItem = 0;
1156     _holder = new PreviewHolder();
1157     _remove = new ColorItem();
1158     loadEmUp();
1159     if ( !possible.empty() ) {
1160         JustForNow* first = 0;
1161         Glib::ustring targetName;
1162         if ( !_prefs_path.empty() ) {
1163             Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1164             targetName = prefs->getString(_prefs_path + "/palette");
1165             if (!targetName.empty()) {
1166                 for ( std::vector<JustForNow*>::iterator iter = possible.begin(); iter != possible.end(); ++iter ) {
1167                     if ( (*iter)->_name == targetName ) {
1168                         first = *iter;
1169                         break;
1170                     }
1171                 }
1172             }
1173         }
1175         if ( !first ) {
1176             first = possible.front();
1177         }
1179         if ( first->_prefWidth > 0 ) {
1180             _holder->setColumnPref( first->_prefWidth );
1181         }
1182         _holder->freezeUpdates();
1183         _holder->addPreview(_remove);
1184         for ( std::vector<ColorItem*>::iterator it = first->_colors.begin(); it != first->_colors.end(); it++ ) {
1185             _holder->addPreview(*it);
1186         }
1187         _holder->thawUpdates();
1189         Gtk::RadioMenuItem::Group groupOne;
1191         int i = 0;
1192         for ( std::vector<JustForNow*>::iterator it = possible.begin(); it != possible.end(); it++ ) {
1193             JustForNow* curr = *it;
1194             Gtk::RadioMenuItem* single = manage(new Gtk::RadioMenuItem(groupOne, curr->_name));
1195             if ( curr == first ) {
1196                 hotItem = single;
1197             }
1198             _regItem( single, 3, i );
1199             i++;
1200         }
1201     }
1204     _getContents()->pack_start(*_holder, Gtk::PACK_EXPAND_WIDGET);
1205     _setTargetFillable(_holder);
1207     show_all_children();
1209     restorePanelPrefs();
1210     if ( hotItem ) {
1211         hotItem->set_active();
1212     }
1215 SwatchesPanel::~SwatchesPanel()
1217     if (_remove) delete _remove;
1218     if (_holder) delete _holder;
1221 void SwatchesPanel::setOrientation( Gtk::AnchorType how )
1223     // Must call the parent class or bad things might happen
1224     Inkscape::UI::Widget::Panel::setOrientation( how );
1226     if ( _holder )
1227     {
1228         _holder->setOrientation( Gtk::ANCHOR_SOUTH );
1229     }
1232 void SwatchesPanel::_handleAction( int setId, int itemId )
1234     switch( setId ) {
1235         case 3:
1236         {
1237             if ( itemId >= 0 && itemId < static_cast<int>(possible.size()) ) {
1238                 _holder->clear();
1239                 JustForNow* curr = possible[itemId];
1241                 if ( !_prefs_path.empty() ) {
1242                     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1243                     prefs->setString(_prefs_path + "/palette", curr->_name);
1244                 }
1246                 if ( curr->_prefWidth > 0 ) {
1247                     _holder->setColumnPref( curr->_prefWidth );
1248                 }
1249                 _holder->freezeUpdates();
1250                 _holder->addPreview(_remove);
1251                 for ( std::vector<ColorItem*>::iterator it = curr->_colors.begin(); it != curr->_colors.end(); it++ ) {
1252                     _holder->addPreview(*it);
1253                 }
1254                 _holder->thawUpdates();
1255             }
1256         }
1257         break;
1258     }
1261 } //namespace Dialogs
1262 } //namespace UI
1263 } //namespace Inkscape
1266 /*
1267   Local Variables:
1268   mode:c++
1269   c-file-style:"stroustrup"
1270   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1271   indent-tabs-mode:nil
1272   fill-column:99
1273   End:
1274 */
1275 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :