Code

Implementing the "Convert" popup menu item for gradients/swatches. Part of bug #59441.
[inkscape.git] / src / ui / dialog / swatches.cpp
2 /** @file
3  * @brief Color swatches dialog
4  */
5 /* Authors:
6  *   Jon A. Cruz
7  *   John Bintz
8  *
9  * Copyright (C) 2005 Jon A. Cruz
10  * Copyright (C) 2008 John Bintz
11  *
12  * Released under GNU GPL, read the file 'COPYING' for more information
13  */
15 #include <errno.h>
16 #include <map>
18 #include <gtk/gtkdialog.h> //for GTK_RESPONSE* types
19 #include <gtk/gtkdnd.h>
20 #include <gtk/gtkmenu.h>
21 #include <gtk/gtkmenuitem.h>
22 #include <gtk/gtkseparatormenuitem.h>
23 #include <glibmm/i18n.h>
24 #include <gdkmm/pixbuf.h>
26 #include "color-item.h"
27 #include "desktop.h"
28 #include "desktop-handles.h"
29 #include "desktop-style.h"
30 #include "document.h"
31 #include "document-private.h"
32 #include "extension/db.h"
33 #include "inkscape.h"
34 #include "inkscape.h"
35 #include "io/sys.h"
36 #include "io/resource.h"
37 #include "message-context.h"
38 #include "path-prefix.h"
39 #include "preferences.h"
40 #include "sp-item.h"
41 #include "sp-gradient-fns.h"
42 #include "sp-gradient.h"
43 #include "sp-gradient-vector.h"
44 #include "swatches.h"
45 #include "style.h"
46 #include "ui/previewholder.h"
47 #include "widgets/desktop-widget.h"
48 #include "widgets/gradient-vector.h"
49 #include "widgets/eek-preview.h"
50 #include "display/nr-plain-stuff.h"
51 #include "sp-gradient-reference.h"
54 namespace Inkscape {
55 namespace UI {
56 namespace Dialogs {
58 #define VBLOCK 16
59 #define PREVIEW_PIXBUF_WIDTH 128
61 void _loadPaletteFile( gchar const *filename );
64 class DocTrack;
66 std::vector<SwatchPage*> possible;
67 static std::map<SPDocument*, SwatchPage*> docPalettes;
68 static std::vector<DocTrack*> docTrackings;
69 static std::map<SwatchesPanel*, SPDocument*> docPerPanel;
72 class SwatchesPanelHook : public SwatchesPanel
73 {
74 public:
75     static void convertGradient( GtkMenuItem * menuitem, gpointer userData );
76 };
78 static void handleClick( GtkWidget* /*widget*/, gpointer callback_data ) {
79     ColorItem* item = reinterpret_cast<ColorItem*>(callback_data);
80     if ( item ) {
81         item->buttonClicked(false);
82     }
83 }
85 static void handleSecondaryClick( GtkWidget* /*widget*/, gint /*arg1*/, gpointer callback_data ) {
86     ColorItem* item = reinterpret_cast<ColorItem*>(callback_data);
87     if ( item ) {
88         item->buttonClicked(true);
89     }
90 }
92 static GtkWidget* popupMenu = 0;
93 static GtkWidget *popupSubHolder = 0;
94 static GtkWidget *popupSub = 0;
95 static std::vector<Glib::ustring> popupItems;
96 static std::vector<GtkWidget*> popupExtras;
97 static ColorItem* bounceTarget = 0;
98 static SwatchesPanel* bouncePanel = 0;
100 static void redirClick( GtkMenuItem *menuitem, gpointer /*user_data*/ )
102     if ( bounceTarget ) {
103         handleClick( GTK_WIDGET(menuitem), bounceTarget );
104     }
107 static void redirSecondaryClick( GtkMenuItem *menuitem, gpointer /*user_data*/ )
109     if ( bounceTarget ) {
110         handleSecondaryClick( GTK_WIDGET(menuitem), 0, bounceTarget );
111     }
114 static void editGradientImpl( SPGradient* gr )
116     if ( gr ) {
117         GtkWidget *dialog = sp_gradient_vector_editor_new( gr );
118         gtk_widget_show( dialog );
119     }
122 static void editGradient( GtkMenuItem */*menuitem*/, gpointer /*user_data*/ )
124     if ( bounceTarget ) {
125         SwatchesPanel* swp = bouncePanel;
126         SPDesktop* desktop = swp ? swp->getDesktop() : 0;
127         SPDocument *doc = desktop ? desktop->doc() : 0;
128         if (doc) {
129             std::string targetName(bounceTarget->def.descr);
130             const GSList *gradients = sp_document_get_resource_list(doc, "gradient");
131             for (const GSList *item = gradients; item; item = item->next) {
132                 SPGradient* grad = SP_GRADIENT(item->data);
133                 if ( targetName == grad->getId() ) {
134                     editGradientImpl( grad );
135                     break;
136                 }
137             }
138         }
139     }
142 static void addNewGradient( GtkMenuItem */*menuitem*/, gpointer /*user_data*/ )
144     if ( bounceTarget ) {
145         SwatchesPanel* swp = bouncePanel;
146         SPDesktop* desktop = swp ? swp->getDesktop() : 0;
147         SPDocument *doc = desktop ? desktop->doc() : 0;
148         if (doc) {
149             Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
151             Inkscape::XML::Node *repr = xml_doc->createElement("svg:linearGradient");
152             repr->setAttribute("osb:paint", "solid");
153             Inkscape::XML::Node *stop = xml_doc->createElement("svg:stop");
154             stop->setAttribute("offset", "0");
155             stop->setAttribute("style", "stop-color:#000;stop-opacity:1;");
156             repr->appendChild(stop);
157             Inkscape::GC::release(stop);
159             SP_OBJECT_REPR( SP_DOCUMENT_DEFS(doc) )->addChild(repr, NULL);
161             SPGradient * gr = static_cast<SPGradient *>(doc->getObjectByRepr(repr));
163             Inkscape::GC::release(repr);
166             editGradientImpl( gr );
167         }
168     }
171 void SwatchesPanelHook::convertGradient( GtkMenuItem * /*menuitem*/, gpointer userData )
173     if ( bounceTarget ) {
174         SwatchesPanel* swp = bouncePanel;
175         SPDesktop* desktop = swp ? swp->getDesktop() : 0;
176         SPDocument *doc = desktop ? desktop->doc() : 0;
177         gint index = GPOINTER_TO_INT(userData);
178         if ( doc && (index >= 0) && (static_cast<guint>(index) < popupItems.size()) ) {
179             Glib::ustring targetName = popupItems[index];
181             const GSList *gradients = sp_document_get_resource_list(doc, "gradient");
182             for (const GSList *item = gradients; item; item = item->next) {
183                 SPGradient* grad = SP_GRADIENT(item->data);
184                 if ( targetName == grad->getId() ) {
185                     grad->repr->setAttribute("osb:paint", "solid");
187                     sp_document_done(doc, SP_VERB_CONTEXT_GRADIENT,
188                                      _("Add gradient stop"));
190                     handleGradientsChange(doc); // work-around for signal not being emmitted
191                     break;
192                 }
193             }
194         }
195     }
198 static SwatchesPanel* findContainingPanel( GtkWidget *widget )
200     SwatchesPanel *swp = 0;
202     std::map<GtkWidget*, SwatchesPanel*> rawObjects;
203     for (std::map<SwatchesPanel*, SPDocument*>::iterator it = docPerPanel.begin(); it != docPerPanel.end(); ++it) {
204         rawObjects[GTK_WIDGET(it->first->gobj())] = it->first;
205     }
207     for (GtkWidget* curr = widget; curr && !swp; curr = gtk_widget_get_parent(curr)) {
208         if (rawObjects.find(curr) != rawObjects.end()) {
209             swp = rawObjects[curr];
210         }
211     }
213     return swp;
216 static void removeit( GtkWidget *widget, gpointer data )
218     gtk_container_remove( GTK_CONTAINER(data), widget );
221 gboolean colorItemHandleButtonPress( GtkWidget* widget, GdkEventButton* event, gpointer user_data )
223     gboolean handled = FALSE;
225     if ( (event->button == 3) && (event->type == GDK_BUTTON_PRESS) ) {
226         SwatchesPanel* swp = findContainingPanel( widget );
228         if ( !popupMenu ) {
229             popupMenu = gtk_menu_new();
230             GtkWidget* child = 0;
232             //TRANSLATORS: An item in context menu on a colour in the swatches
233             child = gtk_menu_item_new_with_label(_("Set fill"));
234             g_signal_connect( G_OBJECT(child),
235                               "activate",
236                               G_CALLBACK(redirClick),
237                               user_data);
238             gtk_menu_shell_append(GTK_MENU_SHELL(popupMenu), child);
240             //TRANSLATORS: An item in context menu on a colour in the swatches
241             child = gtk_menu_item_new_with_label(_("Set stroke"));
243             g_signal_connect( G_OBJECT(child),
244                               "activate",
245                               G_CALLBACK(redirSecondaryClick),
246                               user_data);
247             gtk_menu_shell_append(GTK_MENU_SHELL(popupMenu), child);
249             child = gtk_separator_menu_item_new();
250             gtk_menu_shell_append(GTK_MENU_SHELL(popupMenu), child);
251             popupExtras.push_back(child);
253             child = gtk_menu_item_new_with_label(_("Add"));
254             g_signal_connect( G_OBJECT(child),
255                               "activate",
256                               G_CALLBACK(addNewGradient),
257                               user_data );
258             gtk_menu_shell_append(GTK_MENU_SHELL(popupMenu), child);
259             popupExtras.push_back(child);
261             child = gtk_menu_item_new_with_label(_("Delete"));
262             gtk_menu_shell_append(GTK_MENU_SHELL(popupMenu), child);
263             //popupExtras.push_back(child);
264             gtk_widget_set_sensitive( child, FALSE );
266             child = gtk_menu_item_new_with_label(_("Edit..."));
267             g_signal_connect( G_OBJECT(child),
268                               "activate",
269                               G_CALLBACK(editGradient),
270                               user_data );
271             gtk_menu_shell_append(GTK_MENU_SHELL(popupMenu), child);
272             popupExtras.push_back(child);
274             child = gtk_separator_menu_item_new();
275             gtk_menu_shell_append(GTK_MENU_SHELL(popupMenu), child);
276             popupExtras.push_back(child);
278             child = gtk_menu_item_new_with_label(_("Convert"));
279             gtk_menu_shell_append(GTK_MENU_SHELL(popupMenu), child);
280             //popupExtras.push_back(child);
281             //gtk_widget_set_sensitive( child, FALSE );
282             {
283                 popupSubHolder = child;
284                 popupSub = gtk_menu_new();
285                 gtk_menu_item_set_submenu( GTK_MENU_ITEM(child), popupSub );
286             }
288             gtk_widget_show_all(popupMenu);
289         }
291         ColorItem* item = reinterpret_cast<ColorItem*>(user_data);
292         if ( item ) {
293             bool show = swp && (swp->getSelectedIndex() == 0);
294             for ( std::vector<GtkWidget*>::iterator it = popupExtras.begin(); it != popupExtras.end(); ++ it) {
295                 gtk_widget_set_sensitive(*it, show);
296             }
298             bounceTarget = item;
299             bouncePanel = swp;
300             popupItems.clear();
301             if ( popupMenu ) {
302                 gtk_container_foreach(GTK_CONTAINER(popupSub), removeit, popupSub);
303                 bool processed = false;
304                 GtkWidget *wdgt = gtk_widget_get_ancestor(widget, SP_TYPE_DESKTOP_WIDGET);
305                 if ( wdgt ) {
306                     SPDesktopWidget *dtw = SP_DESKTOP_WIDGET(wdgt);
307                     if ( dtw && dtw->desktop ) {
308                         // Pick up all gradients with vectors
309                         const GSList *gradients = sp_document_get_resource_list(dtw->desktop->doc(), "gradient");
310                         gint index = 0;
311                         for (const GSList *curr = gradients; curr; curr = curr->next) {
312                             SPGradient* grad = SP_GRADIENT(curr->data);
313                             if (SP_GRADIENT_HAS_STOPS(grad) && !grad->isSwatch()) {
314                                 //gl = g_slist_prepend(gl, curr->data);
315                                 processed = true;
316                                 GtkWidget *child = gtk_menu_item_new_with_label(grad->getId());
317                                 gtk_menu_shell_append(GTK_MENU_SHELL(popupSub), child);
319                                 popupItems.push_back(grad->getId());
320                                 g_signal_connect( G_OBJECT(child),
321                                                   "activate",
322                                                   G_CALLBACK(SwatchesPanelHook::convertGradient),
323                                                   GINT_TO_POINTER(index) );
324                                 index++;
325                             }
326                         }
328                         gtk_widget_show_all(popupSub);
329                     }
330                 }
331                 gtk_widget_set_sensitive( popupSubHolder, processed );
333                 gtk_menu_popup(GTK_MENU(popupMenu), NULL, NULL, NULL, NULL, event->button, event->time);
334                 handled = TRUE;
335             }
336         }
337     }
339     return handled;
343 static char* trim( char* str ) {
344     char* ret = str;
345     while ( *str && (*str == ' ' || *str == '\t') ) {
346         str++;
347     }
348     ret = str;
349     while ( *str ) {
350         str++;
351     }
352     str--;
353     while ( str > ret && (( *str == ' ' || *str == '\t' ) || *str == '\r' || *str == '\n') ) {
354         *str-- = 0;
355     }
356     return ret;
359 void skipWhitespace( char*& str ) {
360     while ( *str == ' ' || *str == '\t' ) {
361         str++;
362     }
365 bool parseNum( char*& str, int& val ) {
366     val = 0;
367     while ( '0' <= *str && *str <= '9' ) {
368         val = val * 10 + (*str - '0');
369         str++;
370     }
371     bool retval = !(*str == 0 || *str == ' ' || *str == '\t' || *str == '\r' || *str == '\n');
372     return retval;
376 void _loadPaletteFile( gchar const *filename )
378     char block[1024];
379     FILE *f = Inkscape::IO::fopen_utf8name( filename, "r" );
380     if ( f ) {
381         char* result = fgets( block, sizeof(block), f );
382         if ( result ) {
383             if ( strncmp( "GIMP Palette", block, 12 ) == 0 ) {
384                 bool inHeader = true;
385                 bool hasErr = false;
387                 SwatchPage *onceMore = new SwatchPage();
389                 do {
390                     result = fgets( block, sizeof(block), f );
391                     block[sizeof(block) - 1] = 0;
392                     if ( result ) {
393                         if ( block[0] == '#' ) {
394                             // ignore comment
395                         } else {
396                             char *ptr = block;
397                             // very simple check for header versus entry
398                             while ( *ptr == ' ' || *ptr == '\t' ) {
399                                 ptr++;
400                             }
401                             if ( (*ptr == 0) || (*ptr == '\r') || (*ptr == '\n') ) {
402                                 // blank line. skip it.
403                             } else if ( '0' <= *ptr && *ptr <= '9' ) {
404                                 // should be an entry link
405                                 inHeader = false;
406                                 ptr = block;
407                                 Glib::ustring name("");
408                                 int r = 0;
409                                 int g = 0;
410                                 int b = 0;
411                                 skipWhitespace(ptr);
412                                 if ( *ptr ) {
413                                     hasErr = parseNum(ptr, r);
414                                     if ( !hasErr ) {
415                                         skipWhitespace(ptr);
416                                         hasErr = parseNum(ptr, g);
417                                     }
418                                     if ( !hasErr ) {
419                                         skipWhitespace(ptr);
420                                         hasErr = parseNum(ptr, b);
421                                     }
422                                     if ( !hasErr && *ptr ) {
423                                         char* n = trim(ptr);
424                                         if (n != NULL) {
425                                             name = n;
426                                         }
427                                     }
428                                     if ( !hasErr ) {
429                                         // Add the entry now
430                                         Glib::ustring nameStr(name);
431                                         ColorItem* item = new ColorItem( r, g, b, nameStr );
432                                         onceMore->_colors.push_back(item);
433                                     }
434                                 } else {
435                                     hasErr = true;
436                                 }
437                             } else {
438                                 if ( !inHeader ) {
439                                     // Hmmm... probably bad. Not quite the format we want?
440                                     hasErr = true;
441                                 } else {
442                                     char* sep = strchr(result, ':');
443                                     if ( sep ) {
444                                         *sep = 0;
445                                         char* val = trim(sep + 1);
446                                         char* name = trim(result);
447                                         if ( *name ) {
448                                             if ( strcmp( "Name", name ) == 0 )
449                                             {
450                                                 onceMore->_name = val;
451                                             }
452                                             else if ( strcmp( "Columns", name ) == 0 )
453                                             {
454                                                 gchar* endPtr = 0;
455                                                 guint64 numVal = g_ascii_strtoull( val, &endPtr, 10 );
456                                                 if ( (numVal == G_MAXUINT64) && (ERANGE == errno) ) {
457                                                     // overflow
458                                                 } else if ( (numVal == 0) && (endPtr == val) ) {
459                                                     // failed conversion
460                                                 } else {
461                                                     onceMore->_prefWidth = numVal;
462                                                 }
463                                             }
464                                         } else {
465                                             // error
466                                             hasErr = true;
467                                         }
468                                     } else {
469                                         // error
470                                         hasErr = true;
471                                     }
472                                 }
473                             }
474                         }
475                     }
476                 } while ( result && !hasErr );
477                 if ( !hasErr ) {
478                     possible.push_back(onceMore);
479 #if ENABLE_MAGIC_COLORS
480                     ColorItem::_wireMagicColors( onceMore );
481 #endif // ENABLE_MAGIC_COLORS
482                 } else {
483                     delete onceMore;
484                 }
485             }
486         }
488         fclose(f);
489     }
492 static void loadEmUp()
494     static bool beenHere = false;
495     if ( !beenHere ) {
496         beenHere = true;
498         std::list<gchar *> sources;
499         sources.push_back( profile_path("palettes") );
500         sources.push_back( g_strdup(INKSCAPE_PALETTESDIR) );
501         sources.push_back( g_strdup(CREATE_PALETTESDIR) );
503         // Use this loop to iterate through a list of possible document locations.
504         while (!sources.empty()) {
505             gchar *dirname = sources.front();
507             if ( Inkscape::IO::file_test( dirname, G_FILE_TEST_EXISTS )
508                 && Inkscape::IO::file_test( dirname, G_FILE_TEST_IS_DIR )) {
509                 GError *err = 0;
510                 GDir *directory = g_dir_open(dirname, 0, &err);
511                 if (!directory) {
512                     gchar *safeDir = Inkscape::IO::sanitizeString(dirname);
513                     g_warning(_("Palettes directory (%s) is unavailable."), safeDir);
514                     g_free(safeDir);
515                 } else {
516                     gchar *filename = 0;
517                     while ((filename = (gchar *)g_dir_read_name(directory)) != NULL) {
518                         gchar* lower = g_ascii_strdown( filename, -1 );
519 //                        if ( g_str_has_suffix(lower, ".gpl") ) {
520                             gchar* full = g_build_filename(dirname, filename, NULL);
521                             if ( !Inkscape::IO::file_test( full, G_FILE_TEST_IS_DIR ) ) {
522                                 _loadPaletteFile(full);
523                             }
524                             g_free(full);
525 //                      }
526                         g_free(lower);
527                     }
528                     g_dir_close(directory);
529                 }
530             }
532             // toss the dirname
533             g_free(dirname);
534             sources.pop_front();
535         }
536     }
547 SwatchesPanel& SwatchesPanel::getInstance()
549     return *new SwatchesPanel();
553 /**
554  * Constructor
555  */
556 SwatchesPanel::SwatchesPanel(gchar const* prefsPath) :
557     Inkscape::UI::Widget::Panel("", prefsPath, SP_VERB_DIALOG_SWATCHES, "", true),
558     _holder(0),
559     _clear(0),
560     _remove(0),
561     _currentIndex(0),
562     _currentDesktop(0),
563     _currentDocument(0)
565     Gtk::RadioMenuItem* hotItem = 0;
566     _holder = new PreviewHolder();
567     _clear = new ColorItem( ege::PaintDef::CLEAR );
568     _remove = new ColorItem( ege::PaintDef::NONE );
569     if (docPalettes.empty()) {
570         SwatchPage *docPalette = new SwatchPage();
572         docPalette->_name = "Auto";
573         docPalettes[0] = docPalette;
574     }
576     loadEmUp();
577     if ( !possible.empty() ) {
578         SwatchPage* first = 0;
579         int index = 0;
580         Glib::ustring targetName;
581         if ( !_prefs_path.empty() ) {
582             Inkscape::Preferences *prefs = Inkscape::Preferences::get();
583             targetName = prefs->getString(_prefs_path + "/palette");
584             if (!targetName.empty()) {
585                 if (targetName == "Auto") {
586                     first = docPalettes[0];
587                 } else {
588                     index++;
589                     for ( std::vector<SwatchPage*>::iterator iter = possible.begin(); iter != possible.end(); ++iter ) {
590                         if ( (*iter)->_name == targetName ) {
591                             first = *iter;
592                             break;
593                         }
594                         index++;
595                     }
596                 }
597             }
598         }
600         if ( !first ) {
601             first = docPalettes[0];
602             _currentIndex = 0;
603         } else {
604             _currentIndex = index;
605         }
607         _rebuild();
609         Gtk::RadioMenuItem::Group groupOne;
611         int i = 0;
612         std::vector<SwatchPage*> swatchSets = _getSwatchSets();
613         for ( std::vector<SwatchPage*>::iterator it = swatchSets.begin(); it != swatchSets.end(); it++ ) {
614             SwatchPage* curr = *it;
615             Gtk::RadioMenuItem* single = manage(new Gtk::RadioMenuItem(groupOne, curr->_name));
616             if ( curr == first ) {
617                 hotItem = single;
618             }
619             _regItem( single, 3, i );
620             i++;
621         }
622     }
625     _getContents()->pack_start(*_holder, Gtk::PACK_EXPAND_WIDGET);
626     _setTargetFillable(_holder);
628     show_all_children();
630     restorePanelPrefs();
631     if ( hotItem ) {
632         hotItem->set_active();
633     }
636 SwatchesPanel::~SwatchesPanel()
638     _trackDocument( this, 0 );
640     _documentConnection.disconnect();
641     _selChanged.disconnect();
643     if ( _clear ) {
644         delete _clear;
645     }
646     if ( _remove ) {
647         delete _remove;
648     }
649     if ( _holder ) {
650         delete _holder;
651     }
654 void SwatchesPanel::setOrientation( Gtk::AnchorType how )
656     // Must call the parent class or bad things might happen
657     Inkscape::UI::Widget::Panel::setOrientation( how );
659     if ( _holder )
660     {
661         _holder->setOrientation( Gtk::ANCHOR_SOUTH );
662     }
665 void SwatchesPanel::setDesktop( SPDesktop* desktop )
667     if ( desktop != _currentDesktop ) {
668         if ( _currentDesktop ) {
669             _documentConnection.disconnect();
670             _selChanged.disconnect();
671         }
673         _currentDesktop = desktop;
675         if ( desktop ) {
676             _currentDesktop->selection->connectChanged(
677                 sigc::hide(sigc::mem_fun(*this, &SwatchesPanel::_updateFromSelection)));
679             _currentDesktop->selection->connectModified(
680                 sigc::hide(sigc::hide(sigc::mem_fun(*this, &SwatchesPanel::_updateFromSelection))));
682             _currentDesktop->connectToolSubselectionChanged(
683                 sigc::hide(sigc::mem_fun(*this, &SwatchesPanel::_updateFromSelection)));
685             sigc::bound_mem_functor1<void, Inkscape::UI::Dialogs::SwatchesPanel, SPDocument*> first = sigc::mem_fun(*this, &SwatchesPanel::_setDocument);
686             sigc::slot<void, SPDocument*> base2 = first;
687             sigc::slot<void,SPDesktop*, SPDocument*> slot2 = sigc::hide<0>( base2 );
688             _documentConnection = desktop->connectDocumentReplaced( slot2 );
690             _setDocument( desktop->doc() );
691         } else {
692             _setDocument(0);
693         }
694     }
698 class DocTrack
700 public:
701     DocTrack(SPDocument *doc, sigc::connection &gradientRsrcChanged, sigc::connection &defsChanged, sigc::connection &defsModified) :
702         doc(doc),
703         gradientRsrcChanged(gradientRsrcChanged),
704         defsChanged(defsChanged),
705         defsModified(defsModified)
706     {
707     }
709     ~DocTrack()
710     {
711         if (doc) {
712             gradientRsrcChanged.disconnect();
713             defsChanged.disconnect();
714             defsModified.disconnect();
715         }
716     }
718     SPDocument *doc;
719     sigc::connection gradientRsrcChanged;
720     sigc::connection defsChanged;
721     sigc::connection defsModified;
723 private:
724     DocTrack(DocTrack const &); // no copy
725     DocTrack &operator=(DocTrack const &); // no assign
726 };
728 void SwatchesPanel::_trackDocument( SwatchesPanel *panel, SPDocument *document )
730     SPDocument *oldDoc = 0;
731     if (docPerPanel.find(panel) != docPerPanel.end()) {
732         oldDoc = docPerPanel[panel];
733         if (!oldDoc) {
734             docPerPanel.erase(panel); // Should not be needed, but clean up just in case.
735         }
736     }
737     if (oldDoc != document) {
738         if (oldDoc) {
739             docPerPanel[panel] = 0;
740             bool found = false;
741             for (std::map<SwatchesPanel*, SPDocument*>::iterator it = docPerPanel.begin(); (it != docPerPanel.end()) && !found; ++it) {
742                 found = (it->second == document);
743             }
744             if (!found) {
745                 for (std::vector<DocTrack*>::iterator it = docTrackings.begin(); it != docTrackings.end(); ++it){
746                     if ((*it)->doc == oldDoc) {
747                         delete *it;
748                         docTrackings.erase(it);
749                         break;
750                     }
751                 }
752             }
753         }
755         if (document) {
756             bool found = false;
757             for (std::map<SwatchesPanel*, SPDocument*>::iterator it = docPerPanel.begin(); (it != docPerPanel.end()) && !found; ++it) {
758                 found = (it->second == document);
759             }
760             docPerPanel[panel] = document;
761             if (!found) {
762                 sigc::connection conn1 = sp_document_resources_changed_connect( document, "gradient", sigc::bind(sigc::ptr_fun(&SwatchesPanel::handleGradientsChange), document) );
763                 sigc::connection conn2 = SP_DOCUMENT_DEFS(document)->connectRelease( sigc::hide(sigc::bind(sigc::ptr_fun(&SwatchesPanel::handleDefsModified), document)) );
764                 sigc::connection conn3 = SP_DOCUMENT_DEFS(document)->connectModified( sigc::hide(sigc::hide(sigc::bind(sigc::ptr_fun(&SwatchesPanel::handleDefsModified), document))) );
766                 DocTrack *dt = new DocTrack(document, conn1, conn2, conn3);
767                 docTrackings.push_back(dt);
769                 if (docPalettes.find(document) == docPalettes.end()) {
770                     SwatchPage *docPalette = new SwatchPage();
771                     docPalette->_name = "Auto";
772                     docPalettes[document] = docPalette;
773                 }
774             }
775         }
776     }
778     std::set<SPDocument*> docs;
779     for (std::map<SwatchesPanel*, SPDocument*>::iterator it = docPerPanel.begin(); it != docPerPanel.end(); ++it) {
780         docs.insert(it->second);
781     }
784 void SwatchesPanel::_setDocument( SPDocument *document )
786     if ( document != _currentDocument ) {
787         _trackDocument(this, document);
788         _currentDocument = document;
789         handleGradientsChange( document );
790     }
793 static void recalcSwatchContents(SPDocument* doc,
794                 std::vector<ColorItem*> &tmpColors,
795                 std::map<ColorItem*, guchar*> &previewMappings,
796                 std::map<ColorItem*, SPGradient*> &gradMappings)
798     std::vector<SPGradient*> newList;
800     const GSList *gradients = sp_document_get_resource_list(doc, "gradient");
801     for (const GSList *item = gradients; item; item = item->next) {
802         SPGradient* grad = SP_GRADIENT(item->data);
803         if ( grad->isSwatch() ) {
804             newList.push_back(SP_GRADIENT(item->data));
805         }
806     }
808     if ( !newList.empty() ) {
809         for ( std::vector<SPGradient*>::iterator it = newList.begin(); it != newList.end(); ++it )
810         {
811             SPGradient* grad = *it;
812             sp_gradient_ensure_vector( grad );
813             SPGradientStop first = grad->vector.stops[0];
814             SPColor color = first.color;
815             guint32 together = color.toRGBA32(first.opacity);
817             SPGradientStop second = (*it)->vector.stops[1];
818             SPColor color2 = second.color;
820             Glib::ustring name( grad->getId() );
821             unsigned int r = SP_RGBA32_R_U(together);
822             unsigned int g = SP_RGBA32_G_U(together);
823             unsigned int b = SP_RGBA32_B_U(together);
824             ColorItem* item = new ColorItem( r, g, b, name );
826             gint width = PREVIEW_PIXBUF_WIDTH;
827             gint height = VBLOCK;
828             guchar* px = g_new( guchar, 3 * height * width );
829             nr_render_checkerboard_rgb( px, width, height, 3 * width, 0, 0 );
831             sp_gradient_render_vector_block_rgb( grad,
832                                                  px, width, height, 3 * width,
833                                                  0, width, TRUE );
835             previewMappings[item] = px;
837             tmpColors.push_back(item);
838             gradMappings[item] = grad;
839         }
840     }
843 void SwatchesPanel::handleGradientsChange(SPDocument *document)
845     SwatchPage *docPalette = (docPalettes.find(document) != docPalettes.end()) ? docPalettes[document] : 0;
846     if (docPalette) {
847         std::vector<ColorItem*> tmpColors;
848         std::map<ColorItem*, guchar*> tmpPrevs;
849         std::map<ColorItem*, SPGradient*> tmpGrads;
850         recalcSwatchContents(document, tmpColors, tmpPrevs, tmpGrads);
852         for (std::map<ColorItem*, guchar*>::iterator it = tmpPrevs.begin(); it != tmpPrevs.end(); ++it) {
853             it->first->setPixData(it->second, PREVIEW_PIXBUF_WIDTH, VBLOCK);
854         }
856         for (std::map<ColorItem*, SPGradient*>::iterator it = tmpGrads.begin(); it != tmpGrads.end(); ++it) {
857             it->first->setGradient(it->second);
858         }
860         docPalette->_colors.swap(tmpColors);
861         for (std::vector<ColorItem*>::iterator it = tmpColors.begin(); it != tmpColors.end(); ++it) {
862             delete *it;
863         }
866         // Figure out which SwatchesPanel instances are affected and update them.
868         for (std::map<SwatchesPanel*, SPDocument*>::iterator it = docPerPanel.begin(); it != docPerPanel.end(); ++it) {
869             if (it->second == document) {
870                 SwatchesPanel* swp = it->first;
871                 std::vector<SwatchPage*> pages = swp->_getSwatchSets();
872                 SwatchPage* curr = pages[swp->_currentIndex];
873                 if (curr == docPalette) {
874                     swp->_rebuild();
875                 }
876             }
877         }
878     }
881 void SwatchesPanel::handleDefsModified(SPDocument *document)
883     SwatchPage *docPalette = (docPalettes.find(document) != docPalettes.end()) ? docPalettes[document] : 0;
884     if (docPalette) {
885         std::vector<ColorItem*> tmpColors;
886         std::map<ColorItem*, guchar*> tmpPrevs;
887         std::map<ColorItem*, SPGradient*> tmpGrads;
888         recalcSwatchContents(document, tmpColors, tmpPrevs, tmpGrads);
890         int cap = std::min(docPalette->_colors.size(), tmpColors.size());
891         for (int i = 0; i < cap; i++) {
892             ColorItem* newColor = tmpColors[i];
893             ColorItem* oldColor = docPalette->_colors[i];
894             if ( (newColor->def.getType() != oldColor->def.getType()) ||
895                  (newColor->def.getR() != oldColor->def.getR()) ||
896                  (newColor->def.getG() != oldColor->def.getG()) ||
897                  (newColor->def.getB() != oldColor->def.getB()) ) {
898                 oldColor->def.setRGB(newColor->def.getR(), newColor->def.getG(), newColor->def.getB());
899             }
900             if (tmpGrads.find(newColor) != tmpGrads.end()) {
901                 oldColor->setGradient(tmpGrads[newColor]);
902             }
903             if ( tmpPrevs.find(newColor) != tmpPrevs.end() ) {
904                 oldColor->setPixData(tmpPrevs[newColor], PREVIEW_PIXBUF_WIDTH, VBLOCK);
905             }
906         }
907     }
910 std::vector<SwatchPage*> SwatchesPanel::_getSwatchSets() const
912     std::vector<SwatchPage*> tmp;
913     if (docPalettes.find(_currentDocument) != docPalettes.end()) {
914         tmp.push_back(docPalettes[_currentDocument]);
915     }
917     tmp.insert(tmp.end(), possible.begin(), possible.end());
919     return tmp;
922 void SwatchesPanel::_updateFromSelection()
924     SwatchPage *docPalette = (docPalettes.find(_currentDocument) != docPalettes.end()) ? docPalettes[_currentDocument] : 0;
925     if ( docPalette ) {
926         Glib::ustring fillId;
927         Glib::ustring strokeId;
929         SPStyle *tmpStyle = sp_style_new( sp_desktop_document(_currentDesktop) );
930         int result = sp_desktop_query_style( _currentDesktop, tmpStyle, QUERY_STYLE_PROPERTY_FILL );
931         switch (result) {
932             case QUERY_STYLE_SINGLE:
933             case QUERY_STYLE_MULTIPLE_AVERAGED:
934             case QUERY_STYLE_MULTIPLE_SAME:
935             {
936                 if (tmpStyle->fill.set && tmpStyle->fill.isPaintserver()) {
937                     SPPaintServer* server = tmpStyle->getFillPaintServer();
938                     if ( SP_IS_GRADIENT(server) ) {
939                         SPGradient* target = 0;
940                         SPGradient* grad = SP_GRADIENT(server);
941                         if (grad->repr->attribute("osb:paint")) {
942                             target = grad;
943                         } else if ( grad->ref ) {
944                             SPGradient *tmp = grad->ref->getObject();
945                             if ( tmp && tmp->repr->attribute("osb:paint") ) {
946                                 target = tmp;
947                             }
948                         }
949                         if ( target ) {
950                             gchar const* id = target->repr->attribute("id");
951                             if ( id ) {
952                                 fillId = id;
953                             }
954                         }
955                     }
956                 }
957                 break;
958             }
959         }
961         result = sp_desktop_query_style( _currentDesktop, tmpStyle, QUERY_STYLE_PROPERTY_STROKE );
962         switch (result) {
963             case QUERY_STYLE_SINGLE:
964             case QUERY_STYLE_MULTIPLE_AVERAGED:
965             case QUERY_STYLE_MULTIPLE_SAME:
966             {
967                 if (tmpStyle->stroke.set && tmpStyle->stroke.isPaintserver()) {
968                     SPPaintServer* server = tmpStyle->getStrokePaintServer();
969                     if ( SP_IS_GRADIENT(server) ) {
970                         SPGradient* target = 0;
971                         SPGradient* grad = SP_GRADIENT(server);
972                         if (grad->repr->attribute("osb:paint")) {
973                             target = grad;
974                         } else if ( grad->ref ) {
975                             SPGradient *tmp = grad->ref->getObject();
976                             if ( tmp && tmp->repr->attribute("osb:paint") ) {
977                                 target = tmp;
978                             }
979                         }
980                         if ( target ) {
981                             gchar const* id = target->repr->attribute("id");
982                             if ( id ) {
983                                 strokeId = id;
984                             }
985                         }
986                     }
987                 }
988                 break;
989             }
990         }
991         sp_style_unref(tmpStyle);
993         for ( std::vector<ColorItem*>::iterator it = docPalette->_colors.begin(); it != docPalette->_colors.end(); ++it ) {
994             ColorItem* item = *it;
995             bool isFill = (fillId == item->def.descr);
996             bool isStroke = (strokeId == item->def.descr);
997             item->setState( isFill, isStroke );
998         }
999     }
1002 void SwatchesPanel::_handleAction( int setId, int itemId )
1004     switch( setId ) {
1005         case 3:
1006         {
1007             std::vector<SwatchPage*> pages = _getSwatchSets();
1008             if ( itemId >= 0 && itemId < static_cast<int>(pages.size()) ) {
1009                 _currentIndex = itemId;
1011                 if ( !_prefs_path.empty() ) {
1012                     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1013                     prefs->setString(_prefs_path + "/palette", pages[_currentIndex]->_name);
1014                 }
1016                 _rebuild();
1017             }
1018         }
1019         break;
1020     }
1023 void SwatchesPanel::_rebuild()
1025     std::vector<SwatchPage*> pages = _getSwatchSets();
1026     SwatchPage* curr = pages[_currentIndex];
1027     _holder->clear();
1029     if ( curr->_prefWidth > 0 ) {
1030         _holder->setColumnPref( curr->_prefWidth );
1031     }
1032     _holder->freezeUpdates();
1033     // TODO restore once 'clear' works _holder->addPreview(_clear);
1034     _holder->addPreview(_remove);
1035     for ( std::vector<ColorItem*>::iterator it = curr->_colors.begin(); it != curr->_colors.end(); it++ ) {
1036         _holder->addPreview(*it);
1037     }
1038     _holder->thawUpdates();
1044 } //namespace Dialogs
1045 } //namespace UI
1046 } //namespace Inkscape
1049 /*
1050   Local Variables:
1051   mode:c++
1052   c-file-style:"stroustrup"
1053   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1054   indent-tabs-mode:nil
1055   fill-column:99
1056   End:
1057 */
1058 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :