Code

More infrastructure to have waiting LPEs that are freshly created and applied to...
[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     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  * (spiro spline mode is treated separately)
249  */
250 void
251 spdc_check_for_and_apply_waiting_LPE(SPDrawContext *dc, SPItem *item)
253     using namespace Inkscape::LivePathEffect;
255     if (item) {
256         if (prefs_get_int_attribute("tools.freehand", "spiro-spline-mode", 0)) {
257             Effect::createAndApply(SPIRO, dc->desktop->doc(), item);
258             return;
259         }
260         if (dc->waiting_LPE_type != INVALID_LPE) {
261             Effect::createAndApply(dc->waiting_LPE_type, dc->desktop->doc(), item);
262         }
263     }
266 /*
267  * Selection handlers
268  */
270 static void
271 spdc_selection_changed(Inkscape::Selection *sel, SPDrawContext *dc)
273     // note: in draw context, selection_changed() is only called when a new item was created;
274     // otherwise the following function call would yield wrong results
275     spdc_check_for_and_apply_waiting_LPE(dc, sel->singleItem());
277     if (dc->attach) {
278         spdc_attach_selection(dc, sel);
279     }
282 /* fixme: We have to ensure this is not delayed (Lauris) */
284 static void
285 spdc_selection_modified(Inkscape::Selection *sel, guint /*flags*/, SPDrawContext *dc)
287     if (dc->attach) {
288         spdc_attach_selection(dc, sel);
289     }
292 static void
293 spdc_attach_selection(SPDrawContext *dc, Inkscape::Selection */*sel*/)
295     /* We reset white and forget white/start/end anchors */
296     spdc_reset_white(dc);
297     dc->sa = NULL;
298     dc->ea = NULL;
300     SPItem *item = dc->selection ? dc->selection->singleItem() : NULL;
302     if ( item && SP_IS_PATH(item) ) {
303         /* Create new white data */
304         /* Item */
305         dc->white_item = item;
306         /* Curve list */
307         /* We keep it in desktop coordinates to eliminate calculation errors */
308         SPCurve *norm = sp_path_get_curve_for_edit (SP_PATH(item));
309         norm->transform(sp_item_i2d_affine(dc->white_item));
310         g_return_if_fail( norm != NULL );
311         dc->white_curves = g_slist_reverse(norm->split());
312         norm->unref();
313         /* Anchor list */
314         for (GSList *l = dc->white_curves; l != NULL; l = l->next) {
315             SPCurve *c;
316             c = (SPCurve*)l->data;
317             g_return_if_fail( c->get_length() > 1 );
318             if ( !c->is_closed() ) {
319                 SPDrawAnchor *a;
320                 a = sp_draw_anchor_new(dc, c, TRUE, c->first_point());
321                 dc->white_anchors = g_slist_prepend(dc->white_anchors, a);
322                 a = sp_draw_anchor_new(dc, c, FALSE, c->last_point());
323                 dc->white_anchors = g_slist_prepend(dc->white_anchors, a);
324             }
325         }
326         /* fixme: recalculate active anchor? */
327     }
331 /**
332  *  Snaps node or handle to PI/rotationsnapsperpi degree increments.
333  *
334  *  \param dc draw context
335  *  \param p cursor point (to be changed by snapping)
336  *  \param o origin point
337  *  \param state  keyboard state to check if ctrl was pressed
338 */
340 void spdc_endpoint_snap_rotation(SPEventContext const *const ec, NR::Point &p, NR::Point const o,
341                                  guint state)
343     /* Control must be down for this snap to work */
344     if ((state & GDK_CONTROL_MASK) == 0) {
345         return;
346     }
348     unsigned const snaps = abs(prefs_get_int_attribute("options.rotationsnapsperpi", "value", 12));
349     /* 0 means no snapping. */
351     /* mirrored by fabs, so this corresponds to 15 degrees */
352     NR::Point best; /* best solution */
353     double bn = NR_HUGE; /* best normal */
354     double bdot = 0;
355     NR::Point v = NR::Point(0, 1);
356     double const r00 = cos(M_PI / snaps), r01 = sin(M_PI / snaps);
357     double const r10 = -r01, r11 = r00;
359     NR::Point delta = p - o;
361     for (unsigned i = 0; i < snaps; i++) {
362         double const ndot = fabs(dot(v,NR::rot90(delta)));
363         NR::Point t(r00*v[NR::X] + r01*v[NR::Y],
364                     r10*v[NR::X] + r11*v[NR::Y]);
365         if (ndot < bn) {
366             /* I think it is better numerically to use the normal, rather than the dot product
367              * to assess solutions, but I haven't proven it. */
368             bn = ndot;
369             best = v;
370             bdot = dot(v, delta);
371         }
372         v = t;
373     }
375     if (fabs(bdot) > 0) {
376         p = o + bdot * best;
378         /* Snap it along best vector */
379         SnapManager &m = SP_EVENT_CONTEXT_DESKTOP(ec)->namedview->snap_manager;
380         m.setup(SP_EVENT_CONTEXT_DESKTOP(ec), NULL);
381         m.constrainedSnapReturnByRef( Inkscape::Snapper::SNAPPOINT_NODE, p, Inkscape::Snapper::ConstraintLine(best));
382     }
386 void spdc_endpoint_snap_free(SPEventContext const * const ec, NR::Point& p, guint const state)
388     /* Shift disables this snap */
389     if (state & GDK_SHIFT_MASK) {
390         return;
391     }
393     SnapManager &m = SP_EVENT_CONTEXT_DESKTOP(ec)->namedview->snap_manager;
394     m.setup(SP_EVENT_CONTEXT_DESKTOP(ec), NULL);
395     m.freeSnapReturnByRef(Inkscape::Snapper::SNAPPOINT_NODE, p);
398 static SPCurve *
399 reverse_then_unref(SPCurve *orig)
401     SPCurve *ret = orig->create_reverse();
402     orig->unref();
403     return ret;
406 /**
407  * Concats red, blue and green.
408  * If any anchors are defined, process these, optionally removing curves from white list
409  * Invoke _flush_white to write result back to object.
410  */
411 void
412 spdc_concat_colors_and_flush(SPDrawContext *dc, gboolean forceclosed)
414     /* Concat RBG */
415     SPCurve *c = dc->green_curve;
417     /* Green */
418     dc->green_curve = new SPCurve(64);
419     while (dc->green_bpaths) {
420         gtk_object_destroy(GTK_OBJECT(dc->green_bpaths->data));
421         dc->green_bpaths = g_slist_remove(dc->green_bpaths, dc->green_bpaths->data);
422     }
423     /* Blue */
424     c->append_continuous(dc->blue_curve, 0.0625);
425     dc->blue_curve->reset();
426     sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->blue_bpath), NULL);
427     /* Red */
428     if (dc->red_curve_is_valid) {
429         c->append_continuous(dc->red_curve, 0.0625);
430     }
431     dc->red_curve->reset();
432     sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->red_bpath), NULL);
434     if (c->is_empty()) {
435         c->unref();
436         return;
437     }
439     /* Step A - test, whether we ended on green anchor */
440     if ( forceclosed || ( dc->green_anchor && dc->green_anchor->active ) ) {
441         // We hit green anchor, closing Green-Blue-Red
442         SP_EVENT_CONTEXT_DESKTOP(dc)->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Path is closed."));
443         c->closepath_current();
444         /* Closed path, just flush */
445         spdc_flush_white(dc, c);
446         c->unref();
447         return;
448     }
450     /* Step B - both start and end anchored to same curve */
451     if ( dc->sa && dc->ea
452          && ( dc->sa->curve == dc->ea->curve )
453          && ( ( dc->sa != dc->ea )
454               || dc->sa->curve->is_closed() ) )
455     {
456         // We hit bot start and end of single curve, closing paths
457         SP_EVENT_CONTEXT_DESKTOP(dc)->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Closing path."));
458         if (dc->sa->start && !(dc->sa->curve->is_closed()) ) {
459             c = reverse_then_unref(c);
460         }
461         dc->sa->curve->append_continuous(c, 0.0625);
462         c->unref();
463         dc->sa->curve->closepath_current();
464         spdc_flush_white(dc, NULL);
465         return;
466     }
468     /* Step C - test start */
469     if (dc->sa) {
470         SPCurve *s = dc->sa->curve;
471         dc->white_curves = g_slist_remove(dc->white_curves, s);
472         if (dc->sa->start) {
473             s = reverse_then_unref(s);
474         }
475         s->append_continuous(c, 0.0625);
476         c->unref();
477         c = s;
478     } else /* Step D - test end */ if (dc->ea) {
479         SPCurve *e = dc->ea->curve;
480         dc->white_curves = g_slist_remove(dc->white_curves, e);
481         if (!dc->ea->start) {
482             e = reverse_then_unref(e);
483         }
484         c->append_continuous(e, 0.0625);
485         e->unref();
486     }
489     spdc_flush_white(dc, c);
491     c->unref();
494 static char const *
495 tool_name(SPDrawContext *dc)
497     return ( SP_IS_PEN_CONTEXT(dc)
498              ? "tools.freehand.pen"
499              : "tools.freehand.pencil" );
502 /*
503  * Flushes white curve(s) and additional curve into object
504  *
505  * No cleaning of colored curves - this has to be done by caller
506  * No rereading of white data, so if you cannot rely on ::modified, do it in caller
507  *
508  */
510 static void
511 spdc_flush_white(SPDrawContext *dc, SPCurve *gc)
513     SPCurve *c;
515     if (dc->white_curves) {
516         g_assert(dc->white_item);
517         c = SPCurve::concat(dc->white_curves);
518         g_slist_free(dc->white_curves);
519         dc->white_curves = NULL;
520         if (gc) {
521             c->append(gc, FALSE);
522         }
523     } else if (gc) {
524         c = gc;
525         c->ref();
526     } else {
527         return;
528     }
530     /* Now we have to go back to item coordinates at last */
531     c->transform(( dc->white_item
532                             ? sp_item_dt2i_affine(dc->white_item)
533                             : sp_desktop_dt2root_affine(SP_EVENT_CONTEXT_DESKTOP(dc)) ));
535     SPDesktop *desktop = SP_EVENT_CONTEXT_DESKTOP(dc);
536     SPDocument *doc = sp_desktop_document(desktop);
537     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
539     if ( c && !c->is_empty() ) {
540         /* We actually have something to write */
542         bool has_lpe = false;
543         Inkscape::XML::Node *repr;
544         if (dc->white_item) {
545             repr = SP_OBJECT_REPR(dc->white_item);
546             has_lpe = sp_lpe_item_has_path_effect_recursive(SP_LPE_ITEM(dc->white_item));
547         } else {
548             repr = xml_doc->createElement("svg:path");
549             /* Set style */
550             sp_desktop_apply_style_tool(desktop, repr, tool_name(dc), false);
551         }
553         gchar *str = sp_svg_write_path( c->get_pathvector() );
554         g_assert( str != NULL );
555         if (has_lpe)
556             repr->setAttribute("inkscape:original-d", str);
557         else
558             repr->setAttribute("d", str);
559         g_free(str);
561         if (!dc->white_item) {
562             /* Attach repr */
563             SPItem *item = SP_ITEM(desktop->currentLayer()->appendChildRepr(repr));
564             dc->selection->set(repr);
565             Inkscape::GC::release(repr);
566             item->transform = i2i_affine(desktop->currentRoot(), desktop->currentLayer());
567             item->updateRepr();
568         }
570         sp_document_done(doc, SP_IS_PEN_CONTEXT(dc)? SP_VERB_CONTEXT_PEN : SP_VERB_CONTEXT_PENCIL, 
571                          _("Draw path"));
573         // When quickly drawing several subpaths with Shift, the next subpath may be finished and
574         // flushed before the selection_modified signal is fired by the previous change, which
575         // results in the tool losing all of the selected path's curve except that last subpath. To
576         // fix this, we force the selection_modified callback now, to make sure the tool's curve is
577         // in sync immediately.
578         spdc_selection_modified(sp_desktop_selection(desktop), 0, dc);
579     }
581     c->unref();
583     /* Flush pending updates */
584     sp_document_ensure_up_to_date(doc);
587 /**
588  * Returns FIRST active anchor (the activated one).
589  */
590 SPDrawAnchor *
591 spdc_test_inside(SPDrawContext *dc, NR::Point p)
593     SPDrawAnchor *active = NULL;
595     /* Test green anchor */
596     if (dc->green_anchor) {
597         active = sp_draw_anchor_test(dc->green_anchor, p, TRUE);
598     }
600     for (GSList *l = dc->white_anchors; l != NULL; l = l->next) {
601         SPDrawAnchor *na = sp_draw_anchor_test((SPDrawAnchor *) l->data, p, !active);
602         if ( !active && na ) {
603             active = na;
604         }
605     }
607     return active;
610 static void
611 spdc_reset_white(SPDrawContext *dc)
613     if (dc->white_item) {
614         /* We do not hold refcount */
615         dc->white_item = NULL;
616     }
617     while (dc->white_curves) {
618         reinterpret_cast<SPCurve *>(dc->white_curves->data)->unref();
619         dc->white_curves = g_slist_remove(dc->white_curves, dc->white_curves->data);
620     }
621     while (dc->white_anchors) {
622         sp_draw_anchor_destroy((SPDrawAnchor *) dc->white_anchors->data);
623         dc->white_anchors = g_slist_remove(dc->white_anchors, dc->white_anchors->data);
624     }
627 static void
628 spdc_free_colors(SPDrawContext *dc)
630     /* Red */
631     if (dc->red_bpath) {
632         gtk_object_destroy(GTK_OBJECT(dc->red_bpath));
633         dc->red_bpath = NULL;
634     }
635     if (dc->red_curve) {
636         dc->red_curve = dc->red_curve->unref();
637     }
638     /* Blue */
639     if (dc->blue_bpath) {
640         gtk_object_destroy(GTK_OBJECT(dc->blue_bpath));
641         dc->blue_bpath = NULL;
642     }
643     if (dc->blue_curve) {
644         dc->blue_curve = dc->blue_curve->unref();
645     }
646     /* Green */
647     while (dc->green_bpaths) {
648         gtk_object_destroy(GTK_OBJECT(dc->green_bpaths->data));
649         dc->green_bpaths = g_slist_remove(dc->green_bpaths, dc->green_bpaths->data);
650     }
651     if (dc->green_curve) {
652         dc->green_curve = dc->green_curve->unref();
653     }
654     if (dc->green_anchor) {
655         dc->green_anchor = sp_draw_anchor_destroy(dc->green_anchor);
656     }
657     /* White */
658     if (dc->white_item) {
659         /* We do not hold refcount */
660         dc->white_item = NULL;
661     }
662     while (dc->white_curves) {
663         reinterpret_cast<SPCurve *>(dc->white_curves->data)->unref();
664         dc->white_curves = g_slist_remove(dc->white_curves, dc->white_curves->data);
665     }
666     while (dc->white_anchors) {
667         sp_draw_anchor_destroy((SPDrawAnchor *) dc->white_anchors->data);
668         dc->white_anchors = g_slist_remove(dc->white_anchors, dc->white_anchors->data);
669     }
673 /*
674   Local Variables:
675   mode:c++
676   c-file-style:"stroustrup"
677   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
678   indent-tabs-mode:nil
679   fill-column:99
680   End:
681 */
682 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :