Code

Split SPCanvasItem and SPCanvasGroup to individual .h files. Removed forward header.
[inkscape.git] / src / display / canvas-grid.cpp
1 /** @file
2  * @brief Cartesian grid implementation
3  */
4 /* Copyright (C) Johan Engelen 2006-2007 <johan@shouraizou.nl>
5  * Copyright (C) Lauris Kaplinski 2000
6  *   Abhishek Sharma
7  */
9 /* As a general comment, I am not exactly proud of how things are done.
10  * (for example the 'enable' widget and readRepr things)
11  * It does seem to work however. I intend to clean up and sort things out later, but that can take forever...
12  * Don't be shy to correct things.
13  */
15 #include "sp-canvas-group.h"
16 #include "sp-canvas-util.h"
17 #include "util/mathfns.h"
18 #include "libnr/nr-pixops.h"
19 #include "desktop-handles.h"
20 #include "helper/units.h"
21 #include "svg/svg-color.h"
22 #include "xml/node-event-vector.h"
23 #include "sp-object.h"
25 #include "sp-namedview.h"
26 #include "inkscape.h"
27 #include "desktop.h"
29 #include "../document.h"
30 #include "preferences.h"
32 #include "canvas-grid.h"
33 #include "canvas-axonomgrid.h"
35 using Inkscape::DocumentUndo;
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, Geom::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             (gchar *)"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, Geom::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 = doc->getReprDoc();
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     DocumentUndo::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) );
329     Inkscape::UI::Widget::RegisteredCheckButton * _rcb_snap_visible_only = Gtk::manage(
330             new Inkscape::UI::Widget::RegisteredCheckButton( _("Snap to visible _grid lines only"),
331                             _("When zoomed out, not all grid lines will be displayed. Only the visible ones will be snapped to"),
332                              "snapvisiblegridlinesonly", _wr, true, repr, doc) );
334     Inkscape::UI::Widget::RegisteredCheckButton * _rcb_visible = Gtk::manage(
335         new Inkscape::UI::Widget::RegisteredCheckButton( _("_Visible"),
336                         _("Determines whether the grid is displayed or not. Objects are still snapped to invisible grids."),
337                          "visible", _wr, true, repr, doc) );
339     vbox->pack_start(*_rcb_enabled, true, true);
340     vbox->pack_start(*_rcb_visible, true, true);
341     vbox->pack_start(*_rcb_snap_visible_only, true, true);
342     Gtk::Widget * gridwdg = newSpecificWidget();
343     vbox->pack_start(*gridwdg, true, true);
345     std::list<Gtk::Widget*> slaves;
346     slaves.push_back(_rcb_visible);
347     slaves.push_back(_rcb_snap_visible_only);
348     slaves.push_back(gridwdg);
349     _rcb_enabled->setSlaveWidgets(slaves);
351     // set widget values
352     _rcb_visible->setActive(visible);
353     if (snapper != NULL) {
354         _rcb_enabled->setActive(snapper->getEnabled());
355         _rcb_snap_visible_only->setActive(snapper->getSnapVisibleOnly());
356     }
358     return dynamic_cast<Gtk::Widget *> (vbox);
361 void
362 CanvasGrid::on_repr_attr_changed(Inkscape::XML::Node *repr, gchar const *key, gchar const *oldval, gchar const *newval, bool is_interactive, void *data)
364     if (!data)
365         return;
367     ((CanvasGrid*) data)->onReprAttrChanged(repr, key, oldval, newval, is_interactive);
370 bool CanvasGrid::isEnabled()
372     if (snapper == NULL) {
373        return false;
374     }
376     return snapper->getEnabled();
379 // ##########################################################
380 //   CanvasXYGrid
383 /**
384 * "attach_all" function
385 * A DIRECT COPY-PASTE FROM DOCUMENT-PROPERTIES.CPP  TO QUICKLY GET RESULTS
387  * Helper function that attachs widgets in a 3xn table. The widgets come in an
388  * array that has two entries per table row. The two entries code for four
389  * possible cases: (0,0) means insert space in first column; (0, non-0) means
390  * widget in columns 2-3; (non-0, 0) means label in columns 1-3; and
391  * (non-0, non-0) means two widgets in columns 2 and 3.
392 **/
393 #define SPACE_SIZE_X 15
394 #define SPACE_SIZE_Y 10
395 static inline void
396 attach_all(Gtk::Table &table, Gtk::Widget const *const arr[], unsigned size, int start = 0)
398     for (unsigned i=0, r=start; i<size/sizeof(Gtk::Widget*); i+=2) {
399         if (arr[i] && arr[i+1]) {
400             table.attach (const_cast<Gtk::Widget&>(*arr[i]),   1, 2, r, r+1,
401                           Gtk::FILL|Gtk::EXPAND, (Gtk::AttachOptions)0,0,0);
402             table.attach (const_cast<Gtk::Widget&>(*arr[i+1]), 2, 3, r, r+1,
403                           Gtk::FILL|Gtk::EXPAND, (Gtk::AttachOptions)0,0,0);
404         } else {
405             if (arr[i+1]) {
406                 table.attach (const_cast<Gtk::Widget&>(*arr[i+1]), 1, 3, r, r+1,
407                               Gtk::FILL|Gtk::EXPAND, (Gtk::AttachOptions)0,0,0);
408             } else if (arr[i]) {
409                 Gtk::Label& label = reinterpret_cast<Gtk::Label&> (const_cast<Gtk::Widget&>(*arr[i]));
410                 label.set_alignment (0.0);
411                 table.attach (label, 0, 3, r, r+1,
412                               Gtk::FILL|Gtk::EXPAND, (Gtk::AttachOptions)0,0,0);
413             } else {
414                 Gtk::HBox *space = manage (new Gtk::HBox);
415                 space->set_size_request (SPACE_SIZE_X, SPACE_SIZE_Y);
416                 table.attach (*space, 0, 1, r, r+1,
417                               (Gtk::AttachOptions)0, (Gtk::AttachOptions)0,0,0);
418             }
419         }
420         ++r;
421     }
424 CanvasXYGrid::CanvasXYGrid (SPNamedView * nv, Inkscape::XML::Node * in_repr, SPDocument * in_doc)
425     : CanvasGrid(nv, in_repr, in_doc, GRID_RECTANGULAR)
427     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
428     gridunit = sp_unit_get_by_abbreviation( prefs->getString("/options/grids/xy/units").data() );
429     if (!gridunit)
430         gridunit = &sp_unit_get_by_id(SP_UNIT_PX);
431     origin[Geom::X] = sp_units_get_pixels(prefs->getDouble("/options/grids/xy/origin_x", 0.0), *gridunit);
432     origin[Geom::Y] = sp_units_get_pixels(prefs->getDouble("/options/grids/xy/origin_y", 0.0), *gridunit);
433     color = prefs->getInt("/options/grids/xy/color", 0x0000ff20);
434     empcolor = prefs->getInt("/options/grids/xy/empcolor", 0x0000ff40);
435     empspacing = prefs->getInt("/options/grids/xy/empspacing", 5);
436     spacing[Geom::X] = sp_units_get_pixels(prefs->getDouble("/options/grids/xy/spacing_x", 0.0), *gridunit);
437     spacing[Geom::Y] = sp_units_get_pixels(prefs->getDouble("/options/grids/xy/spacing_y", 0.0), *gridunit);
438     render_dotted = prefs->getBool("/options/grids/xy/dotted", false);
440     snapper = new CanvasXYGridSnapper(this, &namedview->snap_manager, 0);
442     if (repr) readRepr();
445 CanvasXYGrid::~CanvasXYGrid ()
447    if (snapper) delete snapper;
451 /* fixme: Collect all these length parsing methods and think common sane API */
453 static gboolean
454 sp_nv_read_length(gchar const *str, guint base, gdouble *val, SPUnit const **unit)
456     if (!str) {
457         return FALSE;
458     }
460     gchar *u;
461     gdouble v = g_ascii_strtod(str, &u);
462     if (!u) {
463         return FALSE;
464     }
465     while (isspace(*u)) {
466         u += 1;
467     }
469     if (!*u) {
470         /* No unit specified - keep default */
471         *val = v;
472         return TRUE;
473     }
475     if (base & SP_UNIT_DEVICE) {
476         if (u[0] && u[1] && !isalnum(u[2]) && !strncmp(u, "px", 2)) {
477             *unit = &sp_unit_get_by_id(SP_UNIT_PX);
478             *val = v;
479             return TRUE;
480         }
481     }
483     if (base & SP_UNIT_ABSOLUTE) {
484         if (!strncmp(u, "pt", 2)) {
485             *unit = &sp_unit_get_by_id(SP_UNIT_PT);
486         } else if (!strncmp(u, "mm", 2)) {
487             *unit = &sp_unit_get_by_id(SP_UNIT_MM);
488         } else if (!strncmp(u, "cm", 2)) {
489             *unit = &sp_unit_get_by_id(SP_UNIT_CM);
490         } else if (!strncmp(u, "m", 1)) {
491             *unit = &sp_unit_get_by_id(SP_UNIT_M);
492         } else if (!strncmp(u, "in", 2)) {
493             *unit = &sp_unit_get_by_id(SP_UNIT_IN);
494         } else {
495             return FALSE;
496         }
497         *val = v;
498         return TRUE;
499     }
501     return FALSE;
504 static gboolean sp_nv_read_opacity(gchar const *str, guint32 *color)
506     if (!str) {
507         return FALSE;
508     }
510     gchar *u;
511     gdouble v = g_ascii_strtod(str, &u);
512     if (!u) {
513         return FALSE;
514     }
515     v = CLAMP(v, 0.0, 1.0);
517     *color = (*color & 0xffffff00) | (guint32) floor(v * 255.9999);
519     return TRUE;
522 /** If the passed scalar is invalid (<=0), then set the widget and the scalar
523     to use the given old value.
525     @param oldVal Old value to use if the new one is invalid.
526     @param pTarget The scalar to validate.
527     @param widget Widget associated with the scalar.
528 */
529 static void validateScalar(double oldVal,
530                            double* pTarget)
532     // Avoid nullness.
533     if ( pTarget == NULL )
534         return;
536     // Invalid new value?
537     if ( *pTarget <= 0 ) {
538         // If the old value is somehow invalid as well, then default to 1.
539         if ( oldVal <= 0 )
540             oldVal = 1;
542         // Reset the scalar and associated widget to the old value.
543         *pTarget = oldVal;
544     } //if
546 } //validateScalar
549 /** If the passed int is invalid (<=0), then set the widget and the int
550     to use the given old value.
552     @param oldVal Old value to use if the new one is invalid.
553     @param pTarget The int to validate.
554     @param widget Widget associated with the int.
555 */
556 static void validateInt(gint oldVal,
557                         gint* pTarget)
559     // Avoid nullness.
560     if ( pTarget == NULL )
561         return;
563     // Invalid new value?
564     if ( *pTarget <= 0 ) {
565         // If the old value is somehow invalid as well, then default to 1.
566         if ( oldVal <= 0 )
567             oldVal = 1;
569         // Reset the int and associated widget to the old value.
570         *pTarget = oldVal;
571     } //if
573 } //validateInt
575 void
576 CanvasXYGrid::readRepr()
578     gchar const *value;
579     if ( (value = repr->attribute("originx")) ) {
580         sp_nv_read_length(value, SP_UNIT_ABSOLUTE | SP_UNIT_DEVICE, &origin[Geom::X], &gridunit);
581         origin[Geom::X] = sp_units_get_pixels(origin[Geom::X], *(gridunit));
582     }
584     if ( (value = repr->attribute("originy")) ) {
585         sp_nv_read_length(value, SP_UNIT_ABSOLUTE | SP_UNIT_DEVICE, &origin[Geom::Y], &gridunit);
586         origin[Geom::Y] = sp_units_get_pixels(origin[Geom::Y], *(gridunit));
587     }
589     if ( (value = repr->attribute("spacingx")) ) {
590         double oldVal = spacing[Geom::X];
591         sp_nv_read_length(value, SP_UNIT_ABSOLUTE | SP_UNIT_DEVICE, &spacing[Geom::X], &gridunit);
592         validateScalar( oldVal, &spacing[Geom::X]);
593         spacing[Geom::X] = sp_units_get_pixels(spacing[Geom::X], *(gridunit));
595     }
596     if ( (value = repr->attribute("spacingy")) ) {
597         double oldVal = spacing[Geom::Y];
598         sp_nv_read_length(value, SP_UNIT_ABSOLUTE | SP_UNIT_DEVICE, &spacing[Geom::Y], &gridunit);
599         validateScalar( oldVal, &spacing[Geom::Y]);
600         spacing[Geom::Y] = sp_units_get_pixels(spacing[Geom::Y], *(gridunit));
602     }
604     if ( (value = repr->attribute("color")) ) {
605         color = (color & 0xff) | sp_svg_read_color(value, color);
606     }
608     if ( (value = repr->attribute("empcolor")) ) {
609         empcolor = (empcolor & 0xff) | sp_svg_read_color(value, empcolor);
610     }
612     if ( (value = repr->attribute("opacity")) ) {
613         sp_nv_read_opacity(value, &color);
614     }
615     if ( (value = repr->attribute("empopacity")) ) {
616         sp_nv_read_opacity(value, &empcolor);
617     }
619     if ( (value = repr->attribute("empspacing")) ) {
620         gint oldVal = empspacing;
621         empspacing = atoi(value);
622         validateInt( oldVal, &empspacing);
623     }
625     if ( (value = repr->attribute("dotted")) ) {
626         render_dotted = (strcmp(value,"false") != 0 && strcmp(value, "0") != 0);
627     }
629     if ( (value = repr->attribute("visible")) ) {
630         visible = (strcmp(value,"false") != 0 && strcmp(value, "0") != 0);
631     }
633     if ( (value = repr->attribute("enabled")) ) {
634         g_assert(snapper != NULL);
635         snapper->setEnabled(strcmp(value,"false") != 0 && strcmp(value, "0") != 0);
636     }
638     if ( (value = repr->attribute("snapvisiblegridlinesonly")) ) {
639         g_assert(snapper != NULL);
640         snapper->setSnapVisibleOnly(strcmp(value,"false") != 0 && strcmp(value, "0") != 0);
641     }
643     for (GSList *l = canvasitems; l != NULL; l = l->next) {
644         sp_canvas_item_request_update ( SP_CANVAS_ITEM(l->data) );
645     }
647     return;
650 /**
651  * Called when XML node attribute changed; updates dialog widgets if change was not done by widgets themselves.
652  */
653 void
654 CanvasXYGrid::onReprAttrChanged(Inkscape::XML::Node */*repr*/, gchar const */*key*/, gchar const */*oldval*/, gchar const */*newval*/, bool /*is_interactive*/)
656     readRepr();
658     if ( ! (_wr.isUpdating()) )
659         updateWidgets();
665 Gtk::Widget *
666 CanvasXYGrid::newSpecificWidget()
668     Gtk::Table * table = Gtk::manage( new Gtk::Table(1,1) );
670     Inkscape::UI::Widget::RegisteredUnitMenu *_rumg = Gtk::manage( new Inkscape::UI::Widget::RegisteredUnitMenu(
671             _("Grid _units:"), "units", _wr, repr, doc) );
672     Inkscape::UI::Widget::RegisteredScalarUnit *_rsu_ox = Gtk::manage( new Inkscape::UI::Widget::RegisteredScalarUnit(
673             _("_Origin X:"), _("X coordinate of grid origin"), "originx", *_rumg, _wr, repr, doc) );
674     Inkscape::UI::Widget::RegisteredScalarUnit *_rsu_oy = Gtk::manage( new Inkscape::UI::Widget::RegisteredScalarUnit(
675             _("O_rigin Y:"), _("Y coordinate of grid origin"), "originy", *_rumg, _wr, repr, doc) );
676     Inkscape::UI::Widget::RegisteredScalarUnit *_rsu_sx = Gtk::manage( new Inkscape::UI::Widget::RegisteredScalarUnit(
677             _("Spacing _X:"), _("Distance between vertical grid lines"), "spacingx", *_rumg, _wr, repr, doc) );
678     Inkscape::UI::Widget::RegisteredScalarUnit *_rsu_sy = Gtk::manage( new Inkscape::UI::Widget::RegisteredScalarUnit(
679             _("Spacing _Y:"), _("Distance between horizontal grid lines"), "spacingy", *_rumg, _wr, repr, doc) );
681     Inkscape::UI::Widget::RegisteredColorPicker *_rcp_gcol = Gtk::manage(
682         new Inkscape::UI::Widget::RegisteredColorPicker(
683             _("Grid line _color:"), _("Grid line color"), _("Color of grid lines"),
684             "color", "opacity", _wr, repr, doc));
686     Inkscape::UI::Widget::RegisteredColorPicker *_rcp_gmcol = Gtk::manage(
687         new Inkscape::UI::Widget::RegisteredColorPicker(
688             _("Ma_jor grid line color:"), _("Major grid line color"),
689             _("Color of the major (highlighted) grid lines"), "empcolor", "empopacity",
690             _wr, repr, doc));
692     Inkscape::UI::Widget::RegisteredSuffixedInteger *_rsi = Gtk::manage( new Inkscape::UI::Widget::RegisteredSuffixedInteger(
693             _("_Major grid line every:"), "", _("lines"), "empspacing", _wr, repr, doc) );
695     table->set_spacings(2);
697 _wr.setUpdating (true);
699     _rsu_ox->setDigits(4);
700     _rsu_ox->setIncrements(0.1, 1.0);
702     _rsu_oy->setDigits(4);
703     _rsu_oy->setIncrements(0.1, 1.0);
705     _rsu_sx->setDigits(4);
706     _rsu_sx->setIncrements(0.1, 1.0);
708     _rsu_sy->setDigits(4);
709     _rsu_sy->setIncrements(0.1, 1.0);
711     Inkscape::UI::Widget::RegisteredCheckButton * _rcb_dotted = Gtk::manage(
712                 new Inkscape::UI::Widget::RegisteredCheckButton( _("_Show dots instead of lines"),
713                        _("If set, displays dots at gridpoints instead of gridlines"),
714                         "dotted", _wr, false, repr, doc) );
715 _wr.setUpdating (false);
717     Gtk::Widget const *const widget_array[] = {
718         0,                  _rumg,
719         0,                  _rsu_ox,
720         0,                  _rsu_oy,
721         0,                  _rsu_sx,
722         0,                  _rsu_sy,
723         _rcp_gcol->_label,   _rcp_gcol,
724         0,                  0,
725         _rcp_gmcol->_label,  _rcp_gmcol,
726         0,                  _rsi,
727         0,                  _rcb_dotted,
728     };
730     attach_all (*table, widget_array, sizeof(widget_array));
732     // set widget values
733     _rumg->setUnit (gridunit);
735     gdouble val;
736     val = origin[Geom::X];
737     val = sp_pixels_get_units (val, *(gridunit));
738     _rsu_ox->setValue (val);
739     val = origin[Geom::Y];
740     val = sp_pixels_get_units (val, *(gridunit));
741     _rsu_oy->setValue (val);
742     val = spacing[Geom::X];
743     double gridx = sp_pixels_get_units (val, *(gridunit));
744     _rsu_sx->setValue (gridx);
745     val = spacing[Geom::Y];
746     double gridy = sp_pixels_get_units (val, *(gridunit));
747     _rsu_sy->setValue (gridy);
749     _rcp_gcol->setRgba32 (color);
750     _rcp_gmcol->setRgba32 (empcolor);
751     _rsi->setValue (empspacing);
753     _rcb_dotted->setActive(render_dotted);
755     return table;
759 /**
760  * Update dialog widgets from object's values.
761  */
762 void
763 CanvasXYGrid::updateWidgets()
765 /*
766     if (_wr.isUpdating()) return;
768     _wr.setUpdating (true);
770     _rcb_visible.setActive(visible);
771     if (snapper != NULL) {
772         _rcb_enabled.setActive(snapper->getEnabled());
773     }
775     _rumg.setUnit (gridunit);
777     gdouble val;
778     val = origin[Geom::X];
779     val = sp_pixels_get_units (val, *(gridunit));
780     _rsu_ox.setValue (val);
781     val = origin[Geom::Y];
782     val = sp_pixels_get_units (val, *(gridunit));
783     _rsu_oy.setValue (val);
784     val = spacing[Geom::X];
785     double gridx = sp_pixels_get_units (val, *(gridunit));
786     _rsu_sx.setValue (gridx);
787     val = spacing[Geom::Y];
788     double gridy = sp_pixels_get_units (val, *(gridunit));
789     _rsu_sy.setValue (gridy);
791     _rcp_gcol.setRgba32 (color);
792     _rcp_gmcol.setRgba32 (empcolor);
793     _rsi.setValue (empspacing);
795     _rcb_dotted.setActive(render_dotted);
797     _wr.setUpdating (false);
799     return;
800 */
805 void
806 CanvasXYGrid::Update (Geom::Matrix const &affine, unsigned int /*flags*/)
808     ow = origin * affine;
809     sw = spacing * affine;
810     sw -= Geom::Point(affine[4], affine[5]);
812     for(int dim = 0; dim < 2; dim++) {
813         gint scaling_factor = empspacing;
815         if (scaling_factor <= 1)
816             scaling_factor = 5;
818         scaled[dim] = FALSE;
819         sw[dim] = fabs (sw[dim]);
820         while (sw[dim] < 8.0) {
821             scaled[dim] = TRUE;
822             sw[dim] *= scaling_factor;
823             /* First pass, go up to the major line spacing, then
824                keep increasing by two. */
825             scaling_factor = 2;
826         }
827     }
831 static void
832 grid_hline (SPCanvasBuf *buf, gint y, gint xs, gint xe, guint32 rgba)
834     if ((y >= buf->rect.y0) && (y < buf->rect.y1)) {
835         guint r, g, b, a;
836         gint x0, x1, x;
837         guchar *p;
838         r = NR_RGBA32_R (rgba);
839         g = NR_RGBA32_G (rgba);
840         b = NR_RGBA32_B (rgba);
841         a = NR_RGBA32_A (rgba);
842         x0 = MAX (buf->rect.x0, xs);
843         x1 = MIN (buf->rect.x1, xe + 1);
844         p = buf->buf + (y - buf->rect.y0) * buf->buf_rowstride + (x0 - buf->rect.x0) * 4;
845         for (x = x0; x < x1; x++) {
846             p[0] = NR_COMPOSEN11_1111 (r, a, p[0]);
847             p[1] = NR_COMPOSEN11_1111 (g, a, p[1]);
848             p[2] = NR_COMPOSEN11_1111 (b, a, p[2]);
849             p += 4;
850         }
851     }
854 static void
855 grid_vline (SPCanvasBuf *buf, gint x, gint ys, gint ye, guint32 rgba)
857     if ((x >= buf->rect.x0) && (x < buf->rect.x1)) {
858         guint r, g, b, a;
859         gint y0, y1, y;
860         guchar *p;
861         r = NR_RGBA32_R(rgba);
862         g = NR_RGBA32_G (rgba);
863         b = NR_RGBA32_B (rgba);
864         a = NR_RGBA32_A (rgba);
865         y0 = MAX (buf->rect.y0, ys);
866         y1 = MIN (buf->rect.y1, ye + 1);
867         p = buf->buf + (y0 - buf->rect.y0) * buf->buf_rowstride + (x - buf->rect.x0) * 4;
868         for (y = y0; y < y1; y++) {
869             p[0] = NR_COMPOSEN11_1111 (r, a, p[0]);
870             p[1] = NR_COMPOSEN11_1111 (g, a, p[1]);
871             p[2] = NR_COMPOSEN11_1111 (b, a, p[2]);
872             p += buf->buf_rowstride;
873         }
874     }
877 static void
878 grid_dot (SPCanvasBuf *buf, gint x, gint y, guint32 rgba)
880     if ( (y >= buf->rect.y0) && (y < buf->rect.y1)
881          && (x >= buf->rect.x0) && (x < buf->rect.x1) ) {
882         guint r, g, b, a;
883         guchar *p;
884         r = NR_RGBA32_R (rgba);
885         g = NR_RGBA32_G (rgba);
886         b = NR_RGBA32_B (rgba);
887         a = NR_RGBA32_A (rgba);
888         p = buf->buf + (y - buf->rect.y0) * buf->buf_rowstride + (x - buf->rect.x0) * 4;
889         p[0] = NR_COMPOSEN11_1111 (r, a, p[0]);
890         p[1] = NR_COMPOSEN11_1111 (g, a, p[1]);
891         p[2] = NR_COMPOSEN11_1111 (b, a, p[2]);
892     }
895 void
896 CanvasXYGrid::Render (SPCanvasBuf *buf)
898     gdouble const sxg = floor ((buf->rect.x0 - ow[Geom::X]) / sw[Geom::X]) * sw[Geom::X] + ow[Geom::X];
899     gint const  xlinestart = (gint) Inkscape::round((sxg - ow[Geom::X]) / sw[Geom::X]);
900     gdouble const syg = floor ((buf->rect.y0 - ow[Geom::Y]) / sw[Geom::Y]) * sw[Geom::Y] + ow[Geom::Y];
901     gint const  ylinestart = (gint) Inkscape::round((syg - ow[Geom::Y]) / sw[Geom::Y]);
903     //set correct coloring, depending preference (when zoomed out, always major coloring or minor coloring)
904     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
905     guint32 _empcolor;
906     bool no_emp_when_zoomed_out = prefs->getBool("/options/grids/no_emphasize_when_zoomedout", false);
907     if( (scaled[Geom::X] || scaled[Geom::Y]) && no_emp_when_zoomed_out ) {
908         _empcolor = color;
909     } else {
910         _empcolor = empcolor;
911     }
913     if (!render_dotted) {
914         gint ylinenum;
915         gdouble y;
916         for (y = syg, ylinenum = ylinestart; y < buf->rect.y1; y += sw[Geom::Y], ylinenum++) {
917             gint const y0 = (gint) Inkscape::round(y);
918             if (!scaled[Geom::Y] && (ylinenum % empspacing) != 0) {
919                 grid_hline (buf, y0, buf->rect.x0, buf->rect.x1 - 1, color);
920             } else {
921                 grid_hline (buf, y0, buf->rect.x0, buf->rect.x1 - 1, _empcolor);
922             }
923         }
925         gint xlinenum;
926         gdouble x;
927         for (x = sxg, xlinenum = xlinestart; x < buf->rect.x1; x += sw[Geom::X], xlinenum++) {
928             gint const ix = (gint) Inkscape::round(x);
929             if (!scaled[Geom::X] && (xlinenum % empspacing) != 0) {
930                 grid_vline (buf, ix, buf->rect.y0, buf->rect.y1, color);
931             } else {
932                 grid_vline (buf, ix, buf->rect.y0, buf->rect.y1, _empcolor);
933             }
934         }
935     } else {
936         gint ylinenum;
937         gdouble y;
938         for (y = syg, ylinenum = ylinestart; y < buf->rect.y1; y += sw[Geom::Y], ylinenum++) {
939             gint const iy = (gint) Inkscape::round(y);
941             gint xlinenum;
942             gdouble x;
943             for (x = sxg, xlinenum = xlinestart; x < buf->rect.x1; x += sw[Geom::X], xlinenum++) {
944                 gint const ix = (gint) Inkscape::round(x);
945                 if ( (!scaled[Geom::X] && (xlinenum % empspacing) != 0)
946                      || (!scaled[Geom::Y] && (ylinenum % empspacing) != 0)
947                      || ((scaled[Geom::X] || scaled[Geom::Y]) && no_emp_when_zoomed_out) )
948                 {
949                     grid_dot (buf, ix, iy, color | (guint32)0x000000FF); // put alpha to max value
950                 } else {
951                     gint const pitch = 1;
952                     grid_dot (buf, ix-pitch, iy, _empcolor);
953                     grid_dot (buf, ix+pitch, iy, _empcolor);
955                     grid_dot (buf, ix, iy, _empcolor | (guint32)0x000000FF);  // put alpha to max value
957                     grid_dot (buf, ix, iy-pitch, _empcolor);
958                     grid_dot (buf, ix, iy+pitch, _empcolor);
959                 }
960             }
962         }
963     }
966 CanvasXYGridSnapper::CanvasXYGridSnapper(CanvasXYGrid *grid, SnapManager *sm, Geom::Coord const d) : LineSnapper(sm, d)
968     this->grid = grid;
971 /**
972  *  \return Snap tolerance (desktop coordinates); depends on current zoom so that it's always the same in screen pixels
973  */
974 Geom::Coord CanvasXYGridSnapper::getSnapperTolerance() const
976     SPDesktop const *dt = _snapmanager->getDesktop();
977     double const zoom =  dt ? dt->current_zoom() : 1;
978     return _snapmanager->snapprefs.getGridTolerance() / zoom;
981 bool CanvasXYGridSnapper::getSnapperAlwaysSnap() const
983     return _snapmanager->snapprefs.getGridTolerance() == 10000; //TODO: Replace this threshold of 10000 by a constant; see also tolerance-slider.cpp
986 LineSnapper::LineList
987 CanvasXYGridSnapper::_getSnapLines(Geom::Point const &p) const
989     LineList s;
991     if ( grid == NULL ) {
992         return s;
993     }
995     for (unsigned int i = 0; i < 2; ++i) {
997         double spacing;
999         if (getSnapVisibleOnly()) {
1000             // Only snapping to visible grid lines
1001             spacing = grid->sw[i]; // this is the spacing of the visible grid lines measured in screen pixels
1002             // convert screen pixels to px
1003             // FIXME: after we switch to snapping dist in screen pixels, this will be unnecessary
1004             SPDesktop const *dt = _snapmanager->getDesktop();
1005             if (dt) {
1006                 spacing /= dt->current_zoom();
1007             }
1008         } else {
1009             // Snapping to any grid line, whether it's visible or not
1010             spacing = grid->spacing[i];
1011         }
1013         Geom::Coord rounded;
1014         Geom::Point point_on_line;
1016         rounded = Inkscape::Util::round_to_upper_multiple_plus(p[i], spacing, grid->origin[i]);
1017         point_on_line = i ? Geom::Point(0, rounded) : Geom::Point(rounded, 0);
1018         s.push_back(std::make_pair(component_vectors[i], point_on_line));
1020         rounded = Inkscape::Util::round_to_lower_multiple_plus(p[i], spacing, grid->origin[i]);
1021         point_on_line = i ? Geom::Point(0, rounded) : Geom::Point(rounded, 0);
1022         s.push_back(std::make_pair(component_vectors[i], point_on_line));
1023     }
1025     return s;
1028 void CanvasXYGridSnapper::_addSnappedLine(SnappedConstraints &sc, Geom::Point const snapped_point, Geom::Coord const snapped_distance,  SnapSourceType const &source, long source_num, Geom::Point const normal_to_line, Geom::Point const point_on_line) const
1030     SnappedLine dummy = SnappedLine(snapped_point, snapped_distance, source, source_num, Inkscape::SNAPTARGET_GRID, getSnapperTolerance(), getSnapperAlwaysSnap(), normal_to_line, point_on_line);
1031     sc.grid_lines.push_back(dummy);
1034 void CanvasXYGridSnapper::_addSnappedPoint(SnappedConstraints &sc, Geom::Point const snapped_point, Geom::Coord const snapped_distance, SnapSourceType const &source, long source_num, bool constrained_snap) const
1036     SnappedPoint dummy = SnappedPoint(snapped_point, source, source_num, Inkscape::SNAPTARGET_GRID, snapped_distance, getSnapperTolerance(), getSnapperAlwaysSnap(), constrained_snap, true);
1037     sc.points.push_back(dummy);
1040 /**
1041  *  \return true if this Snapper will snap at least one kind of point.
1042  */
1043 bool CanvasXYGridSnapper::ThisSnapperMightSnap() const
1045     return _snap_enabled && _snapmanager->snapprefs.getSnapToGrids() && _snapmanager->snapprefs.getSnapModeBBoxOrNodes();
1048 } // namespace Inkscape
1051 /*
1052   Local Variables:
1053   mode:c++
1054   c-file-style:"stroustrup"
1055   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1056   indent-tabs-mode:nil
1057   fill-column:99
1058   End:
1059 */
1060 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 :