Code

Fix bug: allow curved paths again when switching back from 'wait for path' mode in...
[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_type = 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     dc->waiting_LPE_type = Inkscape::LivePathEffect::INVALID_LPE;
143     spdc_free_colors(dc);
145     G_OBJECT_CLASS(draw_parent_class)->dispose(object);
148 static void
149 sp_draw_context_setup(SPEventContext *ec)
151     SPDrawContext *dc = SP_DRAW_CONTEXT(ec);
152     SPDesktop *dt = ec->desktop;
154     if (((SPEventContextClass *) draw_parent_class)->setup) {
155         ((SPEventContextClass *) draw_parent_class)->setup(ec);
156     }
158     dc->selection = sp_desktop_selection(dt);
160     /* Connect signals to track selection changes */
161     dc->sel_changed_connection = dc->selection->connectChanged(
162         sigc::bind(sigc::ptr_fun(&spdc_selection_changed), dc)
163     );
164     dc->sel_modified_connection = dc->selection->connectModified(
165         sigc::bind(sigc::ptr_fun(&spdc_selection_modified), dc)
166     );
168     /* Create red bpath */
169     dc->red_bpath = sp_canvas_bpath_new(sp_desktop_sketch(ec->desktop), NULL);
170     sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(dc->red_bpath), dc->red_color, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
171     /* Create red curve */
172     dc->red_curve = new SPCurve(4);
174     /* Create blue bpath */
175     dc->blue_bpath = sp_canvas_bpath_new(sp_desktop_sketch(ec->desktop), NULL);
176     sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(dc->blue_bpath), dc->blue_color, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
177     /* Create blue curve */
178     dc->blue_curve = new SPCurve(8);
180     /* Create green curve */
181     dc->green_curve = new SPCurve(64);
182     /* No green anchor by default */
183     dc->green_anchor = NULL;
184     dc->green_closed = FALSE;
186     dc->attach = TRUE;
187     spdc_attach_selection(dc, dc->selection);
190 static void
191 sp_draw_context_finish(SPEventContext *ec)
193     SPDrawContext *dc = SP_DRAW_CONTEXT(ec);
195     dc->sel_changed_connection.disconnect();
196     dc->sel_modified_connection.disconnect();
198     if (dc->grab) {
199         sp_canvas_item_ungrab(dc->grab, GDK_CURRENT_TIME);
200     }
202     if (dc->selection) {
203         dc->selection = NULL;
204     }
206     spdc_free_colors(dc);
209 static void
210 sp_draw_context_set(SPEventContext */*ec*/, const gchar */*key*/, const gchar */*value*/)
214 gint
215 sp_draw_context_root_handler(SPEventContext *ec, GdkEvent *event)
217     gint ret = FALSE;
219     switch (event->type) {
220         case GDK_KEY_PRESS:
221             switch (get_group0_keyval (&event->key)) {
222                 case GDK_Up:
223                 case GDK_Down:
224                 case GDK_KP_Up:
225                 case GDK_KP_Down:
226                     // prevent the zoom field from activation
227                     if (!MOD__CTRL_ONLY) {
228                         ret = TRUE;
229                     }
230                     break;
231                 default:
232             break;
233         }
234         break;
235     default:
236         break;
237     }
239     if (!ret) {
240         if (((SPEventContextClass *) draw_parent_class)->root_handler) {
241             ret = ((SPEventContextClass *) draw_parent_class)->root_handler(ec, event);
242         }
243     }
245     return ret;
248 /*
249  * If we have an item and a waiting LPE, apply the effect to the item
250  * (spiro spline mode is treated separately)
251  */
252 void
253 spdc_check_for_and_apply_waiting_LPE(SPDrawContext *dc, SPItem *item)
255     using namespace Inkscape::LivePathEffect;
257     if (item) {
258         if (prefs_get_int_attribute("tools.freehand", "spiro-spline-mode", 0)) {
259             Effect::createAndApply(SPIRO, dc->desktop->doc(), item);
260             return;
261         }
262         if (dc->waiting_LPE_type != INVALID_LPE) {
263             Effect::createAndApply(dc->waiting_LPE_type, dc->desktop->doc(), item);
264             dc->waiting_LPE_type = INVALID_LPE;
265         }
266         if (SP_IS_PEN_CONTEXT(dc)) {
267             SP_PEN_CONTEXT(dc)->polylines_only = false;
268         }
269     }
272 /*
273  * Selection handlers
274  */
276 static void
277 spdc_selection_changed(Inkscape::Selection *sel, SPDrawContext *dc)
279     // note: in draw context, selection_changed() is only called when a new item was created;
280     // otherwise the following function call would yield wrong results
281     spdc_check_for_and_apply_waiting_LPE(dc, sel->singleItem());
283     if (dc->attach) {
284         spdc_attach_selection(dc, sel);
285     }
288 /* fixme: We have to ensure this is not delayed (Lauris) */
290 static void
291 spdc_selection_modified(Inkscape::Selection *sel, guint /*flags*/, SPDrawContext *dc)
293     if (dc->attach) {
294         spdc_attach_selection(dc, sel);
295     }
298 static void
299 spdc_attach_selection(SPDrawContext *dc, Inkscape::Selection */*sel*/)
301     /* We reset white and forget white/start/end anchors */
302     spdc_reset_white(dc);
303     dc->sa = NULL;
304     dc->ea = NULL;
306     SPItem *item = dc->selection ? dc->selection->singleItem() : NULL;
308     if ( item && SP_IS_PATH(item) ) {
309         /* Create new white data */
310         /* Item */
311         dc->white_item = item;
312         /* Curve list */
313         /* We keep it in desktop coordinates to eliminate calculation errors */
314         SPCurve *norm = sp_path_get_curve_for_edit (SP_PATH(item));
315         norm->transform(sp_item_i2d_affine(dc->white_item));
316         g_return_if_fail( norm != NULL );
317         dc->white_curves = g_slist_reverse(norm->split());
318         norm->unref();
319         /* Anchor list */
320         for (GSList *l = dc->white_curves; l != NULL; l = l->next) {
321             SPCurve *c;
322             c = (SPCurve*)l->data;
323             g_return_if_fail( c->get_length() > 1 );
324             if ( !c->is_closed() ) {
325                 SPDrawAnchor *a;
326                 a = sp_draw_anchor_new(dc, c, TRUE, c->first_point());
327                 dc->white_anchors = g_slist_prepend(dc->white_anchors, a);
328                 a = sp_draw_anchor_new(dc, c, FALSE, c->last_point());
329                 dc->white_anchors = g_slist_prepend(dc->white_anchors, a);
330             }
331         }
332         /* fixme: recalculate active anchor? */
333     }
337 /**
338  *  Snaps node or handle to PI/rotationsnapsperpi degree increments.
339  *
340  *  \param dc draw context
341  *  \param p cursor point (to be changed by snapping)
342  *  \param o origin point
343  *  \param state  keyboard state to check if ctrl was pressed
344 */
346 void spdc_endpoint_snap_rotation(SPEventContext const *const ec, NR::Point &p, NR::Point const o,
347                                  guint state)
349     /* Control must be down for this snap to work */
350     if ((state & GDK_CONTROL_MASK) == 0) {
351         return;
352     }
354     unsigned const snaps = abs(prefs_get_int_attribute("options.rotationsnapsperpi", "value", 12));
355     /* 0 means no snapping. */
357     /* mirrored by fabs, so this corresponds to 15 degrees */
358     NR::Point best; /* best solution */
359     double bn = NR_HUGE; /* best normal */
360     double bdot = 0;
361     NR::Point v = NR::Point(0, 1);
362     double const r00 = cos(M_PI / snaps), r01 = sin(M_PI / snaps);
363     double const r10 = -r01, r11 = r00;
365     NR::Point delta = p - o;
367     for (unsigned i = 0; i < snaps; i++) {
368         double const ndot = fabs(dot(v,NR::rot90(delta)));
369         NR::Point t(r00*v[NR::X] + r01*v[NR::Y],
370                     r10*v[NR::X] + r11*v[NR::Y]);
371         if (ndot < bn) {
372             /* I think it is better numerically to use the normal, rather than the dot product
373              * to assess solutions, but I haven't proven it. */
374             bn = ndot;
375             best = v;
376             bdot = dot(v, delta);
377         }
378         v = t;
379     }
381     if (fabs(bdot) > 0) {
382         p = o + bdot * best;
384         /* Snap it along best vector */
385         SnapManager &m = SP_EVENT_CONTEXT_DESKTOP(ec)->namedview->snap_manager;
386         m.setup(SP_EVENT_CONTEXT_DESKTOP(ec), NULL);
387         m.constrainedSnapReturnByRef( Inkscape::Snapper::SNAPPOINT_NODE, p, Inkscape::Snapper::ConstraintLine(best));
388     }
392 void spdc_endpoint_snap_free(SPEventContext const * const ec, NR::Point& p, guint const state)
394     /* Shift disables this snap */
395     if (state & GDK_SHIFT_MASK) {
396         return;
397     }
399     SnapManager &m = SP_EVENT_CONTEXT_DESKTOP(ec)->namedview->snap_manager;
400     m.setup(SP_EVENT_CONTEXT_DESKTOP(ec), NULL);
401     m.freeSnapReturnByRef(Inkscape::Snapper::SNAPPOINT_NODE, p);
404 static SPCurve *
405 reverse_then_unref(SPCurve *orig)
407     SPCurve *ret = orig->create_reverse();
408     orig->unref();
409     return ret;
412 /**
413  * Concats red, blue and green.
414  * If any anchors are defined, process these, optionally removing curves from white list
415  * Invoke _flush_white to write result back to object.
416  */
417 void
418 spdc_concat_colors_and_flush(SPDrawContext *dc, gboolean forceclosed)
420     /* Concat RBG */
421     SPCurve *c = dc->green_curve;
423     /* Green */
424     dc->green_curve = new SPCurve(64);
425     while (dc->green_bpaths) {
426         gtk_object_destroy(GTK_OBJECT(dc->green_bpaths->data));
427         dc->green_bpaths = g_slist_remove(dc->green_bpaths, dc->green_bpaths->data);
428     }
429     /* Blue */
430     c->append_continuous(dc->blue_curve, 0.0625);
431     dc->blue_curve->reset();
432     sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->blue_bpath), NULL);
433     /* Red */
434     if (dc->red_curve_is_valid) {
435         c->append_continuous(dc->red_curve, 0.0625);
436     }
437     dc->red_curve->reset();
438     sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->red_bpath), NULL);
440     if (c->is_empty()) {
441         c->unref();
442         return;
443     }
445     /* Step A - test, whether we ended on green anchor */
446     if ( forceclosed || ( dc->green_anchor && dc->green_anchor->active ) ) {
447         // We hit green anchor, closing Green-Blue-Red
448         SP_EVENT_CONTEXT_DESKTOP(dc)->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Path is closed."));
449         c->closepath_current();
450         /* Closed path, just flush */
451         spdc_flush_white(dc, c);
452         c->unref();
453         return;
454     }
456     /* Step B - both start and end anchored to same curve */
457     if ( dc->sa && dc->ea
458          && ( dc->sa->curve == dc->ea->curve )
459          && ( ( dc->sa != dc->ea )
460               || dc->sa->curve->is_closed() ) )
461     {
462         // We hit bot start and end of single curve, closing paths
463         SP_EVENT_CONTEXT_DESKTOP(dc)->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Closing path."));
464         if (dc->sa->start && !(dc->sa->curve->is_closed()) ) {
465             c = reverse_then_unref(c);
466         }
467         dc->sa->curve->append_continuous(c, 0.0625);
468         c->unref();
469         dc->sa->curve->closepath_current();
470         spdc_flush_white(dc, NULL);
471         return;
472     }
474     /* Step C - test start */
475     if (dc->sa) {
476         SPCurve *s = dc->sa->curve;
477         dc->white_curves = g_slist_remove(dc->white_curves, s);
478         if (dc->sa->start) {
479             s = reverse_then_unref(s);
480         }
481         s->append_continuous(c, 0.0625);
482         c->unref();
483         c = s;
484     } else /* Step D - test end */ if (dc->ea) {
485         SPCurve *e = dc->ea->curve;
486         dc->white_curves = g_slist_remove(dc->white_curves, e);
487         if (!dc->ea->start) {
488             e = reverse_then_unref(e);
489         }
490         c->append_continuous(e, 0.0625);
491         e->unref();
492     }
495     spdc_flush_white(dc, c);
497     c->unref();
500 static char const *
501 tool_name(SPDrawContext *dc)
503     return ( SP_IS_PEN_CONTEXT(dc)
504              ? "tools.freehand.pen"
505              : "tools.freehand.pencil" );
508 /*
509  * Flushes white curve(s) and additional curve into object
510  *
511  * No cleaning of colored curves - this has to be done by caller
512  * No rereading of white data, so if you cannot rely on ::modified, do it in caller
513  *
514  */
516 static void
517 spdc_flush_white(SPDrawContext *dc, SPCurve *gc)
519     SPCurve *c;
521     if (dc->white_curves) {
522         g_assert(dc->white_item);
523         c = SPCurve::concat(dc->white_curves);
524         g_slist_free(dc->white_curves);
525         dc->white_curves = NULL;
526         if (gc) {
527             c->append(gc, FALSE);
528         }
529     } else if (gc) {
530         c = gc;
531         c->ref();
532     } else {
533         return;
534     }
536     /* Now we have to go back to item coordinates at last */
537     c->transform(( dc->white_item
538                             ? sp_item_dt2i_affine(dc->white_item)
539                             : sp_desktop_dt2root_affine(SP_EVENT_CONTEXT_DESKTOP(dc)) ));
541     SPDesktop *desktop = SP_EVENT_CONTEXT_DESKTOP(dc);
542     SPDocument *doc = sp_desktop_document(desktop);
543     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
545     if ( c && !c->is_empty() ) {
546         /* We actually have something to write */
548         bool has_lpe = false;
549         Inkscape::XML::Node *repr;
550         if (dc->white_item) {
551             repr = SP_OBJECT_REPR(dc->white_item);
552             has_lpe = sp_lpe_item_has_path_effect_recursive(SP_LPE_ITEM(dc->white_item));
553         } else {
554             repr = xml_doc->createElement("svg:path");
555             /* Set style */
556             sp_desktop_apply_style_tool(desktop, repr, tool_name(dc), false);
557         }
559         gchar *str = sp_svg_write_path( c->get_pathvector() );
560         g_assert( str != NULL );
561         if (has_lpe)
562             repr->setAttribute("inkscape:original-d", str);
563         else
564             repr->setAttribute("d", str);
565         g_free(str);
567         if (!dc->white_item) {
568             /* Attach repr */
569             SPItem *item = SP_ITEM(desktop->currentLayer()->appendChildRepr(repr));
570             dc->selection->set(repr);
571             Inkscape::GC::release(repr);
572             item->transform = i2i_affine(desktop->currentRoot(), desktop->currentLayer());
573             item->updateRepr();
574         }
576         sp_document_done(doc, SP_IS_PEN_CONTEXT(dc)? SP_VERB_CONTEXT_PEN : SP_VERB_CONTEXT_PENCIL, 
577                          _("Draw path"));
579         // When quickly drawing several subpaths with Shift, the next subpath may be finished and
580         // flushed before the selection_modified signal is fired by the previous change, which
581         // results in the tool losing all of the selected path's curve except that last subpath. To
582         // fix this, we force the selection_modified callback now, to make sure the tool's curve is
583         // in sync immediately.
584         spdc_selection_modified(sp_desktop_selection(desktop), 0, dc);
585     }
587     c->unref();
589     /* Flush pending updates */
590     sp_document_ensure_up_to_date(doc);
593 /**
594  * Returns FIRST active anchor (the activated one).
595  */
596 SPDrawAnchor *
597 spdc_test_inside(SPDrawContext *dc, NR::Point p)
599     SPDrawAnchor *active = NULL;
601     /* Test green anchor */
602     if (dc->green_anchor) {
603         active = sp_draw_anchor_test(dc->green_anchor, p, TRUE);
604     }
606     for (GSList *l = dc->white_anchors; l != NULL; l = l->next) {
607         SPDrawAnchor *na = sp_draw_anchor_test((SPDrawAnchor *) l->data, p, !active);
608         if ( !active && na ) {
609             active = na;
610         }
611     }
613     return active;
616 static void
617 spdc_reset_white(SPDrawContext *dc)
619     if (dc->white_item) {
620         /* We do not hold refcount */
621         dc->white_item = NULL;
622     }
623     while (dc->white_curves) {
624         reinterpret_cast<SPCurve *>(dc->white_curves->data)->unref();
625         dc->white_curves = g_slist_remove(dc->white_curves, dc->white_curves->data);
626     }
627     while (dc->white_anchors) {
628         sp_draw_anchor_destroy((SPDrawAnchor *) dc->white_anchors->data);
629         dc->white_anchors = g_slist_remove(dc->white_anchors, dc->white_anchors->data);
630     }
633 static void
634 spdc_free_colors(SPDrawContext *dc)
636     /* Red */
637     if (dc->red_bpath) {
638         gtk_object_destroy(GTK_OBJECT(dc->red_bpath));
639         dc->red_bpath = NULL;
640     }
641     if (dc->red_curve) {
642         dc->red_curve = dc->red_curve->unref();
643     }
644     /* Blue */
645     if (dc->blue_bpath) {
646         gtk_object_destroy(GTK_OBJECT(dc->blue_bpath));
647         dc->blue_bpath = NULL;
648     }
649     if (dc->blue_curve) {
650         dc->blue_curve = dc->blue_curve->unref();
651     }
652     /* Green */
653     while (dc->green_bpaths) {
654         gtk_object_destroy(GTK_OBJECT(dc->green_bpaths->data));
655         dc->green_bpaths = g_slist_remove(dc->green_bpaths, dc->green_bpaths->data);
656     }
657     if (dc->green_curve) {
658         dc->green_curve = dc->green_curve->unref();
659     }
660     if (dc->green_anchor) {
661         dc->green_anchor = sp_draw_anchor_destroy(dc->green_anchor);
662     }
663     /* White */
664     if (dc->white_item) {
665         /* We do not hold refcount */
666         dc->white_item = NULL;
667     }
668     while (dc->white_curves) {
669         reinterpret_cast<SPCurve *>(dc->white_curves->data)->unref();
670         dc->white_curves = g_slist_remove(dc->white_curves, dc->white_curves->data);
671     }
672     while (dc->white_anchors) {
673         sp_draw_anchor_destroy((SPDrawAnchor *) dc->white_anchors->data);
674         dc->white_anchors = g_slist_remove(dc->white_anchors, dc->white_anchors->data);
675     }
679 /*
680   Local Variables:
681   mode:c++
682   c-file-style:"stroustrup"
683   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
684   indent-tabs-mode:nil
685   fill-column:99
686   End:
687 */
688 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :