Code

comment typo
[inkscape.git] / src / display / canvas-grid.cpp
1 #define INKSCAPE_CANVAS_GRID_C
3 /*
4  *
5  * Copyright (C) Johan Engelen 2006-2007 <johan@shouraizou.nl>
6  * Copyright (C) Lauris Kaplinski 2000
7  *
8  */
10 /* As a general comment, I am not exactly proud of how things are done.
11  * (for example the 'enable' widget and readRepr things)
12  * It does seem to work however. I intend to clean up and sort things out later, but that can take forever...
13  * Don't be shy to correct things.
14  */
17 #include "sp-canvas-util.h"
18 #include "util/mathfns.h" 
19 #include "display-forward.h"
20 #include <libnr/nr-pixops.h>
21 #include "desktop-handles.h"
22 #include "helper/units.h"
23 #include "svg/svg-color.h"
24 #include "xml/node-event-vector.h"
25 #include "sp-object.h"
27 #include "sp-namedview.h"
28 #include "inkscape.h"
29 #include "desktop.h"
31 #include "../document.h"
32 #include "prefs-utils.h"
34 #include "canvas-grid.h"
35 #include "canvas-axonomgrid.h"
37 namespace Inkscape {
39 static gchar const *const grid_name[] = {
40     N_("Rectangular grid"),
41     N_("Axonometric grid")
42 };
43 static gchar const *const grid_svgname[] = {
44     "xygrid",
45     "axonomgrid"
46 };
49 // ##########################################################
50 // Grid CanvasItem
51 static void grid_canvasitem_class_init (GridCanvasItemClass *klass);
52 static void grid_canvasitem_init (GridCanvasItem *grid);
53 static void grid_canvasitem_destroy (GtkObject *object);
55 static void grid_canvasitem_update (SPCanvasItem *item, NR::Matrix const &affine, unsigned int flags);
56 static void grid_canvasitem_render (SPCanvasItem *item, SPCanvasBuf *buf);
58 static SPCanvasItemClass * parent_class;
60 GtkType
61 grid_canvasitem_get_type (void)
62 {
63     static GtkType grid_canvasitem_type = 0;
65     if (!grid_canvasitem_type) {
66         GtkTypeInfo grid_canvasitem_info = {
67             (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, NR::Matrix const &affine, unsigned int flags)
129     GridCanvasItem *gridcanvasitem = INKSCAPE_GRID_CANVASITEM (item);
131     if (parent_class->update)
132         (* parent_class->update) (item, affine, flags);
134     if (gridcanvasitem->grid) {
135         gridcanvasitem->grid->Update(affine, flags);
137         sp_canvas_request_redraw (item->canvas,
138                          -1000000, -1000000,
139                          1000000, 1000000);
141         item->x1 = item->y1 = -1000000;
142         item->x2 = item->y2 = 1000000;
143     }
148 // ##########################################################
149 //   CanvasGrid
151     static Inkscape::XML::NodeEventVector const _repr_events = {
152         NULL, /* child_added */
153         NULL, /* child_removed */
154         CanvasGrid::on_repr_attr_changed,
155         NULL, /* content_changed */
156         NULL  /* order_changed */
157     };
159 CanvasGrid::CanvasGrid(SPNamedView * nv, Inkscape::XML::Node * in_repr, SPDocument *in_doc, GridType type)
160     : visible(true), gridtype(type)
162     repr = in_repr;
163     doc = in_doc;
164     if (repr) {
165         repr->addListener (&_repr_events, this);
166     }
168     namedview = nv;
169     canvasitems = NULL;
172 CanvasGrid::~CanvasGrid()
174     if (repr) {
175         repr->removeListenerByData (this);
176     }
178     while (canvasitems) {
179         gtk_object_destroy(GTK_OBJECT(canvasitems->data));
180         canvasitems = g_slist_remove(canvasitems, canvasitems->data);
181     }
184 const char *
185 CanvasGrid::getName()
187     return _(grid_name[gridtype]);
190 const char *
191 CanvasGrid::getSVGName()
193     return grid_svgname[gridtype];
196 GridType
197 CanvasGrid::getGridType()
199     return gridtype;
203 char const *
204 CanvasGrid::getName(GridType type)
206     return _(grid_name[type]);
209 char const *
210 CanvasGrid::getSVGName(GridType type)
212     return grid_svgname[type];
215 GridType
216 CanvasGrid::getGridTypeFromSVGName(char const *typestr)
218     if (!typestr) return GRID_RECTANGULAR;
220     gint t = 0;
221     for (t = GRID_MAXTYPENR; t >= 0; t--) {  //this automatically defaults to grid0 which is rectangular grid
222         if (!strcmp(typestr, grid_svgname[t])) break;
223     }
224     return (GridType) t;
227 GridType
228 CanvasGrid::getGridTypeFromName(char const *typestr)
230     if (!typestr) return GRID_RECTANGULAR;
232     gint t = 0;
233     for (t = GRID_MAXTYPENR; t >= 0; t--) {  //this automatically defaults to grid0 which is rectangular grid
234         if (!strcmp(typestr, _(grid_name[t]))) break;
235     }
236     return (GridType) t;
240 /*
241 *  writes an <inkscape:grid> child to repr.
242 */
243 void
244 CanvasGrid::writeNewGridToRepr(Inkscape::XML::Node * repr, SPDocument * doc, GridType gridtype)
246     if (!repr) return;
247     if (gridtype > GRID_MAXTYPENR) return;
249     // first create the child xml node, then hook it to repr. This order is important, to not set off listeners to repr before the new node is complete.
251     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
252     Inkscape::XML::Node *newnode;
253     newnode = xml_doc->createElement("inkscape:grid");
254     newnode->setAttribute("type", getSVGName(gridtype));
256     repr->appendChild(newnode);
257     Inkscape::GC::release(newnode);
259     sp_document_done(doc, SP_VERB_DIALOG_NAMEDVIEW, _("Create new grid"));
262 /*
263 * Creates a new CanvasGrid object of type gridtype
264 */
265 CanvasGrid*
266 CanvasGrid::NewGrid(SPNamedView * nv, Inkscape::XML::Node * repr, SPDocument * doc, GridType gridtype)
268     if (!repr) return NULL;
269     if (!doc) {
270         g_error("CanvasGrid::NewGrid - doc==NULL");
271         return NULL;
272     }
274     switch (gridtype) {
275         case GRID_RECTANGULAR:
276             return (CanvasGrid*) new CanvasXYGrid(nv, repr, doc);
277         case GRID_AXONOMETRIC:
278             return (CanvasGrid*) new CanvasAxonomGrid(nv, repr, doc);
279     }
281     return NULL;
285 /**
286 *  creates a new grid canvasitem for the SPDesktop given as parameter. Keeps a link to this canvasitem in the canvasitems list.
287 */
288 GridCanvasItem *
289 CanvasGrid::createCanvasItem(SPDesktop * desktop)
291     if (!desktop) return NULL;
292 //    Johan: I think for multiple desktops it is best if each has their own canvasitem,
293 //           but share the same CanvasGrid object; that is what this function is for.
295     // check if there is already a canvasitem on this desktop linking to this grid
296     for (GSList *l = canvasitems; l != NULL; l = l->next) {
297         if ( sp_desktop_gridgroup(desktop) == SP_CANVAS_GROUP(SP_CANVAS_ITEM(l->data)->parent) ) {
298             return NULL;
299         }
300     }
302     GridCanvasItem * item = INKSCAPE_GRID_CANVASITEM( sp_canvas_item_new(sp_desktop_gridgroup(desktop), INKSCAPE_TYPE_GRID_CANVASITEM, NULL) );
303     item->grid = this;
304     sp_canvas_item_show(SP_CANVAS_ITEM(item));
306     gtk_object_ref(GTK_OBJECT(item));    // since we're keeping a link to this item, we need to bump up the ref count
307     canvasitems = g_slist_prepend(canvasitems, item);
309     return item;
312 Gtk::Widget *
313 CanvasGrid::newWidget()
315     Gtk::VBox * vbox = Gtk::manage( new Gtk::VBox() );
316     Gtk::Label * namelabel = Gtk::manage(new Gtk::Label("", Gtk::ALIGN_CENTER) );
318     Glib::ustring str("<b>");
319     str += getName();
320     str += "</b>";
321     namelabel->set_markup(str);
322     vbox->pack_start(*namelabel, true, true);
324     Inkscape::UI::Widget::RegisteredCheckButton * _rcb_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     gridunit = sp_unit_get_by_abbreviation( prefs_get_string_attribute("options.grids.xy", "units") );
419     if (!gridunit)
420         gridunit = &sp_unit_get_by_id(SP_UNIT_PX);
421     origin[NR::X] = sp_units_get_pixels( prefs_get_double_attribute ("options.grids.xy", "origin_x", 0.0), *(gridunit) );
422     origin[NR::Y] = sp_units_get_pixels( prefs_get_double_attribute ("options.grids.xy", "origin_y", 0.0), *(gridunit) );
423     color = prefs_get_int_attribute("options.grids.xy", "color", 0x0000ff20);
424     empcolor = prefs_get_int_attribute("options.grids.xy", "empcolor", 0x0000ff40);
425     empspacing = prefs_get_int_attribute("options.grids.xy", "empspacing", 5);
426     spacing[NR::X] = sp_units_get_pixels( prefs_get_double_attribute ("options.grids.xy", "spacing_x", 0.0), *(gridunit) );
427     spacing[NR::Y] = sp_units_get_pixels( prefs_get_double_attribute ("options.grids.xy", "spacing_y", 0.0), *(gridunit) );
428     render_dotted = prefs_get_int_attribute ("options.grids.xy", "dotted", 0) == 1;
430     snapper = new CanvasXYGridSnapper(this, namedview, 0);
432     if (repr) readRepr();
435 CanvasXYGrid::~CanvasXYGrid ()
437    if (snapper) delete snapper;
441 /* fixme: Collect all these length parsing methods and think common sane API */
443 static gboolean
444 sp_nv_read_length(gchar const *str, guint base, gdouble *val, SPUnit const **unit)
446     if (!str) {
447         return FALSE;
448     }
450     gchar *u;
451     gdouble v = g_ascii_strtod(str, &u);
452     if (!u) {
453         return FALSE;
454     }
455     while (isspace(*u)) {
456         u += 1;
457     }
459     if (!*u) {
460         /* No unit specified - keep default */
461         *val = v;
462         return TRUE;
463     }
465     if (base & SP_UNIT_DEVICE) {
466         if (u[0] && u[1] && !isalnum(u[2]) && !strncmp(u, "px", 2)) {
467             *unit = &sp_unit_get_by_id(SP_UNIT_PX);
468             *val = v;
469             return TRUE;
470         }
471     }
473     if (base & SP_UNIT_ABSOLUTE) {
474         if (!strncmp(u, "pt", 2)) {
475             *unit = &sp_unit_get_by_id(SP_UNIT_PT);
476         } else if (!strncmp(u, "mm", 2)) {
477             *unit = &sp_unit_get_by_id(SP_UNIT_MM);
478         } else if (!strncmp(u, "cm", 2)) {
479             *unit = &sp_unit_get_by_id(SP_UNIT_CM);
480         } else if (!strncmp(u, "m", 1)) {
481             *unit = &sp_unit_get_by_id(SP_UNIT_M);
482         } else if (!strncmp(u, "in", 2)) {
483             *unit = &sp_unit_get_by_id(SP_UNIT_IN);
484         } else {
485             return FALSE;
486         }
487         *val = v;
488         return TRUE;
489     }
491     return FALSE;
494 static gboolean sp_nv_read_opacity(gchar const *str, guint32 *color)
496     if (!str) {
497         return FALSE;
498     }
500     gchar *u;
501     gdouble v = g_ascii_strtod(str, &u);
502     if (!u) {
503         return FALSE;
504     }
505     v = CLAMP(v, 0.0, 1.0);
507     *color = (*color & 0xffffff00) | (guint32) floor(v * 255.9999);
509     return TRUE;
512 /** If the passed scalar is invalid (<=0), then set the widget and the scalar
513     to use the given old value.
515     @param oldVal Old value to use if the new one is invalid.
516     @param pTarget The scalar to validate.
517     @param widget Widget associated with the scalar.
518 */
519 static void validateScalar(double oldVal,
520                            double* pTarget)
522     // Avoid nullness.
523     if ( pTarget == NULL )
524         return;
526     // Invalid new value?
527     if ( *pTarget <= 0 ) {
528         // If the old value is somehow invalid as well, then default to 1.
529         if ( oldVal <= 0 )
530             oldVal = 1;
532         // Reset the scalar and associated widget to the old value.
533         *pTarget = oldVal;
534     } //if
536 } //validateScalar
539 /** If the passed int is invalid (<=0), then set the widget and the int
540     to use the given old value.
542     @param oldVal Old value to use if the new one is invalid.
543     @param pTarget The int to validate.
544     @param widget Widget associated with the int.
545 */
546 static void validateInt(gint oldVal,
547                         gint* pTarget)
549     // Avoid nullness.
550     if ( pTarget == NULL )
551         return;
553     // Invalid new value?
554     if ( *pTarget <= 0 ) {
555         // If the old value is somehow invalid as well, then default to 1.
556         if ( oldVal <= 0 )
557             oldVal = 1;
559         // Reset the int and associated widget to the old value.
560         *pTarget = oldVal;
561     } //if
563 } //validateInt
565 void
566 CanvasXYGrid::readRepr()
568     gchar const *value;
569     if ( (value = repr->attribute("originx")) ) {
570         sp_nv_read_length(value, SP_UNIT_ABSOLUTE | SP_UNIT_DEVICE, &origin[NR::X], &gridunit);
571         origin[NR::X] = sp_units_get_pixels(origin[NR::X], *(gridunit));
572     }
574     if ( (value = repr->attribute("originy")) ) {
575         sp_nv_read_length(value, SP_UNIT_ABSOLUTE | SP_UNIT_DEVICE, &origin[NR::Y], &gridunit);
576         origin[NR::Y] = sp_units_get_pixels(origin[NR::Y], *(gridunit));
577     }
579     if ( (value = repr->attribute("spacingx")) ) {
580         double oldVal = spacing[NR::X];
581         sp_nv_read_length(value, SP_UNIT_ABSOLUTE | SP_UNIT_DEVICE, &spacing[NR::X], &gridunit);
582         validateScalar( oldVal, &spacing[NR::X]);
583         spacing[NR::X] = sp_units_get_pixels(spacing[NR::X], *(gridunit));
585     }
586     if ( (value = repr->attribute("spacingy")) ) {
587         double oldVal = spacing[NR::Y];
588         sp_nv_read_length(value, SP_UNIT_ABSOLUTE | SP_UNIT_DEVICE, &spacing[NR::Y], &gridunit);
589         validateScalar( oldVal, &spacing[NR::Y]);
590         spacing[NR::Y] = sp_units_get_pixels(spacing[NR::Y], *(gridunit));
592     }
594     if ( (value = repr->attribute("color")) ) {
595         color = (color & 0xff) | sp_svg_read_color(value, color);
596     }
598     if ( (value = repr->attribute("empcolor")) ) {
599         empcolor = (empcolor & 0xff) | sp_svg_read_color(value, empcolor);
600     }
602     if ( (value = repr->attribute("opacity")) ) {
603         sp_nv_read_opacity(value, &color);
604     }
605     if ( (value = repr->attribute("empopacity")) ) {
606         sp_nv_read_opacity(value, &empcolor);
607     }
609     if ( (value = repr->attribute("empspacing")) ) {
610         gint oldVal = empspacing;
611         empspacing = atoi(value);
612         validateInt( oldVal, &empspacing);
613     }
615     if ( (value = repr->attribute("dotted")) ) {
616         render_dotted = (strcmp(value,"true") == 0);
617     }
619     if ( (value = repr->attribute("visible")) ) {
620         visible = (strcmp(value,"true") == 0);
621     }
622     
623     if ( (value = repr->attribute("enabled")) ) {
624         g_assert(snapper != NULL);
625         snapper->setEnabled(strcmp(value,"true") == 0);
626     }
628     for (GSList *l = canvasitems; l != NULL; l = l->next) {
629         sp_canvas_item_request_update ( SP_CANVAS_ITEM(l->data) );
630     }
632     return;
635 /**
636  * Called when XML node attribute changed; updates dialog widgets if change was not done by widgets themselves.
637  */
638 void
639 CanvasXYGrid::onReprAttrChanged(Inkscape::XML::Node */*repr*/, gchar const */*key*/, gchar const */*oldval*/, gchar const */*newval*/, bool /*is_interactive*/)
641     readRepr();
643     if ( ! (_wr.isUpdating()) )
644         updateWidgets();
650 Gtk::Widget *
651 CanvasXYGrid::newSpecificWidget()
653     Gtk::Table * table = Gtk::manage( new Gtk::Table(1,1) );
655     Inkscape::UI::Widget::RegisteredUnitMenu *_rumg = Gtk::manage( new Inkscape::UI::Widget::RegisteredUnitMenu(
656             _("Grid _units:"), "units", _wr, repr, doc) );
657     Inkscape::UI::Widget::RegisteredScalarUnit *_rsu_ox = Gtk::manage( new Inkscape::UI::Widget::RegisteredScalarUnit(
658             _("_Origin X:"), _("X coordinate of grid origin"), "originx", *_rumg, _wr, repr, doc) );
659     Inkscape::UI::Widget::RegisteredScalarUnit *_rsu_oy = Gtk::manage( new Inkscape::UI::Widget::RegisteredScalarUnit(
660             _("O_rigin Y:"), _("Y coordinate of grid origin"), "originy", *_rumg, _wr, repr, doc) );
661     Inkscape::UI::Widget::RegisteredScalarUnit *_rsu_sx = Gtk::manage( new Inkscape::UI::Widget::RegisteredScalarUnit(
662             _("Spacing _X:"), _("Distance between vertical grid lines"), "spacingx", *_rumg, _wr, repr, doc) );
663     Inkscape::UI::Widget::RegisteredScalarUnit *_rsu_sy = Gtk::manage( new Inkscape::UI::Widget::RegisteredScalarUnit(
664             _("Spacing _Y:"), _("Distance between horizontal grid lines"), "spacingy", *_rumg, _wr, repr, doc) );
666     Inkscape::UI::Widget::RegisteredColorPicker *_rcp_gcol = Gtk::manage(
667         new Inkscape::UI::Widget::RegisteredColorPicker(
668             _("Grid line _color:"), _("Grid line color"), _("Color of grid lines"), 
669             "color", "opacity", _wr, repr, doc));
671     Inkscape::UI::Widget::RegisteredColorPicker *_rcp_gmcol = Gtk::manage(
672         new Inkscape::UI::Widget::RegisteredColorPicker(
673             _("Ma_jor grid line color:"), _("Major grid line color"), 
674             _("Color of the major (highlighted) grid lines"), "empcolor", "empopacity", 
675             _wr, repr, doc));
676     
677     Inkscape::UI::Widget::RegisteredSuffixedInteger *_rsi = Gtk::manage( new Inkscape::UI::Widget::RegisteredSuffixedInteger(
678             _("_Major grid line every:"), "", _("lines"), "empspacing", _wr, repr, doc) );
680     table->set_spacings(2);
682 _wr.setUpdating (true);
684     _rsu_ox->setDigits(4);
685     _rsu_ox->setIncrements(0.1, 1.0);
687     _rsu_oy->setDigits(4);
688     _rsu_oy->setIncrements(0.1, 1.0);
690     _rsu_sx->setDigits(4);
691     _rsu_sx->setIncrements(0.1, 1.0);
693     _rsu_sy->setDigits(4);
694     _rsu_sy->setIncrements(0.1, 1.0);
696     Inkscape::UI::Widget::RegisteredCheckButton * _rcb_dotted = Gtk::manage(
697                 new Inkscape::UI::Widget::RegisteredCheckButton( _("_Show dots instead of lines"),
698                        _("If set, displays dots at gridpoints instead of gridlines"),
699                         "dotted", _wr, false, repr, doc) );
700 _wr.setUpdating (false);
702     Gtk::Widget const *const widget_array[] = {
703         0,                  _rumg,
704         0,                  _rsu_ox,
705         0,                  _rsu_oy,
706         0,                  _rsu_sx,
707         0,                  _rsu_sy,
708         _rcp_gcol->_label,   _rcp_gcol,
709         0,                  0,
710         _rcp_gmcol->_label,  _rcp_gmcol,
711         0,                  _rsi,
712         0,                  _rcb_dotted,
713     };
715     attach_all (*table, widget_array, sizeof(widget_array));
717     // set widget values
718     _rumg->setUnit (gridunit);
720     gdouble val;
721     val = origin[NR::X];
722     val = sp_pixels_get_units (val, *(gridunit));
723     _rsu_ox->setValue (val);
724     val = origin[NR::Y];
725     val = sp_pixels_get_units (val, *(gridunit));
726     _rsu_oy->setValue (val);
727     val = spacing[NR::X];
728     double gridx = sp_pixels_get_units (val, *(gridunit));
729     _rsu_sx->setValue (gridx);
730     val = spacing[NR::Y];
731     double gridy = sp_pixels_get_units (val, *(gridunit));
732     _rsu_sy->setValue (gridy);
734     _rcp_gcol->setRgba32 (color);
735     _rcp_gmcol->setRgba32 (empcolor);
736     _rsi->setValue (empspacing);
738     _rcb_dotted->setActive(render_dotted);
740     return table;
744 /**
745  * Update dialog widgets from object's values.
746  */
747 void
748 CanvasXYGrid::updateWidgets()
750 /*
751     if (_wr.isUpdating()) return;
753     _wr.setUpdating (true);
755     _rcb_visible.setActive(visible);
756     if (snapper != NULL) {
757         _rcb_enabled.setActive(snapper->getEnabled());
758     }
760     _rumg.setUnit (gridunit);
762     gdouble val;
763     val = origin[NR::X];
764     val = sp_pixels_get_units (val, *(gridunit));
765     _rsu_ox.setValue (val);
766     val = origin[NR::Y];
767     val = sp_pixels_get_units (val, *(gridunit));
768     _rsu_oy.setValue (val);
769     val = spacing[NR::X];
770     double gridx = sp_pixels_get_units (val, *(gridunit));
771     _rsu_sx.setValue (gridx);
772     val = spacing[NR::Y];
773     double gridy = sp_pixels_get_units (val, *(gridunit));
774     _rsu_sy.setValue (gridy);
776     _rcp_gcol.setRgba32 (color);
777     _rcp_gmcol.setRgba32 (empcolor);
778     _rsi.setValue (empspacing);
780     _rcb_dotted.setActive(render_dotted);
782     _wr.setUpdating (false);
784     return;
785 */
790 void
791 CanvasXYGrid::Update (NR::Matrix const &affine, unsigned int /*flags*/)
793     ow = origin * affine;
794     sw = spacing * affine;
795     sw -= NR::Point(affine[4], affine[5]);
797     for(int dim = 0; dim < 2; dim++) {
798         gint scaling_factor = empspacing;
800         if (scaling_factor <= 1)
801             scaling_factor = 5;
803         scaled[dim] = FALSE;
804         sw[dim] = fabs (sw[dim]);
805         while (sw[dim] < 8.0) {
806             scaled[dim] = TRUE;
807             sw[dim] *= scaling_factor;
808             /* First pass, go up to the major line spacing, then
809                keep increasing by two. */
810             scaling_factor = 2;
811         }
812     }
816 static void
817 grid_hline (SPCanvasBuf *buf, gint y, gint xs, gint xe, guint32 rgba)
819     if ((y >= buf->rect.y0) && (y < buf->rect.y1)) {
820         guint r, g, b, a;
821         gint x0, x1, x;
822         guchar *p;
823         r = NR_RGBA32_R (rgba);
824         g = NR_RGBA32_G (rgba);
825         b = NR_RGBA32_B (rgba);
826         a = NR_RGBA32_A (rgba);
827         x0 = MAX (buf->rect.x0, xs);
828         x1 = MIN (buf->rect.x1, xe + 1);
829         p = buf->buf + (y - buf->rect.y0) * buf->buf_rowstride + (x0 - buf->rect.x0) * 4;
830         for (x = x0; x < x1; x++) {
831             p[0] = NR_COMPOSEN11_1111 (r, a, p[0]);
832             p[1] = NR_COMPOSEN11_1111 (g, a, p[1]);
833             p[2] = NR_COMPOSEN11_1111 (b, a, p[2]);
834             p += 4;
835         }
836     }
839 static void
840 grid_vline (SPCanvasBuf *buf, gint x, gint ys, gint ye, guint32 rgba)
842     if ((x >= buf->rect.x0) && (x < buf->rect.x1)) {
843         guint r, g, b, a;
844         gint y0, y1, y;
845         guchar *p;
846         r = NR_RGBA32_R(rgba);
847         g = NR_RGBA32_G (rgba);
848         b = NR_RGBA32_B (rgba);
849         a = NR_RGBA32_A (rgba);
850         y0 = MAX (buf->rect.y0, ys);
851         y1 = MIN (buf->rect.y1, ye + 1);
852         p = buf->buf + (y0 - buf->rect.y0) * buf->buf_rowstride + (x - buf->rect.x0) * 4;
853         for (y = y0; y < y1; y++) {
854             p[0] = NR_COMPOSEN11_1111 (r, a, p[0]);
855             p[1] = NR_COMPOSEN11_1111 (g, a, p[1]);
856             p[2] = NR_COMPOSEN11_1111 (b, a, p[2]);
857             p += buf->buf_rowstride;
858         }
859     }
862 static void
863 grid_dot (SPCanvasBuf *buf, gint x, gint y, guint32 rgba)
865     if ( (y >= buf->rect.y0) && (y < buf->rect.y1)
866          && (x >= buf->rect.x0) && (x < buf->rect.x1) ) {
867         guint r, g, b, a;
868         guchar *p;
869         r = NR_RGBA32_R (rgba);
870         g = NR_RGBA32_G (rgba);
871         b = NR_RGBA32_B (rgba);
872         a = NR_RGBA32_A (rgba);
873         p = buf->buf + (y - buf->rect.y0) * buf->buf_rowstride + (x - buf->rect.x0) * 4;
874         p[0] = NR_COMPOSEN11_1111 (r, a, p[0]);
875         p[1] = NR_COMPOSEN11_1111 (g, a, p[1]);
876         p[2] = NR_COMPOSEN11_1111 (b, a, p[2]);
877     }
880 void
881 CanvasXYGrid::Render (SPCanvasBuf *buf)
883     gdouble const sxg = floor ((buf->rect.x0 - ow[NR::X]) / sw[NR::X]) * sw[NR::X] + ow[NR::X];
884     gint const  xlinestart = (gint) Inkscape::round((sxg - ow[NR::X]) / sw[NR::X]);
885     gdouble const syg = floor ((buf->rect.y0 - ow[NR::Y]) / sw[NR::Y]) * sw[NR::Y] + ow[NR::Y];
886     gint const  ylinestart = (gint) Inkscape::round((syg - ow[NR::Y]) / sw[NR::Y]);
888     //set correct coloring, depending preference (when zoomed out, always major coloring or minor coloring)
889     guint32 _empcolor;
890     bool no_emp_when_zoomed_out = prefs_get_int_attribute ("options.grids", "no_emphasize_when_zoomedout", 0) == 1;
891     if( (scaled[NR::X] || scaled[NR::Y]) && no_emp_when_zoomed_out ) {
892         _empcolor = color;
893     } else {
894         _empcolor = empcolor;
895     }
897     if (!render_dotted) {
898         gint ylinenum;
899         gdouble y;
900         for (y = syg, ylinenum = ylinestart; y < buf->rect.y1; y += sw[NR::Y], ylinenum++) {
901             gint const y0 = (gint) Inkscape::round(y);
902             if (!scaled[NR::Y] && (ylinenum % empspacing) != 0) {
903                 grid_hline (buf, y0, buf->rect.x0, buf->rect.x1 - 1, color);
904             } else {
905                 grid_hline (buf, y0, buf->rect.x0, buf->rect.x1 - 1, _empcolor);
906             }
907         }
909         gint xlinenum;
910         gdouble x;
911         for (x = sxg, xlinenum = xlinestart; x < buf->rect.x1; x += sw[NR::X], xlinenum++) {
912             gint const ix = (gint) Inkscape::round(x);
913             if (!scaled[NR::X] && (xlinenum % empspacing) != 0) {
914                 grid_vline (buf, ix, buf->rect.y0, buf->rect.y1, color);
915             } else {
916                 grid_vline (buf, ix, buf->rect.y0, buf->rect.y1, _empcolor);
917             }
918         }
919     } else {
920         gint ylinenum;
921         gdouble y;
922         for (y = syg, ylinenum = ylinestart; y < buf->rect.y1; y += sw[NR::Y], ylinenum++) {
923             gint const iy = (gint) Inkscape::round(y);
925             gint xlinenum;
926             gdouble x;
927             for (x = sxg, xlinenum = xlinestart; x < buf->rect.x1; x += sw[NR::X], xlinenum++) {
928                 gint const ix = (gint) Inkscape::round(x);
929                 if ( (!scaled[NR::X] && (xlinenum % empspacing) != 0)
930                      || (!scaled[NR::Y] && (ylinenum % empspacing) != 0)
931                      || ((scaled[NR::X] || scaled[NR::Y]) && no_emp_when_zoomed_out) )
932                 {
933                     grid_dot (buf, ix, iy, color | (guint32)0x000000FF); // put alpha to max value
934                 } else {
935                     gint const pitch = 1;
936                     grid_dot (buf, ix-pitch, iy, _empcolor);
937                     grid_dot (buf, ix+pitch, iy, _empcolor);
939                     grid_dot (buf, ix, iy, _empcolor | (guint32)0x000000FF);  // put alpha to max value
941                     grid_dot (buf, ix, iy-pitch, _empcolor);
942                     grid_dot (buf, ix, iy+pitch, _empcolor);
943                 }
944             }
946         }
947     }
950 CanvasXYGridSnapper::CanvasXYGridSnapper(CanvasXYGrid *grid, SPNamedView const *nv, NR::Coord const d) : LineSnapper(nv, d)
952     this->grid = grid;
955 LineSnapper::LineList
956 CanvasXYGridSnapper::_getSnapLines(Geom::Point const &p) const
958     LineList s;
960     if ( grid == NULL ) {
961         return s;
962     }
964     for (unsigned int i = 0; i < 2; ++i) {
966         /* This is to make sure we snap to only visible grid lines */
967         double scaled_spacing = grid->sw[i]; // this is spacing of visible lines in screen pixels
969         // convert screen pixels to px
970         // FIXME: after we switch to snapping dist in screen pixels, this will be unnecessary
971         if (SP_ACTIVE_DESKTOP) {
972             scaled_spacing /= SP_ACTIVE_DESKTOP->current_zoom();
973         }
975         Geom::Coord rounded;        
976         Geom::Point point_on_line;
977         
978         rounded = Inkscape::Util::round_to_upper_multiple_plus(p[i], scaled_spacing, grid->origin[i]);
979         point_on_line = i ? Geom::Point(0, rounded) : Geom::Point(rounded, 0);
980         s.push_back(std::make_pair(component_vectors[i], point_on_line));
981         
982         rounded = Inkscape::Util::round_to_lower_multiple_plus(p[i], scaled_spacing, grid->origin[i]);
983         point_on_line = i ? Geom::Point(0, rounded) : Geom::Point(rounded, 0);
984         s.push_back(std::make_pair(component_vectors[i], point_on_line));
985     }
987     return s;
990 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 
992     SnappedLine dummy = SnappedLine(snapped_point, snapped_distance, getSnapperTolerance(), getSnapperAlwaysSnap(), normal_to_line, point_on_line);
993     sc.grid_lines.push_back(dummy);
996 /**
997  *  \return true if this Snapper will snap at least one kind of point.
998  */
999 bool CanvasXYGridSnapper::ThisSnapperMightSnap() const
1001     return _named_view == NULL ? false : (_snap_enabled && _snap_from != 0);
1008 }; /* namespace Inkscape */
1011 /*
1012   Local Variables:
1013   mode:c++
1014   c-file-style:"stroustrup"
1015   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1016   indent-tabs-mode:nil
1017   fill-column:99
1018   End:
1019 */
1020 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :