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 */
8 /* As a general comment, I am not exactly proud of how things are done.
9 * (for example the 'enable' widget and readRepr things)
10 * It does seem to work however. I intend to clean up and sort things out later, but that can take forever...
11 * Don't be shy to correct things.
12 */
14 #define INKSCAPE_CANVAS_GRID_C
16 #include "sp-canvas-util.h"
17 #include "util/mathfns.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"
31 #include "preferences.h"
33 #include "canvas-grid.h"
34 #include "canvas-axonomgrid.h"
36 namespace Inkscape {
38 static gchar const *const grid_name[] = {
39 N_("Rectangular grid"),
40 N_("Axonometric grid")
41 };
42 static gchar const *const grid_svgname[] = {
43 "xygrid",
44 "axonomgrid"
45 };
48 // ##########################################################
49 // Grid CanvasItem
50 static void grid_canvasitem_class_init (GridCanvasItemClass *klass);
51 static void grid_canvasitem_init (GridCanvasItem *grid);
52 static void grid_canvasitem_destroy (GtkObject *object);
54 static void grid_canvasitem_update (SPCanvasItem *item, Geom::Matrix const &affine, unsigned int flags);
55 static void grid_canvasitem_render (SPCanvasItem *item, SPCanvasBuf *buf);
57 static SPCanvasItemClass * parent_class;
59 GtkType
60 grid_canvasitem_get_type (void)
61 {
62 static GtkType grid_canvasitem_type = 0;
64 if (!grid_canvasitem_type) {
65 GtkTypeInfo grid_canvasitem_info = {
66 (gchar *)"GridCanvasItem",
67 sizeof (GridCanvasItem),
68 sizeof (GridCanvasItemClass),
69 (GtkClassInitFunc) grid_canvasitem_class_init,
70 (GtkObjectInitFunc) grid_canvasitem_init,
71 NULL, NULL,
72 (GtkClassInitFunc) NULL
73 };
74 grid_canvasitem_type = gtk_type_unique (sp_canvas_item_get_type (), &grid_canvasitem_info);
75 }
76 return grid_canvasitem_type;
77 }
79 static void
80 grid_canvasitem_class_init (GridCanvasItemClass *klass)
81 {
82 GtkObjectClass *object_class;
83 SPCanvasItemClass *item_class;
85 object_class = (GtkObjectClass *) klass;
86 item_class = (SPCanvasItemClass *) klass;
88 parent_class = (SPCanvasItemClass*)gtk_type_class (sp_canvas_item_get_type ());
90 object_class->destroy = grid_canvasitem_destroy;
92 item_class->update = grid_canvasitem_update;
93 item_class->render = grid_canvasitem_render;
94 }
96 static void
97 grid_canvasitem_init (GridCanvasItem *griditem)
98 {
99 griditem->grid = NULL;
100 }
102 static void
103 grid_canvasitem_destroy (GtkObject *object)
104 {
105 g_return_if_fail (object != NULL);
106 g_return_if_fail (INKSCAPE_IS_GRID_CANVASITEM (object));
108 if (GTK_OBJECT_CLASS (parent_class)->destroy)
109 (* GTK_OBJECT_CLASS (parent_class)->destroy) (object);
110 }
112 /**
113 */
114 static void
115 grid_canvasitem_render (SPCanvasItem * item, SPCanvasBuf * buf)
116 {
117 GridCanvasItem *gridcanvasitem = INKSCAPE_GRID_CANVASITEM (item);
119 if ( gridcanvasitem->grid && gridcanvasitem->grid->isVisible() ) {
120 sp_canvas_prepare_buffer (buf);
121 gridcanvasitem->grid->Render(buf);
122 }
123 }
125 static void
126 grid_canvasitem_update (SPCanvasItem *item, Geom::Matrix const &affine, unsigned int flags)
127 {
128 GridCanvasItem *gridcanvasitem = INKSCAPE_GRID_CANVASITEM (item);
130 if (parent_class->update)
131 (* parent_class->update) (item, affine, flags);
133 if (gridcanvasitem->grid) {
134 gridcanvasitem->grid->Update(affine, flags);
136 sp_canvas_request_redraw (item->canvas,
137 -1000000, -1000000,
138 1000000, 1000000);
140 item->x1 = item->y1 = -1000000;
141 item->x2 = item->y2 = 1000000;
142 }
143 }
147 // ##########################################################
148 // CanvasGrid
150 static Inkscape::XML::NodeEventVector const _repr_events = {
151 NULL, /* child_added */
152 NULL, /* child_removed */
153 CanvasGrid::on_repr_attr_changed,
154 NULL, /* content_changed */
155 NULL /* order_changed */
156 };
158 CanvasGrid::CanvasGrid(SPNamedView * nv, Inkscape::XML::Node * in_repr, SPDocument *in_doc, GridType type)
159 : visible(true), gridtype(type)
160 {
161 repr = in_repr;
162 doc = in_doc;
163 if (repr) {
164 repr->addListener (&_repr_events, this);
165 }
167 namedview = nv;
168 canvasitems = NULL;
169 }
171 CanvasGrid::~CanvasGrid()
172 {
173 if (repr) {
174 repr->removeListenerByData (this);
175 }
177 while (canvasitems) {
178 gtk_object_destroy(GTK_OBJECT(canvasitems->data));
179 canvasitems = g_slist_remove(canvasitems, canvasitems->data);
180 }
181 }
183 const char *
184 CanvasGrid::getName()
185 {
186 return _(grid_name[gridtype]);
187 }
189 const char *
190 CanvasGrid::getSVGName()
191 {
192 return grid_svgname[gridtype];
193 }
195 GridType
196 CanvasGrid::getGridType()
197 {
198 return gridtype;
199 }
202 char const *
203 CanvasGrid::getName(GridType type)
204 {
205 return _(grid_name[type]);
206 }
208 char const *
209 CanvasGrid::getSVGName(GridType type)
210 {
211 return grid_svgname[type];
212 }
214 GridType
215 CanvasGrid::getGridTypeFromSVGName(char const *typestr)
216 {
217 if (!typestr) return GRID_RECTANGULAR;
219 gint t = 0;
220 for (t = GRID_MAXTYPENR; t >= 0; t--) { //this automatically defaults to grid0 which is rectangular grid
221 if (!strcmp(typestr, grid_svgname[t])) break;
222 }
223 return (GridType) t;
224 }
226 GridType
227 CanvasGrid::getGridTypeFromName(char const *typestr)
228 {
229 if (!typestr) return GRID_RECTANGULAR;
231 gint t = 0;
232 for (t = GRID_MAXTYPENR; t >= 0; t--) { //this automatically defaults to grid0 which is rectangular grid
233 if (!strcmp(typestr, _(grid_name[t]))) break;
234 }
235 return (GridType) t;
236 }
239 /*
240 * writes an <inkscape:grid> child to repr.
241 */
242 void
243 CanvasGrid::writeNewGridToRepr(Inkscape::XML::Node * repr, SPDocument * doc, GridType gridtype)
244 {
245 if (!repr) return;
246 if (gridtype > GRID_MAXTYPENR) return;
248 // 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.
250 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
251 Inkscape::XML::Node *newnode;
252 newnode = xml_doc->createElement("inkscape:grid");
253 newnode->setAttribute("type", getSVGName(gridtype));
255 repr->appendChild(newnode);
256 Inkscape::GC::release(newnode);
258 sp_document_done(doc, SP_VERB_DIALOG_NAMEDVIEW, _("Create new grid"));
259 }
261 /*
262 * Creates a new CanvasGrid object of type gridtype
263 */
264 CanvasGrid*
265 CanvasGrid::NewGrid(SPNamedView * nv, Inkscape::XML::Node * repr, SPDocument * doc, GridType gridtype)
266 {
267 if (!repr) return NULL;
268 if (!doc) {
269 g_error("CanvasGrid::NewGrid - doc==NULL");
270 return NULL;
271 }
273 switch (gridtype) {
274 case GRID_RECTANGULAR:
275 return (CanvasGrid*) new CanvasXYGrid(nv, repr, doc);
276 case GRID_AXONOMETRIC:
277 return (CanvasGrid*) new CanvasAxonomGrid(nv, repr, doc);
278 }
280 return NULL;
281 }
284 /**
285 * creates a new grid canvasitem for the SPDesktop given as parameter. Keeps a link to this canvasitem in the canvasitems list.
286 */
287 GridCanvasItem *
288 CanvasGrid::createCanvasItem(SPDesktop * desktop)
289 {
290 if (!desktop) return NULL;
291 // Johan: I think for multiple desktops it is best if each has their own canvasitem,
292 // but share the same CanvasGrid object; that is what this function is for.
294 // check if there is already a canvasitem on this desktop linking to this grid
295 for (GSList *l = canvasitems; l != NULL; l = l->next) {
296 if ( sp_desktop_gridgroup(desktop) == SP_CANVAS_GROUP(SP_CANVAS_ITEM(l->data)->parent) ) {
297 return NULL;
298 }
299 }
301 GridCanvasItem * item = INKSCAPE_GRID_CANVASITEM( sp_canvas_item_new(sp_desktop_gridgroup(desktop), INKSCAPE_TYPE_GRID_CANVASITEM, NULL) );
302 item->grid = this;
303 sp_canvas_item_show(SP_CANVAS_ITEM(item));
305 gtk_object_ref(GTK_OBJECT(item)); // since we're keeping a link to this item, we need to bump up the ref count
306 canvasitems = g_slist_prepend(canvasitems, item);
308 return item;
309 }
311 Gtk::Widget *
312 CanvasGrid::newWidget()
313 {
314 Gtk::VBox * vbox = Gtk::manage( new Gtk::VBox() );
315 Gtk::Label * namelabel = Gtk::manage(new Gtk::Label("", Gtk::ALIGN_CENTER) );
317 Glib::ustring str("<b>");
318 str += getName();
319 str += "</b>";
320 namelabel->set_markup(str);
321 vbox->pack_start(*namelabel, true, true);
323 Inkscape::UI::Widget::RegisteredCheckButton * _rcb_enabled = Gtk::manage(
324 new Inkscape::UI::Widget::RegisteredCheckButton( _("_Enabled"),
325 _("Determines whether to snap to this grid or not. Can be 'on' for invisible grids."),
326 "enabled", _wr, false, repr, doc) );
328 Inkscape::UI::Widget::RegisteredCheckButton * _rcb_snap_visible_only = Gtk::manage(
329 new Inkscape::UI::Widget::RegisteredCheckButton( _("Snap to visible _grid lines only"),
330 _("When zoomed out, not all grid lines will be displayed. Only the visible ones will be snapped to"),
331 "snapvisiblegridlinesonly", _wr, true, repr, doc) );
333 Inkscape::UI::Widget::RegisteredCheckButton * _rcb_visible = Gtk::manage(
334 new Inkscape::UI::Widget::RegisteredCheckButton( _("_Visible"),
335 _("Determines whether the grid is displayed or not. Objects are still snapped to invisible grids."),
336 "visible", _wr, true, repr, doc) );
338 vbox->pack_start(*_rcb_enabled, true, true);
339 vbox->pack_start(*_rcb_visible, true, true);
340 vbox->pack_start(*_rcb_snap_visible_only, true, true);
341 Gtk::Widget * gridwdg = newSpecificWidget();
342 vbox->pack_start(*gridwdg, true, true);
344 std::list<Gtk::Widget*> slaves;
345 slaves.push_back(_rcb_visible);
346 slaves.push_back(_rcb_snap_visible_only);
347 slaves.push_back(gridwdg);
348 _rcb_enabled->setSlaveWidgets(slaves);
350 // set widget values
351 _rcb_visible->setActive(visible);
352 if (snapper != NULL) {
353 _rcb_enabled->setActive(snapper->getEnabled());
354 _rcb_snap_visible_only->setActive(snapper->getSnapVisibleOnly());
355 }
357 return dynamic_cast<Gtk::Widget *> (vbox);
358 }
360 void
361 CanvasGrid::on_repr_attr_changed(Inkscape::XML::Node *repr, gchar const *key, gchar const *oldval, gchar const *newval, bool is_interactive, void *data)
362 {
363 if (!data)
364 return;
366 ((CanvasGrid*) data)->onReprAttrChanged(repr, key, oldval, newval, is_interactive);
367 }
369 bool CanvasGrid::isEnabled()
370 {
371 if (snapper == NULL) {
372 return false;
373 }
375 return snapper->getEnabled();
376 }
378 // ##########################################################
379 // CanvasXYGrid
382 /**
383 * "attach_all" function
384 * A DIRECT COPY-PASTE FROM DOCUMENT-PROPERTIES.CPP TO QUICKLY GET RESULTS
385 *
386 * Helper function that attachs widgets in a 3xn table. The widgets come in an
387 * array that has two entries per table row. The two entries code for four
388 * possible cases: (0,0) means insert space in first column; (0, non-0) means
389 * widget in columns 2-3; (non-0, 0) means label in columns 1-3; and
390 * (non-0, non-0) means two widgets in columns 2 and 3.
391 **/
392 #define SPACE_SIZE_X 15
393 #define SPACE_SIZE_Y 10
394 static inline void
395 attach_all(Gtk::Table &table, Gtk::Widget const *const arr[], unsigned size, int start = 0)
396 {
397 for (unsigned i=0, r=start; i<size/sizeof(Gtk::Widget*); i+=2) {
398 if (arr[i] && arr[i+1]) {
399 table.attach (const_cast<Gtk::Widget&>(*arr[i]), 1, 2, r, r+1,
400 Gtk::FILL|Gtk::EXPAND, (Gtk::AttachOptions)0,0,0);
401 table.attach (const_cast<Gtk::Widget&>(*arr[i+1]), 2, 3, r, r+1,
402 Gtk::FILL|Gtk::EXPAND, (Gtk::AttachOptions)0,0,0);
403 } else {
404 if (arr[i+1]) {
405 table.attach (const_cast<Gtk::Widget&>(*arr[i+1]), 1, 3, r, r+1,
406 Gtk::FILL|Gtk::EXPAND, (Gtk::AttachOptions)0,0,0);
407 } else if (arr[i]) {
408 Gtk::Label& label = reinterpret_cast<Gtk::Label&> (const_cast<Gtk::Widget&>(*arr[i]));
409 label.set_alignment (0.0);
410 table.attach (label, 0, 3, r, r+1,
411 Gtk::FILL|Gtk::EXPAND, (Gtk::AttachOptions)0,0,0);
412 } else {
413 Gtk::HBox *space = manage (new Gtk::HBox);
414 space->set_size_request (SPACE_SIZE_X, SPACE_SIZE_Y);
415 table.attach (*space, 0, 1, r, r+1,
416 (Gtk::AttachOptions)0, (Gtk::AttachOptions)0,0,0);
417 }
418 }
419 ++r;
420 }
421 }
423 CanvasXYGrid::CanvasXYGrid (SPNamedView * nv, Inkscape::XML::Node * in_repr, SPDocument * in_doc)
424 : CanvasGrid(nv, in_repr, in_doc, GRID_RECTANGULAR)
425 {
426 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
427 gridunit = sp_unit_get_by_abbreviation( prefs->getString("/options/grids/xy/units").data() );
428 if (!gridunit)
429 gridunit = &sp_unit_get_by_id(SP_UNIT_PX);
430 origin[Geom::X] = sp_units_get_pixels(prefs->getDouble("/options/grids/xy/origin_x", 0.0), *gridunit);
431 origin[Geom::Y] = sp_units_get_pixels(prefs->getDouble("/options/grids/xy/origin_y", 0.0), *gridunit);
432 color = prefs->getInt("/options/grids/xy/color", 0x0000ff20);
433 empcolor = prefs->getInt("/options/grids/xy/empcolor", 0x0000ff40);
434 empspacing = prefs->getInt("/options/grids/xy/empspacing", 5);
435 spacing[Geom::X] = sp_units_get_pixels(prefs->getDouble("/options/grids/xy/spacing_x", 0.0), *gridunit);
436 spacing[Geom::Y] = sp_units_get_pixels(prefs->getDouble("/options/grids/xy/spacing_y", 0.0), *gridunit);
437 render_dotted = prefs->getBool("/options/grids/xy/dotted", false);
439 snapper = new CanvasXYGridSnapper(this, &namedview->snap_manager, 0);
441 if (repr) readRepr();
442 }
444 CanvasXYGrid::~CanvasXYGrid ()
445 {
446 if (snapper) delete snapper;
447 }
450 /* fixme: Collect all these length parsing methods and think common sane API */
452 static gboolean
453 sp_nv_read_length(gchar const *str, guint base, gdouble *val, SPUnit const **unit)
454 {
455 if (!str) {
456 return FALSE;
457 }
459 gchar *u;
460 gdouble v = g_ascii_strtod(str, &u);
461 if (!u) {
462 return FALSE;
463 }
464 while (isspace(*u)) {
465 u += 1;
466 }
468 if (!*u) {
469 /* No unit specified - keep default */
470 *val = v;
471 return TRUE;
472 }
474 if (base & SP_UNIT_DEVICE) {
475 if (u[0] && u[1] && !isalnum(u[2]) && !strncmp(u, "px", 2)) {
476 *unit = &sp_unit_get_by_id(SP_UNIT_PX);
477 *val = v;
478 return TRUE;
479 }
480 }
482 if (base & SP_UNIT_ABSOLUTE) {
483 if (!strncmp(u, "pt", 2)) {
484 *unit = &sp_unit_get_by_id(SP_UNIT_PT);
485 } else if (!strncmp(u, "mm", 2)) {
486 *unit = &sp_unit_get_by_id(SP_UNIT_MM);
487 } else if (!strncmp(u, "cm", 2)) {
488 *unit = &sp_unit_get_by_id(SP_UNIT_CM);
489 } else if (!strncmp(u, "m", 1)) {
490 *unit = &sp_unit_get_by_id(SP_UNIT_M);
491 } else if (!strncmp(u, "in", 2)) {
492 *unit = &sp_unit_get_by_id(SP_UNIT_IN);
493 } else {
494 return FALSE;
495 }
496 *val = v;
497 return TRUE;
498 }
500 return FALSE;
501 }
503 static gboolean sp_nv_read_opacity(gchar const *str, guint32 *color)
504 {
505 if (!str) {
506 return FALSE;
507 }
509 gchar *u;
510 gdouble v = g_ascii_strtod(str, &u);
511 if (!u) {
512 return FALSE;
513 }
514 v = CLAMP(v, 0.0, 1.0);
516 *color = (*color & 0xffffff00) | (guint32) floor(v * 255.9999);
518 return TRUE;
519 }
521 /** If the passed scalar is invalid (<=0), then set the widget and the scalar
522 to use the given old value.
524 @param oldVal Old value to use if the new one is invalid.
525 @param pTarget The scalar to validate.
526 @param widget Widget associated with the scalar.
527 */
528 static void validateScalar(double oldVal,
529 double* pTarget)
530 {
531 // Avoid nullness.
532 if ( pTarget == NULL )
533 return;
535 // Invalid new value?
536 if ( *pTarget <= 0 ) {
537 // If the old value is somehow invalid as well, then default to 1.
538 if ( oldVal <= 0 )
539 oldVal = 1;
541 // Reset the scalar and associated widget to the old value.
542 *pTarget = oldVal;
543 } //if
545 } //validateScalar
548 /** If the passed int is invalid (<=0), then set the widget and the int
549 to use the given old value.
551 @param oldVal Old value to use if the new one is invalid.
552 @param pTarget The int to validate.
553 @param widget Widget associated with the int.
554 */
555 static void validateInt(gint oldVal,
556 gint* pTarget)
557 {
558 // Avoid nullness.
559 if ( pTarget == NULL )
560 return;
562 // Invalid new value?
563 if ( *pTarget <= 0 ) {
564 // If the old value is somehow invalid as well, then default to 1.
565 if ( oldVal <= 0 )
566 oldVal = 1;
568 // Reset the int and associated widget to the old value.
569 *pTarget = oldVal;
570 } //if
572 } //validateInt
574 void
575 CanvasXYGrid::readRepr()
576 {
577 gchar const *value;
578 if ( (value = repr->attribute("originx")) ) {
579 sp_nv_read_length(value, SP_UNIT_ABSOLUTE | SP_UNIT_DEVICE, &origin[Geom::X], &gridunit);
580 origin[Geom::X] = sp_units_get_pixels(origin[Geom::X], *(gridunit));
581 }
583 if ( (value = repr->attribute("originy")) ) {
584 sp_nv_read_length(value, SP_UNIT_ABSOLUTE | SP_UNIT_DEVICE, &origin[Geom::Y], &gridunit);
585 origin[Geom::Y] = sp_units_get_pixels(origin[Geom::Y], *(gridunit));
586 }
588 if ( (value = repr->attribute("spacingx")) ) {
589 double oldVal = spacing[Geom::X];
590 sp_nv_read_length(value, SP_UNIT_ABSOLUTE | SP_UNIT_DEVICE, &spacing[Geom::X], &gridunit);
591 validateScalar( oldVal, &spacing[Geom::X]);
592 spacing[Geom::X] = sp_units_get_pixels(spacing[Geom::X], *(gridunit));
594 }
595 if ( (value = repr->attribute("spacingy")) ) {
596 double oldVal = spacing[Geom::Y];
597 sp_nv_read_length(value, SP_UNIT_ABSOLUTE | SP_UNIT_DEVICE, &spacing[Geom::Y], &gridunit);
598 validateScalar( oldVal, &spacing[Geom::Y]);
599 spacing[Geom::Y] = sp_units_get_pixels(spacing[Geom::Y], *(gridunit));
601 }
603 if ( (value = repr->attribute("color")) ) {
604 color = (color & 0xff) | sp_svg_read_color(value, color);
605 }
607 if ( (value = repr->attribute("empcolor")) ) {
608 empcolor = (empcolor & 0xff) | sp_svg_read_color(value, empcolor);
609 }
611 if ( (value = repr->attribute("opacity")) ) {
612 sp_nv_read_opacity(value, &color);
613 }
614 if ( (value = repr->attribute("empopacity")) ) {
615 sp_nv_read_opacity(value, &empcolor);
616 }
618 if ( (value = repr->attribute("empspacing")) ) {
619 gint oldVal = empspacing;
620 empspacing = atoi(value);
621 validateInt( oldVal, &empspacing);
622 }
624 if ( (value = repr->attribute("dotted")) ) {
625 render_dotted = (strcmp(value,"false") != 0 && strcmp(value, "0") != 0);
626 }
628 if ( (value = repr->attribute("visible")) ) {
629 visible = (strcmp(value,"false") != 0 && strcmp(value, "0") != 0);
630 }
632 if ( (value = repr->attribute("enabled")) ) {
633 g_assert(snapper != NULL);
634 snapper->setEnabled(strcmp(value,"false") != 0 && strcmp(value, "0") != 0);
635 }
637 if ( (value = repr->attribute("snapvisiblegridlinesonly")) ) {
638 g_assert(snapper != NULL);
639 snapper->setSnapVisibleOnly(strcmp(value,"false") != 0 && strcmp(value, "0") != 0);
640 }
642 for (GSList *l = canvasitems; l != NULL; l = l->next) {
643 sp_canvas_item_request_update ( SP_CANVAS_ITEM(l->data) );
644 }
646 return;
647 }
649 /**
650 * Called when XML node attribute changed; updates dialog widgets if change was not done by widgets themselves.
651 */
652 void
653 CanvasXYGrid::onReprAttrChanged(Inkscape::XML::Node */*repr*/, gchar const */*key*/, gchar const */*oldval*/, gchar const */*newval*/, bool /*is_interactive*/)
654 {
655 readRepr();
657 if ( ! (_wr.isUpdating()) )
658 updateWidgets();
659 }
664 Gtk::Widget *
665 CanvasXYGrid::newSpecificWidget()
666 {
667 Gtk::Table * table = Gtk::manage( new Gtk::Table(1,1) );
669 Inkscape::UI::Widget::RegisteredUnitMenu *_rumg = Gtk::manage( new Inkscape::UI::Widget::RegisteredUnitMenu(
670 _("Grid _units:"), "units", _wr, repr, doc) );
671 Inkscape::UI::Widget::RegisteredScalarUnit *_rsu_ox = Gtk::manage( new Inkscape::UI::Widget::RegisteredScalarUnit(
672 _("_Origin X:"), _("X coordinate of grid origin"), "originx", *_rumg, _wr, repr, doc) );
673 Inkscape::UI::Widget::RegisteredScalarUnit *_rsu_oy = Gtk::manage( new Inkscape::UI::Widget::RegisteredScalarUnit(
674 _("O_rigin Y:"), _("Y coordinate of grid origin"), "originy", *_rumg, _wr, repr, doc) );
675 Inkscape::UI::Widget::RegisteredScalarUnit *_rsu_sx = Gtk::manage( new Inkscape::UI::Widget::RegisteredScalarUnit(
676 _("Spacing _X:"), _("Distance between vertical grid lines"), "spacingx", *_rumg, _wr, repr, doc) );
677 Inkscape::UI::Widget::RegisteredScalarUnit *_rsu_sy = Gtk::manage( new Inkscape::UI::Widget::RegisteredScalarUnit(
678 _("Spacing _Y:"), _("Distance between horizontal grid lines"), "spacingy", *_rumg, _wr, repr, doc) );
680 Inkscape::UI::Widget::RegisteredColorPicker *_rcp_gcol = Gtk::manage(
681 new Inkscape::UI::Widget::RegisteredColorPicker(
682 _("Grid line _color:"), _("Grid line color"), _("Color of grid lines"),
683 "color", "opacity", _wr, repr, doc));
685 Inkscape::UI::Widget::RegisteredColorPicker *_rcp_gmcol = Gtk::manage(
686 new Inkscape::UI::Widget::RegisteredColorPicker(
687 _("Ma_jor grid line color:"), _("Major grid line color"),
688 _("Color of the major (highlighted) grid lines"), "empcolor", "empopacity",
689 _wr, repr, doc));
691 Inkscape::UI::Widget::RegisteredSuffixedInteger *_rsi = Gtk::manage( new Inkscape::UI::Widget::RegisteredSuffixedInteger(
692 _("_Major grid line every:"), "", _("lines"), "empspacing", _wr, repr, doc) );
694 table->set_spacings(2);
696 _wr.setUpdating (true);
698 _rsu_ox->setDigits(4);
699 _rsu_ox->setIncrements(0.1, 1.0);
701 _rsu_oy->setDigits(4);
702 _rsu_oy->setIncrements(0.1, 1.0);
704 _rsu_sx->setDigits(4);
705 _rsu_sx->setIncrements(0.1, 1.0);
707 _rsu_sy->setDigits(4);
708 _rsu_sy->setIncrements(0.1, 1.0);
710 Inkscape::UI::Widget::RegisteredCheckButton * _rcb_dotted = Gtk::manage(
711 new Inkscape::UI::Widget::RegisteredCheckButton( _("_Show dots instead of lines"),
712 _("If set, displays dots at gridpoints instead of gridlines"),
713 "dotted", _wr, false, repr, doc) );
714 _wr.setUpdating (false);
716 Gtk::Widget const *const widget_array[] = {
717 0, _rumg,
718 0, _rsu_ox,
719 0, _rsu_oy,
720 0, _rsu_sx,
721 0, _rsu_sy,
722 _rcp_gcol->_label, _rcp_gcol,
723 0, 0,
724 _rcp_gmcol->_label, _rcp_gmcol,
725 0, _rsi,
726 0, _rcb_dotted,
727 };
729 attach_all (*table, widget_array, sizeof(widget_array));
731 // set widget values
732 _rumg->setUnit (gridunit);
734 gdouble val;
735 val = origin[Geom::X];
736 val = sp_pixels_get_units (val, *(gridunit));
737 _rsu_ox->setValue (val);
738 val = origin[Geom::Y];
739 val = sp_pixels_get_units (val, *(gridunit));
740 _rsu_oy->setValue (val);
741 val = spacing[Geom::X];
742 double gridx = sp_pixels_get_units (val, *(gridunit));
743 _rsu_sx->setValue (gridx);
744 val = spacing[Geom::Y];
745 double gridy = sp_pixels_get_units (val, *(gridunit));
746 _rsu_sy->setValue (gridy);
748 _rcp_gcol->setRgba32 (color);
749 _rcp_gmcol->setRgba32 (empcolor);
750 _rsi->setValue (empspacing);
752 _rcb_dotted->setActive(render_dotted);
754 return table;
755 }
758 /**
759 * Update dialog widgets from object's values.
760 */
761 void
762 CanvasXYGrid::updateWidgets()
763 {
764 /*
765 if (_wr.isUpdating()) return;
767 _wr.setUpdating (true);
769 _rcb_visible.setActive(visible);
770 if (snapper != NULL) {
771 _rcb_enabled.setActive(snapper->getEnabled());
772 }
774 _rumg.setUnit (gridunit);
776 gdouble val;
777 val = origin[Geom::X];
778 val = sp_pixels_get_units (val, *(gridunit));
779 _rsu_ox.setValue (val);
780 val = origin[Geom::Y];
781 val = sp_pixels_get_units (val, *(gridunit));
782 _rsu_oy.setValue (val);
783 val = spacing[Geom::X];
784 double gridx = sp_pixels_get_units (val, *(gridunit));
785 _rsu_sx.setValue (gridx);
786 val = spacing[Geom::Y];
787 double gridy = sp_pixels_get_units (val, *(gridunit));
788 _rsu_sy.setValue (gridy);
790 _rcp_gcol.setRgba32 (color);
791 _rcp_gmcol.setRgba32 (empcolor);
792 _rsi.setValue (empspacing);
794 _rcb_dotted.setActive(render_dotted);
796 _wr.setUpdating (false);
798 return;
799 */
800 }
804 void
805 CanvasXYGrid::Update (Geom::Matrix const &affine, unsigned int /*flags*/)
806 {
807 ow = origin * affine;
808 sw = spacing * affine;
809 sw -= Geom::Point(affine[4], affine[5]);
811 for(int dim = 0; dim < 2; dim++) {
812 gint scaling_factor = empspacing;
814 if (scaling_factor <= 1)
815 scaling_factor = 5;
817 scaled[dim] = FALSE;
818 sw[dim] = fabs (sw[dim]);
819 while (sw[dim] < 8.0) {
820 scaled[dim] = TRUE;
821 sw[dim] *= scaling_factor;
822 /* First pass, go up to the major line spacing, then
823 keep increasing by two. */
824 scaling_factor = 2;
825 }
826 }
827 }
830 static void
831 grid_hline (SPCanvasBuf *buf, gint y, gint xs, gint xe, guint32 rgba)
832 {
833 if ((y >= buf->rect.y0) && (y < buf->rect.y1)) {
834 guint r, g, b, a;
835 gint x0, x1, x;
836 guchar *p;
837 r = NR_RGBA32_R (rgba);
838 g = NR_RGBA32_G (rgba);
839 b = NR_RGBA32_B (rgba);
840 a = NR_RGBA32_A (rgba);
841 x0 = MAX (buf->rect.x0, xs);
842 x1 = MIN (buf->rect.x1, xe + 1);
843 p = buf->buf + (y - buf->rect.y0) * buf->buf_rowstride + (x0 - buf->rect.x0) * 4;
844 for (x = x0; x < x1; x++) {
845 p[0] = NR_COMPOSEN11_1111 (r, a, p[0]);
846 p[1] = NR_COMPOSEN11_1111 (g, a, p[1]);
847 p[2] = NR_COMPOSEN11_1111 (b, a, p[2]);
848 p += 4;
849 }
850 }
851 }
853 static void
854 grid_vline (SPCanvasBuf *buf, gint x, gint ys, gint ye, guint32 rgba)
855 {
856 if ((x >= buf->rect.x0) && (x < buf->rect.x1)) {
857 guint r, g, b, a;
858 gint y0, y1, y;
859 guchar *p;
860 r = NR_RGBA32_R(rgba);
861 g = NR_RGBA32_G (rgba);
862 b = NR_RGBA32_B (rgba);
863 a = NR_RGBA32_A (rgba);
864 y0 = MAX (buf->rect.y0, ys);
865 y1 = MIN (buf->rect.y1, ye + 1);
866 p = buf->buf + (y0 - buf->rect.y0) * buf->buf_rowstride + (x - buf->rect.x0) * 4;
867 for (y = y0; y < y1; y++) {
868 p[0] = NR_COMPOSEN11_1111 (r, a, p[0]);
869 p[1] = NR_COMPOSEN11_1111 (g, a, p[1]);
870 p[2] = NR_COMPOSEN11_1111 (b, a, p[2]);
871 p += buf->buf_rowstride;
872 }
873 }
874 }
876 static void
877 grid_dot (SPCanvasBuf *buf, gint x, gint y, guint32 rgba)
878 {
879 if ( (y >= buf->rect.y0) && (y < buf->rect.y1)
880 && (x >= buf->rect.x0) && (x < buf->rect.x1) ) {
881 guint r, g, b, a;
882 guchar *p;
883 r = NR_RGBA32_R (rgba);
884 g = NR_RGBA32_G (rgba);
885 b = NR_RGBA32_B (rgba);
886 a = NR_RGBA32_A (rgba);
887 p = buf->buf + (y - buf->rect.y0) * buf->buf_rowstride + (x - buf->rect.x0) * 4;
888 p[0] = NR_COMPOSEN11_1111 (r, a, p[0]);
889 p[1] = NR_COMPOSEN11_1111 (g, a, p[1]);
890 p[2] = NR_COMPOSEN11_1111 (b, a, p[2]);
891 }
892 }
894 void
895 CanvasXYGrid::Render (SPCanvasBuf *buf)
896 {
897 gdouble const sxg = floor ((buf->rect.x0 - ow[Geom::X]) / sw[Geom::X]) * sw[Geom::X] + ow[Geom::X];
898 gint const xlinestart = (gint) Inkscape::round((sxg - ow[Geom::X]) / sw[Geom::X]);
899 gdouble const syg = floor ((buf->rect.y0 - ow[Geom::Y]) / sw[Geom::Y]) * sw[Geom::Y] + ow[Geom::Y];
900 gint const ylinestart = (gint) Inkscape::round((syg - ow[Geom::Y]) / sw[Geom::Y]);
902 //set correct coloring, depending preference (when zoomed out, always major coloring or minor coloring)
903 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
904 guint32 _empcolor;
905 bool no_emp_when_zoomed_out = prefs->getBool("/options/grids/no_emphasize_when_zoomedout", false);
906 if( (scaled[Geom::X] || scaled[Geom::Y]) && no_emp_when_zoomed_out ) {
907 _empcolor = color;
908 } else {
909 _empcolor = empcolor;
910 }
912 if (!render_dotted) {
913 gint ylinenum;
914 gdouble y;
915 for (y = syg, ylinenum = ylinestart; y < buf->rect.y1; y += sw[Geom::Y], ylinenum++) {
916 gint const y0 = (gint) Inkscape::round(y);
917 if (!scaled[Geom::Y] && (ylinenum % empspacing) != 0) {
918 grid_hline (buf, y0, buf->rect.x0, buf->rect.x1 - 1, color);
919 } else {
920 grid_hline (buf, y0, buf->rect.x0, buf->rect.x1 - 1, _empcolor);
921 }
922 }
924 gint xlinenum;
925 gdouble x;
926 for (x = sxg, xlinenum = xlinestart; x < buf->rect.x1; x += sw[Geom::X], xlinenum++) {
927 gint const ix = (gint) Inkscape::round(x);
928 if (!scaled[Geom::X] && (xlinenum % empspacing) != 0) {
929 grid_vline (buf, ix, buf->rect.y0, buf->rect.y1, color);
930 } else {
931 grid_vline (buf, ix, buf->rect.y0, buf->rect.y1, _empcolor);
932 }
933 }
934 } else {
935 gint ylinenum;
936 gdouble y;
937 for (y = syg, ylinenum = ylinestart; y < buf->rect.y1; y += sw[Geom::Y], ylinenum++) {
938 gint const iy = (gint) Inkscape::round(y);
940 gint xlinenum;
941 gdouble x;
942 for (x = sxg, xlinenum = xlinestart; x < buf->rect.x1; x += sw[Geom::X], xlinenum++) {
943 gint const ix = (gint) Inkscape::round(x);
944 if ( (!scaled[Geom::X] && (xlinenum % empspacing) != 0)
945 || (!scaled[Geom::Y] && (ylinenum % empspacing) != 0)
946 || ((scaled[Geom::X] || scaled[Geom::Y]) && no_emp_when_zoomed_out) )
947 {
948 grid_dot (buf, ix, iy, color | (guint32)0x000000FF); // put alpha to max value
949 } else {
950 gint const pitch = 1;
951 grid_dot (buf, ix-pitch, iy, _empcolor);
952 grid_dot (buf, ix+pitch, iy, _empcolor);
954 grid_dot (buf, ix, iy, _empcolor | (guint32)0x000000FF); // put alpha to max value
956 grid_dot (buf, ix, iy-pitch, _empcolor);
957 grid_dot (buf, ix, iy+pitch, _empcolor);
958 }
959 }
961 }
962 }
963 }
965 CanvasXYGridSnapper::CanvasXYGridSnapper(CanvasXYGrid *grid, SnapManager *sm, Geom::Coord const d) : LineSnapper(sm, d)
966 {
967 this->grid = grid;
968 }
970 /**
971 * \return Snap tolerance (desktop coordinates); depends on current zoom so that it's always the same in screen pixels
972 */
973 Geom::Coord CanvasXYGridSnapper::getSnapperTolerance() const
974 {
975 SPDesktop const *dt = _snapmanager->getDesktop();
976 double const zoom = dt ? dt->current_zoom() : 1;
977 return _snapmanager->snapprefs.getGridTolerance() / zoom;
978 }
980 bool CanvasXYGridSnapper::getSnapperAlwaysSnap() const
981 {
982 return _snapmanager->snapprefs.getGridTolerance() == 10000; //TODO: Replace this threshold of 10000 by a constant; see also tolerance-slider.cpp
983 }
985 LineSnapper::LineList
986 CanvasXYGridSnapper::_getSnapLines(Geom::Point const &p) const
987 {
988 LineList s;
990 if ( grid == NULL ) {
991 return s;
992 }
994 for (unsigned int i = 0; i < 2; ++i) {
996 double spacing;
998 if (getSnapVisibleOnly()) {
999 // Only snapping to visible grid lines
1000 spacing = grid->sw[i]; // this is the spacing of the visible grid lines measured in screen pixels
1001 // convert screen pixels to px
1002 // FIXME: after we switch to snapping dist in screen pixels, this will be unnecessary
1003 SPDesktop const *dt = _snapmanager->getDesktop();
1004 if (dt) {
1005 spacing /= dt->current_zoom();
1006 }
1007 } else {
1008 // Snapping to any grid line, whether it's visible or not
1009 spacing = grid->spacing[i];
1010 }
1012 Geom::Coord rounded;
1013 Geom::Point point_on_line;
1015 rounded = Inkscape::Util::round_to_upper_multiple_plus(p[i], spacing, grid->origin[i]);
1016 point_on_line = i ? Geom::Point(0, rounded) : Geom::Point(rounded, 0);
1017 s.push_back(std::make_pair(component_vectors[i], point_on_line));
1019 rounded = Inkscape::Util::round_to_lower_multiple_plus(p[i], spacing, grid->origin[i]);
1020 point_on_line = i ? Geom::Point(0, rounded) : Geom::Point(rounded, 0);
1021 s.push_back(std::make_pair(component_vectors[i], point_on_line));
1022 }
1024 return s;
1025 }
1027 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
1028 {
1029 SnappedLine dummy = SnappedLine(snapped_point, snapped_distance, source, source_num, Inkscape::SNAPTARGET_GRID, getSnapperTolerance(), getSnapperAlwaysSnap(), normal_to_line, point_on_line);
1030 sc.grid_lines.push_back(dummy);
1031 }
1033 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
1034 {
1035 SnappedPoint dummy = SnappedPoint(snapped_point, source, source_num, Inkscape::SNAPTARGET_GRID, snapped_distance, getSnapperTolerance(), getSnapperAlwaysSnap(), constrained_snap, true);
1036 sc.points.push_back(dummy);
1037 }
1039 /**
1040 * \return true if this Snapper will snap at least one kind of point.
1041 */
1042 bool CanvasXYGridSnapper::ThisSnapperMightSnap() const
1043 {
1044 return _snap_enabled && _snapmanager->snapprefs.getSnapToGrids() && _snapmanager->snapprefs.getSnapModeBBoxOrNodes();
1045 }
1047 } // namespace Inkscape
1050 /*
1051 Local Variables:
1052 mode:c++
1053 c-file-style:"stroustrup"
1054 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1055 indent-tabs-mode:nil
1056 fill-column:99
1057 End:
1058 */
1059 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :