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 {
45 ColorItem::ColorItem() : _isRemove(true){};
46 ColorItem::ColorItem( unsigned int r, unsigned int g, unsigned int b, Glib::ustring& name ) :
47 def( r, g, b, name ),
48 _isRemove(false),
49 _isLive(false),
50 _linkIsTone(false),
51 _linkPercent(0),
52 _linkGray(0),
53 _linkSrc(0)
54 {
55 }
57 ColorItem::~ColorItem()
58 {
59 }
61 ColorItem::ColorItem(ColorItem const &other) :
62 Inkscape::UI::Previewable()
63 {
64 if ( this != &other ) {
65 *this = other;
66 }
67 }
69 ColorItem &ColorItem::operator=(ColorItem const &other)
70 {
71 if ( this != &other ) {
72 def = other.def;
74 // TODO - correct linkage
75 _linkSrc = other._linkSrc;
76 g_message("Erk!");
77 }
78 return *this;
79 }
82 class JustForNow
83 {
84 public:
85 JustForNow() : _prefWidth(0) {}
87 Glib::ustring _name;
88 int _prefWidth;
89 std::vector<ColorItem*> _colors;
90 };
92 static std::vector<JustForNow*> possible;
96 typedef enum {
97 APP_X_INKY_COLOR_ID = 0,
98 APP_X_INKY_COLOR = 0,
99 APP_X_COLOR,
100 TEXT_DATA
101 } colorFlavorType;
103 //TODO: warning: deprecated conversion from string constant to ‘gchar*’
104 //
105 //Turn out to be warnings that we should probably leave in place. The
106 // pointers/types used need to be read-only. So until we correct the using
107 // code, those warnings are actually desired. They say "Hey! Fix this". We
108 // definitely don't want to hide/ignore them. --JonCruz
109 static const GtkTargetEntry sourceColorEntries[] = {
110 #if ENABLE_MAGIC_COLORS
111 // {"application/x-inkscape-color-id", GTK_TARGET_SAME_APP, APP_X_INKY_COLOR_ID},
112 {"application/x-inkscape-color", 0, APP_X_INKY_COLOR},
113 #endif // ENABLE_MAGIC_COLORS
114 {"application/x-color", 0, APP_X_COLOR},
115 {"text/plain", 0, TEXT_DATA},
116 };
118 void ColorItem::_dragGetColorData( GtkWidget *widget,
119 GdkDragContext *drag_context,
120 GtkSelectionData *data,
121 guint info,
122 guint time,
123 gpointer user_data)
124 {
125 (void)widget;
126 (void)drag_context;
127 (void)time;
128 static GdkAtom typeXColor = gdk_atom_intern("application/x-color", FALSE);
129 static GdkAtom typeText = gdk_atom_intern("text/plain", FALSE);
131 ColorItem* item = reinterpret_cast<ColorItem*>(user_data);
132 if ( info == TEXT_DATA ) {
133 gchar* tmp = g_strdup_printf("#%02x%02x%02x", item->def.getR(), item->def.getG(), item->def.getB() );
135 gtk_selection_data_set( data,
136 typeText,
137 8, // format
138 (guchar*)tmp,
139 strlen((const char*)tmp) + 1);
140 g_free(tmp);
141 tmp = 0;
142 } else if ( info == APP_X_INKY_COLOR ) {
143 Glib::ustring paletteName;
145 // Find where this thing came from
146 bool found = false;
147 int index = 0;
148 for ( std::vector<JustForNow*>::iterator it = possible.begin(); it != possible.end() && !found; ++it ) {
149 JustForNow* curr = *it;
150 index = 0;
151 for ( std::vector<ColorItem*>::iterator zz = curr->_colors.begin(); zz != curr->_colors.end(); ++zz ) {
152 if ( item == *zz ) {
153 found = true;
154 paletteName = curr->_name;
155 break;
156 } else {
157 index++;
158 }
159 }
160 }
162 // if ( found ) {
163 // g_message("Found the color at entry %d in palette '%s'", index, paletteName.c_str() );
164 // } else {
165 // g_message("Unable to find the color");
166 // }
167 int itemCount = 4 + 2 + 1 + paletteName.length();
169 guint16* tmp = new guint16[itemCount];
170 tmp[0] = (item->def.getR() << 8) | item->def.getR();
171 tmp[1] = (item->def.getG() << 8) | item->def.getG();
172 tmp[2] = (item->def.getB() << 8) | item->def.getB();
173 tmp[3] = 0xffff;
174 tmp[4] = (item->_isLive || !item->_listeners.empty() || (item->_linkSrc != 0) ) ? 1 : 0;
176 tmp[5] = index;
177 tmp[6] = paletteName.length();
178 for ( unsigned int i = 0; i < paletteName.length(); i++ ) {
179 tmp[7 + i] = paletteName[i];
180 }
181 gtk_selection_data_set( data,
182 typeXColor,
183 16, // format
184 reinterpret_cast<const guchar*>(tmp),
185 itemCount * 2);
186 delete[] tmp;
187 } else {
188 guint16 tmp[4];
189 tmp[0] = (item->def.getR() << 8) | item->def.getR();
190 tmp[1] = (item->def.getG() << 8) | item->def.getG();
191 tmp[2] = (item->def.getB() << 8) | item->def.getB();
192 tmp[3] = 0xffff;
193 gtk_selection_data_set( data,
194 typeXColor,
195 16, // format
196 reinterpret_cast<const guchar*>(tmp),
197 (3+1) * 2);
198 }
199 }
201 static void dragBegin( GtkWidget *widget, GdkDragContext* dc, gpointer data )
202 {
203 (void)widget;
204 ColorItem* item = reinterpret_cast<ColorItem*>(data);
205 if ( item )
206 {
207 if (item->isRemove()){
208 GError *error = NULL;
209 gchar *filepath = (gchar *) g_strdup_printf("%s/remove-color.png", INKSCAPE_PIXMAPDIR);
210 gsize bytesRead = 0;
211 gsize bytesWritten = 0;
212 gchar *localFilename = g_filename_from_utf8( filepath,
213 -1,
214 &bytesRead,
215 &bytesWritten,
216 &error);
217 GdkPixbuf* pixbuf = gdk_pixbuf_new_from_file_at_scale(localFilename, 32, 24, FALSE, &error);
218 g_free(localFilename);
219 g_free(filepath);
220 gtk_drag_set_icon_pixbuf( dc, pixbuf, 0, 0 );
221 return;
222 }
224 Glib::RefPtr<Gdk::Pixbuf> thumb = Gdk::Pixbuf::create( Gdk::COLORSPACE_RGB, false, 8, 32, 24 );
225 guint32 fillWith = (0xff000000 & (item->def.getR() << 24))
226 | (0x00ff0000 & (item->def.getG() << 16))
227 | (0x0000ff00 & (item->def.getB() << 8));
228 thumb->fill( fillWith );
229 gtk_drag_set_icon_pixbuf( dc, thumb->gobj(), 0, 0 );
230 }
232 }
234 //"drag-drop"
235 // gboolean dragDropColorData( GtkWidget *widget,
236 // GdkDragContext *drag_context,
237 // gint x,
238 // gint y,
239 // guint time,
240 // gpointer user_data)
241 // {
242 // // TODO finish
244 // return TRUE;
245 // }
247 static void handleClick( GtkWidget* widget, gpointer callback_data ) {
248 (void)widget;
249 ColorItem* item = reinterpret_cast<ColorItem*>(callback_data);
250 if ( item ) {
251 item->buttonClicked(false);
252 }
253 }
255 static void handleSecondaryClick( GtkWidget* widget, gint arg1, gpointer callback_data ) {
256 (void)widget;
257 (void)arg1;
258 ColorItem* item = reinterpret_cast<ColorItem*>(callback_data);
259 if ( item ) {
260 item->buttonClicked(true);
261 }
262 }
264 static gboolean handleEnterNotify( GtkWidget* /*widget*/, GdkEventCrossing* /*event*/, gpointer callback_data ) {
265 ColorItem* item = reinterpret_cast<ColorItem*>(callback_data);
266 if ( item ) {
267 SPDesktop *desktop = SP_ACTIVE_DESKTOP;
268 if ( desktop ) {
269 gchar* msg = g_strdup_printf(_("Color: <b>%s</b>; <b>Click</b> to set fill, <b>Shift+click</b> to set stroke"),
270 item->def.descr.c_str());
271 desktop->tipsMessageContext()->set(Inkscape::INFORMATION_MESSAGE, msg);
272 g_free(msg);
273 }
274 }
275 return FALSE;
276 }
278 static gboolean handleLeaveNotify( GtkWidget* /*widget*/, GdkEventCrossing* /*event*/, gpointer callback_data ) {
279 ColorItem* item = reinterpret_cast<ColorItem*>(callback_data);
280 if ( item ) {
281 SPDesktop *desktop = SP_ACTIVE_DESKTOP;
282 if ( desktop ) {
283 desktop->tipsMessageContext()->clear();
284 }
285 }
286 return FALSE;
287 }
289 static GtkWidget* popupMenu = 0;
290 static ColorItem* bounceTarget = 0;
292 static void redirClick( GtkMenuItem *menuitem, gpointer user_data )
293 {
294 (void)user_data;
295 if ( bounceTarget ) {
296 handleClick( GTK_WIDGET(menuitem), bounceTarget );
297 }
298 }
300 static void redirSecondaryClick( GtkMenuItem *menuitem, gpointer user_data )
301 {
302 (void)user_data;
303 if ( bounceTarget ) {
304 handleSecondaryClick( GTK_WIDGET(menuitem), 0, bounceTarget );
305 }
306 }
308 static gboolean handleButtonPress( GtkWidget* widget, GdkEventButton* event, gpointer user_data)
309 {
310 (void)widget;
311 gboolean handled = FALSE;
313 if ( (event->button == 3) && (event->type == GDK_BUTTON_PRESS) ) {
314 if ( !popupMenu ) {
315 popupMenu = gtk_menu_new();
316 GtkWidget* child = 0;
318 //TRANSLATORS: An item in context menu on a colour in the swatches
319 child = gtk_menu_item_new_with_label(_("Set fill"));
320 g_signal_connect( G_OBJECT(child),
321 "activate",
322 G_CALLBACK(redirClick),
323 user_data);
324 gtk_menu_shell_append(GTK_MENU_SHELL(popupMenu), child);
326 //TRANSLATORS: An item in context menu on a colour in the swatches
327 child = gtk_menu_item_new_with_label(_("Set stroke"));
329 g_signal_connect( G_OBJECT(child),
330 "activate",
331 G_CALLBACK(redirSecondaryClick),
332 user_data);
333 gtk_menu_shell_append(GTK_MENU_SHELL(popupMenu), child);
335 gtk_widget_show_all(popupMenu);
336 }
338 ColorItem* item = reinterpret_cast<ColorItem*>(user_data);
339 if ( item ) {
340 bounceTarget = item;
341 if ( popupMenu ) {
342 gtk_menu_popup(GTK_MENU(popupMenu), NULL, NULL, NULL, NULL, event->button, event->time);
343 handled = TRUE;
344 }
345 }
346 }
348 return handled;
349 }
351 static void dieDieDie( GtkObject *obj, gpointer user_data )
352 {
353 g_message("die die die %p %p", obj, user_data );
354 }
356 //TODO: warning: deprecated conversion from string constant to ‘gchar*’
357 //
358 //Turn out to be warnings that we should probably leave in place. The
359 // pointers/types used need to be read-only. So until we correct the using
360 // code, those warnings are actually desired. They say "Hey! Fix this". We
361 // definitely don't want to hide/ignore them. --JonCruz
362 static const GtkTargetEntry destColorTargets[] = {
363 #if ENABLE_MAGIC_COLORS
364 // {"application/x-inkscape-color-id", GTK_TARGET_SAME_APP, APP_X_INKY_COLOR_ID},
365 {"application/x-inkscape-color", 0, APP_X_INKY_COLOR},
366 #endif // ENABLE_MAGIC_COLORS
367 {"application/x-color", 0, APP_X_COLOR},
368 };
370 #include "color.h" // for SP_RGBA32_U_COMPOSE
372 void ColorItem::_dropDataIn( GtkWidget *widget,
373 GdkDragContext *drag_context,
374 gint x, gint y,
375 GtkSelectionData *data,
376 guint info,
377 guint event_time,
378 gpointer user_data)
379 {
380 (void)widget;
381 (void)drag_context;
382 (void)x;
383 (void)y;
384 (void)event_time;
385 // g_message(" droppy droppy %d", info);
386 switch (info) {
387 case APP_X_INKY_COLOR:
388 {
389 if ( data->length >= 8 ) {
390 // Careful about endian issues.
391 guint16* dataVals = (guint16*)data->data;
392 if ( user_data ) {
393 ColorItem* item = reinterpret_cast<ColorItem*>(user_data);
394 if ( item->def.isEditable() ) {
395 // Shove on in the new value
396 item->def.setRGB( 0x0ff & (dataVals[0] >> 8), 0x0ff & (dataVals[1] >> 8), 0x0ff & (dataVals[2] >> 8) );
397 }
398 }
399 }
400 break;
401 }
402 case APP_X_COLOR:
403 {
404 if ( data->length == 8 ) {
405 // Careful about endian issues.
406 guint16* dataVals = (guint16*)data->data;
407 // {
408 // gchar c[64] = {0};
409 // sp_svg_write_color( c, 64,
410 // SP_RGBA32_U_COMPOSE(
411 // 0x0ff & (dataVals[0] >> 8),
412 // 0x0ff & (dataVals[1] >> 8),
413 // 0x0ff & (dataVals[2] >> 8),
414 // 0xff // can't have transparency in the color itself
415 // //0x0ff & (data->data[3] >> 8),
416 // ));
417 // }
418 if ( user_data ) {
419 ColorItem* item = reinterpret_cast<ColorItem*>(user_data);
420 if ( item->def.isEditable() ) {
421 // Shove on in the new value
422 item->def.setRGB( 0x0ff & (dataVals[0] >> 8), 0x0ff & (dataVals[1] >> 8), 0x0ff & (dataVals[2] >> 8) );
423 }
424 }
425 }
426 break;
427 }
428 default:
429 g_message("unknown drop type");
430 }
432 }
434 static bool bruteForce( SPDocument* document, Inkscape::XML::Node* node, Glib::ustring const& match, int r, int g, int b )
435 {
436 bool changed = false;
438 if ( node ) {
439 gchar const * val = node->attribute("inkscape:x-fill-tag");
440 if ( val && (match == val) ) {
441 SPObject *obj = document->getObjectByRepr( node );
443 gchar c[64] = {0};
444 sp_svg_write_color( c, sizeof(c), SP_RGBA32_U_COMPOSE( r, g, b, 0xff ) );
445 SPCSSAttr *css = sp_repr_css_attr_new();
446 sp_repr_css_set_property( css, "fill", c );
448 sp_desktop_apply_css_recursive( (SPItem*)obj, css, true );
449 ((SPItem*)obj)->updateRepr();
451 changed = true;
452 }
454 val = node->attribute("inkscape:x-stroke-tag");
455 if ( val && (match == val) ) {
456 SPObject *obj = document->getObjectByRepr( node );
458 gchar c[64] = {0};
459 sp_svg_write_color( c, sizeof(c), SP_RGBA32_U_COMPOSE( r, g, b, 0xff ) );
460 SPCSSAttr *css = sp_repr_css_attr_new();
461 sp_repr_css_set_property( css, "stroke", c );
463 sp_desktop_apply_css_recursive( (SPItem*)obj, css, true );
464 ((SPItem*)obj)->updateRepr();
466 changed = true;
467 }
469 Inkscape::XML::Node* first = node->firstChild();
470 changed |= bruteForce( document, first, match, r, g, b );
472 changed |= bruteForce( document, node->next(), match, r, g, b );
473 }
475 return changed;
476 }
478 void ColorItem::_colorDefChanged(void* data)
479 {
480 ColorItem* item = reinterpret_cast<ColorItem*>(data);
481 if ( item ) {
482 for ( std::vector<Gtk::Widget*>::iterator it = item->_previews.begin(); it != item->_previews.end(); ++it ) {
483 Gtk::Widget* widget = *it;
484 if ( IS_EEK_PREVIEW(widget->gobj()) ) {
485 EekPreview * preview = EEK_PREVIEW(widget->gobj());
486 eek_preview_set_color( preview,
487 (item->def.getR() << 8) | item->def.getR(),
488 (item->def.getG() << 8) | item->def.getG(),
489 (item->def.getB() << 8) | item->def.getB() );
491 eek_preview_set_linked( preview, (LinkType)((item->_linkSrc ? PREVIEW_LINK_IN:0)
492 | (item->_listeners.empty() ? 0:PREVIEW_LINK_OUT)
493 | (item->_isLive ? PREVIEW_LINK_OTHER:0)) );
495 widget->queue_draw();
496 }
497 }
499 for ( std::vector<ColorItem*>::iterator it = item->_listeners.begin(); it != item->_listeners.end(); ++it ) {
500 guint r = item->def.getR();
501 guint g = item->def.getG();
502 guint b = item->def.getB();
504 if ( (*it)->_linkIsTone ) {
505 r = ( ((*it)->_linkPercent * (*it)->_linkGray) + ((100 - (*it)->_linkPercent) * r) ) / 100;
506 g = ( ((*it)->_linkPercent * (*it)->_linkGray) + ((100 - (*it)->_linkPercent) * g) ) / 100;
507 b = ( ((*it)->_linkPercent * (*it)->_linkGray) + ((100 - (*it)->_linkPercent) * b) ) / 100;
508 } else {
509 r = ( ((*it)->_linkPercent * 255) + ((100 - (*it)->_linkPercent) * r) ) / 100;
510 g = ( ((*it)->_linkPercent * 255) + ((100 - (*it)->_linkPercent) * g) ) / 100;
511 b = ( ((*it)->_linkPercent * 255) + ((100 - (*it)->_linkPercent) * b) ) / 100;
512 }
514 (*it)->def.setRGB( r, g, b );
515 }
518 // Look for objects using this color
519 {
520 SPDesktop *desktop = SP_ACTIVE_DESKTOP;
521 if ( desktop ) {
522 SPDocument* document = sp_desktop_document( desktop );
523 Inkscape::XML::Node *rroot = sp_document_repr_root( document );
524 if ( rroot ) {
526 // Find where this thing came from
527 Glib::ustring paletteName;
528 bool found = false;
529 int index = 0;
530 for ( std::vector<JustForNow*>::iterator it2 = possible.begin(); it2 != possible.end() && !found; ++it2 ) {
531 JustForNow* curr = *it2;
532 index = 0;
533 for ( std::vector<ColorItem*>::iterator zz = curr->_colors.begin(); zz != curr->_colors.end(); ++zz ) {
534 if ( item == *zz ) {
535 found = true;
536 paletteName = curr->_name;
537 break;
538 } else {
539 index++;
540 }
541 }
542 }
544 if ( !paletteName.empty() ) {
545 gchar* str = g_strdup_printf("%d|", index);
546 paletteName.insert( 0, str );
547 g_free(str);
548 str = 0;
550 if ( bruteForce( document, rroot, paletteName, item->def.getR(), item->def.getG(), item->def.getB() ) ) {
551 sp_document_done( document , SP_VERB_DIALOG_SWATCHES,
552 _("Change color definition"));
553 }
554 }
555 }
556 }
557 }
558 }
559 }
562 Gtk::Widget* ColorItem::getPreview(PreviewStyle style, ViewType view, ::PreviewSize size, guint ratio)
563 {
564 Gtk::Widget* widget = 0;
565 if ( style == PREVIEW_STYLE_BLURB) {
566 Gtk::Label *lbl = new Gtk::Label(def.descr);
567 lbl->set_alignment(Gtk::ALIGN_LEFT, Gtk::ALIGN_CENTER);
568 widget = lbl;
569 } else {
570 // Glib::ustring blank(" ");
571 // if ( size == Inkscape::ICON_SIZE_MENU || size == Inkscape::ICON_SIZE_DECORATION ) {
572 // blank = " ";
573 // }
575 GtkWidget* eekWidget = eek_preview_new();
576 EekPreview * preview = EEK_PREVIEW(eekWidget);
577 Gtk::Widget* newBlot = Glib::wrap(eekWidget);
579 eek_preview_set_color( preview, (def.getR() << 8) | def.getR(), (def.getG() << 8) | def.getG(), (def.getB() << 8) | def.getB());
580 if ( _isRemove ) {
581 GError *error = NULL;
582 gchar *filepath = (gchar *) g_strdup_printf("%s/remove-color.png", INKSCAPE_PIXMAPDIR);
583 gsize bytesRead = 0;
584 gsize bytesWritten = 0;
585 gchar *localFilename = g_filename_from_utf8( filepath,
586 -1,
587 &bytesRead,
588 &bytesWritten,
589 &error);
590 GdkPixbuf* pixbuf = gdk_pixbuf_new_from_file(localFilename, &error);
591 if (!pixbuf) {
592 g_warning("Null pixbuf for %p [%s]", localFilename, localFilename );
593 }
594 g_free(localFilename);
595 g_free(filepath);
597 eek_preview_set_pixbuf( preview, pixbuf );
598 }
600 eek_preview_set_details( preview, (::PreviewStyle)style, (::ViewType)view, (::PreviewSize)size, ratio );
601 eek_preview_set_linked( preview, (LinkType)((_linkSrc ? PREVIEW_LINK_IN:0)
602 | (_listeners.empty() ? 0:PREVIEW_LINK_OUT)
603 | (_isLive ? PREVIEW_LINK_OTHER:0)) );
605 def.addCallback( _colorDefChanged, this );
607 GValue val = {0, {{0}, {0}}};
608 g_value_init( &val, G_TYPE_BOOLEAN );
609 g_value_set_boolean( &val, FALSE );
610 g_object_set_property( G_OBJECT(preview), "focus-on-click", &val );
612 /*
613 Gtk::Button *btn = new Gtk::Button(blank);
614 Gdk::Color color;
615 color.set_rgb((_r << 8)|_r, (_g << 8)|_g, (_b << 8)|_b);
616 btn->modify_bg(Gtk::STATE_NORMAL, color);
617 btn->modify_bg(Gtk::STATE_ACTIVE, color);
618 btn->modify_bg(Gtk::STATE_PRELIGHT, color);
619 btn->modify_bg(Gtk::STATE_SELECTED, color);
621 Gtk::Widget* newBlot = btn;
622 */
624 tips.set_tip((*newBlot), def.descr);
626 /*
627 newBlot->signal_clicked().connect( sigc::mem_fun(*this, &ColorItem::buttonClicked) );
629 sigc::signal<void> type_signal_something;
630 */
632 g_signal_connect( G_OBJECT(newBlot->gobj()),
633 "clicked",
634 G_CALLBACK(handleClick),
635 this);
637 g_signal_connect( G_OBJECT(newBlot->gobj()),
638 "alt-clicked",
639 G_CALLBACK(handleSecondaryClick),
640 this);
642 g_signal_connect( G_OBJECT(newBlot->gobj()),
643 "button-press-event",
644 G_CALLBACK(handleButtonPress),
645 this);
647 gtk_drag_source_set( GTK_WIDGET(newBlot->gobj()),
648 GDK_BUTTON1_MASK,
649 sourceColorEntries,
650 G_N_ELEMENTS(sourceColorEntries),
651 GdkDragAction(GDK_ACTION_MOVE | GDK_ACTION_COPY) );
653 g_signal_connect( G_OBJECT(newBlot->gobj()),
654 "drag-data-get",
655 G_CALLBACK(ColorItem::_dragGetColorData),
656 this);
658 g_signal_connect( G_OBJECT(newBlot->gobj()),
659 "drag-begin",
660 G_CALLBACK(dragBegin),
661 this );
663 g_signal_connect( G_OBJECT(newBlot->gobj()),
664 "enter-notify-event",
665 G_CALLBACK(handleEnterNotify),
666 this);
668 g_signal_connect( G_OBJECT(newBlot->gobj()),
669 "leave-notify-event",
670 G_CALLBACK(handleLeaveNotify),
671 this);
673 // g_signal_connect( G_OBJECT(newBlot->gobj()),
674 // "drag-drop",
675 // G_CALLBACK(dragDropColorData),
676 // this);
678 if ( def.isEditable() )
679 {
680 gtk_drag_dest_set( GTK_WIDGET(newBlot->gobj()),
681 GTK_DEST_DEFAULT_ALL,
682 destColorTargets,
683 G_N_ELEMENTS(destColorTargets),
684 GdkDragAction(GDK_ACTION_COPY | GDK_ACTION_MOVE) );
687 g_signal_connect( G_OBJECT(newBlot->gobj()),
688 "drag-data-received",
689 G_CALLBACK(_dropDataIn),
690 this );
691 }
693 g_signal_connect( G_OBJECT(newBlot->gobj()),
694 "destroy",
695 G_CALLBACK(dieDieDie),
696 this);
699 widget = newBlot;
700 }
702 _previews.push_back( widget );
704 return widget;
705 }
707 void ColorItem::buttonClicked(bool secondary)
708 {
709 SPDesktop *desktop = SP_ACTIVE_DESKTOP;
710 if (!desktop) return;
711 char const * attrName = secondary ? "stroke" : "fill";
713 gchar c[64];
714 if (!_isRemove){
715 guint32 rgba = (def.getR() << 24) | (def.getG() << 16) | (def.getB() << 8) | 0xff;
716 sp_svg_write_color(c, sizeof(c), rgba);
717 }
719 SPCSSAttr *css = sp_repr_css_attr_new();
720 sp_repr_css_set_property( css, attrName, _isRemove ? "none" : c );
721 sp_desktop_set_style(desktop, css);
722 sp_repr_css_attr_unref(css);
724 if (_isRemove){
725 sp_document_done (sp_desktop_document (desktop), SP_VERB_DIALOG_SWATCHES,
726 secondary? _("Remove stroke color") : _("Remove fill color"));
727 } else {
728 sp_document_done (sp_desktop_document (desktop), SP_VERB_DIALOG_SWATCHES,
729 secondary? _("Set stroke color from swatch") : _("Set fill color from swatch"));
730 }
731 }
733 static char* trim( char* str ) {
734 char* ret = str;
735 while ( *str && (*str == ' ' || *str == '\t') ) {
736 str++;
737 }
738 ret = str;
739 while ( *str ) {
740 str++;
741 }
742 str--;
743 while ( str > ret && (( *str == ' ' || *str == '\t' ) || *str == '\r' || *str == '\n') ) {
744 *str-- = 0;
745 }
746 return ret;
747 }
749 void skipWhitespace( char*& str ) {
750 while ( *str == ' ' || *str == '\t' ) {
751 str++;
752 }
753 }
755 bool parseNum( char*& str, int& val ) {
756 val = 0;
757 while ( '0' <= *str && *str <= '9' ) {
758 val = val * 10 + (*str - '0');
759 str++;
760 }
761 bool retval = !(*str == 0 || *str == ' ' || *str == '\t' || *str == '\r' || *str == '\n');
762 return retval;
763 }
766 static bool getBlock( std::string& dst, guchar ch, std::string const str )
767 {
768 bool good = false;
769 std::string::size_type pos = str.find(ch);
770 if ( pos != std::string::npos )
771 {
772 std::string::size_type pos2 = str.find( '(', pos );
773 if ( pos2 != std::string::npos ) {
774 std::string::size_type endPos = str.find( ')', pos2 );
775 if ( endPos != std::string::npos ) {
776 dst = str.substr( pos2 + 1, (endPos - pos2 - 1) );
777 good = true;
778 }
779 }
780 }
781 return good;
782 }
784 static bool popVal( guint64& numVal, std::string& str )
785 {
786 bool good = false;
787 std::string::size_type endPos = str.find(',');
788 if ( endPos == std::string::npos ) {
789 endPos = str.length();
790 }
792 if ( endPos != std::string::npos && endPos > 0 ) {
793 std::string xxx = str.substr( 0, endPos );
794 const gchar* ptr = xxx.c_str();
795 gchar* endPtr = 0;
796 numVal = g_ascii_strtoull( ptr, &endPtr, 10 );
797 if ( (numVal == G_MAXUINT64) && (ERANGE == errno) ) {
798 // overflow
799 } else if ( (numVal == 0) && (endPtr == ptr) ) {
800 // failed conversion
801 } else {
802 good = true;
803 str.erase( 0, endPos + 1 );
804 }
805 }
807 return good;
808 }
810 void ColorItem::_wireMagicColors( void* p )
811 {
812 JustForNow* onceMore = reinterpret_cast<JustForNow*>(p);
813 if ( onceMore )
814 {
815 for ( std::vector<ColorItem*>::iterator it = onceMore->_colors.begin(); it != onceMore->_colors.end(); ++it )
816 {
817 std::string::size_type pos = (*it)->def.descr.find("*{");
818 if ( pos != std::string::npos )
819 {
820 std::string subby = (*it)->def.descr.substr( pos + 2 );
821 std::string::size_type endPos = subby.find("}*");
822 if ( endPos != std::string::npos )
823 {
824 subby.erase( endPos );
825 //g_message("FOUND MAGIC at '%s'", (*it)->def.descr.c_str());
826 //g_message(" '%s'", subby.c_str());
828 if ( subby.find('E') != std::string::npos )
829 {
830 (*it)->def.setEditable( true );
831 }
833 if ( subby.find('L') != std::string::npos )
834 {
835 (*it)->_isLive = true;
836 }
838 std::string part;
839 // Tint. index + 1 more val.
840 if ( getBlock( part, 'T', subby ) ) {
841 guint64 colorIndex = 0;
842 if ( popVal( colorIndex, part ) ) {
843 guint64 percent = 0;
844 if ( popVal( percent, part ) ) {
845 (*it)->_linkTint( *(onceMore->_colors[colorIndex]), percent );
846 }
847 }
848 }
850 // Shade/tone. index + 1 or 2 more val.
851 if ( getBlock( part, 'S', subby ) ) {
852 guint64 colorIndex = 0;
853 if ( popVal( colorIndex, part ) ) {
854 guint64 percent = 0;
855 if ( popVal( percent, part ) ) {
856 guint64 grayLevel = 0;
857 if ( !popVal( grayLevel, part ) ) {
858 grayLevel = 0;
859 }
860 (*it)->_linkTone( *(onceMore->_colors[colorIndex]), percent, grayLevel );
861 }
862 }
863 }
865 }
866 }
867 }
868 }
869 }
872 void ColorItem::_linkTint( ColorItem& other, int percent )
873 {
874 if ( !_linkSrc )
875 {
876 other._listeners.push_back(this);
877 _linkIsTone = false;
878 _linkPercent = percent;
879 if ( _linkPercent > 100 )
880 _linkPercent = 100;
881 if ( _linkPercent < 0 )
882 _linkPercent = 0;
883 _linkGray = 0;
884 _linkSrc = &other;
886 ColorItem::_colorDefChanged(&other);
887 }
888 }
890 void ColorItem::_linkTone( ColorItem& other, int percent, int grayLevel )
891 {
892 if ( !_linkSrc )
893 {
894 other._listeners.push_back(this);
895 _linkIsTone = true;
896 _linkPercent = percent;
897 if ( _linkPercent > 100 )
898 _linkPercent = 100;
899 if ( _linkPercent < 0 )
900 _linkPercent = 0;
901 _linkGray = grayLevel;
902 _linkSrc = &other;
904 ColorItem::_colorDefChanged(&other);
905 }
906 }
909 void _loadPaletteFile( gchar const *filename )
910 {
911 char block[1024];
912 FILE *f = Inkscape::IO::fopen_utf8name( filename, "r" );
913 if ( f ) {
914 char* result = fgets( block, sizeof(block), f );
915 if ( result ) {
916 if ( strncmp( "GIMP Palette", block, 12 ) == 0 ) {
917 bool inHeader = true;
918 bool hasErr = false;
920 JustForNow *onceMore = new JustForNow();
922 do {
923 result = fgets( block, sizeof(block), f );
924 block[sizeof(block) - 1] = 0;
925 if ( result ) {
926 if ( block[0] == '#' ) {
927 // ignore comment
928 } else {
929 char *ptr = block;
930 // very simple check for header versus entry
931 while ( *ptr == ' ' || *ptr == '\t' ) {
932 ptr++;
933 }
934 if ( (*ptr == 0) || (*ptr == '\r') || (*ptr == '\n') ) {
935 // blank line. skip it.
936 } else if ( '0' <= *ptr && *ptr <= '9' ) {
937 // should be an entry link
938 inHeader = false;
939 ptr = block;
940 Glib::ustring name("");
941 int r = 0;
942 int g = 0;
943 int b = 0;
944 skipWhitespace(ptr);
945 if ( *ptr ) {
946 hasErr = parseNum(ptr, r);
947 if ( !hasErr ) {
948 skipWhitespace(ptr);
949 hasErr = parseNum(ptr, g);
950 }
951 if ( !hasErr ) {
952 skipWhitespace(ptr);
953 hasErr = parseNum(ptr, b);
954 }
955 if ( !hasErr && *ptr ) {
956 char* n = trim(ptr);
957 if (n != NULL) {
958 name = n;
959 }
960 }
961 if ( !hasErr ) {
962 // Add the entry now
963 Glib::ustring nameStr(name);
964 ColorItem* item = new ColorItem( r, g, b, nameStr );
965 onceMore->_colors.push_back(item);
966 }
967 } else {
968 hasErr = true;
969 }
970 } else {
971 if ( !inHeader ) {
972 // Hmmm... probably bad. Not quite the format we want?
973 hasErr = true;
974 } else {
975 char* sep = strchr(result, ':');
976 if ( sep ) {
977 *sep = 0;
978 char* val = trim(sep + 1);
979 char* name = trim(result);
980 if ( *name ) {
981 if ( strcmp( "Name", name ) == 0 )
982 {
983 onceMore->_name = val;
984 }
985 else if ( strcmp( "Columns", name ) == 0 )
986 {
987 gchar* endPtr = 0;
988 guint64 numVal = g_ascii_strtoull( val, &endPtr, 10 );
989 if ( (numVal == G_MAXUINT64) && (ERANGE == errno) ) {
990 // overflow
991 } else if ( (numVal == 0) && (endPtr == val) ) {
992 // failed conversion
993 } else {
994 onceMore->_prefWidth = numVal;
995 }
996 }
997 } else {
998 // error
999 hasErr = true;
1000 }
1001 } else {
1002 // error
1003 hasErr = true;
1004 }
1005 }
1006 }
1007 }
1008 }
1009 } while ( result && !hasErr );
1010 if ( !hasErr ) {
1011 possible.push_back(onceMore);
1012 #if ENABLE_MAGIC_COLORS
1013 ColorItem::_wireMagicColors( onceMore );
1014 #endif // ENABLE_MAGIC_COLORS
1015 } else {
1016 delete onceMore;
1017 }
1018 }
1019 }
1021 fclose(f);
1022 }
1023 }
1025 static void loadEmUp()
1026 {
1027 static bool beenHere = false;
1028 if ( !beenHere ) {
1029 beenHere = true;
1031 std::list<gchar *> sources;
1032 sources.push_back( profile_path("palettes") );
1033 sources.push_back( g_strdup(INKSCAPE_PALETTESDIR) );
1034 sources.push_back( g_strdup(CREATE_PALETTESDIR) );
1036 // Use this loop to iterate through a list of possible document locations.
1037 while (!sources.empty()) {
1038 gchar *dirname = sources.front();
1040 if ( Inkscape::IO::file_test( dirname, G_FILE_TEST_EXISTS )
1041 && Inkscape::IO::file_test( dirname, G_FILE_TEST_IS_DIR )) {
1042 GError *err = 0;
1043 GDir *directory = g_dir_open(dirname, 0, &err);
1044 if (!directory) {
1045 gchar *safeDir = Inkscape::IO::sanitizeString(dirname);
1046 g_warning(_("Palettes directory (%s) is unavailable."), safeDir);
1047 g_free(safeDir);
1048 } else {
1049 gchar *filename = 0;
1050 while ((filename = (gchar *)g_dir_read_name(directory)) != NULL) {
1051 gchar* lower = g_ascii_strdown( filename, -1 );
1052 // if ( g_str_has_suffix(lower, ".gpl") ) {
1053 gchar* full = g_build_filename(dirname, filename, NULL);
1054 if ( !Inkscape::IO::file_test( full, G_FILE_TEST_IS_DIR ) ) {
1055 _loadPaletteFile(full);
1056 }
1057 g_free(full);
1058 // }
1059 g_free(lower);
1060 }
1061 g_dir_close(directory);
1062 }
1063 }
1065 // toss the dirname
1066 g_free(dirname);
1067 sources.pop_front();
1068 }
1069 }
1070 }
1080 SwatchesPanel& SwatchesPanel::getInstance()
1081 {
1082 return *new SwatchesPanel();
1083 }
1086 /**
1087 * Constructor
1088 */
1089 SwatchesPanel::SwatchesPanel(gchar const* prefsPath) :
1090 Inkscape::UI::Widget::Panel("", prefsPath, SP_VERB_DIALOG_SWATCHES, "", true),
1091 _holder(0)
1092 {
1093 Gtk::RadioMenuItem* hotItem = 0;
1094 _holder = new PreviewHolder();
1095 _remove = new ColorItem();
1096 loadEmUp();
1097 if ( !possible.empty() ) {
1098 JustForNow* first = 0;
1099 Glib::ustring targetName;
1100 if ( !_prefs_path.empty() ) {
1101 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1102 targetName = prefs->getString(_prefs_path + "/palette");
1103 if (!targetName.empty()) {
1104 for ( std::vector<JustForNow*>::iterator iter = possible.begin(); iter != possible.end(); ++iter ) {
1105 if ( (*iter)->_name == targetName ) {
1106 first = *iter;
1107 break;
1108 }
1109 }
1110 }
1111 }
1113 if ( !first ) {
1114 first = possible.front();
1115 }
1117 if ( first->_prefWidth > 0 ) {
1118 _holder->setColumnPref( first->_prefWidth );
1119 }
1120 _holder->freezeUpdates();
1121 _holder->addPreview(_remove);
1122 for ( std::vector<ColorItem*>::iterator it = first->_colors.begin(); it != first->_colors.end(); it++ ) {
1123 _holder->addPreview(*it);
1124 }
1125 _holder->thawUpdates();
1127 Gtk::RadioMenuItem::Group groupOne;
1129 int i = 0;
1130 for ( std::vector<JustForNow*>::iterator it = possible.begin(); it != possible.end(); it++ ) {
1131 JustForNow* curr = *it;
1132 Gtk::RadioMenuItem* single = manage(new Gtk::RadioMenuItem(groupOne, curr->_name));
1133 if ( curr == first ) {
1134 hotItem = single;
1135 }
1136 _regItem( single, 3, i );
1137 i++;
1138 }
1139 }
1142 _getContents()->pack_start(*_holder, Gtk::PACK_EXPAND_WIDGET);
1143 _setTargetFillable(_holder);
1145 show_all_children();
1147 restorePanelPrefs();
1148 if ( hotItem ) {
1149 hotItem->set_active();
1150 }
1151 }
1153 SwatchesPanel::~SwatchesPanel()
1154 {
1155 if (_remove) delete _remove;
1156 if (_holder) delete _holder;
1157 }
1159 void SwatchesPanel::setOrientation( Gtk::AnchorType how )
1160 {
1161 // Must call the parent class or bad things might happen
1162 Inkscape::UI::Widget::Panel::setOrientation( how );
1164 if ( _holder )
1165 {
1166 _holder->setOrientation( Gtk::ANCHOR_SOUTH );
1167 }
1168 }
1170 void SwatchesPanel::_handleAction( int setId, int itemId )
1171 {
1172 switch( setId ) {
1173 case 3:
1174 {
1175 if ( itemId >= 0 && itemId < static_cast<int>(possible.size()) ) {
1176 _holder->clear();
1177 JustForNow* curr = possible[itemId];
1179 if ( !_prefs_path.empty() ) {
1180 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1181 prefs->setString(_prefs_path + "/palette", curr->_name);
1182 }
1184 if ( curr->_prefWidth > 0 ) {
1185 _holder->setColumnPref( curr->_prefWidth );
1186 }
1187 _holder->freezeUpdates();
1188 _holder->addPreview(_remove);
1189 for ( std::vector<ColorItem*>::iterator it = curr->_colors.begin(); it != curr->_colors.end(); it++ ) {
1190 _holder->addPreview(*it);
1191 }
1192 _holder->thawUpdates();
1193 }
1194 }
1195 break;
1196 }
1197 }
1199 } //namespace Dialogs
1200 } //namespace UI
1201 } //namespace Inkscape
1204 /*
1205 Local Variables:
1206 mode:c++
1207 c-file-style:"stroustrup"
1208 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1209 indent-tabs-mode:nil
1210 fill-column:99
1211 End:
1212 */
1213 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :