Code

Next roud of NR ==> Geom conversion
[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 "preferences.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, 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 = sp_document_repr_doc(doc);
252     Inkscape::XML::Node *newnode;
253     newnode = xml_doc->createElement("inkscape:grid");
254     newnode->setAttribute("type", getSVGName(gridtype));
256     repr->appendChild(newnode);
257     Inkscape::GC::release(newnode);
259     sp_document_done(doc, SP_VERB_DIALOG_NAMEDVIEW, _("Create new grid"));
262 /*
263 * Creates a new CanvasGrid object of type gridtype
264 */
265 CanvasGrid*
266 CanvasGrid::NewGrid(SPNamedView * nv, Inkscape::XML::Node * repr, SPDocument * doc, GridType gridtype)
268     if (!repr) return NULL;
269     if (!doc) {
270         g_error("CanvasGrid::NewGrid - doc==NULL");
271         return NULL;
272     }
274     switch (gridtype) {
275         case GRID_RECTANGULAR:
276             return (CanvasGrid*) new CanvasXYGrid(nv, repr, doc);
277         case GRID_AXONOMETRIC:
278             return (CanvasGrid*) new CanvasAxonomGrid(nv, repr, doc);
279     }
281     return NULL;
285 /**
286 *  creates a new grid canvasitem for the SPDesktop given as parameter. Keeps a link to this canvasitem in the canvasitems list.
287 */
288 GridCanvasItem *
289 CanvasGrid::createCanvasItem(SPDesktop * desktop)
291     if (!desktop) return NULL;
292 //    Johan: I think for multiple desktops it is best if each has their own canvasitem,
293 //           but share the same CanvasGrid object; that is what this function is for.
295     // check if there is already a canvasitem on this desktop linking to this grid
296     for (GSList *l = canvasitems; l != NULL; l = l->next) {
297         if ( sp_desktop_gridgroup(desktop) == SP_CANVAS_GROUP(SP_CANVAS_ITEM(l->data)->parent) ) {
298             return NULL;
299         }
300     }
302     GridCanvasItem * item = INKSCAPE_GRID_CANVASITEM( sp_canvas_item_new(sp_desktop_gridgroup(desktop), INKSCAPE_TYPE_GRID_CANVASITEM, NULL) );
303     item->grid = this;
304     sp_canvas_item_show(SP_CANVAS_ITEM(item));
306     gtk_object_ref(GTK_OBJECT(item));    // since we're keeping a link to this item, we need to bump up the ref count
307     canvasitems = g_slist_prepend(canvasitems, item);
309     return item;
312 Gtk::Widget *
313 CanvasGrid::newWidget()
315     Gtk::VBox * vbox = Gtk::manage( new Gtk::VBox() );
316     Gtk::Label * namelabel = Gtk::manage(new Gtk::Label("", Gtk::ALIGN_CENTER) );
318     Glib::ustring str("<b>");
319     str += getName();
320     str += "</b>";
321     namelabel->set_markup(str);
322     vbox->pack_start(*namelabel, true, true);
324     Inkscape::UI::Widget::RegisteredCheckButton * _rcb_enabled = Gtk::manage(
325         new Inkscape::UI::Widget::RegisteredCheckButton( _("_Enabled"),
326                         _("Determines whether to snap to this grid or not. Can be 'on' for invisible grids."),
327                          "enabled", _wr, false, repr, doc) );
328     Inkscape::UI::Widget::RegisteredCheckButton * _rcb_visible = Gtk::manage(
329         new Inkscape::UI::Widget::RegisteredCheckButton( _("_Visible"),
330                         _("Determines whether the grid is displayed or not. Objects are still snapped to invisible grids."),
331                          "visible", _wr, true, repr, doc) );
333     vbox->pack_start(*_rcb_enabled, true, true);
334     vbox->pack_start(*_rcb_visible, true, true);
335     Gtk::Widget * gridwdg = newSpecificWidget();
336     vbox->pack_start(*gridwdg, true, true);
338     std::list<Gtk::Widget*> slaves;
339     slaves.push_back(_rcb_visible);
340     slaves.push_back(gridwdg);
341     _rcb_enabled->setSlaveWidgets(slaves);
343     // set widget values
344     _rcb_visible->setActive(visible);
345     if (snapper != NULL) {
346         _rcb_enabled->setActive(snapper->getEnabled());
347     }
349     return dynamic_cast<Gtk::Widget *> (vbox);
352 void
353 CanvasGrid::on_repr_attr_changed(Inkscape::XML::Node *repr, gchar const *key, gchar const *oldval, gchar const *newval, bool is_interactive, void *data)
355     if (!data)
356         return;
358     ((CanvasGrid*) data)->onReprAttrChanged(repr, key, oldval, newval, is_interactive);
361 bool CanvasGrid::isEnabled() 
362
363     if (snapper == NULL) {
364        return false;
365     } 
366     
367     return snapper->getEnabled();    
370 // ##########################################################
371 //   CanvasXYGrid
374 /**
375 * "attach_all" function
376 * A DIRECT COPY-PASTE FROM DOCUMENT-PROPERTIES.CPP  TO QUICKLY GET RESULTS
378  * Helper function that attachs widgets in a 3xn table. The widgets come in an
379  * array that has two entries per table row. The two entries code for four
380  * possible cases: (0,0) means insert space in first column; (0, non-0) means
381  * widget in columns 2-3; (non-0, 0) means label in columns 1-3; and
382  * (non-0, non-0) means two widgets in columns 2 and 3.
383 **/
384 #define SPACE_SIZE_X 15
385 #define SPACE_SIZE_Y 10
386 static inline void
387 attach_all(Gtk::Table &table, Gtk::Widget const *const arr[], unsigned size, int start = 0)
389     for (unsigned i=0, r=start; i<size/sizeof(Gtk::Widget*); i+=2) {
390         if (arr[i] && arr[i+1]) {
391             table.attach (const_cast<Gtk::Widget&>(*arr[i]),   1, 2, r, r+1,
392                           Gtk::FILL|Gtk::EXPAND, (Gtk::AttachOptions)0,0,0);
393             table.attach (const_cast<Gtk::Widget&>(*arr[i+1]), 2, 3, r, r+1,
394                           Gtk::FILL|Gtk::EXPAND, (Gtk::AttachOptions)0,0,0);
395         } else {
396             if (arr[i+1]) {
397                 table.attach (const_cast<Gtk::Widget&>(*arr[i+1]), 1, 3, r, r+1,
398                               Gtk::FILL|Gtk::EXPAND, (Gtk::AttachOptions)0,0,0);
399             } else if (arr[i]) {
400                 Gtk::Label& label = reinterpret_cast<Gtk::Label&> (const_cast<Gtk::Widget&>(*arr[i]));
401                 label.set_alignment (0.0);
402                 table.attach (label, 0, 3, r, r+1,
403                               Gtk::FILL|Gtk::EXPAND, (Gtk::AttachOptions)0,0,0);
404             } else {
405                 Gtk::HBox *space = manage (new Gtk::HBox);
406                 space->set_size_request (SPACE_SIZE_X, SPACE_SIZE_Y);
407                 table.attach (*space, 0, 1, r, r+1,
408                               (Gtk::AttachOptions)0, (Gtk::AttachOptions)0,0,0);
409             }
410         }
411         ++r;
412     }
415 CanvasXYGrid::CanvasXYGrid (SPNamedView * nv, Inkscape::XML::Node * in_repr, SPDocument * in_doc)
416     : CanvasGrid(nv, in_repr, in_doc, GRID_RECTANGULAR)
418     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
419     gridunit = sp_unit_get_by_abbreviation( prefs->getString("options.grids.xy", "units").data() );
420     if (!gridunit)
421         gridunit = &sp_unit_get_by_id(SP_UNIT_PX);
422     origin[Geom::X] = sp_units_get_pixels(prefs->getDouble("options.grids.xy", "origin_x", 0.0), *gridunit);
423     origin[Geom::Y] = sp_units_get_pixels(prefs->getDouble("options.grids.xy", "origin_y", 0.0), *gridunit);
424     color = prefs->getInt("options.grids.xy", "color", 0x0000ff20);
425     empcolor = prefs->getInt("options.grids.xy", "empcolor", 0x0000ff40);
426     empspacing = prefs->getInt("options.grids.xy", "empspacing", 5);
427     spacing[Geom::X] = sp_units_get_pixels(prefs->getDouble("options.grids.xy", "spacing_x", 0.0), *gridunit);
428     spacing[Geom::Y] = sp_units_get_pixels(prefs->getDouble("options.grids.xy", "spacing_y", 0.0), *gridunit);
429     render_dotted = prefs->getBool("options.grids.xy", "dotted", false);
431     snapper = new CanvasXYGridSnapper(this, &namedview->snap_manager, 0);
433     if (repr) readRepr();
436 CanvasXYGrid::~CanvasXYGrid ()
438    if (snapper) delete snapper;
442 /* fixme: Collect all these length parsing methods and think common sane API */
444 static gboolean
445 sp_nv_read_length(gchar const *str, guint base, gdouble *val, SPUnit const **unit)
447     if (!str) {
448         return FALSE;
449     }
451     gchar *u;
452     gdouble v = g_ascii_strtod(str, &u);
453     if (!u) {
454         return FALSE;
455     }
456     while (isspace(*u)) {
457         u += 1;
458     }
460     if (!*u) {
461         /* No unit specified - keep default */
462         *val = v;
463         return TRUE;
464     }
466     if (base & SP_UNIT_DEVICE) {
467         if (u[0] && u[1] && !isalnum(u[2]) && !strncmp(u, "px", 2)) {
468             *unit = &sp_unit_get_by_id(SP_UNIT_PX);
469             *val = v;
470             return TRUE;
471         }
472     }
474     if (base & SP_UNIT_ABSOLUTE) {
475         if (!strncmp(u, "pt", 2)) {
476             *unit = &sp_unit_get_by_id(SP_UNIT_PT);
477         } else if (!strncmp(u, "mm", 2)) {
478             *unit = &sp_unit_get_by_id(SP_UNIT_MM);
479         } else if (!strncmp(u, "cm", 2)) {
480             *unit = &sp_unit_get_by_id(SP_UNIT_CM);
481         } else if (!strncmp(u, "m", 1)) {
482             *unit = &sp_unit_get_by_id(SP_UNIT_M);
483         } else if (!strncmp(u, "in", 2)) {
484             *unit = &sp_unit_get_by_id(SP_UNIT_IN);
485         } else {
486             return FALSE;
487         }
488         *val = v;
489         return TRUE;
490     }
492     return FALSE;
495 static gboolean sp_nv_read_opacity(gchar const *str, guint32 *color)
497     if (!str) {
498         return FALSE;
499     }
501     gchar *u;
502     gdouble v = g_ascii_strtod(str, &u);
503     if (!u) {
504         return FALSE;
505     }
506     v = CLAMP(v, 0.0, 1.0);
508     *color = (*color & 0xffffff00) | (guint32) floor(v * 255.9999);
510     return TRUE;
513 /** If the passed scalar is invalid (<=0), then set the widget and the scalar
514     to use the given old value.
516     @param oldVal Old value to use if the new one is invalid.
517     @param pTarget The scalar to validate.
518     @param widget Widget associated with the scalar.
519 */
520 static void validateScalar(double oldVal,
521                            double* pTarget)
523     // Avoid nullness.
524     if ( pTarget == NULL )
525         return;
527     // Invalid new value?
528     if ( *pTarget <= 0 ) {
529         // If the old value is somehow invalid as well, then default to 1.
530         if ( oldVal <= 0 )
531             oldVal = 1;
533         // Reset the scalar and associated widget to the old value.
534         *pTarget = oldVal;
535     } //if
537 } //validateScalar
540 /** If the passed int is invalid (<=0), then set the widget and the int
541     to use the given old value.
543     @param oldVal Old value to use if the new one is invalid.
544     @param pTarget The int to validate.
545     @param widget Widget associated with the int.
546 */
547 static void validateInt(gint oldVal,
548                         gint* pTarget)
550     // Avoid nullness.
551     if ( pTarget == NULL )
552         return;
554     // Invalid new value?
555     if ( *pTarget <= 0 ) {
556         // If the old value is somehow invalid as well, then default to 1.
557         if ( oldVal <= 0 )
558             oldVal = 1;
560         // Reset the int and associated widget to the old value.
561         *pTarget = oldVal;
562     } //if
564 } //validateInt
566 void
567 CanvasXYGrid::readRepr()
569     gchar const *value;
570     if ( (value = repr->attribute("originx")) ) {
571         sp_nv_read_length(value, SP_UNIT_ABSOLUTE | SP_UNIT_DEVICE, &origin[Geom::X], &gridunit);
572         origin[Geom::X] = sp_units_get_pixels(origin[Geom::X], *(gridunit));
573     }
575     if ( (value = repr->attribute("originy")) ) {
576         sp_nv_read_length(value, SP_UNIT_ABSOLUTE | SP_UNIT_DEVICE, &origin[Geom::Y], &gridunit);
577         origin[Geom::Y] = sp_units_get_pixels(origin[Geom::Y], *(gridunit));
578     }
580     if ( (value = repr->attribute("spacingx")) ) {
581         double oldVal = spacing[Geom::X];
582         sp_nv_read_length(value, SP_UNIT_ABSOLUTE | SP_UNIT_DEVICE, &spacing[Geom::X], &gridunit);
583         validateScalar( oldVal, &spacing[Geom::X]);
584         spacing[Geom::X] = sp_units_get_pixels(spacing[Geom::X], *(gridunit));
586     }
587     if ( (value = repr->attribute("spacingy")) ) {
588         double oldVal = spacing[Geom::Y];
589         sp_nv_read_length(value, SP_UNIT_ABSOLUTE | SP_UNIT_DEVICE, &spacing[Geom::Y], &gridunit);
590         validateScalar( oldVal, &spacing[Geom::Y]);
591         spacing[Geom::Y] = sp_units_get_pixels(spacing[Geom::Y], *(gridunit));
593     }
595     if ( (value = repr->attribute("color")) ) {
596         color = (color & 0xff) | sp_svg_read_color(value, color);
597     }
599     if ( (value = repr->attribute("empcolor")) ) {
600         empcolor = (empcolor & 0xff) | sp_svg_read_color(value, empcolor);
601     }
603     if ( (value = repr->attribute("opacity")) ) {
604         sp_nv_read_opacity(value, &color);
605     }
606     if ( (value = repr->attribute("empopacity")) ) {
607         sp_nv_read_opacity(value, &empcolor);
608     }
610     if ( (value = repr->attribute("empspacing")) ) {
611         gint oldVal = empspacing;
612         empspacing = atoi(value);
613         validateInt( oldVal, &empspacing);
614     }
616     if ( (value = repr->attribute("dotted")) ) {
617         render_dotted = (strcmp(value,"false") != 0 && strcmp(value, "0") != 0);
618     }
620     if ( (value = repr->attribute("visible")) ) {
621         visible = (strcmp(value,"false") != 0 && strcmp(value, "0") != 0);
622     }
623     
624     if ( (value = repr->attribute("enabled")) ) {
625         g_assert(snapper != NULL);
626         snapper->setEnabled(strcmp(value,"false") != 0 && strcmp(value, "0") != 0);
627     }
629     for (GSList *l = canvasitems; l != NULL; l = l->next) {
630         sp_canvas_item_request_update ( SP_CANVAS_ITEM(l->data) );
631     }
633     return;
636 /**
637  * Called when XML node attribute changed; updates dialog widgets if change was not done by widgets themselves.
638  */
639 void
640 CanvasXYGrid::onReprAttrChanged(Inkscape::XML::Node */*repr*/, gchar const */*key*/, gchar const */*oldval*/, gchar const */*newval*/, bool /*is_interactive*/)
642     readRepr();
644     if ( ! (_wr.isUpdating()) )
645         updateWidgets();
651 Gtk::Widget *
652 CanvasXYGrid::newSpecificWidget()
654     Gtk::Table * table = Gtk::manage( new Gtk::Table(1,1) );
656     Inkscape::UI::Widget::RegisteredUnitMenu *_rumg = Gtk::manage( new Inkscape::UI::Widget::RegisteredUnitMenu(
657             _("Grid _units:"), "units", _wr, repr, doc) );
658     Inkscape::UI::Widget::RegisteredScalarUnit *_rsu_ox = Gtk::manage( new Inkscape::UI::Widget::RegisteredScalarUnit(
659             _("_Origin X:"), _("X coordinate of grid origin"), "originx", *_rumg, _wr, repr, doc) );
660     Inkscape::UI::Widget::RegisteredScalarUnit *_rsu_oy = Gtk::manage( new Inkscape::UI::Widget::RegisteredScalarUnit(
661             _("O_rigin Y:"), _("Y coordinate of grid origin"), "originy", *_rumg, _wr, repr, doc) );
662     Inkscape::UI::Widget::RegisteredScalarUnit *_rsu_sx = Gtk::manage( new Inkscape::UI::Widget::RegisteredScalarUnit(
663             _("Spacing _X:"), _("Distance between vertical grid lines"), "spacingx", *_rumg, _wr, repr, doc) );
664     Inkscape::UI::Widget::RegisteredScalarUnit *_rsu_sy = Gtk::manage( new Inkscape::UI::Widget::RegisteredScalarUnit(
665             _("Spacing _Y:"), _("Distance between horizontal grid lines"), "spacingy", *_rumg, _wr, repr, doc) );
667     Inkscape::UI::Widget::RegisteredColorPicker *_rcp_gcol = Gtk::manage(
668         new Inkscape::UI::Widget::RegisteredColorPicker(
669             _("Grid line _color:"), _("Grid line color"), _("Color of grid lines"), 
670             "color", "opacity", _wr, repr, doc));
672     Inkscape::UI::Widget::RegisteredColorPicker *_rcp_gmcol = Gtk::manage(
673         new Inkscape::UI::Widget::RegisteredColorPicker(
674             _("Ma_jor grid line color:"), _("Major grid line color"), 
675             _("Color of the major (highlighted) grid lines"), "empcolor", "empopacity", 
676             _wr, repr, doc));
677     
678     Inkscape::UI::Widget::RegisteredSuffixedInteger *_rsi = Gtk::manage( new Inkscape::UI::Widget::RegisteredSuffixedInteger(
679             _("_Major grid line every:"), "", _("lines"), "empspacing", _wr, repr, doc) );
681     table->set_spacings(2);
683 _wr.setUpdating (true);
685     _rsu_ox->setDigits(4);
686     _rsu_ox->setIncrements(0.1, 1.0);
688     _rsu_oy->setDigits(4);
689     _rsu_oy->setIncrements(0.1, 1.0);
691     _rsu_sx->setDigits(4);
692     _rsu_sx->setIncrements(0.1, 1.0);
694     _rsu_sy->setDigits(4);
695     _rsu_sy->setIncrements(0.1, 1.0);
697     Inkscape::UI::Widget::RegisteredCheckButton * _rcb_dotted = Gtk::manage(
698                 new Inkscape::UI::Widget::RegisteredCheckButton( _("_Show dots instead of lines"),
699                        _("If set, displays dots at gridpoints instead of gridlines"),
700                         "dotted", _wr, false, repr, doc) );
701 _wr.setUpdating (false);
703     Gtk::Widget const *const widget_array[] = {
704         0,                  _rumg,
705         0,                  _rsu_ox,
706         0,                  _rsu_oy,
707         0,                  _rsu_sx,
708         0,                  _rsu_sy,
709         _rcp_gcol->_label,   _rcp_gcol,
710         0,                  0,
711         _rcp_gmcol->_label,  _rcp_gmcol,
712         0,                  _rsi,
713         0,                  _rcb_dotted,
714     };
716     attach_all (*table, widget_array, sizeof(widget_array));
718     // set widget values
719     _rumg->setUnit (gridunit);
721     gdouble val;
722     val = origin[Geom::X];
723     val = sp_pixels_get_units (val, *(gridunit));
724     _rsu_ox->setValue (val);
725     val = origin[Geom::Y];
726     val = sp_pixels_get_units (val, *(gridunit));
727     _rsu_oy->setValue (val);
728     val = spacing[Geom::X];
729     double gridx = sp_pixels_get_units (val, *(gridunit));
730     _rsu_sx->setValue (gridx);
731     val = spacing[Geom::Y];
732     double gridy = sp_pixels_get_units (val, *(gridunit));
733     _rsu_sy->setValue (gridy);
735     _rcp_gcol->setRgba32 (color);
736     _rcp_gmcol->setRgba32 (empcolor);
737     _rsi->setValue (empspacing);
739     _rcb_dotted->setActive(render_dotted);
741     return table;
745 /**
746  * Update dialog widgets from object's values.
747  */
748 void
749 CanvasXYGrid::updateWidgets()
751 /*
752     if (_wr.isUpdating()) return;
754     _wr.setUpdating (true);
756     _rcb_visible.setActive(visible);
757     if (snapper != NULL) {
758         _rcb_enabled.setActive(snapper->getEnabled());
759     }
761     _rumg.setUnit (gridunit);
763     gdouble val;
764     val = origin[Geom::X];
765     val = sp_pixels_get_units (val, *(gridunit));
766     _rsu_ox.setValue (val);
767     val = origin[Geom::Y];
768     val = sp_pixels_get_units (val, *(gridunit));
769     _rsu_oy.setValue (val);
770     val = spacing[Geom::X];
771     double gridx = sp_pixels_get_units (val, *(gridunit));
772     _rsu_sx.setValue (gridx);
773     val = spacing[Geom::Y];
774     double gridy = sp_pixels_get_units (val, *(gridunit));
775     _rsu_sy.setValue (gridy);
777     _rcp_gcol.setRgba32 (color);
778     _rcp_gmcol.setRgba32 (empcolor);
779     _rsi.setValue (empspacing);
781     _rcb_dotted.setActive(render_dotted);
783     _wr.setUpdating (false);
785     return;
786 */
791 void
792 CanvasXYGrid::Update (Geom::Matrix const &affine, unsigned int /*flags*/)
794     ow = origin * affine;
795     sw = spacing * affine;
796     sw -= Geom::Point(affine[4], affine[5]);
798     for(int dim = 0; dim < 2; dim++) {
799         gint scaling_factor = empspacing;
801         if (scaling_factor <= 1)
802             scaling_factor = 5;
804         scaled[dim] = FALSE;
805         sw[dim] = fabs (sw[dim]);
806         while (sw[dim] < 8.0) {
807             scaled[dim] = TRUE;
808             sw[dim] *= scaling_factor;
809             /* First pass, go up to the major line spacing, then
810                keep increasing by two. */
811             scaling_factor = 2;
812         }
813     }
817 static void
818 grid_hline (SPCanvasBuf *buf, gint y, gint xs, gint xe, guint32 rgba)
820     if ((y >= buf->rect.y0) && (y < buf->rect.y1)) {
821         guint r, g, b, a;
822         gint x0, x1, x;
823         guchar *p;
824         r = NR_RGBA32_R (rgba);
825         g = NR_RGBA32_G (rgba);
826         b = NR_RGBA32_B (rgba);
827         a = NR_RGBA32_A (rgba);
828         x0 = MAX (buf->rect.x0, xs);
829         x1 = MIN (buf->rect.x1, xe + 1);
830         p = buf->buf + (y - buf->rect.y0) * buf->buf_rowstride + (x0 - buf->rect.x0) * 4;
831         for (x = x0; x < x1; x++) {
832             p[0] = NR_COMPOSEN11_1111 (r, a, p[0]);
833             p[1] = NR_COMPOSEN11_1111 (g, a, p[1]);
834             p[2] = NR_COMPOSEN11_1111 (b, a, p[2]);
835             p += 4;
836         }
837     }
840 static void
841 grid_vline (SPCanvasBuf *buf, gint x, gint ys, gint ye, guint32 rgba)
843     if ((x >= buf->rect.x0) && (x < buf->rect.x1)) {
844         guint r, g, b, a;
845         gint y0, y1, y;
846         guchar *p;
847         r = NR_RGBA32_R(rgba);
848         g = NR_RGBA32_G (rgba);
849         b = NR_RGBA32_B (rgba);
850         a = NR_RGBA32_A (rgba);
851         y0 = MAX (buf->rect.y0, ys);
852         y1 = MIN (buf->rect.y1, ye + 1);
853         p = buf->buf + (y0 - buf->rect.y0) * buf->buf_rowstride + (x - buf->rect.x0) * 4;
854         for (y = y0; y < y1; y++) {
855             p[0] = NR_COMPOSEN11_1111 (r, a, p[0]);
856             p[1] = NR_COMPOSEN11_1111 (g, a, p[1]);
857             p[2] = NR_COMPOSEN11_1111 (b, a, p[2]);
858             p += buf->buf_rowstride;
859         }
860     }
863 static void
864 grid_dot (SPCanvasBuf *buf, gint x, gint y, guint32 rgba)
866     if ( (y >= buf->rect.y0) && (y < buf->rect.y1)
867          && (x >= buf->rect.x0) && (x < buf->rect.x1) ) {
868         guint r, g, b, a;
869         guchar *p;
870         r = NR_RGBA32_R (rgba);
871         g = NR_RGBA32_G (rgba);
872         b = NR_RGBA32_B (rgba);
873         a = NR_RGBA32_A (rgba);
874         p = buf->buf + (y - buf->rect.y0) * buf->buf_rowstride + (x - buf->rect.x0) * 4;
875         p[0] = NR_COMPOSEN11_1111 (r, a, p[0]);
876         p[1] = NR_COMPOSEN11_1111 (g, a, p[1]);
877         p[2] = NR_COMPOSEN11_1111 (b, a, p[2]);
878     }
881 void
882 CanvasXYGrid::Render (SPCanvasBuf *buf)
884     gdouble const sxg = floor ((buf->rect.x0 - ow[Geom::X]) / sw[Geom::X]) * sw[Geom::X] + ow[Geom::X];
885     gint const  xlinestart = (gint) Inkscape::round((sxg - ow[Geom::X]) / sw[Geom::X]);
886     gdouble const syg = floor ((buf->rect.y0 - ow[Geom::Y]) / sw[Geom::Y]) * sw[Geom::Y] + ow[Geom::Y];
887     gint const  ylinestart = (gint) Inkscape::round((syg - ow[Geom::Y]) / sw[Geom::Y]);
889     //set correct coloring, depending preference (when zoomed out, always major coloring or minor coloring)
890     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
891     guint32 _empcolor;
892     bool no_emp_when_zoomed_out = prefs->getBool("options.grids", "no_emphasize_when_zoomedout", false);
893     if( (scaled[Geom::X] || scaled[Geom::Y]) && no_emp_when_zoomed_out ) {
894         _empcolor = color;
895     } else {
896         _empcolor = empcolor;
897     }
899     if (!render_dotted) {
900         gint ylinenum;
901         gdouble y;
902         for (y = syg, ylinenum = ylinestart; y < buf->rect.y1; y += sw[Geom::Y], ylinenum++) {
903             gint const y0 = (gint) Inkscape::round(y);
904             if (!scaled[Geom::Y] && (ylinenum % empspacing) != 0) {
905                 grid_hline (buf, y0, buf->rect.x0, buf->rect.x1 - 1, color);
906             } else {
907                 grid_hline (buf, y0, buf->rect.x0, buf->rect.x1 - 1, _empcolor);
908             }
909         }
911         gint xlinenum;
912         gdouble x;
913         for (x = sxg, xlinenum = xlinestart; x < buf->rect.x1; x += sw[Geom::X], xlinenum++) {
914             gint const ix = (gint) Inkscape::round(x);
915             if (!scaled[Geom::X] && (xlinenum % empspacing) != 0) {
916                 grid_vline (buf, ix, buf->rect.y0, buf->rect.y1, color);
917             } else {
918                 grid_vline (buf, ix, buf->rect.y0, buf->rect.y1, _empcolor);
919             }
920         }
921     } else {
922         gint ylinenum;
923         gdouble y;
924         for (y = syg, ylinenum = ylinestart; y < buf->rect.y1; y += sw[Geom::Y], ylinenum++) {
925             gint const iy = (gint) Inkscape::round(y);
927             gint xlinenum;
928             gdouble x;
929             for (x = sxg, xlinenum = xlinestart; x < buf->rect.x1; x += sw[Geom::X], xlinenum++) {
930                 gint const ix = (gint) Inkscape::round(x);
931                 if ( (!scaled[Geom::X] && (xlinenum % empspacing) != 0)
932                      || (!scaled[Geom::Y] && (ylinenum % empspacing) != 0)
933                      || ((scaled[Geom::X] || scaled[Geom::Y]) && no_emp_when_zoomed_out) )
934                 {
935                     grid_dot (buf, ix, iy, color | (guint32)0x000000FF); // put alpha to max value
936                 } else {
937                     gint const pitch = 1;
938                     grid_dot (buf, ix-pitch, iy, _empcolor);
939                     grid_dot (buf, ix+pitch, iy, _empcolor);
941                     grid_dot (buf, ix, iy, _empcolor | (guint32)0x000000FF);  // put alpha to max value
943                     grid_dot (buf, ix, iy-pitch, _empcolor);
944                     grid_dot (buf, ix, iy+pitch, _empcolor);
945                 }
946             }
948         }
949     }
952 CanvasXYGridSnapper::CanvasXYGridSnapper(CanvasXYGrid *grid, SnapManager const *sm, Geom::Coord const d) : LineSnapper(sm, d)
954     this->grid = grid;
957 LineSnapper::LineList
958 CanvasXYGridSnapper::_getSnapLines(Geom::Point const &p) const
960     LineList s;
962     if ( grid == NULL ) {
963         return s;
964     }
966     for (unsigned int i = 0; i < 2; ++i) {
968         /* This is to make sure we snap to only visible grid lines */
969         double scaled_spacing = grid->sw[i]; // this is spacing of visible lines in screen pixels
971         // convert screen pixels to px
972         // FIXME: after we switch to snapping dist in screen pixels, this will be unnecessary
973         if (SP_ACTIVE_DESKTOP) {
974             scaled_spacing /= SP_ACTIVE_DESKTOP->current_zoom();
975         }
977         Geom::Coord rounded;        
978         Geom::Point point_on_line;
979         
980         rounded = Inkscape::Util::round_to_upper_multiple_plus(p[i], scaled_spacing, grid->origin[i]);
981         point_on_line = i ? Geom::Point(0, rounded) : Geom::Point(rounded, 0);
982         s.push_back(std::make_pair(component_vectors[i], point_on_line));
983         
984         rounded = Inkscape::Util::round_to_lower_multiple_plus(p[i], scaled_spacing, grid->origin[i]);
985         point_on_line = i ? Geom::Point(0, rounded) : Geom::Point(rounded, 0);
986         s.push_back(std::make_pair(component_vectors[i], point_on_line));
987     }
989     return s;
992 void CanvasXYGridSnapper::_addSnappedLine(SnappedConstraints &sc, Geom::Point const snapped_point, Geom::Coord const snapped_distance, Geom::Point const normal_to_line, Geom::Point const point_on_line) const 
994     SnappedLine dummy = SnappedLine(snapped_point, snapped_distance, getSnapperTolerance(), getSnapperAlwaysSnap(), normal_to_line, point_on_line);
995     sc.grid_lines.push_back(dummy);
998 /**
999  *  \return true if this Snapper will snap at least one kind of point.
1000  */
1001 bool CanvasXYGridSnapper::ThisSnapperMightSnap() const
1003     return _snap_enabled && _snap_from != 0;
1010 }; /* namespace Inkscape */
1013 /*
1014   Local Variables:
1015   mode:c++
1016   c-file-style:"stroustrup"
1017   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1018   indent-tabs-mode:nil
1019   fill-column:99
1020   End:
1021 */
1022 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :