Code

Renamed ColorDef to PaintDef to prep for expanded functionality.
[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>
15 #include <map>
17 #include <gtk/gtkdialog.h> //for GTK_RESPONSE* types
18 #include <gtk/gtkdnd.h>
19 #include <gtk/gtkmenu.h>
20 #include <gtk/gtkmenuitem.h>
21 #include <gtk/gtkseparatormenuitem.h>
22 #include <glibmm/i18n.h>
23 #include <gdkmm/pixbuf.h>
25 #include "desktop.h"
26 #include "desktop-handles.h"
27 #include "desktop-style.h"
28 #include "document.h"
29 #include "extension/db.h"
30 #include "inkscape.h"
31 #include "inkscape.h"
32 #include "io/sys.h"
33 #include "io/resource.h"
34 #include "message-context.h"
35 #include "path-prefix.h"
36 #include "preferences.h"
37 #include "sp-item.h"
38 #include "svg/svg-color.h"
39 #include "sp-gradient-fns.h"
40 #include "sp-gradient.h"
41 #include "sp-gradient-vector.h"
42 #include "swatches.h"
43 #include "widgets/eek-preview.h"
45 namespace Inkscape {
46 namespace UI {
47 namespace Dialogs {
50 ColorItem::ColorItem(ege::PaintDef::ColorType type) :
51     def(type),
52     _isLive(false),
53     _linkIsTone(false),
54     _linkPercent(0),
55     _linkGray(0),
56     _linkSrc(0)
57 {
58 }
60 ColorItem::ColorItem( unsigned int r, unsigned int g, unsigned int b, Glib::ustring& name ) :
61     def( r, g, b, name ),
62     _isLive(false),
63     _linkIsTone(false),
64     _linkPercent(0),
65     _linkGray(0),
66     _linkSrc(0)
67 {
68 }
70 ColorItem::~ColorItem()
71 {
72 }
74 ColorItem::ColorItem(ColorItem const &other) :
75     Inkscape::UI::Previewable()
76 {
77     if ( this != &other ) {
78         *this = other;
79     }
80 }
82 ColorItem &ColorItem::operator=(ColorItem const &other)
83 {
84     if ( this != &other ) {
85         def = other.def;
87         // TODO - correct linkage
88         _linkSrc = other._linkSrc;
89         g_message("Erk!");
90     }
91     return *this;
92 }
95 class JustForNow
96 {
97 public:
98     JustForNow() : _prefWidth(0) {}
100     Glib::ustring _name;
101     int _prefWidth;
102     std::vector<ColorItem*> _colors;
103 };
105 static std::vector<JustForNow*> possible;
108 static std::vector<std::string> mimeStrings;
109 static std::map<std::string, guint> mimeToInt;
111 void ColorItem::_dragGetColorData( GtkWidget */*widget*/,
112                                    GdkDragContext */*drag_context*/,
113                                    GtkSelectionData *data,
114                                    guint info,
115                                    guint /*time*/,
116                                    gpointer user_data)
118     ColorItem* item = reinterpret_cast<ColorItem*>(user_data);
119     std::string key;
120     if ( info < mimeStrings.size() ) {
121         key = mimeStrings[info];
122     } else {
123         g_warning("ERROR: unknown value (%d)", info);
124     }
126     if ( !key.empty() ) {
127         char* tmp = 0;
128         int len = 0;
129         int format = 0;
130         item->def.getMIMEData(key, tmp, len, format);
131         if ( tmp ) {
132             GdkAtom dataAtom = gdk_atom_intern( key.c_str(), FALSE );
133             gtk_selection_data_set( data, dataAtom, format, (guchar*)tmp, len );
134             delete[] tmp;
135         }
136     }
139 static void dragBegin( GtkWidget */*widget*/, GdkDragContext* dc, gpointer data )
141     ColorItem* item = reinterpret_cast<ColorItem*>(data);
142     if ( item )
143     {
144         using Inkscape::IO::Resource::get_path;
145         using Inkscape::IO::Resource::ICONS;
146         using Inkscape::IO::Resource::SYSTEM;
148         if (item->def.getType() != ege::PaintDef::RGB){
149             GError *error = NULL;
150             gsize bytesRead = 0;
151             gsize bytesWritten = 0;
152             gchar *localFilename = g_filename_from_utf8( get_path(SYSTEM, ICONS, "remove-color.png"),
153                                                  -1,
154                                                  &bytesRead,
155                                                  &bytesWritten,
156                                                  &error);
157             GdkPixbuf* pixbuf = gdk_pixbuf_new_from_file_at_scale(localFilename, 32, 24, FALSE, &error);
158             g_free(localFilename);
159             gtk_drag_set_icon_pixbuf( dc, pixbuf, 0, 0 );
160             return;
161         }
163         Glib::RefPtr<Gdk::Pixbuf> thumb = Gdk::Pixbuf::create( Gdk::COLORSPACE_RGB, false, 8, 32, 24 );
164         guint32 fillWith = (0xff000000 & (item->def.getR() << 24))
165                          | (0x00ff0000 & (item->def.getG() << 16))
166                          | (0x0000ff00 & (item->def.getB() <<  8));
167         thumb->fill( fillWith );
168         gtk_drag_set_icon_pixbuf( dc, thumb->gobj(), 0, 0 );
169     }
173 //"drag-drop"
174 // gboolean dragDropColorData( GtkWidget *widget,
175 //                             GdkDragContext *drag_context,
176 //                             gint x,
177 //                             gint y,
178 //                             guint time,
179 //                             gpointer user_data)
180 // {
181 // // TODO finish
183 //     return TRUE;
184 // }
186 static void handleClick( GtkWidget* /*widget*/, gpointer callback_data ) {
187     ColorItem* item = reinterpret_cast<ColorItem*>(callback_data);
188     if ( item ) {
189         item->buttonClicked(false);
190     }
193 static void handleSecondaryClick( GtkWidget* /*widget*/, gint /*arg1*/, gpointer callback_data ) {
194     ColorItem* item = reinterpret_cast<ColorItem*>(callback_data);
195     if ( item ) {
196         item->buttonClicked(true);
197     }
200 static gboolean handleEnterNotify( GtkWidget* /*widget*/, GdkEventCrossing* /*event*/, gpointer callback_data ) {
201     ColorItem* item = reinterpret_cast<ColorItem*>(callback_data);
202     if ( item ) {
203         SPDesktop *desktop = SP_ACTIVE_DESKTOP;
204         if ( desktop ) {
205             gchar* msg = g_strdup_printf(_("Color: <b>%s</b>; <b>Click</b> to set fill, <b>Shift+click</b> to set stroke"),
206                                          item->def.descr.c_str());
207             desktop->tipsMessageContext()->set(Inkscape::INFORMATION_MESSAGE, msg);
208             g_free(msg);
209         }
210     }
211     return FALSE;
214 static gboolean handleLeaveNotify( GtkWidget* /*widget*/, GdkEventCrossing* /*event*/, gpointer callback_data ) {
215     ColorItem* item = reinterpret_cast<ColorItem*>(callback_data);
216     if ( item ) {
217         SPDesktop *desktop = SP_ACTIVE_DESKTOP;
218         if ( desktop ) {
219             desktop->tipsMessageContext()->clear();
220         }
221     }
222     return FALSE;
225 static GtkWidget* popupMenu = 0;
226 static ColorItem* bounceTarget = 0;
228 static void redirClick( GtkMenuItem *menuitem, gpointer /*user_data*/ )
230     if ( bounceTarget ) {
231         handleClick( GTK_WIDGET(menuitem), bounceTarget );
232     }
235 static void redirSecondaryClick( GtkMenuItem *menuitem, gpointer /*user_data*/ )
237     if ( bounceTarget ) {
238         handleSecondaryClick( GTK_WIDGET(menuitem), 0, bounceTarget );
239     }
242 static gboolean handleButtonPress( GtkWidget* /*widget*/, GdkEventButton* event, gpointer user_data)
244     gboolean handled = FALSE;
246     if ( (event->button == 3) && (event->type == GDK_BUTTON_PRESS) ) {
247         if ( !popupMenu ) {
248             popupMenu = gtk_menu_new();
249             GtkWidget* child = 0;
251             //TRANSLATORS: An item in context menu on a colour in the swatches
252             child = gtk_menu_item_new_with_label(_("Set fill"));
253             g_signal_connect( G_OBJECT(child),
254                               "activate",
255                               G_CALLBACK(redirClick),
256                               user_data);
257             gtk_menu_shell_append(GTK_MENU_SHELL(popupMenu), child);
259             //TRANSLATORS: An item in context menu on a colour in the swatches
260             child = gtk_menu_item_new_with_label(_("Set stroke"));
262             g_signal_connect( G_OBJECT(child),
263                               "activate",
264                               G_CALLBACK(redirSecondaryClick),
265                               user_data);
266             gtk_menu_shell_append(GTK_MENU_SHELL(popupMenu), child);
268             gtk_widget_show_all(popupMenu);
269         }
271         ColorItem* item = reinterpret_cast<ColorItem*>(user_data);
272         if ( item ) {
273             bounceTarget = item;
274             if ( popupMenu ) {
275                 gtk_menu_popup(GTK_MENU(popupMenu), NULL, NULL, NULL, NULL, event->button, event->time);
276                 handled = TRUE;
277             }
278         }
279     }
281     return handled;
284 static void dieDieDie( GtkObject *obj, gpointer user_data )
286     g_message("die die die %p  %p", obj, user_data );
289 #include "color.h" // for SP_RGBA32_U_COMPOSE
291 void ColorItem::_dropDataIn( GtkWidget */*widget*/,
292                              GdkDragContext */*drag_context*/,
293                              gint /*x*/, gint /*y*/,
294                              GtkSelectionData */*data*/,
295                              guint /*info*/,
296                              guint /*event_time*/,
297                              gpointer /*user_data*/)
301 static bool bruteForce( SPDocument* document, Inkscape::XML::Node* node, Glib::ustring const& match, int r, int g, int b )
303     bool changed = false;
305     if ( node ) {
306         gchar const * val = node->attribute("inkscape:x-fill-tag");
307         if ( val  && (match == val) ) {
308             SPObject *obj = document->getObjectByRepr( node );
310             gchar c[64] = {0};
311             sp_svg_write_color( c, sizeof(c), SP_RGBA32_U_COMPOSE( r, g, b, 0xff ) );
312             SPCSSAttr *css = sp_repr_css_attr_new();
313             sp_repr_css_set_property( css, "fill", c );
315             sp_desktop_apply_css_recursive( (SPItem*)obj, css, true );
316             ((SPItem*)obj)->updateRepr();
318             changed = true;
319         }
321         val = node->attribute("inkscape:x-stroke-tag");
322         if ( val  && (match == val) ) {
323             SPObject *obj = document->getObjectByRepr( node );
325             gchar c[64] = {0};
326             sp_svg_write_color( c, sizeof(c), SP_RGBA32_U_COMPOSE( r, g, b, 0xff ) );
327             SPCSSAttr *css = sp_repr_css_attr_new();
328             sp_repr_css_set_property( css, "stroke", c );
330             sp_desktop_apply_css_recursive( (SPItem*)obj, css, true );
331             ((SPItem*)obj)->updateRepr();
333             changed = true;
334         }
336         Inkscape::XML::Node* first = node->firstChild();
337         changed |= bruteForce( document, first, match, r, g, b );
339         changed |= bruteForce( document, node->next(), match, r, g, b );
340     }
342     return changed;
345 void ColorItem::_colorDefChanged(void* data)
347     ColorItem* item = reinterpret_cast<ColorItem*>(data);
348     if ( item ) {
349         for ( std::vector<Gtk::Widget*>::iterator it =  item->_previews.begin(); it != item->_previews.end(); ++it ) {
350             Gtk::Widget* widget = *it;
351             if ( IS_EEK_PREVIEW(widget->gobj()) ) {
352                 EekPreview * preview = EEK_PREVIEW(widget->gobj());
353                 eek_preview_set_color( preview,
354                                        (item->def.getR() << 8) | item->def.getR(),
355                                        (item->def.getG() << 8) | item->def.getG(),
356                                        (item->def.getB() << 8) | item->def.getB() );
358                 eek_preview_set_linked( preview, (LinkType)((item->_linkSrc ? PREVIEW_LINK_IN:0)
359                                                             | (item->_listeners.empty() ? 0:PREVIEW_LINK_OUT)
360                                                             | (item->_isLive ? PREVIEW_LINK_OTHER:0)) );
362                 widget->queue_draw();
363             }
364         }
366         for ( std::vector<ColorItem*>::iterator it = item->_listeners.begin(); it != item->_listeners.end(); ++it ) {
367             guint r = item->def.getR();
368             guint g = item->def.getG();
369             guint b = item->def.getB();
371             if ( (*it)->_linkIsTone ) {
372                 r = ( ((*it)->_linkPercent * (*it)->_linkGray) + ((100 - (*it)->_linkPercent) * r) ) / 100;
373                 g = ( ((*it)->_linkPercent * (*it)->_linkGray) + ((100 - (*it)->_linkPercent) * g) ) / 100;
374                 b = ( ((*it)->_linkPercent * (*it)->_linkGray) + ((100 - (*it)->_linkPercent) * b) ) / 100;
375             } else {
376                 r = ( ((*it)->_linkPercent * 255) + ((100 - (*it)->_linkPercent) * r) ) / 100;
377                 g = ( ((*it)->_linkPercent * 255) + ((100 - (*it)->_linkPercent) * g) ) / 100;
378                 b = ( ((*it)->_linkPercent * 255) + ((100 - (*it)->_linkPercent) * b) ) / 100;
379             }
381             (*it)->def.setRGB( r, g, b );
382         }
385         // Look for objects using this color
386         {
387             SPDesktop *desktop = SP_ACTIVE_DESKTOP;
388             if ( desktop ) {
389                 SPDocument* document = sp_desktop_document( desktop );
390                 Inkscape::XML::Node *rroot =  sp_document_repr_root( document );
391                 if ( rroot ) {
393                     // Find where this thing came from
394                     Glib::ustring paletteName;
395                     bool found = false;
396                     int index = 0;
397                     for ( std::vector<JustForNow*>::iterator it2 = possible.begin(); it2 != possible.end() && !found; ++it2 ) {
398                         JustForNow* curr = *it2;
399                         index = 0;
400                         for ( std::vector<ColorItem*>::iterator zz = curr->_colors.begin(); zz != curr->_colors.end(); ++zz ) {
401                             if ( item == *zz ) {
402                                 found = true;
403                                 paletteName = curr->_name;
404                                 break;
405                             } else {
406                                 index++;
407                             }
408                         }
409                     }
411                     if ( !paletteName.empty() ) {
412                         gchar* str = g_strdup_printf("%d|", index);
413                         paletteName.insert( 0, str );
414                         g_free(str);
415                         str = 0;
417                         if ( bruteForce( document, rroot, paletteName, item->def.getR(), item->def.getG(), item->def.getB() ) ) {
418                             sp_document_done( document , SP_VERB_DIALOG_SWATCHES,
419                                               _("Change color definition"));
420                         }
421                     }
422                 }
423             }
424         }
425     }
429 Gtk::Widget* ColorItem::getPreview(PreviewStyle style, ViewType view, ::PreviewSize size, guint ratio)
431     Gtk::Widget* widget = 0;
432     if ( style == PREVIEW_STYLE_BLURB) {
433         Gtk::Label *lbl = new Gtk::Label(def.descr);
434         lbl->set_alignment(Gtk::ALIGN_LEFT, Gtk::ALIGN_CENTER);
435         widget = lbl;
436     } else {
437 //         Glib::ustring blank("          ");
438 //         if ( size == Inkscape::ICON_SIZE_MENU || size == Inkscape::ICON_SIZE_DECORATION ) {
439 //             blank = " ";
440 //         }
442         GtkWidget* eekWidget = eek_preview_new();
443         EekPreview * preview = EEK_PREVIEW(eekWidget);
444         Gtk::Widget* newBlot = Glib::wrap(eekWidget);
446         eek_preview_set_color( preview, (def.getR() << 8) | def.getR(), (def.getG() << 8) | def.getG(), (def.getB() << 8) | def.getB());
447         if ( def.getType() != ege::PaintDef::RGB ) {
448             using Inkscape::IO::Resource::get_path;
449             using Inkscape::IO::Resource::ICONS;
450             using Inkscape::IO::Resource::SYSTEM;
451             GError *error = NULL;
452             gsize bytesRead = 0;
453             gsize bytesWritten = 0;
454             gchar *localFilename = g_filename_from_utf8( get_path(SYSTEM, ICONS, "remove-color.png"),
455                                                  -1,
456                                                  &bytesRead,
457                                                  &bytesWritten,
458                                                  &error);
459             GdkPixbuf* pixbuf = gdk_pixbuf_new_from_file(localFilename, &error);
460             if (!pixbuf) {
461                 g_warning("Null pixbuf for %p [%s]", localFilename, localFilename );
462             }
463             g_free(localFilename);
465             eek_preview_set_pixbuf( preview, pixbuf );
466         }
468         eek_preview_set_details( preview, (::PreviewStyle)style, (::ViewType)view, (::PreviewSize)size, ratio );
469         eek_preview_set_linked( preview, (LinkType)((_linkSrc ? PREVIEW_LINK_IN:0)
470                                                     | (_listeners.empty() ? 0:PREVIEW_LINK_OUT)
471                                                     | (_isLive ? PREVIEW_LINK_OTHER:0)) );
473         def.addCallback( _colorDefChanged, this );
475         GValue val = {0, {{0}, {0}}};
476         g_value_init( &val, G_TYPE_BOOLEAN );
477         g_value_set_boolean( &val, FALSE );
478         g_object_set_property( G_OBJECT(preview), "focus-on-click", &val );
480 /*
481         Gtk::Button *btn = new Gtk::Button(blank);
482         Gdk::Color color;
483         color.set_rgb((_r << 8)|_r, (_g << 8)|_g, (_b << 8)|_b);
484         btn->modify_bg(Gtk::STATE_NORMAL, color);
485         btn->modify_bg(Gtk::STATE_ACTIVE, color);
486         btn->modify_bg(Gtk::STATE_PRELIGHT, color);
487         btn->modify_bg(Gtk::STATE_SELECTED, color);
489         Gtk::Widget* newBlot = btn;
490 */
492         tips.set_tip((*newBlot), def.descr);
494 /*
495         newBlot->signal_clicked().connect( sigc::mem_fun(*this, &ColorItem::buttonClicked) );
497         sigc::signal<void> type_signal_something;
498 */
500         g_signal_connect( G_OBJECT(newBlot->gobj()),
501                           "clicked",
502                           G_CALLBACK(handleClick),
503                           this);
505         g_signal_connect( G_OBJECT(newBlot->gobj()),
506                           "alt-clicked",
507                           G_CALLBACK(handleSecondaryClick),
508                           this);
510         g_signal_connect( G_OBJECT(newBlot->gobj()),
511                           "button-press-event",
512                           G_CALLBACK(handleButtonPress),
513                           this);
515         {
516             std::vector<std::string> listing = def.getMIMETypes();
517             int entryCount = listing.size();
518             GtkTargetEntry* entries = new GtkTargetEntry[entryCount];
519             GtkTargetEntry* curr = entries;
520             for ( std::vector<std::string>::iterator it = listing.begin(); it != listing.end(); ++it ) {
521                 curr->target = g_strdup(it->c_str());
522                 curr->flags = 0;
523                 if ( mimeToInt.find(*it) == mimeToInt.end() ){
524                     // these next lines are order-dependent:
525                     mimeToInt[*it] = mimeStrings.size();
526                     mimeStrings.push_back(*it);
527                 }
528                 curr->info = mimeToInt[curr->target];
529                 curr++;
530             }
531             gtk_drag_source_set( GTK_WIDGET(newBlot->gobj()),
532                                  GDK_BUTTON1_MASK,
533                                  entries, entryCount,
534                                  GdkDragAction(GDK_ACTION_MOVE | GDK_ACTION_COPY) );
535             for ( int i = 0; i < entryCount; i++ ) {
536                 g_free(entries[i].target);
537             }
538             delete[] entries;
539         }
541         g_signal_connect( G_OBJECT(newBlot->gobj()),
542                           "drag-data-get",
543                           G_CALLBACK(ColorItem::_dragGetColorData),
544                           this);
546         g_signal_connect( G_OBJECT(newBlot->gobj()),
547                           "drag-begin",
548                           G_CALLBACK(dragBegin),
549                           this );
551         g_signal_connect( G_OBJECT(newBlot->gobj()),
552                           "enter-notify-event",
553                           G_CALLBACK(handleEnterNotify),
554                           this);
556         g_signal_connect( G_OBJECT(newBlot->gobj()),
557                           "leave-notify-event",
558                           G_CALLBACK(handleLeaveNotify),
559                           this);
561 //         g_signal_connect( G_OBJECT(newBlot->gobj()),
562 //                           "drag-drop",
563 //                           G_CALLBACK(dragDropColorData),
564 //                           this);
566         if ( def.isEditable() )
567         {
568 //             gtk_drag_dest_set( GTK_WIDGET(newBlot->gobj()),
569 //                                GTK_DEST_DEFAULT_ALL,
570 //                                destColorTargets,
571 //                                G_N_ELEMENTS(destColorTargets),
572 //                                GdkDragAction(GDK_ACTION_COPY | GDK_ACTION_MOVE) );
575 //             g_signal_connect( G_OBJECT(newBlot->gobj()),
576 //                               "drag-data-received",
577 //                               G_CALLBACK(_dropDataIn),
578 //                               this );
579         }
581         g_signal_connect( G_OBJECT(newBlot->gobj()),
582                           "destroy",
583                           G_CALLBACK(dieDieDie),
584                           this);
587         widget = newBlot;
588     }
590     _previews.push_back( widget );
592     return widget;
595 void ColorItem::buttonClicked(bool secondary)
597     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
598     if (desktop) {
599         char const * attrName = secondary ? "stroke" : "fill";
601         SPCSSAttr *css = sp_repr_css_attr_new();
602         Glib::ustring descr;
603         switch (def.getType()) {
604             case ege::PaintDef::CLEAR: {
605                 // TODO actually make this clear
606                 sp_repr_css_set_property( css, attrName, "none" );
607                 descr = secondary? _("Remove stroke color") : _("Remove fill color");
608                 break;
609             }
610             case ege::PaintDef::NONE: {
611                 sp_repr_css_set_property( css, attrName, "none" );
612                 descr = secondary? _("Set stroke color to none") : _("Set fill color to none");
613                 break;
614             }
615             case ege::PaintDef::RGB: {
616                 gchar c[64];
617                 guint32 rgba = (def.getR() << 24) | (def.getG() << 16) | (def.getB() << 8) | 0xff;
618                 sp_svg_write_color(c, sizeof(c), rgba);
620                 sp_repr_css_set_property( css, attrName, c );
621                 descr = secondary? _("Set stroke color from swatch") : _("Set fill color from swatch");
622                 break;
623             }
624         }
625         sp_desktop_set_style(desktop, css);
626         sp_repr_css_attr_unref(css);
628         sp_document_done( sp_desktop_document(desktop), SP_VERB_DIALOG_SWATCHES, descr.c_str() );
629     }
632 static char* trim( char* str ) {
633     char* ret = str;
634     while ( *str && (*str == ' ' || *str == '\t') ) {
635         str++;
636     }
637     ret = str;
638     while ( *str ) {
639         str++;
640     }
641     str--;
642     while ( str > ret && (( *str == ' ' || *str == '\t' ) || *str == '\r' || *str == '\n') ) {
643         *str-- = 0;
644     }
645     return ret;
648 void skipWhitespace( char*& str ) {
649     while ( *str == ' ' || *str == '\t' ) {
650         str++;
651     }
654 bool parseNum( char*& str, int& val ) {
655     val = 0;
656     while ( '0' <= *str && *str <= '9' ) {
657         val = val * 10 + (*str - '0');
658         str++;
659     }
660     bool retval = !(*str == 0 || *str == ' ' || *str == '\t' || *str == '\r' || *str == '\n');
661     return retval;
665 static bool getBlock( std::string& dst, guchar ch, std::string const str )
667     bool good = false;
668     std::string::size_type pos = str.find(ch);
669     if ( pos != std::string::npos )
670     {
671         std::string::size_type pos2 = str.find( '(', pos );
672         if ( pos2 != std::string::npos ) {
673             std::string::size_type endPos = str.find( ')', pos2 );
674             if ( endPos != std::string::npos ) {
675                 dst = str.substr( pos2 + 1, (endPos - pos2 - 1) );
676                 good = true;
677             }
678         }
679     }
680     return good;
683 static bool popVal( guint64& numVal, std::string& str )
685     bool good = false;
686     std::string::size_type endPos = str.find(',');
687     if ( endPos == std::string::npos ) {
688         endPos = str.length();
689     }
691     if ( endPos != std::string::npos && endPos > 0 ) {
692         std::string xxx = str.substr( 0, endPos );
693         const gchar* ptr = xxx.c_str();
694         gchar* endPtr = 0;
695         numVal = g_ascii_strtoull( ptr, &endPtr, 10 );
696         if ( (numVal == G_MAXUINT64) && (ERANGE == errno) ) {
697             // overflow
698         } else if ( (numVal == 0) && (endPtr == ptr) ) {
699             // failed conversion
700         } else {
701             good = true;
702             str.erase( 0, endPos + 1 );
703         }
704     }
706     return good;
709 void ColorItem::_wireMagicColors( void* p )
711     JustForNow* onceMore = reinterpret_cast<JustForNow*>(p);
712     if ( onceMore )
713     {
714         for ( std::vector<ColorItem*>::iterator it = onceMore->_colors.begin(); it != onceMore->_colors.end(); ++it )
715         {
716             std::string::size_type pos = (*it)->def.descr.find("*{");
717             if ( pos != std::string::npos )
718             {
719                 std::string subby = (*it)->def.descr.substr( pos + 2 );
720                 std::string::size_type endPos = subby.find("}*");
721                 if ( endPos != std::string::npos )
722                 {
723                     subby.erase( endPos );
724                     //g_message("FOUND MAGIC at '%s'", (*it)->def.descr.c_str());
725                     //g_message("               '%s'", subby.c_str());
727                     if ( subby.find('E') != std::string::npos )
728                     {
729                         (*it)->def.setEditable( true );
730                     }
732                     if ( subby.find('L') != std::string::npos )
733                     {
734                         (*it)->_isLive = true;
735                     }
737                     std::string part;
738                     // Tint. index + 1 more val.
739                     if ( getBlock( part, 'T', subby ) ) {
740                         guint64 colorIndex = 0;
741                         if ( popVal( colorIndex, part ) ) {
742                             guint64 percent = 0;
743                             if ( popVal( percent, part ) ) {
744                                 (*it)->_linkTint( *(onceMore->_colors[colorIndex]), percent );
745                             }
746                         }
747                     }
749                     // Shade/tone. index + 1 or 2 more val.
750                     if ( getBlock( part, 'S', subby ) ) {
751                         guint64 colorIndex = 0;
752                         if ( popVal( colorIndex, part ) ) {
753                             guint64 percent = 0;
754                             if ( popVal( percent, part ) ) {
755                                 guint64 grayLevel = 0;
756                                 if ( !popVal( grayLevel, part ) ) {
757                                     grayLevel = 0;
758                                 }
759                                 (*it)->_linkTone( *(onceMore->_colors[colorIndex]), percent, grayLevel );
760                             }
761                         }
762                     }
764                 }
765             }
766         }
767     }
771 void ColorItem::_linkTint( ColorItem& other, int percent )
773     if ( !_linkSrc )
774     {
775         other._listeners.push_back(this);
776         _linkIsTone = false;
777         _linkPercent = percent;
778         if ( _linkPercent > 100 )
779             _linkPercent = 100;
780         if ( _linkPercent < 0 )
781             _linkPercent = 0;
782         _linkGray = 0;
783         _linkSrc = &other;
785         ColorItem::_colorDefChanged(&other);
786     }
789 void ColorItem::_linkTone( ColorItem& other, int percent, int grayLevel )
791     if ( !_linkSrc )
792     {
793         other._listeners.push_back(this);
794         _linkIsTone = true;
795         _linkPercent = percent;
796         if ( _linkPercent > 100 )
797             _linkPercent = 100;
798         if ( _linkPercent < 0 )
799             _linkPercent = 0;
800         _linkGray = grayLevel;
801         _linkSrc = &other;
803         ColorItem::_colorDefChanged(&other);
804     }
808 void _loadPaletteFile( gchar const *filename )
810     char block[1024];
811     FILE *f = Inkscape::IO::fopen_utf8name( filename, "r" );
812     if ( f ) {
813         char* result = fgets( block, sizeof(block), f );
814         if ( result ) {
815             if ( strncmp( "GIMP Palette", block, 12 ) == 0 ) {
816                 bool inHeader = true;
817                 bool hasErr = false;
819                 JustForNow *onceMore = new JustForNow();
821                 do {
822                     result = fgets( block, sizeof(block), f );
823                     block[sizeof(block) - 1] = 0;
824                     if ( result ) {
825                         if ( block[0] == '#' ) {
826                             // ignore comment
827                         } else {
828                             char *ptr = block;
829                             // very simple check for header versus entry
830                             while ( *ptr == ' ' || *ptr == '\t' ) {
831                                 ptr++;
832                             }
833                             if ( (*ptr == 0) || (*ptr == '\r') || (*ptr == '\n') ) {
834                                 // blank line. skip it.
835                             } else if ( '0' <= *ptr && *ptr <= '9' ) {
836                                 // should be an entry link
837                                 inHeader = false;
838                                 ptr = block;
839                                 Glib::ustring name("");
840                                 int r = 0;
841                                 int g = 0;
842                                 int b = 0;
843                                 skipWhitespace(ptr);
844                                 if ( *ptr ) {
845                                     hasErr = parseNum(ptr, r);
846                                     if ( !hasErr ) {
847                                         skipWhitespace(ptr);
848                                         hasErr = parseNum(ptr, g);
849                                     }
850                                     if ( !hasErr ) {
851                                         skipWhitespace(ptr);
852                                         hasErr = parseNum(ptr, b);
853                                     }
854                                     if ( !hasErr && *ptr ) {
855                                         char* n = trim(ptr);
856                                         if (n != NULL) {
857                                             name = n;
858                                         }
859                                     }
860                                     if ( !hasErr ) {
861                                         // Add the entry now
862                                         Glib::ustring nameStr(name);
863                                         ColorItem* item = new ColorItem( r, g, b, nameStr );
864                                         onceMore->_colors.push_back(item);
865                                     }
866                                 } else {
867                                     hasErr = true;
868                                 }
869                             } else {
870                                 if ( !inHeader ) {
871                                     // Hmmm... probably bad. Not quite the format we want?
872                                     hasErr = true;
873                                 } else {
874                                     char* sep = strchr(result, ':');
875                                     if ( sep ) {
876                                         *sep = 0;
877                                         char* val = trim(sep + 1);
878                                         char* name = trim(result);
879                                         if ( *name ) {
880                                             if ( strcmp( "Name", name ) == 0 )
881                                             {
882                                                 onceMore->_name = val;
883                                             }
884                                             else if ( strcmp( "Columns", name ) == 0 )
885                                             {
886                                                 gchar* endPtr = 0;
887                                                 guint64 numVal = g_ascii_strtoull( val, &endPtr, 10 );
888                                                 if ( (numVal == G_MAXUINT64) && (ERANGE == errno) ) {
889                                                     // overflow
890                                                 } else if ( (numVal == 0) && (endPtr == val) ) {
891                                                     // failed conversion
892                                                 } else {
893                                                     onceMore->_prefWidth = numVal;
894                                                 }
895                                             }
896                                         } else {
897                                             // error
898                                             hasErr = true;
899                                         }
900                                     } else {
901                                         // error
902                                         hasErr = true;
903                                     }
904                                 }
905                             }
906                         }
907                     }
908                 } while ( result && !hasErr );
909                 if ( !hasErr ) {
910                     possible.push_back(onceMore);
911 #if ENABLE_MAGIC_COLORS
912                     ColorItem::_wireMagicColors( onceMore );
913 #endif // ENABLE_MAGIC_COLORS
914                 } else {
915                     delete onceMore;
916                 }
917             }
918         }
920         fclose(f);
921     }
924 static void loadEmUp()
926     static bool beenHere = false;
927     if ( !beenHere ) {
928         beenHere = true;
930         std::list<gchar *> sources;
931         sources.push_back( profile_path("palettes") );
932         sources.push_back( g_strdup(INKSCAPE_PALETTESDIR) );
933         sources.push_back( g_strdup(CREATE_PALETTESDIR) );
935         // Use this loop to iterate through a list of possible document locations.
936         while (!sources.empty()) {
937             gchar *dirname = sources.front();
939             if ( Inkscape::IO::file_test( dirname, G_FILE_TEST_EXISTS )
940                 && Inkscape::IO::file_test( dirname, G_FILE_TEST_IS_DIR )) {
941                 GError *err = 0;
942                 GDir *directory = g_dir_open(dirname, 0, &err);
943                 if (!directory) {
944                     gchar *safeDir = Inkscape::IO::sanitizeString(dirname);
945                     g_warning(_("Palettes directory (%s) is unavailable."), safeDir);
946                     g_free(safeDir);
947                 } else {
948                     gchar *filename = 0;
949                     while ((filename = (gchar *)g_dir_read_name(directory)) != NULL) {
950                         gchar* lower = g_ascii_strdown( filename, -1 );
951 //                        if ( g_str_has_suffix(lower, ".gpl") ) {
952                             gchar* full = g_build_filename(dirname, filename, NULL);
953                             if ( !Inkscape::IO::file_test( full, G_FILE_TEST_IS_DIR ) ) {
954                                 _loadPaletteFile(full);
955                             }
956                             g_free(full);
957 //                      }
958                         g_free(lower);
959                     }
960                     g_dir_close(directory);
961                 }
962             }
964             // toss the dirname
965             g_free(dirname);
966             sources.pop_front();
967         }
968     }
979 SwatchesPanel& SwatchesPanel::getInstance()
981     return *new SwatchesPanel();
985 /**
986  * Constructor
987  */
988 SwatchesPanel::SwatchesPanel(gchar const* prefsPath) :
989     Inkscape::UI::Widget::Panel("", prefsPath, SP_VERB_DIALOG_SWATCHES, "", true),
990     _holder(0),
991     _clear(0),
992     _remove(0),
993     _currentIndex(0),
994     _currentDesktop(0),
995     _currentDocument(0),
996     _ptr(0)
998     Gtk::RadioMenuItem* hotItem = 0;
999     _holder = new PreviewHolder();
1000     _clear = new ColorItem( ege::PaintDef::CLEAR );
1001     _remove = new ColorItem( ege::PaintDef::NONE );
1002     {
1003         JustForNow *docPalette = new JustForNow();
1005         docPalette->_name = "Auto";
1006         possible.push_back(docPalette);
1008         _ptr = docPalette;
1009     }
1010     loadEmUp();
1011     if ( !possible.empty() ) {
1012         JustForNow* first = 0;
1013         int index = 0;
1014         Glib::ustring targetName;
1015         if ( !_prefs_path.empty() ) {
1016             Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1017             targetName = prefs->getString(_prefs_path + "/palette");
1018             if (!targetName.empty()) {
1019                 for ( std::vector<JustForNow*>::iterator iter = possible.begin(); iter != possible.end(); ++iter ) {
1020                     if ( (*iter)->_name == targetName ) {
1021                         first = *iter;
1022                         break;
1023                     }
1024                     index++;
1025                 }
1026             }
1027         }
1029         if ( !first ) {
1030             first = possible.front();
1031             _currentIndex = 0;
1032         } else {
1033             _currentIndex = index;
1034         }
1036         _rebuild();
1038         Gtk::RadioMenuItem::Group groupOne;
1040         int i = 0;
1041         for ( std::vector<JustForNow*>::iterator it = possible.begin(); it != possible.end(); it++ ) {
1042             JustForNow* curr = *it;
1043             Gtk::RadioMenuItem* single = manage(new Gtk::RadioMenuItem(groupOne, curr->_name));
1044             if ( curr == first ) {
1045                 hotItem = single;
1046             }
1047             _regItem( single, 3, i );
1048             i++;
1049         }
1050     }
1053     _getContents()->pack_start(*_holder, Gtk::PACK_EXPAND_WIDGET);
1054     _setTargetFillable(_holder);
1056     show_all_children();
1058     restorePanelPrefs();
1059     if ( hotItem ) {
1060         hotItem->set_active();
1061     }
1064 SwatchesPanel::~SwatchesPanel()
1066     _documentConnection.disconnect();
1067     _resourceConnection.disconnect();
1069     if ( _clear ) {
1070         delete _clear;
1071     }
1072     if ( _remove ) {
1073         delete _remove;
1074     }
1075     if ( _holder ) {
1076         delete _holder;
1077     }
1080 void SwatchesPanel::setOrientation( Gtk::AnchorType how )
1082     // Must call the parent class or bad things might happen
1083     Inkscape::UI::Widget::Panel::setOrientation( how );
1085     if ( _holder )
1086     {
1087         _holder->setOrientation( Gtk::ANCHOR_SOUTH );
1088     }
1091 void SwatchesPanel::setDesktop( SPDesktop* desktop )
1093     if ( desktop != _currentDesktop ) {
1094         if ( _currentDesktop ) {
1095             _documentConnection.disconnect();
1096         }
1098         _currentDesktop = desktop;
1100         if ( desktop ) {
1101             sigc::bound_mem_functor1<void, Inkscape::UI::Dialogs::SwatchesPanel, SPDocument*> first = sigc::mem_fun(*this, &SwatchesPanel::_setDocument);
1103             sigc::slot<void, SPDocument*> base2 = first;
1105             sigc::slot<void,SPDesktop*, SPDocument*> slot2 = sigc::hide<0>( base2 );
1106             _documentConnection = desktop->connectDocumentReplaced( slot2 );
1108             _setDocument( desktop->doc() );
1109         } else {
1110             _setDocument(0);
1111         }
1112     }
1115 void SwatchesPanel::_setDocument( SPDocument *document )
1117     if ( document != _currentDocument ) {
1118         if ( _currentDocument ) {
1119             _resourceConnection.disconnect();
1120         }
1121         _currentDocument = document;
1122         if ( _currentDocument ) {
1123             _resourceConnection = sp_document_resources_changed_connect(document,
1124                                                                         "gradient",
1125                                                                         sigc::mem_fun(*this, &SwatchesPanel::_handleGradientsChange));
1126         }
1128         _handleGradientsChange();
1129     }
1132 void SwatchesPanel::_handleGradientsChange()
1134     std::vector<SPGradient*> newList;
1136     const GSList *gradients = sp_document_get_resource_list(_currentDocument, "gradient");
1137     for (const GSList *item = gradients; item; item = item->next) {
1138         SPGradient* grad = SP_GRADIENT(item->data);
1139         if ( grad->has_stops ) {
1140             newList.push_back(SP_GRADIENT(item->data));
1141         }
1142     }
1144     if ( _ptr ) {
1145         JustForNow *docPalette = reinterpret_cast<JustForNow *>(_ptr);
1146         // TODO delete pointed to objects
1147         docPalette->_colors.clear();
1148         if ( !newList.empty() ) {
1149             for ( std::vector<SPGradient*>::iterator it = newList.begin(); it != newList.end(); ++it )
1150             {
1151                 if ( (*it)->vector.stops.size() == 2 ) {
1152                     SPGradientStop first = (*it)->vector.stops[0];
1153                     SPGradientStop second = (*it)->vector.stops[1];
1154                     if ((first.offset <0.0001) && (static_cast<int>(second.offset * 100.0f) == 100)) {
1155                         SPColor color = first.color;
1156                         guint32 together = color.toRGBA32(0);
1158                         // Pick only single-color gradients for now
1159                         SPColor color2 = second.color;
1160                         guint32 together2 = color2.toRGBA32(0);
1161                         if ( together == together2 ) {
1162                             Glib::ustring name((*it)->id);
1163                             unsigned int r = SP_RGBA32_R_U(together);
1164                             unsigned int g = SP_RGBA32_G_U(together);
1165                             unsigned int b = SP_RGBA32_B_U(together);
1166                             ColorItem* item = new ColorItem( r, g, b, name );
1167                             docPalette->_colors.push_back(item);
1168                         }
1169                     }
1170                 }
1171             }
1172         }
1173         JustForNow* curr = possible[_currentIndex];
1174         if (curr == docPalette) {
1175             _rebuild();
1176         }
1177     }
1180 void SwatchesPanel::_handleAction( int setId, int itemId )
1182     switch( setId ) {
1183         case 3:
1184         {
1185             if ( itemId >= 0 && itemId < static_cast<int>(possible.size()) ) {
1186                 _currentIndex = itemId;
1188                 if ( !_prefs_path.empty() ) {
1189                     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1190                     prefs->setString(_prefs_path + "/palette", possible[_currentIndex]->_name);
1191                 }
1193                 _rebuild();
1194             }
1195         }
1196         break;
1197     }
1200 void SwatchesPanel::_rebuild()
1202     JustForNow* curr = possible[_currentIndex];
1203     _holder->clear();
1205     if ( curr->_prefWidth > 0 ) {
1206         _holder->setColumnPref( curr->_prefWidth );
1207     }
1208     _holder->freezeUpdates();
1209     // TODO restore once 'clear' works _holder->addPreview(_clear);
1210     _holder->addPreview(_remove);
1211     for ( std::vector<ColorItem*>::iterator it = curr->_colors.begin(); it != curr->_colors.end(); it++ ) {
1212         _holder->addPreview(*it);
1213     }
1214     _holder->thawUpdates();
1220 } //namespace Dialogs
1221 } //namespace UI
1222 } //namespace Inkscape
1225 /*
1226   Local Variables:
1227   mode:c++
1228   c-file-style:"stroustrup"
1229   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1230   indent-tabs-mode:nil
1231   fill-column:99
1232   End:
1233 */
1234 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :