Code

Fix: [ 1829427 ] PNG export via cmd line is restricted to 65535x65535
[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 {
44 SwatchesPanel* SwatchesPanel::instance = 0;
47 ColorItem::ColorItem( unsigned int r, unsigned int g, unsigned int b, Glib::ustring& name ) :
48     def( r, g, b, name ),
49     _isLive(false),
50     _linkIsTone(false),
51     _linkPercent(0),
52     _linkGray(0),
53     _linkSrc(0)
54 {
55 }
57 ColorItem::~ColorItem()
58 {
59 }
61 ColorItem::ColorItem(ColorItem const &other) :
62     Inkscape::UI::Previewable()
63 {
64     if ( this != &other ) {
65         *this = other;
66     }
67 }
69 ColorItem &ColorItem::operator=(ColorItem const &other)
70 {
71     if ( this != &other ) {
72         def = other.def;
74         // TODO - correct linkage
75         _linkSrc = other._linkSrc;
76         g_message("Erk!");
77     }
78     return *this;
79 }
82 class JustForNow
83 {
84 public:
85     JustForNow() : _prefWidth(0) {}
87     Glib::ustring _name;
88     int _prefWidth;
89     std::vector<ColorItem*> _colors;
90 };
92 static std::vector<JustForNow*> possible;
96 typedef enum {
97     APP_X_INKY_COLOR_ID = 0,
98     APP_X_INKY_COLOR = 0,
99     APP_X_COLOR,
100     TEXT_DATA
101 } colorFlavorType;
103 static const GtkTargetEntry sourceColorEntries[] = {
104 #if ENABLE_MAGIC_COLORS
105 //    {"application/x-inkscape-color-id", GTK_TARGET_SAME_APP, APP_X_INKY_COLOR_ID},
106     {"application/x-inkscape-color", 0, APP_X_INKY_COLOR},
107 #endif // ENABLE_MAGIC_COLORS
108     {"application/x-color", 0, APP_X_COLOR},
109     {"text/plain", 0, TEXT_DATA},
110 };
112 void ColorItem::_dragGetColorData( GtkWidget *widget,
113                                    GdkDragContext *drag_context,
114                                    GtkSelectionData *data,
115                                    guint info,
116                                    guint time,
117                                    gpointer user_data)
119     (void)widget;
120     (void)drag_context;
121     (void)time;
122     static GdkAtom typeXColor = gdk_atom_intern("application/x-color", FALSE);
123     static GdkAtom typeText = gdk_atom_intern("text/plain", FALSE);
125     ColorItem* item = reinterpret_cast<ColorItem*>(user_data);
126     if ( info == TEXT_DATA ) {
127         gchar* tmp = g_strdup_printf("#%02x%02x%02x", item->def.getR(), item->def.getG(), item->def.getB() );
129         gtk_selection_data_set( data,
130                                 typeText,
131                                 8, // format
132                                 (guchar*)tmp,
133                                 strlen((const char*)tmp) + 1);
134         g_free(tmp);
135         tmp = 0;
136     } else if ( info == APP_X_INKY_COLOR ) {
137         Glib::ustring paletteName;
139         // Find where this thing came from
140         bool found = false;
141         int index = 0;
142         for ( std::vector<JustForNow*>::iterator it = possible.begin(); it != possible.end() && !found; ++it ) {
143             JustForNow* curr = *it;
144             index = 0;
145             for ( std::vector<ColorItem*>::iterator zz = curr->_colors.begin(); zz != curr->_colors.end(); ++zz ) {
146                 if ( item == *zz ) {
147                     found = true;
148                     paletteName = curr->_name;
149                     break;
150                 } else {
151                     index++;
152                 }
153             }
154         }
156 //         if ( found ) {
157 //             g_message("Found the color at entry %d in palette '%s'", index, paletteName.c_str() );
158 //         } else {
159 //             g_message("Unable to find the color");
160 //         }
161         int itemCount = 4 + 2 + 1 + paletteName.length();
163         guint16* tmp = new guint16[itemCount];
164         tmp[0] = (item->def.getR() << 8) | item->def.getR();
165         tmp[1] = (item->def.getG() << 8) | item->def.getG();
166         tmp[2] = (item->def.getB() << 8) | item->def.getB();
167         tmp[3] = 0xffff;
168         tmp[4] = (item->_isLive || !item->_listeners.empty() || (item->_linkSrc != 0) ) ? 1 : 0;
170         tmp[5] = index;
171         tmp[6] = paletteName.length();
172         for ( unsigned int i = 0; i < paletteName.length(); i++ ) {
173             tmp[7 + i] = paletteName[i];
174         }
175         gtk_selection_data_set( data,
176                                 typeXColor,
177                                 16, // format
178                                 reinterpret_cast<const guchar*>(tmp),
179                                 itemCount * 2);
180         delete[] tmp;
181     } else {
182         guint16 tmp[4];
183         tmp[0] = (item->def.getR() << 8) | item->def.getR();
184         tmp[1] = (item->def.getG() << 8) | item->def.getG();
185         tmp[2] = (item->def.getB() << 8) | item->def.getB();
186         tmp[3] = 0xffff;
187         gtk_selection_data_set( data,
188                                 typeXColor,
189                                 16, // format
190                                 reinterpret_cast<const guchar*>(tmp),
191                                 (3+1) * 2);
192     }
195 static void dragBegin( GtkWidget *widget, GdkDragContext* dc, gpointer data )
197     (void)widget;
198     ColorItem* item = reinterpret_cast<ColorItem*>(data);
199     if ( item )
200     {
201         Glib::RefPtr<Gdk::Pixbuf> thumb = Gdk::Pixbuf::create( Gdk::COLORSPACE_RGB, false, 8, 32, 24 );
202         guint32 fillWith = (0xff000000 & (item->def.getR() << 24))
203                          | (0x00ff0000 & (item->def.getG() << 16))
204                          | (0x0000ff00 & (item->def.getB() <<  8));
205         thumb->fill( fillWith );
206         gtk_drag_set_icon_pixbuf( dc, thumb->gobj(), 0, 0 );
207     }
211 //"drag-drop"
212 // gboolean dragDropColorData( GtkWidget *widget,
213 //                             GdkDragContext *drag_context,
214 //                             gint x,
215 //                             gint y,
216 //                             guint time,
217 //                             gpointer user_data)
218 // {
219 // // TODO finish
221 //     return TRUE;
222 // }
224 static void handleClick( GtkWidget* widget, gpointer callback_data ) {
225     (void)widget;
226     ColorItem* item = reinterpret_cast<ColorItem*>(callback_data);
227     if ( item ) {
228         item->buttonClicked(false);
229     }
232 static void handleSecondaryClick( GtkWidget* widget, gint arg1, gpointer callback_data ) {
233     (void)widget;
234     (void)arg1;
235     ColorItem* item = reinterpret_cast<ColorItem*>(callback_data);
236     if ( item ) {
237         item->buttonClicked(true);
238     }
241 static GtkWidget* popupMenu = 0;
242 static ColorItem* bounceTarget = 0;
244 static void redirClick( GtkMenuItem *menuitem, gpointer user_data )
246     (void)user_data;
247     if ( bounceTarget ) {
248         handleClick( GTK_WIDGET(menuitem), bounceTarget );
249     }
252 static void redirSecondaryClick( GtkMenuItem *menuitem, gpointer user_data )
254     (void)user_data;
255     if ( bounceTarget ) {
256         handleSecondaryClick( GTK_WIDGET(menuitem), 0, bounceTarget );
257     }
260 static gboolean handleButtonPress( GtkWidget* widget, GdkEventButton* event, gpointer user_data)
262     (void)widget;
263     gboolean handled = FALSE;
265     if ( (event->button == 3) && (event->type == GDK_BUTTON_PRESS) ) {
266         if ( !popupMenu ) {
267             popupMenu = gtk_menu_new();
268             GtkWidget* child = 0;
270             child = gtk_menu_item_new_with_label("Set fill");
271             g_signal_connect( G_OBJECT(child),
272                               "activate",
273                               G_CALLBACK(redirClick),
274                               user_data);
275             gtk_menu_shell_append(GTK_MENU_SHELL(popupMenu), child);
277             child = gtk_menu_item_new_with_label("Set stroke");
279             g_signal_connect( G_OBJECT(child),
280                               "activate",
281                               G_CALLBACK(redirSecondaryClick),
282                               user_data);
283             gtk_menu_shell_append(GTK_MENU_SHELL(popupMenu), child);
285             gtk_widget_show_all(popupMenu);
286         }
288         ColorItem* item = reinterpret_cast<ColorItem*>(user_data);
289         if ( item ) {
290             bounceTarget = item;
291             if ( popupMenu ) {
292                 gtk_menu_popup(GTK_MENU(popupMenu), NULL, NULL, NULL, NULL, event->button, event->time);
293                 handled = TRUE;
294             }
295         }
296     }
298     return handled;
301 static void dieDieDie( GtkObject *obj, gpointer user_data )
303     g_message("die die die %p  %p", obj, user_data );
306 static const GtkTargetEntry destColorTargets[] = {
307 #if ENABLE_MAGIC_COLORS
308 //    {"application/x-inkscape-color-id", GTK_TARGET_SAME_APP, APP_X_INKY_COLOR_ID},
309     {"application/x-inkscape-color", 0, APP_X_INKY_COLOR},
310 #endif // ENABLE_MAGIC_COLORS
311     {"application/x-color", 0, APP_X_COLOR},
312 };
314 #include "color.h" // for SP_RGBA32_U_COMPOSE
316 void ColorItem::_dropDataIn( GtkWidget *widget,
317                              GdkDragContext *drag_context,
318                              gint x, gint y,
319                              GtkSelectionData *data,
320                              guint info,
321                              guint event_time,
322                              gpointer user_data)
324     (void)widget;
325     (void)drag_context;
326     (void)x;
327     (void)y;
328     (void)event_time;
329 //     g_message("    droppy droppy   %d", info);
330      switch (info) {
331          case APP_X_INKY_COLOR:
332          {
333              if ( data->length >= 8 ) {
334                  // Careful about endian issues.
335                  guint16* dataVals = (guint16*)data->data;
336                  if ( user_data ) {
337                      ColorItem* item = reinterpret_cast<ColorItem*>(user_data);
338                      if ( item->def.isEditable() ) {
339                          // Shove on in the new value
340                          item->def.setRGB( 0x0ff & (dataVals[0] >> 8), 0x0ff & (dataVals[1] >> 8), 0x0ff & (dataVals[2] >> 8) );
341                      }
342                  }
343              }
344              break;
345          }
346          case APP_X_COLOR:
347          {
348              if ( data->length == 8 ) {
349                  // Careful about endian issues.
350                  guint16* dataVals = (guint16*)data->data;
351 //                  {
352 //                      gchar c[64] = {0};
353 //                      sp_svg_write_color( c, 64,
354 //                                          SP_RGBA32_U_COMPOSE(
355 //                                              0x0ff & (dataVals[0] >> 8),
356 //                                              0x0ff & (dataVals[1] >> 8),
357 //                                              0x0ff & (dataVals[2] >> 8),
358 //                                              0xff // can't have transparency in the color itself
359 //                                              //0x0ff & (data->data[3] >> 8),
360 //                                              ));
361 //                  }
362                  if ( user_data ) {
363                      ColorItem* item = reinterpret_cast<ColorItem*>(user_data);
364                      if ( item->def.isEditable() ) {
365                          // Shove on in the new value
366                          item->def.setRGB( 0x0ff & (dataVals[0] >> 8), 0x0ff & (dataVals[1] >> 8), 0x0ff & (dataVals[2] >> 8) );
367                      }
368                  }
369              }
370              break;
371          }
372          default:
373              g_message("unknown drop type");
374      }
378 static bool bruteForce( SPDocument* document, Inkscape::XML::Node* node, Glib::ustring const& match, int r, int g, int b )
380     bool changed = false;
382     if ( node ) {
383         gchar const * val = node->attribute("inkscape:x-fill-tag");
384         if ( val  && (match == val) ) {
385             SPObject *obj = document->getObjectByRepr( node );
387             gchar c[64] = {0};
388             sp_svg_write_color( c, sizeof(c), SP_RGBA32_U_COMPOSE( r, g, b, 0xff ) );
389             SPCSSAttr *css = sp_repr_css_attr_new();
390             sp_repr_css_set_property( css, "fill", c );
392             sp_desktop_apply_css_recursive( (SPItem*)obj, css, true );
393             ((SPItem*)obj)->updateRepr();
395             changed = true;
396         }
398         val = node->attribute("inkscape:x-stroke-tag");
399         if ( val  && (match == val) ) {
400             SPObject *obj = document->getObjectByRepr( node );
402             gchar c[64] = {0};
403             sp_svg_write_color( c, sizeof(c), SP_RGBA32_U_COMPOSE( r, g, b, 0xff ) );
404             SPCSSAttr *css = sp_repr_css_attr_new();
405             sp_repr_css_set_property( css, "stroke", c );
407             sp_desktop_apply_css_recursive( (SPItem*)obj, css, true );
408             ((SPItem*)obj)->updateRepr();
410             changed = true;
411         }
413         Inkscape::XML::Node* first = node->firstChild();
414         changed |= bruteForce( document, first, match, r, g, b );
416         changed |= bruteForce( document, node->next(), match, r, g, b );
417     }
419     return changed;
422 void ColorItem::_colorDefChanged(void* data)
424     ColorItem* item = reinterpret_cast<ColorItem*>(data);
425     if ( item ) {
426         for ( std::vector<Gtk::Widget*>::iterator it =  item->_previews.begin(); it != item->_previews.end(); ++it ) {
427             Gtk::Widget* widget = *it;
428             if ( IS_EEK_PREVIEW(widget->gobj()) ) {
429                 EekPreview * preview = EEK_PREVIEW(widget->gobj());
430                 eek_preview_set_color( preview,
431                                        (item->def.getR() << 8) | item->def.getR(),
432                                        (item->def.getG() << 8) | item->def.getG(),
433                                        (item->def.getB() << 8) | item->def.getB() );
435                 eek_preview_set_linked( preview, (LinkType)((item->_linkSrc ? PREVIEW_LINK_IN:0)
436                                                             | (item->_listeners.empty() ? 0:PREVIEW_LINK_OUT)
437                                                             | (item->_isLive ? PREVIEW_LINK_OTHER:0)) );
439                 widget->queue_draw();
440             }
441         }
443         for ( std::vector<ColorItem*>::iterator it = item->_listeners.begin(); it != item->_listeners.end(); ++it ) {
444             guint r = item->def.getR();
445             guint g = item->def.getG();
446             guint b = item->def.getB();
448             if ( (*it)->_linkIsTone ) {
449                 r = ( ((*it)->_linkPercent * (*it)->_linkGray) + ((100 - (*it)->_linkPercent) * r) ) / 100;
450                 g = ( ((*it)->_linkPercent * (*it)->_linkGray) + ((100 - (*it)->_linkPercent) * g) ) / 100;
451                 b = ( ((*it)->_linkPercent * (*it)->_linkGray) + ((100 - (*it)->_linkPercent) * b) ) / 100;
452             } else {
453                 r = ( ((*it)->_linkPercent * 255) + ((100 - (*it)->_linkPercent) * r) ) / 100;
454                 g = ( ((*it)->_linkPercent * 255) + ((100 - (*it)->_linkPercent) * g) ) / 100;
455                 b = ( ((*it)->_linkPercent * 255) + ((100 - (*it)->_linkPercent) * b) ) / 100;
456             }
458             (*it)->def.setRGB( r, g, b );
459         }
462         // Look for objects using this color
463         {
464             SPDesktop *desktop = SP_ACTIVE_DESKTOP;
465             if ( desktop ) {
466                 SPDocument* document = sp_desktop_document( desktop );
467                 Inkscape::XML::Node *rroot =  sp_document_repr_root( document );
468                 if ( rroot ) {
470                     // Find where this thing came from
471                     Glib::ustring paletteName;
472                     bool found = false;
473                     int index = 0;
474                     for ( std::vector<JustForNow*>::iterator it2 = possible.begin(); it2 != possible.end() && !found; ++it2 ) {
475                         JustForNow* curr = *it2;
476                         index = 0;
477                         for ( std::vector<ColorItem*>::iterator zz = curr->_colors.begin(); zz != curr->_colors.end(); ++zz ) {
478                             if ( item == *zz ) {
479                                 found = true;
480                                 paletteName = curr->_name;
481                                 break;
482                             } else {
483                                 index++;
484                             }
485                         }
486                     }
488                     if ( !paletteName.empty() ) {
489                         gchar* str = g_strdup_printf("%d|", index);
490                         paletteName.insert( 0, str );
491                         g_free(str);
492                         str = 0;
494                         if ( bruteForce( document, rroot, paletteName, item->def.getR(), item->def.getG(), item->def.getB() ) ) {
495                             sp_document_done( document , SP_VERB_DIALOG_SWATCHES, 
496                                               _("Change color definition"));
497                         }
498                     }
499                 }
500             }
501         }
502     }
506 Gtk::Widget* ColorItem::getPreview(PreviewStyle style, ViewType view, Inkscape::IconSize size)
508     Gtk::Widget* widget = 0;
509     if ( style == PREVIEW_STYLE_BLURB ) {
510         Gtk::Label *lbl = new Gtk::Label(def.descr);
511         lbl->set_alignment(Gtk::ALIGN_LEFT, Gtk::ALIGN_CENTER);
512         widget = lbl;
513     } else {
514         Glib::ustring blank("          ");
515         if ( size == Inkscape::ICON_SIZE_MENU || size == Inkscape::ICON_SIZE_DECORATION ) {
516             blank = " ";
517         }
519         GtkWidget* eekWidget = eek_preview_new();
520         EekPreview * preview = EEK_PREVIEW(eekWidget);
521         Gtk::Widget* newBlot = Glib::wrap(eekWidget);
523         eek_preview_set_color( preview, (def.getR() << 8) | def.getR(), (def.getG() << 8) | def.getG(), (def.getB() << 8) | def.getB());
525         eek_preview_set_details( preview, (::PreviewStyle)style, (::ViewType)view, (::GtkIconSize)size );
526         eek_preview_set_linked( preview, (LinkType)((_linkSrc ? PREVIEW_LINK_IN:0)
527                                                     | (_listeners.empty() ? 0:PREVIEW_LINK_OUT)
528                                                     | (_isLive ? PREVIEW_LINK_OTHER:0)) );
530         def.addCallback( _colorDefChanged, this );
532         GValue val = {0, {{0}, {0}}};
533         g_value_init( &val, G_TYPE_BOOLEAN );
534         g_value_set_boolean( &val, FALSE );
535         g_object_set_property( G_OBJECT(preview), "focus-on-click", &val );
537 /*
538         Gtk::Button *btn = new Gtk::Button(blank);
539         Gdk::Color color;
540         color.set_rgb((_r << 8)|_r, (_g << 8)|_g, (_b << 8)|_b);
541         btn->modify_bg(Gtk::STATE_NORMAL, color);
542         btn->modify_bg(Gtk::STATE_ACTIVE, color);
543         btn->modify_bg(Gtk::STATE_PRELIGHT, color);
544         btn->modify_bg(Gtk::STATE_SELECTED, color);
546         Gtk::Widget* newBlot = btn;
547 */
549         tips.set_tip((*newBlot), def.descr);
551 /*
552         newBlot->signal_clicked().connect( sigc::mem_fun(*this, &ColorItem::buttonClicked) );
554         sigc::signal<void> type_signal_something;
555 */
557         g_signal_connect( G_OBJECT(newBlot->gobj()),
558                           "clicked",
559                           G_CALLBACK(handleClick),
560                           this);
562         g_signal_connect( G_OBJECT(newBlot->gobj()),
563                           "alt-clicked",
564                           G_CALLBACK(handleSecondaryClick),
565                           this);
567         g_signal_connect( G_OBJECT(newBlot->gobj()),
568                           "button-press-event",
569                           G_CALLBACK(handleButtonPress),
570                           this);
572         gtk_drag_source_set( GTK_WIDGET(newBlot->gobj()),
573                              GDK_BUTTON1_MASK,
574                              sourceColorEntries,
575                              G_N_ELEMENTS(sourceColorEntries),
576                              GdkDragAction(GDK_ACTION_MOVE | GDK_ACTION_COPY) );
578         g_signal_connect( G_OBJECT(newBlot->gobj()),
579                           "drag-data-get",
580                           G_CALLBACK(ColorItem::_dragGetColorData),
581                           this);
583         g_signal_connect( G_OBJECT(newBlot->gobj()),
584                           "drag-begin",
585                           G_CALLBACK(dragBegin),
586                           this );
588 //         g_signal_connect( G_OBJECT(newBlot->gobj()),
589 //                           "drag-drop",
590 //                           G_CALLBACK(dragDropColorData),
591 //                           this);
593         if ( def.isEditable() )
594         {
595             gtk_drag_dest_set( GTK_WIDGET(newBlot->gobj()),
596                                GTK_DEST_DEFAULT_ALL,
597                                destColorTargets,
598                                G_N_ELEMENTS(destColorTargets),
599                                GdkDragAction(GDK_ACTION_COPY | GDK_ACTION_MOVE) );
602             g_signal_connect( G_OBJECT(newBlot->gobj()),
603                               "drag-data-received",
604                               G_CALLBACK(_dropDataIn),
605                               this );
606         }
608         g_signal_connect( G_OBJECT(newBlot->gobj()),
609                           "destroy",
610                           G_CALLBACK(dieDieDie),
611                           this);
614         widget = newBlot;
615     }
617     _previews.push_back( widget );
619     return widget;
622 void ColorItem::buttonClicked(bool secondary)
624     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
625     if (desktop) {
626         char const * attrName = secondary ? "stroke" : "fill";
627         guint32 rgba = (def.getR() << 24) | (def.getG() << 16) | (def.getB() << 8) | 0xff;
628         gchar c[64];
629         sp_svg_write_color(c, sizeof(c), rgba);
631         SPCSSAttr *css = sp_repr_css_attr_new();
632         sp_repr_css_set_property( css, attrName, c );
633         sp_desktop_set_style(desktop, css);
635         sp_repr_css_attr_unref(css);
636         sp_document_done (sp_desktop_document (desktop), SP_VERB_DIALOG_SWATCHES, 
637                           secondary? _("Set stroke color from swatch") : _("Set fill color from swatch"));
638     }
644 static char* trim( char* str ) {
645     char* ret = str;
646     while ( *str && (*str == ' ' || *str == '\t') ) {
647         str++;
648     }
649     ret = str;
650     while ( *str ) {
651         str++;
652     }
653     str--;
654     while ( str > ret && ( *str == ' ' || *str == '\t' ) || *str == '\r' || *str == '\n' ) {
655         *str-- = 0;
656     }
657     return ret;
660 void skipWhitespace( char*& str ) {
661     while ( *str == ' ' || *str == '\t' ) {
662         str++;
663     }
666 bool parseNum( char*& str, int& val ) {
667     val = 0;
668     while ( '0' <= *str && *str <= '9' ) {
669         val = val * 10 + (*str - '0');
670         str++;
671     }
672     bool retval = !(*str == 0 || *str == ' ' || *str == '\t' || *str == '\r' || *str == '\n');
673     return retval;
677 static bool getBlock( std::string& dst, guchar ch, std::string const str )
679     bool good = false;
680     std::string::size_type pos = str.find(ch);
681     if ( pos != std::string::npos )
682     {
683         std::string::size_type pos2 = str.find( '(', pos );
684         if ( pos2 != std::string::npos ) {
685             std::string::size_type endPos = str.find( ')', pos2 );
686             if ( endPos != std::string::npos ) {
687                 dst = str.substr( pos2 + 1, (endPos - pos2 - 1) );
688                 good = true;
689             }
690         }
691     }
692     return good;
695 static bool popVal( guint64& numVal, std::string& str )
697     bool good = false;
698     std::string::size_type endPos = str.find(',');
699     if ( endPos == std::string::npos ) {
700         endPos = str.length();
701     }
703     if ( endPos != std::string::npos && endPos > 0 ) {
704         std::string xxx = str.substr( 0, endPos );
705         const gchar* ptr = xxx.c_str();
706         gchar* endPtr = 0;
707         numVal = g_ascii_strtoull( ptr, &endPtr, 10 );
708         if ( (numVal == G_MAXUINT64) && (ERANGE == errno) ) {
709             // overflow
710         } else if ( (numVal == 0) && (endPtr == ptr) ) {
711             // failed conversion
712         } else {
713             good = true;
714             str.erase( 0, endPos + 1 );
715         }
716     }
718     return good;
721 void ColorItem::_wireMagicColors( void* p )
723     JustForNow* onceMore = reinterpret_cast<JustForNow*>(p);
724     if ( onceMore )
725     {
726         for ( std::vector<ColorItem*>::iterator it = onceMore->_colors.begin(); it != onceMore->_colors.end(); ++it )
727         {
728             std::string::size_type pos = (*it)->def.descr.find("*{");
729             if ( pos != std::string::npos )
730             {
731                 std::string subby = (*it)->def.descr.substr( pos + 2 );
732                 std::string::size_type endPos = subby.find("}*");
733                 if ( endPos != std::string::npos )
734                 {
735                     subby.erase( endPos );
736                     //g_message("FOUND MAGIC at '%s'", (*it)->def.descr.c_str());
737                     //g_message("               '%s'", subby.c_str());
739                     if ( subby.find('E') != std::string::npos )
740                     {
741                         (*it)->def.setEditable( true );
742                     }
744                     if ( subby.find('L') != std::string::npos )
745                     {
746                         (*it)->_isLive = true;
747                     }
749                     std::string part;
750                     // Tint. index + 1 more val.
751                     if ( getBlock( part, 'T', subby ) ) {
752                         guint64 colorIndex = 0;
753                         if ( popVal( colorIndex, part ) ) {
754                             guint64 percent = 0;
755                             if ( popVal( percent, part ) ) {
756                                 (*it)->_linkTint( *(onceMore->_colors[colorIndex]), percent );
757                             }
758                         }
759                     }
761                     // Shade/tone. index + 1 or 2 more val.
762                     if ( getBlock( part, 'S', subby ) ) {
763                         guint64 colorIndex = 0;
764                         if ( popVal( colorIndex, part ) ) {
765                             guint64 percent = 0;
766                             if ( popVal( percent, part ) ) {
767                                 guint64 grayLevel = 0;
768                                 if ( !popVal( grayLevel, part ) ) {
769                                     grayLevel = 0;
770                                 }
771                                 (*it)->_linkTone( *(onceMore->_colors[colorIndex]), percent, grayLevel );
772                             }
773                         }
774                     }
776                 }
777             }
778         }
779     }
783 void ColorItem::_linkTint( ColorItem& other, int percent )
785     if ( !_linkSrc )
786     {
787         other._listeners.push_back(this);
788         _linkIsTone = false;
789         _linkPercent = percent;
790         if ( _linkPercent > 100 )
791             _linkPercent = 100;
792         if ( _linkPercent < 0 )
793             _linkPercent = 0;
794         _linkGray = 0;
795         _linkSrc = &other;
797         ColorItem::_colorDefChanged(&other);
798     }
801 void ColorItem::_linkTone( ColorItem& other, int percent, int grayLevel )
803     if ( !_linkSrc )
804     {
805         other._listeners.push_back(this);
806         _linkIsTone = true;
807         _linkPercent = percent;
808         if ( _linkPercent > 100 )
809             _linkPercent = 100;
810         if ( _linkPercent < 0 )
811             _linkPercent = 0;
812         _linkGray = grayLevel;
813         _linkSrc = &other;
815         ColorItem::_colorDefChanged(&other);
816     }
820 void _loadPaletteFile( gchar const *filename )
822     char block[1024];
823     FILE *f = Inkscape::IO::fopen_utf8name( filename, "r" );
824     if ( f ) {
825         char* result = fgets( block, sizeof(block), f );
826         if ( result ) {
827             if ( strncmp( "GIMP Palette", block, 12 ) == 0 ) {
828                 bool inHeader = true;
829                 bool hasErr = false;
831                 JustForNow *onceMore = new JustForNow();
833                 do {
834                     result = fgets( block, sizeof(block), f );
835                     block[sizeof(block) - 1] = 0;
836                     if ( result ) {
837                         if ( block[0] == '#' ) {
838                             // ignore comment
839                         } else {
840                             char *ptr = block;
841                             // very simple check for header versus entry
842                             while ( *ptr == ' ' || *ptr == '\t' ) {
843                                 ptr++;
844                             }
845                             if ( *ptr == 0 ) {
846                                 // blank line. skip it.
847                             } else if ( '0' <= *ptr && *ptr <= '9' ) {
848                                 // should be an entry link
849                                 inHeader = false;
850                                 ptr = block;
851                                 Glib::ustring name("");
852                                 int r = 0;
853                                 int g = 0;
854                                 int b = 0;
855                                 skipWhitespace(ptr);
856                                 if ( *ptr ) {
857                                     hasErr = parseNum(ptr, r);
858                                     if ( !hasErr ) {
859                                         skipWhitespace(ptr);
860                                         hasErr = parseNum(ptr, g);
861                                     }
862                                     if ( !hasErr ) {
863                                         skipWhitespace(ptr);
864                                         hasErr = parseNum(ptr, b);
865                                     }
866                                     if ( !hasErr && *ptr ) {
867                                         char* n = trim(ptr);
868                                         if (n != NULL) {
869                                             name = n;
870                                         }
871                                     }
872                                     if ( !hasErr ) {
873                                         // Add the entry now
874                                         Glib::ustring nameStr(name);
875                                         ColorItem* item = new ColorItem( r, g, b, nameStr );
876                                         onceMore->_colors.push_back(item);
877                                     }
878                                 } else {
879                                     hasErr = true;
880                                 }
881                             } else {
882                                 if ( !inHeader ) {
883                                     // Hmmm... probably bad. Not quite the format we want?
884                                     hasErr = true;
885                                 } else {
886                                     char* sep = strchr(result, ':');
887                                     if ( sep ) {
888                                         *sep = 0;
889                                         char* val = trim(sep + 1);
890                                         char* name = trim(result);
891                                         if ( *name ) {
892                                             if ( strcmp( "Name", name ) == 0 )
893                                             {
894                                                 onceMore->_name = val;
895                                             }
896                                             else if ( strcmp( "Columns", name ) == 0 )
897                                             {
898                                                 gchar* endPtr = 0;
899                                                 guint64 numVal = g_ascii_strtoull( val, &endPtr, 10 );
900                                                 if ( (numVal == G_MAXUINT64) && (ERANGE == errno) ) {
901                                                     // overflow
902                                                 } else if ( (numVal == 0) && (endPtr == val) ) {
903                                                     // failed conversion
904                                                 } else {
905                                                     onceMore->_prefWidth = numVal;
906                                                 }
907                                             }
908                                         } else {
909                                             // error
910                                             hasErr = true;
911                                         }
912                                     } else {
913                                         // error
914                                         hasErr = true;
915                                     }
916                                 }
917                             }
918                         }
919                     }
920                 } while ( result && !hasErr );
921                 if ( !hasErr ) {
922                     possible.push_back(onceMore);
923 #if ENABLE_MAGIC_COLORS
924                     ColorItem::_wireMagicColors( onceMore );
925 #endif // ENABLE_MAGIC_COLORS
926                 } else {
927                     delete onceMore;
928                 }
929             }
930         }
932         fclose(f);
933     }
936 static void loadEmUp()
938     static bool beenHere = false;
939     if ( !beenHere ) {
940         beenHere = true;
942         std::list<gchar *> sources;
943         sources.push_back( profile_path("palettes") );
944         sources.push_back( g_strdup(INKSCAPE_PALETTESDIR) );
945         sources.push_back( g_strdup(CREATE_PALETTESDIR) );
947         // Use this loop to iterate through a list of possible document locations.
948         while (!sources.empty()) {
949             gchar *dirname = sources.front();
951             if ( Inkscape::IO::file_test( dirname, (GFileTest)(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR) ) ) {
952                 GError *err = 0;
953                 GDir *directory = g_dir_open(dirname, 0, &err);
954                 if (!directory) {
955                     gchar *safeDir = Inkscape::IO::sanitizeString(dirname);
956                     g_warning(_("Palettes directory (%s) is unavailable."), safeDir);
957                     g_free(safeDir);
958                 } else {
959                     gchar *filename = 0;
960                     while ((filename = (gchar *)g_dir_read_name(directory)) != NULL) {
961                         gchar* lower = g_ascii_strdown( filename, -1 );
962 //                        if ( g_str_has_suffix(lower, ".gpl") ) {
963                             gchar* full = g_build_filename(dirname, filename, NULL);
964                             if ( !Inkscape::IO::file_test( full, (GFileTest)(G_FILE_TEST_IS_DIR ) ) ) {
965                                 _loadPaletteFile(full);
966                             }
967                             g_free(full);
968 //                      }
969                         g_free(lower);
970                     }
971                     g_dir_close(directory);
972                 }
973             }
975             // toss the dirname
976             g_free(dirname);
977             sources.pop_front();
978         }
979     }
990 SwatchesPanel& SwatchesPanel::getInstance()
992     if ( !instance ) {
993         instance = new SwatchesPanel();
994     }
996     return *instance;
1001 /**
1002  * Constructor
1003  */
1004 SwatchesPanel::SwatchesPanel(gchar const* prefsPath) :
1005     Inkscape::UI::Widget::Panel( Glib::ustring(), prefsPath, true ),
1006     _holder(0)
1008     Gtk::RadioMenuItem* hotItem = 0;
1009     _holder = new PreviewHolder();
1010     loadEmUp();
1012     if ( !possible.empty() ) {
1013         JustForNow* first = 0;
1014         gchar const* targetName = 0;
1015         if ( _prefs_path ) {
1016             targetName = prefs_get_string_attribute( _prefs_path, "palette" );
1017             if ( targetName ) {
1018                 for ( std::vector<JustForNow*>::iterator iter = possible.begin(); iter != possible.end(); ++iter ) {
1019                     if ( (*iter)->_name == targetName ) {
1020                         first = *iter;
1021                         break;
1022                     }
1023                 }
1024             }
1025         }
1027         if ( !first ) {
1028             first = possible.front();
1029         }
1031         if ( first->_prefWidth > 0 ) {
1032             _holder->setColumnPref( first->_prefWidth );
1033         }
1034         _holder->freezeUpdates();
1035         for ( std::vector<ColorItem*>::iterator it = first->_colors.begin(); it != first->_colors.end(); it++ ) {
1036             _holder->addPreview(*it);
1037         }
1038         _holder->thawUpdates();
1040         Gtk::RadioMenuItem::Group groupOne;
1041         int i = 0;
1042         for ( std::vector<JustForNow*>::iterator it = possible.begin(); it != possible.end(); it++ ) {
1043             JustForNow* curr = *it;
1044             Gtk::RadioMenuItem* single = manage(new Gtk::RadioMenuItem(groupOne, curr->_name));
1045             if ( curr == first ) {
1046                 hotItem = single;
1047             }
1048             _regItem( single, 3, i );
1049             i++;
1050         }
1052     }
1055     _getContents()->pack_start(*_holder, Gtk::PACK_EXPAND_WIDGET);
1056     _setTargetFillable(_holder);
1058     show_all_children();
1060     restorePanelPrefs();
1061     if ( hotItem ) {
1062         hotItem->set_active();
1063     }
1066 SwatchesPanel::~SwatchesPanel()
1070 void SwatchesPanel::setOrientation( Gtk::AnchorType how )
1072     // Must call the parent class or bad things might happen
1073     Inkscape::UI::Widget::Panel::setOrientation( how );
1075     if ( _holder )
1076     {
1077         _holder->setOrientation( Gtk::ANCHOR_SOUTH );
1078     }
1081 void SwatchesPanel::_handleAction( int setId, int itemId )
1083     switch( setId ) {
1084         case 3:
1085         {
1086             if ( itemId >= 0 && itemId < static_cast<int>(possible.size()) ) {
1087                 _holder->clear();
1088                 JustForNow* curr = possible[itemId];
1090                 if ( _prefs_path ) {
1091                     prefs_set_string_attribute( _prefs_path, "palette", curr->_name.c_str() );
1092                 }
1094                 if ( curr->_prefWidth > 0 ) {
1095                     _holder->setColumnPref( curr->_prefWidth );
1096                 }
1097                 _holder->freezeUpdates();
1098                 for ( std::vector<ColorItem*>::iterator it = curr->_colors.begin(); it != curr->_colors.end(); it++ ) {
1099                     _holder->addPreview(*it);
1100                 }
1101                 _holder->thawUpdates();
1102             }
1103         }
1104         break;
1105     }
1108 } //namespace Dialogs
1109 } //namespace UI
1110 } //namespace Inkscape
1113 /*
1114   Local Variables:
1115   mode:c++
1116   c-file-style:"stroustrup"
1117   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1118   indent-tabs-mode:nil
1119   fill-column:99
1120   End:
1121 */
1122 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :