1f708e3de3534c1c84f8387ecc391d7da91c0f2b
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>
15 #include <map>
17 #include <gtk/gtkdialog.h> //for GTK_RESPONSE* types
18 #include <gtk/gtkdnd.h>
19 #include <gtk/gtkmenu.h>
20 #include <gtk/gtkmenuitem.h>
21 #include <gtk/gtkseparatormenuitem.h>
22 #include <glibmm/i18n.h>
23 #include <gdkmm/pixbuf.h>
25 #include "desktop.h"
26 #include "desktop-handles.h"
27 #include "desktop-style.h"
28 #include "document.h"
29 #include "document-private.h"
30 #include "extension/db.h"
31 #include "inkscape.h"
32 #include "inkscape.h"
33 #include "io/sys.h"
34 #include "io/resource.h"
35 #include "message-context.h"
36 #include "path-prefix.h"
37 #include "preferences.h"
38 #include "sp-item.h"
39 #include "svg/svg-color.h"
40 #include "sp-gradient-fns.h"
41 #include "sp-gradient.h"
42 #include "sp-gradient-vector.h"
43 #include "swatches.h"
44 #include "style.h"
45 #include "widgets/gradient-vector.h"
46 #include "widgets/eek-preview.h"
47 #include "display/nr-plain-stuff.h"
48 #include "sp-gradient-reference.h"
50 //#define USE_DOCUMENT_PALETTE 1
52 namespace Inkscape {
53 namespace UI {
54 namespace Dialogs {
56 #define VBLOCK 16
58 void _loadPaletteFile( gchar const *filename );
60 /**
61 * The color swatch you see on screen as a clickable box.
62 */
63 class ColorItem : public Inkscape::UI::Previewable
64 {
65 friend void _loadPaletteFile( gchar const *filename );
66 public:
67 ColorItem( ege::PaintDef::ColorType type );
68 ColorItem( unsigned int r, unsigned int g, unsigned int b,
69 Glib::ustring& name );
70 virtual ~ColorItem();
71 ColorItem(ColorItem const &other);
72 virtual ColorItem &operator=(ColorItem const &other);
73 virtual Gtk::Widget* getPreview(PreviewStyle style,
74 ViewType view,
75 ::PreviewSize size,
76 guint ratio);
77 void buttonClicked(bool secondary = false);
79 void setState( bool fill, bool stroke );
80 bool isFill() { return _isFill; }
81 bool isStroke() { return _isStroke; }
83 ege::PaintDef def;
84 void* ptr;
86 private:
87 static void _dropDataIn( GtkWidget *widget,
88 GdkDragContext *drag_context,
89 gint x, gint y,
90 GtkSelectionData *data,
91 guint info,
92 guint event_time,
93 gpointer user_data);
95 static void _dragGetColorData( GtkWidget *widget,
96 GdkDragContext *drag_context,
97 GtkSelectionData *data,
98 guint info,
99 guint time,
100 gpointer user_data);
102 static void _wireMagicColors( void* p );
103 static void _colorDefChanged(void* data);
105 void _linkTint( ColorItem& other, int percent );
106 void _linkTone( ColorItem& other, int percent, int grayLevel );
108 Gtk::Tooltips tips;
109 std::vector<Gtk::Widget*> _previews;
111 bool _isFill;
112 bool _isStroke;
113 bool _isLive;
114 bool _linkIsTone;
115 int _linkPercent;
116 int _linkGray;
117 ColorItem* _linkSrc;
118 std::vector<ColorItem*> _listeners;
119 };
123 ColorItem::ColorItem(ege::PaintDef::ColorType type) :
124 def(type),
125 ptr(0),
126 _isFill(false),
127 _isStroke(false),
128 _isLive(false),
129 _linkIsTone(false),
130 _linkPercent(0),
131 _linkGray(0),
132 _linkSrc(0)
133 {
134 }
136 ColorItem::ColorItem( unsigned int r, unsigned int g, unsigned int b, Glib::ustring& name ) :
137 def( r, g, b, name ),
138 ptr(0),
139 _isFill(false),
140 _isStroke(false),
141 _isLive(false),
142 _linkIsTone(false),
143 _linkPercent(0),
144 _linkGray(0),
145 _linkSrc(0)
146 {
147 }
149 ColorItem::~ColorItem()
150 {
151 }
153 ColorItem::ColorItem(ColorItem const &other) :
154 Inkscape::UI::Previewable()
155 {
156 if ( this != &other ) {
157 *this = other;
158 }
159 }
161 ColorItem &ColorItem::operator=(ColorItem const &other)
162 {
163 if ( this != &other ) {
164 def = other.def;
166 // TODO - correct linkage
167 _linkSrc = other._linkSrc;
168 g_message("Erk!");
169 }
170 return *this;
171 }
173 void ColorItem::setState( bool fill, bool stroke )
174 {
175 if ( (_isFill != fill) || (_isStroke != stroke) ) {
176 _isFill = fill;
177 _isStroke = stroke;
179 for ( std::vector<Gtk::Widget*>::iterator it = _previews.begin(); it != _previews.end(); ++it ) {
180 Gtk::Widget* widget = *it;
181 if ( IS_EEK_PREVIEW(widget->gobj()) ) {
182 EekPreview * preview = EEK_PREVIEW(widget->gobj());
184 int val = eek_preview_get_linked( preview );
185 val &= ~(PREVIEW_FILL | PREVIEW_STROKE);
186 if ( _isFill ) {
187 val |= PREVIEW_FILL;
188 }
189 if ( _isStroke ) {
190 val |= PREVIEW_STROKE;
191 }
192 eek_preview_set_linked( preview, static_cast<LinkType>(val) );
193 }
194 }
195 }
196 }
199 class JustForNow
200 {
201 public:
202 JustForNow() : _prefWidth(0) {}
204 Glib::ustring _name;
205 int _prefWidth;
206 std::vector<ColorItem*> _colors;
207 };
209 static std::vector<JustForNow*> possible;
212 static std::vector<std::string> mimeStrings;
213 static std::map<std::string, guint> mimeToInt;
215 static std::map<ColorItem*, guchar*> previewMap;
216 static std::map<ColorItem*, SPGradient*> gradMap; // very temporary workaround.
218 void ColorItem::_dragGetColorData( GtkWidget */*widget*/,
219 GdkDragContext */*drag_context*/,
220 GtkSelectionData *data,
221 guint info,
222 guint /*time*/,
223 gpointer user_data)
224 {
225 ColorItem* item = reinterpret_cast<ColorItem*>(user_data);
226 std::string key;
227 if ( info < mimeStrings.size() ) {
228 key = mimeStrings[info];
229 } else {
230 g_warning("ERROR: unknown value (%d)", info);
231 }
233 if ( !key.empty() ) {
234 char* tmp = 0;
235 int len = 0;
236 int format = 0;
237 item->def.getMIMEData(key, tmp, len, format);
238 if ( tmp ) {
239 GdkAtom dataAtom = gdk_atom_intern( key.c_str(), FALSE );
240 gtk_selection_data_set( data, dataAtom, format, (guchar*)tmp, len );
241 delete[] tmp;
242 }
243 }
244 }
246 static void dragBegin( GtkWidget */*widget*/, GdkDragContext* dc, gpointer data )
247 {
248 ColorItem* item = reinterpret_cast<ColorItem*>(data);
249 if ( item )
250 {
251 using Inkscape::IO::Resource::get_path;
252 using Inkscape::IO::Resource::ICONS;
253 using Inkscape::IO::Resource::SYSTEM;
254 int width = 32;
255 int height = 24;
257 if (item->def.getType() != ege::PaintDef::RGB){
258 GError *error = NULL;
259 gsize bytesRead = 0;
260 gsize bytesWritten = 0;
261 gchar *localFilename = g_filename_from_utf8( get_path(SYSTEM, ICONS, "remove-color.png"),
262 -1,
263 &bytesRead,
264 &bytesWritten,
265 &error);
266 GdkPixbuf* pixbuf = gdk_pixbuf_new_from_file_at_scale(localFilename, width, height, FALSE, &error);
267 g_free(localFilename);
268 gtk_drag_set_icon_pixbuf( dc, pixbuf, 0, 0 );
269 } else {
270 GdkPixbuf* pixbuf = 0;
271 if ( gradMap.find(item) == gradMap.end() ){
272 Glib::RefPtr<Gdk::Pixbuf> thumb = Gdk::Pixbuf::create( Gdk::COLORSPACE_RGB, false, 8, width, height );
273 guint32 fillWith = (0xff000000 & (item->def.getR() << 24))
274 | (0x00ff0000 & (item->def.getG() << 16))
275 | (0x0000ff00 & (item->def.getB() << 8));
276 thumb->fill( fillWith );
277 pixbuf = thumb->gobj();
278 } else {
279 SPGradient* grad = gradMap[item];
281 guchar* px = g_new( guchar, 3 * height * width );
282 nr_render_checkerboard_rgb( px, width, height, 3 * width, 0, 0 );
284 sp_gradient_render_vector_block_rgb( grad,
285 px, width, height, 3 * width,
286 0, width, TRUE );
288 pixbuf = gdk_pixbuf_new_from_data( px, GDK_COLORSPACE_RGB, FALSE, 8,
289 width, height, width * 3,
290 0, // add delete function
291 0 );
292 }
293 gtk_drag_set_icon_pixbuf( dc, pixbuf, 0, 0 );
294 }
295 }
297 }
299 //"drag-drop"
300 // gboolean dragDropColorData( GtkWidget *widget,
301 // GdkDragContext *drag_context,
302 // gint x,
303 // gint y,
304 // guint time,
305 // gpointer user_data)
306 // {
307 // // TODO finish
309 // return TRUE;
310 // }
312 static void handleClick( GtkWidget* /*widget*/, gpointer callback_data ) {
313 ColorItem* item = reinterpret_cast<ColorItem*>(callback_data);
314 if ( item ) {
315 item->buttonClicked(false);
316 }
317 }
319 static void handleSecondaryClick( GtkWidget* /*widget*/, gint /*arg1*/, gpointer callback_data ) {
320 ColorItem* item = reinterpret_cast<ColorItem*>(callback_data);
321 if ( item ) {
322 item->buttonClicked(true);
323 }
324 }
326 static gboolean handleEnterNotify( GtkWidget* /*widget*/, GdkEventCrossing* /*event*/, gpointer callback_data ) {
327 ColorItem* item = reinterpret_cast<ColorItem*>(callback_data);
328 if ( item ) {
329 SPDesktop *desktop = SP_ACTIVE_DESKTOP;
330 if ( desktop ) {
331 gchar* msg = g_strdup_printf(_("Color: <b>%s</b>; <b>Click</b> to set fill, <b>Shift+click</b> to set stroke"),
332 item->def.descr.c_str());
333 desktop->tipsMessageContext()->set(Inkscape::INFORMATION_MESSAGE, msg);
334 g_free(msg);
335 }
336 }
337 return FALSE;
338 }
340 static gboolean handleLeaveNotify( GtkWidget* /*widget*/, GdkEventCrossing* /*event*/, gpointer callback_data ) {
341 ColorItem* item = reinterpret_cast<ColorItem*>(callback_data);
342 if ( item ) {
343 SPDesktop *desktop = SP_ACTIVE_DESKTOP;
344 if ( desktop ) {
345 desktop->tipsMessageContext()->clear();
346 }
347 }
348 return FALSE;
349 }
351 static GtkWidget* popupMenu = 0;
352 static std::vector<GtkWidget*> popupExtras;
353 static ColorItem* bounceTarget = 0;
355 static void redirClick( GtkMenuItem *menuitem, gpointer /*user_data*/ )
356 {
357 if ( bounceTarget ) {
358 handleClick( GTK_WIDGET(menuitem), bounceTarget );
359 }
360 }
362 static void redirSecondaryClick( GtkMenuItem *menuitem, gpointer /*user_data*/ )
363 {
364 if ( bounceTarget ) {
365 handleSecondaryClick( GTK_WIDGET(menuitem), 0, bounceTarget );
366 }
367 }
369 #if USE_DOCUMENT_PALETTE
370 static void editGradientImpl( SPGradient* gr )
371 {
372 if ( gr ) {
373 GtkWidget *dialog = sp_gradient_vector_editor_new( gr );
374 gtk_widget_show( dialog );
375 }
376 }
378 static void editGradient( GtkMenuItem */*menuitem*/, gpointer /*user_data*/ )
379 {
380 if ( bounceTarget ) {
381 SwatchesPanel* swp = bounceTarget->ptr ? reinterpret_cast<SwatchesPanel*>(bounceTarget->ptr) : 0;
382 SPDesktop* desktop = swp ? swp->getDesktop() : 0;
383 SPDocument *doc = desktop ? desktop->doc() : 0;
384 if (doc) {
385 std::string targetName(bounceTarget->def.descr);
386 const GSList *gradients = sp_document_get_resource_list(doc, "gradient");
387 for (const GSList *item = gradients; item; item = item->next) {
388 SPGradient* grad = SP_GRADIENT(item->data);
389 if ( targetName == grad->id ) {
390 editGradientImpl( grad );
391 break;
392 }
393 }
394 }
395 }
396 }
398 static void addNewGradient( GtkMenuItem */*menuitem*/, gpointer /*user_data*/ )
399 {
400 if ( bounceTarget ) {
401 SwatchesPanel* swp = bounceTarget->ptr ? reinterpret_cast<SwatchesPanel*>(bounceTarget->ptr) : 0;
402 SPDesktop* desktop = swp ? swp->getDesktop() : 0;
403 SPDocument *doc = desktop ? desktop->doc() : 0;
404 if (doc) {
405 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
407 Inkscape::XML::Node *repr = xml_doc->createElement("svg:linearGradient");
408 repr->setAttribute("osb:paint", "solid");
409 Inkscape::XML::Node *stop = xml_doc->createElement("svg:stop");
410 stop->setAttribute("offset", "0");
411 stop->setAttribute("style", "stop-color:#000;stop-opacity:1;");
412 repr->appendChild(stop);
413 Inkscape::GC::release(stop);
415 SP_OBJECT_REPR( SP_DOCUMENT_DEFS(doc) )->addChild(repr, NULL);
417 SPGradient * gr = static_cast<SPGradient *>(doc->getObjectByRepr(repr));
419 Inkscape::GC::release(repr);
422 editGradientImpl( gr );
423 // Work-around for timing of gradient addition change. Must follow edit.
424 if ( swp ) {
425 swp->handleGradientsChange();
426 }
427 }
428 }
429 }
430 #endif // USE_DOCUMENT_PALETTE
432 static gboolean handleButtonPress( GtkWidget* /*widget*/, GdkEventButton* event, gpointer user_data)
433 {
434 gboolean handled = FALSE;
436 if ( (event->button == 3) && (event->type == GDK_BUTTON_PRESS) ) {
437 if ( !popupMenu ) {
438 popupMenu = gtk_menu_new();
439 GtkWidget* child = 0;
441 //TRANSLATORS: An item in context menu on a colour in the swatches
442 child = gtk_menu_item_new_with_label(_("Set fill"));
443 g_signal_connect( G_OBJECT(child),
444 "activate",
445 G_CALLBACK(redirClick),
446 user_data);
447 gtk_menu_shell_append(GTK_MENU_SHELL(popupMenu), child);
449 //TRANSLATORS: An item in context menu on a colour in the swatches
450 child = gtk_menu_item_new_with_label(_("Set stroke"));
452 g_signal_connect( G_OBJECT(child),
453 "activate",
454 G_CALLBACK(redirSecondaryClick),
455 user_data);
456 gtk_menu_shell_append(GTK_MENU_SHELL(popupMenu), child);
458 #if USE_DOCUMENT_PALETTE
459 child = gtk_separator_menu_item_new();
460 gtk_menu_shell_append(GTK_MENU_SHELL(popupMenu), child);
461 popupExtras.push_back(child);
463 child = gtk_menu_item_new_with_label(_("Add"));
464 g_signal_connect( G_OBJECT(child),
465 "activate",
466 G_CALLBACK(addNewGradient),
467 user_data );
468 gtk_menu_shell_append(GTK_MENU_SHELL(popupMenu), child);
469 popupExtras.push_back(child);
471 child = gtk_menu_item_new_with_label(_("Delete"));
472 gtk_menu_shell_append(GTK_MENU_SHELL(popupMenu), child);
473 //popupExtras.push_back(child);
474 gtk_widget_set_sensitive( child, FALSE );
476 child = gtk_menu_item_new_with_label(_("Edit..."));
477 g_signal_connect( G_OBJECT(child),
478 "activate",
479 G_CALLBACK(editGradient),
480 user_data );
481 gtk_menu_shell_append(GTK_MENU_SHELL(popupMenu), child);
482 popupExtras.push_back(child);
484 child = gtk_separator_menu_item_new();
485 gtk_menu_shell_append(GTK_MENU_SHELL(popupMenu), child);
486 popupExtras.push_back(child);
488 child = gtk_menu_item_new_with_label(_("Convert"));
489 gtk_menu_shell_append(GTK_MENU_SHELL(popupMenu), child);
490 //popupExtras.push_back(child);
491 gtk_widget_set_sensitive( child, FALSE );
492 #endif // USE_DOCUMENT_PALETTE
494 gtk_widget_show_all(popupMenu);
495 }
497 ColorItem* item = reinterpret_cast<ColorItem*>(user_data);
498 if ( item ) {
499 SwatchesPanel* swp = item->ptr ? reinterpret_cast<SwatchesPanel*>(item->ptr) : 0;
500 bool show = swp && (swp->getSelectedIndex() == 0);
501 for ( std::vector<GtkWidget*>::iterator it = popupExtras.begin(); it != popupExtras.end(); ++ it) {
502 gtk_widget_set_sensitive(*it, show);
503 }
505 bounceTarget = item;
506 if ( popupMenu ) {
507 gtk_menu_popup(GTK_MENU(popupMenu), NULL, NULL, NULL, NULL, event->button, event->time);
508 handled = TRUE;
509 }
510 }
511 }
513 return handled;
514 }
516 static void dieDieDie( GtkObject *obj, gpointer user_data )
517 {
518 g_message("die die die %p %p", obj, user_data );
519 }
521 #include "color.h" // for SP_RGBA32_U_COMPOSE
523 void ColorItem::_dropDataIn( GtkWidget */*widget*/,
524 GdkDragContext */*drag_context*/,
525 gint /*x*/, gint /*y*/,
526 GtkSelectionData */*data*/,
527 guint /*info*/,
528 guint /*event_time*/,
529 gpointer /*user_data*/)
530 {
531 }
533 static bool bruteForce( SPDocument* document, Inkscape::XML::Node* node, Glib::ustring const& match, int r, int g, int b )
534 {
535 bool changed = false;
537 if ( node ) {
538 gchar const * val = node->attribute("inkscape:x-fill-tag");
539 if ( val && (match == val) ) {
540 SPObject *obj = document->getObjectByRepr( node );
542 gchar c[64] = {0};
543 sp_svg_write_color( c, sizeof(c), SP_RGBA32_U_COMPOSE( r, g, b, 0xff ) );
544 SPCSSAttr *css = sp_repr_css_attr_new();
545 sp_repr_css_set_property( css, "fill", c );
547 sp_desktop_apply_css_recursive( (SPItem*)obj, css, true );
548 ((SPItem*)obj)->updateRepr();
550 changed = true;
551 }
553 val = node->attribute("inkscape:x-stroke-tag");
554 if ( val && (match == val) ) {
555 SPObject *obj = document->getObjectByRepr( node );
557 gchar c[64] = {0};
558 sp_svg_write_color( c, sizeof(c), SP_RGBA32_U_COMPOSE( r, g, b, 0xff ) );
559 SPCSSAttr *css = sp_repr_css_attr_new();
560 sp_repr_css_set_property( css, "stroke", c );
562 sp_desktop_apply_css_recursive( (SPItem*)obj, css, true );
563 ((SPItem*)obj)->updateRepr();
565 changed = true;
566 }
568 Inkscape::XML::Node* first = node->firstChild();
569 changed |= bruteForce( document, first, match, r, g, b );
571 changed |= bruteForce( document, node->next(), match, r, g, b );
572 }
574 return changed;
575 }
577 void ColorItem::_colorDefChanged(void* data)
578 {
579 ColorItem* item = reinterpret_cast<ColorItem*>(data);
580 if ( item ) {
581 for ( std::vector<Gtk::Widget*>::iterator it = item->_previews.begin(); it != item->_previews.end(); ++it ) {
582 Gtk::Widget* widget = *it;
583 if ( IS_EEK_PREVIEW(widget->gobj()) ) {
584 EekPreview * preview = EEK_PREVIEW(widget->gobj());
585 eek_preview_set_color( preview,
586 (item->def.getR() << 8) | item->def.getR(),
587 (item->def.getG() << 8) | item->def.getG(),
588 (item->def.getB() << 8) | item->def.getB() );
590 eek_preview_set_linked( preview, (LinkType)((item->_linkSrc ? PREVIEW_LINK_IN:0)
591 | (item->_listeners.empty() ? 0:PREVIEW_LINK_OUT)
592 | (item->_isLive ? PREVIEW_LINK_OTHER:0)) );
594 widget->queue_draw();
595 }
596 }
598 for ( std::vector<ColorItem*>::iterator it = item->_listeners.begin(); it != item->_listeners.end(); ++it ) {
599 guint r = item->def.getR();
600 guint g = item->def.getG();
601 guint b = item->def.getB();
603 if ( (*it)->_linkIsTone ) {
604 r = ( ((*it)->_linkPercent * (*it)->_linkGray) + ((100 - (*it)->_linkPercent) * r) ) / 100;
605 g = ( ((*it)->_linkPercent * (*it)->_linkGray) + ((100 - (*it)->_linkPercent) * g) ) / 100;
606 b = ( ((*it)->_linkPercent * (*it)->_linkGray) + ((100 - (*it)->_linkPercent) * b) ) / 100;
607 } else {
608 r = ( ((*it)->_linkPercent * 255) + ((100 - (*it)->_linkPercent) * r) ) / 100;
609 g = ( ((*it)->_linkPercent * 255) + ((100 - (*it)->_linkPercent) * g) ) / 100;
610 b = ( ((*it)->_linkPercent * 255) + ((100 - (*it)->_linkPercent) * b) ) / 100;
611 }
613 (*it)->def.setRGB( r, g, b );
614 }
617 // Look for objects using this color
618 {
619 SPDesktop *desktop = SP_ACTIVE_DESKTOP;
620 if ( desktop ) {
621 SPDocument* document = sp_desktop_document( desktop );
622 Inkscape::XML::Node *rroot = sp_document_repr_root( document );
623 if ( rroot ) {
625 // Find where this thing came from
626 Glib::ustring paletteName;
627 bool found = false;
628 int index = 0;
629 for ( std::vector<JustForNow*>::iterator it2 = possible.begin(); it2 != possible.end() && !found; ++it2 ) {
630 JustForNow* curr = *it2;
631 index = 0;
632 for ( std::vector<ColorItem*>::iterator zz = curr->_colors.begin(); zz != curr->_colors.end(); ++zz ) {
633 if ( item == *zz ) {
634 found = true;
635 paletteName = curr->_name;
636 break;
637 } else {
638 index++;
639 }
640 }
641 }
643 if ( !paletteName.empty() ) {
644 gchar* str = g_strdup_printf("%d|", index);
645 paletteName.insert( 0, str );
646 g_free(str);
647 str = 0;
649 if ( bruteForce( document, rroot, paletteName, item->def.getR(), item->def.getG(), item->def.getB() ) ) {
650 sp_document_done( document , SP_VERB_DIALOG_SWATCHES,
651 _("Change color definition"));
652 }
653 }
654 }
655 }
656 }
657 }
658 }
661 Gtk::Widget* ColorItem::getPreview(PreviewStyle style, ViewType view, ::PreviewSize size, guint ratio)
662 {
663 Gtk::Widget* widget = 0;
664 if ( style == PREVIEW_STYLE_BLURB) {
665 Gtk::Label *lbl = new Gtk::Label(def.descr);
666 lbl->set_alignment(Gtk::ALIGN_LEFT, Gtk::ALIGN_CENTER);
667 widget = lbl;
668 } else {
669 // Glib::ustring blank(" ");
670 // if ( size == Inkscape::ICON_SIZE_MENU || size == Inkscape::ICON_SIZE_DECORATION ) {
671 // blank = " ";
672 // }
674 GtkWidget* eekWidget = eek_preview_new();
675 EekPreview * preview = EEK_PREVIEW(eekWidget);
676 Gtk::Widget* newBlot = Glib::wrap(eekWidget);
678 if ( previewMap.find(this) == previewMap.end() ){
679 eek_preview_set_color( preview, (def.getR() << 8) | def.getR(),
680 (def.getG() << 8) | def.getG(),
681 (def.getB() << 8) | def.getB());
682 } else {
683 guchar* px = previewMap[this];
684 int width = 128;
685 int height = 16;
686 GdkPixbuf* pixbuf = gdk_pixbuf_new_from_data( px, GDK_COLORSPACE_RGB, FALSE, 8,
687 width, height, width * 3,
688 0, // add delete function
689 0 );
690 eek_preview_set_pixbuf( preview, pixbuf );
691 }
692 if ( def.getType() != ege::PaintDef::RGB ) {
693 using Inkscape::IO::Resource::get_path;
694 using Inkscape::IO::Resource::ICONS;
695 using Inkscape::IO::Resource::SYSTEM;
696 GError *error = NULL;
697 gsize bytesRead = 0;
698 gsize bytesWritten = 0;
699 gchar *localFilename = g_filename_from_utf8( get_path(SYSTEM, ICONS, "remove-color.png"),
700 -1,
701 &bytesRead,
702 &bytesWritten,
703 &error);
704 GdkPixbuf* pixbuf = gdk_pixbuf_new_from_file(localFilename, &error);
705 if (!pixbuf) {
706 g_warning("Null pixbuf for %p [%s]", localFilename, localFilename );
707 }
708 g_free(localFilename);
710 eek_preview_set_pixbuf( preview, pixbuf );
711 }
713 eek_preview_set_details( preview, (::PreviewStyle)style, (::ViewType)view, (::PreviewSize)size, ratio );
714 eek_preview_set_linked( preview, (LinkType)((_linkSrc ? PREVIEW_LINK_IN:0)
715 | (_listeners.empty() ? 0:PREVIEW_LINK_OUT)
716 | (_isLive ? PREVIEW_LINK_OTHER:0)) );
718 def.addCallback( _colorDefChanged, this );
720 GValue val = {0, {{0}, {0}}};
721 g_value_init( &val, G_TYPE_BOOLEAN );
722 g_value_set_boolean( &val, FALSE );
723 g_object_set_property( G_OBJECT(preview), "focus-on-click", &val );
725 /*
726 Gtk::Button *btn = new Gtk::Button(blank);
727 Gdk::Color color;
728 color.set_rgb((_r << 8)|_r, (_g << 8)|_g, (_b << 8)|_b);
729 btn->modify_bg(Gtk::STATE_NORMAL, color);
730 btn->modify_bg(Gtk::STATE_ACTIVE, color);
731 btn->modify_bg(Gtk::STATE_PRELIGHT, color);
732 btn->modify_bg(Gtk::STATE_SELECTED, color);
734 Gtk::Widget* newBlot = btn;
735 */
737 tips.set_tip((*newBlot), def.descr);
739 /*
740 newBlot->signal_clicked().connect( sigc::mem_fun(*this, &ColorItem::buttonClicked) );
742 sigc::signal<void> type_signal_something;
743 */
745 g_signal_connect( G_OBJECT(newBlot->gobj()),
746 "clicked",
747 G_CALLBACK(handleClick),
748 this);
750 g_signal_connect( G_OBJECT(newBlot->gobj()),
751 "alt-clicked",
752 G_CALLBACK(handleSecondaryClick),
753 this);
755 g_signal_connect( G_OBJECT(newBlot->gobj()),
756 "button-press-event",
757 G_CALLBACK(handleButtonPress),
758 this);
760 {
761 std::vector<std::string> listing = def.getMIMETypes();
762 int entryCount = listing.size();
763 GtkTargetEntry* entries = new GtkTargetEntry[entryCount];
764 GtkTargetEntry* curr = entries;
765 for ( std::vector<std::string>::iterator it = listing.begin(); it != listing.end(); ++it ) {
766 curr->target = g_strdup(it->c_str());
767 curr->flags = 0;
768 if ( mimeToInt.find(*it) == mimeToInt.end() ){
769 // these next lines are order-dependent:
770 mimeToInt[*it] = mimeStrings.size();
771 mimeStrings.push_back(*it);
772 }
773 curr->info = mimeToInt[curr->target];
774 curr++;
775 }
776 gtk_drag_source_set( GTK_WIDGET(newBlot->gobj()),
777 GDK_BUTTON1_MASK,
778 entries, entryCount,
779 GdkDragAction(GDK_ACTION_MOVE | GDK_ACTION_COPY) );
780 for ( int i = 0; i < entryCount; i++ ) {
781 g_free(entries[i].target);
782 }
783 delete[] entries;
784 }
786 g_signal_connect( G_OBJECT(newBlot->gobj()),
787 "drag-data-get",
788 G_CALLBACK(ColorItem::_dragGetColorData),
789 this);
791 g_signal_connect( G_OBJECT(newBlot->gobj()),
792 "drag-begin",
793 G_CALLBACK(dragBegin),
794 this );
796 g_signal_connect( G_OBJECT(newBlot->gobj()),
797 "enter-notify-event",
798 G_CALLBACK(handleEnterNotify),
799 this);
801 g_signal_connect( G_OBJECT(newBlot->gobj()),
802 "leave-notify-event",
803 G_CALLBACK(handleLeaveNotify),
804 this);
806 // g_signal_connect( G_OBJECT(newBlot->gobj()),
807 // "drag-drop",
808 // G_CALLBACK(dragDropColorData),
809 // this);
811 if ( def.isEditable() )
812 {
813 // gtk_drag_dest_set( GTK_WIDGET(newBlot->gobj()),
814 // GTK_DEST_DEFAULT_ALL,
815 // destColorTargets,
816 // G_N_ELEMENTS(destColorTargets),
817 // GdkDragAction(GDK_ACTION_COPY | GDK_ACTION_MOVE) );
820 // g_signal_connect( G_OBJECT(newBlot->gobj()),
821 // "drag-data-received",
822 // G_CALLBACK(_dropDataIn),
823 // this );
824 }
826 g_signal_connect( G_OBJECT(newBlot->gobj()),
827 "destroy",
828 G_CALLBACK(dieDieDie),
829 this);
832 widget = newBlot;
833 }
835 _previews.push_back( widget );
837 return widget;
838 }
840 void ColorItem::buttonClicked(bool secondary)
841 {
842 SPDesktop *desktop = SP_ACTIVE_DESKTOP;
843 if (desktop) {
844 char const * attrName = secondary ? "stroke" : "fill";
846 SPCSSAttr *css = sp_repr_css_attr_new();
847 Glib::ustring descr;
848 switch (def.getType()) {
849 case ege::PaintDef::CLEAR: {
850 // TODO actually make this clear
851 sp_repr_css_set_property( css, attrName, "none" );
852 descr = secondary? _("Remove stroke color") : _("Remove fill color");
853 break;
854 }
855 case ege::PaintDef::NONE: {
856 sp_repr_css_set_property( css, attrName, "none" );
857 descr = secondary? _("Set stroke color to none") : _("Set fill color to none");
858 break;
859 }
860 case ege::PaintDef::RGB: {
861 Glib::ustring colorspec;
862 if ( gradMap.find(this) == gradMap.end() ){
863 gchar c[64];
864 guint32 rgba = (def.getR() << 24) | (def.getG() << 16) | (def.getB() << 8) | 0xff;
865 sp_svg_write_color(c, sizeof(c), rgba);
866 colorspec = c;
867 } else {
868 SPGradient* grad = gradMap[this];
869 colorspec = "url(#";
870 colorspec += grad->id;
871 colorspec += ")";
872 }
873 sp_repr_css_set_property( css, attrName, colorspec.c_str() );
874 descr = secondary? _("Set stroke color from swatch") : _("Set fill color from swatch");
875 break;
876 }
877 }
878 sp_desktop_set_style(desktop, css);
879 sp_repr_css_attr_unref(css);
881 sp_document_done( sp_desktop_document(desktop), SP_VERB_DIALOG_SWATCHES, descr.c_str() );
882 }
883 }
885 static char* trim( char* str ) {
886 char* ret = str;
887 while ( *str && (*str == ' ' || *str == '\t') ) {
888 str++;
889 }
890 ret = str;
891 while ( *str ) {
892 str++;
893 }
894 str--;
895 while ( str > ret && (( *str == ' ' || *str == '\t' ) || *str == '\r' || *str == '\n') ) {
896 *str-- = 0;
897 }
898 return ret;
899 }
901 void skipWhitespace( char*& str ) {
902 while ( *str == ' ' || *str == '\t' ) {
903 str++;
904 }
905 }
907 bool parseNum( char*& str, int& val ) {
908 val = 0;
909 while ( '0' <= *str && *str <= '9' ) {
910 val = val * 10 + (*str - '0');
911 str++;
912 }
913 bool retval = !(*str == 0 || *str == ' ' || *str == '\t' || *str == '\r' || *str == '\n');
914 return retval;
915 }
918 static bool getBlock( std::string& dst, guchar ch, std::string const str )
919 {
920 bool good = false;
921 std::string::size_type pos = str.find(ch);
922 if ( pos != std::string::npos )
923 {
924 std::string::size_type pos2 = str.find( '(', pos );
925 if ( pos2 != std::string::npos ) {
926 std::string::size_type endPos = str.find( ')', pos2 );
927 if ( endPos != std::string::npos ) {
928 dst = str.substr( pos2 + 1, (endPos - pos2 - 1) );
929 good = true;
930 }
931 }
932 }
933 return good;
934 }
936 static bool popVal( guint64& numVal, std::string& str )
937 {
938 bool good = false;
939 std::string::size_type endPos = str.find(',');
940 if ( endPos == std::string::npos ) {
941 endPos = str.length();
942 }
944 if ( endPos != std::string::npos && endPos > 0 ) {
945 std::string xxx = str.substr( 0, endPos );
946 const gchar* ptr = xxx.c_str();
947 gchar* endPtr = 0;
948 numVal = g_ascii_strtoull( ptr, &endPtr, 10 );
949 if ( (numVal == G_MAXUINT64) && (ERANGE == errno) ) {
950 // overflow
951 } else if ( (numVal == 0) && (endPtr == ptr) ) {
952 // failed conversion
953 } else {
954 good = true;
955 str.erase( 0, endPos + 1 );
956 }
957 }
959 return good;
960 }
962 void ColorItem::_wireMagicColors( void* p )
963 {
964 JustForNow* onceMore = reinterpret_cast<JustForNow*>(p);
965 if ( onceMore )
966 {
967 for ( std::vector<ColorItem*>::iterator it = onceMore->_colors.begin(); it != onceMore->_colors.end(); ++it )
968 {
969 std::string::size_type pos = (*it)->def.descr.find("*{");
970 if ( pos != std::string::npos )
971 {
972 std::string subby = (*it)->def.descr.substr( pos + 2 );
973 std::string::size_type endPos = subby.find("}*");
974 if ( endPos != std::string::npos )
975 {
976 subby.erase( endPos );
977 //g_message("FOUND MAGIC at '%s'", (*it)->def.descr.c_str());
978 //g_message(" '%s'", subby.c_str());
980 if ( subby.find('E') != std::string::npos )
981 {
982 (*it)->def.setEditable( true );
983 }
985 if ( subby.find('L') != std::string::npos )
986 {
987 (*it)->_isLive = true;
988 }
990 std::string part;
991 // Tint. index + 1 more val.
992 if ( getBlock( part, 'T', subby ) ) {
993 guint64 colorIndex = 0;
994 if ( popVal( colorIndex, part ) ) {
995 guint64 percent = 0;
996 if ( popVal( percent, part ) ) {
997 (*it)->_linkTint( *(onceMore->_colors[colorIndex]), percent );
998 }
999 }
1000 }
1002 // Shade/tone. index + 1 or 2 more val.
1003 if ( getBlock( part, 'S', subby ) ) {
1004 guint64 colorIndex = 0;
1005 if ( popVal( colorIndex, part ) ) {
1006 guint64 percent = 0;
1007 if ( popVal( percent, part ) ) {
1008 guint64 grayLevel = 0;
1009 if ( !popVal( grayLevel, part ) ) {
1010 grayLevel = 0;
1011 }
1012 (*it)->_linkTone( *(onceMore->_colors[colorIndex]), percent, grayLevel );
1013 }
1014 }
1015 }
1017 }
1018 }
1019 }
1020 }
1021 }
1024 void ColorItem::_linkTint( ColorItem& other, int percent )
1025 {
1026 if ( !_linkSrc )
1027 {
1028 other._listeners.push_back(this);
1029 _linkIsTone = false;
1030 _linkPercent = percent;
1031 if ( _linkPercent > 100 )
1032 _linkPercent = 100;
1033 if ( _linkPercent < 0 )
1034 _linkPercent = 0;
1035 _linkGray = 0;
1036 _linkSrc = &other;
1038 ColorItem::_colorDefChanged(&other);
1039 }
1040 }
1042 void ColorItem::_linkTone( ColorItem& other, int percent, int grayLevel )
1043 {
1044 if ( !_linkSrc )
1045 {
1046 other._listeners.push_back(this);
1047 _linkIsTone = true;
1048 _linkPercent = percent;
1049 if ( _linkPercent > 100 )
1050 _linkPercent = 100;
1051 if ( _linkPercent < 0 )
1052 _linkPercent = 0;
1053 _linkGray = grayLevel;
1054 _linkSrc = &other;
1056 ColorItem::_colorDefChanged(&other);
1057 }
1058 }
1061 void _loadPaletteFile( gchar const *filename )
1062 {
1063 char block[1024];
1064 FILE *f = Inkscape::IO::fopen_utf8name( filename, "r" );
1065 if ( f ) {
1066 char* result = fgets( block, sizeof(block), f );
1067 if ( result ) {
1068 if ( strncmp( "GIMP Palette", block, 12 ) == 0 ) {
1069 bool inHeader = true;
1070 bool hasErr = false;
1072 JustForNow *onceMore = new JustForNow();
1074 do {
1075 result = fgets( block, sizeof(block), f );
1076 block[sizeof(block) - 1] = 0;
1077 if ( result ) {
1078 if ( block[0] == '#' ) {
1079 // ignore comment
1080 } else {
1081 char *ptr = block;
1082 // very simple check for header versus entry
1083 while ( *ptr == ' ' || *ptr == '\t' ) {
1084 ptr++;
1085 }
1086 if ( (*ptr == 0) || (*ptr == '\r') || (*ptr == '\n') ) {
1087 // blank line. skip it.
1088 } else if ( '0' <= *ptr && *ptr <= '9' ) {
1089 // should be an entry link
1090 inHeader = false;
1091 ptr = block;
1092 Glib::ustring name("");
1093 int r = 0;
1094 int g = 0;
1095 int b = 0;
1096 skipWhitespace(ptr);
1097 if ( *ptr ) {
1098 hasErr = parseNum(ptr, r);
1099 if ( !hasErr ) {
1100 skipWhitespace(ptr);
1101 hasErr = parseNum(ptr, g);
1102 }
1103 if ( !hasErr ) {
1104 skipWhitespace(ptr);
1105 hasErr = parseNum(ptr, b);
1106 }
1107 if ( !hasErr && *ptr ) {
1108 char* n = trim(ptr);
1109 if (n != NULL) {
1110 name = n;
1111 }
1112 }
1113 if ( !hasErr ) {
1114 // Add the entry now
1115 Glib::ustring nameStr(name);
1116 ColorItem* item = new ColorItem( r, g, b, nameStr );
1117 onceMore->_colors.push_back(item);
1118 }
1119 } else {
1120 hasErr = true;
1121 }
1122 } else {
1123 if ( !inHeader ) {
1124 // Hmmm... probably bad. Not quite the format we want?
1125 hasErr = true;
1126 } else {
1127 char* sep = strchr(result, ':');
1128 if ( sep ) {
1129 *sep = 0;
1130 char* val = trim(sep + 1);
1131 char* name = trim(result);
1132 if ( *name ) {
1133 if ( strcmp( "Name", name ) == 0 )
1134 {
1135 onceMore->_name = val;
1136 }
1137 else if ( strcmp( "Columns", name ) == 0 )
1138 {
1139 gchar* endPtr = 0;
1140 guint64 numVal = g_ascii_strtoull( val, &endPtr, 10 );
1141 if ( (numVal == G_MAXUINT64) && (ERANGE == errno) ) {
1142 // overflow
1143 } else if ( (numVal == 0) && (endPtr == val) ) {
1144 // failed conversion
1145 } else {
1146 onceMore->_prefWidth = numVal;
1147 }
1148 }
1149 } else {
1150 // error
1151 hasErr = true;
1152 }
1153 } else {
1154 // error
1155 hasErr = true;
1156 }
1157 }
1158 }
1159 }
1160 }
1161 } while ( result && !hasErr );
1162 if ( !hasErr ) {
1163 possible.push_back(onceMore);
1164 #if ENABLE_MAGIC_COLORS
1165 ColorItem::_wireMagicColors( onceMore );
1166 #endif // ENABLE_MAGIC_COLORS
1167 } else {
1168 delete onceMore;
1169 }
1170 }
1171 }
1173 fclose(f);
1174 }
1175 }
1177 static void loadEmUp()
1178 {
1179 static bool beenHere = false;
1180 if ( !beenHere ) {
1181 beenHere = true;
1183 std::list<gchar *> sources;
1184 sources.push_back( profile_path("palettes") );
1185 sources.push_back( g_strdup(INKSCAPE_PALETTESDIR) );
1186 sources.push_back( g_strdup(CREATE_PALETTESDIR) );
1188 // Use this loop to iterate through a list of possible document locations.
1189 while (!sources.empty()) {
1190 gchar *dirname = sources.front();
1192 if ( Inkscape::IO::file_test( dirname, G_FILE_TEST_EXISTS )
1193 && Inkscape::IO::file_test( dirname, G_FILE_TEST_IS_DIR )) {
1194 GError *err = 0;
1195 GDir *directory = g_dir_open(dirname, 0, &err);
1196 if (!directory) {
1197 gchar *safeDir = Inkscape::IO::sanitizeString(dirname);
1198 g_warning(_("Palettes directory (%s) is unavailable."), safeDir);
1199 g_free(safeDir);
1200 } else {
1201 gchar *filename = 0;
1202 while ((filename = (gchar *)g_dir_read_name(directory)) != NULL) {
1203 gchar* lower = g_ascii_strdown( filename, -1 );
1204 // if ( g_str_has_suffix(lower, ".gpl") ) {
1205 gchar* full = g_build_filename(dirname, filename, NULL);
1206 if ( !Inkscape::IO::file_test( full, G_FILE_TEST_IS_DIR ) ) {
1207 _loadPaletteFile(full);
1208 }
1209 g_free(full);
1210 // }
1211 g_free(lower);
1212 }
1213 g_dir_close(directory);
1214 }
1215 }
1217 // toss the dirname
1218 g_free(dirname);
1219 sources.pop_front();
1220 }
1221 }
1222 }
1232 SwatchesPanel& SwatchesPanel::getInstance()
1233 {
1234 return *new SwatchesPanel();
1235 }
1238 /**
1239 * Constructor
1240 */
1241 SwatchesPanel::SwatchesPanel(gchar const* prefsPath) :
1242 Inkscape::UI::Widget::Panel("", prefsPath, SP_VERB_DIALOG_SWATCHES, "", true),
1243 _holder(0),
1244 _clear(0),
1245 _remove(0),
1246 _currentIndex(0),
1247 _currentDesktop(0),
1248 _currentDocument(0),
1249 _ptr(0)
1250 {
1251 Gtk::RadioMenuItem* hotItem = 0;
1252 _holder = new PreviewHolder();
1253 _clear = new ColorItem( ege::PaintDef::CLEAR );
1254 _clear->ptr = this;
1255 _remove = new ColorItem( ege::PaintDef::NONE );
1256 _remove->ptr = this;
1257 #if USE_DOCUMENT_PALETTE
1258 {
1259 JustForNow *docPalette = new JustForNow();
1261 docPalette->_name = "Auto";
1262 possible.push_back(docPalette);
1264 _ptr = docPalette;
1265 }
1266 #endif // USE_DOCUMENT_PALETTE
1267 loadEmUp();
1268 if ( !possible.empty() ) {
1269 JustForNow* first = 0;
1270 int index = 0;
1271 Glib::ustring targetName;
1272 if ( !_prefs_path.empty() ) {
1273 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1274 targetName = prefs->getString(_prefs_path + "/palette");
1275 if (!targetName.empty()) {
1276 for ( std::vector<JustForNow*>::iterator iter = possible.begin(); iter != possible.end(); ++iter ) {
1277 if ( (*iter)->_name == targetName ) {
1278 first = *iter;
1279 break;
1280 }
1281 index++;
1282 }
1283 }
1284 }
1286 if ( !first ) {
1287 first = possible.front();
1288 _currentIndex = 0;
1289 } else {
1290 _currentIndex = index;
1291 }
1293 _rebuild();
1295 Gtk::RadioMenuItem::Group groupOne;
1297 int i = 0;
1298 for ( std::vector<JustForNow*>::iterator it = possible.begin(); it != possible.end(); it++ ) {
1299 JustForNow* curr = *it;
1300 Gtk::RadioMenuItem* single = manage(new Gtk::RadioMenuItem(groupOne, curr->_name));
1301 if ( curr == first ) {
1302 hotItem = single;
1303 }
1304 _regItem( single, 3, i );
1305 i++;
1306 }
1307 }
1310 _getContents()->pack_start(*_holder, Gtk::PACK_EXPAND_WIDGET);
1311 _setTargetFillable(_holder);
1313 show_all_children();
1315 restorePanelPrefs();
1316 if ( hotItem ) {
1317 hotItem->set_active();
1318 }
1319 }
1321 SwatchesPanel::~SwatchesPanel()
1322 {
1323 _documentConnection.disconnect();
1324 _resourceConnection.disconnect();
1325 _selChanged.disconnect();
1326 _setModified.disconnect();
1327 _subselChanged.disconnect();
1329 if ( _clear ) {
1330 delete _clear;
1331 }
1332 if ( _remove ) {
1333 delete _remove;
1334 }
1335 if ( _holder ) {
1336 delete _holder;
1337 }
1338 }
1340 void SwatchesPanel::setOrientation( Gtk::AnchorType how )
1341 {
1342 // Must call the parent class or bad things might happen
1343 Inkscape::UI::Widget::Panel::setOrientation( how );
1345 if ( _holder )
1346 {
1347 _holder->setOrientation( Gtk::ANCHOR_SOUTH );
1348 }
1349 }
1351 void SwatchesPanel::setDesktop( SPDesktop* desktop )
1352 {
1353 if ( desktop != _currentDesktop ) {
1354 if ( _currentDesktop ) {
1355 _documentConnection.disconnect();
1356 _selChanged.disconnect();
1357 _setModified.disconnect();
1358 _subselChanged.disconnect();
1359 }
1361 _currentDesktop = desktop;
1363 if ( desktop ) {
1364 _currentDesktop->selection->connectChanged(
1365 sigc::hide(sigc::mem_fun(*this, &SwatchesPanel::_updateFromSelection)));
1367 _currentDesktop->selection->connectModified(
1368 sigc::hide(sigc::hide(sigc::mem_fun(*this, &SwatchesPanel::_updateFromSelection))));
1370 _currentDesktop->connectToolSubselectionChanged(
1371 sigc::hide(sigc::mem_fun(*this, &SwatchesPanel::_updateFromSelection)));
1373 sigc::bound_mem_functor1<void, Inkscape::UI::Dialogs::SwatchesPanel, SPDocument*> first = sigc::mem_fun(*this, &SwatchesPanel::_setDocument);
1374 sigc::slot<void, SPDocument*> base2 = first;
1375 sigc::slot<void,SPDesktop*, SPDocument*> slot2 = sigc::hide<0>( base2 );
1376 _documentConnection = desktop->connectDocumentReplaced( slot2 );
1378 _setDocument( desktop->doc() );
1379 } else {
1380 _setDocument(0);
1381 }
1382 }
1383 }
1385 void SwatchesPanel::_setDocument( SPDocument *document )
1386 {
1387 if ( document != _currentDocument ) {
1388 if ( _currentDocument ) {
1389 _resourceConnection.disconnect();
1390 }
1391 _currentDocument = document;
1392 if ( _currentDocument ) {
1393 _resourceConnection = sp_document_resources_changed_connect(document,
1394 "gradient",
1395 sigc::mem_fun(*this, &SwatchesPanel::handleGradientsChange));
1396 }
1398 handleGradientsChange();
1399 }
1400 }
1402 void SwatchesPanel::handleGradientsChange()
1403 {
1404 std::vector<SPGradient*> newList;
1406 const GSList *gradients = sp_document_get_resource_list(_currentDocument, "gradient");
1407 for (const GSList *item = gradients; item; item = item->next) {
1408 SPGradient* grad = SP_GRADIENT(item->data);
1409 if ( grad->has_stops ) {
1410 newList.push_back(SP_GRADIENT(item->data));
1411 }
1412 }
1414 #if USE_DOCUMENT_PALETTE
1415 if ( _ptr ) {
1416 JustForNow *docPalette = reinterpret_cast<JustForNow *>(_ptr);
1417 // TODO delete pointed to objects
1418 docPalette->_colors.clear();
1419 if ( !newList.empty() ) {
1420 for ( std::vector<SPGradient*>::iterator it = newList.begin(); it != newList.end(); ++it )
1421 {
1422 SPGradient* grad = *it;
1423 if ( grad->repr->attribute("osb:paint") ) {
1424 sp_gradient_ensure_vector( grad );
1425 SPGradientStop first = grad->vector.stops[0];
1426 SPColor color = first.color;
1427 guint32 together = color.toRGBA32(first.opacity);
1429 // At the moment we can't trust the count of 1 vs 2 stops.
1430 SPGradientStop second = (*it)->vector.stops[1];
1431 SPColor color2 = second.color;
1432 guint32 together2 = color2.toRGBA32(second.opacity);
1434 if ( (grad->vector.stops.size() <= 2) && (together == together2) ) {
1435 // Treat as solid-color
1436 Glib::ustring name( grad->id );
1437 unsigned int r = SP_RGBA32_R_U(together);
1438 unsigned int g = SP_RGBA32_G_U(together);
1439 unsigned int b = SP_RGBA32_B_U(together);
1440 ColorItem* item = new ColorItem( r, g, b, name );
1441 item->ptr = this;
1442 docPalette->_colors.push_back(item);
1443 gradMap[item] = grad;
1444 } else {
1445 // Treat as gradient
1446 Glib::ustring name( grad->id );
1447 unsigned int r = SP_RGBA32_R_U(together);
1448 unsigned int g = SP_RGBA32_G_U(together);
1449 unsigned int b = SP_RGBA32_B_U(together);
1450 ColorItem* item = new ColorItem( r, g, b, name );
1451 item->ptr = this;
1452 docPalette->_colors.push_back(item);
1454 gint width = 128;
1455 gint height = VBLOCK;
1456 guchar* px = g_new( guchar, 3 * height * width );
1457 nr_render_checkerboard_rgb( px, width, VBLOCK, 3 * width, 0, 0 );
1459 sp_gradient_render_vector_block_rgb( grad,
1460 px, width, height, 3 * width,
1461 0, width, TRUE );
1463 previewMap[item] = px;
1464 gradMap[item] = grad;
1465 }
1466 }
1467 }
1468 }
1469 JustForNow* curr = possible[_currentIndex];
1470 if (curr == docPalette) {
1471 _rebuild();
1472 }
1473 }
1474 #endif // USE_DOCUMENT_PALETTE
1475 }
1477 void SwatchesPanel::_updateFromSelection()
1478 {
1479 #if USE_DOCUMENT_PALETTE
1480 if ( _ptr ) {
1481 JustForNow *docPalette = reinterpret_cast<JustForNow *>(_ptr);
1483 Glib::ustring fillId;
1484 Glib::ustring strokeId;
1486 SPStyle *tmpStyle = sp_style_new( sp_desktop_document(_currentDesktop) );
1487 int result = sp_desktop_query_style( _currentDesktop, tmpStyle, QUERY_STYLE_PROPERTY_FILL );
1488 switch (result) {
1489 case QUERY_STYLE_SINGLE:
1490 case QUERY_STYLE_MULTIPLE_AVERAGED:
1491 case QUERY_STYLE_MULTIPLE_SAME:
1492 {
1493 if (tmpStyle->fill.set && tmpStyle->fill.isPaintserver()) {
1494 SPPaintServer* server = tmpStyle->getFillPaintServer();
1495 if ( SP_IS_GRADIENT(server) ) {
1496 SPGradient* target = 0;
1497 SPGradient* grad = SP_GRADIENT(server);
1498 if (grad->repr->attribute("osb:paint")) {
1499 target = grad;
1500 } else if ( grad->ref ) {
1501 SPGradient *tmp = grad->ref->getObject();
1502 if ( tmp && tmp->repr->attribute("osb:paint") ) {
1503 target = tmp;
1504 }
1505 }
1506 if ( target ) {
1507 gchar const* id = target->repr->attribute("id");
1508 if ( id ) {
1509 fillId = id;
1510 }
1511 }
1512 }
1513 }
1514 break;
1515 }
1516 }
1518 result = sp_desktop_query_style( _currentDesktop, tmpStyle, QUERY_STYLE_PROPERTY_STROKE );
1519 switch (result) {
1520 case QUERY_STYLE_SINGLE:
1521 case QUERY_STYLE_MULTIPLE_AVERAGED:
1522 case QUERY_STYLE_MULTIPLE_SAME:
1523 {
1524 if (tmpStyle->stroke.set && tmpStyle->stroke.isPaintserver()) {
1525 SPPaintServer* server = tmpStyle->getStrokePaintServer();
1526 if ( SP_IS_GRADIENT(server) ) {
1527 SPGradient* target = 0;
1528 SPGradient* grad = SP_GRADIENT(server);
1529 if (grad->repr->attribute("osb:paint")) {
1530 target = grad;
1531 } else if ( grad->ref ) {
1532 SPGradient *tmp = grad->ref->getObject();
1533 if ( tmp && tmp->repr->attribute("osb:paint") ) {
1534 target = tmp;
1535 }
1536 }
1537 if ( target ) {
1538 gchar const* id = target->repr->attribute("id");
1539 if ( id ) {
1540 strokeId = id;
1541 }
1542 }
1543 }
1544 }
1545 break;
1546 }
1547 }
1548 sp_style_unref(tmpStyle);
1550 for ( std::vector<ColorItem*>::iterator it = docPalette->_colors.begin(); it != docPalette->_colors.end(); ++it ) {
1551 ColorItem* item = *it;
1552 bool isFill = (fillId == item->def.descr);
1553 bool isStroke = (strokeId == item->def.descr);
1554 item->setState( isFill, isStroke );
1555 }
1556 }
1557 #endif // USE_DOCUMENT_PALETTE
1558 }
1560 void SwatchesPanel::_handleAction( int setId, int itemId )
1561 {
1562 switch( setId ) {
1563 case 3:
1564 {
1565 if ( itemId >= 0 && itemId < static_cast<int>(possible.size()) ) {
1566 _currentIndex = itemId;
1568 if ( !_prefs_path.empty() ) {
1569 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1570 prefs->setString(_prefs_path + "/palette", possible[_currentIndex]->_name);
1571 }
1573 _rebuild();
1574 }
1575 }
1576 break;
1577 }
1578 }
1580 void SwatchesPanel::_rebuild()
1581 {
1582 JustForNow* curr = possible[_currentIndex];
1583 _holder->clear();
1585 if ( curr->_prefWidth > 0 ) {
1586 _holder->setColumnPref( curr->_prefWidth );
1587 }
1588 _holder->freezeUpdates();
1589 // TODO restore once 'clear' works _holder->addPreview(_clear);
1590 _holder->addPreview(_remove);
1591 for ( std::vector<ColorItem*>::iterator it = curr->_colors.begin(); it != curr->_colors.end(); it++ ) {
1592 _holder->addPreview(*it);
1593 }
1594 _holder->thawUpdates();
1595 }
1600 } //namespace Dialogs
1601 } //namespace UI
1602 } //namespace Inkscape
1605 /*
1606 Local Variables:
1607 mode:c++
1608 c-file-style:"stroustrup"
1609 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1610 indent-tabs-mode:nil
1611 fill-column:99
1612 End:
1613 */
1614 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :