Code

merge inline patch from Jimmy
[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 "prefs-utils.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             desktop->tipsMessageContext()->set(Inkscape::INFORMATION_MESSAGE, g_strconcat(
249               _("Color: <b>"),
250               item->def.descr.c_str(),
251               _("</b>"),
252               _("; "),
253               _("<b>Click</b> to set fill, <b>Shift+click</b> to set stroke"),
254               NULL
255             ));
256         }
257     }
258     return FALSE;
261 static gboolean handleLeaveNotify( GtkWidget* widget, GdkEventCrossing* event, gpointer callback_data ) {
262     ColorItem* item = reinterpret_cast<ColorItem*>(callback_data);
263     if ( item ) {
264         SPDesktop *desktop = SP_ACTIVE_DESKTOP;
265         if ( desktop ) {
266             desktop->tipsMessageContext()->clear();
267         }
268     }
269     return FALSE;
272 static GtkWidget* popupMenu = 0;
273 static ColorItem* bounceTarget = 0;
275 static void redirClick( GtkMenuItem *menuitem, gpointer user_data )
277     (void)user_data;
278     if ( bounceTarget ) {
279         handleClick( GTK_WIDGET(menuitem), bounceTarget );
280     }
283 static void redirSecondaryClick( GtkMenuItem *menuitem, gpointer user_data )
285     (void)user_data;
286     if ( bounceTarget ) {
287         handleSecondaryClick( GTK_WIDGET(menuitem), 0, bounceTarget );
288     }
291 static gboolean handleButtonPress( GtkWidget* widget, GdkEventButton* event, gpointer user_data)
293     (void)widget;
294     gboolean handled = FALSE;
296     if ( (event->button == 3) && (event->type == GDK_BUTTON_PRESS) ) {
297         if ( !popupMenu ) {
298             popupMenu = gtk_menu_new();
299             GtkWidget* child = 0;
301             //TRANSLATORS: An item in context menu on a colour in the swatches
302             child = gtk_menu_item_new_with_label(_("Set fill"));
303             g_signal_connect( G_OBJECT(child),
304                               "activate",
305                               G_CALLBACK(redirClick),
306                               user_data);
307             gtk_menu_shell_append(GTK_MENU_SHELL(popupMenu), child);
309             //TRANSLATORS: An item in context menu on a colour in the swatches
310             child = gtk_menu_item_new_with_label(_("Set stroke"));
312             g_signal_connect( G_OBJECT(child),
313                               "activate",
314                               G_CALLBACK(redirSecondaryClick),
315                               user_data);
316             gtk_menu_shell_append(GTK_MENU_SHELL(popupMenu), child);
318             gtk_widget_show_all(popupMenu);
319         }
321         ColorItem* item = reinterpret_cast<ColorItem*>(user_data);
322         if ( item ) {
323             bounceTarget = item;
324             if ( popupMenu ) {
325                 gtk_menu_popup(GTK_MENU(popupMenu), NULL, NULL, NULL, NULL, event->button, event->time);
326                 handled = TRUE;
327             }
328         }
329     }
331     return handled;
334 static void dieDieDie( GtkObject *obj, gpointer user_data )
336     g_message("die die die %p  %p", obj, user_data );
339 static const GtkTargetEntry destColorTargets[] = {
340 #if ENABLE_MAGIC_COLORS
341 //    {"application/x-inkscape-color-id", GTK_TARGET_SAME_APP, APP_X_INKY_COLOR_ID},
342     {"application/x-inkscape-color", 0, APP_X_INKY_COLOR},
343 #endif // ENABLE_MAGIC_COLORS
344     {"application/x-color", 0, APP_X_COLOR},
345 };
347 #include "color.h" // for SP_RGBA32_U_COMPOSE
349 void ColorItem::_dropDataIn( GtkWidget *widget,
350                              GdkDragContext *drag_context,
351                              gint x, gint y,
352                              GtkSelectionData *data,
353                              guint info,
354                              guint event_time,
355                              gpointer user_data)
357     (void)widget;
358     (void)drag_context;
359     (void)x;
360     (void)y;
361     (void)event_time;
362 //     g_message("    droppy droppy   %d", info);
363      switch (info) {
364          case APP_X_INKY_COLOR:
365          {
366              if ( data->length >= 8 ) {
367                  // Careful about endian issues.
368                  guint16* dataVals = (guint16*)data->data;
369                  if ( user_data ) {
370                      ColorItem* item = reinterpret_cast<ColorItem*>(user_data);
371                      if ( item->def.isEditable() ) {
372                          // Shove on in the new value
373                          item->def.setRGB( 0x0ff & (dataVals[0] >> 8), 0x0ff & (dataVals[1] >> 8), 0x0ff & (dataVals[2] >> 8) );
374                      }
375                  }
376              }
377              break;
378          }
379          case APP_X_COLOR:
380          {
381              if ( data->length == 8 ) {
382                  // Careful about endian issues.
383                  guint16* dataVals = (guint16*)data->data;
384 //                  {
385 //                      gchar c[64] = {0};
386 //                      sp_svg_write_color( c, 64,
387 //                                          SP_RGBA32_U_COMPOSE(
388 //                                              0x0ff & (dataVals[0] >> 8),
389 //                                              0x0ff & (dataVals[1] >> 8),
390 //                                              0x0ff & (dataVals[2] >> 8),
391 //                                              0xff // can't have transparency in the color itself
392 //                                              //0x0ff & (data->data[3] >> 8),
393 //                                              ));
394 //                  }
395                  if ( user_data ) {
396                      ColorItem* item = reinterpret_cast<ColorItem*>(user_data);
397                      if ( item->def.isEditable() ) {
398                          // Shove on in the new value
399                          item->def.setRGB( 0x0ff & (dataVals[0] >> 8), 0x0ff & (dataVals[1] >> 8), 0x0ff & (dataVals[2] >> 8) );
400                      }
401                  }
402              }
403              break;
404          }
405          default:
406              g_message("unknown drop type");
407      }
411 static bool bruteForce( SPDocument* document, Inkscape::XML::Node* node, Glib::ustring const& match, int r, int g, int b )
413     bool changed = false;
415     if ( node ) {
416         gchar const * val = node->attribute("inkscape:x-fill-tag");
417         if ( val  && (match == val) ) {
418             SPObject *obj = document->getObjectByRepr( node );
420             gchar c[64] = {0};
421             sp_svg_write_color( c, sizeof(c), SP_RGBA32_U_COMPOSE( r, g, b, 0xff ) );
422             SPCSSAttr *css = sp_repr_css_attr_new();
423             sp_repr_css_set_property( css, "fill", c );
425             sp_desktop_apply_css_recursive( (SPItem*)obj, css, true );
426             ((SPItem*)obj)->updateRepr();
428             changed = true;
429         }
431         val = node->attribute("inkscape:x-stroke-tag");
432         if ( val  && (match == val) ) {
433             SPObject *obj = document->getObjectByRepr( node );
435             gchar c[64] = {0};
436             sp_svg_write_color( c, sizeof(c), SP_RGBA32_U_COMPOSE( r, g, b, 0xff ) );
437             SPCSSAttr *css = sp_repr_css_attr_new();
438             sp_repr_css_set_property( css, "stroke", c );
440             sp_desktop_apply_css_recursive( (SPItem*)obj, css, true );
441             ((SPItem*)obj)->updateRepr();
443             changed = true;
444         }
446         Inkscape::XML::Node* first = node->firstChild();
447         changed |= bruteForce( document, first, match, r, g, b );
449         changed |= bruteForce( document, node->next(), match, r, g, b );
450     }
452     return changed;
455 void ColorItem::_colorDefChanged(void* data)
457     ColorItem* item = reinterpret_cast<ColorItem*>(data);
458     if ( item ) {
459         for ( std::vector<Gtk::Widget*>::iterator it =  item->_previews.begin(); it != item->_previews.end(); ++it ) {
460             Gtk::Widget* widget = *it;
461             if ( IS_EEK_PREVIEW(widget->gobj()) ) {
462                 EekPreview * preview = EEK_PREVIEW(widget->gobj());
463                 eek_preview_set_color( preview,
464                                        (item->def.getR() << 8) | item->def.getR(),
465                                        (item->def.getG() << 8) | item->def.getG(),
466                                        (item->def.getB() << 8) | item->def.getB() );
468                 eek_preview_set_linked( preview, (LinkType)((item->_linkSrc ? PREVIEW_LINK_IN:0)
469                                                             | (item->_listeners.empty() ? 0:PREVIEW_LINK_OUT)
470                                                             | (item->_isLive ? PREVIEW_LINK_OTHER:0)) );
472                 widget->queue_draw();
473             }
474         }
476         for ( std::vector<ColorItem*>::iterator it = item->_listeners.begin(); it != item->_listeners.end(); ++it ) {
477             guint r = item->def.getR();
478             guint g = item->def.getG();
479             guint b = item->def.getB();
481             if ( (*it)->_linkIsTone ) {
482                 r = ( ((*it)->_linkPercent * (*it)->_linkGray) + ((100 - (*it)->_linkPercent) * r) ) / 100;
483                 g = ( ((*it)->_linkPercent * (*it)->_linkGray) + ((100 - (*it)->_linkPercent) * g) ) / 100;
484                 b = ( ((*it)->_linkPercent * (*it)->_linkGray) + ((100 - (*it)->_linkPercent) * b) ) / 100;
485             } else {
486                 r = ( ((*it)->_linkPercent * 255) + ((100 - (*it)->_linkPercent) * r) ) / 100;
487                 g = ( ((*it)->_linkPercent * 255) + ((100 - (*it)->_linkPercent) * g) ) / 100;
488                 b = ( ((*it)->_linkPercent * 255) + ((100 - (*it)->_linkPercent) * b) ) / 100;
489             }
491             (*it)->def.setRGB( r, g, b );
492         }
495         // Look for objects using this color
496         {
497             SPDesktop *desktop = SP_ACTIVE_DESKTOP;
498             if ( desktop ) {
499                 SPDocument* document = sp_desktop_document( desktop );
500                 Inkscape::XML::Node *rroot =  sp_document_repr_root( document );
501                 if ( rroot ) {
503                     // Find where this thing came from
504                     Glib::ustring paletteName;
505                     bool found = false;
506                     int index = 0;
507                     for ( std::vector<JustForNow*>::iterator it2 = possible.begin(); it2 != possible.end() && !found; ++it2 ) {
508                         JustForNow* curr = *it2;
509                         index = 0;
510                         for ( std::vector<ColorItem*>::iterator zz = curr->_colors.begin(); zz != curr->_colors.end(); ++zz ) {
511                             if ( item == *zz ) {
512                                 found = true;
513                                 paletteName = curr->_name;
514                                 break;
515                             } else {
516                                 index++;
517                             }
518                         }
519                     }
521                     if ( !paletteName.empty() ) {
522                         gchar* str = g_strdup_printf("%d|", index);
523                         paletteName.insert( 0, str );
524                         g_free(str);
525                         str = 0;
527                         if ( bruteForce( document, rroot, paletteName, item->def.getR(), item->def.getG(), item->def.getB() ) ) {
528                             sp_document_done( document , SP_VERB_DIALOG_SWATCHES, 
529                                               _("Change color definition"));
530                         }
531                     }
532                 }
533             }
534         }
535     }
539 Gtk::Widget* ColorItem::getPreview(PreviewStyle style, ViewType view, ::PreviewSize size, guint ratio)
541     Gtk::Widget* widget = 0;
542     if ( style == PREVIEW_STYLE_BLURB ) {
543         Gtk::Label *lbl = new Gtk::Label(def.descr);
544         lbl->set_alignment(Gtk::ALIGN_LEFT, Gtk::ALIGN_CENTER);
545         widget = lbl;
546     } else {
547 //         Glib::ustring blank("          ");
548 //         if ( size == Inkscape::ICON_SIZE_MENU || size == Inkscape::ICON_SIZE_DECORATION ) {
549 //             blank = " ";
550 //         }
552         GtkWidget* eekWidget = eek_preview_new();
553         EekPreview * preview = EEK_PREVIEW(eekWidget);
554         Gtk::Widget* newBlot = Glib::wrap(eekWidget);
556         eek_preview_set_color( preview, (def.getR() << 8) | def.getR(), (def.getG() << 8) | def.getG(), (def.getB() << 8) | def.getB());
558         eek_preview_set_details( preview, (::PreviewStyle)style, (::ViewType)view, (::PreviewSize)size, ratio );
559         eek_preview_set_linked( preview, (LinkType)((_linkSrc ? PREVIEW_LINK_IN:0)
560                                                     | (_listeners.empty() ? 0:PREVIEW_LINK_OUT)
561                                                     | (_isLive ? PREVIEW_LINK_OTHER:0)) );
563         def.addCallback( _colorDefChanged, this );
565         GValue val = {0, {{0}, {0}}};
566         g_value_init( &val, G_TYPE_BOOLEAN );
567         g_value_set_boolean( &val, FALSE );
568         g_object_set_property( G_OBJECT(preview), "focus-on-click", &val );
570 /*
571         Gtk::Button *btn = new Gtk::Button(blank);
572         Gdk::Color color;
573         color.set_rgb((_r << 8)|_r, (_g << 8)|_g, (_b << 8)|_b);
574         btn->modify_bg(Gtk::STATE_NORMAL, color);
575         btn->modify_bg(Gtk::STATE_ACTIVE, color);
576         btn->modify_bg(Gtk::STATE_PRELIGHT, color);
577         btn->modify_bg(Gtk::STATE_SELECTED, color);
579         Gtk::Widget* newBlot = btn;
580 */
582         tips.set_tip((*newBlot), def.descr);
584 /*
585         newBlot->signal_clicked().connect( sigc::mem_fun(*this, &ColorItem::buttonClicked) );
587         sigc::signal<void> type_signal_something;
588 */
590         g_signal_connect( G_OBJECT(newBlot->gobj()),
591                           "clicked",
592                           G_CALLBACK(handleClick),
593                           this);
595         g_signal_connect( G_OBJECT(newBlot->gobj()),
596                           "alt-clicked",
597                           G_CALLBACK(handleSecondaryClick),
598                           this);
600         g_signal_connect( G_OBJECT(newBlot->gobj()),
601                           "button-press-event",
602                           G_CALLBACK(handleButtonPress),
603                           this);
605         gtk_drag_source_set( GTK_WIDGET(newBlot->gobj()),
606                              GDK_BUTTON1_MASK,
607                              sourceColorEntries,
608                              G_N_ELEMENTS(sourceColorEntries),
609                              GdkDragAction(GDK_ACTION_MOVE | GDK_ACTION_COPY) );
611         g_signal_connect( G_OBJECT(newBlot->gobj()),
612                           "drag-data-get",
613                           G_CALLBACK(ColorItem::_dragGetColorData),
614                           this);
616         g_signal_connect( G_OBJECT(newBlot->gobj()),
617                           "drag-begin",
618                           G_CALLBACK(dragBegin),
619                           this );
621         g_signal_connect( G_OBJECT(newBlot->gobj()),
622                           "enter-notify-event",
623                           G_CALLBACK(handleEnterNotify),
624                           this);
626         g_signal_connect( G_OBJECT(newBlot->gobj()),
627                           "leave-notify-event",
628                           G_CALLBACK(handleLeaveNotify),
629                           this);
631 //         g_signal_connect( G_OBJECT(newBlot->gobj()),
632 //                           "drag-drop",
633 //                           G_CALLBACK(dragDropColorData),
634 //                           this);
636         if ( def.isEditable() )
637         {
638             gtk_drag_dest_set( GTK_WIDGET(newBlot->gobj()),
639                                GTK_DEST_DEFAULT_ALL,
640                                destColorTargets,
641                                G_N_ELEMENTS(destColorTargets),
642                                GdkDragAction(GDK_ACTION_COPY | GDK_ACTION_MOVE) );
645             g_signal_connect( G_OBJECT(newBlot->gobj()),
646                               "drag-data-received",
647                               G_CALLBACK(_dropDataIn),
648                               this );
649         }
651         g_signal_connect( G_OBJECT(newBlot->gobj()),
652                           "destroy",
653                           G_CALLBACK(dieDieDie),
654                           this);
657         widget = newBlot;
658     }
660     _previews.push_back( widget );
662     return widget;
665 void ColorItem::buttonClicked(bool secondary)
667     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
668     if (desktop) {
669         char const * attrName = secondary ? "stroke" : "fill";
670         guint32 rgba = (def.getR() << 24) | (def.getG() << 16) | (def.getB() << 8) | 0xff;
671         gchar c[64];
672         sp_svg_write_color(c, sizeof(c), rgba);
674         SPCSSAttr *css = sp_repr_css_attr_new();
675         sp_repr_css_set_property( css, attrName, c );
676         sp_desktop_set_style(desktop, css);
678         sp_repr_css_attr_unref(css);
679         sp_document_done (sp_desktop_document (desktop), SP_VERB_DIALOG_SWATCHES, 
680                           secondary? _("Set stroke color from swatch") : _("Set fill color from swatch"));
681     }
687 static char* trim( char* str ) {
688     char* ret = str;
689     while ( *str && (*str == ' ' || *str == '\t') ) {
690         str++;
691     }
692     ret = str;
693     while ( *str ) {
694         str++;
695     }
696     str--;
697     while ( str > ret && ( *str == ' ' || *str == '\t' ) || *str == '\r' || *str == '\n' ) {
698         *str-- = 0;
699     }
700     return ret;
703 void skipWhitespace( char*& str ) {
704     while ( *str == ' ' || *str == '\t' ) {
705         str++;
706     }
709 bool parseNum( char*& str, int& val ) {
710     val = 0;
711     while ( '0' <= *str && *str <= '9' ) {
712         val = val * 10 + (*str - '0');
713         str++;
714     }
715     bool retval = !(*str == 0 || *str == ' ' || *str == '\t' || *str == '\r' || *str == '\n');
716     return retval;
720 static bool getBlock( std::string& dst, guchar ch, std::string const str )
722     bool good = false;
723     std::string::size_type pos = str.find(ch);
724     if ( pos != std::string::npos )
725     {
726         std::string::size_type pos2 = str.find( '(', pos );
727         if ( pos2 != std::string::npos ) {
728             std::string::size_type endPos = str.find( ')', pos2 );
729             if ( endPos != std::string::npos ) {
730                 dst = str.substr( pos2 + 1, (endPos - pos2 - 1) );
731                 good = true;
732             }
733         }
734     }
735     return good;
738 static bool popVal( guint64& numVal, std::string& str )
740     bool good = false;
741     std::string::size_type endPos = str.find(',');
742     if ( endPos == std::string::npos ) {
743         endPos = str.length();
744     }
746     if ( endPos != std::string::npos && endPos > 0 ) {
747         std::string xxx = str.substr( 0, endPos );
748         const gchar* ptr = xxx.c_str();
749         gchar* endPtr = 0;
750         numVal = g_ascii_strtoull( ptr, &endPtr, 10 );
751         if ( (numVal == G_MAXUINT64) && (ERANGE == errno) ) {
752             // overflow
753         } else if ( (numVal == 0) && (endPtr == ptr) ) {
754             // failed conversion
755         } else {
756             good = true;
757             str.erase( 0, endPos + 1 );
758         }
759     }
761     return good;
764 void ColorItem::_wireMagicColors( void* p )
766     JustForNow* onceMore = reinterpret_cast<JustForNow*>(p);
767     if ( onceMore )
768     {
769         for ( std::vector<ColorItem*>::iterator it = onceMore->_colors.begin(); it != onceMore->_colors.end(); ++it )
770         {
771             std::string::size_type pos = (*it)->def.descr.find("*{");
772             if ( pos != std::string::npos )
773             {
774                 std::string subby = (*it)->def.descr.substr( pos + 2 );
775                 std::string::size_type endPos = subby.find("}*");
776                 if ( endPos != std::string::npos )
777                 {
778                     subby.erase( endPos );
779                     //g_message("FOUND MAGIC at '%s'", (*it)->def.descr.c_str());
780                     //g_message("               '%s'", subby.c_str());
782                     if ( subby.find('E') != std::string::npos )
783                     {
784                         (*it)->def.setEditable( true );
785                     }
787                     if ( subby.find('L') != std::string::npos )
788                     {
789                         (*it)->_isLive = true;
790                     }
792                     std::string part;
793                     // Tint. index + 1 more val.
794                     if ( getBlock( part, 'T', subby ) ) {
795                         guint64 colorIndex = 0;
796                         if ( popVal( colorIndex, part ) ) {
797                             guint64 percent = 0;
798                             if ( popVal( percent, part ) ) {
799                                 (*it)->_linkTint( *(onceMore->_colors[colorIndex]), percent );
800                             }
801                         }
802                     }
804                     // Shade/tone. index + 1 or 2 more val.
805                     if ( getBlock( part, 'S', subby ) ) {
806                         guint64 colorIndex = 0;
807                         if ( popVal( colorIndex, part ) ) {
808                             guint64 percent = 0;
809                             if ( popVal( percent, part ) ) {
810                                 guint64 grayLevel = 0;
811                                 if ( !popVal( grayLevel, part ) ) {
812                                     grayLevel = 0;
813                                 }
814                                 (*it)->_linkTone( *(onceMore->_colors[colorIndex]), percent, grayLevel );
815                             }
816                         }
817                     }
819                 }
820             }
821         }
822     }
826 void ColorItem::_linkTint( ColorItem& other, int percent )
828     if ( !_linkSrc )
829     {
830         other._listeners.push_back(this);
831         _linkIsTone = false;
832         _linkPercent = percent;
833         if ( _linkPercent > 100 )
834             _linkPercent = 100;
835         if ( _linkPercent < 0 )
836             _linkPercent = 0;
837         _linkGray = 0;
838         _linkSrc = &other;
840         ColorItem::_colorDefChanged(&other);
841     }
844 void ColorItem::_linkTone( ColorItem& other, int percent, int grayLevel )
846     if ( !_linkSrc )
847     {
848         other._listeners.push_back(this);
849         _linkIsTone = true;
850         _linkPercent = percent;
851         if ( _linkPercent > 100 )
852             _linkPercent = 100;
853         if ( _linkPercent < 0 )
854             _linkPercent = 0;
855         _linkGray = grayLevel;
856         _linkSrc = &other;
858         ColorItem::_colorDefChanged(&other);
859     }
863 void _loadPaletteFile( gchar const *filename )
865     char block[1024];
866     FILE *f = Inkscape::IO::fopen_utf8name( filename, "r" );
867     if ( f ) {
868         char* result = fgets( block, sizeof(block), f );
869         if ( result ) {
870             if ( strncmp( "GIMP Palette", block, 12 ) == 0 ) {
871                 bool inHeader = true;
872                 bool hasErr = false;
874                 JustForNow *onceMore = new JustForNow();
876                 do {
877                     result = fgets( block, sizeof(block), f );
878                     block[sizeof(block) - 1] = 0;
879                     if ( result ) {
880                         if ( block[0] == '#' ) {
881                             // ignore comment
882                         } else {
883                             char *ptr = block;
884                             // very simple check for header versus entry
885                             while ( *ptr == ' ' || *ptr == '\t' ) {
886                                 ptr++;
887                             }
888                             if ( (*ptr == 0) || (*ptr == '\r') || (*ptr == '\n') ) {
889                                 // blank line. skip it.
890                             } else if ( '0' <= *ptr && *ptr <= '9' ) {
891                                 // should be an entry link
892                                 inHeader = false;
893                                 ptr = block;
894                                 Glib::ustring name("");
895                                 int r = 0;
896                                 int g = 0;
897                                 int b = 0;
898                                 skipWhitespace(ptr);
899                                 if ( *ptr ) {
900                                     hasErr = parseNum(ptr, r);
901                                     if ( !hasErr ) {
902                                         skipWhitespace(ptr);
903                                         hasErr = parseNum(ptr, g);
904                                     }
905                                     if ( !hasErr ) {
906                                         skipWhitespace(ptr);
907                                         hasErr = parseNum(ptr, b);
908                                     }
909                                     if ( !hasErr && *ptr ) {
910                                         char* n = trim(ptr);
911                                         if (n != NULL) {
912                                             name = n;
913                                         }
914                                     }
915                                     if ( !hasErr ) {
916                                         // Add the entry now
917                                         Glib::ustring nameStr(name);
918                                         ColorItem* item = new ColorItem( r, g, b, nameStr );
919                                         onceMore->_colors.push_back(item);
920                                     }
921                                 } else {
922                                     hasErr = true;
923                                 }
924                             } else {
925                                 if ( !inHeader ) {
926                                     // Hmmm... probably bad. Not quite the format we want?
927                                     hasErr = true;
928                                 } else {
929                                     char* sep = strchr(result, ':');
930                                     if ( sep ) {
931                                         *sep = 0;
932                                         char* val = trim(sep + 1);
933                                         char* name = trim(result);
934                                         if ( *name ) {
935                                             if ( strcmp( "Name", name ) == 0 )
936                                             {
937                                                 onceMore->_name = val;
938                                             }
939                                             else if ( strcmp( "Columns", name ) == 0 )
940                                             {
941                                                 gchar* endPtr = 0;
942                                                 guint64 numVal = g_ascii_strtoull( val, &endPtr, 10 );
943                                                 if ( (numVal == G_MAXUINT64) && (ERANGE == errno) ) {
944                                                     // overflow
945                                                 } else if ( (numVal == 0) && (endPtr == val) ) {
946                                                     // failed conversion
947                                                 } else {
948                                                     onceMore->_prefWidth = numVal;
949                                                 }
950                                             }
951                                         } else {
952                                             // error
953                                             hasErr = true;
954                                         }
955                                     } else {
956                                         // error
957                                         hasErr = true;
958                                     }
959                                 }
960                             }
961                         }
962                     }
963                 } while ( result && !hasErr );
964                 if ( !hasErr ) {
965                     possible.push_back(onceMore);
966 #if ENABLE_MAGIC_COLORS
967                     ColorItem::_wireMagicColors( onceMore );
968 #endif // ENABLE_MAGIC_COLORS
969                 } else {
970                     delete onceMore;
971                 }
972             }
973         }
975         fclose(f);
976     }
979 static void loadEmUp()
981     static bool beenHere = false;
982     if ( !beenHere ) {
983         beenHere = true;
985         std::list<gchar *> sources;
986         sources.push_back( profile_path("palettes") );
987         sources.push_back( g_strdup(INKSCAPE_PALETTESDIR) );
988         sources.push_back( g_strdup(CREATE_PALETTESDIR) );
990         // Use this loop to iterate through a list of possible document locations.
991         while (!sources.empty()) {
992             gchar *dirname = sources.front();
994             if ( Inkscape::IO::file_test( dirname, G_FILE_TEST_EXISTS )
995                 && Inkscape::IO::file_test( dirname, G_FILE_TEST_IS_DIR )) {
996                 GError *err = 0;
997                 GDir *directory = g_dir_open(dirname, 0, &err);
998                 if (!directory) {
999                     gchar *safeDir = Inkscape::IO::sanitizeString(dirname);
1000                     g_warning(_("Palettes directory (%s) is unavailable."), safeDir);
1001                     g_free(safeDir);
1002                 } else {
1003                     gchar *filename = 0;
1004                     while ((filename = (gchar *)g_dir_read_name(directory)) != NULL) {
1005                         gchar* lower = g_ascii_strdown( filename, -1 );
1006 //                        if ( g_str_has_suffix(lower, ".gpl") ) {
1007                             gchar* full = g_build_filename(dirname, filename, NULL);
1008                             if ( !Inkscape::IO::file_test( full, G_FILE_TEST_IS_DIR ) ) {
1009                                 _loadPaletteFile(full);
1010                             }
1011                             g_free(full);
1012 //                      }
1013                         g_free(lower);
1014                     }
1015                     g_dir_close(directory);
1016                 }
1017             }
1019             // toss the dirname
1020             g_free(dirname);
1021             sources.pop_front();
1022         }
1023     }
1034 SwatchesPanel& SwatchesPanel::getInstance()
1036     return *new SwatchesPanel();
1040 /**
1041  * Constructor
1042  */
1043 SwatchesPanel::SwatchesPanel(gchar const* prefsPath) :
1044     Inkscape::UI::Widget::Panel("", prefsPath, SP_VERB_DIALOG_SWATCHES, "", true),
1045     _holder(0)
1047     Gtk::RadioMenuItem* hotItem = 0;
1048     _holder = new PreviewHolder();
1049     loadEmUp();
1051     if ( !possible.empty() ) {
1052         JustForNow* first = 0;
1053         gchar const* targetName = 0;
1054         if ( _prefs_path ) {
1055             targetName = prefs_get_string_attribute( _prefs_path, "palette" );
1056             if ( targetName ) {
1057                 for ( std::vector<JustForNow*>::iterator iter = possible.begin(); iter != possible.end(); ++iter ) {
1058                     if ( (*iter)->_name == targetName ) {
1059                         first = *iter;
1060                         break;
1061                     }
1062                 }
1063             }
1064         }
1066         if ( !first ) {
1067             first = possible.front();
1068         }
1070         if ( first->_prefWidth > 0 ) {
1071             _holder->setColumnPref( first->_prefWidth );
1072         }
1073         _holder->freezeUpdates();
1074         for ( std::vector<ColorItem*>::iterator it = first->_colors.begin(); it != first->_colors.end(); it++ ) {
1075             _holder->addPreview(*it);
1076         }
1077         _holder->thawUpdates();
1079         Gtk::RadioMenuItem::Group groupOne;
1080         int i = 0;
1081         for ( std::vector<JustForNow*>::iterator it = possible.begin(); it != possible.end(); it++ ) {
1082             JustForNow* curr = *it;
1083             Gtk::RadioMenuItem* single = manage(new Gtk::RadioMenuItem(groupOne, curr->_name));
1084             if ( curr == first ) {
1085                 hotItem = single;
1086             }
1087             _regItem( single, 3, i );
1088             i++;
1089         }
1091     }
1094     _getContents()->pack_start(*_holder, Gtk::PACK_EXPAND_WIDGET);
1095     _setTargetFillable(_holder);
1097     show_all_children();
1099     restorePanelPrefs();
1100     if ( hotItem ) {
1101         hotItem->set_active();
1102     }
1105 SwatchesPanel::~SwatchesPanel()
1109 void SwatchesPanel::setOrientation( Gtk::AnchorType how )
1111     // Must call the parent class or bad things might happen
1112     Inkscape::UI::Widget::Panel::setOrientation( how );
1114     if ( _holder )
1115     {
1116         _holder->setOrientation( Gtk::ANCHOR_SOUTH );
1117     }
1120 void SwatchesPanel::_handleAction( int setId, int itemId )
1122     switch( setId ) {
1123         case 3:
1124         {
1125             if ( itemId >= 0 && itemId < static_cast<int>(possible.size()) ) {
1126                 _holder->clear();
1127                 JustForNow* curr = possible[itemId];
1129                 if ( _prefs_path ) {
1130                     prefs_set_string_attribute( _prefs_path, "palette", curr->_name.c_str() );
1131                 }
1133                 if ( curr->_prefWidth > 0 ) {
1134                     _holder->setColumnPref( curr->_prefWidth );
1135                 }
1136                 _holder->freezeUpdates();
1137                 for ( std::vector<ColorItem*>::iterator it = curr->_colors.begin(); it != curr->_colors.end(); it++ ) {
1138                     _holder->addPreview(*it);
1139                 }
1140                 _holder->thawUpdates();
1141             }
1142         }
1143         break;
1144     }
1147 } //namespace Dialogs
1148 } //namespace UI
1149 } //namespace Inkscape
1152 /*
1153   Local Variables:
1154   mode:c++
1155   c-file-style:"stroustrup"
1156   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1157   indent-tabs-mode:nil
1158   fill-column:99
1159   End:
1160 */
1161 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :