Code

fix 64-bit issues with width of npos -- patch #1675697 from mellum
[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 void bouncy( GtkWidget* widget, gpointer callback_data ) {
218     ColorItem* item = reinterpret_cast<ColorItem*>(callback_data);
219     if ( item ) {
220         item->buttonClicked(false);
221     }
224 static void bouncy2( GtkWidget* widget, gint arg1, gpointer callback_data ) {
225     ColorItem* item = reinterpret_cast<ColorItem*>(callback_data);
226     if ( item ) {
227         item->buttonClicked(true);
228     }
231 static void dieDieDie( GtkObject *obj, gpointer user_data )
233     g_message("die die die %p  %p", obj, user_data );
236 static const GtkTargetEntry destColorTargets[] = {
237 #if ENABLE_MAGIC_COLORS
238 //    {"application/x-inkscape-color-id", GTK_TARGET_SAME_APP, APP_X_INKY_COLOR_ID},
239     {"application/x-inkscape-color", 0, APP_X_INKY_COLOR},
240 #endif // ENABLE_MAGIC_COLORS
241     {"application/x-color", 0, APP_X_COLOR},
242 };
244 #include "color.h" // for SP_RGBA32_U_COMPOSE
246 void ColorItem::_dropDataIn( GtkWidget *widget,
247                              GdkDragContext *drag_context,
248                              gint x, gint y,
249                              GtkSelectionData *data,
250                              guint info,
251                              guint event_time,
252                              gpointer user_data)
254 //     g_message("    droppy droppy   %d", info);
255      switch (info) {
256          case APP_X_INKY_COLOR:
257          {
258              if ( data->length >= 8 ) {
259                  // Careful about endian issues.
260                  guint16* dataVals = (guint16*)data->data;
261                  if ( user_data ) {
262                      ColorItem* item = reinterpret_cast<ColorItem*>(user_data);
263                      if ( item->def.isEditable() ) {
264                          // Shove on in the new value
265                          item->def.setRGB( 0x0ff & (dataVals[0] >> 8), 0x0ff & (dataVals[1] >> 8), 0x0ff & (dataVals[2] >> 8) );
266                      }
267                  }
268              }
269              break;
270          }
271          case APP_X_COLOR:
272          {
273              if ( data->length == 8 ) {
274                  // Careful about endian issues.
275                  guint16* dataVals = (guint16*)data->data;
276 //                  {
277 //                      gchar c[64] = {0};
278 //                      sp_svg_write_color( c, 64,
279 //                                          SP_RGBA32_U_COMPOSE(
280 //                                              0x0ff & (dataVals[0] >> 8),
281 //                                              0x0ff & (dataVals[1] >> 8),
282 //                                              0x0ff & (dataVals[2] >> 8),
283 //                                              0xff // can't have transparency in the color itself
284 //                                              //0x0ff & (data->data[3] >> 8),
285 //                                              ));
286 //                  }
287                  if ( user_data ) {
288                      ColorItem* item = reinterpret_cast<ColorItem*>(user_data);
289                      if ( item->def.isEditable() ) {
290                          // Shove on in the new value
291                          item->def.setRGB( 0x0ff & (dataVals[0] >> 8), 0x0ff & (dataVals[1] >> 8), 0x0ff & (dataVals[2] >> 8) );
292                      }
293                  }
294              }
295              break;
296          }
297          default:
298              g_message("unknown drop type");
299      }
303 static bool bruteForce( SPDocument* document, Inkscape::XML::Node* node, Glib::ustring const& match, int r, int g, int b )
305     bool changed = false;
307     if ( node ) {
308         gchar const * val = node->attribute("inkscape:x-fill-tag");
309         if ( val  && (match == val) ) {
310             SPObject *obj = document->getObjectByRepr( node );
312             gchar c[64] = {0};
313             sp_svg_write_color( c, 64, SP_RGBA32_U_COMPOSE( r, g, b, 0xff ) );
314             SPCSSAttr *css = sp_repr_css_attr_new();
315             sp_repr_css_set_property( css, "fill", c );
317             sp_desktop_apply_css_recursive( (SPItem*)obj, css, true );
318             ((SPItem*)obj)->updateRepr();
320             changed = true;
321         }
323         val = node->attribute("inkscape:x-stroke-tag");
324         if ( val  && (match == val) ) {
325             SPObject *obj = document->getObjectByRepr( node );
327             gchar c[64] = {0};
328             sp_svg_write_color( c, 64, SP_RGBA32_U_COMPOSE( r, g, b, 0xff ) );
329             SPCSSAttr *css = sp_repr_css_attr_new();
330             sp_repr_css_set_property( css, "stroke", c );
332             sp_desktop_apply_css_recursive( (SPItem*)obj, css, true );
333             ((SPItem*)obj)->updateRepr();
335             changed = true;
336         }
338         Inkscape::XML::Node* first = node->firstChild();
339         changed |= bruteForce( document, first, match, r, g, b );
341         changed |= bruteForce( document, node->next(), match, r, g, b );
342     }
344     return changed;
347 void ColorItem::_colorDefChanged(void* data)
349     ColorItem* item = reinterpret_cast<ColorItem*>(data);
350     if ( item ) {
351         for ( std::vector<Gtk::Widget*>::iterator it =  item->_previews.begin(); it != item->_previews.end(); ++it ) {
352             Gtk::Widget* widget = *it;
353             if ( IS_EEK_PREVIEW(widget->gobj()) ) {
354                 EekPreview * preview = EEK_PREVIEW(widget->gobj());
355                 eek_preview_set_color( preview,
356                                        (item->def.getR() << 8) | item->def.getR(),
357                                        (item->def.getG() << 8) | item->def.getG(),
358                                        (item->def.getB() << 8) | item->def.getB() );
360                 eek_preview_set_linked( preview, (LinkType)((item->_linkSrc ? PREVIEW_LINK_IN:0)
361                                                             | (item->_listeners.empty() ? 0:PREVIEW_LINK_OUT)
362                                                             | (item->_isLive ? PREVIEW_LINK_OTHER:0)) );
364                 widget->queue_draw();
365             }
366         }
368         for ( std::vector<ColorItem*>::iterator it = item->_listeners.begin(); it != item->_listeners.end(); ++it ) {
369             guint r = item->def.getR();
370             guint g = item->def.getG();
371             guint b = item->def.getB();
373             if ( (*it)->_linkIsTone ) {
374                 r = ( ((*it)->_linkPercent * (*it)->_linkGray) + ((100 - (*it)->_linkPercent) * r) ) / 100;
375                 g = ( ((*it)->_linkPercent * (*it)->_linkGray) + ((100 - (*it)->_linkPercent) * g) ) / 100;
376                 b = ( ((*it)->_linkPercent * (*it)->_linkGray) + ((100 - (*it)->_linkPercent) * b) ) / 100;
377             } else {
378                 r = ( ((*it)->_linkPercent * 255) + ((100 - (*it)->_linkPercent) * r) ) / 100;
379                 g = ( ((*it)->_linkPercent * 255) + ((100 - (*it)->_linkPercent) * g) ) / 100;
380                 b = ( ((*it)->_linkPercent * 255) + ((100 - (*it)->_linkPercent) * b) ) / 100;
381             }
383             (*it)->def.setRGB( r, g, b );
384         }
387         // Look for objects using this color
388         {
389             SPDesktop *desktop = SP_ACTIVE_DESKTOP;
390             if ( desktop ) {
391                 SPDocument* document = sp_desktop_document( desktop );
392                 Inkscape::XML::Node *rroot =  sp_document_repr_root( document );
393                 if ( rroot ) {
395                     // Find where this thing came from
396                     Glib::ustring paletteName;
397                     bool found = false;
398                     int index = 0;
399                     for ( std::vector<JustForNow*>::iterator it2 = possible.begin(); it2 != possible.end() && !found; ++it2 ) {
400                         JustForNow* curr = *it2;
401                         index = 0;
402                         for ( std::vector<ColorItem*>::iterator zz = curr->_colors.begin(); zz != curr->_colors.end(); ++zz ) {
403                             if ( item == *zz ) {
404                                 found = true;
405                                 paletteName = curr->_name;
406                                 break;
407                             } else {
408                                 index++;
409                             }
410                         }
411                     }
413                     if ( !paletteName.empty() ) {
414                         gchar* str = g_strdup_printf("%d|", index);
415                         paletteName.insert( 0, str );
416                         g_free(str);
417                         str = 0;
419                         if ( bruteForce( document, rroot, paletteName, item->def.getR(), item->def.getG(), item->def.getB() ) ) {
420                             sp_document_done( document , SP_VERB_DIALOG_SWATCHES, 
421                                               _("Change color definition"));
422                         }
423                     }
424                 }
425             }
426         }
427     }
431 Gtk::Widget* ColorItem::getPreview(PreviewStyle style, ViewType view, Inkscape::IconSize size)
433     Gtk::Widget* widget = 0;
434     if ( style == PREVIEW_STYLE_BLURB ) {
435         Gtk::Label *lbl = new Gtk::Label(def.descr);
436         lbl->set_alignment(Gtk::ALIGN_LEFT, Gtk::ALIGN_CENTER);
437         widget = lbl;
438     } else {
439         Glib::ustring blank("          ");
440         if ( size == Inkscape::ICON_SIZE_MENU || size == Inkscape::ICON_SIZE_DECORATION ) {
441             blank = " ";
442         }
444         GtkWidget* eekWidget = eek_preview_new();
445         EekPreview * preview = EEK_PREVIEW(eekWidget);
446         Gtk::Widget* newBlot = Glib::wrap(eekWidget);
448         eek_preview_set_color( preview, (def.getR() << 8) | def.getR(), (def.getG() << 8) | def.getG(), (def.getB() << 8) | def.getB());
450         eek_preview_set_details( preview, (::PreviewStyle)style, (::ViewType)view, (::GtkIconSize)size );
451         eek_preview_set_linked( preview, (LinkType)((_linkSrc ? PREVIEW_LINK_IN:0)
452                                                     | (_listeners.empty() ? 0:PREVIEW_LINK_OUT)
453                                                     | (_isLive ? PREVIEW_LINK_OTHER:0)) );
455         def.addCallback( _colorDefChanged, this );
457         GValue val = {0, {{0}, {0}}};
458         g_value_init( &val, G_TYPE_BOOLEAN );
459         g_value_set_boolean( &val, FALSE );
460         g_object_set_property( G_OBJECT(preview), "focus-on-click", &val );
462 /*
463         Gtk::Button *btn = new Gtk::Button(blank);
464         Gdk::Color color;
465         color.set_rgb((_r << 8)|_r, (_g << 8)|_g, (_b << 8)|_b);
466         btn->modify_bg(Gtk::STATE_NORMAL, color);
467         btn->modify_bg(Gtk::STATE_ACTIVE, color);
468         btn->modify_bg(Gtk::STATE_PRELIGHT, color);
469         btn->modify_bg(Gtk::STATE_SELECTED, color);
471         Gtk::Widget* newBlot = btn;
472 */
474         tips.set_tip((*newBlot), def.descr);
476 /*
477         newBlot->signal_clicked().connect( sigc::mem_fun(*this, &ColorItem::buttonClicked) );
479         sigc::signal<void> type_signal_something;
480 */
481         g_signal_connect( G_OBJECT(newBlot->gobj()),
482                           "clicked",
483                           G_CALLBACK(bouncy),
484                           this);
486         g_signal_connect( G_OBJECT(newBlot->gobj()),
487                           "alt-clicked",
488                           G_CALLBACK(bouncy2),
489                           this);
491         gtk_drag_source_set( GTK_WIDGET(newBlot->gobj()),
492                              GDK_BUTTON1_MASK,
493                              sourceColorEntries,
494                              G_N_ELEMENTS(sourceColorEntries),
495                              GdkDragAction(GDK_ACTION_MOVE | GDK_ACTION_COPY) );
497         g_signal_connect( G_OBJECT(newBlot->gobj()),
498                           "drag-data-get",
499                           G_CALLBACK(ColorItem::_dragGetColorData),
500                           this);
502         g_signal_connect( G_OBJECT(newBlot->gobj()),
503                           "drag-begin",
504                           G_CALLBACK(dragBegin),
505                           this );
507 //         g_signal_connect( G_OBJECT(newBlot->gobj()),
508 //                           "drag-drop",
509 //                           G_CALLBACK(dragDropColorData),
510 //                           this);
512         if ( def.isEditable() )
513         {
514             gtk_drag_dest_set( GTK_WIDGET(newBlot->gobj()),
515                                GTK_DEST_DEFAULT_ALL,
516                                destColorTargets,
517                                G_N_ELEMENTS(destColorTargets),
518                                GdkDragAction(GDK_ACTION_COPY | GDK_ACTION_MOVE) );
521             g_signal_connect( G_OBJECT(newBlot->gobj()),
522                               "drag-data-received",
523                               G_CALLBACK(_dropDataIn),
524                               this );
525         }
527         g_signal_connect( G_OBJECT(newBlot->gobj()),
528                           "destroy",
529                           G_CALLBACK(dieDieDie),
530                           this);
533         widget = newBlot;
534     }
536     _previews.push_back( widget );
538     return widget;
541 void ColorItem::buttonClicked(bool secondary)
543     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
544     if (desktop) {
545         char const * attrName = secondary ? "stroke" : "fill";
546         guint32 rgba = (def.getR() << 24) | (def.getG() << 16) | (def.getB() << 8) | 0xff;
547         gchar c[64];
548         sp_svg_write_color(c, 64, rgba);
550         SPCSSAttr *css = sp_repr_css_attr_new();
551         sp_repr_css_set_property( css, attrName, c );
552         sp_desktop_set_style(desktop, css);
554         sp_repr_css_attr_unref(css);
555         sp_document_done (sp_desktop_document (desktop), SP_VERB_DIALOG_SWATCHES, 
556                           secondary? _("Set stroke color from swatch") : _("Set fill color from swatch"));
557     }
563 static char* trim( char* str ) {
564     char* ret = str;
565     while ( *str && (*str == ' ' || *str == '\t') ) {
566         str++;
567     }
568     ret = str;
569     while ( *str ) {
570         str++;
571     }
572     str--;
573     while ( str > ret && ( *str == ' ' || *str == '\t' ) || *str == '\r' || *str == '\n' ) {
574         *str-- = 0;
575     }
576     return ret;
579 void skipWhitespace( char*& str ) {
580     while ( *str == ' ' || *str == '\t' ) {
581         str++;
582     }
585 bool parseNum( char*& str, int& val ) {
586     val = 0;
587     while ( '0' <= *str && *str <= '9' ) {
588         val = val * 10 + (*str - '0');
589         str++;
590     }
591     bool retval = !(*str == 0 || *str == ' ' || *str == '\t' || *str == '\r' || *str == '\n');
592     return retval;
596 static bool getBlock( std::string& dst, guchar ch, std::string const str )
598     bool good = false;
599     std::string::size_type pos = str.find(ch);
600     if ( pos != std::string::npos )
601     {
602         std::string::size_type pos2 = str.find( '(', pos );
603         if ( pos2 != std::string::npos ) {
604             std::string::size_type endPos = str.find( ')', pos2 );
605             if ( endPos != std::string::npos ) {
606                 dst = str.substr( pos2 + 1, (endPos - pos2 - 1) );
607                 good = true;
608             }
609         }
610     }
611     return good;
614 static bool popVal( guint64& numVal, std::string& str )
616     bool good = false;
617     std::string::size_type endPos = str.find(',');
618     if ( endPos == std::string::npos ) {
619         endPos = str.length();
620     }
622     if ( endPos != std::string::npos && endPos > 0 ) {
623         std::string xxx = str.substr( 0, endPos );
624         const gchar* ptr = xxx.c_str();
625         gchar* endPtr = 0;
626         numVal = g_ascii_strtoull( ptr, &endPtr, 10 );
627         if ( (numVal == G_MAXUINT64) && (ERANGE == errno) ) {
628             // overflow
629         } else if ( (numVal == 0) && (endPtr == ptr) ) {
630             // failed conversion
631         } else {
632             good = true;
633             str.erase( 0, endPos + 1 );
634         }
635     }
637     return good;
640 void ColorItem::_wireMagicColors( void* p )
642     JustForNow* onceMore = reinterpret_cast<JustForNow*>(p);
643     if ( onceMore )
644     {
645         for ( std::vector<ColorItem*>::iterator it = onceMore->_colors.begin(); it != onceMore->_colors.end(); ++it )
646         {
647             std::string::size_type pos = (*it)->def.descr.find("*{");
648             if ( pos != std::string::npos )
649             {
650                 std::string subby = (*it)->def.descr.substr( pos + 2 );
651                 std::string::size_type endPos = subby.find("}*");
652                 if ( endPos != std::string::npos )
653                 {
654                     subby.erase( endPos );
655                     //g_message("FOUND MAGIC at '%s'", (*it)->def.descr.c_str());
656                     //g_message("               '%s'", subby.c_str());
658                     if ( subby.find('E') != std::string::npos )
659                     {
660                         (*it)->def.setEditable( true );
661                     }
663                     if ( subby.find('L') != std::string::npos )
664                     {
665                         (*it)->_isLive = true;
666                     }
668                     std::string part;
669                     // Tint. index + 1 more val.
670                     if ( getBlock( part, 'T', subby ) ) {
671                         guint64 colorIndex = 0;
672                         if ( popVal( colorIndex, part ) ) {
673                             guint64 percent = 0;
674                             if ( popVal( percent, part ) ) {
675                                 (*it)->_linkTint( *(onceMore->_colors[colorIndex]), percent );
676                             }
677                         }
678                     }
680                     // Shade/tone. index + 1 or 2 more val.
681                     if ( getBlock( part, 'S', subby ) ) {
682                         guint64 colorIndex = 0;
683                         if ( popVal( colorIndex, part ) ) {
684                             guint64 percent = 0;
685                             if ( popVal( percent, part ) ) {
686                                 guint64 grayLevel = 0;
687                                 if ( !popVal( grayLevel, part ) ) {
688                                     grayLevel = 0;
689                                 }
690                                 (*it)->_linkTone( *(onceMore->_colors[colorIndex]), percent, grayLevel );
691                             }
692                         }
693                     }
695                 }
696             }
697         }
698     }
702 void ColorItem::_linkTint( ColorItem& other, int percent )
704     if ( !_linkSrc )
705     {
706         other._listeners.push_back(this);
707         _linkIsTone = false;
708         _linkPercent = percent;
709         if ( _linkPercent > 100 )
710             _linkPercent = 100;
711         if ( _linkPercent < 0 )
712             _linkPercent = 0;
713         _linkGray = 0;
714         _linkSrc = &other;
716         ColorItem::_colorDefChanged(&other);
717     }
720 void ColorItem::_linkTone( ColorItem& other, int percent, int grayLevel )
722     if ( !_linkSrc )
723     {
724         other._listeners.push_back(this);
725         _linkIsTone = true;
726         _linkPercent = percent;
727         if ( _linkPercent > 100 )
728             _linkPercent = 100;
729         if ( _linkPercent < 0 )
730             _linkPercent = 0;
731         _linkGray = grayLevel;
732         _linkSrc = &other;
734         ColorItem::_colorDefChanged(&other);
735     }
739 void _loadPaletteFile( gchar const *filename )
741     char block[1024];
742     FILE *f = Inkscape::IO::fopen_utf8name( filename, "r" );
743     if ( f ) {
744         char* result = fgets( block, sizeof(block), f );
745         if ( result ) {
746             if ( strncmp( "GIMP Palette", block, 12 ) == 0 ) {
747                 bool inHeader = true;
748                 bool hasErr = false;
750                 JustForNow *onceMore = new JustForNow();
752                 do {
753                     result = fgets( block, sizeof(block), f );
754                     block[sizeof(block) - 1] = 0;
755                     if ( result ) {
756                         if ( block[0] == '#' ) {
757                             // ignore comment
758                         } else {
759                             char *ptr = block;
760                             // very simple check for header versus entry
761                             while ( *ptr == ' ' || *ptr == '\t' ) {
762                                 ptr++;
763                             }
764                             if ( *ptr == 0 ) {
765                                 // blank line. skip it.
766                             } else if ( '0' <= *ptr && *ptr <= '9' ) {
767                                 // should be an entry link
768                                 inHeader = false;
769                                 ptr = block;
770                                 Glib::ustring name("");
771                                 int r = 0;
772                                 int g = 0;
773                                 int b = 0;
774                                 skipWhitespace(ptr);
775                                 if ( *ptr ) {
776                                     hasErr = parseNum(ptr, r);
777                                     if ( !hasErr ) {
778                                         skipWhitespace(ptr);
779                                         hasErr = parseNum(ptr, g);
780                                     }
781                                     if ( !hasErr ) {
782                                         skipWhitespace(ptr);
783                                         hasErr = parseNum(ptr, b);
784                                     }
785                                     if ( !hasErr && *ptr ) {
786                                         char* n = trim(ptr);
787                                         if (n != NULL) {
788                                             name = n;
789                                         }
790                                     }
791                                     if ( !hasErr ) {
792                                         // Add the entry now
793                                         Glib::ustring nameStr(name);
794                                         ColorItem* item = new ColorItem( r, g, b, nameStr );
795                                         onceMore->_colors.push_back(item);
796                                     }
797                                 } else {
798                                     hasErr = true;
799                                 }
800                             } else {
801                                 if ( !inHeader ) {
802                                     // Hmmm... probably bad. Not quite the format we want?
803                                     hasErr = true;
804                                 } else {
805                                     char* sep = strchr(result, ':');
806                                     if ( sep ) {
807                                         *sep = 0;
808                                         char* val = trim(sep + 1);
809                                         char* name = trim(result);
810                                         if ( *name ) {
811                                             if ( strcmp( "Name", name ) == 0 )
812                                             {
813                                                 onceMore->_name = val;
814                                             }
815                                             else if ( strcmp( "Columns", name ) == 0 )
816                                             {
817                                                 gchar* endPtr = 0;
818                                                 guint64 numVal = g_ascii_strtoull( val, &endPtr, 10 );
819                                                 if ( (numVal == G_MAXUINT64) && (ERANGE == errno) ) {
820                                                     // overflow
821                                                 } else if ( (numVal == 0) && (endPtr == val) ) {
822                                                     // failed conversion
823                                                 } else {
824                                                     onceMore->_prefWidth = numVal;
825                                                 }
826                                             }
827                                         } else {
828                                             // error
829                                             hasErr = true;
830                                         }
831                                     } else {
832                                         // error
833                                         hasErr = true;
834                                     }
835                                 }
836                             }
837                         }
838                     }
839                 } while ( result && !hasErr );
840                 if ( !hasErr ) {
841                     possible.push_back(onceMore);
842 #if ENABLE_MAGIC_COLORS
843                     ColorItem::_wireMagicColors( onceMore );
844 #endif // ENABLE_MAGIC_COLORS
845                 } else {
846                     delete onceMore;
847                 }
848             }
849         }
851         fclose(f);
852     }
855 static void loadEmUp()
857     static bool beenHere = false;
858     if ( !beenHere ) {
859         beenHere = true;
861         std::list<gchar *> sources;
862         sources.push_back( profile_path("palettes") );
863         sources.push_back( g_strdup(INKSCAPE_PALETTESDIR) );
864         sources.push_back( g_strdup(CREATE_PALETTESDIR) );
866         // Use this loop to iterate through a list of possible document locations.
867         while (!sources.empty()) {
868             gchar *dirname = sources.front();
870             if ( Inkscape::IO::file_test( dirname, (GFileTest)(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR) ) ) {
871                 GError *err = 0;
872                 GDir *directory = g_dir_open(dirname, 0, &err);
873                 if (!directory) {
874                     gchar *safeDir = Inkscape::IO::sanitizeString(dirname);
875                     g_warning(_("Palettes directory (%s) is unavailable."), safeDir);
876                     g_free(safeDir);
877                 } else {
878                     gchar *filename = 0;
879                     while ((filename = (gchar *)g_dir_read_name(directory)) != NULL) {
880                         gchar* lower = g_ascii_strdown( filename, -1 );
881 //                        if ( g_str_has_suffix(lower, ".gpl") ) {
882                             gchar* full = g_build_filename(dirname, filename, NULL);
883                             if ( !Inkscape::IO::file_test( full, (GFileTest)(G_FILE_TEST_IS_DIR ) ) ) {
884                                 _loadPaletteFile(full);
885                             }
886                             g_free(full);
887 //                      }
888                         g_free(lower);
889                     }
890                     g_dir_close(directory);
891                 }
892             }
894             // toss the dirname
895             g_free(dirname);
896             sources.pop_front();
897         }
898     }
909 SwatchesPanel& SwatchesPanel::getInstance()
911     if ( !instance ) {
912         instance = new SwatchesPanel();
913     }
915     return *instance;
920 /**
921  * Constructor
922  */
923 SwatchesPanel::SwatchesPanel(gchar const* prefsPath) :
924     Inkscape::UI::Widget::Panel( Glib::ustring(), prefsPath, true ),
925     _holder(0)
927     Gtk::RadioMenuItem* hotItem = 0;
928     _holder = new PreviewHolder();
929     loadEmUp();
931     if ( !possible.empty() ) {
932         JustForNow* first = 0;
933         gchar const* targetName = 0;
934         if ( _prefs_path ) {
935             targetName = prefs_get_string_attribute( _prefs_path, "palette" );
936             if ( targetName ) {
937                 for ( std::vector<JustForNow*>::iterator iter = possible.begin(); iter != possible.end(); ++iter ) {
938                     if ( (*iter)->_name == targetName ) {
939                         first = *iter;
940                         break;
941                     }
942                 }
943             }
944         }
946         if ( !first ) {
947             first = possible.front();
948         }
950         if ( first->_prefWidth > 0 ) {
951             _holder->setColumnPref( first->_prefWidth );
952         }
953         _holder->freezeUpdates();
954         for ( std::vector<ColorItem*>::iterator it = first->_colors.begin(); it != first->_colors.end(); it++ ) {
955             _holder->addPreview(*it);
956         }
957         _holder->thawUpdates();
959         Gtk::RadioMenuItem::Group groupOne;
960         int i = 0;
961         for ( std::vector<JustForNow*>::iterator it = possible.begin(); it != possible.end(); it++ ) {
962             JustForNow* curr = *it;
963             Gtk::RadioMenuItem* single = manage(new Gtk::RadioMenuItem(groupOne, curr->_name));
964             if ( curr == first ) {
965                 hotItem = single;
966             }
967             _regItem( single, 3, i );
968             i++;
969         }
971     }
974     _getContents()->pack_start(*_holder, Gtk::PACK_EXPAND_WIDGET);
975     _setTargetFillable(_holder);
977     show_all_children();
979     restorePanelPrefs();
980     if ( hotItem ) {
981         hotItem->set_active();
982     }
985 SwatchesPanel::~SwatchesPanel()
989 void SwatchesPanel::setOrientation( Gtk::AnchorType how )
991     // Must call the parent class or bad things might happen
992     Inkscape::UI::Widget::Panel::setOrientation( how );
994     if ( _holder )
995     {
996         _holder->setOrientation( Gtk::ANCHOR_SOUTH );
997     }
1000 void SwatchesPanel::_handleAction( int setId, int itemId )
1002     switch( setId ) {
1003         case 3:
1004         {
1005             if ( itemId >= 0 && itemId < static_cast<int>(possible.size()) ) {
1006                 _holder->clear();
1007                 JustForNow* curr = possible[itemId];
1009                 if ( _prefs_path ) {
1010                     prefs_set_string_attribute( _prefs_path, "palette", curr->_name.c_str() );
1011                 }
1013                 if ( curr->_prefWidth > 0 ) {
1014                     _holder->setColumnPref( curr->_prefWidth );
1015                 }
1016                 _holder->freezeUpdates();
1017                 for ( std::vector<ColorItem*>::iterator it = curr->_colors.begin(); it != curr->_colors.end(); it++ ) {
1018                     _holder->addPreview(*it);
1019                 }
1020                 _holder->thawUpdates();
1021             }
1022         }
1023         break;
1024     }
1027 } //namespace Dialogs
1028 } //namespace UI
1029 } //namespace Inkscape
1032 /*
1033   Local Variables:
1034   mode:c++
1035   c-file-style:"stroustrup"
1036   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1037   indent-tabs-mode:nil
1038   fill-column:99
1039   End:
1040 */
1041 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :