Code

stop toggling insensitive state for modification flag updates (fixes critical bug...
[inkscape.git] / src / dialogs / swatches.cpp
1 /*
2  * A simple panel for color swatches
3  *
4  * Authors:
5  *   Jon A. Cruz
6  *
7  * Copyright (C) 2005 Jon A. Cruz
8  *
9  * Released under GNU GPL, read the file 'COPYING' for more information
10  */
11 #ifdef HAVE_CONFIG_H
12 # include <config.h>
13 #endif
15 #include <errno.h>
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>
23 #include <glibmm/i18n.h>
24 #include <gdkmm/pixbuf.h>
25 #include "inkscape.h"
26 #include "document.h"
27 #include "desktop-handles.h"
28 #include "extension/db.h"
29 #include "inkscape.h"
30 #include "svg/svg-color.h"
31 #include "desktop-style.h"
32 #include "io/sys.h"
33 #include "path-prefix.h"
34 #include "swatches.h"
35 #include "sp-item.h"
36 #include "prefs-utils.h"
38 #include "eek-preview.h"
40 namespace Inkscape {
41 namespace UI {
42 namespace Dialogs {
45 ColorItem::ColorItem( unsigned int r, unsigned int g, unsigned int b, Glib::ustring& name ) :
46     def( r, g, b, name ),
47     _isLive(false),
48     _linkIsTone(false),
49     _linkPercent(0),
50     _linkGray(0),
51     _linkSrc(0)
52 {
53 }
55 ColorItem::~ColorItem()
56 {
57 }
59 ColorItem::ColorItem(ColorItem const &other) :
60     Inkscape::UI::Previewable()
61 {
62     if ( this != &other ) {
63         *this = other;
64     }
65 }
67 ColorItem &ColorItem::operator=(ColorItem const &other)
68 {
69     if ( this != &other ) {
70         def = other.def;
72         // TODO - correct linkage
73         _linkSrc = other._linkSrc;
74         g_message("Erk!");
75     }
76     return *this;
77 }
80 class JustForNow
81 {
82 public:
83     JustForNow() : _prefWidth(0) {}
85     Glib::ustring _name;
86     int _prefWidth;
87     std::vector<ColorItem*> _colors;
88 };
90 static std::vector<JustForNow*> possible;
94 typedef enum {
95     APP_X_INKY_COLOR_ID = 0,
96     APP_X_INKY_COLOR = 0,
97     APP_X_COLOR,
98     TEXT_DATA
99 } colorFlavorType;
101 static const GtkTargetEntry sourceColorEntries[] = {
102 #if ENABLE_MAGIC_COLORS
103 //    {"application/x-inkscape-color-id", GTK_TARGET_SAME_APP, APP_X_INKY_COLOR_ID},
104     {"application/x-inkscape-color", 0, APP_X_INKY_COLOR},
105 #endif // ENABLE_MAGIC_COLORS
106     {"application/x-color", 0, APP_X_COLOR},
107     {"text/plain", 0, TEXT_DATA},
108 };
110 void ColorItem::_dragGetColorData( GtkWidget *widget,
111                                    GdkDragContext *drag_context,
112                                    GtkSelectionData *data,
113                                    guint info,
114                                    guint time,
115                                    gpointer user_data)
117     (void)widget;
118     (void)drag_context;
119     (void)time;
120     static GdkAtom typeXColor = gdk_atom_intern("application/x-color", FALSE);
121     static GdkAtom typeText = gdk_atom_intern("text/plain", FALSE);
123     ColorItem* item = reinterpret_cast<ColorItem*>(user_data);
124     if ( info == TEXT_DATA ) {
125         gchar* tmp = g_strdup_printf("#%02x%02x%02x", item->def.getR(), item->def.getG(), item->def.getB() );
127         gtk_selection_data_set( data,
128                                 typeText,
129                                 8, // format
130                                 (guchar*)tmp,
131                                 strlen((const char*)tmp) + 1);
132         g_free(tmp);
133         tmp = 0;
134     } else if ( info == APP_X_INKY_COLOR ) {
135         Glib::ustring paletteName;
137         // Find where this thing came from
138         bool found = false;
139         int index = 0;
140         for ( std::vector<JustForNow*>::iterator it = possible.begin(); it != possible.end() && !found; ++it ) {
141             JustForNow* curr = *it;
142             index = 0;
143             for ( std::vector<ColorItem*>::iterator zz = curr->_colors.begin(); zz != curr->_colors.end(); ++zz ) {
144                 if ( item == *zz ) {
145                     found = true;
146                     paletteName = curr->_name;
147                     break;
148                 } else {
149                     index++;
150                 }
151             }
152         }
154 //         if ( found ) {
155 //             g_message("Found the color at entry %d in palette '%s'", index, paletteName.c_str() );
156 //         } else {
157 //             g_message("Unable to find the color");
158 //         }
159         int itemCount = 4 + 2 + 1 + paletteName.length();
161         guint16* tmp = new guint16[itemCount];
162         tmp[0] = (item->def.getR() << 8) | item->def.getR();
163         tmp[1] = (item->def.getG() << 8) | item->def.getG();
164         tmp[2] = (item->def.getB() << 8) | item->def.getB();
165         tmp[3] = 0xffff;
166         tmp[4] = (item->_isLive || !item->_listeners.empty() || (item->_linkSrc != 0) ) ? 1 : 0;
168         tmp[5] = index;
169         tmp[6] = paletteName.length();
170         for ( unsigned int i = 0; i < paletteName.length(); i++ ) {
171             tmp[7 + i] = paletteName[i];
172         }
173         gtk_selection_data_set( data,
174                                 typeXColor,
175                                 16, // format
176                                 reinterpret_cast<const guchar*>(tmp),
177                                 itemCount * 2);
178         delete[] tmp;
179     } else {
180         guint16 tmp[4];
181         tmp[0] = (item->def.getR() << 8) | item->def.getR();
182         tmp[1] = (item->def.getG() << 8) | item->def.getG();
183         tmp[2] = (item->def.getB() << 8) | item->def.getB();
184         tmp[3] = 0xffff;
185         gtk_selection_data_set( data,
186                                 typeXColor,
187                                 16, // format
188                                 reinterpret_cast<const guchar*>(tmp),
189                                 (3+1) * 2);
190     }
193 static void dragBegin( GtkWidget *widget, GdkDragContext* dc, gpointer data )
195     (void)widget;
196     ColorItem* item = reinterpret_cast<ColorItem*>(data);
197     if ( item )
198     {
199         Glib::RefPtr<Gdk::Pixbuf> thumb = Gdk::Pixbuf::create( Gdk::COLORSPACE_RGB, false, 8, 32, 24 );
200         guint32 fillWith = (0xff000000 & (item->def.getR() << 24))
201                          | (0x00ff0000 & (item->def.getG() << 16))
202                          | (0x0000ff00 & (item->def.getB() <<  8));
203         thumb->fill( fillWith );
204         gtk_drag_set_icon_pixbuf( dc, thumb->gobj(), 0, 0 );
205     }
209 //"drag-drop"
210 // gboolean dragDropColorData( GtkWidget *widget,
211 //                             GdkDragContext *drag_context,
212 //                             gint x,
213 //                             gint y,
214 //                             guint time,
215 //                             gpointer user_data)
216 // {
217 // // TODO finish
219 //     return TRUE;
220 // }
222 static void handleClick( GtkWidget* widget, gpointer callback_data ) {
223     (void)widget;
224     ColorItem* item = reinterpret_cast<ColorItem*>(callback_data);
225     if ( item ) {
226         item->buttonClicked(false);
227     }
230 static void handleSecondaryClick( GtkWidget* widget, gint arg1, gpointer callback_data ) {
231     (void)widget;
232     (void)arg1;
233     ColorItem* item = reinterpret_cast<ColorItem*>(callback_data);
234     if ( item ) {
235         item->buttonClicked(true);
236     }
239 static GtkWidget* popupMenu = 0;
240 static ColorItem* bounceTarget = 0;
242 static void redirClick( GtkMenuItem *menuitem, gpointer user_data )
244     (void)user_data;
245     if ( bounceTarget ) {
246         handleClick( GTK_WIDGET(menuitem), bounceTarget );
247     }
250 static void redirSecondaryClick( GtkMenuItem *menuitem, gpointer user_data )
252     (void)user_data;
253     if ( bounceTarget ) {
254         handleSecondaryClick( GTK_WIDGET(menuitem), 0, bounceTarget );
255     }
258 static gboolean handleButtonPress( GtkWidget* widget, GdkEventButton* event, gpointer user_data)
260     (void)widget;
261     gboolean handled = FALSE;
263     if ( (event->button == 3) && (event->type == GDK_BUTTON_PRESS) ) {
264         if ( !popupMenu ) {
265             popupMenu = gtk_menu_new();
266             GtkWidget* child = 0;
268             child = gtk_menu_item_new_with_label("Set fill");
269             g_signal_connect( G_OBJECT(child),
270                               "activate",
271                               G_CALLBACK(redirClick),
272                               user_data);
273             gtk_menu_shell_append(GTK_MENU_SHELL(popupMenu), child);
275             child = gtk_menu_item_new_with_label("Set stroke");
277             g_signal_connect( G_OBJECT(child),
278                               "activate",
279                               G_CALLBACK(redirSecondaryClick),
280                               user_data);
281             gtk_menu_shell_append(GTK_MENU_SHELL(popupMenu), child);
283             gtk_widget_show_all(popupMenu);
284         }
286         ColorItem* item = reinterpret_cast<ColorItem*>(user_data);
287         if ( item ) {
288             bounceTarget = item;
289             if ( popupMenu ) {
290                 gtk_menu_popup(GTK_MENU(popupMenu), NULL, NULL, NULL, NULL, event->button, event->time);
291                 handled = TRUE;
292             }
293         }
294     }
296     return handled;
299 static void dieDieDie( GtkObject *obj, gpointer user_data )
301     g_message("die die die %p  %p", obj, user_data );
304 static const GtkTargetEntry destColorTargets[] = {
305 #if ENABLE_MAGIC_COLORS
306 //    {"application/x-inkscape-color-id", GTK_TARGET_SAME_APP, APP_X_INKY_COLOR_ID},
307     {"application/x-inkscape-color", 0, APP_X_INKY_COLOR},
308 #endif // ENABLE_MAGIC_COLORS
309     {"application/x-color", 0, APP_X_COLOR},
310 };
312 #include "color.h" // for SP_RGBA32_U_COMPOSE
314 void ColorItem::_dropDataIn( GtkWidget *widget,
315                              GdkDragContext *drag_context,
316                              gint x, gint y,
317                              GtkSelectionData *data,
318                              guint info,
319                              guint event_time,
320                              gpointer user_data)
322     (void)widget;
323     (void)drag_context;
324     (void)x;
325     (void)y;
326     (void)event_time;
327 //     g_message("    droppy droppy   %d", info);
328      switch (info) {
329          case APP_X_INKY_COLOR:
330          {
331              if ( data->length >= 8 ) {
332                  // Careful about endian issues.
333                  guint16* dataVals = (guint16*)data->data;
334                  if ( user_data ) {
335                      ColorItem* item = reinterpret_cast<ColorItem*>(user_data);
336                      if ( item->def.isEditable() ) {
337                          // Shove on in the new value
338                          item->def.setRGB( 0x0ff & (dataVals[0] >> 8), 0x0ff & (dataVals[1] >> 8), 0x0ff & (dataVals[2] >> 8) );
339                      }
340                  }
341              }
342              break;
343          }
344          case APP_X_COLOR:
345          {
346              if ( data->length == 8 ) {
347                  // Careful about endian issues.
348                  guint16* dataVals = (guint16*)data->data;
349 //                  {
350 //                      gchar c[64] = {0};
351 //                      sp_svg_write_color( c, 64,
352 //                                          SP_RGBA32_U_COMPOSE(
353 //                                              0x0ff & (dataVals[0] >> 8),
354 //                                              0x0ff & (dataVals[1] >> 8),
355 //                                              0x0ff & (dataVals[2] >> 8),
356 //                                              0xff // can't have transparency in the color itself
357 //                                              //0x0ff & (data->data[3] >> 8),
358 //                                              ));
359 //                  }
360                  if ( user_data ) {
361                      ColorItem* item = reinterpret_cast<ColorItem*>(user_data);
362                      if ( item->def.isEditable() ) {
363                          // Shove on in the new value
364                          item->def.setRGB( 0x0ff & (dataVals[0] >> 8), 0x0ff & (dataVals[1] >> 8), 0x0ff & (dataVals[2] >> 8) );
365                      }
366                  }
367              }
368              break;
369          }
370          default:
371              g_message("unknown drop type");
372      }
376 static bool bruteForce( SPDocument* document, Inkscape::XML::Node* node, Glib::ustring const& match, int r, int g, int b )
378     bool changed = false;
380     if ( node ) {
381         gchar const * val = node->attribute("inkscape:x-fill-tag");
382         if ( val  && (match == val) ) {
383             SPObject *obj = document->getObjectByRepr( node );
385             gchar c[64] = {0};
386             sp_svg_write_color( c, sizeof(c), SP_RGBA32_U_COMPOSE( r, g, b, 0xff ) );
387             SPCSSAttr *css = sp_repr_css_attr_new();
388             sp_repr_css_set_property( css, "fill", c );
390             sp_desktop_apply_css_recursive( (SPItem*)obj, css, true );
391             ((SPItem*)obj)->updateRepr();
393             changed = true;
394         }
396         val = node->attribute("inkscape:x-stroke-tag");
397         if ( val  && (match == val) ) {
398             SPObject *obj = document->getObjectByRepr( node );
400             gchar c[64] = {0};
401             sp_svg_write_color( c, sizeof(c), SP_RGBA32_U_COMPOSE( r, g, b, 0xff ) );
402             SPCSSAttr *css = sp_repr_css_attr_new();
403             sp_repr_css_set_property( css, "stroke", c );
405             sp_desktop_apply_css_recursive( (SPItem*)obj, css, true );
406             ((SPItem*)obj)->updateRepr();
408             changed = true;
409         }
411         Inkscape::XML::Node* first = node->firstChild();
412         changed |= bruteForce( document, first, match, r, g, b );
414         changed |= bruteForce( document, node->next(), match, r, g, b );
415     }
417     return changed;
420 void ColorItem::_colorDefChanged(void* data)
422     ColorItem* item = reinterpret_cast<ColorItem*>(data);
423     if ( item ) {
424         for ( std::vector<Gtk::Widget*>::iterator it =  item->_previews.begin(); it != item->_previews.end(); ++it ) {
425             Gtk::Widget* widget = *it;
426             if ( IS_EEK_PREVIEW(widget->gobj()) ) {
427                 EekPreview * preview = EEK_PREVIEW(widget->gobj());
428                 eek_preview_set_color( preview,
429                                        (item->def.getR() << 8) | item->def.getR(),
430                                        (item->def.getG() << 8) | item->def.getG(),
431                                        (item->def.getB() << 8) | item->def.getB() );
433                 eek_preview_set_linked( preview, (LinkType)((item->_linkSrc ? PREVIEW_LINK_IN:0)
434                                                             | (item->_listeners.empty() ? 0:PREVIEW_LINK_OUT)
435                                                             | (item->_isLive ? PREVIEW_LINK_OTHER:0)) );
437                 widget->queue_draw();
438             }
439         }
441         for ( std::vector<ColorItem*>::iterator it = item->_listeners.begin(); it != item->_listeners.end(); ++it ) {
442             guint r = item->def.getR();
443             guint g = item->def.getG();
444             guint b = item->def.getB();
446             if ( (*it)->_linkIsTone ) {
447                 r = ( ((*it)->_linkPercent * (*it)->_linkGray) + ((100 - (*it)->_linkPercent) * r) ) / 100;
448                 g = ( ((*it)->_linkPercent * (*it)->_linkGray) + ((100 - (*it)->_linkPercent) * g) ) / 100;
449                 b = ( ((*it)->_linkPercent * (*it)->_linkGray) + ((100 - (*it)->_linkPercent) * b) ) / 100;
450             } else {
451                 r = ( ((*it)->_linkPercent * 255) + ((100 - (*it)->_linkPercent) * r) ) / 100;
452                 g = ( ((*it)->_linkPercent * 255) + ((100 - (*it)->_linkPercent) * g) ) / 100;
453                 b = ( ((*it)->_linkPercent * 255) + ((100 - (*it)->_linkPercent) * b) ) / 100;
454             }
456             (*it)->def.setRGB( r, g, b );
457         }
460         // Look for objects using this color
461         {
462             SPDesktop *desktop = SP_ACTIVE_DESKTOP;
463             if ( desktop ) {
464                 SPDocument* document = sp_desktop_document( desktop );
465                 Inkscape::XML::Node *rroot =  sp_document_repr_root( document );
466                 if ( rroot ) {
468                     // Find where this thing came from
469                     Glib::ustring paletteName;
470                     bool found = false;
471                     int index = 0;
472                     for ( std::vector<JustForNow*>::iterator it2 = possible.begin(); it2 != possible.end() && !found; ++it2 ) {
473                         JustForNow* curr = *it2;
474                         index = 0;
475                         for ( std::vector<ColorItem*>::iterator zz = curr->_colors.begin(); zz != curr->_colors.end(); ++zz ) {
476                             if ( item == *zz ) {
477                                 found = true;
478                                 paletteName = curr->_name;
479                                 break;
480                             } else {
481                                 index++;
482                             }
483                         }
484                     }
486                     if ( !paletteName.empty() ) {
487                         gchar* str = g_strdup_printf("%d|", index);
488                         paletteName.insert( 0, str );
489                         g_free(str);
490                         str = 0;
492                         if ( bruteForce( document, rroot, paletteName, item->def.getR(), item->def.getG(), item->def.getB() ) ) {
493                             sp_document_done( document , SP_VERB_DIALOG_SWATCHES, 
494                                               _("Change color definition"));
495                         }
496                     }
497                 }
498             }
499         }
500     }
504 Gtk::Widget* ColorItem::getPreview(PreviewStyle style, ViewType view, Inkscape::IconSize size)
506     Gtk::Widget* widget = 0;
507     if ( style == PREVIEW_STYLE_BLURB ) {
508         Gtk::Label *lbl = new Gtk::Label(def.descr);
509         lbl->set_alignment(Gtk::ALIGN_LEFT, Gtk::ALIGN_CENTER);
510         widget = lbl;
511     } else {
512         Glib::ustring blank("          ");
513         if ( size == Inkscape::ICON_SIZE_MENU || size == Inkscape::ICON_SIZE_DECORATION ) {
514             blank = " ";
515         }
517         GtkWidget* eekWidget = eek_preview_new();
518         EekPreview * preview = EEK_PREVIEW(eekWidget);
519         Gtk::Widget* newBlot = Glib::wrap(eekWidget);
521         eek_preview_set_color( preview, (def.getR() << 8) | def.getR(), (def.getG() << 8) | def.getG(), (def.getB() << 8) | def.getB());
523         eek_preview_set_details( preview, (::PreviewStyle)style, (::ViewType)view, (::GtkIconSize)size );
524         eek_preview_set_linked( preview, (LinkType)((_linkSrc ? PREVIEW_LINK_IN:0)
525                                                     | (_listeners.empty() ? 0:PREVIEW_LINK_OUT)
526                                                     | (_isLive ? PREVIEW_LINK_OTHER:0)) );
528         def.addCallback( _colorDefChanged, this );
530         GValue val = {0, {{0}, {0}}};
531         g_value_init( &val, G_TYPE_BOOLEAN );
532         g_value_set_boolean( &val, FALSE );
533         g_object_set_property( G_OBJECT(preview), "focus-on-click", &val );
535 /*
536         Gtk::Button *btn = new Gtk::Button(blank);
537         Gdk::Color color;
538         color.set_rgb((_r << 8)|_r, (_g << 8)|_g, (_b << 8)|_b);
539         btn->modify_bg(Gtk::STATE_NORMAL, color);
540         btn->modify_bg(Gtk::STATE_ACTIVE, color);
541         btn->modify_bg(Gtk::STATE_PRELIGHT, color);
542         btn->modify_bg(Gtk::STATE_SELECTED, color);
544         Gtk::Widget* newBlot = btn;
545 */
547         tips.set_tip((*newBlot), def.descr);
549 /*
550         newBlot->signal_clicked().connect( sigc::mem_fun(*this, &ColorItem::buttonClicked) );
552         sigc::signal<void> type_signal_something;
553 */
555         g_signal_connect( G_OBJECT(newBlot->gobj()),
556                           "clicked",
557                           G_CALLBACK(handleClick),
558                           this);
560         g_signal_connect( G_OBJECT(newBlot->gobj()),
561                           "alt-clicked",
562                           G_CALLBACK(handleSecondaryClick),
563                           this);
565         g_signal_connect( G_OBJECT(newBlot->gobj()),
566                           "button-press-event",
567                           G_CALLBACK(handleButtonPress),
568                           this);
570         gtk_drag_source_set( GTK_WIDGET(newBlot->gobj()),
571                              GDK_BUTTON1_MASK,
572                              sourceColorEntries,
573                              G_N_ELEMENTS(sourceColorEntries),
574                              GdkDragAction(GDK_ACTION_MOVE | GDK_ACTION_COPY) );
576         g_signal_connect( G_OBJECT(newBlot->gobj()),
577                           "drag-data-get",
578                           G_CALLBACK(ColorItem::_dragGetColorData),
579                           this);
581         g_signal_connect( G_OBJECT(newBlot->gobj()),
582                           "drag-begin",
583                           G_CALLBACK(dragBegin),
584                           this );
586 //         g_signal_connect( G_OBJECT(newBlot->gobj()),
587 //                           "drag-drop",
588 //                           G_CALLBACK(dragDropColorData),
589 //                           this);
591         if ( def.isEditable() )
592         {
593             gtk_drag_dest_set( GTK_WIDGET(newBlot->gobj()),
594                                GTK_DEST_DEFAULT_ALL,
595                                destColorTargets,
596                                G_N_ELEMENTS(destColorTargets),
597                                GdkDragAction(GDK_ACTION_COPY | GDK_ACTION_MOVE) );
600             g_signal_connect( G_OBJECT(newBlot->gobj()),
601                               "drag-data-received",
602                               G_CALLBACK(_dropDataIn),
603                               this );
604         }
606         g_signal_connect( G_OBJECT(newBlot->gobj()),
607                           "destroy",
608                           G_CALLBACK(dieDieDie),
609                           this);
612         widget = newBlot;
613     }
615     _previews.push_back( widget );
617     return widget;
620 void ColorItem::buttonClicked(bool secondary)
622     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
623     if (desktop) {
624         char const * attrName = secondary ? "stroke" : "fill";
625         guint32 rgba = (def.getR() << 24) | (def.getG() << 16) | (def.getB() << 8) | 0xff;
626         gchar c[64];
627         sp_svg_write_color(c, sizeof(c), rgba);
629         SPCSSAttr *css = sp_repr_css_attr_new();
630         sp_repr_css_set_property( css, attrName, c );
631         sp_desktop_set_style(desktop, css);
633         sp_repr_css_attr_unref(css);
634         sp_document_done (sp_desktop_document (desktop), SP_VERB_DIALOG_SWATCHES, 
635                           secondary? _("Set stroke color from swatch") : _("Set fill color from swatch"));
636     }
642 static char* trim( char* str ) {
643     char* ret = str;
644     while ( *str && (*str == ' ' || *str == '\t') ) {
645         str++;
646     }
647     ret = str;
648     while ( *str ) {
649         str++;
650     }
651     str--;
652     while ( str > ret && ( *str == ' ' || *str == '\t' ) || *str == '\r' || *str == '\n' ) {
653         *str-- = 0;
654     }
655     return ret;
658 void skipWhitespace( char*& str ) {
659     while ( *str == ' ' || *str == '\t' ) {
660         str++;
661     }
664 bool parseNum( char*& str, int& val ) {
665     val = 0;
666     while ( '0' <= *str && *str <= '9' ) {
667         val = val * 10 + (*str - '0');
668         str++;
669     }
670     bool retval = !(*str == 0 || *str == ' ' || *str == '\t' || *str == '\r' || *str == '\n');
671     return retval;
675 static bool getBlock( std::string& dst, guchar ch, std::string const str )
677     bool good = false;
678     std::string::size_type pos = str.find(ch);
679     if ( pos != std::string::npos )
680     {
681         std::string::size_type pos2 = str.find( '(', pos );
682         if ( pos2 != std::string::npos ) {
683             std::string::size_type endPos = str.find( ')', pos2 );
684             if ( endPos != std::string::npos ) {
685                 dst = str.substr( pos2 + 1, (endPos - pos2 - 1) );
686                 good = true;
687             }
688         }
689     }
690     return good;
693 static bool popVal( guint64& numVal, std::string& str )
695     bool good = false;
696     std::string::size_type endPos = str.find(',');
697     if ( endPos == std::string::npos ) {
698         endPos = str.length();
699     }
701     if ( endPos != std::string::npos && endPos > 0 ) {
702         std::string xxx = str.substr( 0, endPos );
703         const gchar* ptr = xxx.c_str();
704         gchar* endPtr = 0;
705         numVal = g_ascii_strtoull( ptr, &endPtr, 10 );
706         if ( (numVal == G_MAXUINT64) && (ERANGE == errno) ) {
707             // overflow
708         } else if ( (numVal == 0) && (endPtr == ptr) ) {
709             // failed conversion
710         } else {
711             good = true;
712             str.erase( 0, endPos + 1 );
713         }
714     }
716     return good;
719 void ColorItem::_wireMagicColors( void* p )
721     JustForNow* onceMore = reinterpret_cast<JustForNow*>(p);
722     if ( onceMore )
723     {
724         for ( std::vector<ColorItem*>::iterator it = onceMore->_colors.begin(); it != onceMore->_colors.end(); ++it )
725         {
726             std::string::size_type pos = (*it)->def.descr.find("*{");
727             if ( pos != std::string::npos )
728             {
729                 std::string subby = (*it)->def.descr.substr( pos + 2 );
730                 std::string::size_type endPos = subby.find("}*");
731                 if ( endPos != std::string::npos )
732                 {
733                     subby.erase( endPos );
734                     //g_message("FOUND MAGIC at '%s'", (*it)->def.descr.c_str());
735                     //g_message("               '%s'", subby.c_str());
737                     if ( subby.find('E') != std::string::npos )
738                     {
739                         (*it)->def.setEditable( true );
740                     }
742                     if ( subby.find('L') != std::string::npos )
743                     {
744                         (*it)->_isLive = true;
745                     }
747                     std::string part;
748                     // Tint. index + 1 more val.
749                     if ( getBlock( part, 'T', subby ) ) {
750                         guint64 colorIndex = 0;
751                         if ( popVal( colorIndex, part ) ) {
752                             guint64 percent = 0;
753                             if ( popVal( percent, part ) ) {
754                                 (*it)->_linkTint( *(onceMore->_colors[colorIndex]), percent );
755                             }
756                         }
757                     }
759                     // Shade/tone. index + 1 or 2 more val.
760                     if ( getBlock( part, 'S', subby ) ) {
761                         guint64 colorIndex = 0;
762                         if ( popVal( colorIndex, part ) ) {
763                             guint64 percent = 0;
764                             if ( popVal( percent, part ) ) {
765                                 guint64 grayLevel = 0;
766                                 if ( !popVal( grayLevel, part ) ) {
767                                     grayLevel = 0;
768                                 }
769                                 (*it)->_linkTone( *(onceMore->_colors[colorIndex]), percent, grayLevel );
770                             }
771                         }
772                     }
774                 }
775             }
776         }
777     }
781 void ColorItem::_linkTint( ColorItem& other, int percent )
783     if ( !_linkSrc )
784     {
785         other._listeners.push_back(this);
786         _linkIsTone = false;
787         _linkPercent = percent;
788         if ( _linkPercent > 100 )
789             _linkPercent = 100;
790         if ( _linkPercent < 0 )
791             _linkPercent = 0;
792         _linkGray = 0;
793         _linkSrc = &other;
795         ColorItem::_colorDefChanged(&other);
796     }
799 void ColorItem::_linkTone( ColorItem& other, int percent, int grayLevel )
801     if ( !_linkSrc )
802     {
803         other._listeners.push_back(this);
804         _linkIsTone = true;
805         _linkPercent = percent;
806         if ( _linkPercent > 100 )
807             _linkPercent = 100;
808         if ( _linkPercent < 0 )
809             _linkPercent = 0;
810         _linkGray = grayLevel;
811         _linkSrc = &other;
813         ColorItem::_colorDefChanged(&other);
814     }
818 void _loadPaletteFile( gchar const *filename )
820     char block[1024];
821     FILE *f = Inkscape::IO::fopen_utf8name( filename, "r" );
822     if ( f ) {
823         char* result = fgets( block, sizeof(block), f );
824         if ( result ) {
825             if ( strncmp( "GIMP Palette", block, 12 ) == 0 ) {
826                 bool inHeader = true;
827                 bool hasErr = false;
829                 JustForNow *onceMore = new JustForNow();
831                 do {
832                     result = fgets( block, sizeof(block), f );
833                     block[sizeof(block) - 1] = 0;
834                     if ( result ) {
835                         if ( block[0] == '#' ) {
836                             // ignore comment
837                         } else {
838                             char *ptr = block;
839                             // very simple check for header versus entry
840                             while ( *ptr == ' ' || *ptr == '\t' ) {
841                                 ptr++;
842                             }
843                             if ( *ptr == 0 ) {
844                                 // blank line. skip it.
845                             } else if ( '0' <= *ptr && *ptr <= '9' ) {
846                                 // should be an entry link
847                                 inHeader = false;
848                                 ptr = block;
849                                 Glib::ustring name("");
850                                 int r = 0;
851                                 int g = 0;
852                                 int b = 0;
853                                 skipWhitespace(ptr);
854                                 if ( *ptr ) {
855                                     hasErr = parseNum(ptr, r);
856                                     if ( !hasErr ) {
857                                         skipWhitespace(ptr);
858                                         hasErr = parseNum(ptr, g);
859                                     }
860                                     if ( !hasErr ) {
861                                         skipWhitespace(ptr);
862                                         hasErr = parseNum(ptr, b);
863                                     }
864                                     if ( !hasErr && *ptr ) {
865                                         char* n = trim(ptr);
866                                         if (n != NULL) {
867                                             name = n;
868                                         }
869                                     }
870                                     if ( !hasErr ) {
871                                         // Add the entry now
872                                         Glib::ustring nameStr(name);
873                                         ColorItem* item = new ColorItem( r, g, b, nameStr );
874                                         onceMore->_colors.push_back(item);
875                                     }
876                                 } else {
877                                     hasErr = true;
878                                 }
879                             } else {
880                                 if ( !inHeader ) {
881                                     // Hmmm... probably bad. Not quite the format we want?
882                                     hasErr = true;
883                                 } else {
884                                     char* sep = strchr(result, ':');
885                                     if ( sep ) {
886                                         *sep = 0;
887                                         char* val = trim(sep + 1);
888                                         char* name = trim(result);
889                                         if ( *name ) {
890                                             if ( strcmp( "Name", name ) == 0 )
891                                             {
892                                                 onceMore->_name = val;
893                                             }
894                                             else if ( strcmp( "Columns", name ) == 0 )
895                                             {
896                                                 gchar* endPtr = 0;
897                                                 guint64 numVal = g_ascii_strtoull( val, &endPtr, 10 );
898                                                 if ( (numVal == G_MAXUINT64) && (ERANGE == errno) ) {
899                                                     // overflow
900                                                 } else if ( (numVal == 0) && (endPtr == val) ) {
901                                                     // failed conversion
902                                                 } else {
903                                                     onceMore->_prefWidth = numVal;
904                                                 }
905                                             }
906                                         } else {
907                                             // error
908                                             hasErr = true;
909                                         }
910                                     } else {
911                                         // error
912                                         hasErr = true;
913                                     }
914                                 }
915                             }
916                         }
917                     }
918                 } while ( result && !hasErr );
919                 if ( !hasErr ) {
920                     possible.push_back(onceMore);
921 #if ENABLE_MAGIC_COLORS
922                     ColorItem::_wireMagicColors( onceMore );
923 #endif // ENABLE_MAGIC_COLORS
924                 } else {
925                     delete onceMore;
926                 }
927             }
928         }
930         fclose(f);
931     }
934 static void loadEmUp()
936     static bool beenHere = false;
937     if ( !beenHere ) {
938         beenHere = true;
940         std::list<gchar *> sources;
941         sources.push_back( profile_path("palettes") );
942         sources.push_back( g_strdup(INKSCAPE_PALETTESDIR) );
943         sources.push_back( g_strdup(CREATE_PALETTESDIR) );
945         // Use this loop to iterate through a list of possible document locations.
946         while (!sources.empty()) {
947             gchar *dirname = sources.front();
949             if ( Inkscape::IO::file_test( dirname, (GFileTest)(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR) ) ) {
950                 GError *err = 0;
951                 GDir *directory = g_dir_open(dirname, 0, &err);
952                 if (!directory) {
953                     gchar *safeDir = Inkscape::IO::sanitizeString(dirname);
954                     g_warning(_("Palettes directory (%s) is unavailable."), safeDir);
955                     g_free(safeDir);
956                 } else {
957                     gchar *filename = 0;
958                     while ((filename = (gchar *)g_dir_read_name(directory)) != NULL) {
959                         gchar* lower = g_ascii_strdown( filename, -1 );
960 //                        if ( g_str_has_suffix(lower, ".gpl") ) {
961                             gchar* full = g_build_filename(dirname, filename, NULL);
962                             if ( !Inkscape::IO::file_test( full, (GFileTest)(G_FILE_TEST_IS_DIR ) ) ) {
963                                 _loadPaletteFile(full);
964                             }
965                             g_free(full);
966 //                      }
967                         g_free(lower);
968                     }
969                     g_dir_close(directory);
970                 }
971             }
973             // toss the dirname
974             g_free(dirname);
975             sources.pop_front();
976         }
977     }
988 SwatchesPanel& SwatchesPanel::getInstance()
990     return *new SwatchesPanel();
994 /**
995  * Constructor
996  */
997 SwatchesPanel::SwatchesPanel(gchar const* prefsPath) :
998     Inkscape::UI::Widget::Panel("", prefsPath, SP_VERB_DIALOG_SWATCHES, "", true),
999     _holder(0)
1001     Gtk::RadioMenuItem* hotItem = 0;
1002     _holder = new PreviewHolder();
1003     loadEmUp();
1005     if ( !possible.empty() ) {
1006         JustForNow* first = 0;
1007         gchar const* targetName = 0;
1008         if ( _prefs_path ) {
1009             targetName = prefs_get_string_attribute( _prefs_path, "palette" );
1010             if ( targetName ) {
1011                 for ( std::vector<JustForNow*>::iterator iter = possible.begin(); iter != possible.end(); ++iter ) {
1012                     if ( (*iter)->_name == targetName ) {
1013                         first = *iter;
1014                         break;
1015                     }
1016                 }
1017             }
1018         }
1020         if ( !first ) {
1021             first = possible.front();
1022         }
1024         if ( first->_prefWidth > 0 ) {
1025             _holder->setColumnPref( first->_prefWidth );
1026         }
1027         _holder->freezeUpdates();
1028         for ( std::vector<ColorItem*>::iterator it = first->_colors.begin(); it != first->_colors.end(); it++ ) {
1029             _holder->addPreview(*it);
1030         }
1031         _holder->thawUpdates();
1033         Gtk::RadioMenuItem::Group groupOne;
1034         int i = 0;
1035         for ( std::vector<JustForNow*>::iterator it = possible.begin(); it != possible.end(); it++ ) {
1036             JustForNow* curr = *it;
1037             Gtk::RadioMenuItem* single = manage(new Gtk::RadioMenuItem(groupOne, curr->_name));
1038             if ( curr == first ) {
1039                 hotItem = single;
1040             }
1041             _regItem( single, 3, i );
1042             i++;
1043         }
1045     }
1048     _getContents()->pack_start(*_holder, Gtk::PACK_EXPAND_WIDGET);
1049     _setTargetFillable(_holder);
1051     show_all_children();
1053     restorePanelPrefs();
1054     if ( hotItem ) {
1055         hotItem->set_active();
1056     }
1059 SwatchesPanel::~SwatchesPanel()
1063 void SwatchesPanel::setOrientation( Gtk::AnchorType how )
1065     // Must call the parent class or bad things might happen
1066     Inkscape::UI::Widget::Panel::setOrientation( how );
1068     if ( _holder )
1069     {
1070         _holder->setOrientation( Gtk::ANCHOR_SOUTH );
1071     }
1074 void SwatchesPanel::_handleAction( int setId, int itemId )
1076     switch( setId ) {
1077         case 3:
1078         {
1079             if ( itemId >= 0 && itemId < static_cast<int>(possible.size()) ) {
1080                 _holder->clear();
1081                 JustForNow* curr = possible[itemId];
1083                 if ( _prefs_path ) {
1084                     prefs_set_string_attribute( _prefs_path, "palette", curr->_name.c_str() );
1085                 }
1087                 if ( curr->_prefWidth > 0 ) {
1088                     _holder->setColumnPref( curr->_prefWidth );
1089                 }
1090                 _holder->freezeUpdates();
1091                 for ( std::vector<ColorItem*>::iterator it = curr->_colors.begin(); it != curr->_colors.end(); it++ ) {
1092                     _holder->addPreview(*it);
1093                 }
1094                 _holder->thawUpdates();
1095             }
1096         }
1097         break;
1098     }
1101 } //namespace Dialogs
1102 } //namespace UI
1103 } //namespace Inkscape
1106 /*
1107   Local Variables:
1108   mode:c++
1109   c-file-style:"stroustrup"
1110   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1111   indent-tabs-mode:nil
1112   fill-column:99
1113   End:
1114 */
1115 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :