Code

7da1b5694fa0bd1927674e3e68a1f3faf4ecc2d7
[inkscape.git] / src / dialogs / swatches.cpp
1 /*
2  * A simple panel for color swatches
3  *
4  * Authors:
5  *   Jon A. Cruz
6  *
7  * Copyright (C) 2005 Jon A. Cruz
8  *
9  * Released under GNU GPL, read the file 'COPYING' for more information
10  */
11 #ifdef HAVE_CONFIG_H
12 # include <config.h>
13 #endif
15 #include <errno.h>
17 #include <gtk/gtkdialog.h> //for GTK_RESPONSE* types
18 #include <gtk/gtkdnd.h>
20 #include <glibmm/i18n.h>
21 #include "inkscape.h"
22 #include "document.h"
23 #include "desktop-handles.h"
24 #include "extension/db.h"
25 #include "inkscape.h"
26 #include "svg/svg.h"
27 #include "desktop-style.h"
28 #include "io/sys.h"
29 #include "path-prefix.h"
30 #include "swatches.h"
32 #include "eek-preview.h"
34 namespace Inkscape {
35 namespace UI {
36 namespace Dialogs {
38 SwatchesPanel* SwatchesPanel::instance = 0;
41 ColorItem::ColorItem( unsigned int r, unsigned int g, unsigned int b, Glib::ustring& name ) :
42     _r(r),
43     _g(g),
44     _b(b),
45     _name(name)
46 {
47 }
49 ColorItem::~ColorItem()
50 {
51 }
53 ColorItem::ColorItem(ColorItem const &other) :
54     Inkscape::UI::Previewable()
55 {
56     if ( this != &other ) {
57         *this = other;
58     }
59 }
61 ColorItem &ColorItem::operator=(ColorItem const &other)
62 {
63     if ( this != &other ) {
64         _r = other._r;
65         _g = other._g;
66         _b = other._b;
67         _name = other._name;
68     }
69     return *this;
70 }
72 typedef enum {
73     XCOLOR_DATA = 0,
74     TEXT_DATA
75 } colorFlavorType;
77 static const GtkTargetEntry color_entries[] = {
78     {"application/x-color", 0, XCOLOR_DATA},
79     {"text/plain", 0, TEXT_DATA},
80 };
82 static void dragGetColorData( GtkWidget *widget,
83                               GdkDragContext *drag_context,
84                               GtkSelectionData *data,
85                               guint info,
86                               guint time,
87                               gpointer user_data)
88 {
89     static GdkAtom typeXColor = gdk_atom_intern("application/x-color", FALSE);
90     static GdkAtom typeText = gdk_atom_intern("text/plain", FALSE);
92     ColorItem* item = reinterpret_cast<ColorItem*>(user_data);
93     if ( info == 1 ) {
94         gchar* tmp = g_strdup_printf("#%02x%02x%02x", item->_r, item->_g, item->_b);
96         gtk_selection_data_set( data,
97                                 typeText,
98                                 8, // format
99                                 (guchar*)tmp,
100                                 strlen((const char*)tmp) + 1);
101         g_free(tmp);
102         tmp = 0;
103     } else {
104         guchar tmp[8];
105         tmp[0] = item->_r;
106         tmp[1] = item->_r;
107         tmp[2] = item->_g;
108         tmp[3] = item->_g;
109         tmp[4] = item->_b;
110         tmp[5] = item->_b;
111         tmp[6] = 0x0ff;
112         tmp[7] = 0x0ff;
113         gtk_selection_data_set( data,
114                                 typeXColor,
115                                 8, // format
116                                 tmp,
117                                 (3+1) * 2);
118     }
121 //"drag-drop"
122 gboolean dragDropColorData( GtkWidget *widget,
123                             GdkDragContext *drag_context,
124                             gint x,
125                             gint y,
126                             guint time,
127                             gpointer user_data)
129 // TODO finish
130     return TRUE;
133 static void bouncy( GtkWidget* widget, gpointer callback_data ) {
134     ColorItem* item = reinterpret_cast<ColorItem*>(callback_data);
135     if ( item ) {
136         item->buttonClicked(false);
137     }
140 static void bouncy2( GtkWidget* widget, gint arg1, gpointer callback_data ) {
141     ColorItem* item = reinterpret_cast<ColorItem*>(callback_data);
142     if ( item ) {
143         item->buttonClicked(true);
144     }
147 Gtk::Widget* ColorItem::getPreview(PreviewStyle style, ViewType view, Gtk::BuiltinIconSize size)
149     Gtk::Widget* widget = 0;
150     if ( style == PREVIEW_STYLE_BLURB ) {
151         Gtk::Label *lbl = new Gtk::Label(_name);
152         lbl->set_alignment(Gtk::ALIGN_LEFT, Gtk::ALIGN_CENTER);
153         widget = lbl;
154     } else {
155         Glib::ustring blank("          ");
156         if ( size == Gtk::ICON_SIZE_MENU ) {
157             blank = " ";
158         }
160         GtkWidget* eekWidget = eek_preview_new();
161         EekPreview * preview = EEK_PREVIEW(eekWidget);
162         Gtk::Widget* newBlot = Glib::wrap(eekWidget);
164         eek_preview_set_color( preview, (_r << 8)|_r, (_g << 8)|_g, (_b << 8)|_b);
166         eek_preview_set_details( preview, (::PreviewStyle)style, (::ViewType)view, (::GtkIconSize)size );
168         GValue val = {0, {{0}, {0}}};
169         g_value_init( &val, G_TYPE_BOOLEAN );
170         g_value_set_boolean( &val, FALSE );
171         g_object_set_property( G_OBJECT(preview), "focus-on-click", &val );
173 /*
174         Gtk::Button *btn = new Gtk::Button(blank);
175         Gdk::Color color;
176         color.set_rgb((_r << 8)|_r, (_g << 8)|_g, (_b << 8)|_b);
177         btn->modify_bg(Gtk::STATE_NORMAL, color);
178         btn->modify_bg(Gtk::STATE_ACTIVE, color);
179         btn->modify_bg(Gtk::STATE_PRELIGHT, color);
180         btn->modify_bg(Gtk::STATE_SELECTED, color);
182         Gtk::Widget* newBlot = btn;
183 */
185         tips.set_tip((*newBlot), _name);
187 /*
188         newBlot->signal_clicked().connect( sigc::mem_fun(*this, &ColorItem::buttonClicked) );
190         sigc::signal<void> type_signal_something;
191 */
192         g_signal_connect( G_OBJECT(newBlot->gobj()),
193                           "clicked",
194                           G_CALLBACK(bouncy),
195                           this);
197         g_signal_connect( G_OBJECT(newBlot->gobj()),
198                           "alt-clicked",
199                           G_CALLBACK(bouncy2),
200                           this);
202         gtk_drag_source_set( GTK_WIDGET(newBlot->gobj()),
203                              GDK_BUTTON1_MASK,
204                              color_entries,
205                              G_N_ELEMENTS(color_entries),
206                              GdkDragAction(GDK_ACTION_MOVE | GDK_ACTION_COPY) );
208         g_signal_connect( G_OBJECT(newBlot->gobj()),
209                           "drag-data-get",
210                           G_CALLBACK(dragGetColorData),
211                           this);
213         g_signal_connect( G_OBJECT(newBlot->gobj()),
214                           "drag-drop",
215                           G_CALLBACK(dragDropColorData),
216                           this);
218         widget = newBlot;
219     }
221     return widget;
224 void ColorItem::buttonClicked(bool secondary)
226     SPDesktop *desktop = SP_ACTIVE_DESKTOP;
227     if (desktop) {
228         char const * attrName = secondary ? "stroke" : "fill";
229         guint32 rgba = (_r << 24) | (_g << 16) | (_b << 8) | 0xff;
230         gchar c[64];
231         sp_svg_write_color(c, 64, rgba);
233         SPCSSAttr *css = sp_repr_css_attr_new();
234         sp_repr_css_set_property( css, attrName, c );
235         sp_desktop_set_style(desktop, css);
237         sp_repr_css_attr_unref(css);
238         sp_document_done (SP_DT_DOCUMENT (desktop));
239     }
245 static char* trim( char* str ) {
246     char* ret = str;
247     while ( *str && (*str == ' ' || *str == '\t') ) {
248         str++;
249     }
250     ret = str;
251     while ( *str ) {
252         str++;
253     }
254     str--;
255     while ( str > ret && ( *str == ' ' || *str == '\t' ) || *str == '\r' || *str == '\n' ) {
256         *str-- = 0;
257     }
258     return ret;
261 void skipWhitespace( char*& str ) {
262     while ( *str == ' ' || *str == '\t' ) {
263         str++;
264     }
267 bool parseNum( char*& str, int& val ) {
268     val = 0;
269     while ( '0' <= *str && *str <= '9' ) {
270         val = val * 10 + (*str - '0');
271         str++;
272     }
273     bool retval = !(*str == 0 || *str == ' ' || *str == '\t' || *str == '\r' || *str == '\n');
274     return retval;
278 class JustForNow
280 public:
281     JustForNow() : _prefWidth(0) {}
283     Glib::ustring _name;
284     int _prefWidth;
285     std::vector<ColorItem*> _colors;
286 };
288 static std::vector<JustForNow*> possible;
290 static void loadPaletteFile( gchar const *filename )
292     char block[1024];
293     FILE *f = Inkscape::IO::fopen_utf8name( filename, "r" );
294     if ( f ) {
295         char* result = fgets( block, sizeof(block), f );
296         if ( result ) {
297             if ( strncmp( "GIMP Palette", block, 12 ) == 0 ) {
298                 bool inHeader = true;
299                 bool hasErr = false;
301                 JustForNow *onceMore = new JustForNow();
303                 do {
304                     result = fgets( block, sizeof(block), f );
305                     block[sizeof(block) - 1] = 0;
306                     if ( result ) {
307                         if ( block[0] == '#' ) {
308                             // ignore comment
309                         } else {
310                             char *ptr = block;
311                             // very simple check for header versus entry
312                             while ( *ptr == ' ' || *ptr == '\t' ) {
313                                 ptr++;
314                             }
315                             if ( *ptr == 0 ) {
316                                 // blank line. skip it.
317                             } else if ( '0' <= *ptr && *ptr <= '9' ) {
318                                 // should be an entry link
319                                 inHeader = false;
320                                 ptr = block;
321                                 Glib::ustring name("");
322                                 int r = 0;
323                                 int g = 0;
324                                 int b = 0;
325                                 skipWhitespace(ptr);
326                                 if ( *ptr ) {
327                                     hasErr = parseNum(ptr, r);
328                                     if ( !hasErr ) {
329                                         skipWhitespace(ptr);
330                                         hasErr = parseNum(ptr, g);
331                                     }
332                                     if ( !hasErr ) {
333                                         skipWhitespace(ptr);
334                                         hasErr = parseNum(ptr, b);
335                                     }
336                                     if ( !hasErr && *ptr ) {
337                                         char* n = trim(ptr);
338                                         if (n != NULL) {
339                                             name = n;
340                                         }
341                                     }
342                                     if ( !hasErr ) {
343                                         // Add the entry now
344                                         Glib::ustring nameStr(name);
345                                         ColorItem* item = new ColorItem( r, g, b, nameStr );
346                                         onceMore->_colors.push_back(item);
347                                     }
348                                 } else {
349                                     hasErr = true;
350                                 }
351                             } else {
352                                 if ( !inHeader ) {
353                                     // Hmmm... probably bad. Not quite the format we want?
354                                     hasErr = true;
355                                 } else {
356                                     char* sep = strchr(result, ':');
357                                     if ( sep ) {
358                                         *sep = 0;
359                                         char* val = trim(sep + 1);
360                                         char* name = trim(result);
361                                         if ( *name ) {
362                                             if ( strcmp( "Name", name ) == 0 )
363                                             {
364                                                 onceMore->_name = val;
365                                             }
366                                             else if ( strcmp( "Columns", name ) == 0 )
367                                             {
368                                                 gchar* endPtr = 0;
369                                                 guint64 numVal = g_ascii_strtoull( val, &endPtr, 10 );
370                                                 if ( (numVal == G_MAXUINT64) && (ERANGE == errno) ) {
371                                                     // overflow
372                                                 } else if ( (numVal == 0) && (endPtr == val) ) {
373                                                     // failed conversion
374                                                 } else {
375                                                     onceMore->_prefWidth = numVal;
376                                                 }
377                                             }
378                                         } else {
379                                             // error
380                                             hasErr = true;
381                                         }
382                                     } else {
383                                         // error
384                                         hasErr = true;
385                                     }
386                                 }
387                             }
388                         }
389                     }
390                 } while ( result && !hasErr );
391                 if ( !hasErr ) {
392                     possible.push_back(onceMore);
393                 } else {
394                     delete onceMore;
395                 }
396             }
397         }
399         fclose(f);
400     }
403 static void loadEmUp()
405     static bool beenHere = false;
406     if ( !beenHere ) {
407         beenHere = true;
409         std::list<gchar *> sources;
410         sources.push_back( profile_path("palettes") );
411         sources.push_back( g_strdup(INKSCAPE_PALETTESDIR) );
413         // Use this loop to iterate through a list of possible document locations.
414         while (!sources.empty()) {
415             gchar *dirname = sources.front();
417             if ( Inkscape::IO::file_test( dirname, (GFileTest)(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR) ) ) {
418                 GError *err = 0;
419                 GDir *directory = g_dir_open(dirname, 0, &err);
420                 if (!directory) {
421                     gchar *safeDir = Inkscape::IO::sanitizeString(dirname);
422                     g_warning(_("Palettes directory (%s) is unavailable."), safeDir);
423                     g_free(safeDir);
424                 } else {
425                     gchar *filename = 0;
426                     while ((filename = (gchar *)g_dir_read_name(directory)) != NULL) {
427                         gchar* full = g_build_filename(dirname, filename, NULL);
428                         if ( !Inkscape::IO::file_test( full, (GFileTest)(G_FILE_TEST_IS_DIR ) ) ) {
429                             loadPaletteFile(full);
430                         }
431                         g_free(full);
432                     }
433                     g_dir_close(directory);
434                 }
435             }
437             // toss the dirname
438             g_free(dirname);
439             sources.pop_front();
440         }
441     }
452 SwatchesPanel& SwatchesPanel::getInstance()
454     if ( !instance ) {
455         instance = new SwatchesPanel();
456     }
458     return *instance;
463 /**
464  * Constructor
465  */
466 SwatchesPanel::SwatchesPanel() :
467     Inkscape::UI::Widget::Panel ("dialogs.swatches"),
468     _holder(0)
470     _holder = new PreviewHolder();
471     loadEmUp();
473     if ( !possible.empty() ) {
474         JustForNow* first = possible.front();
475         if ( first->_prefWidth > 0 ) {
476             _holder->setColumnPref( first->_prefWidth );
477         }
478         _holder->freezeUpdates();
479         for ( std::vector<ColorItem*>::iterator it = first->_colors.begin(); it != first->_colors.end(); it++ ) {
480             _holder->addPreview(*it);
481         }
482         _holder->thawUpdates();
484         Gtk::RadioMenuItem::Group groupOne;
485         int i = 0;
486         for ( std::vector<JustForNow*>::iterator it = possible.begin(); it != possible.end(); it++ ) {
487             JustForNow* curr = *it;
488             Gtk::RadioMenuItem* single = manage(new Gtk::RadioMenuItem(groupOne, curr->_name));
489             _regItem( single, 3, i );
490             i++;
491         }
493     }
496     _getContents()->pack_start(*_holder, Gtk::PACK_EXPAND_WIDGET);
497     _setTargetFillable(_holder);
499     show_all_children();
501     restorePanelPrefs();
504 SwatchesPanel::~SwatchesPanel()
508 void SwatchesPanel::setOrientation( Gtk::AnchorType how )
510     // Must call the parent class or bad things might happen
511     Inkscape::UI::Widget::Panel::setOrientation( how );
513     if ( _holder )
514     {
515         _holder->setOrientation( Gtk::ANCHOR_SOUTH );
516     }
519 void SwatchesPanel::_handleAction( int setId, int itemId )
521     switch( setId ) {
522         case 3:
523         {
524             if ( itemId >= 0 && itemId < static_cast<int>(possible.size()) ) {
525                 _holder->clear();
526                 JustForNow* curr = possible[itemId];
527                 if ( curr->_prefWidth > 0 ) {
528                     _holder->setColumnPref( curr->_prefWidth );
529                 }
530                 _holder->freezeUpdates();
531                 for ( std::vector<ColorItem*>::iterator it = curr->_colors.begin(); it != curr->_colors.end(); it++ ) {
532                     _holder->addPreview(*it);
533                 }
534                 _holder->thawUpdates();
535             }
536         }
537         break;
538     }
541 } //namespace Dialogs
542 } //namespace UI
543 } //namespace Inkscape
546 /*
547   Local Variables:
548   mode:c++
549   c-file-style:"stroustrup"
550   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
551   indent-tabs-mode:nil
552   fill-column:99
553   End:
554 */
555 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :