Code

ab4fa35ad65dd969ae1a638fbbfb51f733029add
[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"
34 #include "eek-preview.h"
36 namespace Inkscape {
37 namespace UI {
38 namespace Dialogs {
40 SwatchesPanel* SwatchesPanel::instance = 0;
43 ColorItem::ColorItem( unsigned int r, unsigned int g, unsigned int b, Glib::ustring& name ) :
44     def( r, g, b, name ),
45     _isLive(false),
46     _linkIsTone(false),
47     _linkPercent(0),
48     _linkGray(0),
49     _linkSrc(0)
50 {
51 }
53 ColorItem::~ColorItem()
54 {
55 }
57 ColorItem::ColorItem(ColorItem const &other) :
58     Inkscape::UI::Previewable()
59 {
60     if ( this != &other ) {
61         *this = other;
62     }
63 }
65 ColorItem &ColorItem::operator=(ColorItem const &other)
66 {
67     if ( this != &other ) {
68         def = other.def;
70         // TODO - correct linkage
71         _linkSrc = other._linkSrc;
72         g_message("Erk!");
73     }
74     return *this;
75 }
78 class JustForNow
79 {
80 public:
81     JustForNow() : _prefWidth(0) {}
83     Glib::ustring _name;
84     int _prefWidth;
85     std::vector<ColorItem*> _colors;
86 };
88 static std::vector<JustForNow*> possible;
92 typedef enum {
93     APP_X_INKY_COLOR_ID = 0,
94     APP_X_INKY_COLOR = 0,
95     APP_X_COLOR,
96     TEXT_DATA
97 } colorFlavorType;
99 static const GtkTargetEntry sourceColorEntries[] = {
100 //    {"application/x-inkscape-color-id", GTK_TARGET_SAME_APP, APP_X_INKY_COLOR_ID},
101     {"application/x-inkscape-color", 0, APP_X_INKY_COLOR},
102     {"application/x-color", 0, APP_X_COLOR},
103     {"text/plain", 0, TEXT_DATA},
104 };
106 void ColorItem::_dragGetColorData( GtkWidget *widget,
107                                    GdkDragContext *drag_context,
108                                    GtkSelectionData *data,
109                                    guint info,
110                                    guint time,
111                                    gpointer user_data)
113     static GdkAtom typeXColor = gdk_atom_intern("application/x-color", FALSE);
114     static GdkAtom typeText = gdk_atom_intern("text/plain", FALSE);
116     ColorItem* item = reinterpret_cast<ColorItem*>(user_data);
117     if ( info == TEXT_DATA ) {
118         gchar* tmp = g_strdup_printf("#%02x%02x%02x", item->def.getR(), item->def.getG(), item->def.getB() );
120         gtk_selection_data_set( data,
121                                 typeText,
122                                 8, // format
123                                 (guchar*)tmp,
124                                 strlen((const char*)tmp) + 1);
125         g_free(tmp);
126         tmp = 0;
127     } else if ( info == APP_X_INKY_COLOR ) {
128         Glib::ustring paletteName;
130         // Find where this thing came from
131         bool found = false;
132         int index = 0;
133         for ( std::vector<JustForNow*>::iterator it = possible.begin(); it != possible.end() && !found; ++it ) {
134             JustForNow* curr = *it;
135             index = 0;
136             for ( std::vector<ColorItem*>::iterator zz = curr->_colors.begin(); zz != curr->_colors.end(); ++zz ) {
137                 if ( item == *zz ) {
138                     found = true;
139                     paletteName = curr->_name;
140                     break;
141                 } else {
142                     index++;
143                 }
144             }
145         }
147 //         if ( found ) {
148 //             g_message("Found the color at entry %d in palette '%s'", index, paletteName.c_str() );
149 //         } else {
150 //             g_message("Unable to find the color");
151 //         }
152         int itemCount = 4 + 2 + 1 + paletteName.length();
154         guint16* tmp = new guint16[itemCount];
155         tmp[0] = (item->def.getR() << 8) | item->def.getR();
156         tmp[1] = (item->def.getG() << 8) | item->def.getG();
157         tmp[2] = (item->def.getB() << 8) | item->def.getB();
158         tmp[3] = 0xffff;
159         tmp[4] = (item->_isLive || !item->_listeners.empty() || (item->_linkSrc != 0) ) ? 1 : 0;
161         tmp[5] = index;
162         tmp[6] = paletteName.length();
163         for ( unsigned int i = 0; i < paletteName.length(); i++ ) {
164             tmp[7 + i] = paletteName[i];
165         }
166         gtk_selection_data_set( data,
167                                 typeXColor,
168                                 16, // format
169                                 reinterpret_cast<const guchar*>(tmp),
170                                 itemCount * 2);
171         delete[] tmp;
172     } else {
173         guint16 tmp[4];
174         tmp[0] = (item->def.getR() << 8) | item->def.getR();
175         tmp[1] = (item->def.getG() << 8) | item->def.getG();
176         tmp[2] = (item->def.getB() << 8) | item->def.getB();
177         tmp[3] = 0xffff;
178         gtk_selection_data_set( data,
179                                 typeXColor,
180                                 16, // format
181                                 reinterpret_cast<const guchar*>(tmp),
182                                 (3+1) * 2);
183     }
186 static void dragBegin( GtkWidget *widget, GdkDragContext* dc, gpointer data )
188     ColorItem* item = reinterpret_cast<ColorItem*>(data);
189     if ( item )
190     {
191         Glib::RefPtr<Gdk::Pixbuf> thumb = Gdk::Pixbuf::create( Gdk::COLORSPACE_RGB, false, 8, 32, 24 );
192         guint32 fillWith = (0xff000000 & (item->def.getR() << 24))
193                          | (0x00ff0000 & (item->def.getG() << 16))
194                          | (0x0000ff00 & (item->def.getB() <<  8));
195         thumb->fill( fillWith );
196         gtk_drag_set_icon_pixbuf( dc, thumb->gobj(), 0, 0 );
197     }
201 //"drag-drop"
202 // gboolean dragDropColorData( GtkWidget *widget,
203 //                             GdkDragContext *drag_context,
204 //                             gint x,
205 //                             gint y,
206 //                             guint time,
207 //                             gpointer user_data)
208 // {
209 // // TODO finish
211 //     return TRUE;
212 // }
214 static void bouncy( GtkWidget* widget, gpointer callback_data ) {
215     ColorItem* item = reinterpret_cast<ColorItem*>(callback_data);
216     if ( item ) {
217         item->buttonClicked(false);
218     }
221 static void bouncy2( GtkWidget* widget, gint arg1, gpointer callback_data ) {
222     ColorItem* item = reinterpret_cast<ColorItem*>(callback_data);
223     if ( item ) {
224         item->buttonClicked(true);
225     }
228 static void dieDieDie( GtkObject *obj, gpointer user_data )
230     g_message("die die die %p  %p", obj, user_data );
233 static const GtkTargetEntry destColorTargets[] = {
234 //    {"application/x-inkscape-color-id", GTK_TARGET_SAME_APP, APP_X_INKY_COLOR_ID},
235     {"application/x-inkscape-color", 0, APP_X_INKY_COLOR},
236     {"application/x-color", 0, APP_X_COLOR},
237 };
239 #include "color.h" // for SP_RGBA32_U_COMPOSE
241 void ColorItem::_dropDataIn( GtkWidget *widget,
242                              GdkDragContext *drag_context,
243                              gint x, gint y,
244                              GtkSelectionData *data,
245                              guint info,
246                              guint event_time,
247                              gpointer user_data)
249 //     g_message("    droppy droppy   %d", info);
250      switch (info) {
251          case APP_X_INKY_COLOR:
252          {
253              if ( data->length >= 8 ) {
254                  // Careful about endian issues.
255                  guint16* dataVals = (guint16*)data->data;
256                  if ( user_data ) {
257                      ColorItem* item = reinterpret_cast<ColorItem*>(user_data);
258                      if ( item->def.isEditable() ) {
259                          // Shove on in the new value
260                          item->def.setRGB( 0x0ff & (dataVals[0] >> 8), 0x0ff & (dataVals[1] >> 8), 0x0ff & (dataVals[2] >> 8) );
261                      }
262                  }
263              }
264              break;
265          }
266          case APP_X_COLOR:
267          {
268              if ( data->length == 8 ) {
269                  // Careful about endian issues.
270                  guint16* dataVals = (guint16*)data->data;
271 //                  {
272 //                      gchar c[64] = {0};
273 //                      sp_svg_write_color( c, 64,
274 //                                          SP_RGBA32_U_COMPOSE(
275 //                                              0x0ff & (dataVals[0] >> 8),
276 //                                              0x0ff & (dataVals[1] >> 8),
277 //                                              0x0ff & (dataVals[2] >> 8),
278 //                                              0xff // can't have transparency in the color itself
279 //                                              //0x0ff & (data->data[3] >> 8),
280 //                                              ));
281 //                  }
282                  if ( user_data ) {
283                      ColorItem* item = reinterpret_cast<ColorItem*>(user_data);
284                      if ( item->def.isEditable() ) {
285                          // Shove on in the new value
286                          item->def.setRGB( 0x0ff & (dataVals[0] >> 8), 0x0ff & (dataVals[1] >> 8), 0x0ff & (dataVals[2] >> 8) );
287                      }
288                  }
289              }
290              break;
291          }
292          default:
293              g_message("unknown drop type");
294      }
298 static bool bruteForce( SPDocument* document, Inkscape::XML::Node* node, Glib::ustring const& match, int r, int g, int b )
300     bool changed = false;
302     if ( node ) {
303         gchar const * val = node->attribute("inkscape:x-fill-tag");
304         if ( val  && (match == val) ) {
305             SPObject *obj = document->getObjectByRepr( node );
307             gchar c[64] = {0};
308             sp_svg_write_color( c, 64, SP_RGBA32_U_COMPOSE( r, g, b, 0xff ) );
309             SPCSSAttr *css = sp_repr_css_attr_new();
310             sp_repr_css_set_property( css, "fill", c );
312             sp_desktop_apply_css_recursive( (SPItem*)obj, css, true );
313             ((SPItem*)obj)->updateRepr();
315             changed = true;
316         }
318         val = node->attribute("inkscape:x-stroke-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, "stroke", c );
327             sp_desktop_apply_css_recursive( (SPItem*)obj, css, true );
328             ((SPItem*)obj)->updateRepr();
330             changed = true;
331         }
333         Inkscape::XML::Node* first = node->firstChild();
334         changed |= bruteForce( document, first, match, r, g, b );
336         changed |= bruteForce( document, node->next(), match, r, g, b );
337     }
339     return changed;
342 void ColorItem::_colorDefChanged(void* data)
344     ColorItem* item = reinterpret_cast<ColorItem*>(data);
345     if ( item ) {
346         for ( std::vector<Gtk::Widget*>::iterator it =  item->_previews.begin(); it != item->_previews.end(); ++it ) {
347             Gtk::Widget* widget = *it;
348             if ( IS_EEK_PREVIEW(widget->gobj()) ) {
349                 EekPreview * preview = EEK_PREVIEW(widget->gobj());
350                 eek_preview_set_color( preview,
351                                        (item->def.getR() << 8) | item->def.getR(),
352                                        (item->def.getG() << 8) | item->def.getG(),
353                                        (item->def.getB() << 8) | item->def.getB() );
355                 eek_preview_set_linked( preview, (LinkType)((item->_linkSrc ? PREVIEW_LINK_IN:0)
356                                                             | (item->_listeners.empty() ? 0:PREVIEW_LINK_OUT)
357                                                             | (item->_isLive ? PREVIEW_LINK_OTHER:0)) );
359                 widget->queue_draw();
360             }
361         }
363         for ( std::vector<ColorItem*>::iterator it = item->_listeners.begin(); it != item->_listeners.end(); ++it ) {
364             guint r = item->def.getR();
365             guint g = item->def.getG();
366             guint b = item->def.getB();
368             if ( (*it)->_linkIsTone ) {
369                 r = ( ((*it)->_linkPercent * (*it)->_linkGray) + ((100 - (*it)->_linkPercent) * r) ) / 100;
370                 g = ( ((*it)->_linkPercent * (*it)->_linkGray) + ((100 - (*it)->_linkPercent) * g) ) / 100;
371                 b = ( ((*it)->_linkPercent * (*it)->_linkGray) + ((100 - (*it)->_linkPercent) * b) ) / 100;
372             } else {
373                 r = ( ((*it)->_linkPercent * 255) + ((100 - (*it)->_linkPercent) * r) ) / 100;
374                 g = ( ((*it)->_linkPercent * 255) + ((100 - (*it)->_linkPercent) * g) ) / 100;
375                 b = ( ((*it)->_linkPercent * 255) + ((100 - (*it)->_linkPercent) * b) ) / 100;
376             }
378             (*it)->def.setRGB( r, g, b );
379         }
382         // Look for objects using this color
383         {
384             SPDesktop *desktop = SP_ACTIVE_DESKTOP;
385             if ( desktop ) {
386                 SPDocument* document = SP_DT_DOCUMENT( desktop );
387                 Inkscape::XML::Node *rroot =  sp_document_repr_root( document );
388                 if ( rroot ) {
390                     // Find where this thing came from
391                     Glib::ustring paletteName;
392                     bool found = false;
393                     int index = 0;
394                     for ( std::vector<JustForNow*>::iterator it2 = possible.begin(); it2 != possible.end() && !found; ++it2 ) {
395                         JustForNow* curr = *it2;
396                         index = 0;
397                         for ( std::vector<ColorItem*>::iterator zz = curr->_colors.begin(); zz != curr->_colors.end(); ++zz ) {
398                             if ( item == *zz ) {
399                                 found = true;
400                                 paletteName = curr->_name;
401                                 break;
402                             } else {
403                                 index++;
404                             }
405                         }
406                     }
408                     if ( !paletteName.empty() ) {
409                         gchar* str = g_strdup_printf("%d|", index);
410                         paletteName.insert( 0, str );
411                         g_free(str);
412                         str = 0;
414                         if ( bruteForce( document, rroot, paletteName, item->def.getR(), item->def.getG(), item->def.getB() ) ) {
415                             sp_document_done( document );
416                         }
417                     }
418                 }
419             }
420         }
421     }
425 Gtk::Widget* ColorItem::getPreview(PreviewStyle style, ViewType view, Gtk::BuiltinIconSize size)
427     Gtk::Widget* widget = 0;
428     if ( style == PREVIEW_STYLE_BLURB ) {
429         Gtk::Label *lbl = new Gtk::Label(def.descr);
430         lbl->set_alignment(Gtk::ALIGN_LEFT, Gtk::ALIGN_CENTER);
431         widget = lbl;
432     } else {
433         Glib::ustring blank("          ");
434         if ( size == Gtk::ICON_SIZE_MENU ) {
435             blank = " ";
436         }
438         GtkWidget* eekWidget = eek_preview_new();
439         EekPreview * preview = EEK_PREVIEW(eekWidget);
440         Gtk::Widget* newBlot = Glib::wrap(eekWidget);
442         eek_preview_set_color( preview, (def.getR() << 8) | def.getR(), (def.getG() << 8) | def.getG(), (def.getB() << 8) | def.getB());
444         eek_preview_set_details( preview, (::PreviewStyle)style, (::ViewType)view, (::GtkIconSize)size );
445         eek_preview_set_linked( preview, (LinkType)((_linkSrc ? PREVIEW_LINK_IN:0)
446                                                     | (_listeners.empty() ? 0:PREVIEW_LINK_OUT)
447                                                     | (_isLive ? PREVIEW_LINK_OTHER:0)) );
449         def.addCallback( _colorDefChanged, this );
451         GValue val = {0, {{0}, {0}}};
452         g_value_init( &val, G_TYPE_BOOLEAN );
453         g_value_set_boolean( &val, FALSE );
454         g_object_set_property( G_OBJECT(preview), "focus-on-click", &val );
456 /*
457         Gtk::Button *btn = new Gtk::Button(blank);
458         Gdk::Color color;
459         color.set_rgb((_r << 8)|_r, (_g << 8)|_g, (_b << 8)|_b);
460         btn->modify_bg(Gtk::STATE_NORMAL, color);
461         btn->modify_bg(Gtk::STATE_ACTIVE, color);
462         btn->modify_bg(Gtk::STATE_PRELIGHT, color);
463         btn->modify_bg(Gtk::STATE_SELECTED, color);
465         Gtk::Widget* newBlot = btn;
466 */
468         tips.set_tip((*newBlot), def.descr);
470 /*
471         newBlot->signal_clicked().connect( sigc::mem_fun(*this, &ColorItem::buttonClicked) );
473         sigc::signal<void> type_signal_something;
474 */
475         g_signal_connect( G_OBJECT(newBlot->gobj()),
476                           "clicked",
477                           G_CALLBACK(bouncy),
478                           this);
480         g_signal_connect( G_OBJECT(newBlot->gobj()),
481                           "alt-clicked",
482                           G_CALLBACK(bouncy2),
483                           this);
485         gtk_drag_source_set( GTK_WIDGET(newBlot->gobj()),
486                              GDK_BUTTON1_MASK,
487                              sourceColorEntries,
488                              G_N_ELEMENTS(sourceColorEntries),
489                              GdkDragAction(GDK_ACTION_MOVE | GDK_ACTION_COPY) );
491         g_signal_connect( G_OBJECT(newBlot->gobj()),
492                           "drag-data-get",
493                           G_CALLBACK(ColorItem::_dragGetColorData),
494                           this);
496         g_signal_connect( G_OBJECT(newBlot->gobj()),
497                           "drag-begin",
498                           G_CALLBACK(dragBegin),
499                           this );
501 //         g_signal_connect( G_OBJECT(newBlot->gobj()),
502 //                           "drag-drop",
503 //                           G_CALLBACK(dragDropColorData),
504 //                           this);
506         if ( def.isEditable() )
507         {
508             gtk_drag_dest_set( GTK_WIDGET(newBlot->gobj()),
509                                GTK_DEST_DEFAULT_ALL,
510                                destColorTargets,
511                                G_N_ELEMENTS(destColorTargets),
512                                GdkDragAction(GDK_ACTION_COPY | GDK_ACTION_MOVE) );
515             g_signal_connect( G_OBJECT(newBlot->gobj()),
516                               "drag-data-received",
517                               G_CALLBACK(_dropDataIn),
518                               this );
519         }
521         g_signal_connect( G_OBJECT(newBlot->gobj()),
522                           "destroy",
523                           G_CALLBACK(dieDieDie),
524                           this);
527         widget = newBlot;
528     }
530     _previews.push_back( widget );
532     return widget;
535 void ColorItem::buttonClicked(bool secondary)
537     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
538     if (desktop) {
539         char const * attrName = secondary ? "stroke" : "fill";
540         guint32 rgba = (def.getR() << 24) | (def.getG() << 16) | (def.getB() << 8) | 0xff;
541         gchar c[64];
542         sp_svg_write_color(c, 64, rgba);
544         SPCSSAttr *css = sp_repr_css_attr_new();
545         sp_repr_css_set_property( css, attrName, c );
546         sp_desktop_set_style(desktop, css);
548         sp_repr_css_attr_unref(css);
549         sp_document_done (SP_DT_DOCUMENT (desktop));
550     }
556 static char* trim( char* str ) {
557     char* ret = str;
558     while ( *str && (*str == ' ' || *str == '\t') ) {
559         str++;
560     }
561     ret = str;
562     while ( *str ) {
563         str++;
564     }
565     str--;
566     while ( str > ret && ( *str == ' ' || *str == '\t' ) || *str == '\r' || *str == '\n' ) {
567         *str-- = 0;
568     }
569     return ret;
572 void skipWhitespace( char*& str ) {
573     while ( *str == ' ' || *str == '\t' ) {
574         str++;
575     }
578 bool parseNum( char*& str, int& val ) {
579     val = 0;
580     while ( '0' <= *str && *str <= '9' ) {
581         val = val * 10 + (*str - '0');
582         str++;
583     }
584     bool retval = !(*str == 0 || *str == ' ' || *str == '\t' || *str == '\r' || *str == '\n');
585     return retval;
589 static bool getBlock( std::string& dst, guchar ch, std::string const str )
591     bool good = false;
592     size_t pos = str.find(ch);
593     if ( pos != std::string::npos )
594     {
595         size_t pos2 = str.find( '(', pos );
596         if ( pos2 != std::string::npos ) {
597             size_t endPos = str.find( ')', pos2 );
598             if ( endPos != std::string::npos ) {
599                 dst = str.substr( pos2 + 1, (endPos - pos2 - 1) );
600                 good = true;
601             }
602         }
603     }
604     return good;
607 static bool popVal( guint64& numVal, std::string& str )
609     bool good = false;
610     size_t endPos = str.find(',');
611     if ( endPos == std::string::npos ) {
612         endPos = str.length();
613     }
615     if ( endPos != std::string::npos && endPos > 0 ) {
616         std::string xxx = str.substr( 0, endPos );
617         const gchar* ptr = xxx.c_str();
618         gchar* endPtr = 0;
619         numVal = g_ascii_strtoull( ptr, &endPtr, 10 );
620         if ( (numVal == G_MAXUINT64) && (ERANGE == errno) ) {
621             // overflow
622         } else if ( (numVal == 0) && (endPtr == ptr) ) {
623             // failed conversion
624         } else {
625             good = true;
626             str.erase( 0, endPos + 1 );
627         }
628     }
630     return good;
633 void ColorItem::_wireMagicColors( void* p )
635     JustForNow* onceMore = reinterpret_cast<JustForNow*>(p);
636     if ( onceMore )
637     {
638         for ( std::vector<ColorItem*>::iterator it = onceMore->_colors.begin(); it != onceMore->_colors.end(); ++it )
639         {
640             size_t pos = (*it)->def.descr.find("*{");
641             if ( pos != std::string::npos )
642             {
643                 std::string subby = (*it)->def.descr.substr( pos + 2 );
644                 size_t endPos = subby.find("}*");
645                 if ( endPos != std::string::npos )
646                 {
647                     subby.erase( endPos );
648                     //g_message("FOUND MAGIC at '%s'", (*it)->def.descr.c_str());
649                     //g_message("               '%s'", subby.c_str());
651                     if ( subby.find('E') != std::string::npos )
652                     {
653                         (*it)->def.setEditable( true );
654                     }
656                     if ( subby.find('L') != std::string::npos )
657                     {
658                         (*it)->_isLive = true;
659                     }
661                     std::string part;
662                     // Tint. index + 1 more val.
663                     if ( getBlock( part, 'T', subby ) ) {
664                         guint64 colorIndex = 0;
665                         if ( popVal( colorIndex, part ) ) {
666                             guint64 percent = 0;
667                             if ( popVal( percent, part ) ) {
668                                 (*it)->_linkTint( *(onceMore->_colors[colorIndex]), percent );
669                             }
670                         }
671                     }
673                     // Shade/tone. index + 1 or 2 more val.
674                     if ( getBlock( part, 'S', subby ) ) {
675                         guint64 colorIndex = 0;
676                         if ( popVal( colorIndex, part ) ) {
677                             guint64 percent = 0;
678                             if ( popVal( percent, part ) ) {
679                                 guint64 grayLevel = 0;
680                                 if ( !popVal( grayLevel, part ) ) {
681                                     grayLevel = 0;
682                                 }
683                                 (*it)->_linkTone( *(onceMore->_colors[colorIndex]), percent, grayLevel );
684                             }
685                         }
686                     }
688                 }
689             }
690         }
691     }
695 void ColorItem::_linkTint( ColorItem& other, int percent )
697     if ( !_linkSrc )
698     {
699         other._listeners.push_back(this);
700         _linkIsTone = false;
701         _linkPercent = percent;
702         if ( _linkPercent > 100 )
703             _linkPercent = 100;
704         if ( _linkPercent < 0 )
705             _linkPercent = 0;
706         _linkGray = 0;
707         _linkSrc = &other;
709         ColorItem::_colorDefChanged(&other);
710     }
713 void ColorItem::_linkTone( ColorItem& other, int percent, int grayLevel )
715     if ( !_linkSrc )
716     {
717         other._listeners.push_back(this);
718         _linkIsTone = true;
719         _linkPercent = percent;
720         if ( _linkPercent > 100 )
721             _linkPercent = 100;
722         if ( _linkPercent < 0 )
723             _linkPercent = 0;
724         _linkGray = grayLevel;
725         _linkSrc = &other;
727         ColorItem::_colorDefChanged(&other);
728     }
732 void _loadPaletteFile( gchar const *filename )
734     char block[1024];
735     FILE *f = Inkscape::IO::fopen_utf8name( filename, "r" );
736     if ( f ) {
737         char* result = fgets( block, sizeof(block), f );
738         if ( result ) {
739             if ( strncmp( "GIMP Palette", block, 12 ) == 0 ) {
740                 bool inHeader = true;
741                 bool hasErr = false;
743                 JustForNow *onceMore = new JustForNow();
745                 do {
746                     result = fgets( block, sizeof(block), f );
747                     block[sizeof(block) - 1] = 0;
748                     if ( result ) {
749                         if ( block[0] == '#' ) {
750                             // ignore comment
751                         } else {
752                             char *ptr = block;
753                             // very simple check for header versus entry
754                             while ( *ptr == ' ' || *ptr == '\t' ) {
755                                 ptr++;
756                             }
757                             if ( *ptr == 0 ) {
758                                 // blank line. skip it.
759                             } else if ( '0' <= *ptr && *ptr <= '9' ) {
760                                 // should be an entry link
761                                 inHeader = false;
762                                 ptr = block;
763                                 Glib::ustring name("");
764                                 int r = 0;
765                                 int g = 0;
766                                 int b = 0;
767                                 skipWhitespace(ptr);
768                                 if ( *ptr ) {
769                                     hasErr = parseNum(ptr, r);
770                                     if ( !hasErr ) {
771                                         skipWhitespace(ptr);
772                                         hasErr = parseNum(ptr, g);
773                                     }
774                                     if ( !hasErr ) {
775                                         skipWhitespace(ptr);
776                                         hasErr = parseNum(ptr, b);
777                                     }
778                                     if ( !hasErr && *ptr ) {
779                                         char* n = trim(ptr);
780                                         if (n != NULL) {
781                                             name = n;
782                                         }
783                                     }
784                                     if ( !hasErr ) {
785                                         // Add the entry now
786                                         Glib::ustring nameStr(name);
787                                         ColorItem* item = new ColorItem( r, g, b, nameStr );
788                                         onceMore->_colors.push_back(item);
789                                     }
790                                 } else {
791                                     hasErr = true;
792                                 }
793                             } else {
794                                 if ( !inHeader ) {
795                                     // Hmmm... probably bad. Not quite the format we want?
796                                     hasErr = true;
797                                 } else {
798                                     char* sep = strchr(result, ':');
799                                     if ( sep ) {
800                                         *sep = 0;
801                                         char* val = trim(sep + 1);
802                                         char* name = trim(result);
803                                         if ( *name ) {
804                                             if ( strcmp( "Name", name ) == 0 )
805                                             {
806                                                 onceMore->_name = val;
807                                             }
808                                             else if ( strcmp( "Columns", name ) == 0 )
809                                             {
810                                                 gchar* endPtr = 0;
811                                                 guint64 numVal = g_ascii_strtoull( val, &endPtr, 10 );
812                                                 if ( (numVal == G_MAXUINT64) && (ERANGE == errno) ) {
813                                                     // overflow
814                                                 } else if ( (numVal == 0) && (endPtr == val) ) {
815                                                     // failed conversion
816                                                 } else {
817                                                     onceMore->_prefWidth = numVal;
818                                                 }
819                                             }
820                                         } else {
821                                             // error
822                                             hasErr = true;
823                                         }
824                                     } else {
825                                         // error
826                                         hasErr = true;
827                                     }
828                                 }
829                             }
830                         }
831                     }
832                 } while ( result && !hasErr );
833                 if ( !hasErr ) {
834                     possible.push_back(onceMore);
835                     ColorItem::_wireMagicColors( onceMore );
836                 } else {
837                     delete onceMore;
838                 }
839             }
840         }
842         fclose(f);
843     }
846 static void loadEmUp()
848     static bool beenHere = false;
849     if ( !beenHere ) {
850         beenHere = true;
852         std::list<gchar *> sources;
853         sources.push_back( profile_path("palettes") );
854         sources.push_back( g_strdup(INKSCAPE_PALETTESDIR) );
856         // Use this loop to iterate through a list of possible document locations.
857         while (!sources.empty()) {
858             gchar *dirname = sources.front();
860             if ( Inkscape::IO::file_test( dirname, (GFileTest)(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR) ) ) {
861                 GError *err = 0;
862                 GDir *directory = g_dir_open(dirname, 0, &err);
863                 if (!directory) {
864                     gchar *safeDir = Inkscape::IO::sanitizeString(dirname);
865                     g_warning(_("Palettes directory (%s) is unavailable."), safeDir);
866                     g_free(safeDir);
867                 } else {
868                     gchar *filename = 0;
869                     while ((filename = (gchar *)g_dir_read_name(directory)) != NULL) {
870                         gchar* lower = g_ascii_strdown( filename, -1 );
871                         if ( g_str_has_suffix(lower, ".gpl") ) {
872                             gchar* full = g_build_filename(dirname, filename, NULL);
873                             if ( !Inkscape::IO::file_test( full, (GFileTest)(G_FILE_TEST_IS_DIR ) ) ) {
874                                 _loadPaletteFile(full);
875                             }
876                             g_free(full);
877                         }
878                         g_free(lower);
879                     }
880                     g_dir_close(directory);
881                 }
882             }
884             // toss the dirname
885             g_free(dirname);
886             sources.pop_front();
887         }
888     }
899 SwatchesPanel& SwatchesPanel::getInstance()
901     if ( !instance ) {
902         instance = new SwatchesPanel();
903     }
905     return *instance;
910 /**
911  * Constructor
912  */
913 SwatchesPanel::SwatchesPanel() :
914     Inkscape::UI::Widget::Panel ("dialogs.swatches"),
915     _holder(0)
917     _holder = new PreviewHolder();
918     loadEmUp();
920     if ( !possible.empty() ) {
921         JustForNow* first = possible.front();
922         if ( first->_prefWidth > 0 ) {
923             _holder->setColumnPref( first->_prefWidth );
924         }
925         _holder->freezeUpdates();
926         for ( std::vector<ColorItem*>::iterator it = first->_colors.begin(); it != first->_colors.end(); it++ ) {
927             _holder->addPreview(*it);
928         }
929         _holder->thawUpdates();
931         Gtk::RadioMenuItem::Group groupOne;
932         int i = 0;
933         for ( std::vector<JustForNow*>::iterator it = possible.begin(); it != possible.end(); it++ ) {
934             JustForNow* curr = *it;
935             Gtk::RadioMenuItem* single = manage(new Gtk::RadioMenuItem(groupOne, curr->_name));
936             _regItem( single, 3, i );
937             i++;
938         }
940     }
943     _getContents()->pack_start(*_holder, Gtk::PACK_EXPAND_WIDGET);
944     _setTargetFillable(_holder);
946     show_all_children();
948     restorePanelPrefs();
951 SwatchesPanel::~SwatchesPanel()
955 void SwatchesPanel::setOrientation( Gtk::AnchorType how )
957     // Must call the parent class or bad things might happen
958     Inkscape::UI::Widget::Panel::setOrientation( how );
960     if ( _holder )
961     {
962         _holder->setOrientation( Gtk::ANCHOR_SOUTH );
963     }
966 void SwatchesPanel::_handleAction( int setId, int itemId )
968     switch( setId ) {
969         case 3:
970         {
971             if ( itemId >= 0 && itemId < static_cast<int>(possible.size()) ) {
972                 _holder->clear();
973                 JustForNow* curr = possible[itemId];
974                 if ( curr->_prefWidth > 0 ) {
975                     _holder->setColumnPref( curr->_prefWidth );
976                 }
977                 _holder->freezeUpdates();
978                 for ( std::vector<ColorItem*>::iterator it = curr->_colors.begin(); it != curr->_colors.end(); it++ ) {
979                     _holder->addPreview(*it);
980                 }
981                 _holder->thawUpdates();
982             }
983         }
984         break;
985     }
988 } //namespace Dialogs
989 } //namespace UI
990 } //namespace Inkscape
993 /*
994   Local Variables:
995   mode:c++
996   c-file-style:"stroustrup"
997   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
998   indent-tabs-mode:nil
999   fill-column:99
1000   End:
1001 */
1002 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :