Code

- Created a SPLPEItem class that handles applying a LPE to an Item
[inkscape.git] / src / draw-context.cpp
1 #define __SP_DRAW_CONTEXT_C__
3 /*
4  * Generic drawing context
5  *
6  * Author:
7  *   Lauris Kaplinski <lauris@kaplinski.com>
8  *
9  * Copyright (C) 2000 Lauris Kaplinski
10  * Copyright (C) 2000-2001 Ximian, Inc.
11  * Copyright (C) 2002 Lauris Kaplinski
12  *
13  * Released under GNU GPL, read the file 'COPYING' for more information
14  */
16 #define DRAW_VERBOSE
18 #ifdef HAVE_CONFIG_H
19 # include "config.h"
20 #endif
21 #include <gdk/gdkkeysyms.h>
23 #include "display/canvas-bpath.h"
24 #include "xml/repr.h"
25 #include "svg/svg.h"
26 #include <glibmm/i18n.h>
27 #include "libnr/n-art-bpath.h"
28 #include "desktop.h"
29 #include "desktop-affine.h"
30 #include "desktop-handles.h"
31 #include "desktop-style.h"
32 #include "document.h"
33 #include "draw-anchor.h"
34 #include "macros.h"
35 #include "message-stack.h"
36 #include "pen-context.h"
37 #include "prefs-utils.h"
38 #include "selection.h"
39 #include "selection-chemistry.h"
40 #include "snap.h"
41 #include "sp-path.h"
42 #include "sp-namedview.h"
43 #include "display/snap-indicator.h"
45 static void sp_draw_context_class_init(SPDrawContextClass *klass);
46 static void sp_draw_context_init(SPDrawContext *dc);
47 static void sp_draw_context_dispose(GObject *object);
49 static void sp_draw_context_setup(SPEventContext *ec);
50 static void sp_draw_context_set(SPEventContext *ec, gchar const *key, gchar const *value);
51 static void sp_draw_context_finish(SPEventContext *ec);
53 static gint sp_draw_context_root_handler(SPEventContext *event_context, GdkEvent *event);
55 static void spdc_selection_changed(Inkscape::Selection *sel, SPDrawContext *dc);
56 static void spdc_selection_modified(Inkscape::Selection *sel, guint flags, SPDrawContext *dc);
58 static void spdc_attach_selection(SPDrawContext *dc, Inkscape::Selection *sel);
60 static void spdc_flush_white(SPDrawContext *dc, SPCurve *gc);
62 static void spdc_reset_white(SPDrawContext *dc);
63 static void spdc_free_colors(SPDrawContext *dc);
66 static SPEventContextClass *draw_parent_class;
69 GType
70 sp_draw_context_get_type(void)
71 {
72     static GType type = 0;
73     if (!type) {
74         GTypeInfo info = {
75             sizeof(SPDrawContextClass),
76             NULL, NULL,
77             (GClassInitFunc) sp_draw_context_class_init,
78             NULL, NULL,
79             sizeof(SPDrawContext),
80             4,
81             (GInstanceInitFunc) sp_draw_context_init,
82             NULL,   /* value_table */
83         };
84         type = g_type_register_static(SP_TYPE_EVENT_CONTEXT, "SPDrawContext", &info, (GTypeFlags)0);
85     }
86     return type;
87 }
89 static void
90 sp_draw_context_class_init(SPDrawContextClass *klass)
91 {
92     GObjectClass *object_class;
93     SPEventContextClass *ec_class;
95     object_class = (GObjectClass *)klass;
96     ec_class = (SPEventContextClass *) klass;
98     draw_parent_class = (SPEventContextClass*)g_type_class_peek_parent(klass);
100     object_class->dispose = sp_draw_context_dispose;
102     ec_class->setup = sp_draw_context_setup;
103     ec_class->set = sp_draw_context_set;
104     ec_class->finish = sp_draw_context_finish;
105     ec_class->root_handler = sp_draw_context_root_handler;
108 static void
109 sp_draw_context_init(SPDrawContext *dc)
111     dc->attach = FALSE;
113     dc->red_color = 0xff00007f;
114     dc->blue_color = 0x0000ff7f;
115     dc->green_color = 0x00ff007f;
116     dc->red_curve_is_valid = false;
118     new (&dc->sel_changed_connection) sigc::connection();
119     new (&dc->sel_modified_connection) sigc::connection();
122 static void
123 sp_draw_context_dispose(GObject *object)
125     SPDrawContext *dc = SP_DRAW_CONTEXT(object);
127     dc->sel_changed_connection.~connection();
128     dc->sel_modified_connection.~connection();
130     if (dc->grab) {
131         sp_canvas_item_ungrab(dc->grab, GDK_CURRENT_TIME);
132         dc->grab = NULL;
133     }
135     if (dc->selection) {
136         dc->selection = NULL;
137     }
139     spdc_free_colors(dc);
141     G_OBJECT_CLASS(draw_parent_class)->dispose(object);
144 static void
145 sp_draw_context_setup(SPEventContext *ec)
147     SPDrawContext *dc = SP_DRAW_CONTEXT(ec);
148     SPDesktop *dt = ec->desktop;
150     if (((SPEventContextClass *) draw_parent_class)->setup) {
151         ((SPEventContextClass *) draw_parent_class)->setup(ec);
152     }
154     dc->selection = sp_desktop_selection(dt);
156     /* Connect signals to track selection changes */
157     dc->sel_changed_connection = dc->selection->connectChanged(
158         sigc::bind(sigc::ptr_fun(&spdc_selection_changed), dc)
159     );
160     dc->sel_modified_connection = dc->selection->connectModified(
161         sigc::bind(sigc::ptr_fun(&spdc_selection_modified), dc)
162     );
164     /* Create red bpath */
165     dc->red_bpath = sp_canvas_bpath_new(sp_desktop_sketch(ec->desktop), NULL);
166     sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(dc->red_bpath), dc->red_color, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
167     /* Create red curve */
168     dc->red_curve = sp_curve_new_sized(4);
170     /* Create blue bpath */
171     dc->blue_bpath = sp_canvas_bpath_new(sp_desktop_sketch(ec->desktop), NULL);
172     sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(dc->blue_bpath), dc->blue_color, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
173     /* Create blue curve */
174     dc->blue_curve = sp_curve_new_sized(8);
176     /* Create green curve */
177     dc->green_curve = sp_curve_new_sized(64);
178     /* No green anchor by default */
179     dc->green_anchor = NULL;
180     dc->green_closed = FALSE;
182     dc->attach = TRUE;
183     spdc_attach_selection(dc, dc->selection);
186 static void
187 sp_draw_context_finish(SPEventContext *ec)
189     SPDrawContext *dc = SP_DRAW_CONTEXT(ec);
191     dc->sel_changed_connection.disconnect();
192     dc->sel_modified_connection.disconnect();
194     if (dc->grab) {
195         sp_canvas_item_ungrab(dc->grab, GDK_CURRENT_TIME);
196     }
198     if (dc->selection) {
199         dc->selection = NULL;
200     }
202     spdc_free_colors(dc);
205 static void
206 sp_draw_context_set(SPEventContext */*ec*/, const gchar */*key*/, const gchar */*value*/)
210 gint
211 sp_draw_context_root_handler(SPEventContext *ec, GdkEvent *event)
213     gint ret = FALSE;
215     switch (event->type) {
216         case GDK_KEY_PRESS:
217             switch (get_group0_keyval (&event->key)) {
218                 case GDK_Up:
219                 case GDK_Down:
220                 case GDK_KP_Up:
221                 case GDK_KP_Down:
222                     // prevent the zoom field from activation
223                     if (!MOD__CTRL_ONLY) {
224                         ret = TRUE;
225                     }
226                     break;
227                 default:
228             break;
229         }
230         break;
231     default:
232         break;
233     }
235     if (!ret) {
236         if (((SPEventContextClass *) draw_parent_class)->root_handler) {
237             ret = ((SPEventContextClass *) draw_parent_class)->root_handler(ec, event);
238         }
239     }
241     return ret;
245 /*
246  * Selection handlers
247  */
249 static void
250 spdc_selection_changed(Inkscape::Selection *sel, SPDrawContext *dc)
252     if (dc->attach) {
253         spdc_attach_selection(dc, sel);
254     }
257 /* fixme: We have to ensure this is not delayed (Lauris) */
259 static void
260 spdc_selection_modified(Inkscape::Selection *sel, guint /*flags*/, SPDrawContext *dc)
262     if (dc->attach) {
263         spdc_attach_selection(dc, sel);
264     }
267 static void
268 spdc_attach_selection(SPDrawContext *dc, Inkscape::Selection */*sel*/)
270     /* We reset white and forget white/start/end anchors */
271     spdc_reset_white(dc);
272     dc->sa = NULL;
273     dc->ea = NULL;
275     SPItem *item = dc->selection ? dc->selection->singleItem() : NULL;
277     if ( item && SP_IS_PATH(item) ) {
278         /* Create new white data */
279         /* Item */
280         dc->white_item = item;
281         /* Curve list */
282         /* We keep it in desktop coordinates to eliminate calculation errors */
283         SPCurve *norm = sp_path_get_curve_for_edit (SP_PATH(item));
284         sp_curve_transform(norm, sp_item_i2d_affine(dc->white_item));
285         g_return_if_fail( norm != NULL );
286         dc->white_curves = g_slist_reverse(sp_curve_split(norm));
287         sp_curve_unref(norm);
288         /* Anchor list */
289         for (GSList *l = dc->white_curves; l != NULL; l = l->next) {
290             SPCurve *c;
291             c = (SPCurve*)l->data;
292             g_return_if_fail( c->end > 1 );
293             if ( SP_CURVE_BPATH(c)->code == NR_MOVETO_OPEN ) {
294                 NArtBpath *s, *e;
295                 SPDrawAnchor *a;
296                 s = sp_curve_first_bpath(c);
297                 e = sp_curve_last_bpath(c);
298                 a = sp_draw_anchor_new(dc, c, TRUE, NR::Point(s->x3, s->y3));
299                 dc->white_anchors = g_slist_prepend(dc->white_anchors, a);
300                 a = sp_draw_anchor_new(dc, c, FALSE, NR::Point(e->x3, e->y3));
301                 dc->white_anchors = g_slist_prepend(dc->white_anchors, a);
302             }
303         }
304         /* fixme: recalculate active anchor? */
305     }
309 /**
310  *  Snaps node or handle to PI/rotationsnapsperpi degree increments.
311  *
312  *  \param dc draw context
313  *  \param p cursor point (to be changed by snapping)
314  *  \param o origin point
315  *  \param state  keyboard state to check if ctrl was pressed
316 */
318 void spdc_endpoint_snap_rotation(SPEventContext const *const ec, NR::Point &p, NR::Point const o,
319                                  guint state)
321     /* Control must be down for this snap to work */
322     if ((state & GDK_CONTROL_MASK) == 0) {
323         return;
324     }
326     unsigned const snaps = abs(prefs_get_int_attribute("options.rotationsnapsperpi", "value", 12));
327     /* 0 means no snapping. */
329     /* mirrored by fabs, so this corresponds to 15 degrees */
330     NR::Point best; /* best solution */
331     double bn = NR_HUGE; /* best normal */
332     double bdot = 0;
333     NR::Point v = NR::Point(0, 1);
334     double const r00 = cos(M_PI / snaps), r01 = sin(M_PI / snaps);
335     double const r10 = -r01, r11 = r00;
337     NR::Point delta = p - o;
339     for (unsigned i = 0; i < snaps; i++) {
340         double const ndot = fabs(dot(v,NR::rot90(delta)));
341         NR::Point t(r00*v[NR::X] + r01*v[NR::Y],
342                     r10*v[NR::X] + r11*v[NR::Y]);
343         if (ndot < bn) {
344             /* I think it is better numerically to use the normal, rather than the dot product
345              * to assess solutions, but I haven't proven it. */
346             bn = ndot;
347             best = v;
348             bdot = dot(v, delta);
349         }
350         v = t;
351     }
353     if (fabs(bdot) > 0) {
354         p = o + bdot * best;
356         /* Snap it along best vector */
357         SnapManager const &m = SP_EVENT_CONTEXT_DESKTOP(ec)->namedview->snap_manager;
358         Inkscape::SnappedPoint const s = m.constrainedSnap( Inkscape::Snapper::SNAPPOINT_NODE,
359                                                             p, Inkscape::Snapper::ConstraintLine(best), NULL );
360         p = s.getPoint();
361         if (s.getDistance() < NR_HUGE) {
362             SP_EVENT_CONTEXT_DESKTOP(ec)->snapindicator->set_new_snappoint(p.to_2geom());
363         }
364     }
368 void spdc_endpoint_snap_free(SPEventContext const * const ec, NR::Point& p, guint const state)
370     /* Shift disables this snap */
371     if (state & GDK_SHIFT_MASK) {
372         return;
373     }
375     SnapManager const &m = SP_EVENT_CONTEXT_DESKTOP(ec)->namedview->snap_manager;
376     Inkscape::SnappedPoint const s = m.freeSnap(Inkscape::Snapper::SNAPPOINT_NODE, p, NULL);
377     p = s.getPoint();
378     if (s.getDistance() < NR_HUGE) {
379         SP_EVENT_CONTEXT_DESKTOP(ec)->snapindicator->set_new_snappoint(p.to_2geom());
380     }
383 static SPCurve *
384 reverse_then_unref(SPCurve *orig)
386     SPCurve *ret = sp_curve_reverse(orig);
387     sp_curve_unref(orig);
388     return ret;
391 /**
392  * Concats red, blue and green.
393  * If any anchors are defined, process these, optionally removing curves from white list
394  * Invoke _flush_white to write result back to object.
395  */
396 void
397 spdc_concat_colors_and_flush(SPDrawContext *dc, gboolean forceclosed)
399     /* Concat RBG */
400     SPCurve *c = dc->green_curve;
402     /* Green */
403     dc->green_curve = sp_curve_new_sized(64);
404     while (dc->green_bpaths) {
405         gtk_object_destroy(GTK_OBJECT(dc->green_bpaths->data));
406         dc->green_bpaths = g_slist_remove(dc->green_bpaths, dc->green_bpaths->data);
407     }
408     /* Blue */
409     sp_curve_append_continuous(c, dc->blue_curve, 0.0625);
410     sp_curve_reset(dc->blue_curve);
411     sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->blue_bpath), NULL);
412     /* Red */
413     if (dc->red_curve_is_valid) {
414         sp_curve_append_continuous(c, dc->red_curve, 0.0625);
415     }
416     sp_curve_reset(dc->red_curve);
417     sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->red_bpath), NULL);
419     if (sp_curve_empty(c)) {
420         sp_curve_unref(c);
421         return;
422     }
424     /* Step A - test, whether we ended on green anchor */
425     if ( forceclosed || ( dc->green_anchor && dc->green_anchor->active ) ) {
426         // We hit green anchor, closing Green-Blue-Red
427         SP_EVENT_CONTEXT_DESKTOP(dc)->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Path is closed."));
428         sp_curve_closepath_current(c);
429         /* Closed path, just flush */
430         spdc_flush_white(dc, c);
431         sp_curve_unref(c);
432         return;
433     }
435     /* Step B - both start and end anchored to same curve */
436     if ( dc->sa && dc->ea
437          && ( dc->sa->curve == dc->ea->curve )
438          && ( ( dc->sa != dc->ea )
439               || dc->sa->curve->closed ) )
440     {
441         // We hit bot start and end of single curve, closing paths
442         SP_EVENT_CONTEXT_DESKTOP(dc)->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Closing path."));
443         if (dc->sa->start && !(dc->sa->curve->closed) ) {
444             c = reverse_then_unref(c);
445         }
446         sp_curve_append_continuous(dc->sa->curve, c, 0.0625);
447         sp_curve_unref(c);
448         sp_curve_closepath_current(dc->sa->curve);
449         spdc_flush_white(dc, NULL);
450         return;
451     }
453     /* Step C - test start */
454     if (dc->sa) {
455         SPCurve *s = dc->sa->curve;
456         dc->white_curves = g_slist_remove(dc->white_curves, s);
457         if (dc->sa->start) {
458             s = reverse_then_unref(s);
459         }
460         sp_curve_append_continuous(s, c, 0.0625);
461         sp_curve_unref(c);
462         c = s;
463     } else /* Step D - test end */ if (dc->ea) {
464         SPCurve *e = dc->ea->curve;
465         dc->white_curves = g_slist_remove(dc->white_curves, e);
466         if (!dc->ea->start) {
467             e = reverse_then_unref(e);
468         }
469         sp_curve_append_continuous(c, e, 0.0625);
470         sp_curve_unref(e);
471     }
474     spdc_flush_white(dc, c);
476     sp_curve_unref(c);
479 static char const *
480 tool_name(SPDrawContext *dc)
482     return ( SP_IS_PEN_CONTEXT(dc)
483              ? "tools.freehand.pen"
484              : "tools.freehand.pencil" );
487 /*
488  * Flushes white curve(s) and additional curve into object
489  *
490  * No cleaning of colored curves - this has to be done by caller
491  * No rereading of white data, so if you cannot rely on ::modified, do it in caller
492  *
493  */
495 static void
496 spdc_flush_white(SPDrawContext *dc, SPCurve *gc)
498     SPCurve *c;
500     if (dc->white_curves) {
501         g_assert(dc->white_item);
502         c = sp_curve_concat(dc->white_curves);
503         g_slist_free(dc->white_curves);
504         dc->white_curves = NULL;
505         if (gc) {
506             sp_curve_append(c, gc, FALSE);
507         }
508     } else if (gc) {
509         c = gc;
510         sp_curve_ref(c);
511     } else {
512         return;
513     }
515     /* Now we have to go back to item coordinates at last */
516     sp_curve_transform(c, ( dc->white_item
517                             ? sp_item_dt2i_affine(dc->white_item)
518                             : sp_desktop_dt2root_affine(SP_EVENT_CONTEXT_DESKTOP(dc)) ));
520     SPDesktop *desktop = SP_EVENT_CONTEXT_DESKTOP(dc);
521     SPDocument *doc = sp_desktop_document(desktop);
522     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
524     if ( c && !sp_curve_empty(c) ) {
525         /* We actually have something to write */
527         bool has_lpe = false;
528         Inkscape::XML::Node *repr;
529         if (dc->white_item) {
530             repr = SP_OBJECT_REPR(dc->white_item);
531             has_lpe = sp_lpe_item_has_path_effect_recursive(SP_LPE_ITEM(dc->white_item));
532         } else {
533             repr = xml_doc->createElement("svg:path");
534             /* Set style */
535             sp_desktop_apply_style_tool(desktop, repr, tool_name(dc), false);
536         }
538         gchar *str = sp_svg_write_path(SP_CURVE_BPATH(c));
539         g_assert( str != NULL );
540         if (has_lpe)
541             repr->setAttribute("inkscape:original-d", str);
542         else
543             repr->setAttribute("d", str);
544         g_free(str);
546         if (!dc->white_item) {
547             /* Attach repr */
548             SPItem *item = SP_ITEM(desktop->currentLayer()->appendChildRepr(repr));
549             dc->selection->set(repr);
550             Inkscape::GC::release(repr);
551             item->transform = i2i_affine(desktop->currentRoot(), desktop->currentLayer());
552             item->updateRepr();
553         }
555         sp_document_done(doc, SP_IS_PEN_CONTEXT(dc)? SP_VERB_CONTEXT_PEN : SP_VERB_CONTEXT_PENCIL, 
556                          _("Draw path"));
558         // When quickly drawing several subpaths with Shift, the next subpath may be finished and
559         // flushed before the selection_modified signal is fired by the previous change, which
560         // results in the tool losing all of the selected path's curve except that last subpath. To
561         // fix this, we force the selection_modified callback now, to make sure the tool's curve is
562         // in sync immediately.
563         spdc_selection_modified(sp_desktop_selection(desktop), 0, dc);
564     }
566     sp_curve_unref(c);
568     /* Flush pending updates */
569     sp_document_ensure_up_to_date(doc);
572 /**
573  * Returns FIRST active anchor (the activated one).
574  */
575 SPDrawAnchor *
576 spdc_test_inside(SPDrawContext *dc, NR::Point p)
578     SPDrawAnchor *active = NULL;
580     /* Test green anchor */
581     if (dc->green_anchor) {
582         active = sp_draw_anchor_test(dc->green_anchor, p, TRUE);
583     }
585     for (GSList *l = dc->white_anchors; l != NULL; l = l->next) {
586         SPDrawAnchor *na = sp_draw_anchor_test((SPDrawAnchor *) l->data, p, !active);
587         if ( !active && na ) {
588             active = na;
589         }
590     }
592     return active;
595 static void
596 spdc_reset_white(SPDrawContext *dc)
598     if (dc->white_item) {
599         /* We do not hold refcount */
600         dc->white_item = NULL;
601     }
602     while (dc->white_curves) {
603         sp_curve_unref((SPCurve *) dc->white_curves->data);
604         dc->white_curves = g_slist_remove(dc->white_curves, dc->white_curves->data);
605     }
606     while (dc->white_anchors) {
607         sp_draw_anchor_destroy((SPDrawAnchor *) dc->white_anchors->data);
608         dc->white_anchors = g_slist_remove(dc->white_anchors, dc->white_anchors->data);
609     }
612 static void
613 spdc_free_colors(SPDrawContext *dc)
615     /* Red */
616     if (dc->red_bpath) {
617         gtk_object_destroy(GTK_OBJECT(dc->red_bpath));
618         dc->red_bpath = NULL;
619     }
620     if (dc->red_curve) {
621         dc->red_curve = sp_curve_unref(dc->red_curve);
622     }
623     /* Blue */
624     if (dc->blue_bpath) {
625         gtk_object_destroy(GTK_OBJECT(dc->blue_bpath));
626         dc->blue_bpath = NULL;
627     }
628     if (dc->blue_curve) {
629         dc->blue_curve = sp_curve_unref(dc->blue_curve);
630     }
631     /* Green */
632     while (dc->green_bpaths) {
633         gtk_object_destroy(GTK_OBJECT(dc->green_bpaths->data));
634         dc->green_bpaths = g_slist_remove(dc->green_bpaths, dc->green_bpaths->data);
635     }
636     if (dc->green_curve) {
637         dc->green_curve = sp_curve_unref(dc->green_curve);
638     }
639     if (dc->green_anchor) {
640         dc->green_anchor = sp_draw_anchor_destroy(dc->green_anchor);
641     }
642     /* White */
643     if (dc->white_item) {
644         /* We do not hold refcount */
645         dc->white_item = NULL;
646     }
647     while (dc->white_curves) {
648         sp_curve_unref((SPCurve *) dc->white_curves->data);
649         dc->white_curves = g_slist_remove(dc->white_curves, dc->white_curves->data);
650     }
651     while (dc->white_anchors) {
652         sp_draw_anchor_destroy((SPDrawAnchor *) dc->white_anchors->data);
653         dc->white_anchors = g_slist_remove(dc->white_anchors, dc->white_anchors->data);
654     }
658 /*
659   Local Variables:
660   mode:c++
661   c-file-style:"stroustrup"
662   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
663   indent-tabs-mode:nil
664   fill-column:99
665   End:
666 */
667 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :