Code

more unreffing temporary styles properly
[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                 item->buttonClicked(false);
228                 return TRUE; /* we handled this */    
229             }
230             else if (event->button == 3)
231             {
232                 item->buttonClicked(true);
233                 return TRUE; /* we handled this */
234             }
235         }
236     }
238     return FALSE; /* we did not handle this */
241 static void dieDieDie( GtkObject *obj, gpointer user_data )
243     g_message("die die die %p  %p", obj, user_data );
246 static const GtkTargetEntry destColorTargets[] = {
247 #if ENABLE_MAGIC_COLORS
248 //    {"application/x-inkscape-color-id", GTK_TARGET_SAME_APP, APP_X_INKY_COLOR_ID},
249     {"application/x-inkscape-color", 0, APP_X_INKY_COLOR},
250 #endif // ENABLE_MAGIC_COLORS
251     {"application/x-color", 0, APP_X_COLOR},
252 };
254 #include "color.h" // for SP_RGBA32_U_COMPOSE
256 void ColorItem::_dropDataIn( GtkWidget *widget,
257                              GdkDragContext *drag_context,
258                              gint x, gint y,
259                              GtkSelectionData *data,
260                              guint info,
261                              guint event_time,
262                              gpointer user_data)
264 //     g_message("    droppy droppy   %d", info);
265      switch (info) {
266          case APP_X_INKY_COLOR:
267          {
268              if ( data->length >= 8 ) {
269                  // Careful about endian issues.
270                  guint16* dataVals = (guint16*)data->data;
271                  if ( user_data ) {
272                      ColorItem* item = reinterpret_cast<ColorItem*>(user_data);
273                      if ( item->def.isEditable() ) {
274                          // Shove on in the new value
275                          item->def.setRGB( 0x0ff & (dataVals[0] >> 8), 0x0ff & (dataVals[1] >> 8), 0x0ff & (dataVals[2] >> 8) );
276                      }
277                  }
278              }
279              break;
280          }
281          case APP_X_COLOR:
282          {
283              if ( data->length == 8 ) {
284                  // Careful about endian issues.
285                  guint16* dataVals = (guint16*)data->data;
286 //                  {
287 //                      gchar c[64] = {0};
288 //                      sp_svg_write_color( c, 64,
289 //                                          SP_RGBA32_U_COMPOSE(
290 //                                              0x0ff & (dataVals[0] >> 8),
291 //                                              0x0ff & (dataVals[1] >> 8),
292 //                                              0x0ff & (dataVals[2] >> 8),
293 //                                              0xff // can't have transparency in the color itself
294 //                                              //0x0ff & (data->data[3] >> 8),
295 //                                              ));
296 //                  }
297                  if ( user_data ) {
298                      ColorItem* item = reinterpret_cast<ColorItem*>(user_data);
299                      if ( item->def.isEditable() ) {
300                          // Shove on in the new value
301                          item->def.setRGB( 0x0ff & (dataVals[0] >> 8), 0x0ff & (dataVals[1] >> 8), 0x0ff & (dataVals[2] >> 8) );
302                      }
303                  }
304              }
305              break;
306          }
307          default:
308              g_message("unknown drop type");
309      }
313 static bool bruteForce( SPDocument* document, Inkscape::XML::Node* node, Glib::ustring const& match, int r, int g, int b )
315     bool changed = false;
317     if ( node ) {
318         gchar const * val = node->attribute("inkscape:x-fill-tag");
319         if ( val  && (match == val) ) {
320             SPObject *obj = document->getObjectByRepr( node );
322             gchar c[64] = {0};
323             sp_svg_write_color( c, 64, SP_RGBA32_U_COMPOSE( r, g, b, 0xff ) );
324             SPCSSAttr *css = sp_repr_css_attr_new();
325             sp_repr_css_set_property( css, "fill", c );
327             sp_desktop_apply_css_recursive( (SPItem*)obj, css, true );
328             ((SPItem*)obj)->updateRepr();
330             changed = true;
331         }
333         val = node->attribute("inkscape:x-stroke-tag");
334         if ( val  && (match == val) ) {
335             SPObject *obj = document->getObjectByRepr( node );
337             gchar c[64] = {0};
338             sp_svg_write_color( c, 64, SP_RGBA32_U_COMPOSE( r, g, b, 0xff ) );
339             SPCSSAttr *css = sp_repr_css_attr_new();
340             sp_repr_css_set_property( css, "stroke", c );
342             sp_desktop_apply_css_recursive( (SPItem*)obj, css, true );
343             ((SPItem*)obj)->updateRepr();
345             changed = true;
346         }
348         Inkscape::XML::Node* first = node->firstChild();
349         changed |= bruteForce( document, first, match, r, g, b );
351         changed |= bruteForce( document, node->next(), match, r, g, b );
352     }
354     return changed;
357 void ColorItem::_colorDefChanged(void* data)
359     ColorItem* item = reinterpret_cast<ColorItem*>(data);
360     if ( item ) {
361         for ( std::vector<Gtk::Widget*>::iterator it =  item->_previews.begin(); it != item->_previews.end(); ++it ) {
362             Gtk::Widget* widget = *it;
363             if ( IS_EEK_PREVIEW(widget->gobj()) ) {
364                 EekPreview * preview = EEK_PREVIEW(widget->gobj());
365                 eek_preview_set_color( preview,
366                                        (item->def.getR() << 8) | item->def.getR(),
367                                        (item->def.getG() << 8) | item->def.getG(),
368                                        (item->def.getB() << 8) | item->def.getB() );
370                 eek_preview_set_linked( preview, (LinkType)((item->_linkSrc ? PREVIEW_LINK_IN:0)
371                                                             | (item->_listeners.empty() ? 0:PREVIEW_LINK_OUT)
372                                                             | (item->_isLive ? PREVIEW_LINK_OTHER:0)) );
374                 widget->queue_draw();
375             }
376         }
378         for ( std::vector<ColorItem*>::iterator it = item->_listeners.begin(); it != item->_listeners.end(); ++it ) {
379             guint r = item->def.getR();
380             guint g = item->def.getG();
381             guint b = item->def.getB();
383             if ( (*it)->_linkIsTone ) {
384                 r = ( ((*it)->_linkPercent * (*it)->_linkGray) + ((100 - (*it)->_linkPercent) * r) ) / 100;
385                 g = ( ((*it)->_linkPercent * (*it)->_linkGray) + ((100 - (*it)->_linkPercent) * g) ) / 100;
386                 b = ( ((*it)->_linkPercent * (*it)->_linkGray) + ((100 - (*it)->_linkPercent) * b) ) / 100;
387             } else {
388                 r = ( ((*it)->_linkPercent * 255) + ((100 - (*it)->_linkPercent) * r) ) / 100;
389                 g = ( ((*it)->_linkPercent * 255) + ((100 - (*it)->_linkPercent) * g) ) / 100;
390                 b = ( ((*it)->_linkPercent * 255) + ((100 - (*it)->_linkPercent) * b) ) / 100;
391             }
393             (*it)->def.setRGB( r, g, b );
394         }
397         // Look for objects using this color
398         {
399             SPDesktop *desktop = SP_ACTIVE_DESKTOP;
400             if ( desktop ) {
401                 SPDocument* document = sp_desktop_document( desktop );
402                 Inkscape::XML::Node *rroot =  sp_document_repr_root( document );
403                 if ( rroot ) {
405                     // Find where this thing came from
406                     Glib::ustring paletteName;
407                     bool found = false;
408                     int index = 0;
409                     for ( std::vector<JustForNow*>::iterator it2 = possible.begin(); it2 != possible.end() && !found; ++it2 ) {
410                         JustForNow* curr = *it2;
411                         index = 0;
412                         for ( std::vector<ColorItem*>::iterator zz = curr->_colors.begin(); zz != curr->_colors.end(); ++zz ) {
413                             if ( item == *zz ) {
414                                 found = true;
415                                 paletteName = curr->_name;
416                                 break;
417                             } else {
418                                 index++;
419                             }
420                         }
421                     }
423                     if ( !paletteName.empty() ) {
424                         gchar* str = g_strdup_printf("%d|", index);
425                         paletteName.insert( 0, str );
426                         g_free(str);
427                         str = 0;
429                         if ( bruteForce( document, rroot, paletteName, item->def.getR(), item->def.getG(), item->def.getB() ) ) {
430                             sp_document_done( document , SP_VERB_DIALOG_SWATCHES, 
431                                               _("Change color definition"));
432                         }
433                     }
434                 }
435             }
436         }
437     }
441 Gtk::Widget* ColorItem::getPreview(PreviewStyle style, ViewType view, Inkscape::IconSize size)
443     Gtk::Widget* widget = 0;
444     if ( style == PREVIEW_STYLE_BLURB ) {
445         Gtk::Label *lbl = new Gtk::Label(def.descr);
446         lbl->set_alignment(Gtk::ALIGN_LEFT, Gtk::ALIGN_CENTER);
447         widget = lbl;
448     } else {
449         Glib::ustring blank("          ");
450         if ( size == Inkscape::ICON_SIZE_MENU || size == Inkscape::ICON_SIZE_DECORATION ) {
451             blank = " ";
452         }
454         GtkWidget* eekWidget = eek_preview_new();
455         EekPreview * preview = EEK_PREVIEW(eekWidget);
456         Gtk::Widget* newBlot = Glib::wrap(eekWidget);
458         eek_preview_set_color( preview, (def.getR() << 8) | def.getR(), (def.getG() << 8) | def.getG(), (def.getB() << 8) | def.getB());
460         eek_preview_set_details( preview, (::PreviewStyle)style, (::ViewType)view, (::GtkIconSize)size );
461         eek_preview_set_linked( preview, (LinkType)((_linkSrc ? PREVIEW_LINK_IN:0)
462                                                     | (_listeners.empty() ? 0:PREVIEW_LINK_OUT)
463                                                     | (_isLive ? PREVIEW_LINK_OTHER:0)) );
465         def.addCallback( _colorDefChanged, this );
467         GValue val = {0, {{0}, {0}}};
468         g_value_init( &val, G_TYPE_BOOLEAN );
469         g_value_set_boolean( &val, FALSE );
470         g_object_set_property( G_OBJECT(preview), "focus-on-click", &val );
472 /*
473         Gtk::Button *btn = new Gtk::Button(blank);
474         Gdk::Color color;
475         color.set_rgb((_r << 8)|_r, (_g << 8)|_g, (_b << 8)|_b);
476         btn->modify_bg(Gtk::STATE_NORMAL, color);
477         btn->modify_bg(Gtk::STATE_ACTIVE, color);
478         btn->modify_bg(Gtk::STATE_PRELIGHT, color);
479         btn->modify_bg(Gtk::STATE_SELECTED, color);
481         Gtk::Widget* newBlot = btn;
482 */
484         tips.set_tip((*newBlot), def.descr);
486 /*
487         newBlot->signal_clicked().connect( sigc::mem_fun(*this, &ColorItem::buttonClicked) );
489         sigc::signal<void> type_signal_something;
490 */
491         g_signal_connect( G_OBJECT(newBlot->gobj()),
492                           "button-release-event",
493                           G_CALLBACK(onButtonPressed),
494                           this);
495                           
496         gtk_drag_source_set( GTK_WIDGET(newBlot->gobj()),
497                              GDK_BUTTON1_MASK,
498                              sourceColorEntries,
499                              G_N_ELEMENTS(sourceColorEntries),
500                              GdkDragAction(GDK_ACTION_MOVE | GDK_ACTION_COPY) );
502         g_signal_connect( G_OBJECT(newBlot->gobj()),
503                           "drag-data-get",
504                           G_CALLBACK(ColorItem::_dragGetColorData),
505                           this);
507         g_signal_connect( G_OBJECT(newBlot->gobj()),
508                           "drag-begin",
509                           G_CALLBACK(dragBegin),
510                           this );
512 //         g_signal_connect( G_OBJECT(newBlot->gobj()),
513 //                           "drag-drop",
514 //                           G_CALLBACK(dragDropColorData),
515 //                           this);
517         if ( def.isEditable() )
518         {
519             gtk_drag_dest_set( GTK_WIDGET(newBlot->gobj()),
520                                GTK_DEST_DEFAULT_ALL,
521                                destColorTargets,
522                                G_N_ELEMENTS(destColorTargets),
523                                GdkDragAction(GDK_ACTION_COPY | GDK_ACTION_MOVE) );
526             g_signal_connect( G_OBJECT(newBlot->gobj()),
527                               "drag-data-received",
528                               G_CALLBACK(_dropDataIn),
529                               this );
530         }
532         g_signal_connect( G_OBJECT(newBlot->gobj()),
533                           "destroy",
534                           G_CALLBACK(dieDieDie),
535                           this);
538         widget = newBlot;
539     }
541     _previews.push_back( widget );
543     return widget;
546 void ColorItem::buttonClicked(bool secondary)
548     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
549     if (desktop) {
550         char const * attrName = secondary ? "stroke" : "fill";
551         guint32 rgba = (def.getR() << 24) | (def.getG() << 16) | (def.getB() << 8) | 0xff;
552         gchar c[64];
553         sp_svg_write_color(c, 64, rgba);
555         SPCSSAttr *css = sp_repr_css_attr_new();
556         sp_repr_css_set_property( css, attrName, c );
557         sp_desktop_set_style(desktop, css);
559         sp_repr_css_attr_unref(css);
560         sp_document_done (sp_desktop_document (desktop), SP_VERB_DIALOG_SWATCHES, 
561                           secondary? _("Set stroke color from swatch") : _("Set fill color from swatch"));
562     }
568 static char* trim( char* str ) {
569     char* ret = str;
570     while ( *str && (*str == ' ' || *str == '\t') ) {
571         str++;
572     }
573     ret = str;
574     while ( *str ) {
575         str++;
576     }
577     str--;
578     while ( str > ret && ( *str == ' ' || *str == '\t' ) || *str == '\r' || *str == '\n' ) {
579         *str-- = 0;
580     }
581     return ret;
584 void skipWhitespace( char*& str ) {
585     while ( *str == ' ' || *str == '\t' ) {
586         str++;
587     }
590 bool parseNum( char*& str, int& val ) {
591     val = 0;
592     while ( '0' <= *str && *str <= '9' ) {
593         val = val * 10 + (*str - '0');
594         str++;
595     }
596     bool retval = !(*str == 0 || *str == ' ' || *str == '\t' || *str == '\r' || *str == '\n');
597     return retval;
601 static bool getBlock( std::string& dst, guchar ch, std::string const str )
603     bool good = false;
604     std::string::size_type pos = str.find(ch);
605     if ( pos != std::string::npos )
606     {
607         std::string::size_type pos2 = str.find( '(', pos );
608         if ( pos2 != std::string::npos ) {
609             std::string::size_type endPos = str.find( ')', pos2 );
610             if ( endPos != std::string::npos ) {
611                 dst = str.substr( pos2 + 1, (endPos - pos2 - 1) );
612                 good = true;
613             }
614         }
615     }
616     return good;
619 static bool popVal( guint64& numVal, std::string& str )
621     bool good = false;
622     std::string::size_type endPos = str.find(',');
623     if ( endPos == std::string::npos ) {
624         endPos = str.length();
625     }
627     if ( endPos != std::string::npos && endPos > 0 ) {
628         std::string xxx = str.substr( 0, endPos );
629         const gchar* ptr = xxx.c_str();
630         gchar* endPtr = 0;
631         numVal = g_ascii_strtoull( ptr, &endPtr, 10 );
632         if ( (numVal == G_MAXUINT64) && (ERANGE == errno) ) {
633             // overflow
634         } else if ( (numVal == 0) && (endPtr == ptr) ) {
635             // failed conversion
636         } else {
637             good = true;
638             str.erase( 0, endPos + 1 );
639         }
640     }
642     return good;
645 void ColorItem::_wireMagicColors( void* p )
647     JustForNow* onceMore = reinterpret_cast<JustForNow*>(p);
648     if ( onceMore )
649     {
650         for ( std::vector<ColorItem*>::iterator it = onceMore->_colors.begin(); it != onceMore->_colors.end(); ++it )
651         {
652             std::string::size_type pos = (*it)->def.descr.find("*{");
653             if ( pos != std::string::npos )
654             {
655                 std::string subby = (*it)->def.descr.substr( pos + 2 );
656                 std::string::size_type endPos = subby.find("}*");
657                 if ( endPos != std::string::npos )
658                 {
659                     subby.erase( endPos );
660                     //g_message("FOUND MAGIC at '%s'", (*it)->def.descr.c_str());
661                     //g_message("               '%s'", subby.c_str());
663                     if ( subby.find('E') != std::string::npos )
664                     {
665                         (*it)->def.setEditable( true );
666                     }
668                     if ( subby.find('L') != std::string::npos )
669                     {
670                         (*it)->_isLive = true;
671                     }
673                     std::string part;
674                     // Tint. index + 1 more val.
675                     if ( getBlock( part, 'T', subby ) ) {
676                         guint64 colorIndex = 0;
677                         if ( popVal( colorIndex, part ) ) {
678                             guint64 percent = 0;
679                             if ( popVal( percent, part ) ) {
680                                 (*it)->_linkTint( *(onceMore->_colors[colorIndex]), percent );
681                             }
682                         }
683                     }
685                     // Shade/tone. index + 1 or 2 more val.
686                     if ( getBlock( part, 'S', subby ) ) {
687                         guint64 colorIndex = 0;
688                         if ( popVal( colorIndex, part ) ) {
689                             guint64 percent = 0;
690                             if ( popVal( percent, part ) ) {
691                                 guint64 grayLevel = 0;
692                                 if ( !popVal( grayLevel, part ) ) {
693                                     grayLevel = 0;
694                                 }
695                                 (*it)->_linkTone( *(onceMore->_colors[colorIndex]), percent, grayLevel );
696                             }
697                         }
698                     }
700                 }
701             }
702         }
703     }
707 void ColorItem::_linkTint( ColorItem& other, int percent )
709     if ( !_linkSrc )
710     {
711         other._listeners.push_back(this);
712         _linkIsTone = false;
713         _linkPercent = percent;
714         if ( _linkPercent > 100 )
715             _linkPercent = 100;
716         if ( _linkPercent < 0 )
717             _linkPercent = 0;
718         _linkGray = 0;
719         _linkSrc = &other;
721         ColorItem::_colorDefChanged(&other);
722     }
725 void ColorItem::_linkTone( ColorItem& other, int percent, int grayLevel )
727     if ( !_linkSrc )
728     {
729         other._listeners.push_back(this);
730         _linkIsTone = true;
731         _linkPercent = percent;
732         if ( _linkPercent > 100 )
733             _linkPercent = 100;
734         if ( _linkPercent < 0 )
735             _linkPercent = 0;
736         _linkGray = grayLevel;
737         _linkSrc = &other;
739         ColorItem::_colorDefChanged(&other);
740     }
744 void _loadPaletteFile( gchar const *filename )
746     char block[1024];
747     FILE *f = Inkscape::IO::fopen_utf8name( filename, "r" );
748     if ( f ) {
749         char* result = fgets( block, sizeof(block), f );
750         if ( result ) {
751             if ( strncmp( "GIMP Palette", block, 12 ) == 0 ) {
752                 bool inHeader = true;
753                 bool hasErr = false;
755                 JustForNow *onceMore = new JustForNow();
757                 do {
758                     result = fgets( block, sizeof(block), f );
759                     block[sizeof(block) - 1] = 0;
760                     if ( result ) {
761                         if ( block[0] == '#' ) {
762                             // ignore comment
763                         } else {
764                             char *ptr = block;
765                             // very simple check for header versus entry
766                             while ( *ptr == ' ' || *ptr == '\t' ) {
767                                 ptr++;
768                             }
769                             if ( *ptr == 0 ) {
770                                 // blank line. skip it.
771                             } else if ( '0' <= *ptr && *ptr <= '9' ) {
772                                 // should be an entry link
773                                 inHeader = false;
774                                 ptr = block;
775                                 Glib::ustring name("");
776                                 int r = 0;
777                                 int g = 0;
778                                 int b = 0;
779                                 skipWhitespace(ptr);
780                                 if ( *ptr ) {
781                                     hasErr = parseNum(ptr, r);
782                                     if ( !hasErr ) {
783                                         skipWhitespace(ptr);
784                                         hasErr = parseNum(ptr, g);
785                                     }
786                                     if ( !hasErr ) {
787                                         skipWhitespace(ptr);
788                                         hasErr = parseNum(ptr, b);
789                                     }
790                                     if ( !hasErr && *ptr ) {
791                                         char* n = trim(ptr);
792                                         if (n != NULL) {
793                                             name = n;
794                                         }
795                                     }
796                                     if ( !hasErr ) {
797                                         // Add the entry now
798                                         Glib::ustring nameStr(name);
799                                         ColorItem* item = new ColorItem( r, g, b, nameStr );
800                                         onceMore->_colors.push_back(item);
801                                     }
802                                 } else {
803                                     hasErr = true;
804                                 }
805                             } else {
806                                 if ( !inHeader ) {
807                                     // Hmmm... probably bad. Not quite the format we want?
808                                     hasErr = true;
809                                 } else {
810                                     char* sep = strchr(result, ':');
811                                     if ( sep ) {
812                                         *sep = 0;
813                                         char* val = trim(sep + 1);
814                                         char* name = trim(result);
815                                         if ( *name ) {
816                                             if ( strcmp( "Name", name ) == 0 )
817                                             {
818                                                 onceMore->_name = val;
819                                             }
820                                             else if ( strcmp( "Columns", name ) == 0 )
821                                             {
822                                                 gchar* endPtr = 0;
823                                                 guint64 numVal = g_ascii_strtoull( val, &endPtr, 10 );
824                                                 if ( (numVal == G_MAXUINT64) && (ERANGE == errno) ) {
825                                                     // overflow
826                                                 } else if ( (numVal == 0) && (endPtr == val) ) {
827                                                     // failed conversion
828                                                 } else {
829                                                     onceMore->_prefWidth = numVal;
830                                                 }
831                                             }
832                                         } else {
833                                             // error
834                                             hasErr = true;
835                                         }
836                                     } else {
837                                         // error
838                                         hasErr = true;
839                                     }
840                                 }
841                             }
842                         }
843                     }
844                 } while ( result && !hasErr );
845                 if ( !hasErr ) {
846                     possible.push_back(onceMore);
847 #if ENABLE_MAGIC_COLORS
848                     ColorItem::_wireMagicColors( onceMore );
849 #endif // ENABLE_MAGIC_COLORS
850                 } else {
851                     delete onceMore;
852                 }
853             }
854         }
856         fclose(f);
857     }
860 static void loadEmUp()
862     static bool beenHere = false;
863     if ( !beenHere ) {
864         beenHere = true;
866         std::list<gchar *> sources;
867         sources.push_back( profile_path("palettes") );
868         sources.push_back( g_strdup(INKSCAPE_PALETTESDIR) );
869         sources.push_back( g_strdup(CREATE_PALETTESDIR) );
871         // Use this loop to iterate through a list of possible document locations.
872         while (!sources.empty()) {
873             gchar *dirname = sources.front();
875             if ( Inkscape::IO::file_test( dirname, (GFileTest)(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR) ) ) {
876                 GError *err = 0;
877                 GDir *directory = g_dir_open(dirname, 0, &err);
878                 if (!directory) {
879                     gchar *safeDir = Inkscape::IO::sanitizeString(dirname);
880                     g_warning(_("Palettes directory (%s) is unavailable."), safeDir);
881                     g_free(safeDir);
882                 } else {
883                     gchar *filename = 0;
884                     while ((filename = (gchar *)g_dir_read_name(directory)) != NULL) {
885                         gchar* lower = g_ascii_strdown( filename, -1 );
886 //                        if ( g_str_has_suffix(lower, ".gpl") ) {
887                             gchar* full = g_build_filename(dirname, filename, NULL);
888                             if ( !Inkscape::IO::file_test( full, (GFileTest)(G_FILE_TEST_IS_DIR ) ) ) {
889                                 _loadPaletteFile(full);
890                             }
891                             g_free(full);
892 //                      }
893                         g_free(lower);
894                     }
895                     g_dir_close(directory);
896                 }
897             }
899             // toss the dirname
900             g_free(dirname);
901             sources.pop_front();
902         }
903     }
914 SwatchesPanel& SwatchesPanel::getInstance()
916     if ( !instance ) {
917         instance = new SwatchesPanel();
918     }
920     return *instance;
925 /**
926  * Constructor
927  */
928 SwatchesPanel::SwatchesPanel(gchar const* prefsPath) :
929     Inkscape::UI::Widget::Panel( Glib::ustring(), prefsPath, true ),
930     _holder(0)
932     Gtk::RadioMenuItem* hotItem = 0;
933     _holder = new PreviewHolder();
934     loadEmUp();
936     if ( !possible.empty() ) {
937         JustForNow* first = 0;
938         gchar const* targetName = 0;
939         if ( _prefs_path ) {
940             targetName = prefs_get_string_attribute( _prefs_path, "palette" );
941             if ( targetName ) {
942                 for ( std::vector<JustForNow*>::iterator iter = possible.begin(); iter != possible.end(); ++iter ) {
943                     if ( (*iter)->_name == targetName ) {
944                         first = *iter;
945                         break;
946                     }
947                 }
948             }
949         }
951         if ( !first ) {
952             first = possible.front();
953         }
955         if ( first->_prefWidth > 0 ) {
956             _holder->setColumnPref( first->_prefWidth );
957         }
958         _holder->freezeUpdates();
959         for ( std::vector<ColorItem*>::iterator it = first->_colors.begin(); it != first->_colors.end(); it++ ) {
960             _holder->addPreview(*it);
961         }
962         _holder->thawUpdates();
964         Gtk::RadioMenuItem::Group groupOne;
965         int i = 0;
966         for ( std::vector<JustForNow*>::iterator it = possible.begin(); it != possible.end(); it++ ) {
967             JustForNow* curr = *it;
968             Gtk::RadioMenuItem* single = manage(new Gtk::RadioMenuItem(groupOne, curr->_name));
969             if ( curr == first ) {
970                 hotItem = single;
971             }
972             _regItem( single, 3, i );
973             i++;
974         }
976     }
979     _getContents()->pack_start(*_holder, Gtk::PACK_EXPAND_WIDGET);
980     _setTargetFillable(_holder);
982     show_all_children();
984     restorePanelPrefs();
985     if ( hotItem ) {
986         hotItem->set_active();
987     }
990 SwatchesPanel::~SwatchesPanel()
994 void SwatchesPanel::setOrientation( Gtk::AnchorType how )
996     // Must call the parent class or bad things might happen
997     Inkscape::UI::Widget::Panel::setOrientation( how );
999     if ( _holder )
1000     {
1001         _holder->setOrientation( Gtk::ANCHOR_SOUTH );
1002     }
1005 void SwatchesPanel::_handleAction( int setId, int itemId )
1007     switch( setId ) {
1008         case 3:
1009         {
1010             if ( itemId >= 0 && itemId < static_cast<int>(possible.size()) ) {
1011                 _holder->clear();
1012                 JustForNow* curr = possible[itemId];
1014                 if ( _prefs_path ) {
1015                     prefs_set_string_attribute( _prefs_path, "palette", curr->_name.c_str() );
1016                 }
1018                 if ( curr->_prefWidth > 0 ) {
1019                     _holder->setColumnPref( curr->_prefWidth );
1020                 }
1021                 _holder->freezeUpdates();
1022                 for ( std::vector<ColorItem*>::iterator it = curr->_colors.begin(); it != curr->_colors.end(); it++ ) {
1023                     _holder->addPreview(*it);
1024                 }
1025                 _holder->thawUpdates();
1026             }
1027         }
1028         break;
1029     }
1032 } //namespace Dialogs
1033 } //namespace UI
1034 } //namespace Inkscape
1037 /*
1038   Local Variables:
1039   mode:c++
1040   c-file-style:"stroustrup"
1041   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1042   indent-tabs-mode:nil
1043   fill-column:99
1044   End:
1045 */
1046 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :