Code

Adding some no-color to drag-n-drop
[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 ColorItem::ColorItem() : _isRemove(true){};
45 ColorItem::ColorItem( unsigned int r, unsigned int g, unsigned int b, Glib::ustring& name ) :
46     def( r, g, b, name ),
47     _isRemove(false),
48     _isLive(false),
49     _linkIsTone(false),
50     _linkPercent(0),
51     _linkGray(0),
52     _linkSrc(0)
53 {
54 }
56 ColorItem::~ColorItem()
57 {
58 }
60 ColorItem::ColorItem(ColorItem const &other) :
61     Inkscape::UI::Previewable()
62 {
63     if ( this != &other ) {
64         *this = other;
65     }
66 }
68 ColorItem &ColorItem::operator=(ColorItem const &other)
69 {
70     if ( this != &other ) {
71         def = other.def;
73         // TODO - correct linkage
74         _linkSrc = other._linkSrc;
75         g_message("Erk!");
76     }
77     return *this;
78 }
81 class JustForNow
82 {
83 public:
84     JustForNow() : _prefWidth(0) {}
86     Glib::ustring _name;
87     int _prefWidth;
88     std::vector<ColorItem*> _colors;
89 };
91 static std::vector<JustForNow*> possible;
95 typedef enum {
96     APP_X_INKY_COLOR_ID = 0,
97     APP_X_INKY_COLOR = 0,
98     APP_X_COLOR,
99     APP_X_NOCOLOR,
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 static const GtkTargetEntry sourceNoColorEntries[] = {
119     {"application/x-inkscape-nocolor", 0, APP_X_NOCOLOR},
120     {"application/x-color", 0, APP_X_COLOR},
121     {"text/plain", 0, TEXT_DATA},
122 };
124 void ColorItem::_dragGetColorData( GtkWidget *widget,
125                                    GdkDragContext *drag_context,
126                                    GtkSelectionData *data,
127                                    guint info,
128                                    guint time,
129                                    gpointer user_data)
131     (void)widget;
132     (void)drag_context;
133     (void)time;
134     static GdkAtom typeXColor = gdk_atom_intern("application/x-color", FALSE);
135     static GdkAtom typeText = gdk_atom_intern("text/plain", FALSE);
137     ColorItem* item = reinterpret_cast<ColorItem*>(user_data);
138     if ( info == TEXT_DATA ) {
139         gchar* tmp = g_strdup_printf("#%02x%02x%02x", item->def.getR(), item->def.getG(), item->def.getB() );
141         gtk_selection_data_set( data,
142                                 typeText,
143                                 8, // format
144                                 (guchar*)tmp,
145                                 strlen((const char*)tmp) + 1);
146         g_free(tmp);
147         tmp = 0;
148     } else if ( info == APP_X_INKY_COLOR ) {
149         Glib::ustring paletteName;
151         // Find where this thing came from
152         bool found = false;
153         int index = 0;
154         for ( std::vector<JustForNow*>::iterator it = possible.begin(); it != possible.end() && !found; ++it ) {
155             JustForNow* curr = *it;
156             index = 0;
157             for ( std::vector<ColorItem*>::iterator zz = curr->_colors.begin(); zz != curr->_colors.end(); ++zz ) {
158                 if ( item == *zz ) {
159                     found = true;
160                     paletteName = curr->_name;
161                     break;
162                 } else {
163                     index++;
164                 }
165             }
166         }
168 //         if ( found ) {
169 //             g_message("Found the color at entry %d in palette '%s'", index, paletteName.c_str() );
170 //         } else {
171 //             g_message("Unable to find the color");
172 //         }
173         int itemCount = 4 + 2 + 1 + paletteName.length();
175         guint16* tmp = new guint16[itemCount];
176         tmp[0] = (item->def.getR() << 8) | item->def.getR();
177         tmp[1] = (item->def.getG() << 8) | item->def.getG();
178         tmp[2] = (item->def.getB() << 8) | item->def.getB();
179         tmp[3] = 0xffff;
180         tmp[4] = (item->_isLive || !item->_listeners.empty() || (item->_linkSrc != 0) ) ? 1 : 0;
182         tmp[5] = index;
183         tmp[6] = paletteName.length();
184         for ( unsigned int i = 0; i < paletteName.length(); i++ ) {
185             tmp[7 + i] = paletteName[i];
186         }
187         gtk_selection_data_set( data,
188                                 typeXColor,
189                                 16, // format
190                                 reinterpret_cast<const guchar*>(tmp),
191                                 itemCount * 2);
192         delete[] tmp;
193     } else if ( info == APP_X_NOCOLOR ) {
194         Glib::ustring paletteName;
196         // Find where this thing came from
197         bool found = false;
198         int index = 0;
199         for ( std::vector<JustForNow*>::iterator it = possible.begin(); it != possible.end() && !found; ++it ) {
200             JustForNow* curr = *it;
201             index = 0;
202             for ( std::vector<ColorItem*>::iterator zz = curr->_colors.begin(); zz != curr->_colors.end(); ++zz ) {
203                 if ( item == *zz ) {
204                     found = true;
205                     paletteName = curr->_name;
206                     break;
207                 } else {
208                     index++;
209                 }
210             }
211         }
213 //         if ( found ) {
214 //             g_message("Found the color at entry %d in palette '%s'", index, paletteName.c_str() );
215 //         } else {
216 //             g_message("Unable to find the color");
217 //         }
218         int itemCount = 4 + 2 + 1 + paletteName.length();
220         guint16* tmp = new guint16[itemCount];
221         tmp[0] = (item->def.getR() << 8) | item->def.getR();
222         tmp[1] = (item->def.getG() << 8) | item->def.getG();
223         tmp[2] = (item->def.getB() << 8) | item->def.getB();
224         tmp[3] = 0xffff;
225         tmp[4] = (item->_isLive || !item->_listeners.empty() || (item->_linkSrc != 0) ) ? 1 : 0;
227         tmp[5] = index;
228         tmp[6] = paletteName.length();
229         for ( unsigned int i = 0; i < paletteName.length(); i++ ) {
230             tmp[7 + i] = paletteName[i];
231         }
232         gtk_selection_data_set( data,
233                                 typeXColor,
234                                 16, // format
235                                 reinterpret_cast<const guchar*>(tmp),
236                                 itemCount * 2);
237         delete[] tmp;
238     } else {
239         guint16 tmp[4];
240         tmp[0] = (item->def.getR() << 8) | item->def.getR();
241         tmp[1] = (item->def.getG() << 8) | item->def.getG();
242         tmp[2] = (item->def.getB() << 8) | item->def.getB();
243         tmp[3] = 0xffff;
244         gtk_selection_data_set( data,
245                                 typeXColor,
246                                 16, // format
247                                 reinterpret_cast<const guchar*>(tmp),
248                                 (3+1) * 2);
249     }
252 static void dragBegin( GtkWidget *widget, GdkDragContext* dc, gpointer data )
254     (void)widget;
255     ColorItem* item = reinterpret_cast<ColorItem*>(data);
256     if ( item )
257     {
258         if (item->isRemove()){
259             GError *error = NULL;
260             gchar *filepath = (gchar *) g_strdup_printf("%s/remove-color.png", INKSCAPE_PIXMAPDIR);
261             gsize bytesRead = 0;
262             gsize bytesWritten = 0;
263             gchar *localFilename = g_filename_from_utf8( filepath,
264                                                  -1,
265                                                  &bytesRead,
266                                                  &bytesWritten,
267                                                  &error);
268             GdkPixbuf* pixbuf = gdk_pixbuf_new_from_file_at_scale(localFilename, 32, 24, FALSE, &error);
269             g_free(localFilename);
270             g_free(filepath);
271             gtk_drag_set_icon_pixbuf( dc, pixbuf, 0, 0 );
272             return;
273         }
275         Glib::RefPtr<Gdk::Pixbuf> thumb = Gdk::Pixbuf::create( Gdk::COLORSPACE_RGB, false, 8, 32, 24 );
276         guint32 fillWith = (0xff000000 & (item->def.getR() << 24))
277                          | (0x00ff0000 & (item->def.getG() << 16))
278                          | (0x0000ff00 & (item->def.getB() <<  8));
279         thumb->fill( fillWith );
280         gtk_drag_set_icon_pixbuf( dc, thumb->gobj(), 0, 0 );
281     }
285 //"drag-drop"
286 // gboolean dragDropColorData( GtkWidget *widget,
287 //                             GdkDragContext *drag_context,
288 //                             gint x,
289 //                             gint y,
290 //                             guint time,
291 //                             gpointer user_data)
292 // {
293 // // TODO finish
295 //     return TRUE;
296 // }
298 static void handleClick( GtkWidget* widget, gpointer callback_data ) {
299     (void)widget;
300     ColorItem* item = reinterpret_cast<ColorItem*>(callback_data);
301     if ( item ) {
302         item->buttonClicked(false);
303     }
306 static void handleSecondaryClick( GtkWidget* widget, gint arg1, gpointer callback_data ) {
307     (void)widget;
308     (void)arg1;
309     ColorItem* item = reinterpret_cast<ColorItem*>(callback_data);
310     if ( item ) {
311         item->buttonClicked(true);
312     }
315 static gboolean handleEnterNotify( GtkWidget* /*widget*/, GdkEventCrossing* /*event*/, gpointer callback_data ) {
316     ColorItem* item = reinterpret_cast<ColorItem*>(callback_data);
317     if ( item ) {
318         SPDesktop *desktop = SP_ACTIVE_DESKTOP;
319         if ( desktop ) {
320             gchar* msg = g_strdup_printf(_("Color: <b>%s</b>; <b>Click</b> to set fill, <b>Shift+click</b> to set stroke"),
321                                          item->def.descr.c_str());
322             desktop->tipsMessageContext()->set(Inkscape::INFORMATION_MESSAGE, msg);
323             g_free(msg);
324         }
325     }
326     return FALSE;
329 static gboolean handleLeaveNotify( GtkWidget* /*widget*/, GdkEventCrossing* /*event*/, gpointer callback_data ) {
330     ColorItem* item = reinterpret_cast<ColorItem*>(callback_data);
331     if ( item ) {
332         SPDesktop *desktop = SP_ACTIVE_DESKTOP;
333         if ( desktop ) {
334             desktop->tipsMessageContext()->clear();
335         }
336     }
337     return FALSE;
340 static GtkWidget* popupMenu = 0;
341 static ColorItem* bounceTarget = 0;
343 static void redirClick( GtkMenuItem *menuitem, gpointer user_data )
345     (void)user_data;
346     if ( bounceTarget ) {
347         handleClick( GTK_WIDGET(menuitem), bounceTarget );
348     }
351 static void redirSecondaryClick( GtkMenuItem *menuitem, gpointer user_data )
353     (void)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     (void)widget;
362     gboolean handled = FALSE;
364     if ( (event->button == 3) && (event->type == GDK_BUTTON_PRESS) ) {
365         if ( !popupMenu ) {
366             popupMenu = gtk_menu_new();
367             GtkWidget* child = 0;
369             //TRANSLATORS: An item in context menu on a colour in the swatches
370             child = gtk_menu_item_new_with_label(_("Set fill"));
371             g_signal_connect( G_OBJECT(child),
372                               "activate",
373                               G_CALLBACK(redirClick),
374                               user_data);
375             gtk_menu_shell_append(GTK_MENU_SHELL(popupMenu), child);
377             //TRANSLATORS: An item in context menu on a colour in the swatches
378             child = gtk_menu_item_new_with_label(_("Set stroke"));
380             g_signal_connect( G_OBJECT(child),
381                               "activate",
382                               G_CALLBACK(redirSecondaryClick),
383                               user_data);
384             gtk_menu_shell_append(GTK_MENU_SHELL(popupMenu), child);
386             gtk_widget_show_all(popupMenu);
387         }
389         ColorItem* item = reinterpret_cast<ColorItem*>(user_data);
390         if ( item ) {
391             bounceTarget = item;
392             if ( popupMenu ) {
393                 gtk_menu_popup(GTK_MENU(popupMenu), NULL, NULL, NULL, NULL, event->button, event->time);
394                 handled = TRUE;
395             }
396         }
397     }
399     return handled;
402 static void dieDieDie( GtkObject *obj, gpointer user_data )
404     g_message("die die die %p  %p", obj, user_data );
407 //TODO: warning: deprecated conversion from string constant to ‘gchar*’
408 //
409 //Turn out to be warnings that we should probably leave in place. The
410 // pointers/types used need to be read-only. So until we correct the using
411 // code, those warnings are actually desired. They say "Hey! Fix this". We
412 // definitely don't want to hide/ignore them. --JonCruz
413 static const GtkTargetEntry destColorTargets[] = {
414 #if ENABLE_MAGIC_COLORS
415 //    {"application/x-inkscape-color-id", GTK_TARGET_SAME_APP, APP_X_INKY_COLOR_ID},
416     {"application/x-inkscape-color", 0, APP_X_INKY_COLOR},
417 #endif // ENABLE_MAGIC_COLORS
418     {"application/x-color", 0, APP_X_COLOR},
419 };
421 #include "color.h" // for SP_RGBA32_U_COMPOSE
423 void ColorItem::_dropDataIn( GtkWidget *widget,
424                              GdkDragContext *drag_context,
425                              gint x, gint y,
426                              GtkSelectionData *data,
427                              guint info,
428                              guint event_time,
429                              gpointer user_data)
431     (void)widget;
432     (void)drag_context;
433     (void)x;
434     (void)y;
435     (void)event_time;
436 //     g_message("    droppy droppy   %d", info);
437      switch (info) {
438          case APP_X_INKY_COLOR:
439          {
440              if ( data->length >= 8 ) {
441                  // Careful about endian issues.
442                  guint16* dataVals = (guint16*)data->data;
443                  if ( user_data ) {
444                      ColorItem* item = reinterpret_cast<ColorItem*>(user_data);
445                      if ( item->def.isEditable() ) {
446                          // Shove on in the new value
447                          item->def.setRGB( 0x0ff & (dataVals[0] >> 8), 0x0ff & (dataVals[1] >> 8), 0x0ff & (dataVals[2] >> 8) );
448                      }
449                  }
450              }
451              break;
452          }
453          case APP_X_NOCOLOR:
454          {
455 //              g_message("APP_X_NOCOLOR dropping through to x-color");
456          }
457          case APP_X_COLOR:
458          {
459              if ( data->length == 8 ) {
460                  // Careful about endian issues.
461                  guint16* dataVals = (guint16*)data->data;
462 //                  {
463 //                      gchar c[64] = {0};
464 //                      sp_svg_write_color( c, 64,
465 //                                          SP_RGBA32_U_COMPOSE(
466 //                                              0x0ff & (dataVals[0] >> 8),
467 //                                              0x0ff & (dataVals[1] >> 8),
468 //                                              0x0ff & (dataVals[2] >> 8),
469 //                                              0xff // can't have transparency in the color itself
470 //                                              //0x0ff & (data->data[3] >> 8),
471 //                                              ));
472 //                  }
473                  if ( user_data ) {
474                      ColorItem* item = reinterpret_cast<ColorItem*>(user_data);
475                      if ( item->def.isEditable() ) {
476                          // Shove on in the new value
477                          item->def.setRGB( 0x0ff & (dataVals[0] >> 8), 0x0ff & (dataVals[1] >> 8), 0x0ff & (dataVals[2] >> 8) );
478                      }
479                  }
480              }
481              break;
482          }
483          default:
484              g_message("unknown drop type");
485      }
489 static bool bruteForce( SPDocument* document, Inkscape::XML::Node* node, Glib::ustring const& match, int r, int g, int b )
491     bool changed = false;
493     if ( node ) {
494         gchar const * val = node->attribute("inkscape:x-fill-tag");
495         if ( val  && (match == val) ) {
496             SPObject *obj = document->getObjectByRepr( node );
498             gchar c[64] = {0};
499             sp_svg_write_color( c, sizeof(c), SP_RGBA32_U_COMPOSE( r, g, b, 0xff ) );
500             SPCSSAttr *css = sp_repr_css_attr_new();
501             sp_repr_css_set_property( css, "fill", c );
503             sp_desktop_apply_css_recursive( (SPItem*)obj, css, true );
504             ((SPItem*)obj)->updateRepr();
506             changed = true;
507         }
509         val = node->attribute("inkscape:x-stroke-tag");
510         if ( val  && (match == val) ) {
511             SPObject *obj = document->getObjectByRepr( node );
513             gchar c[64] = {0};
514             sp_svg_write_color( c, sizeof(c), SP_RGBA32_U_COMPOSE( r, g, b, 0xff ) );
515             SPCSSAttr *css = sp_repr_css_attr_new();
516             sp_repr_css_set_property( css, "stroke", c );
518             sp_desktop_apply_css_recursive( (SPItem*)obj, css, true );
519             ((SPItem*)obj)->updateRepr();
521             changed = true;
522         }
524         Inkscape::XML::Node* first = node->firstChild();
525         changed |= bruteForce( document, first, match, r, g, b );
527         changed |= bruteForce( document, node->next(), match, r, g, b );
528     }
530     return changed;
533 void ColorItem::_colorDefChanged(void* data)
535     ColorItem* item = reinterpret_cast<ColorItem*>(data);
536     if ( item ) {
537         for ( std::vector<Gtk::Widget*>::iterator it =  item->_previews.begin(); it != item->_previews.end(); ++it ) {
538             Gtk::Widget* widget = *it;
539             if ( IS_EEK_PREVIEW(widget->gobj()) ) {
540                 EekPreview * preview = EEK_PREVIEW(widget->gobj());
541                 eek_preview_set_color( preview,
542                                        (item->def.getR() << 8) | item->def.getR(),
543                                        (item->def.getG() << 8) | item->def.getG(),
544                                        (item->def.getB() << 8) | item->def.getB() );
546                 eek_preview_set_linked( preview, (LinkType)((item->_linkSrc ? PREVIEW_LINK_IN:0)
547                                                             | (item->_listeners.empty() ? 0:PREVIEW_LINK_OUT)
548                                                             | (item->_isLive ? PREVIEW_LINK_OTHER:0)) );
550                 widget->queue_draw();
551             }
552         }
554         for ( std::vector<ColorItem*>::iterator it = item->_listeners.begin(); it != item->_listeners.end(); ++it ) {
555             guint r = item->def.getR();
556             guint g = item->def.getG();
557             guint b = item->def.getB();
559             if ( (*it)->_linkIsTone ) {
560                 r = ( ((*it)->_linkPercent * (*it)->_linkGray) + ((100 - (*it)->_linkPercent) * r) ) / 100;
561                 g = ( ((*it)->_linkPercent * (*it)->_linkGray) + ((100 - (*it)->_linkPercent) * g) ) / 100;
562                 b = ( ((*it)->_linkPercent * (*it)->_linkGray) + ((100 - (*it)->_linkPercent) * b) ) / 100;
563             } else {
564                 r = ( ((*it)->_linkPercent * 255) + ((100 - (*it)->_linkPercent) * r) ) / 100;
565                 g = ( ((*it)->_linkPercent * 255) + ((100 - (*it)->_linkPercent) * g) ) / 100;
566                 b = ( ((*it)->_linkPercent * 255) + ((100 - (*it)->_linkPercent) * b) ) / 100;
567             }
569             (*it)->def.setRGB( r, g, b );
570         }
573         // Look for objects using this color
574         {
575             SPDesktop *desktop = SP_ACTIVE_DESKTOP;
576             if ( desktop ) {
577                 SPDocument* document = sp_desktop_document( desktop );
578                 Inkscape::XML::Node *rroot =  sp_document_repr_root( document );
579                 if ( rroot ) {
581                     // Find where this thing came from
582                     Glib::ustring paletteName;
583                     bool found = false;
584                     int index = 0;
585                     for ( std::vector<JustForNow*>::iterator it2 = possible.begin(); it2 != possible.end() && !found; ++it2 ) {
586                         JustForNow* curr = *it2;
587                         index = 0;
588                         for ( std::vector<ColorItem*>::iterator zz = curr->_colors.begin(); zz != curr->_colors.end(); ++zz ) {
589                             if ( item == *zz ) {
590                                 found = true;
591                                 paletteName = curr->_name;
592                                 break;
593                             } else {
594                                 index++;
595                             }
596                         }
597                     }
599                     if ( !paletteName.empty() ) {
600                         gchar* str = g_strdup_printf("%d|", index);
601                         paletteName.insert( 0, str );
602                         g_free(str);
603                         str = 0;
605                         if ( bruteForce( document, rroot, paletteName, item->def.getR(), item->def.getG(), item->def.getB() ) ) {
606                             sp_document_done( document , SP_VERB_DIALOG_SWATCHES, 
607                                               _("Change color definition"));
608                         }
609                     }
610                 }
611             }
612         }
613     }
617 Gtk::Widget* ColorItem::getPreview(PreviewStyle style, ViewType view, ::PreviewSize size, guint ratio)
619     Gtk::Widget* widget = 0;
620     if ( style == PREVIEW_STYLE_BLURB) {
621         Gtk::Label *lbl = new Gtk::Label(def.descr);
622         lbl->set_alignment(Gtk::ALIGN_LEFT, Gtk::ALIGN_CENTER);
623         widget = lbl;
624     } else {
625 //         Glib::ustring blank("          ");
626 //         if ( size == Inkscape::ICON_SIZE_MENU || size == Inkscape::ICON_SIZE_DECORATION ) {
627 //             blank = " ";
628 //         }
630         GtkWidget* eekWidget = eek_preview_new();
631         EekPreview * preview = EEK_PREVIEW(eekWidget);
632         Gtk::Widget* newBlot = Glib::wrap(eekWidget);
634         eek_preview_set_color( preview, (def.getR() << 8) | def.getR(), (def.getG() << 8) | def.getG(), (def.getB() << 8) | def.getB());
635         if ( _isRemove ) {
636             GError *error = NULL;
637             gchar *filepath = (gchar *) g_strdup_printf("%s/remove-color.png", INKSCAPE_PIXMAPDIR);
638             gsize bytesRead = 0;
639             gsize bytesWritten = 0;
640             gchar *localFilename = g_filename_from_utf8( filepath,
641                                                  -1,
642                                                  &bytesRead,
643                                                  &bytesWritten,
644                                                  &error);
645             GdkPixbuf* pixbuf = gdk_pixbuf_new_from_file(localFilename, &error);
646             if (!pixbuf) {
647                 g_warning("Null pixbuf for %p [%s]", localFilename, localFilename );
648             }
649             g_free(localFilename);
650             g_free(filepath);
652             eek_preview_set_pixbuf( preview, pixbuf );
653         }
655         eek_preview_set_details( preview, (::PreviewStyle)style, (::ViewType)view, (::PreviewSize)size, ratio );
656         eek_preview_set_linked( preview, (LinkType)((_linkSrc ? PREVIEW_LINK_IN:0)
657                                                     | (_listeners.empty() ? 0:PREVIEW_LINK_OUT)
658                                                     | (_isLive ? PREVIEW_LINK_OTHER:0)) );
660         def.addCallback( _colorDefChanged, this );
662         GValue val = {0, {{0}, {0}}};
663         g_value_init( &val, G_TYPE_BOOLEAN );
664         g_value_set_boolean( &val, FALSE );
665         g_object_set_property( G_OBJECT(preview), "focus-on-click", &val );
667 /*
668         Gtk::Button *btn = new Gtk::Button(blank);
669         Gdk::Color color;
670         color.set_rgb((_r << 8)|_r, (_g << 8)|_g, (_b << 8)|_b);
671         btn->modify_bg(Gtk::STATE_NORMAL, color);
672         btn->modify_bg(Gtk::STATE_ACTIVE, color);
673         btn->modify_bg(Gtk::STATE_PRELIGHT, color);
674         btn->modify_bg(Gtk::STATE_SELECTED, color);
676         Gtk::Widget* newBlot = btn;
677 */
679         tips.set_tip((*newBlot), def.descr);
681 /*
682         newBlot->signal_clicked().connect( sigc::mem_fun(*this, &ColorItem::buttonClicked) );
684         sigc::signal<void> type_signal_something;
685 */
687         g_signal_connect( G_OBJECT(newBlot->gobj()),
688                           "clicked",
689                           G_CALLBACK(handleClick),
690                           this);
692         g_signal_connect( G_OBJECT(newBlot->gobj()),
693                           "alt-clicked",
694                           G_CALLBACK(handleSecondaryClick),
695                           this);
697         g_signal_connect( G_OBJECT(newBlot->gobj()),
698                           "button-press-event",
699                           G_CALLBACK(handleButtonPress),
700                           this);
702         if ( isRemove() ) {
703             gtk_drag_source_set( GTK_WIDGET(newBlot->gobj()),
704                                  GDK_BUTTON1_MASK,
705                                  sourceNoColorEntries,
706                                  G_N_ELEMENTS(sourceNoColorEntries),
707                                  GdkDragAction(GDK_ACTION_MOVE | GDK_ACTION_COPY) );
708         } else {
709             gtk_drag_source_set( GTK_WIDGET(newBlot->gobj()),
710                                  GDK_BUTTON1_MASK,
711                                  sourceColorEntries,
712                                  G_N_ELEMENTS(sourceColorEntries),
713                                  GdkDragAction(GDK_ACTION_MOVE | GDK_ACTION_COPY) );
714         }
716         g_signal_connect( G_OBJECT(newBlot->gobj()),
717                           "drag-data-get",
718                           G_CALLBACK(ColorItem::_dragGetColorData),
719                           this);
721         g_signal_connect( G_OBJECT(newBlot->gobj()),
722                           "drag-begin",
723                           G_CALLBACK(dragBegin),
724                           this );
726         g_signal_connect( G_OBJECT(newBlot->gobj()),
727                           "enter-notify-event",
728                           G_CALLBACK(handleEnterNotify),
729                           this);
731         g_signal_connect( G_OBJECT(newBlot->gobj()),
732                           "leave-notify-event",
733                           G_CALLBACK(handleLeaveNotify),
734                           this);
736 //         g_signal_connect( G_OBJECT(newBlot->gobj()),
737 //                           "drag-drop",
738 //                           G_CALLBACK(dragDropColorData),
739 //                           this);
741         if ( def.isEditable() )
742         {
743             gtk_drag_dest_set( GTK_WIDGET(newBlot->gobj()),
744                                GTK_DEST_DEFAULT_ALL,
745                                destColorTargets,
746                                G_N_ELEMENTS(destColorTargets),
747                                GdkDragAction(GDK_ACTION_COPY | GDK_ACTION_MOVE) );
750             g_signal_connect( G_OBJECT(newBlot->gobj()),
751                               "drag-data-received",
752                               G_CALLBACK(_dropDataIn),
753                               this );
754         }
756         g_signal_connect( G_OBJECT(newBlot->gobj()),
757                           "destroy",
758                           G_CALLBACK(dieDieDie),
759                           this);
762         widget = newBlot;
763     }
765     _previews.push_back( widget );
767     return widget;
770 void ColorItem::buttonClicked(bool secondary)
772     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
773     if (!desktop) return;
774     char const * attrName = secondary ? "stroke" : "fill";
776     gchar c[64];
777     if (!_isRemove){
778         guint32 rgba = (def.getR() << 24) | (def.getG() << 16) | (def.getB() << 8) | 0xff;
779         sp_svg_write_color(c, sizeof(c), rgba);
780     }
782     SPCSSAttr *css = sp_repr_css_attr_new();
783     sp_repr_css_set_property( css, attrName, _isRemove ? "none" : c );
784     sp_desktop_set_style(desktop, css);
785     sp_repr_css_attr_unref(css);
787     if (_isRemove){
788         sp_document_done (sp_desktop_document (desktop), SP_VERB_DIALOG_SWATCHES, 
789                       secondary? _("Remove stroke color") : _("Remove fill color"));
790     } else {
791         sp_document_done (sp_desktop_document (desktop), SP_VERB_DIALOG_SWATCHES, 
792                       secondary? _("Set stroke color from swatch") : _("Set fill color from swatch"));
793     }
796 static char* trim( char* str ) {
797     char* ret = str;
798     while ( *str && (*str == ' ' || *str == '\t') ) {
799         str++;
800     }
801     ret = str;
802     while ( *str ) {
803         str++;
804     }
805     str--;
806     while ( str > ret && (( *str == ' ' || *str == '\t' ) || *str == '\r' || *str == '\n') ) {
807         *str-- = 0;
808     }
809     return ret;
812 void skipWhitespace( char*& str ) {
813     while ( *str == ' ' || *str == '\t' ) {
814         str++;
815     }
818 bool parseNum( char*& str, int& val ) {
819     val = 0;
820     while ( '0' <= *str && *str <= '9' ) {
821         val = val * 10 + (*str - '0');
822         str++;
823     }
824     bool retval = !(*str == 0 || *str == ' ' || *str == '\t' || *str == '\r' || *str == '\n');
825     return retval;
829 static bool getBlock( std::string& dst, guchar ch, std::string const str )
831     bool good = false;
832     std::string::size_type pos = str.find(ch);
833     if ( pos != std::string::npos )
834     {
835         std::string::size_type pos2 = str.find( '(', pos );
836         if ( pos2 != std::string::npos ) {
837             std::string::size_type endPos = str.find( ')', pos2 );
838             if ( endPos != std::string::npos ) {
839                 dst = str.substr( pos2 + 1, (endPos - pos2 - 1) );
840                 good = true;
841             }
842         }
843     }
844     return good;
847 static bool popVal( guint64& numVal, std::string& str )
849     bool good = false;
850     std::string::size_type endPos = str.find(',');
851     if ( endPos == std::string::npos ) {
852         endPos = str.length();
853     }
855     if ( endPos != std::string::npos && endPos > 0 ) {
856         std::string xxx = str.substr( 0, endPos );
857         const gchar* ptr = xxx.c_str();
858         gchar* endPtr = 0;
859         numVal = g_ascii_strtoull( ptr, &endPtr, 10 );
860         if ( (numVal == G_MAXUINT64) && (ERANGE == errno) ) {
861             // overflow
862         } else if ( (numVal == 0) && (endPtr == ptr) ) {
863             // failed conversion
864         } else {
865             good = true;
866             str.erase( 0, endPos + 1 );
867         }
868     }
870     return good;
873 void ColorItem::_wireMagicColors( void* p )
875     JustForNow* onceMore = reinterpret_cast<JustForNow*>(p);
876     if ( onceMore )
877     {
878         for ( std::vector<ColorItem*>::iterator it = onceMore->_colors.begin(); it != onceMore->_colors.end(); ++it )
879         {
880             std::string::size_type pos = (*it)->def.descr.find("*{");
881             if ( pos != std::string::npos )
882             {
883                 std::string subby = (*it)->def.descr.substr( pos + 2 );
884                 std::string::size_type endPos = subby.find("}*");
885                 if ( endPos != std::string::npos )
886                 {
887                     subby.erase( endPos );
888                     //g_message("FOUND MAGIC at '%s'", (*it)->def.descr.c_str());
889                     //g_message("               '%s'", subby.c_str());
891                     if ( subby.find('E') != std::string::npos )
892                     {
893                         (*it)->def.setEditable( true );
894                     }
896                     if ( subby.find('L') != std::string::npos )
897                     {
898                         (*it)->_isLive = true;
899                     }
901                     std::string part;
902                     // Tint. index + 1 more val.
903                     if ( getBlock( part, 'T', subby ) ) {
904                         guint64 colorIndex = 0;
905                         if ( popVal( colorIndex, part ) ) {
906                             guint64 percent = 0;
907                             if ( popVal( percent, part ) ) {
908                                 (*it)->_linkTint( *(onceMore->_colors[colorIndex]), percent );
909                             }
910                         }
911                     }
913                     // Shade/tone. index + 1 or 2 more val.
914                     if ( getBlock( part, 'S', subby ) ) {
915                         guint64 colorIndex = 0;
916                         if ( popVal( colorIndex, part ) ) {
917                             guint64 percent = 0;
918                             if ( popVal( percent, part ) ) {
919                                 guint64 grayLevel = 0;
920                                 if ( !popVal( grayLevel, part ) ) {
921                                     grayLevel = 0;
922                                 }
923                                 (*it)->_linkTone( *(onceMore->_colors[colorIndex]), percent, grayLevel );
924                             }
925                         }
926                     }
928                 }
929             }
930         }
931     }
935 void ColorItem::_linkTint( ColorItem& other, int percent )
937     if ( !_linkSrc )
938     {
939         other._listeners.push_back(this);
940         _linkIsTone = false;
941         _linkPercent = percent;
942         if ( _linkPercent > 100 )
943             _linkPercent = 100;
944         if ( _linkPercent < 0 )
945             _linkPercent = 0;
946         _linkGray = 0;
947         _linkSrc = &other;
949         ColorItem::_colorDefChanged(&other);
950     }
953 void ColorItem::_linkTone( ColorItem& other, int percent, int grayLevel )
955     if ( !_linkSrc )
956     {
957         other._listeners.push_back(this);
958         _linkIsTone = true;
959         _linkPercent = percent;
960         if ( _linkPercent > 100 )
961             _linkPercent = 100;
962         if ( _linkPercent < 0 )
963             _linkPercent = 0;
964         _linkGray = grayLevel;
965         _linkSrc = &other;
967         ColorItem::_colorDefChanged(&other);
968     }
972 void _loadPaletteFile( gchar const *filename )
974     char block[1024];
975     FILE *f = Inkscape::IO::fopen_utf8name( filename, "r" );
976     if ( f ) {
977         char* result = fgets( block, sizeof(block), f );
978         if ( result ) {
979             if ( strncmp( "GIMP Palette", block, 12 ) == 0 ) {
980                 bool inHeader = true;
981                 bool hasErr = false;
983                 JustForNow *onceMore = new JustForNow();
985                 do {
986                     result = fgets( block, sizeof(block), f );
987                     block[sizeof(block) - 1] = 0;
988                     if ( result ) {
989                         if ( block[0] == '#' ) {
990                             // ignore comment
991                         } else {
992                             char *ptr = block;
993                             // very simple check for header versus entry
994                             while ( *ptr == ' ' || *ptr == '\t' ) {
995                                 ptr++;
996                             }
997                             if ( (*ptr == 0) || (*ptr == '\r') || (*ptr == '\n') ) {
998                                 // blank line. skip it.
999                             } else if ( '0' <= *ptr && *ptr <= '9' ) {
1000                                 // should be an entry link
1001                                 inHeader = false;
1002                                 ptr = block;
1003                                 Glib::ustring name("");
1004                                 int r = 0;
1005                                 int g = 0;
1006                                 int b = 0;
1007                                 skipWhitespace(ptr);
1008                                 if ( *ptr ) {
1009                                     hasErr = parseNum(ptr, r);
1010                                     if ( !hasErr ) {
1011                                         skipWhitespace(ptr);
1012                                         hasErr = parseNum(ptr, g);
1013                                     }
1014                                     if ( !hasErr ) {
1015                                         skipWhitespace(ptr);
1016                                         hasErr = parseNum(ptr, b);
1017                                     }
1018                                     if ( !hasErr && *ptr ) {
1019                                         char* n = trim(ptr);
1020                                         if (n != NULL) {
1021                                             name = n;
1022                                         }
1023                                     }
1024                                     if ( !hasErr ) {
1025                                         // Add the entry now
1026                                         Glib::ustring nameStr(name);
1027                                         ColorItem* item = new ColorItem( r, g, b, nameStr );
1028                                         onceMore->_colors.push_back(item);
1029                                     }
1030                                 } else {
1031                                     hasErr = true;
1032                                 }
1033                             } else {
1034                                 if ( !inHeader ) {
1035                                     // Hmmm... probably bad. Not quite the format we want?
1036                                     hasErr = true;
1037                                 } else {
1038                                     char* sep = strchr(result, ':');
1039                                     if ( sep ) {
1040                                         *sep = 0;
1041                                         char* val = trim(sep + 1);
1042                                         char* name = trim(result);
1043                                         if ( *name ) {
1044                                             if ( strcmp( "Name", name ) == 0 )
1045                                             {
1046                                                 onceMore->_name = val;
1047                                             }
1048                                             else if ( strcmp( "Columns", name ) == 0 )
1049                                             {
1050                                                 gchar* endPtr = 0;
1051                                                 guint64 numVal = g_ascii_strtoull( val, &endPtr, 10 );
1052                                                 if ( (numVal == G_MAXUINT64) && (ERANGE == errno) ) {
1053                                                     // overflow
1054                                                 } else if ( (numVal == 0) && (endPtr == val) ) {
1055                                                     // failed conversion
1056                                                 } else {
1057                                                     onceMore->_prefWidth = numVal;
1058                                                 }
1059                                             }
1060                                         } else {
1061                                             // error
1062                                             hasErr = true;
1063                                         }
1064                                     } else {
1065                                         // error
1066                                         hasErr = true;
1067                                     }
1068                                 }
1069                             }
1070                         }
1071                     }
1072                 } while ( result && !hasErr );
1073                 if ( !hasErr ) {
1074                     possible.push_back(onceMore);
1075 #if ENABLE_MAGIC_COLORS
1076                     ColorItem::_wireMagicColors( onceMore );
1077 #endif // ENABLE_MAGIC_COLORS
1078                 } else {
1079                     delete onceMore;
1080                 }
1081             }
1082         }
1084         fclose(f);
1085     }
1088 static void loadEmUp()
1090     static bool beenHere = false;
1091     if ( !beenHere ) {
1092         beenHere = true;
1094         std::list<gchar *> sources;
1095         sources.push_back( profile_path("palettes") );
1096         sources.push_back( g_strdup(INKSCAPE_PALETTESDIR) );
1097         sources.push_back( g_strdup(CREATE_PALETTESDIR) );
1099         // Use this loop to iterate through a list of possible document locations.
1100         while (!sources.empty()) {
1101             gchar *dirname = sources.front();
1103             if ( Inkscape::IO::file_test( dirname, G_FILE_TEST_EXISTS )
1104                 && Inkscape::IO::file_test( dirname, G_FILE_TEST_IS_DIR )) {
1105                 GError *err = 0;
1106                 GDir *directory = g_dir_open(dirname, 0, &err);
1107                 if (!directory) {
1108                     gchar *safeDir = Inkscape::IO::sanitizeString(dirname);
1109                     g_warning(_("Palettes directory (%s) is unavailable."), safeDir);
1110                     g_free(safeDir);
1111                 } else {
1112                     gchar *filename = 0;
1113                     while ((filename = (gchar *)g_dir_read_name(directory)) != NULL) {
1114                         gchar* lower = g_ascii_strdown( filename, -1 );
1115 //                        if ( g_str_has_suffix(lower, ".gpl") ) {
1116                             gchar* full = g_build_filename(dirname, filename, NULL);
1117                             if ( !Inkscape::IO::file_test( full, G_FILE_TEST_IS_DIR ) ) {
1118                                 _loadPaletteFile(full);
1119                             }
1120                             g_free(full);
1121 //                      }
1122                         g_free(lower);
1123                     }
1124                     g_dir_close(directory);
1125                 }
1126             }
1128             // toss the dirname
1129             g_free(dirname);
1130             sources.pop_front();
1131         }
1132     }
1143 SwatchesPanel& SwatchesPanel::getInstance()
1145     return *new SwatchesPanel();
1149 /**
1150  * Constructor
1151  */
1152 SwatchesPanel::SwatchesPanel(gchar const* prefsPath) :
1153     Inkscape::UI::Widget::Panel("", prefsPath, SP_VERB_DIALOG_SWATCHES, "", true),
1154     _holder(0)
1156     Gtk::RadioMenuItem* hotItem = 0;
1157     _holder = new PreviewHolder();
1158     _remove = new ColorItem();
1159     loadEmUp();
1160     if ( !possible.empty() ) {
1161         JustForNow* first = 0;
1162         Glib::ustring targetName;
1163         if ( !_prefs_path.empty() ) {
1164             Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1165             targetName = prefs->getString(_prefs_path + "/palette");
1166             if (!targetName.empty()) {
1167                 for ( std::vector<JustForNow*>::iterator iter = possible.begin(); iter != possible.end(); ++iter ) {
1168                     if ( (*iter)->_name == targetName ) {
1169                         first = *iter;
1170                         break;
1171                     }
1172                 }
1173             }
1174         }
1176         if ( !first ) {
1177             first = possible.front();
1178         }
1180         if ( first->_prefWidth > 0 ) {
1181             _holder->setColumnPref( first->_prefWidth );
1182         }
1183         _holder->freezeUpdates();
1184         _holder->addPreview(_remove);
1185         for ( std::vector<ColorItem*>::iterator it = first->_colors.begin(); it != first->_colors.end(); it++ ) {
1186             _holder->addPreview(*it);
1187         }
1188         _holder->thawUpdates();
1190         Gtk::RadioMenuItem::Group groupOne;
1192         int i = 0;
1193         for ( std::vector<JustForNow*>::iterator it = possible.begin(); it != possible.end(); it++ ) {
1194             JustForNow* curr = *it;
1195             Gtk::RadioMenuItem* single = manage(new Gtk::RadioMenuItem(groupOne, curr->_name));
1196             if ( curr == first ) {
1197                 hotItem = single;
1198             }
1199             _regItem( single, 3, i );
1200             i++;
1201         }
1202     }
1205     _getContents()->pack_start(*_holder, Gtk::PACK_EXPAND_WIDGET);
1206     _setTargetFillable(_holder);
1208     show_all_children();
1210     restorePanelPrefs();
1211     if ( hotItem ) {
1212         hotItem->set_active();
1213     }
1216 SwatchesPanel::~SwatchesPanel()
1218     if (_remove) delete _remove;
1219     if (_holder) delete _holder;
1222 void SwatchesPanel::setOrientation( Gtk::AnchorType how )
1224     // Must call the parent class or bad things might happen
1225     Inkscape::UI::Widget::Panel::setOrientation( how );
1227     if ( _holder )
1228     {
1229         _holder->setOrientation( Gtk::ANCHOR_SOUTH );
1230     }
1233 void SwatchesPanel::_handleAction( int setId, int itemId )
1235     switch( setId ) {
1236         case 3:
1237         {
1238             if ( itemId >= 0 && itemId < static_cast<int>(possible.size()) ) {
1239                 _holder->clear();
1240                 JustForNow* curr = possible[itemId];
1242                 if ( !_prefs_path.empty() ) {
1243                     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1244                     prefs->setString(_prefs_path + "/palette", curr->_name);
1245                 }
1247                 if ( curr->_prefWidth > 0 ) {
1248                     _holder->setColumnPref( curr->_prefWidth );
1249                 }
1250                 _holder->freezeUpdates();
1251                 _holder->addPreview(_remove);
1252                 for ( std::vector<ColorItem*>::iterator it = curr->_colors.begin(); it != curr->_colors.end(); it++ ) {
1253                     _holder->addPreview(*it);
1254                 }
1255                 _holder->thawUpdates();
1256             }
1257         }
1258         break;
1259     }
1262 } //namespace Dialogs
1263 } //namespace UI
1264 } //namespace Inkscape
1267 /*
1268   Local Variables:
1269   mode:c++
1270   c-file-style:"stroustrup"
1271   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1272   indent-tabs-mode:nil
1273   fill-column:99
1274   End:
1275 */
1276 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :