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 <gdkmm/pixbuf.h>
22 #include "inkscape.h"
23 #include "document.h"
24 #include "desktop-handles.h"
25 #include "extension/db.h"
26 #include "inkscape.h"
27 #include "svg/svg-color.h"
28 #include "desktop-style.h"
29 #include "io/sys.h"
30 #include "path-prefix.h"
31 #include "swatches.h"
33 #include "eek-preview.h"
35 namespace Inkscape {
36 namespace UI {
37 namespace Dialogs {
39 SwatchesPanel* SwatchesPanel::instance = 0;
42 ColorItem::ColorItem( unsigned int r, unsigned int g, unsigned int b, Glib::ustring& name ) :
43 _r(r),
44 _g(g),
45 _b(b),
46 _name(name)
47 {
48 }
50 ColorItem::~ColorItem()
51 {
52 }
54 ColorItem::ColorItem(ColorItem const &other) :
55 Inkscape::UI::Previewable()
56 {
57 if ( this != &other ) {
58 *this = other;
59 }
60 }
62 ColorItem &ColorItem::operator=(ColorItem const &other)
63 {
64 if ( this != &other ) {
65 _r = other._r;
66 _g = other._g;
67 _b = other._b;
68 _name = other._name;
69 }
70 return *this;
71 }
73 typedef enum {
74 XCOLOR_DATA = 0,
75 TEXT_DATA
76 } colorFlavorType;
78 static const GtkTargetEntry color_entries[] = {
79 {"application/x-color", 0, XCOLOR_DATA},
80 {"text/plain", 0, TEXT_DATA},
81 };
83 static void dragGetColorData( GtkWidget *widget,
84 GdkDragContext *drag_context,
85 GtkSelectionData *data,
86 guint info,
87 guint time,
88 gpointer user_data)
89 {
90 static GdkAtom typeXColor = gdk_atom_intern("application/x-color", FALSE);
91 static GdkAtom typeText = gdk_atom_intern("text/plain", FALSE);
93 ColorItem* item = reinterpret_cast<ColorItem*>(user_data);
94 if ( info == 1 ) {
95 gchar* tmp = g_strdup_printf("#%02x%02x%02x", item->_r, item->_g, item->_b);
97 gtk_selection_data_set( data,
98 typeText,
99 8, // format
100 (guchar*)tmp,
101 strlen((const char*)tmp) + 1);
102 g_free(tmp);
103 tmp = 0;
104 } else {
105 guint16 tmp[4];
106 tmp[0] = (item->_r << 8) | item->_r;
107 tmp[1] = (item->_g << 8) | item->_g;
108 tmp[2] = (item->_b << 8) | item->_b;
109 tmp[3] = 0xffff;
110 gtk_selection_data_set( data,
111 typeXColor,
112 16, // format
113 reinterpret_cast<const guchar*>(tmp),
114 (3+1) * 2);
115 }
116 }
118 static void dragBegin( GtkWidget *widget, GdkDragContext* dc, gpointer data )
119 {
120 ColorItem* item = reinterpret_cast<ColorItem*>(data);
121 if ( item )
122 {
123 Glib::RefPtr<Gdk::Pixbuf> thumb = Gdk::Pixbuf::create( Gdk::COLORSPACE_RGB, false, 8, 32, 24 );
124 guint32 fillWith = (0xff000000 & (item->_r << 24))
125 | (0x00ff0000 & (item->_g << 16))
126 | (0x0000ff00 & (item->_b << 8));
127 thumb->fill( fillWith );
128 gtk_drag_set_icon_pixbuf( dc, thumb->gobj(), 0, 0 );
129 }
131 }
133 //"drag-drop"
134 gboolean dragDropColorData( GtkWidget *widget,
135 GdkDragContext *drag_context,
136 gint x,
137 gint y,
138 guint time,
139 gpointer user_data)
140 {
141 // TODO finish
142 return TRUE;
143 }
145 static void bouncy( GtkWidget* widget, gpointer callback_data ) {
146 ColorItem* item = reinterpret_cast<ColorItem*>(callback_data);
147 if ( item ) {
148 item->buttonClicked(false);
149 }
150 }
152 static void bouncy2( GtkWidget* widget, gint arg1, gpointer callback_data ) {
153 ColorItem* item = reinterpret_cast<ColorItem*>(callback_data);
154 if ( item ) {
155 item->buttonClicked(true);
156 }
157 }
159 Gtk::Widget* ColorItem::getPreview(PreviewStyle style, ViewType view, Gtk::BuiltinIconSize size)
160 {
161 Gtk::Widget* widget = 0;
162 if ( style == PREVIEW_STYLE_BLURB ) {
163 Gtk::Label *lbl = new Gtk::Label(_name);
164 lbl->set_alignment(Gtk::ALIGN_LEFT, Gtk::ALIGN_CENTER);
165 widget = lbl;
166 } else {
167 Glib::ustring blank(" ");
168 if ( size == Gtk::ICON_SIZE_MENU ) {
169 blank = " ";
170 }
172 GtkWidget* eekWidget = eek_preview_new();
173 EekPreview * preview = EEK_PREVIEW(eekWidget);
174 Gtk::Widget* newBlot = Glib::wrap(eekWidget);
176 eek_preview_set_color( preview, (_r << 8)|_r, (_g << 8)|_g, (_b << 8)|_b);
178 eek_preview_set_details( preview, (::PreviewStyle)style, (::ViewType)view, (::GtkIconSize)size );
180 GValue val = {0, {{0}, {0}}};
181 g_value_init( &val, G_TYPE_BOOLEAN );
182 g_value_set_boolean( &val, FALSE );
183 g_object_set_property( G_OBJECT(preview), "focus-on-click", &val );
185 /*
186 Gtk::Button *btn = new Gtk::Button(blank);
187 Gdk::Color color;
188 color.set_rgb((_r << 8)|_r, (_g << 8)|_g, (_b << 8)|_b);
189 btn->modify_bg(Gtk::STATE_NORMAL, color);
190 btn->modify_bg(Gtk::STATE_ACTIVE, color);
191 btn->modify_bg(Gtk::STATE_PRELIGHT, color);
192 btn->modify_bg(Gtk::STATE_SELECTED, color);
194 Gtk::Widget* newBlot = btn;
195 */
197 tips.set_tip((*newBlot), _name);
199 /*
200 newBlot->signal_clicked().connect( sigc::mem_fun(*this, &ColorItem::buttonClicked) );
202 sigc::signal<void> type_signal_something;
203 */
204 g_signal_connect( G_OBJECT(newBlot->gobj()),
205 "clicked",
206 G_CALLBACK(bouncy),
207 this);
209 g_signal_connect( G_OBJECT(newBlot->gobj()),
210 "alt-clicked",
211 G_CALLBACK(bouncy2),
212 this);
214 gtk_drag_source_set( GTK_WIDGET(newBlot->gobj()),
215 GDK_BUTTON1_MASK,
216 color_entries,
217 G_N_ELEMENTS(color_entries),
218 GdkDragAction(GDK_ACTION_MOVE | GDK_ACTION_COPY) );
220 g_signal_connect( G_OBJECT(newBlot->gobj()),
221 "drag-data-get",
222 G_CALLBACK(dragGetColorData),
223 this);
225 g_signal_connect( G_OBJECT(newBlot->gobj()),
226 "drag-begin",
227 G_CALLBACK(dragBegin),
228 this );
230 g_signal_connect( G_OBJECT(newBlot->gobj()),
231 "drag-drop",
232 G_CALLBACK(dragDropColorData),
233 this);
235 widget = newBlot;
236 }
238 return widget;
239 }
241 void ColorItem::buttonClicked(bool secondary)
242 {
243 SPDesktop *desktop = SP_ACTIVE_DESKTOP;
244 if (desktop) {
245 char const * attrName = secondary ? "stroke" : "fill";
246 guint32 rgba = (_r << 24) | (_g << 16) | (_b << 8) | 0xff;
247 gchar c[64];
248 sp_svg_write_color(c, 64, rgba);
250 SPCSSAttr *css = sp_repr_css_attr_new();
251 sp_repr_css_set_property( css, attrName, c );
252 sp_desktop_set_style(desktop, css);
254 sp_repr_css_attr_unref(css);
255 sp_document_done (SP_DT_DOCUMENT (desktop));
256 }
257 }
262 static char* trim( char* str ) {
263 char* ret = str;
264 while ( *str && (*str == ' ' || *str == '\t') ) {
265 str++;
266 }
267 ret = str;
268 while ( *str ) {
269 str++;
270 }
271 str--;
272 while ( str > ret && ( *str == ' ' || *str == '\t' ) || *str == '\r' || *str == '\n' ) {
273 *str-- = 0;
274 }
275 return ret;
276 }
278 void skipWhitespace( char*& str ) {
279 while ( *str == ' ' || *str == '\t' ) {
280 str++;
281 }
282 }
284 bool parseNum( char*& str, int& val ) {
285 val = 0;
286 while ( '0' <= *str && *str <= '9' ) {
287 val = val * 10 + (*str - '0');
288 str++;
289 }
290 bool retval = !(*str == 0 || *str == ' ' || *str == '\t' || *str == '\r' || *str == '\n');
291 return retval;
292 }
295 class JustForNow
296 {
297 public:
298 JustForNow() : _prefWidth(0) {}
300 Glib::ustring _name;
301 int _prefWidth;
302 std::vector<ColorItem*> _colors;
303 };
305 static std::vector<JustForNow*> possible;
307 static void loadPaletteFile( gchar const *filename )
308 {
309 char block[1024];
310 FILE *f = Inkscape::IO::fopen_utf8name( filename, "r" );
311 if ( f ) {
312 char* result = fgets( block, sizeof(block), f );
313 if ( result ) {
314 if ( strncmp( "GIMP Palette", block, 12 ) == 0 ) {
315 bool inHeader = true;
316 bool hasErr = false;
318 JustForNow *onceMore = new JustForNow();
320 do {
321 result = fgets( block, sizeof(block), f );
322 block[sizeof(block) - 1] = 0;
323 if ( result ) {
324 if ( block[0] == '#' ) {
325 // ignore comment
326 } else {
327 char *ptr = block;
328 // very simple check for header versus entry
329 while ( *ptr == ' ' || *ptr == '\t' ) {
330 ptr++;
331 }
332 if ( *ptr == 0 ) {
333 // blank line. skip it.
334 } else if ( '0' <= *ptr && *ptr <= '9' ) {
335 // should be an entry link
336 inHeader = false;
337 ptr = block;
338 Glib::ustring name("");
339 int r = 0;
340 int g = 0;
341 int b = 0;
342 skipWhitespace(ptr);
343 if ( *ptr ) {
344 hasErr = parseNum(ptr, r);
345 if ( !hasErr ) {
346 skipWhitespace(ptr);
347 hasErr = parseNum(ptr, g);
348 }
349 if ( !hasErr ) {
350 skipWhitespace(ptr);
351 hasErr = parseNum(ptr, b);
352 }
353 if ( !hasErr && *ptr ) {
354 char* n = trim(ptr);
355 if (n != NULL) {
356 name = n;
357 }
358 }
359 if ( !hasErr ) {
360 // Add the entry now
361 Glib::ustring nameStr(name);
362 ColorItem* item = new ColorItem( r, g, b, nameStr );
363 onceMore->_colors.push_back(item);
364 }
365 } else {
366 hasErr = true;
367 }
368 } else {
369 if ( !inHeader ) {
370 // Hmmm... probably bad. Not quite the format we want?
371 hasErr = true;
372 } else {
373 char* sep = strchr(result, ':');
374 if ( sep ) {
375 *sep = 0;
376 char* val = trim(sep + 1);
377 char* name = trim(result);
378 if ( *name ) {
379 if ( strcmp( "Name", name ) == 0 )
380 {
381 onceMore->_name = val;
382 }
383 else if ( strcmp( "Columns", name ) == 0 )
384 {
385 gchar* endPtr = 0;
386 guint64 numVal = g_ascii_strtoull( val, &endPtr, 10 );
387 if ( (numVal == G_MAXUINT64) && (ERANGE == errno) ) {
388 // overflow
389 } else if ( (numVal == 0) && (endPtr == val) ) {
390 // failed conversion
391 } else {
392 onceMore->_prefWidth = numVal;
393 }
394 }
395 } else {
396 // error
397 hasErr = true;
398 }
399 } else {
400 // error
401 hasErr = true;
402 }
403 }
404 }
405 }
406 }
407 } while ( result && !hasErr );
408 if ( !hasErr ) {
409 possible.push_back(onceMore);
410 } else {
411 delete onceMore;
412 }
413 }
414 }
416 fclose(f);
417 }
418 }
420 static void loadEmUp()
421 {
422 static bool beenHere = false;
423 if ( !beenHere ) {
424 beenHere = true;
426 std::list<gchar *> sources;
427 sources.push_back( profile_path("palettes") );
428 sources.push_back( g_strdup(INKSCAPE_PALETTESDIR) );
430 // Use this loop to iterate through a list of possible document locations.
431 while (!sources.empty()) {
432 gchar *dirname = sources.front();
434 if ( Inkscape::IO::file_test( dirname, (GFileTest)(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR) ) ) {
435 GError *err = 0;
436 GDir *directory = g_dir_open(dirname, 0, &err);
437 if (!directory) {
438 gchar *safeDir = Inkscape::IO::sanitizeString(dirname);
439 g_warning(_("Palettes directory (%s) is unavailable."), safeDir);
440 g_free(safeDir);
441 } else {
442 gchar *filename = 0;
443 while ((filename = (gchar *)g_dir_read_name(directory)) != NULL) {
444 gchar* full = g_build_filename(dirname, filename, NULL);
445 if ( !Inkscape::IO::file_test( full, (GFileTest)(G_FILE_TEST_IS_DIR ) ) ) {
446 loadPaletteFile(full);
447 }
448 g_free(full);
449 }
450 g_dir_close(directory);
451 }
452 }
454 // toss the dirname
455 g_free(dirname);
456 sources.pop_front();
457 }
458 }
459 }
469 SwatchesPanel& SwatchesPanel::getInstance()
470 {
471 if ( !instance ) {
472 instance = new SwatchesPanel();
473 }
475 return *instance;
476 }
480 /**
481 * Constructor
482 */
483 SwatchesPanel::SwatchesPanel() :
484 Inkscape::UI::Widget::Panel ("dialogs.swatches"),
485 _holder(0)
486 {
487 _holder = new PreviewHolder();
488 loadEmUp();
490 if ( !possible.empty() ) {
491 JustForNow* first = possible.front();
492 if ( first->_prefWidth > 0 ) {
493 _holder->setColumnPref( first->_prefWidth );
494 }
495 _holder->freezeUpdates();
496 for ( std::vector<ColorItem*>::iterator it = first->_colors.begin(); it != first->_colors.end(); it++ ) {
497 _holder->addPreview(*it);
498 }
499 _holder->thawUpdates();
501 Gtk::RadioMenuItem::Group groupOne;
502 int i = 0;
503 for ( std::vector<JustForNow*>::iterator it = possible.begin(); it != possible.end(); it++ ) {
504 JustForNow* curr = *it;
505 Gtk::RadioMenuItem* single = manage(new Gtk::RadioMenuItem(groupOne, curr->_name));
506 _regItem( single, 3, i );
507 i++;
508 }
510 }
513 _getContents()->pack_start(*_holder, Gtk::PACK_EXPAND_WIDGET);
514 _setTargetFillable(_holder);
516 show_all_children();
518 restorePanelPrefs();
519 }
521 SwatchesPanel::~SwatchesPanel()
522 {
523 }
525 void SwatchesPanel::setOrientation( Gtk::AnchorType how )
526 {
527 // Must call the parent class or bad things might happen
528 Inkscape::UI::Widget::Panel::setOrientation( how );
530 if ( _holder )
531 {
532 _holder->setOrientation( Gtk::ANCHOR_SOUTH );
533 }
534 }
536 void SwatchesPanel::_handleAction( int setId, int itemId )
537 {
538 switch( setId ) {
539 case 3:
540 {
541 if ( itemId >= 0 && itemId < static_cast<int>(possible.size()) ) {
542 _holder->clear();
543 JustForNow* curr = possible[itemId];
544 if ( curr->_prefWidth > 0 ) {
545 _holder->setColumnPref( curr->_prefWidth );
546 }
547 _holder->freezeUpdates();
548 for ( std::vector<ColorItem*>::iterator it = curr->_colors.begin(); it != curr->_colors.end(); it++ ) {
549 _holder->addPreview(*it);
550 }
551 _holder->thawUpdates();
552 }
553 }
554 break;
555 }
556 }
558 } //namespace Dialogs
559 } //namespace UI
560 } //namespace Inkscape
563 /*
564 Local Variables:
565 mode:c++
566 c-file-style:"stroustrup"
567 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
568 indent-tabs-mode:nil
569 fill-column:99
570 End:
571 */
572 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :