Code

Filter effects dialog:
[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>
20 #include <glibmm/i18n.h>
21 #include <gdkmm/pixbuf.h>
22 #include "inkscape.h"
23 #include "document.h"
24 #include "desktop-handles.h"
25 #include "extension/db.h"
26 #include "inkscape.h"
27 #include "svg/svg-color.h"
28 #include "desktop-style.h"
29 #include "io/sys.h"
30 #include "path-prefix.h"
31 #include "swatches.h"
32 #include "sp-item.h"
33 #include "prefs-utils.h"
35 #include "eek-preview.h"
37 namespace Inkscape {
38 namespace UI {
39 namespace Dialogs {
41 SwatchesPanel* SwatchesPanel::instance = 0;
44 ColorItem::ColorItem( unsigned int r, unsigned int g, unsigned int b, Glib::ustring& name ) :
45     def( r, g, b, name ),
46     _isLive(false),
47     _linkIsTone(false),
48     _linkPercent(0),
49     _linkGray(0),
50     _linkSrc(0)
51 {
52 }
54 ColorItem::~ColorItem()
55 {
56 }
58 ColorItem::ColorItem(ColorItem const &other) :
59     Inkscape::UI::Previewable()
60 {
61     if ( this != &other ) {
62         *this = other;
63     }
64 }
66 ColorItem &ColorItem::operator=(ColorItem const &other)
67 {
68     if ( this != &other ) {
69         def = other.def;
71         // TODO - correct linkage
72         _linkSrc = other._linkSrc;
73         g_message("Erk!");
74     }
75     return *this;
76 }
79 class JustForNow
80 {
81 public:
82     JustForNow() : _prefWidth(0) {}
84     Glib::ustring _name;
85     int _prefWidth;
86     std::vector<ColorItem*> _colors;
87 };
89 static std::vector<JustForNow*> possible;
93 typedef enum {
94     APP_X_INKY_COLOR_ID = 0,
95     APP_X_INKY_COLOR = 0,
96     APP_X_COLOR,
97     TEXT_DATA
98 } colorFlavorType;
100 static const GtkTargetEntry sourceColorEntries[] = {
101 #if ENABLE_MAGIC_COLORS
102 //    {"application/x-inkscape-color-id", GTK_TARGET_SAME_APP, APP_X_INKY_COLOR_ID},
103     {"application/x-inkscape-color", 0, APP_X_INKY_COLOR},
104 #endif // ENABLE_MAGIC_COLORS
105     {"application/x-color", 0, APP_X_COLOR},
106     {"text/plain", 0, TEXT_DATA},
107 };
109 void ColorItem::_dragGetColorData( GtkWidget *widget,
110                                    GdkDragContext *drag_context,
111                                    GtkSelectionData *data,
112                                    guint info,
113                                    guint time,
114                                    gpointer user_data)
116     static GdkAtom typeXColor = gdk_atom_intern("application/x-color", FALSE);
117     static GdkAtom typeText = gdk_atom_intern("text/plain", FALSE);
119     ColorItem* item = reinterpret_cast<ColorItem*>(user_data);
120     if ( info == TEXT_DATA ) {
121         gchar* tmp = g_strdup_printf("#%02x%02x%02x", item->def.getR(), item->def.getG(), item->def.getB() );
123         gtk_selection_data_set( data,
124                                 typeText,
125                                 8, // format
126                                 (guchar*)tmp,
127                                 strlen((const char*)tmp) + 1);
128         g_free(tmp);
129         tmp = 0;
130     } else if ( info == APP_X_INKY_COLOR ) {
131         Glib::ustring paletteName;
133         // Find where this thing came from
134         bool found = false;
135         int index = 0;
136         for ( std::vector<JustForNow*>::iterator it = possible.begin(); it != possible.end() && !found; ++it ) {
137             JustForNow* curr = *it;
138             index = 0;
139             for ( std::vector<ColorItem*>::iterator zz = curr->_colors.begin(); zz != curr->_colors.end(); ++zz ) {
140                 if ( item == *zz ) {
141                     found = true;
142                     paletteName = curr->_name;
143                     break;
144                 } else {
145                     index++;
146                 }
147             }
148         }
150 //         if ( found ) {
151 //             g_message("Found the color at entry %d in palette '%s'", index, paletteName.c_str() );
152 //         } else {
153 //             g_message("Unable to find the color");
154 //         }
155         int itemCount = 4 + 2 + 1 + paletteName.length();
157         guint16* tmp = new guint16[itemCount];
158         tmp[0] = (item->def.getR() << 8) | item->def.getR();
159         tmp[1] = (item->def.getG() << 8) | item->def.getG();
160         tmp[2] = (item->def.getB() << 8) | item->def.getB();
161         tmp[3] = 0xffff;
162         tmp[4] = (item->_isLive || !item->_listeners.empty() || (item->_linkSrc != 0) ) ? 1 : 0;
164         tmp[5] = index;
165         tmp[6] = paletteName.length();
166         for ( unsigned int i = 0; i < paletteName.length(); i++ ) {
167             tmp[7 + i] = paletteName[i];
168         }
169         gtk_selection_data_set( data,
170                                 typeXColor,
171                                 16, // format
172                                 reinterpret_cast<const guchar*>(tmp),
173                                 itemCount * 2);
174         delete[] tmp;
175     } else {
176         guint16 tmp[4];
177         tmp[0] = (item->def.getR() << 8) | item->def.getR();
178         tmp[1] = (item->def.getG() << 8) | item->def.getG();
179         tmp[2] = (item->def.getB() << 8) | item->def.getB();
180         tmp[3] = 0xffff;
181         gtk_selection_data_set( data,
182                                 typeXColor,
183                                 16, // format
184                                 reinterpret_cast<const guchar*>(tmp),
185                                 (3+1) * 2);
186     }
189 static void dragBegin( GtkWidget *widget, GdkDragContext* dc, gpointer data )
191     ColorItem* item = reinterpret_cast<ColorItem*>(data);
192     if ( item )
193     {
194         Glib::RefPtr<Gdk::Pixbuf> thumb = Gdk::Pixbuf::create( Gdk::COLORSPACE_RGB, false, 8, 32, 24 );
195         guint32 fillWith = (0xff000000 & (item->def.getR() << 24))
196                          | (0x00ff0000 & (item->def.getG() << 16))
197                          | (0x0000ff00 & (item->def.getB() <<  8));
198         thumb->fill( fillWith );
199         gtk_drag_set_icon_pixbuf( dc, thumb->gobj(), 0, 0 );
200     }
204 //"drag-drop"
205 // gboolean dragDropColorData( GtkWidget *widget,
206 //                             GdkDragContext *drag_context,
207 //                             gint x,
208 //                             gint y,
209 //                             guint time,
210 //                             gpointer user_data)
211 // {
212 // // TODO finish
214 //     return TRUE;
215 // }
217 static gboolean onButtonPressed (GtkWidget *widget, GdkEventButton *event, gpointer userdata)
219     /* single click with the right mouse button? */
220     if(event->type == GDK_BUTTON_RELEASE)
221     {
222         ColorItem* item = reinterpret_cast<ColorItem*>(userdata);
223         if(item)
224         {
225             if (event->button == 1)
226             { 
227                                 if(event->state & GDK_SHIFT_MASK)
228                                         item->buttonClicked(true);      /* the button was pressed with shift held down. set the stroke */
229                 else item->buttonClicked(false);
230                 return TRUE; /* we handled this */    
231             }
232             else if (event->button == 3)
233             {
234                 item->buttonClicked(true);
235                 return TRUE; /* we handled this */
236             }
237         }
238     }
240     return FALSE; /* we did not handle this */
243 static void dieDieDie( GtkObject *obj, gpointer user_data )
245     g_message("die die die %p  %p", obj, user_data );
248 static const GtkTargetEntry destColorTargets[] = {
249 #if ENABLE_MAGIC_COLORS
250 //    {"application/x-inkscape-color-id", GTK_TARGET_SAME_APP, APP_X_INKY_COLOR_ID},
251     {"application/x-inkscape-color", 0, APP_X_INKY_COLOR},
252 #endif // ENABLE_MAGIC_COLORS
253     {"application/x-color", 0, APP_X_COLOR},
254 };
256 #include "color.h" // for SP_RGBA32_U_COMPOSE
258 void ColorItem::_dropDataIn( GtkWidget *widget,
259                              GdkDragContext *drag_context,
260                              gint x, gint y,
261                              GtkSelectionData *data,
262                              guint info,
263                              guint event_time,
264                              gpointer user_data)
266 //     g_message("    droppy droppy   %d", info);
267      switch (info) {
268          case APP_X_INKY_COLOR:
269          {
270              if ( data->length >= 8 ) {
271                  // Careful about endian issues.
272                  guint16* dataVals = (guint16*)data->data;
273                  if ( user_data ) {
274                      ColorItem* item = reinterpret_cast<ColorItem*>(user_data);
275                      if ( item->def.isEditable() ) {
276                          // Shove on in the new value
277                          item->def.setRGB( 0x0ff & (dataVals[0] >> 8), 0x0ff & (dataVals[1] >> 8), 0x0ff & (dataVals[2] >> 8) );
278                      }
279                  }
280              }
281              break;
282          }
283          case APP_X_COLOR:
284          {
285              if ( data->length == 8 ) {
286                  // Careful about endian issues.
287                  guint16* dataVals = (guint16*)data->data;
288 //                  {
289 //                      gchar c[64] = {0};
290 //                      sp_svg_write_color( c, 64,
291 //                                          SP_RGBA32_U_COMPOSE(
292 //                                              0x0ff & (dataVals[0] >> 8),
293 //                                              0x0ff & (dataVals[1] >> 8),
294 //                                              0x0ff & (dataVals[2] >> 8),
295 //                                              0xff // can't have transparency in the color itself
296 //                                              //0x0ff & (data->data[3] >> 8),
297 //                                              ));
298 //                  }
299                  if ( user_data ) {
300                      ColorItem* item = reinterpret_cast<ColorItem*>(user_data);
301                      if ( item->def.isEditable() ) {
302                          // Shove on in the new value
303                          item->def.setRGB( 0x0ff & (dataVals[0] >> 8), 0x0ff & (dataVals[1] >> 8), 0x0ff & (dataVals[2] >> 8) );
304                      }
305                  }
306              }
307              break;
308          }
309          default:
310              g_message("unknown drop type");
311      }
315 static bool bruteForce( SPDocument* document, Inkscape::XML::Node* node, Glib::ustring const& match, int r, int g, int b )
317     bool changed = false;
319     if ( node ) {
320         gchar const * val = node->attribute("inkscape:x-fill-tag");
321         if ( val  && (match == val) ) {
322             SPObject *obj = document->getObjectByRepr( node );
324             gchar c[64] = {0};
325             sp_svg_write_color( c, 64, SP_RGBA32_U_COMPOSE( r, g, b, 0xff ) );
326             SPCSSAttr *css = sp_repr_css_attr_new();
327             sp_repr_css_set_property( css, "fill", c );
329             sp_desktop_apply_css_recursive( (SPItem*)obj, css, true );
330             ((SPItem*)obj)->updateRepr();
332             changed = true;
333         }
335         val = node->attribute("inkscape:x-stroke-tag");
336         if ( val  && (match == val) ) {
337             SPObject *obj = document->getObjectByRepr( node );
339             gchar c[64] = {0};
340             sp_svg_write_color( c, 64, SP_RGBA32_U_COMPOSE( r, g, b, 0xff ) );
341             SPCSSAttr *css = sp_repr_css_attr_new();
342             sp_repr_css_set_property( css, "stroke", c );
344             sp_desktop_apply_css_recursive( (SPItem*)obj, css, true );
345             ((SPItem*)obj)->updateRepr();
347             changed = true;
348         }
350         Inkscape::XML::Node* first = node->firstChild();
351         changed |= bruteForce( document, first, match, r, g, b );
353         changed |= bruteForce( document, node->next(), match, r, g, b );
354     }
356     return changed;
359 void ColorItem::_colorDefChanged(void* data)
361     ColorItem* item = reinterpret_cast<ColorItem*>(data);
362     if ( item ) {
363         for ( std::vector<Gtk::Widget*>::iterator it =  item->_previews.begin(); it != item->_previews.end(); ++it ) {
364             Gtk::Widget* widget = *it;
365             if ( IS_EEK_PREVIEW(widget->gobj()) ) {
366                 EekPreview * preview = EEK_PREVIEW(widget->gobj());
367                 eek_preview_set_color( preview,
368                                        (item->def.getR() << 8) | item->def.getR(),
369                                        (item->def.getG() << 8) | item->def.getG(),
370                                        (item->def.getB() << 8) | item->def.getB() );
372                 eek_preview_set_linked( preview, (LinkType)((item->_linkSrc ? PREVIEW_LINK_IN:0)
373                                                             | (item->_listeners.empty() ? 0:PREVIEW_LINK_OUT)
374                                                             | (item->_isLive ? PREVIEW_LINK_OTHER:0)) );
376                 widget->queue_draw();
377             }
378         }
380         for ( std::vector<ColorItem*>::iterator it = item->_listeners.begin(); it != item->_listeners.end(); ++it ) {
381             guint r = item->def.getR();
382             guint g = item->def.getG();
383             guint b = item->def.getB();
385             if ( (*it)->_linkIsTone ) {
386                 r = ( ((*it)->_linkPercent * (*it)->_linkGray) + ((100 - (*it)->_linkPercent) * r) ) / 100;
387                 g = ( ((*it)->_linkPercent * (*it)->_linkGray) + ((100 - (*it)->_linkPercent) * g) ) / 100;
388                 b = ( ((*it)->_linkPercent * (*it)->_linkGray) + ((100 - (*it)->_linkPercent) * b) ) / 100;
389             } else {
390                 r = ( ((*it)->_linkPercent * 255) + ((100 - (*it)->_linkPercent) * r) ) / 100;
391                 g = ( ((*it)->_linkPercent * 255) + ((100 - (*it)->_linkPercent) * g) ) / 100;
392                 b = ( ((*it)->_linkPercent * 255) + ((100 - (*it)->_linkPercent) * b) ) / 100;
393             }
395             (*it)->def.setRGB( r, g, b );
396         }
399         // Look for objects using this color
400         {
401             SPDesktop *desktop = SP_ACTIVE_DESKTOP;
402             if ( desktop ) {
403                 SPDocument* document = sp_desktop_document( desktop );
404                 Inkscape::XML::Node *rroot =  sp_document_repr_root( document );
405                 if ( rroot ) {
407                     // Find where this thing came from
408                     Glib::ustring paletteName;
409                     bool found = false;
410                     int index = 0;
411                     for ( std::vector<JustForNow*>::iterator it2 = possible.begin(); it2 != possible.end() && !found; ++it2 ) {
412                         JustForNow* curr = *it2;
413                         index = 0;
414                         for ( std::vector<ColorItem*>::iterator zz = curr->_colors.begin(); zz != curr->_colors.end(); ++zz ) {
415                             if ( item == *zz ) {
416                                 found = true;
417                                 paletteName = curr->_name;
418                                 break;
419                             } else {
420                                 index++;
421                             }
422                         }
423                     }
425                     if ( !paletteName.empty() ) {
426                         gchar* str = g_strdup_printf("%d|", index);
427                         paletteName.insert( 0, str );
428                         g_free(str);
429                         str = 0;
431                         if ( bruteForce( document, rroot, paletteName, item->def.getR(), item->def.getG(), item->def.getB() ) ) {
432                             sp_document_done( document , SP_VERB_DIALOG_SWATCHES, 
433                                               _("Change color definition"));
434                         }
435                     }
436                 }
437             }
438         }
439     }
443 Gtk::Widget* ColorItem::getPreview(PreviewStyle style, ViewType view, Inkscape::IconSize size)
445     Gtk::Widget* widget = 0;
446     if ( style == PREVIEW_STYLE_BLURB ) {
447         Gtk::Label *lbl = new Gtk::Label(def.descr);
448         lbl->set_alignment(Gtk::ALIGN_LEFT, Gtk::ALIGN_CENTER);
449         widget = lbl;
450     } else {
451         Glib::ustring blank("          ");
452         if ( size == Inkscape::ICON_SIZE_MENU || size == Inkscape::ICON_SIZE_DECORATION ) {
453             blank = " ";
454         }
456         GtkWidget* eekWidget = eek_preview_new();
457         EekPreview * preview = EEK_PREVIEW(eekWidget);
458         Gtk::Widget* newBlot = Glib::wrap(eekWidget);
460         eek_preview_set_color( preview, (def.getR() << 8) | def.getR(), (def.getG() << 8) | def.getG(), (def.getB() << 8) | def.getB());
462         eek_preview_set_details( preview, (::PreviewStyle)style, (::ViewType)view, (::GtkIconSize)size );
463         eek_preview_set_linked( preview, (LinkType)((_linkSrc ? PREVIEW_LINK_IN:0)
464                                                     | (_listeners.empty() ? 0:PREVIEW_LINK_OUT)
465                                                     | (_isLive ? PREVIEW_LINK_OTHER:0)) );
467         def.addCallback( _colorDefChanged, this );
469         GValue val = {0, {{0}, {0}}};
470         g_value_init( &val, G_TYPE_BOOLEAN );
471         g_value_set_boolean( &val, FALSE );
472         g_object_set_property( G_OBJECT(preview), "focus-on-click", &val );
474 /*
475         Gtk::Button *btn = new Gtk::Button(blank);
476         Gdk::Color color;
477         color.set_rgb((_r << 8)|_r, (_g << 8)|_g, (_b << 8)|_b);
478         btn->modify_bg(Gtk::STATE_NORMAL, color);
479         btn->modify_bg(Gtk::STATE_ACTIVE, color);
480         btn->modify_bg(Gtk::STATE_PRELIGHT, color);
481         btn->modify_bg(Gtk::STATE_SELECTED, color);
483         Gtk::Widget* newBlot = btn;
484 */
486         tips.set_tip((*newBlot), def.descr);
488 /*
489         newBlot->signal_clicked().connect( sigc::mem_fun(*this, &ColorItem::buttonClicked) );
491         sigc::signal<void> type_signal_something;
492 */
493         g_signal_connect( G_OBJECT(newBlot->gobj()),
494                           "button-release-event",
495                           G_CALLBACK(onButtonPressed),
496                           this);
497                           
498         gtk_drag_source_set( GTK_WIDGET(newBlot->gobj()),
499                              GDK_BUTTON1_MASK,
500                              sourceColorEntries,
501                              G_N_ELEMENTS(sourceColorEntries),
502                              GdkDragAction(GDK_ACTION_MOVE | GDK_ACTION_COPY) );
504         g_signal_connect( G_OBJECT(newBlot->gobj()),
505                           "drag-data-get",
506                           G_CALLBACK(ColorItem::_dragGetColorData),
507                           this);
509         g_signal_connect( G_OBJECT(newBlot->gobj()),
510                           "drag-begin",
511                           G_CALLBACK(dragBegin),
512                           this );
514 //         g_signal_connect( G_OBJECT(newBlot->gobj()),
515 //                           "drag-drop",
516 //                           G_CALLBACK(dragDropColorData),
517 //                           this);
519         if ( def.isEditable() )
520         {
521             gtk_drag_dest_set( GTK_WIDGET(newBlot->gobj()),
522                                GTK_DEST_DEFAULT_ALL,
523                                destColorTargets,
524                                G_N_ELEMENTS(destColorTargets),
525                                GdkDragAction(GDK_ACTION_COPY | GDK_ACTION_MOVE) );
528             g_signal_connect( G_OBJECT(newBlot->gobj()),
529                               "drag-data-received",
530                               G_CALLBACK(_dropDataIn),
531                               this );
532         }
534         g_signal_connect( G_OBJECT(newBlot->gobj()),
535                           "destroy",
536                           G_CALLBACK(dieDieDie),
537                           this);
540         widget = newBlot;
541     }
543     _previews.push_back( widget );
545     return widget;
548 void ColorItem::buttonClicked(bool secondary)
550     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
551     if (desktop) {
552         char const * attrName = secondary ? "stroke" : "fill";
553         guint32 rgba = (def.getR() << 24) | (def.getG() << 16) | (def.getB() << 8) | 0xff;
554         gchar c[64];
555         sp_svg_write_color(c, 64, rgba);
557         SPCSSAttr *css = sp_repr_css_attr_new();
558         sp_repr_css_set_property( css, attrName, c );
559         sp_desktop_set_style(desktop, css);
561         sp_repr_css_attr_unref(css);
562         sp_document_done (sp_desktop_document (desktop), SP_VERB_DIALOG_SWATCHES, 
563                           secondary? _("Set stroke color from swatch") : _("Set fill color from swatch"));
564     }
570 static char* trim( char* str ) {
571     char* ret = str;
572     while ( *str && (*str == ' ' || *str == '\t') ) {
573         str++;
574     }
575     ret = str;
576     while ( *str ) {
577         str++;
578     }
579     str--;
580     while ( str > ret && ( *str == ' ' || *str == '\t' ) || *str == '\r' || *str == '\n' ) {
581         *str-- = 0;
582     }
583     return ret;
586 void skipWhitespace( char*& str ) {
587     while ( *str == ' ' || *str == '\t' ) {
588         str++;
589     }
592 bool parseNum( char*& str, int& val ) {
593     val = 0;
594     while ( '0' <= *str && *str <= '9' ) {
595         val = val * 10 + (*str - '0');
596         str++;
597     }
598     bool retval = !(*str == 0 || *str == ' ' || *str == '\t' || *str == '\r' || *str == '\n');
599     return retval;
603 static bool getBlock( std::string& dst, guchar ch, std::string const str )
605     bool good = false;
606     std::string::size_type pos = str.find(ch);
607     if ( pos != std::string::npos )
608     {
609         std::string::size_type pos2 = str.find( '(', pos );
610         if ( pos2 != std::string::npos ) {
611             std::string::size_type endPos = str.find( ')', pos2 );
612             if ( endPos != std::string::npos ) {
613                 dst = str.substr( pos2 + 1, (endPos - pos2 - 1) );
614                 good = true;
615             }
616         }
617     }
618     return good;
621 static bool popVal( guint64& numVal, std::string& str )
623     bool good = false;
624     std::string::size_type endPos = str.find(',');
625     if ( endPos == std::string::npos ) {
626         endPos = str.length();
627     }
629     if ( endPos != std::string::npos && endPos > 0 ) {
630         std::string xxx = str.substr( 0, endPos );
631         const gchar* ptr = xxx.c_str();
632         gchar* endPtr = 0;
633         numVal = g_ascii_strtoull( ptr, &endPtr, 10 );
634         if ( (numVal == G_MAXUINT64) && (ERANGE == errno) ) {
635             // overflow
636         } else if ( (numVal == 0) && (endPtr == ptr) ) {
637             // failed conversion
638         } else {
639             good = true;
640             str.erase( 0, endPos + 1 );
641         }
642     }
644     return good;
647 void ColorItem::_wireMagicColors( void* p )
649     JustForNow* onceMore = reinterpret_cast<JustForNow*>(p);
650     if ( onceMore )
651     {
652         for ( std::vector<ColorItem*>::iterator it = onceMore->_colors.begin(); it != onceMore->_colors.end(); ++it )
653         {
654             std::string::size_type pos = (*it)->def.descr.find("*{");
655             if ( pos != std::string::npos )
656             {
657                 std::string subby = (*it)->def.descr.substr( pos + 2 );
658                 std::string::size_type endPos = subby.find("}*");
659                 if ( endPos != std::string::npos )
660                 {
661                     subby.erase( endPos );
662                     //g_message("FOUND MAGIC at '%s'", (*it)->def.descr.c_str());
663                     //g_message("               '%s'", subby.c_str());
665                     if ( subby.find('E') != std::string::npos )
666                     {
667                         (*it)->def.setEditable( true );
668                     }
670                     if ( subby.find('L') != std::string::npos )
671                     {
672                         (*it)->_isLive = true;
673                     }
675                     std::string part;
676                     // Tint. index + 1 more val.
677                     if ( getBlock( part, 'T', subby ) ) {
678                         guint64 colorIndex = 0;
679                         if ( popVal( colorIndex, part ) ) {
680                             guint64 percent = 0;
681                             if ( popVal( percent, part ) ) {
682                                 (*it)->_linkTint( *(onceMore->_colors[colorIndex]), percent );
683                             }
684                         }
685                     }
687                     // Shade/tone. index + 1 or 2 more val.
688                     if ( getBlock( part, 'S', subby ) ) {
689                         guint64 colorIndex = 0;
690                         if ( popVal( colorIndex, part ) ) {
691                             guint64 percent = 0;
692                             if ( popVal( percent, part ) ) {
693                                 guint64 grayLevel = 0;
694                                 if ( !popVal( grayLevel, part ) ) {
695                                     grayLevel = 0;
696                                 }
697                                 (*it)->_linkTone( *(onceMore->_colors[colorIndex]), percent, grayLevel );
698                             }
699                         }
700                     }
702                 }
703             }
704         }
705     }
709 void ColorItem::_linkTint( ColorItem& other, int percent )
711     if ( !_linkSrc )
712     {
713         other._listeners.push_back(this);
714         _linkIsTone = false;
715         _linkPercent = percent;
716         if ( _linkPercent > 100 )
717             _linkPercent = 100;
718         if ( _linkPercent < 0 )
719             _linkPercent = 0;
720         _linkGray = 0;
721         _linkSrc = &other;
723         ColorItem::_colorDefChanged(&other);
724     }
727 void ColorItem::_linkTone( ColorItem& other, int percent, int grayLevel )
729     if ( !_linkSrc )
730     {
731         other._listeners.push_back(this);
732         _linkIsTone = true;
733         _linkPercent = percent;
734         if ( _linkPercent > 100 )
735             _linkPercent = 100;
736         if ( _linkPercent < 0 )
737             _linkPercent = 0;
738         _linkGray = grayLevel;
739         _linkSrc = &other;
741         ColorItem::_colorDefChanged(&other);
742     }
746 void _loadPaletteFile( gchar const *filename )
748     char block[1024];
749     FILE *f = Inkscape::IO::fopen_utf8name( filename, "r" );
750     if ( f ) {
751         char* result = fgets( block, sizeof(block), f );
752         if ( result ) {
753             if ( strncmp( "GIMP Palette", block, 12 ) == 0 ) {
754                 bool inHeader = true;
755                 bool hasErr = false;
757                 JustForNow *onceMore = new JustForNow();
759                 do {
760                     result = fgets( block, sizeof(block), f );
761                     block[sizeof(block) - 1] = 0;
762                     if ( result ) {
763                         if ( block[0] == '#' ) {
764                             // ignore comment
765                         } else {
766                             char *ptr = block;
767                             // very simple check for header versus entry
768                             while ( *ptr == ' ' || *ptr == '\t' ) {
769                                 ptr++;
770                             }
771                             if ( *ptr == 0 ) {
772                                 // blank line. skip it.
773                             } else if ( '0' <= *ptr && *ptr <= '9' ) {
774                                 // should be an entry link
775                                 inHeader = false;
776                                 ptr = block;
777                                 Glib::ustring name("");
778                                 int r = 0;
779                                 int g = 0;
780                                 int b = 0;
781                                 skipWhitespace(ptr);
782                                 if ( *ptr ) {
783                                     hasErr = parseNum(ptr, r);
784                                     if ( !hasErr ) {
785                                         skipWhitespace(ptr);
786                                         hasErr = parseNum(ptr, g);
787                                     }
788                                     if ( !hasErr ) {
789                                         skipWhitespace(ptr);
790                                         hasErr = parseNum(ptr, b);
791                                     }
792                                     if ( !hasErr && *ptr ) {
793                                         char* n = trim(ptr);
794                                         if (n != NULL) {
795                                             name = n;
796                                         }
797                                     }
798                                     if ( !hasErr ) {
799                                         // Add the entry now
800                                         Glib::ustring nameStr(name);
801                                         ColorItem* item = new ColorItem( r, g, b, nameStr );
802                                         onceMore->_colors.push_back(item);
803                                     }
804                                 } else {
805                                     hasErr = true;
806                                 }
807                             } else {
808                                 if ( !inHeader ) {
809                                     // Hmmm... probably bad. Not quite the format we want?
810                                     hasErr = true;
811                                 } else {
812                                     char* sep = strchr(result, ':');
813                                     if ( sep ) {
814                                         *sep = 0;
815                                         char* val = trim(sep + 1);
816                                         char* name = trim(result);
817                                         if ( *name ) {
818                                             if ( strcmp( "Name", name ) == 0 )
819                                             {
820                                                 onceMore->_name = val;
821                                             }
822                                             else if ( strcmp( "Columns", name ) == 0 )
823                                             {
824                                                 gchar* endPtr = 0;
825                                                 guint64 numVal = g_ascii_strtoull( val, &endPtr, 10 );
826                                                 if ( (numVal == G_MAXUINT64) && (ERANGE == errno) ) {
827                                                     // overflow
828                                                 } else if ( (numVal == 0) && (endPtr == val) ) {
829                                                     // failed conversion
830                                                 } else {
831                                                     onceMore->_prefWidth = numVal;
832                                                 }
833                                             }
834                                         } else {
835                                             // error
836                                             hasErr = true;
837                                         }
838                                     } else {
839                                         // error
840                                         hasErr = true;
841                                     }
842                                 }
843                             }
844                         }
845                     }
846                 } while ( result && !hasErr );
847                 if ( !hasErr ) {
848                     possible.push_back(onceMore);
849 #if ENABLE_MAGIC_COLORS
850                     ColorItem::_wireMagicColors( onceMore );
851 #endif // ENABLE_MAGIC_COLORS
852                 } else {
853                     delete onceMore;
854                 }
855             }
856         }
858         fclose(f);
859     }
862 static void loadEmUp()
864     static bool beenHere = false;
865     if ( !beenHere ) {
866         beenHere = true;
868         std::list<gchar *> sources;
869         sources.push_back( profile_path("palettes") );
870         sources.push_back( g_strdup(INKSCAPE_PALETTESDIR) );
871         sources.push_back( g_strdup(CREATE_PALETTESDIR) );
873         // Use this loop to iterate through a list of possible document locations.
874         while (!sources.empty()) {
875             gchar *dirname = sources.front();
877             if ( Inkscape::IO::file_test( dirname, (GFileTest)(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR) ) ) {
878                 GError *err = 0;
879                 GDir *directory = g_dir_open(dirname, 0, &err);
880                 if (!directory) {
881                     gchar *safeDir = Inkscape::IO::sanitizeString(dirname);
882                     g_warning(_("Palettes directory (%s) is unavailable."), safeDir);
883                     g_free(safeDir);
884                 } else {
885                     gchar *filename = 0;
886                     while ((filename = (gchar *)g_dir_read_name(directory)) != NULL) {
887                         gchar* lower = g_ascii_strdown( filename, -1 );
888 //                        if ( g_str_has_suffix(lower, ".gpl") ) {
889                             gchar* full = g_build_filename(dirname, filename, NULL);
890                             if ( !Inkscape::IO::file_test( full, (GFileTest)(G_FILE_TEST_IS_DIR ) ) ) {
891                                 _loadPaletteFile(full);
892                             }
893                             g_free(full);
894 //                      }
895                         g_free(lower);
896                     }
897                     g_dir_close(directory);
898                 }
899             }
901             // toss the dirname
902             g_free(dirname);
903             sources.pop_front();
904         }
905     }
916 SwatchesPanel& SwatchesPanel::getInstance()
918     if ( !instance ) {
919         instance = new SwatchesPanel();
920     }
922     return *instance;
927 /**
928  * Constructor
929  */
930 SwatchesPanel::SwatchesPanel(gchar const* prefsPath) :
931     Inkscape::UI::Widget::Panel( Glib::ustring(), prefsPath, true ),
932     _holder(0)
934     Gtk::RadioMenuItem* hotItem = 0;
935     _holder = new PreviewHolder();
936     loadEmUp();
938     if ( !possible.empty() ) {
939         JustForNow* first = 0;
940         gchar const* targetName = 0;
941         if ( _prefs_path ) {
942             targetName = prefs_get_string_attribute( _prefs_path, "palette" );
943             if ( targetName ) {
944                 for ( std::vector<JustForNow*>::iterator iter = possible.begin(); iter != possible.end(); ++iter ) {
945                     if ( (*iter)->_name == targetName ) {
946                         first = *iter;
947                         break;
948                     }
949                 }
950             }
951         }
953         if ( !first ) {
954             first = possible.front();
955         }
957         if ( first->_prefWidth > 0 ) {
958             _holder->setColumnPref( first->_prefWidth );
959         }
960         _holder->freezeUpdates();
961         for ( std::vector<ColorItem*>::iterator it = first->_colors.begin(); it != first->_colors.end(); it++ ) {
962             _holder->addPreview(*it);
963         }
964         _holder->thawUpdates();
966         Gtk::RadioMenuItem::Group groupOne;
967         int i = 0;
968         for ( std::vector<JustForNow*>::iterator it = possible.begin(); it != possible.end(); it++ ) {
969             JustForNow* curr = *it;
970             Gtk::RadioMenuItem* single = manage(new Gtk::RadioMenuItem(groupOne, curr->_name));
971             if ( curr == first ) {
972                 hotItem = single;
973             }
974             _regItem( single, 3, i );
975             i++;
976         }
978     }
981     _getContents()->pack_start(*_holder, Gtk::PACK_EXPAND_WIDGET);
982     _setTargetFillable(_holder);
984     show_all_children();
986     restorePanelPrefs();
987     if ( hotItem ) {
988         hotItem->set_active();
989     }
992 SwatchesPanel::~SwatchesPanel()
996 void SwatchesPanel::setOrientation( Gtk::AnchorType how )
998     // Must call the parent class or bad things might happen
999     Inkscape::UI::Widget::Panel::setOrientation( how );
1001     if ( _holder )
1002     {
1003         _holder->setOrientation( Gtk::ANCHOR_SOUTH );
1004     }
1007 void SwatchesPanel::_handleAction( int setId, int itemId )
1009     switch( setId ) {
1010         case 3:
1011         {
1012             if ( itemId >= 0 && itemId < static_cast<int>(possible.size()) ) {
1013                 _holder->clear();
1014                 JustForNow* curr = possible[itemId];
1016                 if ( _prefs_path ) {
1017                     prefs_set_string_attribute( _prefs_path, "palette", curr->_name.c_str() );
1018                 }
1020                 if ( curr->_prefWidth > 0 ) {
1021                     _holder->setColumnPref( curr->_prefWidth );
1022                 }
1023                 _holder->freezeUpdates();
1024                 for ( std::vector<ColorItem*>::iterator it = curr->_colors.begin(); it != curr->_colors.end(); it++ ) {
1025                     _holder->addPreview(*it);
1026                 }
1027                 _holder->thawUpdates();
1028             }
1029         }
1030         break;
1031     }
1034 } //namespace Dialogs
1035 } //namespace UI
1036 } //namespace Inkscape
1039 /*
1040   Local Variables:
1041   mode:c++
1042   c-file-style:"stroustrup"
1043   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1044   indent-tabs-mode:nil
1045   fill-column:99
1046   End:
1047 */
1048 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :