Code

Provide knotholder for LPEPerpBisector; TODO: this replaces the usual nodepath 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     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 = new SPCurve(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 = new SPCurve(8);
176     /* Create green curve */
177     dc->green_curve = new SPCurve(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         norm->transform(sp_item_i2d_affine(dc->white_item));
285         g_return_if_fail( norm != NULL );
286         dc->white_curves = g_slist_reverse(norm->split());
287         norm->unref();
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 = c->first_bpath();
297                 e = c->last_bpath();
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 &m = SP_EVENT_CONTEXT_DESKTOP(ec)->namedview->snap_manager;
358         m.setup(SP_EVENT_CONTEXT_DESKTOP(ec), NULL);
359         m.constrainedSnapReturnByRef( Inkscape::Snapper::SNAPPOINT_NODE, p, Inkscape::Snapper::ConstraintLine(best));
360     }
364 void spdc_endpoint_snap_free(SPEventContext const * const ec, NR::Point& p, guint const state)
366     /* Shift disables this snap */
367     if (state & GDK_SHIFT_MASK) {
368         return;
369     }
371     SnapManager &m = SP_EVENT_CONTEXT_DESKTOP(ec)->namedview->snap_manager;
372     m.setup(SP_EVENT_CONTEXT_DESKTOP(ec), NULL);
373     m.freeSnapReturnByRef(Inkscape::Snapper::SNAPPOINT_NODE, p);
376 static SPCurve *
377 reverse_then_unref(SPCurve *orig)
379     SPCurve *ret = orig->create_reverse();
380     orig->unref();
381     return ret;
384 /**
385  * Concats red, blue and green.
386  * If any anchors are defined, process these, optionally removing curves from white list
387  * Invoke _flush_white to write result back to object.
388  */
389 void
390 spdc_concat_colors_and_flush(SPDrawContext *dc, gboolean forceclosed)
392     /* Concat RBG */
393     SPCurve *c = dc->green_curve;
395     /* Green */
396     dc->green_curve = new SPCurve(64);
397     while (dc->green_bpaths) {
398         gtk_object_destroy(GTK_OBJECT(dc->green_bpaths->data));
399         dc->green_bpaths = g_slist_remove(dc->green_bpaths, dc->green_bpaths->data);
400     }
401     /* Blue */
402     c->append_continuous(dc->blue_curve, 0.0625);
403     dc->blue_curve->reset();
404     sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->blue_bpath), NULL);
405     /* Red */
406     if (dc->red_curve_is_valid) {
407         c->append_continuous(dc->red_curve, 0.0625);
408     }
409     dc->red_curve->reset();
410     sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->red_bpath), NULL);
412     if (c->is_empty()) {
413         c->unref();
414         return;
415     }
417     /* Step A - test, whether we ended on green anchor */
418     if ( forceclosed || ( dc->green_anchor && dc->green_anchor->active ) ) {
419         // We hit green anchor, closing Green-Blue-Red
420         SP_EVENT_CONTEXT_DESKTOP(dc)->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Path is closed."));
421         c->closepath_current();
422         /* Closed path, just flush */
423         spdc_flush_white(dc, c);
424         c->unref();
425         return;
426     }
428     /* Step B - both start and end anchored to same curve */
429     if ( dc->sa && dc->ea
430          && ( dc->sa->curve == dc->ea->curve )
431          && ( ( dc->sa != dc->ea )
432               || dc->sa->curve->is_closed() ) )
433     {
434         // We hit bot start and end of single curve, closing paths
435         SP_EVENT_CONTEXT_DESKTOP(dc)->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Closing path."));
436         if (dc->sa->start && !(dc->sa->curve->is_closed()) ) {
437             c = reverse_then_unref(c);
438         }
439         dc->sa->curve->append_continuous(c, 0.0625);
440         c->unref();
441         dc->sa->curve->closepath_current();
442         spdc_flush_white(dc, NULL);
443         return;
444     }
446     /* Step C - test start */
447     if (dc->sa) {
448         SPCurve *s = dc->sa->curve;
449         dc->white_curves = g_slist_remove(dc->white_curves, s);
450         if (dc->sa->start) {
451             s = reverse_then_unref(s);
452         }
453         s->append_continuous(c, 0.0625);
454         c->unref();
455         c = s;
456     } else /* Step D - test end */ if (dc->ea) {
457         SPCurve *e = dc->ea->curve;
458         dc->white_curves = g_slist_remove(dc->white_curves, e);
459         if (!dc->ea->start) {
460             e = reverse_then_unref(e);
461         }
462         c->append_continuous(e, 0.0625);
463         e->unref();
464     }
467     spdc_flush_white(dc, c);
469     c->unref();
472 static char const *
473 tool_name(SPDrawContext *dc)
475     return ( SP_IS_PEN_CONTEXT(dc)
476              ? "tools.freehand.pen"
477              : "tools.freehand.pencil" );
480 /*
481  * Flushes white curve(s) and additional curve into object
482  *
483  * No cleaning of colored curves - this has to be done by caller
484  * No rereading of white data, so if you cannot rely on ::modified, do it in caller
485  *
486  */
488 static void
489 spdc_flush_white(SPDrawContext *dc, SPCurve *gc)
491     SPCurve *c;
493     if (dc->white_curves) {
494         g_assert(dc->white_item);
495         c = SPCurve::concat(dc->white_curves);
496         g_slist_free(dc->white_curves);
497         dc->white_curves = NULL;
498         if (gc) {
499             c->append(gc, FALSE);
500         }
501     } else if (gc) {
502         c = gc;
503         c->ref();
504     } else {
505         return;
506     }
508     /* Now we have to go back to item coordinates at last */
509     c->transform(( dc->white_item
510                             ? sp_item_dt2i_affine(dc->white_item)
511                             : sp_desktop_dt2root_affine(SP_EVENT_CONTEXT_DESKTOP(dc)) ));
513     SPDesktop *desktop = SP_EVENT_CONTEXT_DESKTOP(dc);
514     SPDocument *doc = sp_desktop_document(desktop);
515     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
517     if ( c && !c->is_empty() ) {
518         /* We actually have something to write */
520         bool has_lpe = false;
521         Inkscape::XML::Node *repr;
522         if (dc->white_item) {
523             repr = SP_OBJECT_REPR(dc->white_item);
524             has_lpe = sp_lpe_item_has_path_effect_recursive(SP_LPE_ITEM(dc->white_item));
525         } else {
526             repr = xml_doc->createElement("svg:path");
527             /* Set style */
528             sp_desktop_apply_style_tool(desktop, repr, tool_name(dc), false);
529         }
531         gchar *str = sp_svg_write_path(SP_CURVE_BPATH(c));
532         g_assert( str != NULL );
533         if (has_lpe)
534             repr->setAttribute("inkscape:original-d", str);
535         else
536             repr->setAttribute("d", str);
537         g_free(str);
539         if (!dc->white_item) {
540             /* Attach repr */
541             SPItem *item = SP_ITEM(desktop->currentLayer()->appendChildRepr(repr));
542             dc->selection->set(repr);
543             Inkscape::GC::release(repr);
544             item->transform = i2i_affine(desktop->currentRoot(), desktop->currentLayer());
545             item->updateRepr();
546         }
548         sp_document_done(doc, SP_IS_PEN_CONTEXT(dc)? SP_VERB_CONTEXT_PEN : SP_VERB_CONTEXT_PENCIL, 
549                          _("Draw path"));
551         // When quickly drawing several subpaths with Shift, the next subpath may be finished and
552         // flushed before the selection_modified signal is fired by the previous change, which
553         // results in the tool losing all of the selected path's curve except that last subpath. To
554         // fix this, we force the selection_modified callback now, to make sure the tool's curve is
555         // in sync immediately.
556         spdc_selection_modified(sp_desktop_selection(desktop), 0, dc);
557     }
559     c->unref();
561     /* Flush pending updates */
562     sp_document_ensure_up_to_date(doc);
565 /**
566  * Returns FIRST active anchor (the activated one).
567  */
568 SPDrawAnchor *
569 spdc_test_inside(SPDrawContext *dc, NR::Point p)
571     SPDrawAnchor *active = NULL;
573     /* Test green anchor */
574     if (dc->green_anchor) {
575         active = sp_draw_anchor_test(dc->green_anchor, p, TRUE);
576     }
578     for (GSList *l = dc->white_anchors; l != NULL; l = l->next) {
579         SPDrawAnchor *na = sp_draw_anchor_test((SPDrawAnchor *) l->data, p, !active);
580         if ( !active && na ) {
581             active = na;
582         }
583     }
585     return active;
588 static void
589 spdc_reset_white(SPDrawContext *dc)
591     if (dc->white_item) {
592         /* We do not hold refcount */
593         dc->white_item = NULL;
594     }
595     while (dc->white_curves) {
596         reinterpret_cast<SPCurve *>(dc->white_curves->data)->unref();
597         dc->white_curves = g_slist_remove(dc->white_curves, dc->white_curves->data);
598     }
599     while (dc->white_anchors) {
600         sp_draw_anchor_destroy((SPDrawAnchor *) dc->white_anchors->data);
601         dc->white_anchors = g_slist_remove(dc->white_anchors, dc->white_anchors->data);
602     }
605 static void
606 spdc_free_colors(SPDrawContext *dc)
608     /* Red */
609     if (dc->red_bpath) {
610         gtk_object_destroy(GTK_OBJECT(dc->red_bpath));
611         dc->red_bpath = NULL;
612     }
613     if (dc->red_curve) {
614         dc->red_curve = dc->red_curve->unref();
615     }
616     /* Blue */
617     if (dc->blue_bpath) {
618         gtk_object_destroy(GTK_OBJECT(dc->blue_bpath));
619         dc->blue_bpath = NULL;
620     }
621     if (dc->blue_curve) {
622         dc->blue_curve = dc->blue_curve->unref();
623     }
624     /* Green */
625     while (dc->green_bpaths) {
626         gtk_object_destroy(GTK_OBJECT(dc->green_bpaths->data));
627         dc->green_bpaths = g_slist_remove(dc->green_bpaths, dc->green_bpaths->data);
628     }
629     if (dc->green_curve) {
630         dc->green_curve = dc->green_curve->unref();
631     }
632     if (dc->green_anchor) {
633         dc->green_anchor = sp_draw_anchor_destroy(dc->green_anchor);
634     }
635     /* White */
636     if (dc->white_item) {
637         /* We do not hold refcount */
638         dc->white_item = NULL;
639     }
640     while (dc->white_curves) {
641         reinterpret_cast<SPCurve *>(dc->white_curves->data)->unref();
642         dc->white_curves = g_slist_remove(dc->white_curves, dc->white_curves->data);
643     }
644     while (dc->white_anchors) {
645         sp_draw_anchor_destroy((SPDrawAnchor *) dc->white_anchors->data);
646         dc->white_anchors = g_slist_remove(dc->white_anchors, dc->white_anchors->data);
647     }
651 /*
652   Local Variables:
653   mode:c++
654   c-file-style:"stroustrup"
655   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
656   indent-tabs-mode:nil
657   fill-column:99
658   End:
659 */
660 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :