Code

fix initialization of grid document properties
[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_visible = 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_enabled = 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     vbox->pack_start(*newSpecificWidget(), true, true);
337     // set widget values
338     _rcb_visible->setActive(visible);
339     if (snapper != NULL) {
340         _rcb_enabled->setActive(snapper->getEnabled());
341     }
343     return dynamic_cast<Gtk::Widget *> (vbox);
346 void
347 CanvasGrid::on_repr_attr_changed(Inkscape::XML::Node *repr, gchar const *key, gchar const *oldval, gchar const *newval, bool is_interactive, void *data)
349     if (!data)
350         return;
352     ((CanvasGrid*) data)->onReprAttrChanged(repr, key, oldval, newval, is_interactive);
355 bool CanvasGrid::isEnabled() 
356
357     if (snapper == NULL) {
358        return false;
359     } 
360     
361     return snapper->getEnabled();    
364 // ##########################################################
365 //   CanvasXYGrid
368 /**
369 * "attach_all" function
370 * A DIRECT COPY-PASTE FROM DOCUMENT-PROPERTIES.CPP  TO QUICKLY GET RESULTS
372  * Helper function that attachs widgets in a 3xn table. The widgets come in an
373  * array that has two entries per table row. The two entries code for four
374  * possible cases: (0,0) means insert space in first column; (0, non-0) means
375  * widget in columns 2-3; (non-0, 0) means label in columns 1-3; and
376  * (non-0, non-0) means two widgets in columns 2 and 3.
377 **/
378 #define SPACE_SIZE_X 15
379 #define SPACE_SIZE_Y 10
380 static inline void
381 attach_all(Gtk::Table &table, Gtk::Widget const *const arr[], unsigned size, int start = 0)
383     for (unsigned i=0, r=start; i<size/sizeof(Gtk::Widget*); i+=2) {
384         if (arr[i] && arr[i+1]) {
385             table.attach (const_cast<Gtk::Widget&>(*arr[i]),   1, 2, r, r+1,
386                           Gtk::FILL|Gtk::EXPAND, (Gtk::AttachOptions)0,0,0);
387             table.attach (const_cast<Gtk::Widget&>(*arr[i+1]), 2, 3, r, r+1,
388                           Gtk::FILL|Gtk::EXPAND, (Gtk::AttachOptions)0,0,0);
389         } else {
390             if (arr[i+1]) {
391                 table.attach (const_cast<Gtk::Widget&>(*arr[i+1]), 1, 3, r, r+1,
392                               Gtk::FILL|Gtk::EXPAND, (Gtk::AttachOptions)0,0,0);
393             } else if (arr[i]) {
394                 Gtk::Label& label = reinterpret_cast<Gtk::Label&> (const_cast<Gtk::Widget&>(*arr[i]));
395                 label.set_alignment (0.0);
396                 table.attach (label, 0, 3, r, r+1,
397                               Gtk::FILL|Gtk::EXPAND, (Gtk::AttachOptions)0,0,0);
398             } else {
399                 Gtk::HBox *space = manage (new Gtk::HBox);
400                 space->set_size_request (SPACE_SIZE_X, SPACE_SIZE_Y);
401                 table.attach (*space, 0, 1, r, r+1,
402                               (Gtk::AttachOptions)0, (Gtk::AttachOptions)0,0,0);
403             }
404         }
405         ++r;
406     }
409 CanvasXYGrid::CanvasXYGrid (SPNamedView * nv, Inkscape::XML::Node * in_repr, SPDocument * in_doc)
410     : CanvasGrid(nv, in_repr, in_doc, GRID_RECTANGULAR)
412     gridunit = sp_unit_get_by_abbreviation( prefs_get_string_attribute("options.grids.xy", "units") );
413     if (!gridunit)
414         gridunit = &sp_unit_get_by_id(SP_UNIT_PX);
415     origin[NR::X] = sp_units_get_pixels( prefs_get_double_attribute ("options.grids.xy", "origin_x", 0.0), *(gridunit) );
416     origin[NR::Y] = sp_units_get_pixels( prefs_get_double_attribute ("options.grids.xy", "origin_y", 0.0), *(gridunit) );
417     color = prefs_get_int_attribute("options.grids.xy", "color", 0x0000ff20);
418     empcolor = prefs_get_int_attribute("options.grids.xy", "empcolor", 0x0000ff40);
419     empspacing = prefs_get_int_attribute("options.grids.xy", "empspacing", 5);
420     spacing[NR::X] = sp_units_get_pixels( prefs_get_double_attribute ("options.grids.xy", "spacing_x", 0.0), *(gridunit) );
421     spacing[NR::Y] = sp_units_get_pixels( prefs_get_double_attribute ("options.grids.xy", "spacing_y", 0.0), *(gridunit) );
422     render_dotted = prefs_get_int_attribute ("options.grids.xy", "dotted", 0) == 1;
424     snapper = new CanvasXYGridSnapper(this, namedview, 0);
427 CanvasXYGrid::~CanvasXYGrid ()
429    if (snapper) delete snapper;
433 /* fixme: Collect all these length parsing methods and think common sane API */
435 static gboolean
436 sp_nv_read_length(gchar const *str, guint base, gdouble *val, SPUnit const **unit)
438     if (!str) {
439         return FALSE;
440     }
442     gchar *u;
443     gdouble v = g_ascii_strtod(str, &u);
444     if (!u) {
445         return FALSE;
446     }
447     while (isspace(*u)) {
448         u += 1;
449     }
451     if (!*u) {
452         /* No unit specified - keep default */
453         *val = v;
454         return TRUE;
455     }
457     if (base & SP_UNIT_DEVICE) {
458         if (u[0] && u[1] && !isalnum(u[2]) && !strncmp(u, "px", 2)) {
459             *unit = &sp_unit_get_by_id(SP_UNIT_PX);
460             *val = v;
461             return TRUE;
462         }
463     }
465     if (base & SP_UNIT_ABSOLUTE) {
466         if (!strncmp(u, "pt", 2)) {
467             *unit = &sp_unit_get_by_id(SP_UNIT_PT);
468         } else if (!strncmp(u, "mm", 2)) {
469             *unit = &sp_unit_get_by_id(SP_UNIT_MM);
470         } else if (!strncmp(u, "cm", 2)) {
471             *unit = &sp_unit_get_by_id(SP_UNIT_CM);
472         } else if (!strncmp(u, "m", 1)) {
473             *unit = &sp_unit_get_by_id(SP_UNIT_M);
474         } else if (!strncmp(u, "in", 2)) {
475             *unit = &sp_unit_get_by_id(SP_UNIT_IN);
476         } else {
477             return FALSE;
478         }
479         *val = v;
480         return TRUE;
481     }
483     return FALSE;
486 static gboolean sp_nv_read_opacity(gchar const *str, guint32 *color)
488     if (!str) {
489         return FALSE;
490     }
492     gchar *u;
493     gdouble v = g_ascii_strtod(str, &u);
494     if (!u) {
495         return FALSE;
496     }
497     v = CLAMP(v, 0.0, 1.0);
499     *color = (*color & 0xffffff00) | (guint32) floor(v * 255.9999);
501     return TRUE;
504 /** If the passed scalar is invalid (<=0), then set the widget and the scalar
505     to use the given old value.
507     @param oldVal Old value to use if the new one is invalid.
508     @param pTarget The scalar to validate.
509     @param widget Widget associated with the scalar.
510 */
511 static void validateScalar(double oldVal,
512                            double* pTarget)
514     // Avoid nullness.
515     if ( pTarget == NULL )
516         return;
518     // Invalid new value?
519     if ( *pTarget <= 0 ) {
520         // If the old value is somehow invalid as well, then default to 1.
521         if ( oldVal <= 0 )
522             oldVal = 1;
524         // Reset the scalar and associated widget to the old value.
525         *pTarget = oldVal;
526     } //if
528 } //validateScalar
531 /** If the passed int is invalid (<=0), then set the widget and the int
532     to use the given old value.
534     @param oldVal Old value to use if the new one is invalid.
535     @param pTarget The int to validate.
536     @param widget Widget associated with the int.
537 */
538 static void validateInt(gint oldVal,
539                         gint* pTarget)
541     // Avoid nullness.
542     if ( pTarget == NULL )
543         return;
545     // Invalid new value?
546     if ( *pTarget <= 0 ) {
547         // If the old value is somehow invalid as well, then default to 1.
548         if ( oldVal <= 0 )
549             oldVal = 1;
551         // Reset the int and associated widget to the old value.
552         *pTarget = oldVal;
553     } //if
555 } //validateInt
557 void
558 CanvasXYGrid::readRepr()
560     gchar const *value;
561     if ( (value = repr->attribute("originx")) ) {
562         sp_nv_read_length(value, SP_UNIT_ABSOLUTE | SP_UNIT_DEVICE, &origin[NR::X], &gridunit);
563         origin[NR::X] = sp_units_get_pixels(origin[NR::X], *(gridunit));
564     }
566     if ( (value = repr->attribute("originy")) ) {
567         sp_nv_read_length(value, SP_UNIT_ABSOLUTE | SP_UNIT_DEVICE, &origin[NR::Y], &gridunit);
568         origin[NR::Y] = sp_units_get_pixels(origin[NR::Y], *(gridunit));
569     }
571     if ( (value = repr->attribute("spacingx")) ) {
572         double oldVal = spacing[NR::X];
573         sp_nv_read_length(value, SP_UNIT_ABSOLUTE | SP_UNIT_DEVICE, &spacing[NR::X], &gridunit);
574         validateScalar( oldVal, &spacing[NR::X]);
575         spacing[NR::X] = sp_units_get_pixels(spacing[NR::X], *(gridunit));
577     }
578     if ( (value = repr->attribute("spacingy")) ) {
579         double oldVal = spacing[NR::Y];
580         sp_nv_read_length(value, SP_UNIT_ABSOLUTE | SP_UNIT_DEVICE, &spacing[NR::Y], &gridunit);
581         validateScalar( oldVal, &spacing[NR::Y]);
582         spacing[NR::Y] = sp_units_get_pixels(spacing[NR::Y], *(gridunit));
584     }
586     if ( (value = repr->attribute("color")) ) {
587         color = (color & 0xff) | sp_svg_read_color(value, color);
588     }
590     if ( (value = repr->attribute("empcolor")) ) {
591         empcolor = (empcolor & 0xff) | sp_svg_read_color(value, empcolor);
592     }
594     if ( (value = repr->attribute("opacity")) ) {
595         sp_nv_read_opacity(value, &color);
596     }
597     if ( (value = repr->attribute("empopacity")) ) {
598         sp_nv_read_opacity(value, &empcolor);
599     }
601     if ( (value = repr->attribute("empspacing")) ) {
602         gint oldVal = empspacing;
603         empspacing = atoi(value);
604         validateInt( oldVal, &empspacing);
605     }
607     if ( (value = repr->attribute("dotted")) ) {
608         render_dotted = (strcmp(value,"true") == 0);
609     }
611     if ( (value = repr->attribute("visible")) ) {
612         visible = (strcmp(value,"true") == 0);
613     }
614     
615     if ( (value = repr->attribute("enabled")) ) {
616         g_assert(snapper != NULL);
617         snapper->setEnabled(strcmp(value,"true") == 0);
618     }
620     for (GSList *l = canvasitems; l != NULL; l = l->next) {
621         sp_canvas_item_request_update ( SP_CANVAS_ITEM(l->data) );
622     }
624     return;
627 /**
628  * Called when XML node attribute changed; updates dialog widgets if change was not done by widgets themselves.
629  */
630 void
631 CanvasXYGrid::onReprAttrChanged(Inkscape::XML::Node */*repr*/, gchar const */*key*/, gchar const */*oldval*/, gchar const */*newval*/, bool /*is_interactive*/)
633     readRepr();
635     if ( ! (_wr.isUpdating()) )
636         updateWidgets();
642 Gtk::Widget *
643 CanvasXYGrid::newSpecificWidget()
645     Gtk::Table * table = Gtk::manage( new Gtk::Table(1,1) );
647     Inkscape::UI::Widget::RegisteredUnitMenu *_rumg = new Inkscape::UI::Widget::RegisteredUnitMenu();
648     Inkscape::UI::Widget::RegisteredScalarUnit *_rsu_ox = new Inkscape::UI::Widget::RegisteredScalarUnit();
649     Inkscape::UI::Widget::RegisteredScalarUnit *_rsu_oy = new Inkscape::UI::Widget::RegisteredScalarUnit();
650     Inkscape::UI::Widget::RegisteredScalarUnit *_rsu_sx = new Inkscape::UI::Widget::RegisteredScalarUnit();
651     Inkscape::UI::Widget::RegisteredScalarUnit *_rsu_sy = new Inkscape::UI::Widget::RegisteredScalarUnit();
652     Inkscape::UI::Widget::RegisteredColorPicker *_rcp_gcol = new Inkscape::UI::Widget::RegisteredColorPicker();
653     Inkscape::UI::Widget::RegisteredColorPicker *_rcp_gmcol = new Inkscape::UI::Widget::RegisteredColorPicker();
654     Inkscape::UI::Widget::RegisteredSuffixedInteger *_rsi = new Inkscape::UI::Widget::RegisteredSuffixedInteger();
656     // initialize widgets:
657     table->set_spacings(2);
659 _wr.setUpdating (true);
660     Inkscape::UI::Widget::ScalarUnit * sutemp;
661     _rumg->init (_("Grid _units:"), "units", _wr, repr, doc);
662     _rsu_ox->init (_("_Origin X:"), _("X coordinate of grid origin"),
663                   "originx", *_rumg, _wr, repr, doc);
664         sutemp = _rsu_ox->getSU();
665         sutemp->setDigits(4);
666         sutemp->setIncrements(0.1, 1.0);
667     _rsu_oy->init (_("O_rigin Y:"), _("Y coordinate of grid origin"),
668                   "originy", *_rumg, _wr, repr, doc);
669         sutemp = _rsu_oy->getSU();
670         sutemp->setDigits(4);
671         sutemp->setIncrements(0.1, 1.0);
672     _rsu_sx->init (_("Spacing _X:"), _("Distance between vertical grid lines"),
673                   "spacingx", *_rumg, _wr, repr, doc);
674         sutemp = _rsu_sx->getSU();
675         sutemp->setDigits(4);
676         sutemp->setIncrements(0.1, 1.0);
677     _rsu_sy->init (_("Spacing _Y:"), _("Distance between horizontal grid lines"),
678                   "spacingy", *_rumg, _wr, repr, doc);
679         sutemp = _rsu_sy->getSU();
680         sutemp->setDigits(4);
681         sutemp->setIncrements(0.1, 1.0);
682     _rcp_gcol->init (_("Grid line _color:"), _("Grid line color"),
683                     _("Color of grid lines"), "color", "opacity", _wr, repr, doc);
684     _rcp_gmcol->init (_("Ma_jor grid line color:"), _("Major grid line color"),
685                      _("Color of the major (highlighted) grid lines"),
686                      "empcolor", "empopacity", _wr, repr, doc);
687     _rsi->init (_("_Major grid line every:"), _("lines"), "empspacing", _wr, repr, doc);
689     Inkscape::UI::Widget::RegisteredCheckButton * _rcb_dotted = Gtk::manage(
690                 new Inkscape::UI::Widget::RegisteredCheckButton( _("_Show dots instead of lines"),
691                        _("If set, displays dots at gridpoints instead of gridlines"),
692                         "dotted", _wr, false, repr, doc) 
693                 );
694 _wr.setUpdating (false);
696     Gtk::Widget const *const widget_array[] = {
697         _rumg->_label,       _rumg->_sel,
698         0,                  _rsu_ox->getSU(),
699         0,                  _rsu_oy->getSU(),
700         0,                  _rsu_sx->getSU(),
701         0,                  _rsu_sy->getSU(),
702         _rcp_gcol->_label,   _rcp_gcol->_cp,
703         0,                  0,
704         _rcp_gmcol->_label,  _rcp_gmcol->_cp,
705         _rsi->_label,        &_rsi->_hbox,
706         0,                  _rcb_dotted,
707     };
709     attach_all (*table, widget_array, sizeof(widget_array));
711     if (repr) readRepr();
713     // set widget values
714     _rumg->setUnit (gridunit);
716     gdouble val;
717     val = origin[NR::X];
718     val = sp_pixels_get_units (val, *(gridunit));
719     _rsu_ox->setValue (val);
720     val = origin[NR::Y];
721     val = sp_pixels_get_units (val, *(gridunit));
722     _rsu_oy->setValue (val);
723     val = spacing[NR::X];
724     double gridx = sp_pixels_get_units (val, *(gridunit));
725     _rsu_sx->setValue (gridx);
726     val = spacing[NR::Y];
727     double gridy = sp_pixels_get_units (val, *(gridunit));
728     _rsu_sy->setValue (gridy);
730     _rcp_gcol->setRgba32 (color);
731     _rcp_gmcol->setRgba32 (empcolor);
732     _rsi->setValue (empspacing);
734     _rcb_dotted->setActive(render_dotted);
736     return table;
740 /**
741  * Update dialog widgets from object's values.
742  */
743 void
744 CanvasXYGrid::updateWidgets()
746 /*
747     if (_wr.isUpdating()) return;
749     _wr.setUpdating (true);
751     _rcb_visible.setActive(visible);
752     if (snapper != NULL) {
753         _rcb_enabled.setActive(snapper->getEnabled());
754     }
756     _rumg.setUnit (gridunit);
758     gdouble val;
759     val = origin[NR::X];
760     val = sp_pixels_get_units (val, *(gridunit));
761     _rsu_ox.setValue (val);
762     val = origin[NR::Y];
763     val = sp_pixels_get_units (val, *(gridunit));
764     _rsu_oy.setValue (val);
765     val = spacing[NR::X];
766     double gridx = sp_pixels_get_units (val, *(gridunit));
767     _rsu_sx.setValue (gridx);
768     val = spacing[NR::Y];
769     double gridy = sp_pixels_get_units (val, *(gridunit));
770     _rsu_sy.setValue (gridy);
772     _rcp_gcol.setRgba32 (color);
773     _rcp_gmcol.setRgba32 (empcolor);
774     _rsi.setValue (empspacing);
776     _rcb_dotted.setActive(render_dotted);
778     _wr.setUpdating (false);
780     return;
781 */
786 void
787 CanvasXYGrid::Update (NR::Matrix const &affine, unsigned int /*flags*/)
789     ow = origin * affine;
790     sw = spacing * affine;
791     sw -= NR::Point(affine[4], affine[5]);
793     for(int dim = 0; dim < 2; dim++) {
794         gint scaling_factor = empspacing;
796         if (scaling_factor <= 1)
797             scaling_factor = 5;
799         scaled[dim] = FALSE;
800         sw[dim] = fabs (sw[dim]);
801         while (sw[dim] < 8.0) {
802             scaled[dim] = TRUE;
803             sw[dim] *= scaling_factor;
804             /* First pass, go up to the major line spacing, then
805                keep increasing by two. */
806             scaling_factor = 2;
807         }
808     }
812 static void
813 grid_hline (SPCanvasBuf *buf, gint y, gint xs, gint xe, guint32 rgba)
815     if ((y >= buf->rect.y0) && (y < buf->rect.y1)) {
816         guint r, g, b, a;
817         gint x0, x1, x;
818         guchar *p;
819         r = NR_RGBA32_R (rgba);
820         g = NR_RGBA32_G (rgba);
821         b = NR_RGBA32_B (rgba);
822         a = NR_RGBA32_A (rgba);
823         x0 = MAX (buf->rect.x0, xs);
824         x1 = MIN (buf->rect.x1, xe + 1);
825         p = buf->buf + (y - buf->rect.y0) * buf->buf_rowstride + (x0 - buf->rect.x0) * 3;
826         for (x = x0; x < x1; x++) {
827             p[0] = NR_COMPOSEN11_1111 (r, a, p[0]);
828             p[1] = NR_COMPOSEN11_1111 (g, a, p[1]);
829             p[2] = NR_COMPOSEN11_1111 (b, a, p[2]);
830             p += 3;
831         }
832     }
835 static void
836 grid_vline (SPCanvasBuf *buf, gint x, gint ys, gint ye, guint32 rgba)
838     if ((x >= buf->rect.x0) && (x < buf->rect.x1)) {
839         guint r, g, b, a;
840         gint y0, y1, y;
841         guchar *p;
842         r = NR_RGBA32_R(rgba);
843         g = NR_RGBA32_G (rgba);
844         b = NR_RGBA32_B (rgba);
845         a = NR_RGBA32_A (rgba);
846         y0 = MAX (buf->rect.y0, ys);
847         y1 = MIN (buf->rect.y1, ye + 1);
848         p = buf->buf + (y0 - buf->rect.y0) * buf->buf_rowstride + (x - buf->rect.x0) * 3;
849         for (y = y0; y < y1; y++) {
850             p[0] = NR_COMPOSEN11_1111 (r, a, p[0]);
851             p[1] = NR_COMPOSEN11_1111 (g, a, p[1]);
852             p[2] = NR_COMPOSEN11_1111 (b, a, p[2]);
853             p += buf->buf_rowstride;
854         }
855     }
858 static void
859 grid_dot (SPCanvasBuf *buf, gint x, gint y, guint32 rgba)
861     if ( (y >= buf->rect.y0) && (y < buf->rect.y1)
862          && (x >= buf->rect.x0) && (x < buf->rect.x1) ) {
863         guint r, g, b, a;
864         guchar *p;
865         r = NR_RGBA32_R (rgba);
866         g = NR_RGBA32_G (rgba);
867         b = NR_RGBA32_B (rgba);
868         a = NR_RGBA32_A (rgba);
869         p = buf->buf + (y - buf->rect.y0) * buf->buf_rowstride + (x - buf->rect.x0) * 3;
870         p[0] = NR_COMPOSEN11_1111 (r, a, p[0]);
871         p[1] = NR_COMPOSEN11_1111 (g, a, p[1]);
872         p[2] = NR_COMPOSEN11_1111 (b, a, p[2]);
873     }
876 void
877 CanvasXYGrid::Render (SPCanvasBuf *buf)
879     gdouble const sxg = floor ((buf->rect.x0 - ow[NR::X]) / sw[NR::X]) * sw[NR::X] + ow[NR::X];
880     gint const  xlinestart = (gint) Inkscape::round((sxg - ow[NR::X]) / sw[NR::X]);
881     gdouble const syg = floor ((buf->rect.y0 - ow[NR::Y]) / sw[NR::Y]) * sw[NR::Y] + ow[NR::Y];
882     gint const  ylinestart = (gint) Inkscape::round((syg - ow[NR::Y]) / sw[NR::Y]);
884     //set correct coloring, depending preference (when zoomed out, always major coloring or minor coloring)
885     guint32 _empcolor;
886     bool preference = prefs_get_int_attribute ("options.grids", "no_emphasize_when_zoomedout", 0) == 1;
887     if( (scaled[NR::X] || scaled[NR::Y]) && preference ) {
888         _empcolor = color;
889     } else {
890         _empcolor = empcolor;
891     }
893     if (!render_dotted) {
894         gint ylinenum;
895         gdouble y;
896         for (y = syg, ylinenum = ylinestart; y < buf->rect.y1; y += sw[NR::Y], ylinenum++) {
897             gint const y0 = (gint) Inkscape::round(y);
898             if (!scaled[NR::Y] && (ylinenum % empspacing) != 0) {
899                 grid_hline (buf, y0, buf->rect.x0, buf->rect.x1 - 1, color);
900             } else {
901                 grid_hline (buf, y0, buf->rect.x0, buf->rect.x1 - 1, _empcolor);
902             }
903         }
905         gint xlinenum;
906         gdouble x;
907         for (x = sxg, xlinenum = xlinestart; x < buf->rect.x1; x += sw[NR::X], xlinenum++) {
908             gint const ix = (gint) Inkscape::round(x);
909             if (!scaled[NR::X] && (xlinenum % empspacing) != 0) {
910                 grid_vline (buf, ix, buf->rect.y0, buf->rect.y1, color);
911             } else {
912                 grid_vline (buf, ix, buf->rect.y0, buf->rect.y1, _empcolor);
913             }
914         }
915     } else {
916         gint ylinenum;
917         gdouble y;
918         for (y = syg, ylinenum = ylinestart; y < buf->rect.y1; y += sw[NR::Y], ylinenum++) {
919             gint const iy = (gint) Inkscape::round(y);
921             gint xlinenum;
922             gdouble x;
923             for (x = sxg, xlinenum = xlinestart; x < buf->rect.x1; x += sw[NR::X], xlinenum++) {
924                 gint const ix = (gint) Inkscape::round(x);
925                 if ( (!scaled[NR::X] && (xlinenum % empspacing) == 0)
926                      || (!scaled[NR::Y] && (ylinenum % empspacing) == 0) )
927                 {
928                     grid_dot (buf, ix, iy, _empcolor | (guint32)0x000000FF); // put alpha to max value
929                 } else {
930                     grid_dot (buf, ix, iy, color | (guint32)0x000000FF);  // put alpha to max value
931                 }
932             }
934         }
935     }
938 CanvasXYGridSnapper::CanvasXYGridSnapper(CanvasXYGrid *grid, SPNamedView const *nv, NR::Coord const d) : LineSnapper(nv, d)
940     this->grid = grid;
943 LineSnapper::LineList
944 CanvasXYGridSnapper::_getSnapLines(NR::Point const &p) const
946     LineList s;
948     if ( grid == NULL ) {
949         return s;
950     }
952     for (unsigned int i = 0; i < 2; ++i) {
954         /* This is to make sure we snap to only visible grid lines */
955         double scaled_spacing = grid->sw[i]; // this is spacing of visible lines if screen pixels
957         // convert screen pixels to px
958         // FIXME: after we switch to snapping dist in screen pixels, this will be unnecessary
959         if (SP_ACTIVE_DESKTOP) {
960             scaled_spacing /= SP_ACTIVE_DESKTOP->current_zoom();
961         }
963         NR::Coord rounded;        
964         NR::Point point_on_line;
965         
966         rounded = Inkscape::Util::round_to_upper_multiple_plus(p[i], scaled_spacing, grid->origin[i]);
967         point_on_line = i ? NR::Point(0, rounded) : NR::Point(rounded, 0);
968         s.push_back(std::make_pair(component_vectors[i], point_on_line));
969         
970         rounded = Inkscape::Util::round_to_lower_multiple_plus(p[i], scaled_spacing, grid->origin[i]);
971         point_on_line = i ? NR::Point(0, rounded) : NR::Point(rounded, 0);
972         s.push_back(std::make_pair(component_vectors[i], point_on_line));
973     }
975     return s;
978 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 
980     SnappedLine dummy = SnappedLine(snapped_point, snapped_distance, getSnapperTolerance(), getSnapperAlwaysSnap(), normal_to_line, point_on_line);
981     sc.grid_lines.push_back(dummy);
984 /**
985  *  \return true if this Snapper will snap at least one kind of point.
986  */
987 bool CanvasXYGridSnapper::ThisSnapperMightSnap() const
989     return _named_view == NULL ? false : (_snap_enabled && _snap_from != 0);
996 }; /* namespace Inkscape */
999 /*
1000   Local Variables:
1001   mode:c++
1002   c-file-style:"stroustrup"
1003   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1004   indent-tabs-mode:nil
1005   fill-column:99
1006   End:
1007 */
1008 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :