Code

Improve layout 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 "display-forward.h"
19 #include <libnr/nr-pixops.h>
20 #include "desktop-handles.h"
21 #include "helper/units.h"
22 #include "svg/svg-color.h"
23 #include "xml/node-event-vector.h"
24 #include "sp-object.h"
26 #include "sp-namedview.h"
27 #include "inkscape.h"
28 #include "desktop.h"
30 #include "../document.h"
32 #include "canvas-grid.h"
33 #include "canvas-axonomgrid.h"
35 namespace Inkscape {
37 #define DEFAULTGRIDCOLOR    0x0000FF20
38 #define DEFAULTGRIDEMPCOLOR 0x0000FF40
40 static gchar const *const grid_name[] = {
41     N_("Rectangular grid"),
42     N_("Axonometric grid")
43 };
44 static gchar const *const grid_svgname[] = {
45     "xygrid",
46     "axonomgrid"
47 };
50 // ##########################################################
51 // Grid CanvasItem
52 static void grid_canvasitem_class_init (GridCanvasItemClass *klass);
53 static void grid_canvasitem_init (GridCanvasItem *grid);
54 static void grid_canvasitem_destroy (GtkObject *object);
56 static void grid_canvasitem_update (SPCanvasItem *item, NR::Matrix const &affine, unsigned int flags);
57 static void grid_canvasitem_render (SPCanvasItem *item, SPCanvasBuf *buf);
59 static SPCanvasItemClass * parent_class;
61 GtkType
62 grid_canvasitem_get_type (void)
63 {
64     static GtkType grid_canvasitem_type = 0;
66     if (!grid_canvasitem_type) {
67         GtkTypeInfo grid_canvasitem_info = {
68             "GridCanvasItem",
69             sizeof (GridCanvasItem),
70             sizeof (GridCanvasItemClass),
71             (GtkClassInitFunc) grid_canvasitem_class_init,
72             (GtkObjectInitFunc) grid_canvasitem_init,
73             NULL, NULL,
74             (GtkClassInitFunc) NULL
75         };
76         grid_canvasitem_type = gtk_type_unique (sp_canvas_item_get_type (), &grid_canvasitem_info);
77     }
78     return grid_canvasitem_type;
79 }
81 static void
82 grid_canvasitem_class_init (GridCanvasItemClass *klass)
83 {
84     GtkObjectClass *object_class;
85     SPCanvasItemClass *item_class;
87     object_class = (GtkObjectClass *) klass;
88     item_class = (SPCanvasItemClass *) klass;
90     parent_class = (SPCanvasItemClass*)gtk_type_class (sp_canvas_item_get_type ());
92     object_class->destroy = grid_canvasitem_destroy;
94     item_class->update = grid_canvasitem_update;
95     item_class->render = grid_canvasitem_render;
96 }
98 static void
99 grid_canvasitem_init (GridCanvasItem *griditem)
101     griditem->grid = NULL;
104 static void
105 grid_canvasitem_destroy (GtkObject *object)
107     g_return_if_fail (object != NULL);
108     g_return_if_fail (INKSCAPE_IS_GRID_CANVASITEM (object));
110     if (GTK_OBJECT_CLASS (parent_class)->destroy)
111         (* GTK_OBJECT_CLASS (parent_class)->destroy) (object);
114 /**
115 */
116 static void
117 grid_canvasitem_render (SPCanvasItem * item, SPCanvasBuf * buf)
119     GridCanvasItem *gridcanvasitem = INKSCAPE_GRID_CANVASITEM (item);
121     if ( gridcanvasitem->grid && gridcanvasitem->grid->isVisible() ) {
122         sp_canvas_prepare_buffer (buf);
123         gridcanvasitem->grid->Render(buf);
124     }
127 static void
128 grid_canvasitem_update (SPCanvasItem *item, NR::Matrix const &affine, unsigned int flags)
130     GridCanvasItem *gridcanvasitem = INKSCAPE_GRID_CANVASITEM (item);
132     if (parent_class->update)
133         (* parent_class->update) (item, affine, flags);
135     if (gridcanvasitem->grid) {
136         gridcanvasitem->grid->Update(affine, flags);
138         sp_canvas_request_redraw (item->canvas,
139                          -1000000, -1000000,
140                          1000000, 1000000);
142         item->x1 = item->y1 = -1000000;
143         item->x2 = item->y2 = 1000000;
144     }
149 // ##########################################################
150 //   CanvasGrid
152     static Inkscape::XML::NodeEventVector const _repr_events = {
153         NULL, /* child_added */
154         NULL, /* child_removed */
155         CanvasGrid::on_repr_attr_changed,
156         NULL, /* content_changed */
157         NULL  /* order_changed */
158     };
160 CanvasGrid::CanvasGrid(SPNamedView * nv, Inkscape::XML::Node * in_repr, SPDocument *in_doc, GridType type)
161     : namelabel("", Gtk::ALIGN_CENTER), gridtype(type), visible(true), snap_enabled(true)
163     repr = in_repr;
164     doc = in_doc;
165     if (repr) {
166         repr->addListener (&_repr_events, this);
167     }
169     namedview = nv;
170     canvasitems = NULL;
172     Glib::ustring str("<b>");
173     str += getName();
174     str += "</b>";
175     namelabel.set_markup(str);
176     vbox.pack_start(namelabel, true, true);
178     _rcb_visible.init ( _("_Visible"),
179                         _("Determines whether the grid is displayed or not. Objects are still snapped to invisible grids."),
180                          "visible", _wr, false, repr, doc);
181     vbox.pack_start(*dynamic_cast<Gtk::Widget*>(_rcb_visible._button), true, true);
183     _rcb_snap_enabled.init ( _("_Snapping enabled"),
184                         _("Determines whether to snap to this grid or not. Can be 'on' for invisible grids."),
185                          "snap_enabled", _wr, false, repr, doc);
186     vbox.pack_start(*dynamic_cast<Gtk::Widget*>(_rcb_snap_enabled._button), true, true);
189 CanvasGrid::~CanvasGrid()
191     if (repr) {
192         repr->removeListenerByData (this);
193     }
195     while (canvasitems) {
196         gtk_object_destroy(GTK_OBJECT(canvasitems->data));
197         canvasitems = g_slist_remove(canvasitems, canvasitems->data);
198     }
201 const char *
202 CanvasGrid::getName()
204     return _(grid_name[gridtype]);
207 const char *
208 CanvasGrid::getSVGName()
210     return grid_svgname[gridtype];
213 GridType
214 CanvasGrid::getGridType()
216     return gridtype;
220 char const *
221 CanvasGrid::getName(GridType type)
223     return _(grid_name[type]);
226 char const *
227 CanvasGrid::getSVGName(GridType type)
229     return grid_svgname[type];
232 GridType
233 CanvasGrid::getGridTypeFromSVGName(char const *typestr)
235     if (!typestr) return GRID_RECTANGULAR;
237     gint t = 0;
238     for (t = GRID_MAXTYPENR; t >= 0; t--) {  //this automatically defaults to grid0 which is rectangular grid
239         if (!strcmp(typestr, grid_svgname[t])) break;
240     }
241     return (GridType) t;
244 GridType
245 CanvasGrid::getGridTypeFromName(char const *typestr)
247     if (!typestr) return GRID_RECTANGULAR;
249     gint t = 0;
250     for (t = GRID_MAXTYPENR; t >= 0; t--) {  //this automatically defaults to grid0 which is rectangular grid
251         if (!strcmp(typestr, _(grid_name[t]))) break;
252     }
253     return (GridType) t;
257 /*
258 *  writes an <inkscape:grid> child to repr.
259 */
260 void
261 CanvasGrid::writeNewGridToRepr(Inkscape::XML::Node * repr, SPDocument * doc, GridType gridtype)
263     if (!repr) return;
264     if (gridtype > GRID_MAXTYPENR) return;
266     // 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.
268     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
269     Inkscape::XML::Node *newnode;
270     newnode = xml_doc->createElement("inkscape:grid");
271     newnode->setAttribute("type", getSVGName(gridtype));
273     repr->appendChild(newnode);
274 //    Inkscape::GC::release(repr);  FIX THIS. THIS SHOULD BE HERE!!!
276     sp_document_done(doc, SP_VERB_DIALOG_NAMEDVIEW, _("Create new grid"));
279 /*
280 * Creates a new CanvasGrid object of type gridtype
281 */
282 CanvasGrid*
283 CanvasGrid::NewGrid(SPNamedView * nv, Inkscape::XML::Node * repr, SPDocument * doc, GridType gridtype)
285     if (!repr) return NULL;
286     if (!doc) {
287         g_error("CanvasGrid::NewGrid - doc==NULL");
288         return NULL;
289     }
291     switch (gridtype) {
292         case GRID_RECTANGULAR:
293             return (CanvasGrid*) new CanvasXYGrid(nv, repr, doc);
294         case GRID_AXONOMETRIC:
295             return (CanvasGrid*) new CanvasAxonomGrid(nv, repr, doc);
296     }
298     return NULL;
302 /**
303 *  creates a new grid canvasitem for the SPDesktop given as parameter. Keeps a link to this canvasitem in the canvasitems list.
304 */
305 GridCanvasItem *
306 CanvasGrid::createCanvasItem(SPDesktop * desktop)
308     if (!desktop) return NULL;
309 //    Johan: I think for multiple desktops it is best if each has their own canvasitem,
310 //           but share the same CanvasGrid object; that is what this function is for.
312     // check if there is already a canvasitem on this desktop linking to this grid
313     for (GSList *l = canvasitems; l != NULL; l = l->next) {
314         if ( sp_desktop_gridgroup(desktop) == SP_CANVAS_GROUP(SP_CANVAS_ITEM(l->data)->parent) ) {
315             return NULL;
316         }
317     }
319     GridCanvasItem * item = INKSCAPE_GRID_CANVASITEM( sp_canvas_item_new(sp_desktop_gridgroup(desktop), INKSCAPE_TYPE_GRID_CANVASITEM, NULL) );
320     item->grid = this;
321     sp_canvas_item_show(SP_CANVAS_ITEM(item));
323     gtk_object_ref(GTK_OBJECT(item));    // since we're keeping a link to this item, we need to bump up the ref count
324     canvasitems = g_slist_prepend(canvasitems, item);
326     return item;
329 void
330 CanvasGrid::on_repr_attr_changed(Inkscape::XML::Node *repr, gchar const *key, gchar const *oldval, gchar const *newval, bool is_interactive, void *data)
332     if (!data)
333         return;
335     ((CanvasGrid*) data)->onReprAttrChanged(repr, key, oldval, newval, is_interactive);
339 // ##########################################################
340 //   CanvasXYGrid
343 /**
344 * "attach_all" function
345 * A DIRECT COPY-PASTE FROM DOCUMENT-PROPERTIES.CPP  TO QUICKLY GET RESULTS
347  * Helper function that attachs widgets in a 3xn table. The widgets come in an
348  * array that has two entries per table row. The two entries code for four
349  * possible cases: (0,0) means insert space in first column; (0, non-0) means
350  * widget in columns 2-3; (non-0, 0) means label in columns 1-3; and
351  * (non-0, non-0) means two widgets in columns 2 and 3.
352 **/
353 #define SPACE_SIZE_X 15
354 #define SPACE_SIZE_Y 10
355 static inline void
356 attach_all(Gtk::Table &table, Gtk::Widget const *const arr[], unsigned size, int start = 0)
358     for (unsigned i=0, r=start; i<size/sizeof(Gtk::Widget*); i+=2) {
359         if (arr[i] && arr[i+1]) {
360             table.attach (const_cast<Gtk::Widget&>(*arr[i]),   1, 2, r, r+1,
361                           Gtk::FILL|Gtk::EXPAND, (Gtk::AttachOptions)0,0,0);
362             table.attach (const_cast<Gtk::Widget&>(*arr[i+1]), 2, 3, r, r+1,
363                           Gtk::FILL|Gtk::EXPAND, (Gtk::AttachOptions)0,0,0);
364         } else {
365             if (arr[i+1]) {
366                 table.attach (const_cast<Gtk::Widget&>(*arr[i+1]), 1, 3, r, r+1,
367                               Gtk::FILL|Gtk::EXPAND, (Gtk::AttachOptions)0,0,0);
368             } else if (arr[i]) {
369                 Gtk::Label& label = reinterpret_cast<Gtk::Label&> (const_cast<Gtk::Widget&>(*arr[i]));
370                 label.set_alignment (0.0);
371                 table.attach (label, 0, 3, r, r+1,
372                               Gtk::FILL|Gtk::EXPAND, (Gtk::AttachOptions)0,0,0);
373             } else {
374                 Gtk::HBox *space = manage (new Gtk::HBox);
375                 space->set_size_request (SPACE_SIZE_X, SPACE_SIZE_Y);
376                 table.attach (*space, 0, 1, r, r+1,
377                               (Gtk::AttachOptions)0, (Gtk::AttachOptions)0,0,0);
378             }
379         }
380         ++r;
381     }
384 CanvasXYGrid::CanvasXYGrid (SPNamedView * nv, Inkscape::XML::Node * in_repr, SPDocument * in_doc)
385     : CanvasGrid(nv, in_repr, in_doc, GRID_RECTANGULAR), table(1, 1)
387     origin[NR::X] = origin[NR::Y] = 0.0;
388     color = DEFAULTGRIDCOLOR;
389     empcolor = DEFAULTGRIDEMPCOLOR;
390     empspacing = 5;
391     spacing[NR::X] = spacing[NR::Y] = 1.0;
392     gridunit = &sp_unit_get_by_id(SP_UNIT_PX);
393     render_dotted = false;
395     snapper = new CanvasXYGridSnapper(this, namedview, 0);
397     // initialize widgets:
398     vbox.set_border_width(2);
399     table.set_spacings(2);
400     vbox.pack_start(table, false, false, 0);
402     Inkscape::UI::Widget::ScalarUnit * sutemp;
403     _rumg.init (_("Grid _units:"), "units", _wr, repr, doc);
404     _rsu_ox.init (_("_Origin X:"), _("X coordinate of grid origin"),
405                   "originx", _rumg, _wr, repr, doc);
406         sutemp = _rsu_ox.getSU();
407         sutemp->setDigits(4);
408         sutemp->setIncrements(0.1, 1.0);
409     _rsu_oy.init (_("O_rigin Y:"), _("Y coordinate of grid origin"),
410                   "originy", _rumg, _wr, repr, doc);
411         sutemp = _rsu_oy.getSU();
412         sutemp->setDigits(4);
413         sutemp->setIncrements(0.1, 1.0);
414     _rsu_sx.init (_("Spacing _X:"), _("Distance between vertical grid lines"),
415                   "spacingx", _rumg, _wr, repr, doc);
416         sutemp = _rsu_sx.getSU();
417         sutemp->setDigits(4);
418         sutemp->setIncrements(0.1, 1.0);
419     _rsu_sy.init (_("Spacing _Y:"), _("Distance between horizontal grid lines"),
420                   "spacingy", _rumg, _wr, repr, doc);
421         sutemp = _rsu_sy.getSU();
422         sutemp->setDigits(4);
423         sutemp->setIncrements(0.1, 1.0);
424     _rcp_gcol.init (_("Grid line _color:"), _("Grid line color"),
425                     _("Color of grid lines"), "color", "opacity", _wr, repr, doc);
426     _rcp_gmcol.init (_("Ma_jor grid line color:"), _("Major grid line color"),
427                      _("Color of the major (highlighted) grid lines"),
428                      "empcolor", "empopacity", _wr, repr, doc);
429     _rsi.init (_("_Major grid line every:"), _("lines"), "empspacing", _wr, repr, doc);
430     _rcb_dotted.init ( _("_Show dots instead of lines"),
431                        _("If set, displays dots at gridpoints instead of gridlines"),
432                         "dotted", _wr, false, repr, doc);
434     Gtk::Widget const *const widget_array[] = {
435         _rumg._label,       _rumg._sel,
436         0,                  _rsu_ox.getSU(),
437         0,                  _rsu_oy.getSU(),
438         0,                  _rsu_sx.getSU(),
439         0,                  _rsu_sy.getSU(),
440         _rcp_gcol._label,   _rcp_gcol._cp,
441         0,                  0,
442         _rcp_gmcol._label,  _rcp_gmcol._cp,
443         _rsi._label,        &_rsi._hbox,
444         0,                  _rcb_dotted._button,
445     };
447     attach_all (table, widget_array, sizeof(widget_array));
449     vbox.show();
451     if (repr) readRepr();
452     updateWidgets();
455 CanvasXYGrid::~CanvasXYGrid ()
457    if (snapper) delete snapper;
461 /* fixme: Collect all these length parsing methods and think common sane API */
463 static gboolean
464 sp_nv_read_length(gchar const *str, guint base, gdouble *val, SPUnit const **unit)
466     if (!str) {
467         return FALSE;
468     }
470     gchar *u;
471     gdouble v = g_ascii_strtod(str, &u);
472     if (!u) {
473         return FALSE;
474     }
475     while (isspace(*u)) {
476         u += 1;
477     }
479     if (!*u) {
480         /* No unit specified - keep default */
481         *val = v;
482         return TRUE;
483     }
485     if (base & SP_UNIT_DEVICE) {
486         if (u[0] && u[1] && !isalnum(u[2]) && !strncmp(u, "px", 2)) {
487             *unit = &sp_unit_get_by_id(SP_UNIT_PX);
488             *val = v;
489             return TRUE;
490         }
491     }
493     if (base & SP_UNIT_ABSOLUTE) {
494         if (!strncmp(u, "pt", 2)) {
495             *unit = &sp_unit_get_by_id(SP_UNIT_PT);
496         } else if (!strncmp(u, "mm", 2)) {
497             *unit = &sp_unit_get_by_id(SP_UNIT_MM);
498         } else if (!strncmp(u, "cm", 2)) {
499             *unit = &sp_unit_get_by_id(SP_UNIT_CM);
500         } else if (!strncmp(u, "m", 1)) {
501             *unit = &sp_unit_get_by_id(SP_UNIT_M);
502         } else if (!strncmp(u, "in", 2)) {
503             *unit = &sp_unit_get_by_id(SP_UNIT_IN);
504         } else {
505             return FALSE;
506         }
507         *val = v;
508         return TRUE;
509     }
511     return FALSE;
514 static gboolean sp_nv_read_opacity(gchar const *str, guint32 *color)
516     if (!str) {
517         return FALSE;
518     }
520     gchar *u;
521     gdouble v = g_ascii_strtod(str, &u);
522     if (!u) {
523         return FALSE;
524     }
525     v = CLAMP(v, 0.0, 1.0);
527     *color = (*color & 0xffffff00) | (guint32) floor(v * 255.9999);
529     return TRUE;
532 /** If the passed scalar is invalid (<=0), then set the widget and the scalar
533     to use the given old value.
535     @param oldVal Old value to use if the new one is invalid.
536     @param pTarget The scalar to validate.
537     @param widget Widget associated with the scalar.
538 */
539 static void validateScalar(double oldVal,
540                            double* pTarget,
541                            Inkscape::UI::Widget::RegisteredScalarUnit& widget)
543     // Avoid nullness.
544     if ( pTarget == NULL )
545         return;
547     // Invalid new value?
548     if ( *pTarget <= 0 ) {
549         // If the old value is somehow invalid as well, then default to 1.
550         if ( oldVal <= 0 )
551             oldVal = 1;
553         // Reset the scalar and associated widget to the old value.
554         *pTarget = oldVal;
555         widget.setValue( *pTarget);
556     } //if
558 } //validateScalar
561 /** If the passed int is invalid (<=0), then set the widget and the int
562     to use the given old value.
564     @param oldVal Old value to use if the new one is invalid.
565     @param pTarget The int to validate.
566     @param widget Widget associated with the int.
567 */
568 static void validateInt(gint oldVal,
569                         gint* pTarget,
570                         Inkscape::UI::Widget::RegisteredSuffixedInteger& widget)
572     // Avoid nullness.
573     if ( pTarget == NULL )
574         return;
576     // Invalid new value?
577     if ( *pTarget <= 0 ) {
578         // If the old value is somehow invalid as well, then default to 1.
579         if ( oldVal <= 0 )
580             oldVal = 1;
582         // Reset the int and associated widget to the old value.
583         *pTarget = oldVal;
584         widget.setValue( *pTarget);
585     } //if
587 } //validateInt
589 void
590 CanvasXYGrid::readRepr()
592     gchar const *value;
593     if ( (value = repr->attribute("originx")) ) {
594         sp_nv_read_length(value, SP_UNIT_ABSOLUTE | SP_UNIT_DEVICE, &origin[NR::X], &gridunit);
595         origin[NR::X] = sp_units_get_pixels(origin[NR::X], *(gridunit));
596     }
598     if ( (value = repr->attribute("originy")) ) {
599         sp_nv_read_length(value, SP_UNIT_ABSOLUTE | SP_UNIT_DEVICE, &origin[NR::Y], &gridunit);
600         origin[NR::Y] = sp_units_get_pixels(origin[NR::Y], *(gridunit));
601     }
603     if ( (value = repr->attribute("spacingx")) ) {
604         double oldVal = spacing[NR::X];
605         sp_nv_read_length(value, SP_UNIT_ABSOLUTE | SP_UNIT_DEVICE, &spacing[NR::X], &gridunit);
606         validateScalar( oldVal, &spacing[NR::X], _rsu_sx );
607         spacing[NR::X] = sp_units_get_pixels(spacing[NR::X], *(gridunit));
609     }
610     if ( (value = repr->attribute("spacingy")) ) {
611         double oldVal = spacing[NR::Y];
612         sp_nv_read_length(value, SP_UNIT_ABSOLUTE | SP_UNIT_DEVICE, &spacing[NR::Y], &gridunit);
613         validateScalar( oldVal, &spacing[NR::Y], _rsu_sy );
614         spacing[NR::Y] = sp_units_get_pixels(spacing[NR::Y], *(gridunit));
616     }
618     if ( (value = repr->attribute("color")) ) {
619         color = (color & 0xff) | sp_svg_read_color(value, color);
620     }
622     if ( (value = repr->attribute("empcolor")) ) {
623         empcolor = (empcolor & 0xff) | sp_svg_read_color(value, empcolor);
624     }
626     if ( (value = repr->attribute("opacity")) ) {
627         sp_nv_read_opacity(value, &color);
628     }
629     if ( (value = repr->attribute("empopacity")) ) {
630         sp_nv_read_opacity(value, &empcolor);
631     }
633     if ( (value = repr->attribute("empspacing")) ) {
634         gint oldVal = empspacing;
635         empspacing = atoi(value);
636         validateInt( oldVal, &empspacing, _rsi );
637     }
639     if ( (value = repr->attribute("dotted")) ) {
640         render_dotted = (strcmp(value,"true") == 0);
641     }
643     if ( (value = repr->attribute("visible")) ) {
644         visible = (strcmp(value,"true") == 0);
645     }
647     for (GSList *l = canvasitems; l != NULL; l = l->next) {
648         sp_canvas_item_request_update ( SP_CANVAS_ITEM(l->data) );
649     }
651     return;
654 /**
655  * Called when XML node attribute changed; updates dialog widgets if change was not done by widgets themselves.
656  */
657 void
658 CanvasXYGrid::onReprAttrChanged(Inkscape::XML::Node */*repr*/, gchar const */*key*/, gchar const */*oldval*/, gchar const */*newval*/, bool /*is_interactive*/)
660     readRepr();
662     if ( ! (_wr.isUpdating()) )
663         updateWidgets();
669 Gtk::Widget &
670 CanvasXYGrid::getWidget()
672     return vbox;
676 /**
677  * Update dialog widgets from object's values.
678  */
679 void
680 CanvasXYGrid::updateWidgets()
682     if (_wr.isUpdating()) return;
684     _wr.setUpdating (true);
686     _rcb_visible.setActive(visible);
687     _rcb_snap_enabled.setActive(snap_enabled);
689     _rumg.setUnit (gridunit);
691     gdouble val;
692     val = origin[NR::X];
693     val = sp_pixels_get_units (val, *(gridunit));
694     _rsu_ox.setValue (val);
695     val = origin[NR::Y];
696     val = sp_pixels_get_units (val, *(gridunit));
697     _rsu_oy.setValue (val);
698     val = spacing[NR::X];
699     double gridx = sp_pixels_get_units (val, *(gridunit));
700     _rsu_sx.setValue (gridx);
701     val = spacing[NR::Y];
702     double gridy = sp_pixels_get_units (val, *(gridunit));
703     _rsu_sy.setValue (gridy);
705     _rcp_gcol.setRgba32 (color);
706     _rcp_gmcol.setRgba32 (empcolor);
707     _rsi.setValue (empspacing);
709     _rcb_dotted.setActive(render_dotted);
711     _wr.setUpdating (false);
713     return;
718 void
719 CanvasXYGrid::Update (NR::Matrix const &affine, unsigned int /*flags*/)
721     ow = origin * affine;
722     sw = spacing * affine;
723     sw -= NR::Point(affine[4], affine[5]);
725     for(int dim = 0; dim < 2; dim++) {
726         gint scaling_factor = empspacing;
728         if (scaling_factor <= 1)
729             scaling_factor = 5;
731         scaled[dim] = FALSE;
732         sw[dim] = fabs (sw[dim]);
733         while (sw[dim] < 8.0) {
734             scaled[dim] = TRUE;
735             sw[dim] *= scaling_factor;
736             /* First pass, go up to the major line spacing, then
737                keep increasing by two. */
738             scaling_factor = 2;
739         }
740     }
744 static void
745 grid_hline (SPCanvasBuf *buf, gint y, gint xs, gint xe, guint32 rgba)
747     if ((y >= buf->rect.y0) && (y < buf->rect.y1)) {
748         guint r, g, b, a;
749         gint x0, x1, x;
750         guchar *p;
751         r = NR_RGBA32_R (rgba);
752         g = NR_RGBA32_G (rgba);
753         b = NR_RGBA32_B (rgba);
754         a = NR_RGBA32_A (rgba);
755         x0 = MAX (buf->rect.x0, xs);
756         x1 = MIN (buf->rect.x1, xe + 1);
757         p = buf->buf + (y - buf->rect.y0) * buf->buf_rowstride + (x0 - buf->rect.x0) * 3;
758         for (x = x0; x < x1; x++) {
759             p[0] = NR_COMPOSEN11_1111 (r, a, p[0]);
760             p[1] = NR_COMPOSEN11_1111 (g, a, p[1]);
761             p[2] = NR_COMPOSEN11_1111 (b, a, p[2]);
762             p += 3;
763         }
764     }
767 static void
768 grid_vline (SPCanvasBuf *buf, gint x, gint ys, gint ye, guint32 rgba)
770     if ((x >= buf->rect.x0) && (x < buf->rect.x1)) {
771         guint r, g, b, a;
772         gint y0, y1, y;
773         guchar *p;
774         r = NR_RGBA32_R(rgba);
775         g = NR_RGBA32_G (rgba);
776         b = NR_RGBA32_B (rgba);
777         a = NR_RGBA32_A (rgba);
778         y0 = MAX (buf->rect.y0, ys);
779         y1 = MIN (buf->rect.y1, ye + 1);
780         p = buf->buf + (y0 - buf->rect.y0) * buf->buf_rowstride + (x - buf->rect.x0) * 3;
781         for (y = y0; y < y1; y++) {
782             p[0] = NR_COMPOSEN11_1111 (r, a, p[0]);
783             p[1] = NR_COMPOSEN11_1111 (g, a, p[1]);
784             p[2] = NR_COMPOSEN11_1111 (b, a, p[2]);
785             p += buf->buf_rowstride;
786         }
787     }
790 static void
791 grid_dot (SPCanvasBuf *buf, gint x, gint y, guint32 rgba)
793     if ( (y >= buf->rect.y0) && (y < buf->rect.y1)
794          && (x >= buf->rect.x0) && (x < buf->rect.x1) ) {
795         guint r, g, b, a;
796         guchar *p;
797         r = NR_RGBA32_R (rgba);
798         g = NR_RGBA32_G (rgba);
799         b = NR_RGBA32_B (rgba);
800         a = NR_RGBA32_A (rgba);
801         p = buf->buf + (y - buf->rect.y0) * buf->buf_rowstride + (x - buf->rect.x0) * 3;
802         p[0] = NR_COMPOSEN11_1111 (r, a, p[0]);
803         p[1] = NR_COMPOSEN11_1111 (g, a, p[1]);
804         p[2] = NR_COMPOSEN11_1111 (b, a, p[2]);
805     }
808 void
809 CanvasXYGrid::Render (SPCanvasBuf *buf)
811     gdouble const sxg = floor ((buf->rect.x0 - ow[NR::X]) / sw[NR::X]) * sw[NR::X] + ow[NR::X];
812     gint const  xlinestart = (gint) Inkscape::round((sxg - ow[NR::X]) / sw[NR::X]);
813     gdouble const syg = floor ((buf->rect.y0 - ow[NR::Y]) / sw[NR::Y]) * sw[NR::Y] + ow[NR::Y];
814     gint const  ylinestart = (gint) Inkscape::round((syg - ow[NR::Y]) / sw[NR::Y]);
816     if (!render_dotted) {
817         gint ylinenum;
818         gdouble y;
819         for (y = syg, ylinenum = ylinestart; y < buf->rect.y1; y += sw[NR::Y], ylinenum++) {
820             gint const y0 = (gint) Inkscape::round(y);
822             if (!scaled[NR::Y] && (ylinenum % empspacing) == 0) {
823                 grid_hline (buf, y0, buf->rect.x0, buf->rect.x1 - 1, empcolor);
824             } else {
825                 grid_hline (buf, y0, buf->rect.x0, buf->rect.x1 - 1, color);
826             }
827         }
829         gint xlinenum;
830         gdouble x;
831         for (x = sxg, xlinenum = xlinestart; x < buf->rect.x1; x += sw[NR::X], xlinenum++) {
832             gint const ix = (gint) Inkscape::round(x);
833             if (!scaled[NR::X] && (xlinenum % empspacing) == 0) {
834                 grid_vline (buf, ix, buf->rect.y0, buf->rect.y1, empcolor);
835             } else {
836                 grid_vline (buf, ix, buf->rect.y0, buf->rect.y1, color);
837             }
838         }
839     } else {
840         gint ylinenum;
841         gdouble y;
842         for (y = syg, ylinenum = ylinestart; y < buf->rect.y1; y += sw[NR::Y], ylinenum++) {
843             gint const iy = (gint) Inkscape::round(y);
845             gint xlinenum;
846             gdouble x;
847             for (x = sxg, xlinenum = xlinestart; x < buf->rect.x1; x += sw[NR::X], xlinenum++) {
848                 gint const ix = (gint) Inkscape::round(x);
849                 if ( (!scaled[NR::X] && (xlinenum % empspacing) == 0)
850                      || (!scaled[NR::Y] && (ylinenum % empspacing) == 0) )
851                 {
852                     grid_dot (buf, ix, iy, empcolor | (guint32)0x000000FF); // put alpha to max value
853                 } else {
854                     grid_dot (buf, ix, iy, color | (guint32)0x000000FF);  // put alpha to max value
855                 }
856             }
858         }
859     }
865 /**
866  * \return x rounded to the nearest multiple of c1 plus c0.
867  *
868  * \note
869  * If c1==0 (and c0 is finite), then returns +/-inf.  This makes grid spacing of zero
870  * mean "ignore the grid in this dimention".  We're currently discussing "good" semantics
871  * for guide/grid snapping.
872  */
874 /* FIXME: move this somewhere else, perhaps */
875 static double round_to_nearest_multiple_plus(double x, double const c1, double const c0)
877     return floor((x - c0) / c1 + .5) * c1 + c0;
880 CanvasXYGridSnapper::CanvasXYGridSnapper(CanvasXYGrid *grid, SPNamedView const *nv, NR::Coord const d) : LineSnapper(nv, d)
882     this->grid = grid;
885 LineSnapper::LineList
886 CanvasXYGridSnapper::_getSnapLines(NR::Point const &p) const
888     LineList s;
890     if ( grid == NULL ) {
891         return s;
892     }
894     for (unsigned int i = 0; i < 2; ++i) {
896         /* This is to make sure we snap to only visible grid lines */
897         double scaled_spacing = grid->sw[i]; // this is spacing of visible lines if screen pixels
899         // convert screen pixels to px
900         // FIXME: after we switch to snapping dist in screen pixels, this will be unnecessary
901         if (SP_ACTIVE_DESKTOP) {
902             scaled_spacing /= SP_ACTIVE_DESKTOP->current_zoom();
903         }
905         NR::Coord const rounded = round_to_nearest_multiple_plus(p[i],
906                                                                  scaled_spacing,
907                                                                  grid->origin[i]);
909         s.push_back(std::make_pair(NR::Dim2(i), rounded));
910     }
912     return s;
915 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 
917     SnappedLine dummy = SnappedLine(snapped_point, snapped_distance, normal_to_line, point_on_line);
918     sc.grid_lines.push_back(dummy);
924 }; /* namespace Inkscape */
927 /*
928   Local Variables:
929   mode:c++
930   c-file-style:"stroustrup"
931   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
932   indent-tabs-mode:nil
933   fill-column:99
934   End:
935 */
936 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :