Code

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