Code

Groundwork to allow automatic application of an LPE to a newly drawn path
[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 "display/curve.h"
29 #include "desktop.h"
30 #include "desktop-affine.h"
31 #include "desktop-handles.h"
32 #include "desktop-style.h"
33 #include "document.h"
34 #include "draw-anchor.h"
35 #include "macros.h"
36 #include "message-stack.h"
37 #include "pen-context.h"
38 #include "prefs-utils.h"
39 #include "selection.h"
40 #include "selection-chemistry.h"
41 #include "snap.h"
42 #include "sp-path.h"
43 #include "sp-namedview.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     dc->waiting_LPE = Inkscape::LivePathEffect::INVALID_LPE;
120     new (&dc->sel_changed_connection) sigc::connection();
121     new (&dc->sel_modified_connection) sigc::connection();
124 static void
125 sp_draw_context_dispose(GObject *object)
127     SPDrawContext *dc = SP_DRAW_CONTEXT(object);
129     dc->sel_changed_connection.~connection();
130     dc->sel_modified_connection.~connection();
132     if (dc->grab) {
133         sp_canvas_item_ungrab(dc->grab, GDK_CURRENT_TIME);
134         dc->grab = NULL;
135     }
137     if (dc->selection) {
138         dc->selection = NULL;
139     }
141     spdc_free_colors(dc);
143     G_OBJECT_CLASS(draw_parent_class)->dispose(object);
146 static void
147 sp_draw_context_setup(SPEventContext *ec)
149     SPDrawContext *dc = SP_DRAW_CONTEXT(ec);
150     SPDesktop *dt = ec->desktop;
152     if (((SPEventContextClass *) draw_parent_class)->setup) {
153         ((SPEventContextClass *) draw_parent_class)->setup(ec);
154     }
156     dc->selection = sp_desktop_selection(dt);
158     /* Connect signals to track selection changes */
159     dc->sel_changed_connection = dc->selection->connectChanged(
160         sigc::bind(sigc::ptr_fun(&spdc_selection_changed), dc)
161     );
162     dc->sel_modified_connection = dc->selection->connectModified(
163         sigc::bind(sigc::ptr_fun(&spdc_selection_modified), dc)
164     );
166     /* Create red bpath */
167     dc->red_bpath = sp_canvas_bpath_new(sp_desktop_sketch(ec->desktop), NULL);
168     sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(dc->red_bpath), dc->red_color, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
169     /* Create red curve */
170     dc->red_curve = new SPCurve(4);
172     /* Create blue bpath */
173     dc->blue_bpath = sp_canvas_bpath_new(sp_desktop_sketch(ec->desktop), NULL);
174     sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(dc->blue_bpath), dc->blue_color, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
175     /* Create blue curve */
176     dc->blue_curve = new SPCurve(8);
178     /* Create green curve */
179     dc->green_curve = new SPCurve(64);
180     /* No green anchor by default */
181     dc->green_anchor = NULL;
182     dc->green_closed = FALSE;
184     dc->attach = TRUE;
185     spdc_attach_selection(dc, dc->selection);
188 static void
189 sp_draw_context_finish(SPEventContext *ec)
191     SPDrawContext *dc = SP_DRAW_CONTEXT(ec);
193     dc->sel_changed_connection.disconnect();
194     dc->sel_modified_connection.disconnect();
196     if (dc->grab) {
197         sp_canvas_item_ungrab(dc->grab, GDK_CURRENT_TIME);
198     }
200     if (dc->selection) {
201         dc->selection = NULL;
202     }
204     spdc_free_colors(dc);
207 static void
208 sp_draw_context_set(SPEventContext */*ec*/, const gchar */*key*/, const gchar */*value*/)
212 gint
213 sp_draw_context_root_handler(SPEventContext *ec, GdkEvent *event)
215     gint ret = FALSE;
217     switch (event->type) {
218         case GDK_KEY_PRESS:
219             switch (get_group0_keyval (&event->key)) {
220                 case GDK_Up:
221                 case GDK_Down:
222                 case GDK_KP_Up:
223                 case GDK_KP_Down:
224                     // prevent the zoom field from activation
225                     if (!MOD__CTRL_ONLY) {
226                         ret = TRUE;
227                     }
228                     break;
229                 default:
230             break;
231         }
232         break;
233     default:
234         break;
235     }
237     if (!ret) {
238         if (((SPEventContextClass *) draw_parent_class)->root_handler) {
239             ret = ((SPEventContextClass *) draw_parent_class)->root_handler(ec, event);
240         }
241     }
243     return ret;
246 /*
247  * If we have an item and a waiting LPE, apply the effect to the item
248  */
249 void
250 spdc_check_for_and_apply_waiting_LPE(SPDrawContext *dc, SPItem *item)
252     if (item && dc->waiting_LPE != Inkscape::LivePathEffect::INVALID_LPE) {
253         Inkscape::LivePathEffect::Effect::createAndApply(dc->waiting_LPE, dc->desktop->doc(), item);
254     }
257 /*
258  * Selection handlers
259  */
261 static void
262 spdc_selection_changed(Inkscape::Selection *sel, SPDrawContext *dc)
264     spdc_check_for_and_apply_waiting_LPE(dc, sel->singleItem());
266     if (dc->attach) {
267         spdc_attach_selection(dc, sel);
268     }
271 /* fixme: We have to ensure this is not delayed (Lauris) */
273 static void
274 spdc_selection_modified(Inkscape::Selection *sel, guint /*flags*/, SPDrawContext *dc)
276     if (dc->attach) {
277         spdc_attach_selection(dc, sel);
278     }
281 static void
282 spdc_attach_selection(SPDrawContext *dc, Inkscape::Selection */*sel*/)
284     /* We reset white and forget white/start/end anchors */
285     spdc_reset_white(dc);
286     dc->sa = NULL;
287     dc->ea = NULL;
289     SPItem *item = dc->selection ? dc->selection->singleItem() : NULL;
291     if ( item && SP_IS_PATH(item) ) {
292         /* Create new white data */
293         /* Item */
294         dc->white_item = item;
295         /* Curve list */
296         /* We keep it in desktop coordinates to eliminate calculation errors */
297         SPCurve *norm = sp_path_get_curve_for_edit (SP_PATH(item));
298         norm->transform(sp_item_i2d_affine(dc->white_item));
299         g_return_if_fail( norm != NULL );
300         dc->white_curves = g_slist_reverse(norm->split());
301         norm->unref();
302         /* Anchor list */
303         for (GSList *l = dc->white_curves; l != NULL; l = l->next) {
304             SPCurve *c;
305             c = (SPCurve*)l->data;
306             g_return_if_fail( c->_end > 1 );
307             if ( SP_CURVE_BPATH(c)->code == NR_MOVETO_OPEN ) {
308                 NArtBpath *s, *e;
309                 SPDrawAnchor *a;
310                 s = c->first_bpath();
311                 e = c->last_bpath();
312                 a = sp_draw_anchor_new(dc, c, TRUE, NR::Point(s->x3, s->y3));
313                 dc->white_anchors = g_slist_prepend(dc->white_anchors, a);
314                 a = sp_draw_anchor_new(dc, c, FALSE, NR::Point(e->x3, e->y3));
315                 dc->white_anchors = g_slist_prepend(dc->white_anchors, a);
316             }
317         }
318         /* fixme: recalculate active anchor? */
319     }
323 /**
324  *  Snaps node or handle to PI/rotationsnapsperpi degree increments.
325  *
326  *  \param dc draw context
327  *  \param p cursor point (to be changed by snapping)
328  *  \param o origin point
329  *  \param state  keyboard state to check if ctrl was pressed
330 */
332 void spdc_endpoint_snap_rotation(SPEventContext const *const ec, NR::Point &p, NR::Point const o,
333                                  guint state)
335     /* Control must be down for this snap to work */
336     if ((state & GDK_CONTROL_MASK) == 0) {
337         return;
338     }
340     unsigned const snaps = abs(prefs_get_int_attribute("options.rotationsnapsperpi", "value", 12));
341     /* 0 means no snapping. */
343     /* mirrored by fabs, so this corresponds to 15 degrees */
344     NR::Point best; /* best solution */
345     double bn = NR_HUGE; /* best normal */
346     double bdot = 0;
347     NR::Point v = NR::Point(0, 1);
348     double const r00 = cos(M_PI / snaps), r01 = sin(M_PI / snaps);
349     double const r10 = -r01, r11 = r00;
351     NR::Point delta = p - o;
353     for (unsigned i = 0; i < snaps; i++) {
354         double const ndot = fabs(dot(v,NR::rot90(delta)));
355         NR::Point t(r00*v[NR::X] + r01*v[NR::Y],
356                     r10*v[NR::X] + r11*v[NR::Y]);
357         if (ndot < bn) {
358             /* I think it is better numerically to use the normal, rather than the dot product
359              * to assess solutions, but I haven't proven it. */
360             bn = ndot;
361             best = v;
362             bdot = dot(v, delta);
363         }
364         v = t;
365     }
367     if (fabs(bdot) > 0) {
368         p = o + bdot * best;
370         /* Snap it along best vector */
371         SnapManager &m = SP_EVENT_CONTEXT_DESKTOP(ec)->namedview->snap_manager;
372         m.setup(SP_EVENT_CONTEXT_DESKTOP(ec), NULL);
373         m.constrainedSnapReturnByRef( Inkscape::Snapper::SNAPPOINT_NODE, p, Inkscape::Snapper::ConstraintLine(best));
374     }
378 void spdc_endpoint_snap_free(SPEventContext const * const ec, NR::Point& p, guint const state)
380     /* Shift disables this snap */
381     if (state & GDK_SHIFT_MASK) {
382         return;
383     }
385     SnapManager &m = SP_EVENT_CONTEXT_DESKTOP(ec)->namedview->snap_manager;
386     m.setup(SP_EVENT_CONTEXT_DESKTOP(ec), NULL);
387     m.freeSnapReturnByRef(Inkscape::Snapper::SNAPPOINT_NODE, p);
390 static SPCurve *
391 reverse_then_unref(SPCurve *orig)
393     SPCurve *ret = orig->create_reverse();
394     orig->unref();
395     return ret;
398 /**
399  * Concats red, blue and green.
400  * If any anchors are defined, process these, optionally removing curves from white list
401  * Invoke _flush_white to write result back to object.
402  */
403 void
404 spdc_concat_colors_and_flush(SPDrawContext *dc, gboolean forceclosed)
406     /* Concat RBG */
407     SPCurve *c = dc->green_curve;
409     /* Green */
410     dc->green_curve = new SPCurve(64);
411     while (dc->green_bpaths) {
412         gtk_object_destroy(GTK_OBJECT(dc->green_bpaths->data));
413         dc->green_bpaths = g_slist_remove(dc->green_bpaths, dc->green_bpaths->data);
414     }
415     /* Blue */
416     c->append_continuous(dc->blue_curve, 0.0625);
417     dc->blue_curve->reset();
418     sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->blue_bpath), NULL);
419     /* Red */
420     if (dc->red_curve_is_valid) {
421         c->append_continuous(dc->red_curve, 0.0625);
422     }
423     dc->red_curve->reset();
424     sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->red_bpath), NULL);
426     if (c->is_empty()) {
427         c->unref();
428         return;
429     }
431     /* Step A - test, whether we ended on green anchor */
432     if ( forceclosed || ( dc->green_anchor && dc->green_anchor->active ) ) {
433         // We hit green anchor, closing Green-Blue-Red
434         SP_EVENT_CONTEXT_DESKTOP(dc)->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Path is closed."));
435         c->closepath_current();
436         /* Closed path, just flush */
437         spdc_flush_white(dc, c);
438         c->unref();
439         return;
440     }
442     /* Step B - both start and end anchored to same curve */
443     if ( dc->sa && dc->ea
444          && ( dc->sa->curve == dc->ea->curve )
445          && ( ( dc->sa != dc->ea )
446               || dc->sa->curve->is_closed() ) )
447     {
448         // We hit bot start and end of single curve, closing paths
449         SP_EVENT_CONTEXT_DESKTOP(dc)->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Closing path."));
450         if (dc->sa->start && !(dc->sa->curve->is_closed()) ) {
451             c = reverse_then_unref(c);
452         }
453         dc->sa->curve->append_continuous(c, 0.0625);
454         c->unref();
455         dc->sa->curve->closepath_current();
456         spdc_flush_white(dc, NULL);
457         return;
458     }
460     /* Step C - test start */
461     if (dc->sa) {
462         SPCurve *s = dc->sa->curve;
463         dc->white_curves = g_slist_remove(dc->white_curves, s);
464         if (dc->sa->start) {
465             s = reverse_then_unref(s);
466         }
467         s->append_continuous(c, 0.0625);
468         c->unref();
469         c = s;
470     } else /* Step D - test end */ if (dc->ea) {
471         SPCurve *e = dc->ea->curve;
472         dc->white_curves = g_slist_remove(dc->white_curves, e);
473         if (!dc->ea->start) {
474             e = reverse_then_unref(e);
475         }
476         c->append_continuous(e, 0.0625);
477         e->unref();
478     }
481     spdc_flush_white(dc, c);
483     c->unref();
486 static char const *
487 tool_name(SPDrawContext *dc)
489     return ( SP_IS_PEN_CONTEXT(dc)
490              ? "tools.freehand.pen"
491              : "tools.freehand.pencil" );
494 /*
495  * Flushes white curve(s) and additional curve into object
496  *
497  * No cleaning of colored curves - this has to be done by caller
498  * No rereading of white data, so if you cannot rely on ::modified, do it in caller
499  *
500  */
502 static void
503 spdc_flush_white(SPDrawContext *dc, SPCurve *gc)
505     SPCurve *c;
507     if (dc->white_curves) {
508         g_assert(dc->white_item);
509         c = SPCurve::concat(dc->white_curves);
510         g_slist_free(dc->white_curves);
511         dc->white_curves = NULL;
512         if (gc) {
513             c->append(gc, FALSE);
514         }
515     } else if (gc) {
516         c = gc;
517         c->ref();
518     } else {
519         return;
520     }
522     /* Now we have to go back to item coordinates at last */
523     c->transform(( dc->white_item
524                             ? sp_item_dt2i_affine(dc->white_item)
525                             : sp_desktop_dt2root_affine(SP_EVENT_CONTEXT_DESKTOP(dc)) ));
527     SPDesktop *desktop = SP_EVENT_CONTEXT_DESKTOP(dc);
528     SPDocument *doc = sp_desktop_document(desktop);
529     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
531     if ( c && !c->is_empty() ) {
532         /* We actually have something to write */
534         bool has_lpe = false;
535         Inkscape::XML::Node *repr;
536         if (dc->white_item) {
537             repr = SP_OBJECT_REPR(dc->white_item);
538             has_lpe = sp_lpe_item_has_path_effect_recursive(SP_LPE_ITEM(dc->white_item));
539         } else {
540             repr = xml_doc->createElement("svg:path");
541             /* Set style */
542             sp_desktop_apply_style_tool(desktop, repr, tool_name(dc), false);
543         }
545         gchar *str = sp_svg_write_path(SP_CURVE_BPATH(c));
546         g_assert( str != NULL );
547         if (has_lpe)
548             repr->setAttribute("inkscape:original-d", str);
549         else
550             repr->setAttribute("d", str);
551         g_free(str);
553         if (!dc->white_item) {
554             /* Attach repr */
555             SPItem *item = SP_ITEM(desktop->currentLayer()->appendChildRepr(repr));
556             dc->selection->set(repr);
557             Inkscape::GC::release(repr);
558             item->transform = i2i_affine(desktop->currentRoot(), desktop->currentLayer());
559             item->updateRepr();
560         }
562         sp_document_done(doc, SP_IS_PEN_CONTEXT(dc)? SP_VERB_CONTEXT_PEN : SP_VERB_CONTEXT_PENCIL, 
563                          _("Draw path"));
565         // When quickly drawing several subpaths with Shift, the next subpath may be finished and
566         // flushed before the selection_modified signal is fired by the previous change, which
567         // results in the tool losing all of the selected path's curve except that last subpath. To
568         // fix this, we force the selection_modified callback now, to make sure the tool's curve is
569         // in sync immediately.
570         spdc_selection_modified(sp_desktop_selection(desktop), 0, dc);
571     }
573     c->unref();
575     /* Flush pending updates */
576     sp_document_ensure_up_to_date(doc);
579 /**
580  * Returns FIRST active anchor (the activated one).
581  */
582 SPDrawAnchor *
583 spdc_test_inside(SPDrawContext *dc, NR::Point p)
585     SPDrawAnchor *active = NULL;
587     /* Test green anchor */
588     if (dc->green_anchor) {
589         active = sp_draw_anchor_test(dc->green_anchor, p, TRUE);
590     }
592     for (GSList *l = dc->white_anchors; l != NULL; l = l->next) {
593         SPDrawAnchor *na = sp_draw_anchor_test((SPDrawAnchor *) l->data, p, !active);
594         if ( !active && na ) {
595             active = na;
596         }
597     }
599     return active;
602 static void
603 spdc_reset_white(SPDrawContext *dc)
605     if (dc->white_item) {
606         /* We do not hold refcount */
607         dc->white_item = NULL;
608     }
609     while (dc->white_curves) {
610         reinterpret_cast<SPCurve *>(dc->white_curves->data)->unref();
611         dc->white_curves = g_slist_remove(dc->white_curves, dc->white_curves->data);
612     }
613     while (dc->white_anchors) {
614         sp_draw_anchor_destroy((SPDrawAnchor *) dc->white_anchors->data);
615         dc->white_anchors = g_slist_remove(dc->white_anchors, dc->white_anchors->data);
616     }
619 static void
620 spdc_free_colors(SPDrawContext *dc)
622     /* Red */
623     if (dc->red_bpath) {
624         gtk_object_destroy(GTK_OBJECT(dc->red_bpath));
625         dc->red_bpath = NULL;
626     }
627     if (dc->red_curve) {
628         dc->red_curve = dc->red_curve->unref();
629     }
630     /* Blue */
631     if (dc->blue_bpath) {
632         gtk_object_destroy(GTK_OBJECT(dc->blue_bpath));
633         dc->blue_bpath = NULL;
634     }
635     if (dc->blue_curve) {
636         dc->blue_curve = dc->blue_curve->unref();
637     }
638     /* Green */
639     while (dc->green_bpaths) {
640         gtk_object_destroy(GTK_OBJECT(dc->green_bpaths->data));
641         dc->green_bpaths = g_slist_remove(dc->green_bpaths, dc->green_bpaths->data);
642     }
643     if (dc->green_curve) {
644         dc->green_curve = dc->green_curve->unref();
645     }
646     if (dc->green_anchor) {
647         dc->green_anchor = sp_draw_anchor_destroy(dc->green_anchor);
648     }
649     /* White */
650     if (dc->white_item) {
651         /* We do not hold refcount */
652         dc->white_item = NULL;
653     }
654     while (dc->white_curves) {
655         reinterpret_cast<SPCurve *>(dc->white_curves->data)->unref();
656         dc->white_curves = g_slist_remove(dc->white_curves, dc->white_curves->data);
657     }
658     while (dc->white_anchors) {
659         sp_draw_anchor_destroy((SPDrawAnchor *) dc->white_anchors->data);
660         dc->white_anchors = g_slist_remove(dc->white_anchors, dc->white_anchors->data);
661     }
665 /*
666   Local Variables:
667   mode:c++
668   c-file-style:"stroustrup"
669   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
670   indent-tabs-mode:nil
671   fill-column:99
672   End:
673 */
674 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :