Code

gray out widgets when grid is disabled.
[inkscape.git] / src / display / canvas-grid.cpp
1 #define INKSCAPE_CANVAS_GRID_C
3 /*
4  *
5  * Copyright (C) Johan Engelen 2006-2007 <johan@shouraizou.nl>
6  * Copyright (C) Lauris Kaplinski 2000
7  *
8  */
10 /* As a general comment, I am not exactly proud of how things are done.
11  * (for example the 'enable' widget and readRepr things)
12  * It does seem to work however. I intend to clean up and sort things out later, but that can take forever...
13  * Don't be shy to correct things.
14  */
17 #include "sp-canvas-util.h"
18 #include "util/mathfns.h" 
19 #include "display-forward.h"
20 #include <libnr/nr-pixops.h>
21 #include "desktop-handles.h"
22 #include "helper/units.h"
23 #include "svg/svg-color.h"
24 #include "xml/node-event-vector.h"
25 #include "sp-object.h"
27 #include "sp-namedview.h"
28 #include "inkscape.h"
29 #include "desktop.h"
31 #include "../document.h"
32 #include "prefs-utils.h"
34 #include "canvas-grid.h"
35 #include "canvas-axonomgrid.h"
37 namespace Inkscape {
39 static gchar const *const grid_name[] = {
40     N_("Rectangular grid"),
41     N_("Axonometric grid")
42 };
43 static gchar const *const grid_svgname[] = {
44     "xygrid",
45     "axonomgrid"
46 };
49 // ##########################################################
50 // Grid CanvasItem
51 static void grid_canvasitem_class_init (GridCanvasItemClass *klass);
52 static void grid_canvasitem_init (GridCanvasItem *grid);
53 static void grid_canvasitem_destroy (GtkObject *object);
55 static void grid_canvasitem_update (SPCanvasItem *item, NR::Matrix const &affine, unsigned int flags);
56 static void grid_canvasitem_render (SPCanvasItem *item, SPCanvasBuf *buf);
58 static SPCanvasItemClass * parent_class;
60 GtkType
61 grid_canvasitem_get_type (void)
62 {
63     static GtkType grid_canvasitem_type = 0;
65     if (!grid_canvasitem_type) {
66         GtkTypeInfo grid_canvasitem_info = {
67             "GridCanvasItem",
68             sizeof (GridCanvasItem),
69             sizeof (GridCanvasItemClass),
70             (GtkClassInitFunc) grid_canvasitem_class_init,
71             (GtkObjectInitFunc) grid_canvasitem_init,
72             NULL, NULL,
73             (GtkClassInitFunc) NULL
74         };
75         grid_canvasitem_type = gtk_type_unique (sp_canvas_item_get_type (), &grid_canvasitem_info);
76     }
77     return grid_canvasitem_type;
78 }
80 static void
81 grid_canvasitem_class_init (GridCanvasItemClass *klass)
82 {
83     GtkObjectClass *object_class;
84     SPCanvasItemClass *item_class;
86     object_class = (GtkObjectClass *) klass;
87     item_class = (SPCanvasItemClass *) klass;
89     parent_class = (SPCanvasItemClass*)gtk_type_class (sp_canvas_item_get_type ());
91     object_class->destroy = grid_canvasitem_destroy;
93     item_class->update = grid_canvasitem_update;
94     item_class->render = grid_canvasitem_render;
95 }
97 static void
98 grid_canvasitem_init (GridCanvasItem *griditem)
99 {
100     griditem->grid = NULL;
103 static void
104 grid_canvasitem_destroy (GtkObject *object)
106     g_return_if_fail (object != NULL);
107     g_return_if_fail (INKSCAPE_IS_GRID_CANVASITEM (object));
109     if (GTK_OBJECT_CLASS (parent_class)->destroy)
110         (* GTK_OBJECT_CLASS (parent_class)->destroy) (object);
113 /**
114 */
115 static void
116 grid_canvasitem_render (SPCanvasItem * item, SPCanvasBuf * buf)
118     GridCanvasItem *gridcanvasitem = INKSCAPE_GRID_CANVASITEM (item);
120     if ( gridcanvasitem->grid && gridcanvasitem->grid->isVisible() ) {
121         sp_canvas_prepare_buffer (buf);
122         gridcanvasitem->grid->Render(buf);
123     }
126 static void
127 grid_canvasitem_update (SPCanvasItem *item, NR::Matrix const &affine, unsigned int flags)
129     GridCanvasItem *gridcanvasitem = INKSCAPE_GRID_CANVASITEM (item);
131     if (parent_class->update)
132         (* parent_class->update) (item, affine, flags);
134     if (gridcanvasitem->grid) {
135         gridcanvasitem->grid->Update(affine, flags);
137         sp_canvas_request_redraw (item->canvas,
138                          -1000000, -1000000,
139                          1000000, 1000000);
141         item->x1 = item->y1 = -1000000;
142         item->x2 = item->y2 = 1000000;
143     }
148 // ##########################################################
149 //   CanvasGrid
151     static Inkscape::XML::NodeEventVector const _repr_events = {
152         NULL, /* child_added */
153         NULL, /* child_removed */
154         CanvasGrid::on_repr_attr_changed,
155         NULL, /* content_changed */
156         NULL  /* order_changed */
157     };
159 CanvasGrid::CanvasGrid(SPNamedView * nv, Inkscape::XML::Node * in_repr, SPDocument *in_doc, GridType type)
160     : visible(true), gridtype(type)
162     repr = in_repr;
163     doc = in_doc;
164     if (repr) {
165         repr->addListener (&_repr_events, this);
166     }
168     namedview = nv;
169     canvasitems = NULL;
172 CanvasGrid::~CanvasGrid()
174     if (repr) {
175         repr->removeListenerByData (this);
176     }
178     while (canvasitems) {
179         gtk_object_destroy(GTK_OBJECT(canvasitems->data));
180         canvasitems = g_slist_remove(canvasitems, canvasitems->data);
181     }
184 const char *
185 CanvasGrid::getName()
187     return _(grid_name[gridtype]);
190 const char *
191 CanvasGrid::getSVGName()
193     return grid_svgname[gridtype];
196 GridType
197 CanvasGrid::getGridType()
199     return gridtype;
203 char const *
204 CanvasGrid::getName(GridType type)
206     return _(grid_name[type]);
209 char const *
210 CanvasGrid::getSVGName(GridType type)
212     return grid_svgname[type];
215 GridType
216 CanvasGrid::getGridTypeFromSVGName(char const *typestr)
218     if (!typestr) return GRID_RECTANGULAR;
220     gint t = 0;
221     for (t = GRID_MAXTYPENR; t >= 0; t--) {  //this automatically defaults to grid0 which is rectangular grid
222         if (!strcmp(typestr, grid_svgname[t])) break;
223     }
224     return (GridType) t;
227 GridType
228 CanvasGrid::getGridTypeFromName(char const *typestr)
230     if (!typestr) return GRID_RECTANGULAR;
232     gint t = 0;
233     for (t = GRID_MAXTYPENR; t >= 0; t--) {  //this automatically defaults to grid0 which is rectangular grid
234         if (!strcmp(typestr, _(grid_name[t]))) break;
235     }
236     return (GridType) t;
240 /*
241 *  writes an <inkscape:grid> child to repr.
242 */
243 void
244 CanvasGrid::writeNewGridToRepr(Inkscape::XML::Node * repr, SPDocument * doc, GridType gridtype)
246     if (!repr) return;
247     if (gridtype > GRID_MAXTYPENR) return;
249     // first create the child xml node, then hook it to repr. This order is important, to not set off listeners to repr before the new node is complete.
251     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
252     Inkscape::XML::Node *newnode;
253     newnode = xml_doc->createElement("inkscape:grid");
254     newnode->setAttribute("type", getSVGName(gridtype));
256     repr->appendChild(newnode);
257     Inkscape::GC::release(newnode);
259     sp_document_done(doc, SP_VERB_DIALOG_NAMEDVIEW, _("Create new grid"));
262 /*
263 * Creates a new CanvasGrid object of type gridtype
264 */
265 CanvasGrid*
266 CanvasGrid::NewGrid(SPNamedView * nv, Inkscape::XML::Node * repr, SPDocument * doc, GridType gridtype)
268     if (!repr) return NULL;
269     if (!doc) {
270         g_error("CanvasGrid::NewGrid - doc==NULL");
271         return NULL;
272     }
274     switch (gridtype) {
275         case GRID_RECTANGULAR:
276             return (CanvasGrid*) new CanvasXYGrid(nv, repr, doc);
277         case GRID_AXONOMETRIC:
278             return (CanvasGrid*) new CanvasAxonomGrid(nv, repr, doc);
279     }
281     return NULL;
285 /**
286 *  creates a new grid canvasitem for the SPDesktop given as parameter. Keeps a link to this canvasitem in the canvasitems list.
287 */
288 GridCanvasItem *
289 CanvasGrid::createCanvasItem(SPDesktop * desktop)
291     if (!desktop) return NULL;
292 //    Johan: I think for multiple desktops it is best if each has their own canvasitem,
293 //           but share the same CanvasGrid object; that is what this function is for.
295     // check if there is already a canvasitem on this desktop linking to this grid
296     for (GSList *l = canvasitems; l != NULL; l = l->next) {
297         if ( sp_desktop_gridgroup(desktop) == SP_CANVAS_GROUP(SP_CANVAS_ITEM(l->data)->parent) ) {
298             return NULL;
299         }
300     }
302     GridCanvasItem * item = INKSCAPE_GRID_CANVASITEM( sp_canvas_item_new(sp_desktop_gridgroup(desktop), INKSCAPE_TYPE_GRID_CANVASITEM, NULL) );
303     item->grid = this;
304     sp_canvas_item_show(SP_CANVAS_ITEM(item));
306     gtk_object_ref(GTK_OBJECT(item));    // since we're keeping a link to this item, we need to bump up the ref count
307     canvasitems = g_slist_prepend(canvasitems, item);
309     return item;
312 Gtk::Widget *
313 CanvasGrid::newWidget()
315     Gtk::VBox * vbox = Gtk::manage( new Gtk::VBox() );
316     Gtk::Label * namelabel = Gtk::manage(new Gtk::Label("", Gtk::ALIGN_CENTER) );
318     Glib::ustring str("<b>");
319     str += getName();
320     str += "</b>";
321     namelabel->set_markup(str);
322     vbox->pack_start(*namelabel, true, true);
324     Inkscape::UI::Widget::RegisteredCheckButton * _rcb_enabled = Gtk::manage(
325         new Inkscape::UI::Widget::RegisteredCheckButton( _("_Enabled"),
326                         _("Determines whether to snap to this grid or not. Can be 'on' for invisible grids."),
327                          "enabled", _wr, false, repr, doc) );
328     Inkscape::UI::Widget::RegisteredCheckButton * _rcb_visible = Gtk::manage(
329         new Inkscape::UI::Widget::RegisteredCheckButton( _("_Visible"),
330                         _("Determines whether the grid is displayed or not. Objects are still snapped to invisible grids."),
331                          "visible", _wr, true, repr, doc) );
333     vbox->pack_start(*_rcb_enabled, true, true);
334     vbox->pack_start(*_rcb_visible, true, true);
335     Gtk::Widget * gridwdg = newSpecificWidget();
336     vbox->pack_start(*gridwdg, true, true);
338     std::list<Gtk::Widget*> slaves;
339     slaves.push_back(_rcb_visible);
340     slaves.push_back(gridwdg);
341     _rcb_enabled->setSlaveWidgets(slaves);
343     // set widget values
344     _rcb_visible->setActive(visible);
345     if (snapper != NULL) {
346         _rcb_enabled->setActive(snapper->getEnabled());
347     }
349     return dynamic_cast<Gtk::Widget *> (vbox);
352 void
353 CanvasGrid::on_repr_attr_changed(Inkscape::XML::Node *repr, gchar const *key, gchar const *oldval, gchar const *newval, bool is_interactive, void *data)
355     if (!data)
356         return;
358     ((CanvasGrid*) data)->onReprAttrChanged(repr, key, oldval, newval, is_interactive);
361 bool CanvasGrid::isEnabled() 
362
363     if (snapper == NULL) {
364        return false;
365     } 
366     
367     return snapper->getEnabled();    
370 // ##########################################################
371 //   CanvasXYGrid
374 /**
375 * "attach_all" function
376 * A DIRECT COPY-PASTE FROM DOCUMENT-PROPERTIES.CPP  TO QUICKLY GET RESULTS
378  * Helper function that attachs widgets in a 3xn table. The widgets come in an
379  * array that has two entries per table row. The two entries code for four
380  * possible cases: (0,0) means insert space in first column; (0, non-0) means
381  * widget in columns 2-3; (non-0, 0) means label in columns 1-3; and
382  * (non-0, non-0) means two widgets in columns 2 and 3.
383 **/
384 #define SPACE_SIZE_X 15
385 #define SPACE_SIZE_Y 10
386 static inline void
387 attach_all(Gtk::Table &table, Gtk::Widget const *const arr[], unsigned size, int start = 0)
389     for (unsigned i=0, r=start; i<size/sizeof(Gtk::Widget*); i+=2) {
390         if (arr[i] && arr[i+1]) {
391             table.attach (const_cast<Gtk::Widget&>(*arr[i]),   1, 2, r, r+1,
392                           Gtk::FILL|Gtk::EXPAND, (Gtk::AttachOptions)0,0,0);
393             table.attach (const_cast<Gtk::Widget&>(*arr[i+1]), 2, 3, r, r+1,
394                           Gtk::FILL|Gtk::EXPAND, (Gtk::AttachOptions)0,0,0);
395         } else {
396             if (arr[i+1]) {
397                 table.attach (const_cast<Gtk::Widget&>(*arr[i+1]), 1, 3, r, r+1,
398                               Gtk::FILL|Gtk::EXPAND, (Gtk::AttachOptions)0,0,0);
399             } else if (arr[i]) {
400                 Gtk::Label& label = reinterpret_cast<Gtk::Label&> (const_cast<Gtk::Widget&>(*arr[i]));
401                 label.set_alignment (0.0);
402                 table.attach (label, 0, 3, r, r+1,
403                               Gtk::FILL|Gtk::EXPAND, (Gtk::AttachOptions)0,0,0);
404             } else {
405                 Gtk::HBox *space = manage (new Gtk::HBox);
406                 space->set_size_request (SPACE_SIZE_X, SPACE_SIZE_Y);
407                 table.attach (*space, 0, 1, r, r+1,
408                               (Gtk::AttachOptions)0, (Gtk::AttachOptions)0,0,0);
409             }
410         }
411         ++r;
412     }
415 CanvasXYGrid::CanvasXYGrid (SPNamedView * nv, Inkscape::XML::Node * in_repr, SPDocument * in_doc)
416     : CanvasGrid(nv, in_repr, in_doc, GRID_RECTANGULAR)
418     gridunit = sp_unit_get_by_abbreviation( prefs_get_string_attribute("options.grids.xy", "units") );
419     if (!gridunit)
420         gridunit = &sp_unit_get_by_id(SP_UNIT_PX);
421     origin[NR::X] = sp_units_get_pixels( prefs_get_double_attribute ("options.grids.xy", "origin_x", 0.0), *(gridunit) );
422     origin[NR::Y] = sp_units_get_pixels( prefs_get_double_attribute ("options.grids.xy", "origin_y", 0.0), *(gridunit) );
423     color = prefs_get_int_attribute("options.grids.xy", "color", 0x0000ff20);
424     empcolor = prefs_get_int_attribute("options.grids.xy", "empcolor", 0x0000ff40);
425     empspacing = prefs_get_int_attribute("options.grids.xy", "empspacing", 5);
426     spacing[NR::X] = sp_units_get_pixels( prefs_get_double_attribute ("options.grids.xy", "spacing_x", 0.0), *(gridunit) );
427     spacing[NR::Y] = sp_units_get_pixels( prefs_get_double_attribute ("options.grids.xy", "spacing_y", 0.0), *(gridunit) );
428     render_dotted = prefs_get_int_attribute ("options.grids.xy", "dotted", 0) == 1;
430     snapper = new CanvasXYGridSnapper(this, namedview, 0);
433 CanvasXYGrid::~CanvasXYGrid ()
435    if (snapper) delete snapper;
439 /* fixme: Collect all these length parsing methods and think common sane API */
441 static gboolean
442 sp_nv_read_length(gchar const *str, guint base, gdouble *val, SPUnit const **unit)
444     if (!str) {
445         return FALSE;
446     }
448     gchar *u;
449     gdouble v = g_ascii_strtod(str, &u);
450     if (!u) {
451         return FALSE;
452     }
453     while (isspace(*u)) {
454         u += 1;
455     }
457     if (!*u) {
458         /* No unit specified - keep default */
459         *val = v;
460         return TRUE;
461     }
463     if (base & SP_UNIT_DEVICE) {
464         if (u[0] && u[1] && !isalnum(u[2]) && !strncmp(u, "px", 2)) {
465             *unit = &sp_unit_get_by_id(SP_UNIT_PX);
466             *val = v;
467             return TRUE;
468         }
469     }
471     if (base & SP_UNIT_ABSOLUTE) {
472         if (!strncmp(u, "pt", 2)) {
473             *unit = &sp_unit_get_by_id(SP_UNIT_PT);
474         } else if (!strncmp(u, "mm", 2)) {
475             *unit = &sp_unit_get_by_id(SP_UNIT_MM);
476         } else if (!strncmp(u, "cm", 2)) {
477             *unit = &sp_unit_get_by_id(SP_UNIT_CM);
478         } else if (!strncmp(u, "m", 1)) {
479             *unit = &sp_unit_get_by_id(SP_UNIT_M);
480         } else if (!strncmp(u, "in", 2)) {
481             *unit = &sp_unit_get_by_id(SP_UNIT_IN);
482         } else {
483             return FALSE;
484         }
485         *val = v;
486         return TRUE;
487     }
489     return FALSE;
492 static gboolean sp_nv_read_opacity(gchar const *str, guint32 *color)
494     if (!str) {
495         return FALSE;
496     }
498     gchar *u;
499     gdouble v = g_ascii_strtod(str, &u);
500     if (!u) {
501         return FALSE;
502     }
503     v = CLAMP(v, 0.0, 1.0);
505     *color = (*color & 0xffffff00) | (guint32) floor(v * 255.9999);
507     return TRUE;
510 /** If the passed scalar is invalid (<=0), then set the widget and the scalar
511     to use the given old value.
513     @param oldVal Old value to use if the new one is invalid.
514     @param pTarget The scalar to validate.
515     @param widget Widget associated with the scalar.
516 */
517 static void validateScalar(double oldVal,
518                            double* pTarget)
520     // Avoid nullness.
521     if ( pTarget == NULL )
522         return;
524     // Invalid new value?
525     if ( *pTarget <= 0 ) {
526         // If the old value is somehow invalid as well, then default to 1.
527         if ( oldVal <= 0 )
528             oldVal = 1;
530         // Reset the scalar and associated widget to the old value.
531         *pTarget = oldVal;
532     } //if
534 } //validateScalar
537 /** If the passed int is invalid (<=0), then set the widget and the int
538     to use the given old value.
540     @param oldVal Old value to use if the new one is invalid.
541     @param pTarget The int to validate.
542     @param widget Widget associated with the int.
543 */
544 static void validateInt(gint oldVal,
545                         gint* pTarget)
547     // Avoid nullness.
548     if ( pTarget == NULL )
549         return;
551     // Invalid new value?
552     if ( *pTarget <= 0 ) {
553         // If the old value is somehow invalid as well, then default to 1.
554         if ( oldVal <= 0 )
555             oldVal = 1;
557         // Reset the int and associated widget to the old value.
558         *pTarget = oldVal;
559     } //if
561 } //validateInt
563 void
564 CanvasXYGrid::readRepr()
566     gchar const *value;
567     if ( (value = repr->attribute("originx")) ) {
568         sp_nv_read_length(value, SP_UNIT_ABSOLUTE | SP_UNIT_DEVICE, &origin[NR::X], &gridunit);
569         origin[NR::X] = sp_units_get_pixels(origin[NR::X], *(gridunit));
570     }
572     if ( (value = repr->attribute("originy")) ) {
573         sp_nv_read_length(value, SP_UNIT_ABSOLUTE | SP_UNIT_DEVICE, &origin[NR::Y], &gridunit);
574         origin[NR::Y] = sp_units_get_pixels(origin[NR::Y], *(gridunit));
575     }
577     if ( (value = repr->attribute("spacingx")) ) {
578         double oldVal = spacing[NR::X];
579         sp_nv_read_length(value, SP_UNIT_ABSOLUTE | SP_UNIT_DEVICE, &spacing[NR::X], &gridunit);
580         validateScalar( oldVal, &spacing[NR::X]);
581         spacing[NR::X] = sp_units_get_pixels(spacing[NR::X], *(gridunit));
583     }
584     if ( (value = repr->attribute("spacingy")) ) {
585         double oldVal = spacing[NR::Y];
586         sp_nv_read_length(value, SP_UNIT_ABSOLUTE | SP_UNIT_DEVICE, &spacing[NR::Y], &gridunit);
587         validateScalar( oldVal, &spacing[NR::Y]);
588         spacing[NR::Y] = sp_units_get_pixels(spacing[NR::Y], *(gridunit));
590     }
592     if ( (value = repr->attribute("color")) ) {
593         color = (color & 0xff) | sp_svg_read_color(value, color);
594     }
596     if ( (value = repr->attribute("empcolor")) ) {
597         empcolor = (empcolor & 0xff) | sp_svg_read_color(value, empcolor);
598     }
600     if ( (value = repr->attribute("opacity")) ) {
601         sp_nv_read_opacity(value, &color);
602     }
603     if ( (value = repr->attribute("empopacity")) ) {
604         sp_nv_read_opacity(value, &empcolor);
605     }
607     if ( (value = repr->attribute("empspacing")) ) {
608         gint oldVal = empspacing;
609         empspacing = atoi(value);
610         validateInt( oldVal, &empspacing);
611     }
613     if ( (value = repr->attribute("dotted")) ) {
614         render_dotted = (strcmp(value,"true") == 0);
615     }
617     if ( (value = repr->attribute("visible")) ) {
618         visible = (strcmp(value,"true") == 0);
619     }
620     
621     if ( (value = repr->attribute("enabled")) ) {
622         g_assert(snapper != NULL);
623         snapper->setEnabled(strcmp(value,"true") == 0);
624     }
626     for (GSList *l = canvasitems; l != NULL; l = l->next) {
627         sp_canvas_item_request_update ( SP_CANVAS_ITEM(l->data) );
628     }
630     return;
633 /**
634  * Called when XML node attribute changed; updates dialog widgets if change was not done by widgets themselves.
635  */
636 void
637 CanvasXYGrid::onReprAttrChanged(Inkscape::XML::Node */*repr*/, gchar const */*key*/, gchar const */*oldval*/, gchar const */*newval*/, bool /*is_interactive*/)
639     readRepr();
641     if ( ! (_wr.isUpdating()) )
642         updateWidgets();
648 Gtk::Widget *
649 CanvasXYGrid::newSpecificWidget()
651     Gtk::Table * table = Gtk::manage( new Gtk::Table(1,1) );
653     Inkscape::UI::Widget::RegisteredUnitMenu *_rumg = new Inkscape::UI::Widget::RegisteredUnitMenu();
654     Inkscape::UI::Widget::RegisteredScalarUnit *_rsu_ox = new Inkscape::UI::Widget::RegisteredScalarUnit();
655     Inkscape::UI::Widget::RegisteredScalarUnit *_rsu_oy = new Inkscape::UI::Widget::RegisteredScalarUnit();
656     Inkscape::UI::Widget::RegisteredScalarUnit *_rsu_sx = new Inkscape::UI::Widget::RegisteredScalarUnit();
657     Inkscape::UI::Widget::RegisteredScalarUnit *_rsu_sy = new Inkscape::UI::Widget::RegisteredScalarUnit();
659     Inkscape::UI::Widget::RegisteredColorPicker *_rcp_gcol = Gtk::manage(
660         new Inkscape::UI::Widget::RegisteredColorPicker(
661             _("Grid line _color:"), _("Grid line color"), _("Color of grid lines"), 
662             "color", "opacity", _wr, repr, doc));
664     Inkscape::UI::Widget::RegisteredColorPicker *_rcp_gmcol = Gtk::manage(
665         new Inkscape::UI::Widget::RegisteredColorPicker(
666             _("Ma_jor grid line color:"), _("Major grid line color"), 
667             _("Color of the major (highlighted) grid lines"), "empcolor", "empopacity", 
668             _wr, repr, doc));
669     
670     Inkscape::UI::Widget::RegisteredSuffixedInteger *_rsi = new Inkscape::UI::Widget::RegisteredSuffixedInteger();
672     // initialize widgets:
673     table->set_spacings(2);
675 _wr.setUpdating (true);
676     Inkscape::UI::Widget::ScalarUnit * sutemp;
677     _rumg->init (_("Grid _units:"), "units", _wr, repr, doc);
678     _rsu_ox->init (_("_Origin X:"), _("X coordinate of grid origin"),
679                   "originx", *_rumg, _wr, repr, doc);
680         sutemp = _rsu_ox->getSU();
681         sutemp->setDigits(4);
682         sutemp->setIncrements(0.1, 1.0);
683     _rsu_oy->init (_("O_rigin Y:"), _("Y coordinate of grid origin"),
684                   "originy", *_rumg, _wr, repr, doc);
685         sutemp = _rsu_oy->getSU();
686         sutemp->setDigits(4);
687         sutemp->setIncrements(0.1, 1.0);
688     _rsu_sx->init (_("Spacing _X:"), _("Distance between vertical grid lines"),
689                   "spacingx", *_rumg, _wr, repr, doc);
690         sutemp = _rsu_sx->getSU();
691         sutemp->setDigits(4);
692         sutemp->setIncrements(0.1, 1.0);
693     _rsu_sy->init (_("Spacing _Y:"), _("Distance between horizontal grid lines"),
694                   "spacingy", *_rumg, _wr, repr, doc);
695         sutemp = _rsu_sy->getSU();
696         sutemp->setDigits(4);
697         sutemp->setIncrements(0.1, 1.0);
699     _rsi->init (_("_Major grid line every:"), _("lines"), "empspacing", _wr, repr, doc);
701     Inkscape::UI::Widget::RegisteredCheckButton * _rcb_dotted = Gtk::manage(
702                 new Inkscape::UI::Widget::RegisteredCheckButton( _("_Show dots instead of lines"),
703                        _("If set, displays dots at gridpoints instead of gridlines"),
704                         "dotted", _wr, false, repr, doc) 
705                 );
706 _wr.setUpdating (false);
708     Gtk::Widget const *const widget_array[] = {
709         _rumg->_label,       _rumg->_sel,
710         0,                  _rsu_ox->getSU(),
711         0,                  _rsu_oy->getSU(),
712         0,                  _rsu_sx->getSU(),
713         0,                  _rsu_sy->getSU(),
714         _rcp_gcol->_label,   _rcp_gcol,
715         0,                  0,
716         _rcp_gmcol->_label,  _rcp_gmcol,
717         _rsi->_label,        &_rsi->_hbox,
718         0,                  _rcb_dotted,
719     };
721     attach_all (*table, widget_array, sizeof(widget_array));
723     if (repr) readRepr();
725     // set widget values
726     _rumg->setUnit (gridunit);
728     gdouble val;
729     val = origin[NR::X];
730     val = sp_pixels_get_units (val, *(gridunit));
731     _rsu_ox->setValue (val);
732     val = origin[NR::Y];
733     val = sp_pixels_get_units (val, *(gridunit));
734     _rsu_oy->setValue (val);
735     val = spacing[NR::X];
736     double gridx = sp_pixels_get_units (val, *(gridunit));
737     _rsu_sx->setValue (gridx);
738     val = spacing[NR::Y];
739     double gridy = sp_pixels_get_units (val, *(gridunit));
740     _rsu_sy->setValue (gridy);
742     _rcp_gcol->setRgba32 (color);
743     _rcp_gmcol->setRgba32 (empcolor);
744     _rsi->setValue (empspacing);
746     _rcb_dotted->setActive(render_dotted);
748     return table;
752 /**
753  * Update dialog widgets from object's values.
754  */
755 void
756 CanvasXYGrid::updateWidgets()
758 /*
759     if (_wr.isUpdating()) return;
761     _wr.setUpdating (true);
763     _rcb_visible.setActive(visible);
764     if (snapper != NULL) {
765         _rcb_enabled.setActive(snapper->getEnabled());
766     }
768     _rumg.setUnit (gridunit);
770     gdouble val;
771     val = origin[NR::X];
772     val = sp_pixels_get_units (val, *(gridunit));
773     _rsu_ox.setValue (val);
774     val = origin[NR::Y];
775     val = sp_pixels_get_units (val, *(gridunit));
776     _rsu_oy.setValue (val);
777     val = spacing[NR::X];
778     double gridx = sp_pixels_get_units (val, *(gridunit));
779     _rsu_sx.setValue (gridx);
780     val = spacing[NR::Y];
781     double gridy = sp_pixels_get_units (val, *(gridunit));
782     _rsu_sy.setValue (gridy);
784     _rcp_gcol.setRgba32 (color);
785     _rcp_gmcol.setRgba32 (empcolor);
786     _rsi.setValue (empspacing);
788     _rcb_dotted.setActive(render_dotted);
790     _wr.setUpdating (false);
792     return;
793 */
798 void
799 CanvasXYGrid::Update (NR::Matrix const &affine, unsigned int /*flags*/)
801     ow = origin * affine;
802     sw = spacing * affine;
803     sw -= NR::Point(affine[4], affine[5]);
805     for(int dim = 0; dim < 2; dim++) {
806         gint scaling_factor = empspacing;
808         if (scaling_factor <= 1)
809             scaling_factor = 5;
811         scaled[dim] = FALSE;
812         sw[dim] = fabs (sw[dim]);
813         while (sw[dim] < 8.0) {
814             scaled[dim] = TRUE;
815             sw[dim] *= scaling_factor;
816             /* First pass, go up to the major line spacing, then
817                keep increasing by two. */
818             scaling_factor = 2;
819         }
820     }
824 static void
825 grid_hline (SPCanvasBuf *buf, gint y, gint xs, gint xe, guint32 rgba)
827     if ((y >= buf->rect.y0) && (y < buf->rect.y1)) {
828         guint r, g, b, a;
829         gint x0, x1, x;
830         guchar *p;
831         r = NR_RGBA32_R (rgba);
832         g = NR_RGBA32_G (rgba);
833         b = NR_RGBA32_B (rgba);
834         a = NR_RGBA32_A (rgba);
835         x0 = MAX (buf->rect.x0, xs);
836         x1 = MIN (buf->rect.x1, xe + 1);
837         p = buf->buf + (y - buf->rect.y0) * buf->buf_rowstride + (x0 - buf->rect.x0) * 3;
838         for (x = x0; x < x1; x++) {
839             p[0] = NR_COMPOSEN11_1111 (r, a, p[0]);
840             p[1] = NR_COMPOSEN11_1111 (g, a, p[1]);
841             p[2] = NR_COMPOSEN11_1111 (b, a, p[2]);
842             p += 3;
843         }
844     }
847 static void
848 grid_vline (SPCanvasBuf *buf, gint x, gint ys, gint ye, guint32 rgba)
850     if ((x >= buf->rect.x0) && (x < buf->rect.x1)) {
851         guint r, g, b, a;
852         gint y0, y1, y;
853         guchar *p;
854         r = NR_RGBA32_R(rgba);
855         g = NR_RGBA32_G (rgba);
856         b = NR_RGBA32_B (rgba);
857         a = NR_RGBA32_A (rgba);
858         y0 = MAX (buf->rect.y0, ys);
859         y1 = MIN (buf->rect.y1, ye + 1);
860         p = buf->buf + (y0 - buf->rect.y0) * buf->buf_rowstride + (x - buf->rect.x0) * 3;
861         for (y = y0; y < y1; y++) {
862             p[0] = NR_COMPOSEN11_1111 (r, a, p[0]);
863             p[1] = NR_COMPOSEN11_1111 (g, a, p[1]);
864             p[2] = NR_COMPOSEN11_1111 (b, a, p[2]);
865             p += buf->buf_rowstride;
866         }
867     }
870 static void
871 grid_dot (SPCanvasBuf *buf, gint x, gint y, guint32 rgba)
873     if ( (y >= buf->rect.y0) && (y < buf->rect.y1)
874          && (x >= buf->rect.x0) && (x < buf->rect.x1) ) {
875         guint r, g, b, a;
876         guchar *p;
877         r = NR_RGBA32_R (rgba);
878         g = NR_RGBA32_G (rgba);
879         b = NR_RGBA32_B (rgba);
880         a = NR_RGBA32_A (rgba);
881         p = buf->buf + (y - buf->rect.y0) * buf->buf_rowstride + (x - buf->rect.x0) * 3;
882         p[0] = NR_COMPOSEN11_1111 (r, a, p[0]);
883         p[1] = NR_COMPOSEN11_1111 (g, a, p[1]);
884         p[2] = NR_COMPOSEN11_1111 (b, a, p[2]);
885     }
888 void
889 CanvasXYGrid::Render (SPCanvasBuf *buf)
891     gdouble const sxg = floor ((buf->rect.x0 - ow[NR::X]) / sw[NR::X]) * sw[NR::X] + ow[NR::X];
892     gint const  xlinestart = (gint) Inkscape::round((sxg - ow[NR::X]) / sw[NR::X]);
893     gdouble const syg = floor ((buf->rect.y0 - ow[NR::Y]) / sw[NR::Y]) * sw[NR::Y] + ow[NR::Y];
894     gint const  ylinestart = (gint) Inkscape::round((syg - ow[NR::Y]) / sw[NR::Y]);
896     //set correct coloring, depending preference (when zoomed out, always major coloring or minor coloring)
897     guint32 _empcolor;
898     bool preference = prefs_get_int_attribute ("options.grids", "no_emphasize_when_zoomedout", 0) == 1;
899     if( (scaled[NR::X] || scaled[NR::Y]) && preference ) {
900         _empcolor = color;
901     } else {
902         _empcolor = empcolor;
903     }
905     if (!render_dotted) {
906         gint ylinenum;
907         gdouble y;
908         for (y = syg, ylinenum = ylinestart; y < buf->rect.y1; y += sw[NR::Y], ylinenum++) {
909             gint const y0 = (gint) Inkscape::round(y);
910             if (!scaled[NR::Y] && (ylinenum % empspacing) != 0) {
911                 grid_hline (buf, y0, buf->rect.x0, buf->rect.x1 - 1, color);
912             } else {
913                 grid_hline (buf, y0, buf->rect.x0, buf->rect.x1 - 1, _empcolor);
914             }
915         }
917         gint xlinenum;
918         gdouble x;
919         for (x = sxg, xlinenum = xlinestart; x < buf->rect.x1; x += sw[NR::X], xlinenum++) {
920             gint const ix = (gint) Inkscape::round(x);
921             if (!scaled[NR::X] && (xlinenum % empspacing) != 0) {
922                 grid_vline (buf, ix, buf->rect.y0, buf->rect.y1, color);
923             } else {
924                 grid_vline (buf, ix, buf->rect.y0, buf->rect.y1, _empcolor);
925             }
926         }
927     } else {
928         gint ylinenum;
929         gdouble y;
930         for (y = syg, ylinenum = ylinestart; y < buf->rect.y1; y += sw[NR::Y], ylinenum++) {
931             gint const iy = (gint) Inkscape::round(y);
933             gint xlinenum;
934             gdouble x;
935             for (x = sxg, xlinenum = xlinestart; x < buf->rect.x1; x += sw[NR::X], xlinenum++) {
936                 gint const ix = (gint) Inkscape::round(x);
937                 if ( (!scaled[NR::X] && (xlinenum % empspacing) == 0)
938                      || (!scaled[NR::Y] && (ylinenum % empspacing) == 0) )
939                 {
940                     grid_dot (buf, ix, iy, _empcolor | (guint32)0x000000FF); // put alpha to max value
941                 } else {
942                     grid_dot (buf, ix, iy, color | (guint32)0x000000FF);  // put alpha to max value
943                 }
944             }
946         }
947     }
950 CanvasXYGridSnapper::CanvasXYGridSnapper(CanvasXYGrid *grid, SPNamedView const *nv, NR::Coord const d) : LineSnapper(nv, d)
952     this->grid = grid;
955 LineSnapper::LineList
956 CanvasXYGridSnapper::_getSnapLines(NR::Point const &p) const
958     LineList s;
960     if ( grid == NULL ) {
961         return s;
962     }
964     for (unsigned int i = 0; i < 2; ++i) {
966         /* This is to make sure we snap to only visible grid lines */
967         double scaled_spacing = grid->sw[i]; // this is spacing of visible lines if screen pixels
969         // convert screen pixels to px
970         // FIXME: after we switch to snapping dist in screen pixels, this will be unnecessary
971         if (SP_ACTIVE_DESKTOP) {
972             scaled_spacing /= SP_ACTIVE_DESKTOP->current_zoom();
973         }
975         NR::Coord rounded;        
976         NR::Point point_on_line;
977         
978         rounded = Inkscape::Util::round_to_upper_multiple_plus(p[i], scaled_spacing, grid->origin[i]);
979         point_on_line = i ? NR::Point(0, rounded) : NR::Point(rounded, 0);
980         s.push_back(std::make_pair(component_vectors[i], point_on_line));
981         
982         rounded = Inkscape::Util::round_to_lower_multiple_plus(p[i], scaled_spacing, grid->origin[i]);
983         point_on_line = i ? NR::Point(0, rounded) : NR::Point(rounded, 0);
984         s.push_back(std::make_pair(component_vectors[i], point_on_line));
985     }
987     return s;
990 void CanvasXYGridSnapper::_addSnappedLine(SnappedConstraints &sc, NR::Point const snapped_point, NR::Coord const snapped_distance, NR::Point const normal_to_line, NR::Point const point_on_line) const 
992     SnappedLine dummy = SnappedLine(snapped_point, snapped_distance, getSnapperTolerance(), getSnapperAlwaysSnap(), normal_to_line, point_on_line);
993     sc.grid_lines.push_back(dummy);
996 /**
997  *  \return true if this Snapper will snap at least one kind of point.
998  */
999 bool CanvasXYGridSnapper::ThisSnapperMightSnap() const
1001     return _named_view == NULL ? false : (_snap_enabled && _snap_from != 0);
1008 }; /* namespace Inkscape */
1011 /*
1012   Local Variables:
1013   mode:c++
1014   c-file-style:"stroustrup"
1015   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1016   indent-tabs-mode:nil
1017   fill-column:99
1018   End:
1019 */
1020 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :