1 /** @file
2 * @brief Color swatches dialog
3 */
4 /* Authors:
5 * Jon A. Cruz
6 * John Bintz
7 *
8 * Copyright (C) 2005 Jon A. Cruz
9 * Copyright (C) 2008 John Bintz
10 *
11 * Released under GNU GPL, read the file 'COPYING' for more information
12 */
14 #include <errno.h>
16 #include <gtk/gtkdialog.h> //for GTK_RESPONSE* types
17 #include <gtk/gtkdnd.h>
18 #include <gtk/gtkmenu.h>
19 #include <gtk/gtkmenuitem.h>
20 #include <gtk/gtkseparatormenuitem.h>
22 #include <glibmm/i18n.h>
23 #include <gdkmm/pixbuf.h>
24 #include "inkscape.h"
25 #include "desktop.h"
26 #include "message-context.h"
27 #include "document.h"
28 #include "desktop-handles.h"
29 #include "extension/db.h"
30 #include "inkscape.h"
31 #include "svg/svg-color.h"
32 #include "desktop-style.h"
33 #include "io/sys.h"
34 #include "path-prefix.h"
35 #include "swatches.h"
36 #include "sp-item.h"
37 #include "preferences.h"
39 #include "eek-preview.h"
41 namespace Inkscape {
42 namespace UI {
43 namespace Dialogs {
46 ColorItem::ColorItem( unsigned int r, unsigned int g, unsigned int b, Glib::ustring& name ) :
47 def( r, g, b, name ),
48 _isLive(false),
49 _linkIsTone(false),
50 _linkPercent(0),
51 _linkGray(0),
52 _linkSrc(0)
53 {
54 }
56 ColorItem::~ColorItem()
57 {
58 }
60 ColorItem::ColorItem(ColorItem const &other) :
61 Inkscape::UI::Previewable()
62 {
63 if ( this != &other ) {
64 *this = other;
65 }
66 }
68 ColorItem &ColorItem::operator=(ColorItem const &other)
69 {
70 if ( this != &other ) {
71 def = other.def;
73 // TODO - correct linkage
74 _linkSrc = other._linkSrc;
75 g_message("Erk!");
76 }
77 return *this;
78 }
81 class JustForNow
82 {
83 public:
84 JustForNow() : _prefWidth(0) {}
86 Glib::ustring _name;
87 int _prefWidth;
88 std::vector<ColorItem*> _colors;
89 };
91 static std::vector<JustForNow*> possible;
95 typedef enum {
96 APP_X_INKY_COLOR_ID = 0,
97 APP_X_INKY_COLOR = 0,
98 APP_X_COLOR,
99 TEXT_DATA
100 } colorFlavorType;
102 static const GtkTargetEntry sourceColorEntries[] = {
103 #if ENABLE_MAGIC_COLORS
104 // {"application/x-inkscape-color-id", GTK_TARGET_SAME_APP, APP_X_INKY_COLOR_ID},
105 {"application/x-inkscape-color", 0, APP_X_INKY_COLOR},
106 #endif // ENABLE_MAGIC_COLORS
107 {"application/x-color", 0, APP_X_COLOR},
108 {"text/plain", 0, TEXT_DATA},
109 };
111 void ColorItem::_dragGetColorData( GtkWidget *widget,
112 GdkDragContext *drag_context,
113 GtkSelectionData *data,
114 guint info,
115 guint time,
116 gpointer user_data)
117 {
118 (void)widget;
119 (void)drag_context;
120 (void)time;
121 static GdkAtom typeXColor = gdk_atom_intern("application/x-color", FALSE);
122 static GdkAtom typeText = gdk_atom_intern("text/plain", FALSE);
124 ColorItem* item = reinterpret_cast<ColorItem*>(user_data);
125 if ( info == TEXT_DATA ) {
126 gchar* tmp = g_strdup_printf("#%02x%02x%02x", item->def.getR(), item->def.getG(), item->def.getB() );
128 gtk_selection_data_set( data,
129 typeText,
130 8, // format
131 (guchar*)tmp,
132 strlen((const char*)tmp) + 1);
133 g_free(tmp);
134 tmp = 0;
135 } else if ( info == APP_X_INKY_COLOR ) {
136 Glib::ustring paletteName;
138 // Find where this thing came from
139 bool found = false;
140 int index = 0;
141 for ( std::vector<JustForNow*>::iterator it = possible.begin(); it != possible.end() && !found; ++it ) {
142 JustForNow* curr = *it;
143 index = 0;
144 for ( std::vector<ColorItem*>::iterator zz = curr->_colors.begin(); zz != curr->_colors.end(); ++zz ) {
145 if ( item == *zz ) {
146 found = true;
147 paletteName = curr->_name;
148 break;
149 } else {
150 index++;
151 }
152 }
153 }
155 // if ( found ) {
156 // g_message("Found the color at entry %d in palette '%s'", index, paletteName.c_str() );
157 // } else {
158 // g_message("Unable to find the color");
159 // }
160 int itemCount = 4 + 2 + 1 + paletteName.length();
162 guint16* tmp = new guint16[itemCount];
163 tmp[0] = (item->def.getR() << 8) | item->def.getR();
164 tmp[1] = (item->def.getG() << 8) | item->def.getG();
165 tmp[2] = (item->def.getB() << 8) | item->def.getB();
166 tmp[3] = 0xffff;
167 tmp[4] = (item->_isLive || !item->_listeners.empty() || (item->_linkSrc != 0) ) ? 1 : 0;
169 tmp[5] = index;
170 tmp[6] = paletteName.length();
171 for ( unsigned int i = 0; i < paletteName.length(); i++ ) {
172 tmp[7 + i] = paletteName[i];
173 }
174 gtk_selection_data_set( data,
175 typeXColor,
176 16, // format
177 reinterpret_cast<const guchar*>(tmp),
178 itemCount * 2);
179 delete[] tmp;
180 } else {
181 guint16 tmp[4];
182 tmp[0] = (item->def.getR() << 8) | item->def.getR();
183 tmp[1] = (item->def.getG() << 8) | item->def.getG();
184 tmp[2] = (item->def.getB() << 8) | item->def.getB();
185 tmp[3] = 0xffff;
186 gtk_selection_data_set( data,
187 typeXColor,
188 16, // format
189 reinterpret_cast<const guchar*>(tmp),
190 (3+1) * 2);
191 }
192 }
194 static void dragBegin( GtkWidget *widget, GdkDragContext* dc, gpointer data )
195 {
196 (void)widget;
197 ColorItem* item = reinterpret_cast<ColorItem*>(data);
198 if ( item )
199 {
200 Glib::RefPtr<Gdk::Pixbuf> thumb = Gdk::Pixbuf::create( Gdk::COLORSPACE_RGB, false, 8, 32, 24 );
201 guint32 fillWith = (0xff000000 & (item->def.getR() << 24))
202 | (0x00ff0000 & (item->def.getG() << 16))
203 | (0x0000ff00 & (item->def.getB() << 8));
204 thumb->fill( fillWith );
205 gtk_drag_set_icon_pixbuf( dc, thumb->gobj(), 0, 0 );
206 }
208 }
210 //"drag-drop"
211 // gboolean dragDropColorData( GtkWidget *widget,
212 // GdkDragContext *drag_context,
213 // gint x,
214 // gint y,
215 // guint time,
216 // gpointer user_data)
217 // {
218 // // TODO finish
220 // return TRUE;
221 // }
223 static void handleClick( GtkWidget* widget, gpointer callback_data ) {
224 (void)widget;
225 ColorItem* item = reinterpret_cast<ColorItem*>(callback_data);
226 if ( item ) {
227 item->buttonClicked(false);
228 }
229 }
231 static void handleSecondaryClick( GtkWidget* widget, gint arg1, gpointer callback_data ) {
232 (void)widget;
233 (void)arg1;
234 ColorItem* item = reinterpret_cast<ColorItem*>(callback_data);
235 if ( item ) {
236 item->buttonClicked(true);
237 }
238 }
240 static gboolean handleEnterNotify( GtkWidget* /*widget*/, GdkEventCrossing* /*event*/, gpointer callback_data ) {
241 ColorItem* item = reinterpret_cast<ColorItem*>(callback_data);
242 if ( item ) {
243 SPDesktop *desktop = SP_ACTIVE_DESKTOP;
244 if ( desktop ) {
245 gchar* msg = g_strdup_printf(_("Color: <b>%s</b>; <b>Click</b> to set fill, <b>Shift+click</b> to set stroke"),
246 item->def.descr.c_str());
247 desktop->tipsMessageContext()->set(Inkscape::INFORMATION_MESSAGE, msg);
248 g_free(msg);
249 }
250 }
251 return FALSE;
252 }
254 static gboolean handleLeaveNotify( GtkWidget* /*widget*/, GdkEventCrossing* /*event*/, gpointer callback_data ) {
255 ColorItem* item = reinterpret_cast<ColorItem*>(callback_data);
256 if ( item ) {
257 SPDesktop *desktop = SP_ACTIVE_DESKTOP;
258 if ( desktop ) {
259 desktop->tipsMessageContext()->clear();
260 }
261 }
262 return FALSE;
263 }
265 static GtkWidget* popupMenu = 0;
266 static ColorItem* bounceTarget = 0;
268 static void redirClick( GtkMenuItem *menuitem, gpointer user_data )
269 {
270 (void)user_data;
271 if ( bounceTarget ) {
272 handleClick( GTK_WIDGET(menuitem), bounceTarget );
273 }
274 }
276 static void redirSecondaryClick( GtkMenuItem *menuitem, gpointer user_data )
277 {
278 (void)user_data;
279 if ( bounceTarget ) {
280 handleSecondaryClick( GTK_WIDGET(menuitem), 0, bounceTarget );
281 }
282 }
284 static gboolean handleButtonPress( GtkWidget* widget, GdkEventButton* event, gpointer user_data)
285 {
286 (void)widget;
287 gboolean handled = FALSE;
289 if ( (event->button == 3) && (event->type == GDK_BUTTON_PRESS) ) {
290 if ( !popupMenu ) {
291 popupMenu = gtk_menu_new();
292 GtkWidget* child = 0;
294 //TRANSLATORS: An item in context menu on a colour in the swatches
295 child = gtk_menu_item_new_with_label(_("Set fill"));
296 g_signal_connect( G_OBJECT(child),
297 "activate",
298 G_CALLBACK(redirClick),
299 user_data);
300 gtk_menu_shell_append(GTK_MENU_SHELL(popupMenu), child);
302 //TRANSLATORS: An item in context menu on a colour in the swatches
303 child = gtk_menu_item_new_with_label(_("Set stroke"));
305 g_signal_connect( G_OBJECT(child),
306 "activate",
307 G_CALLBACK(redirSecondaryClick),
308 user_data);
309 gtk_menu_shell_append(GTK_MENU_SHELL(popupMenu), child);
311 gtk_widget_show_all(popupMenu);
312 }
314 ColorItem* item = reinterpret_cast<ColorItem*>(user_data);
315 if ( item ) {
316 bounceTarget = item;
317 if ( popupMenu ) {
318 gtk_menu_popup(GTK_MENU(popupMenu), NULL, NULL, NULL, NULL, event->button, event->time);
319 handled = TRUE;
320 }
321 }
322 }
324 return handled;
325 }
327 static void dieDieDie( GtkObject *obj, gpointer user_data )
328 {
329 g_message("die die die %p %p", obj, user_data );
330 }
332 static const GtkTargetEntry destColorTargets[] = {
333 #if ENABLE_MAGIC_COLORS
334 // {"application/x-inkscape-color-id", GTK_TARGET_SAME_APP, APP_X_INKY_COLOR_ID},
335 {"application/x-inkscape-color", 0, APP_X_INKY_COLOR},
336 #endif // ENABLE_MAGIC_COLORS
337 {"application/x-color", 0, APP_X_COLOR},
338 };
340 #include "color.h" // for SP_RGBA32_U_COMPOSE
342 void ColorItem::_dropDataIn( GtkWidget *widget,
343 GdkDragContext *drag_context,
344 gint x, gint y,
345 GtkSelectionData *data,
346 guint info,
347 guint event_time,
348 gpointer user_data)
349 {
350 (void)widget;
351 (void)drag_context;
352 (void)x;
353 (void)y;
354 (void)event_time;
355 // g_message(" droppy droppy %d", info);
356 switch (info) {
357 case APP_X_INKY_COLOR:
358 {
359 if ( data->length >= 8 ) {
360 // Careful about endian issues.
361 guint16* dataVals = (guint16*)data->data;
362 if ( user_data ) {
363 ColorItem* item = reinterpret_cast<ColorItem*>(user_data);
364 if ( item->def.isEditable() ) {
365 // Shove on in the new value
366 item->def.setRGB( 0x0ff & (dataVals[0] >> 8), 0x0ff & (dataVals[1] >> 8), 0x0ff & (dataVals[2] >> 8) );
367 }
368 }
369 }
370 break;
371 }
372 case APP_X_COLOR:
373 {
374 if ( data->length == 8 ) {
375 // Careful about endian issues.
376 guint16* dataVals = (guint16*)data->data;
377 // {
378 // gchar c[64] = {0};
379 // sp_svg_write_color( c, 64,
380 // SP_RGBA32_U_COMPOSE(
381 // 0x0ff & (dataVals[0] >> 8),
382 // 0x0ff & (dataVals[1] >> 8),
383 // 0x0ff & (dataVals[2] >> 8),
384 // 0xff // can't have transparency in the color itself
385 // //0x0ff & (data->data[3] >> 8),
386 // ));
387 // }
388 if ( user_data ) {
389 ColorItem* item = reinterpret_cast<ColorItem*>(user_data);
390 if ( item->def.isEditable() ) {
391 // Shove on in the new value
392 item->def.setRGB( 0x0ff & (dataVals[0] >> 8), 0x0ff & (dataVals[1] >> 8), 0x0ff & (dataVals[2] >> 8) );
393 }
394 }
395 }
396 break;
397 }
398 default:
399 g_message("unknown drop type");
400 }
402 }
404 static bool bruteForce( SPDocument* document, Inkscape::XML::Node* node, Glib::ustring const& match, int r, int g, int b )
405 {
406 bool changed = false;
408 if ( node ) {
409 gchar const * val = node->attribute("inkscape:x-fill-tag");
410 if ( val && (match == val) ) {
411 SPObject *obj = document->getObjectByRepr( node );
413 gchar c[64] = {0};
414 sp_svg_write_color( c, sizeof(c), SP_RGBA32_U_COMPOSE( r, g, b, 0xff ) );
415 SPCSSAttr *css = sp_repr_css_attr_new();
416 sp_repr_css_set_property( css, "fill", c );
418 sp_desktop_apply_css_recursive( (SPItem*)obj, css, true );
419 ((SPItem*)obj)->updateRepr();
421 changed = true;
422 }
424 val = node->attribute("inkscape:x-stroke-tag");
425 if ( val && (match == val) ) {
426 SPObject *obj = document->getObjectByRepr( node );
428 gchar c[64] = {0};
429 sp_svg_write_color( c, sizeof(c), SP_RGBA32_U_COMPOSE( r, g, b, 0xff ) );
430 SPCSSAttr *css = sp_repr_css_attr_new();
431 sp_repr_css_set_property( css, "stroke", c );
433 sp_desktop_apply_css_recursive( (SPItem*)obj, css, true );
434 ((SPItem*)obj)->updateRepr();
436 changed = true;
437 }
439 Inkscape::XML::Node* first = node->firstChild();
440 changed |= bruteForce( document, first, match, r, g, b );
442 changed |= bruteForce( document, node->next(), match, r, g, b );
443 }
445 return changed;
446 }
448 void ColorItem::_colorDefChanged(void* data)
449 {
450 ColorItem* item = reinterpret_cast<ColorItem*>(data);
451 if ( item ) {
452 for ( std::vector<Gtk::Widget*>::iterator it = item->_previews.begin(); it != item->_previews.end(); ++it ) {
453 Gtk::Widget* widget = *it;
454 if ( IS_EEK_PREVIEW(widget->gobj()) ) {
455 EekPreview * preview = EEK_PREVIEW(widget->gobj());
456 eek_preview_set_color( preview,
457 (item->def.getR() << 8) | item->def.getR(),
458 (item->def.getG() << 8) | item->def.getG(),
459 (item->def.getB() << 8) | item->def.getB() );
461 eek_preview_set_linked( preview, (LinkType)((item->_linkSrc ? PREVIEW_LINK_IN:0)
462 | (item->_listeners.empty() ? 0:PREVIEW_LINK_OUT)
463 | (item->_isLive ? PREVIEW_LINK_OTHER:0)) );
465 widget->queue_draw();
466 }
467 }
469 for ( std::vector<ColorItem*>::iterator it = item->_listeners.begin(); it != item->_listeners.end(); ++it ) {
470 guint r = item->def.getR();
471 guint g = item->def.getG();
472 guint b = item->def.getB();
474 if ( (*it)->_linkIsTone ) {
475 r = ( ((*it)->_linkPercent * (*it)->_linkGray) + ((100 - (*it)->_linkPercent) * r) ) / 100;
476 g = ( ((*it)->_linkPercent * (*it)->_linkGray) + ((100 - (*it)->_linkPercent) * g) ) / 100;
477 b = ( ((*it)->_linkPercent * (*it)->_linkGray) + ((100 - (*it)->_linkPercent) * b) ) / 100;
478 } else {
479 r = ( ((*it)->_linkPercent * 255) + ((100 - (*it)->_linkPercent) * r) ) / 100;
480 g = ( ((*it)->_linkPercent * 255) + ((100 - (*it)->_linkPercent) * g) ) / 100;
481 b = ( ((*it)->_linkPercent * 255) + ((100 - (*it)->_linkPercent) * b) ) / 100;
482 }
484 (*it)->def.setRGB( r, g, b );
485 }
488 // Look for objects using this color
489 {
490 SPDesktop *desktop = SP_ACTIVE_DESKTOP;
491 if ( desktop ) {
492 SPDocument* document = sp_desktop_document( desktop );
493 Inkscape::XML::Node *rroot = sp_document_repr_root( document );
494 if ( rroot ) {
496 // Find where this thing came from
497 Glib::ustring paletteName;
498 bool found = false;
499 int index = 0;
500 for ( std::vector<JustForNow*>::iterator it2 = possible.begin(); it2 != possible.end() && !found; ++it2 ) {
501 JustForNow* curr = *it2;
502 index = 0;
503 for ( std::vector<ColorItem*>::iterator zz = curr->_colors.begin(); zz != curr->_colors.end(); ++zz ) {
504 if ( item == *zz ) {
505 found = true;
506 paletteName = curr->_name;
507 break;
508 } else {
509 index++;
510 }
511 }
512 }
514 if ( !paletteName.empty() ) {
515 gchar* str = g_strdup_printf("%d|", index);
516 paletteName.insert( 0, str );
517 g_free(str);
518 str = 0;
520 if ( bruteForce( document, rroot, paletteName, item->def.getR(), item->def.getG(), item->def.getB() ) ) {
521 sp_document_done( document , SP_VERB_DIALOG_SWATCHES,
522 _("Change color definition"));
523 }
524 }
525 }
526 }
527 }
528 }
529 }
532 Gtk::Widget* ColorItem::getPreview(PreviewStyle style, ViewType view, ::PreviewSize size, guint ratio)
533 {
534 Gtk::Widget* widget = 0;
535 if ( style == PREVIEW_STYLE_BLURB ) {
536 Gtk::Label *lbl = new Gtk::Label(def.descr);
537 lbl->set_alignment(Gtk::ALIGN_LEFT, Gtk::ALIGN_CENTER);
538 widget = lbl;
539 } else {
540 // Glib::ustring blank(" ");
541 // if ( size == Inkscape::ICON_SIZE_MENU || size == Inkscape::ICON_SIZE_DECORATION ) {
542 // blank = " ";
543 // }
545 GtkWidget* eekWidget = eek_preview_new();
546 EekPreview * preview = EEK_PREVIEW(eekWidget);
547 Gtk::Widget* newBlot = Glib::wrap(eekWidget);
549 eek_preview_set_color( preview, (def.getR() << 8) | def.getR(), (def.getG() << 8) | def.getG(), (def.getB() << 8) | def.getB());
551 eek_preview_set_details( preview, (::PreviewStyle)style, (::ViewType)view, (::PreviewSize)size, ratio );
552 eek_preview_set_linked( preview, (LinkType)((_linkSrc ? PREVIEW_LINK_IN:0)
553 | (_listeners.empty() ? 0:PREVIEW_LINK_OUT)
554 | (_isLive ? PREVIEW_LINK_OTHER:0)) );
556 def.addCallback( _colorDefChanged, this );
558 GValue val = {0, {{0}, {0}}};
559 g_value_init( &val, G_TYPE_BOOLEAN );
560 g_value_set_boolean( &val, FALSE );
561 g_object_set_property( G_OBJECT(preview), "focus-on-click", &val );
563 /*
564 Gtk::Button *btn = new Gtk::Button(blank);
565 Gdk::Color color;
566 color.set_rgb((_r << 8)|_r, (_g << 8)|_g, (_b << 8)|_b);
567 btn->modify_bg(Gtk::STATE_NORMAL, color);
568 btn->modify_bg(Gtk::STATE_ACTIVE, color);
569 btn->modify_bg(Gtk::STATE_PRELIGHT, color);
570 btn->modify_bg(Gtk::STATE_SELECTED, color);
572 Gtk::Widget* newBlot = btn;
573 */
575 tips.set_tip((*newBlot), def.descr);
577 /*
578 newBlot->signal_clicked().connect( sigc::mem_fun(*this, &ColorItem::buttonClicked) );
580 sigc::signal<void> type_signal_something;
581 */
583 g_signal_connect( G_OBJECT(newBlot->gobj()),
584 "clicked",
585 G_CALLBACK(handleClick),
586 this);
588 g_signal_connect( G_OBJECT(newBlot->gobj()),
589 "alt-clicked",
590 G_CALLBACK(handleSecondaryClick),
591 this);
593 g_signal_connect( G_OBJECT(newBlot->gobj()),
594 "button-press-event",
595 G_CALLBACK(handleButtonPress),
596 this);
598 gtk_drag_source_set( GTK_WIDGET(newBlot->gobj()),
599 GDK_BUTTON1_MASK,
600 sourceColorEntries,
601 G_N_ELEMENTS(sourceColorEntries),
602 GdkDragAction(GDK_ACTION_MOVE | GDK_ACTION_COPY) );
604 g_signal_connect( G_OBJECT(newBlot->gobj()),
605 "drag-data-get",
606 G_CALLBACK(ColorItem::_dragGetColorData),
607 this);
609 g_signal_connect( G_OBJECT(newBlot->gobj()),
610 "drag-begin",
611 G_CALLBACK(dragBegin),
612 this );
614 g_signal_connect( G_OBJECT(newBlot->gobj()),
615 "enter-notify-event",
616 G_CALLBACK(handleEnterNotify),
617 this);
619 g_signal_connect( G_OBJECT(newBlot->gobj()),
620 "leave-notify-event",
621 G_CALLBACK(handleLeaveNotify),
622 this);
624 // g_signal_connect( G_OBJECT(newBlot->gobj()),
625 // "drag-drop",
626 // G_CALLBACK(dragDropColorData),
627 // this);
629 if ( def.isEditable() )
630 {
631 gtk_drag_dest_set( GTK_WIDGET(newBlot->gobj()),
632 GTK_DEST_DEFAULT_ALL,
633 destColorTargets,
634 G_N_ELEMENTS(destColorTargets),
635 GdkDragAction(GDK_ACTION_COPY | GDK_ACTION_MOVE) );
638 g_signal_connect( G_OBJECT(newBlot->gobj()),
639 "drag-data-received",
640 G_CALLBACK(_dropDataIn),
641 this );
642 }
644 g_signal_connect( G_OBJECT(newBlot->gobj()),
645 "destroy",
646 G_CALLBACK(dieDieDie),
647 this);
650 widget = newBlot;
651 }
653 _previews.push_back( widget );
655 return widget;
656 }
658 void ColorItem::buttonClicked(bool secondary)
659 {
660 SPDesktop *desktop = SP_ACTIVE_DESKTOP;
661 if (desktop) {
662 char const * attrName = secondary ? "stroke" : "fill";
663 guint32 rgba = (def.getR() << 24) | (def.getG() << 16) | (def.getB() << 8) | 0xff;
664 gchar c[64];
665 sp_svg_write_color(c, sizeof(c), rgba);
667 SPCSSAttr *css = sp_repr_css_attr_new();
668 sp_repr_css_set_property( css, attrName, c );
669 sp_desktop_set_style(desktop, css);
671 sp_repr_css_attr_unref(css);
672 sp_document_done (sp_desktop_document (desktop), SP_VERB_DIALOG_SWATCHES,
673 secondary? _("Set stroke color from swatch") : _("Set fill color from swatch"));
674 }
675 }
680 static char* trim( char* str ) {
681 char* ret = str;
682 while ( *str && (*str == ' ' || *str == '\t') ) {
683 str++;
684 }
685 ret = str;
686 while ( *str ) {
687 str++;
688 }
689 str--;
690 while ( str > ret && ( *str == ' ' || *str == '\t' ) || *str == '\r' || *str == '\n' ) {
691 *str-- = 0;
692 }
693 return ret;
694 }
696 void skipWhitespace( char*& str ) {
697 while ( *str == ' ' || *str == '\t' ) {
698 str++;
699 }
700 }
702 bool parseNum( char*& str, int& val ) {
703 val = 0;
704 while ( '0' <= *str && *str <= '9' ) {
705 val = val * 10 + (*str - '0');
706 str++;
707 }
708 bool retval = !(*str == 0 || *str == ' ' || *str == '\t' || *str == '\r' || *str == '\n');
709 return retval;
710 }
713 static bool getBlock( std::string& dst, guchar ch, std::string const str )
714 {
715 bool good = false;
716 std::string::size_type pos = str.find(ch);
717 if ( pos != std::string::npos )
718 {
719 std::string::size_type pos2 = str.find( '(', pos );
720 if ( pos2 != std::string::npos ) {
721 std::string::size_type endPos = str.find( ')', pos2 );
722 if ( endPos != std::string::npos ) {
723 dst = str.substr( pos2 + 1, (endPos - pos2 - 1) );
724 good = true;
725 }
726 }
727 }
728 return good;
729 }
731 static bool popVal( guint64& numVal, std::string& str )
732 {
733 bool good = false;
734 std::string::size_type endPos = str.find(',');
735 if ( endPos == std::string::npos ) {
736 endPos = str.length();
737 }
739 if ( endPos != std::string::npos && endPos > 0 ) {
740 std::string xxx = str.substr( 0, endPos );
741 const gchar* ptr = xxx.c_str();
742 gchar* endPtr = 0;
743 numVal = g_ascii_strtoull( ptr, &endPtr, 10 );
744 if ( (numVal == G_MAXUINT64) && (ERANGE == errno) ) {
745 // overflow
746 } else if ( (numVal == 0) && (endPtr == ptr) ) {
747 // failed conversion
748 } else {
749 good = true;
750 str.erase( 0, endPos + 1 );
751 }
752 }
754 return good;
755 }
757 void ColorItem::_wireMagicColors( void* p )
758 {
759 JustForNow* onceMore = reinterpret_cast<JustForNow*>(p);
760 if ( onceMore )
761 {
762 for ( std::vector<ColorItem*>::iterator it = onceMore->_colors.begin(); it != onceMore->_colors.end(); ++it )
763 {
764 std::string::size_type pos = (*it)->def.descr.find("*{");
765 if ( pos != std::string::npos )
766 {
767 std::string subby = (*it)->def.descr.substr( pos + 2 );
768 std::string::size_type endPos = subby.find("}*");
769 if ( endPos != std::string::npos )
770 {
771 subby.erase( endPos );
772 //g_message("FOUND MAGIC at '%s'", (*it)->def.descr.c_str());
773 //g_message(" '%s'", subby.c_str());
775 if ( subby.find('E') != std::string::npos )
776 {
777 (*it)->def.setEditable( true );
778 }
780 if ( subby.find('L') != std::string::npos )
781 {
782 (*it)->_isLive = true;
783 }
785 std::string part;
786 // Tint. index + 1 more val.
787 if ( getBlock( part, 'T', subby ) ) {
788 guint64 colorIndex = 0;
789 if ( popVal( colorIndex, part ) ) {
790 guint64 percent = 0;
791 if ( popVal( percent, part ) ) {
792 (*it)->_linkTint( *(onceMore->_colors[colorIndex]), percent );
793 }
794 }
795 }
797 // Shade/tone. index + 1 or 2 more val.
798 if ( getBlock( part, 'S', subby ) ) {
799 guint64 colorIndex = 0;
800 if ( popVal( colorIndex, part ) ) {
801 guint64 percent = 0;
802 if ( popVal( percent, part ) ) {
803 guint64 grayLevel = 0;
804 if ( !popVal( grayLevel, part ) ) {
805 grayLevel = 0;
806 }
807 (*it)->_linkTone( *(onceMore->_colors[colorIndex]), percent, grayLevel );
808 }
809 }
810 }
812 }
813 }
814 }
815 }
816 }
819 void ColorItem::_linkTint( ColorItem& other, int percent )
820 {
821 if ( !_linkSrc )
822 {
823 other._listeners.push_back(this);
824 _linkIsTone = false;
825 _linkPercent = percent;
826 if ( _linkPercent > 100 )
827 _linkPercent = 100;
828 if ( _linkPercent < 0 )
829 _linkPercent = 0;
830 _linkGray = 0;
831 _linkSrc = &other;
833 ColorItem::_colorDefChanged(&other);
834 }
835 }
837 void ColorItem::_linkTone( ColorItem& other, int percent, int grayLevel )
838 {
839 if ( !_linkSrc )
840 {
841 other._listeners.push_back(this);
842 _linkIsTone = true;
843 _linkPercent = percent;
844 if ( _linkPercent > 100 )
845 _linkPercent = 100;
846 if ( _linkPercent < 0 )
847 _linkPercent = 0;
848 _linkGray = grayLevel;
849 _linkSrc = &other;
851 ColorItem::_colorDefChanged(&other);
852 }
853 }
856 void _loadPaletteFile( gchar const *filename )
857 {
858 char block[1024];
859 FILE *f = Inkscape::IO::fopen_utf8name( filename, "r" );
860 if ( f ) {
861 char* result = fgets( block, sizeof(block), f );
862 if ( result ) {
863 if ( strncmp( "GIMP Palette", block, 12 ) == 0 ) {
864 bool inHeader = true;
865 bool hasErr = false;
867 JustForNow *onceMore = new JustForNow();
869 do {
870 result = fgets( block, sizeof(block), f );
871 block[sizeof(block) - 1] = 0;
872 if ( result ) {
873 if ( block[0] == '#' ) {
874 // ignore comment
875 } else {
876 char *ptr = block;
877 // very simple check for header versus entry
878 while ( *ptr == ' ' || *ptr == '\t' ) {
879 ptr++;
880 }
881 if ( (*ptr == 0) || (*ptr == '\r') || (*ptr == '\n') ) {
882 // blank line. skip it.
883 } else if ( '0' <= *ptr && *ptr <= '9' ) {
884 // should be an entry link
885 inHeader = false;
886 ptr = block;
887 Glib::ustring name("");
888 int r = 0;
889 int g = 0;
890 int b = 0;
891 skipWhitespace(ptr);
892 if ( *ptr ) {
893 hasErr = parseNum(ptr, r);
894 if ( !hasErr ) {
895 skipWhitespace(ptr);
896 hasErr = parseNum(ptr, g);
897 }
898 if ( !hasErr ) {
899 skipWhitespace(ptr);
900 hasErr = parseNum(ptr, b);
901 }
902 if ( !hasErr && *ptr ) {
903 char* n = trim(ptr);
904 if (n != NULL) {
905 name = n;
906 }
907 }
908 if ( !hasErr ) {
909 // Add the entry now
910 Glib::ustring nameStr(name);
911 ColorItem* item = new ColorItem( r, g, b, nameStr );
912 onceMore->_colors.push_back(item);
913 }
914 } else {
915 hasErr = true;
916 }
917 } else {
918 if ( !inHeader ) {
919 // Hmmm... probably bad. Not quite the format we want?
920 hasErr = true;
921 } else {
922 char* sep = strchr(result, ':');
923 if ( sep ) {
924 *sep = 0;
925 char* val = trim(sep + 1);
926 char* name = trim(result);
927 if ( *name ) {
928 if ( strcmp( "Name", name ) == 0 )
929 {
930 onceMore->_name = val;
931 }
932 else if ( strcmp( "Columns", name ) == 0 )
933 {
934 gchar* endPtr = 0;
935 guint64 numVal = g_ascii_strtoull( val, &endPtr, 10 );
936 if ( (numVal == G_MAXUINT64) && (ERANGE == errno) ) {
937 // overflow
938 } else if ( (numVal == 0) && (endPtr == val) ) {
939 // failed conversion
940 } else {
941 onceMore->_prefWidth = numVal;
942 }
943 }
944 } else {
945 // error
946 hasErr = true;
947 }
948 } else {
949 // error
950 hasErr = true;
951 }
952 }
953 }
954 }
955 }
956 } while ( result && !hasErr );
957 if ( !hasErr ) {
958 possible.push_back(onceMore);
959 #if ENABLE_MAGIC_COLORS
960 ColorItem::_wireMagicColors( onceMore );
961 #endif // ENABLE_MAGIC_COLORS
962 } else {
963 delete onceMore;
964 }
965 }
966 }
968 fclose(f);
969 }
970 }
972 static void loadEmUp()
973 {
974 static bool beenHere = false;
975 if ( !beenHere ) {
976 beenHere = true;
978 std::list<gchar *> sources;
979 sources.push_back( profile_path("palettes") );
980 sources.push_back( g_strdup(INKSCAPE_PALETTESDIR) );
981 sources.push_back( g_strdup(CREATE_PALETTESDIR) );
983 // Use this loop to iterate through a list of possible document locations.
984 while (!sources.empty()) {
985 gchar *dirname = sources.front();
987 if ( Inkscape::IO::file_test( dirname, G_FILE_TEST_EXISTS )
988 && Inkscape::IO::file_test( dirname, G_FILE_TEST_IS_DIR )) {
989 GError *err = 0;
990 GDir *directory = g_dir_open(dirname, 0, &err);
991 if (!directory) {
992 gchar *safeDir = Inkscape::IO::sanitizeString(dirname);
993 g_warning(_("Palettes directory (%s) is unavailable."), safeDir);
994 g_free(safeDir);
995 } else {
996 gchar *filename = 0;
997 while ((filename = (gchar *)g_dir_read_name(directory)) != NULL) {
998 gchar* lower = g_ascii_strdown( filename, -1 );
999 // if ( g_str_has_suffix(lower, ".gpl") ) {
1000 gchar* full = g_build_filename(dirname, filename, NULL);
1001 if ( !Inkscape::IO::file_test( full, G_FILE_TEST_IS_DIR ) ) {
1002 _loadPaletteFile(full);
1003 }
1004 g_free(full);
1005 // }
1006 g_free(lower);
1007 }
1008 g_dir_close(directory);
1009 }
1010 }
1012 // toss the dirname
1013 g_free(dirname);
1014 sources.pop_front();
1015 }
1016 }
1017 }
1027 SwatchesPanel& SwatchesPanel::getInstance()
1028 {
1029 return *new SwatchesPanel();
1030 }
1033 /**
1034 * Constructor
1035 */
1036 SwatchesPanel::SwatchesPanel(gchar const* prefsPath) :
1037 Inkscape::UI::Widget::Panel("", prefsPath, SP_VERB_DIALOG_SWATCHES, "", true),
1038 _holder(0)
1039 {
1040 Gtk::RadioMenuItem* hotItem = 0;
1041 _holder = new PreviewHolder();
1042 loadEmUp();
1044 if ( !possible.empty() ) {
1045 JustForNow* first = 0;
1046 Glib::ustring targetName;
1047 if ( !_prefs_path.empty() ) {
1048 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1049 targetName = prefs->getString(_prefs_path + "/palette");
1050 if (!targetName.empty()) {
1051 for ( std::vector<JustForNow*>::iterator iter = possible.begin(); iter != possible.end(); ++iter ) {
1052 if ( (*iter)->_name == targetName ) {
1053 first = *iter;
1054 break;
1055 }
1056 }
1057 }
1058 }
1060 if ( !first ) {
1061 first = possible.front();
1062 }
1064 if ( first->_prefWidth > 0 ) {
1065 _holder->setColumnPref( first->_prefWidth );
1066 }
1067 _holder->freezeUpdates();
1068 for ( std::vector<ColorItem*>::iterator it = first->_colors.begin(); it != first->_colors.end(); it++ ) {
1069 _holder->addPreview(*it);
1070 }
1071 _holder->thawUpdates();
1073 Gtk::RadioMenuItem::Group groupOne;
1074 int i = 0;
1075 for ( std::vector<JustForNow*>::iterator it = possible.begin(); it != possible.end(); it++ ) {
1076 JustForNow* curr = *it;
1077 Gtk::RadioMenuItem* single = manage(new Gtk::RadioMenuItem(groupOne, curr->_name));
1078 if ( curr == first ) {
1079 hotItem = single;
1080 }
1081 _regItem( single, 3, i );
1082 i++;
1083 }
1085 }
1088 _getContents()->pack_start(*_holder, Gtk::PACK_EXPAND_WIDGET);
1089 _setTargetFillable(_holder);
1091 show_all_children();
1093 restorePanelPrefs();
1094 if ( hotItem ) {
1095 hotItem->set_active();
1096 }
1097 }
1099 SwatchesPanel::~SwatchesPanel()
1100 {
1101 }
1103 void SwatchesPanel::setOrientation( Gtk::AnchorType how )
1104 {
1105 // Must call the parent class or bad things might happen
1106 Inkscape::UI::Widget::Panel::setOrientation( how );
1108 if ( _holder )
1109 {
1110 _holder->setOrientation( Gtk::ANCHOR_SOUTH );
1111 }
1112 }
1114 void SwatchesPanel::_handleAction( int setId, int itemId )
1115 {
1116 switch( setId ) {
1117 case 3:
1118 {
1119 if ( itemId >= 0 && itemId < static_cast<int>(possible.size()) ) {
1120 _holder->clear();
1121 JustForNow* curr = possible[itemId];
1123 if ( !_prefs_path.empty() ) {
1124 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1125 prefs->setString(_prefs_path + "/palette", curr->_name);
1126 }
1128 if ( curr->_prefWidth > 0 ) {
1129 _holder->setColumnPref( curr->_prefWidth );
1130 }
1131 _holder->freezeUpdates();
1132 for ( std::vector<ColorItem*>::iterator it = curr->_colors.begin(); it != curr->_colors.end(); it++ ) {
1133 _holder->addPreview(*it);
1134 }
1135 _holder->thawUpdates();
1136 }
1137 }
1138 break;
1139 }
1140 }
1142 } //namespace Dialogs
1143 } //namespace UI
1144 } //namespace Inkscape
1147 /*
1148 Local Variables:
1149 mode:c++
1150 c-file-style:"stroustrup"
1151 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1152 indent-tabs-mode:nil
1153 fill-column:99
1154 End:
1155 */
1156 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :