Code

ed1d6a7a4820f3248c00ad63a28616460822c331
[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"
44 static void sp_draw_context_class_init(SPDrawContextClass *klass);
45 static void sp_draw_context_init(SPDrawContext *dc);
46 static void sp_draw_context_dispose(GObject *object);
48 static void sp_draw_context_setup(SPEventContext *ec);
49 static void sp_draw_context_set(SPEventContext *ec, gchar const *key, gchar const *value);
50 static void sp_draw_context_finish(SPEventContext *ec);
52 static gint sp_draw_context_root_handler(SPEventContext *event_context, GdkEvent *event);
54 static void spdc_selection_changed(Inkscape::Selection *sel, SPDrawContext *dc);
55 static void spdc_selection_modified(Inkscape::Selection *sel, guint flags, SPDrawContext *dc);
57 static void spdc_attach_selection(SPDrawContext *dc, Inkscape::Selection *sel);
59 static void spdc_flush_white(SPDrawContext *dc, SPCurve *gc);
61 static void spdc_reset_white(SPDrawContext *dc);
62 static void spdc_free_colors(SPDrawContext *dc);
65 static SPEventContextClass *draw_parent_class;
68 GType
69 sp_draw_context_get_type(void)
70 {
71     static GType type = 0;
72     if (!type) {
73         GTypeInfo info = {
74             sizeof(SPDrawContextClass),
75             NULL, NULL,
76             (GClassInitFunc) sp_draw_context_class_init,
77             NULL, NULL,
78             sizeof(SPDrawContext),
79             4,
80             (GInstanceInitFunc) sp_draw_context_init,
81             NULL,   /* value_table */
82         };
83         type = g_type_register_static(SP_TYPE_EVENT_CONTEXT, "SPDrawContext", &info, (GTypeFlags)0);
84     }
85     return type;
86 }
88 static void
89 sp_draw_context_class_init(SPDrawContextClass *klass)
90 {
91     GObjectClass *object_class;
92     SPEventContextClass *ec_class;
94     object_class = (GObjectClass *)klass;
95     ec_class = (SPEventContextClass *) klass;
97     draw_parent_class = (SPEventContextClass*)g_type_class_peek_parent(klass);
99     object_class->dispose = sp_draw_context_dispose;
101     ec_class->setup = sp_draw_context_setup;
102     ec_class->set = sp_draw_context_set;
103     ec_class->finish = sp_draw_context_finish;
104     ec_class->root_handler = sp_draw_context_root_handler;
107 static void
108 sp_draw_context_init(SPDrawContext *dc)
110     dc->attach = FALSE;
112     dc->red_color = 0xff00007f;
113     dc->blue_color = 0x0000ff7f;
114     dc->green_color = 0x00ff007f;
115     dc->red_curve_is_valid = false;
117     new (&dc->sel_changed_connection) sigc::connection();
118     new (&dc->sel_modified_connection) sigc::connection();
121 static void
122 sp_draw_context_dispose(GObject *object)
124     SPDrawContext *dc = SP_DRAW_CONTEXT(object);
126     dc->sel_changed_connection.~connection();
127     dc->sel_modified_connection.~connection();
129     if (dc->grab) {
130         sp_canvas_item_ungrab(dc->grab, GDK_CURRENT_TIME);
131         dc->grab = NULL;
132     }
134     if (dc->selection) {
135         dc->selection = NULL;
136     }
138     spdc_free_colors(dc);
140     G_OBJECT_CLASS(draw_parent_class)->dispose(object);
143 static void
144 sp_draw_context_setup(SPEventContext *ec)
146     SPDrawContext *dc = SP_DRAW_CONTEXT(ec);
147     SPDesktop *dt = ec->desktop;
149     if (((SPEventContextClass *) draw_parent_class)->setup) {
150         ((SPEventContextClass *) draw_parent_class)->setup(ec);
151     }
153     dc->selection = SP_DT_SELECTION(dt);
155     /* Connect signals to track selection changes */
156     dc->sel_changed_connection = dc->selection->connectChanged(
157         sigc::bind(sigc::ptr_fun(&spdc_selection_changed), dc)
158     );
159     dc->sel_modified_connection = dc->selection->connectModified(
160         sigc::bind(sigc::ptr_fun(&spdc_selection_modified), dc)
161     );
163     /* Create red bpath */
164     dc->red_bpath = sp_canvas_bpath_new(SP_DT_SKETCH(ec->desktop), NULL);
165     sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(dc->red_bpath), dc->red_color, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
166     /* Create red curve */
167     dc->red_curve = sp_curve_new_sized(4);
169     /* Create blue bpath */
170     dc->blue_bpath = sp_canvas_bpath_new(SP_DT_SKETCH(ec->desktop), NULL);
171     sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(dc->blue_bpath), dc->blue_color, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
172     /* Create blue curve */
173     dc->blue_curve = sp_curve_new_sized(8);
175     /* Create green curve */
176     dc->green_curve = sp_curve_new_sized(64);
177     /* No green anchor by default */
178     dc->green_anchor = NULL;
179     dc->green_closed = FALSE;
181     dc->attach = TRUE;
182     spdc_attach_selection(dc, dc->selection);
185 static void
186 sp_draw_context_finish(SPEventContext *ec)
188     SPDrawContext *dc = SP_DRAW_CONTEXT(ec);
190     dc->sel_changed_connection.disconnect();
191     dc->sel_modified_connection.disconnect();
193     if (dc->grab) {
194         sp_canvas_item_ungrab(dc->grab, GDK_CURRENT_TIME);
195     }
197     if (dc->selection) {
198         dc->selection = NULL;
199     }
201     spdc_free_colors(dc);
204 static void
205 sp_draw_context_set(SPEventContext *ec, const gchar *key, const gchar *value)
209 gint
210 sp_draw_context_root_handler(SPEventContext *ec, GdkEvent *event)
212     //SPDrawContext *dc = SP_DRAW_CONTEXT(ec);
213     SPDesktop *desktop = ec->desktop;
215     gint ret = FALSE;
217     switch (event->type) {
218         case GDK_KEY_PRESS:
219             switch (get_group0_keyval (&event->key)) {
220                 case GDK_Escape:
221                     SP_DT_SELECTION(desktop)->clear();
222                     ret = TRUE;
223                     break;
224                 case GDK_Tab: // Tab - cycle selection forward
225                     if (!(MOD__CTRL_ONLY || (MOD__CTRL && MOD__SHIFT))) {
226                         sp_selection_item_next();
227                         ret = TRUE;
228                     }
229                     break;
230                 case GDK_ISO_Left_Tab: // Shift Tab - cycle selection backward
231                     if (!(MOD__CTRL_ONLY || (MOD__CTRL && MOD__SHIFT))) {
232                         sp_selection_item_prev();
233                         ret = TRUE;
234                     }
235                     break;
236                 case GDK_Up:
237                 case GDK_Down:
238                 case GDK_KP_Up:
239                 case GDK_KP_Down:
240                     // prevent the zoom field from activation
241                     if (!MOD__CTRL_ONLY) {
242                         ret = TRUE;
243                     }
244                     break;
245                 default:
246             break;
247         }
248         break;
249     default:
250         break;
251     }
253     if (!ret) {
254         if (((SPEventContextClass *) draw_parent_class)->root_handler) {
255             ret = ((SPEventContextClass *) draw_parent_class)->root_handler(ec, event);
256         }
257     }
259     return ret;
263 /*
264  * Selection handlers
265  */
267 static void
268 spdc_selection_changed(Inkscape::Selection *sel, SPDrawContext *dc)
270     if (dc->attach) {
271         spdc_attach_selection(dc, sel);
272     }
275 /* fixme: We have to ensure this is not delayed (Lauris) */
277 static void
278 spdc_selection_modified(Inkscape::Selection *sel, guint flags, SPDrawContext *dc)
280     if (dc->attach) {
281         spdc_attach_selection(dc, sel);
282     }
285 static void
286 spdc_attach_selection(SPDrawContext *dc, Inkscape::Selection *sel)
288     /* We reset white and forget white/start/end anchors */
289     spdc_reset_white(dc);
290     dc->sa = NULL;
291     dc->ea = NULL;
293     SPItem *item = dc->selection ? dc->selection->singleItem() : NULL;
295     if ( item && SP_IS_PATH(item) ) {
296         /* Create new white data */
297         /* Item */
298         dc->white_item = item;
299         /* Curve list */
300         /* We keep it in desktop coordinates to eliminate calculation errors */
301         SPCurve *norm = sp_shape_get_curve(SP_SHAPE(item));
302         sp_curve_transform(norm, sp_item_i2d_affine(dc->white_item));
303         g_return_if_fail( norm != NULL );
304         dc->white_curves = sp_curve_split(norm);
305         sp_curve_unref(norm);
306         /* Anchor list */
307         for (GSList *l = dc->white_curves; l != NULL; l = l->next) {
308             SPCurve *c;
309             c = (SPCurve*)l->data;
310             g_return_if_fail( c->end > 1 );
311             if ( c->bpath->code == NR_MOVETO_OPEN ) {
312                 NArtBpath *s, *e;
313                 SPDrawAnchor *a;
314                 s = sp_curve_first_bpath(c);
315                 e = sp_curve_last_bpath(c);
316                 a = sp_draw_anchor_new(dc, c, TRUE, NR::Point(s->x3, s->y3));
317                 dc->white_anchors = g_slist_prepend(dc->white_anchors, a);
318                 a = sp_draw_anchor_new(dc, c, FALSE, NR::Point(e->x3, e->y3));
319                 dc->white_anchors = g_slist_prepend(dc->white_anchors, a);
320             }
321         }
322         /* fixme: recalculate active anchor? */
323     }
327 /**
328  *  Snaps node or handle to PI/rotationsnapsperpi degree increments.
329  *
330  *  \param dc draw context
331  *  \param p cursor point (to be changed by snapping)
332  *  \param o origin point
333  *  \param state  keyboard state to check if ctrl was pressed
334 */
336 void spdc_endpoint_snap_rotation(SPEventContext const *const ec, NR::Point &p, NR::Point const o,
337                                  guint state)
339     /* Control must be down for this snap to work */
340     if ((state & GDK_CONTROL_MASK) == 0) {
341         return;
342     }
344     unsigned const snaps = abs(prefs_get_int_attribute("options.rotationsnapsperpi", "value", 12));
345     /* 0 means no snapping. */
347     /* mirrored by fabs, so this corresponds to 15 degrees */
348     NR::Point best; /* best solution */
349     double bn = NR_HUGE; /* best normal */
350     double bdot = 0;
351     NR::Point v = NR::Point(0, 1);
352     double const r00 = cos(M_PI / snaps), r01 = sin(M_PI / snaps);
353     double const r10 = -r01, r11 = r00;
355     NR::Point delta = p - o;
357     for (unsigned i = 0; i < snaps; i++) {
358         double const ndot = fabs(dot(v,NR::rot90(delta)));
359         NR::Point t(r00*v[NR::X] + r01*v[NR::Y],
360                     r10*v[NR::X] + r11*v[NR::Y]);
361         if (ndot < bn) {
362             /* I think it is better numerically to use the normal, rather than the dot product
363              * to assess solutions, but I haven't proven it. */
364             bn = ndot;
365             best = v;
366             bdot = dot(v, delta);
367         }
368         v = t;
369     }
370     
371     if (fabs(bdot) > 0) {
372         p = o + bdot * best;
373         
374         /* Snap it along best vector */
375         SnapManager const m(SP_EVENT_CONTEXT_DESKTOP(ec)->namedview);
376         p = m.constrainedSnap(Inkscape::Snapper::SNAP_POINT | Inkscape::Snapper::BBOX_POINT,
377                               p, best, NULL).getPoint();
378     }
382 void spdc_endpoint_snap_free(SPEventContext const * const ec, NR::Point& p, guint const state)
384     /* Shift disables this snap */
385     if (state & GDK_SHIFT_MASK) {
386         return;
387     }
389     /* FIXME: this should be doing bbox snap as well */
390     SnapManager const m(SP_EVENT_CONTEXT_DESKTOP(ec)->namedview);
391     p = m.freeSnap(Inkscape::Snapper::BBOX_POINT | Inkscape::Snapper::SNAP_POINT, p, NULL).getPoint();
394 static SPCurve *
395 reverse_then_unref(SPCurve *orig)
397     SPCurve *ret = sp_curve_reverse(orig);
398     sp_curve_unref(orig);
399     return ret;
402 /**
403  * Concats red, blue and green.
404  * If any anchors are defined, process these, optionally removing curves from white list
405  * Invoke _flush_white to write result back to object.
406  */
407 void
408 spdc_concat_colors_and_flush(SPDrawContext *dc, gboolean forceclosed)
410     /* Concat RBG */
411     SPCurve *c = dc->green_curve;
413     /* Green */
414     dc->green_curve = sp_curve_new_sized(64);
415     while (dc->green_bpaths) {
416         gtk_object_destroy(GTK_OBJECT(dc->green_bpaths->data));
417         dc->green_bpaths = g_slist_remove(dc->green_bpaths, dc->green_bpaths->data);
418     }
419     /* Blue */
420     sp_curve_append_continuous(c, dc->blue_curve, 0.0625);
421     sp_curve_reset(dc->blue_curve);
422     sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->blue_bpath), NULL);
423     /* Red */
424     if (dc->red_curve_is_valid) {
425         sp_curve_append_continuous(c, dc->red_curve, 0.0625);
426     }
427     sp_curve_reset(dc->red_curve);
428     sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->red_bpath), NULL);
430     if (sp_curve_empty(c)) {
431         sp_curve_unref(c);
432         return;
433     }
435     /* Step A - test, whether we ended on green anchor */
436     if ( forceclosed || ( dc->green_anchor && dc->green_anchor->active ) ) {
437         // We hit green anchor, closing Green-Blue-Red
438         SP_EVENT_CONTEXT_DESKTOP(dc)->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Path is closed."));
439         sp_curve_closepath_current(c);
440         /* Closed path, just flush */
441         spdc_flush_white(dc, c);
442         sp_curve_unref(c);
443         return;
444     }
446     /* Step B - both start and end anchored to same curve */
447     if ( dc->sa && dc->ea
448          && ( dc->sa->curve == dc->ea->curve )
449          && ( ( dc->sa != dc->ea )
450               || dc->sa->curve->closed ) )
451     {
452         // We hit bot start and end of single curve, closing paths
453         SP_EVENT_CONTEXT_DESKTOP(dc)->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Closing path."));
454         if (dc->sa->start && !(dc->sa->curve->closed) ) {
455             c = reverse_then_unref(c);
456         }
457         sp_curve_append_continuous(dc->sa->curve, c, 0.0625);
458         sp_curve_unref(c);
459         sp_curve_closepath_current(dc->sa->curve);
460         spdc_flush_white(dc, NULL);
461         return;
462     }
464     /* Step C - test start */
465     if (dc->sa) {
466         SPCurve *s = dc->sa->curve;
467         dc->white_curves = g_slist_remove(dc->white_curves, s);
468         if (dc->sa->start) {
469             s = reverse_then_unref(s);
470         }
471         sp_curve_append_continuous(s, c, 0.0625);
472         sp_curve_unref(c);
473         c = s;
474     } else /* Step D - test end */ if (dc->ea) {
475         SPCurve *e = dc->ea->curve;
476         dc->white_curves = g_slist_remove(dc->white_curves, e);
477         if (!dc->ea->start) {
478             e = reverse_then_unref(e);
479         }
480         sp_curve_append_continuous(c, e, 0.0625);
481         sp_curve_unref(e);
482     }
485     spdc_flush_white(dc, c);
487     sp_curve_unref(c);
490 static char const *
491 tool_name(SPDrawContext *dc)
493     return ( SP_IS_PEN_CONTEXT(dc)
494              ? "tools.freehand.pen"
495              : "tools.freehand.pencil" );
498 /*
499  * Flushes white curve(s) and additional curve into object
500  *
501  * No cleaning of colored curves - this has to be done by caller
502  * No rereading of white data, so if you cannot rely on ::modified, do it in caller
503  *
504  */
506 static void
507 spdc_flush_white(SPDrawContext *dc, SPCurve *gc)
509     SPCurve *c;
511     if (dc->white_curves) {
512         g_assert(dc->white_item);
513         c = sp_curve_concat(dc->white_curves);
514         g_slist_free(dc->white_curves);
515         dc->white_curves = NULL;
516         if (gc) {
517             sp_curve_append(c, gc, FALSE);
518         }
519     } else if (gc) {
520         c = gc;
521         sp_curve_ref(c);
522     } else {
523         return;
524     }
526     /* Now we have to go back to item coordinates at last */
527     sp_curve_transform(c, ( dc->white_item
528                             ? sp_item_dt2i_affine(dc->white_item)
529                             : sp_desktop_dt2root_affine(SP_EVENT_CONTEXT_DESKTOP(dc)) ));
531     SPDesktop *desktop = SP_EVENT_CONTEXT_DESKTOP(dc);
532     SPDocument *doc = SP_DT_DOCUMENT(desktop);
534     if ( c && !sp_curve_empty(c) ) {
535         /* We actually have something to write */
537         Inkscape::XML::Node *repr;
538         if (dc->white_item) {
539             repr = SP_OBJECT_REPR(dc->white_item);
540         } else {
541             repr = sp_repr_new("svg:path");
542             /* Set style */
543             sp_desktop_apply_style_tool(desktop, repr, tool_name(dc), false);
544         }
546         gchar *str = sp_svg_write_path(SP_CURVE_BPATH(c));
547         g_assert( str != NULL );
548         repr->setAttribute("d", str);
549         g_free(str);
551         if (!dc->white_item) {
552             /* Attach repr */
553             SPItem *item = SP_ITEM(desktop->currentLayer()->appendChildRepr(repr));
554             dc->selection->set(repr);
555             Inkscape::GC::release(repr);
556             item->transform = i2i_affine(desktop->currentRoot(), desktop->currentLayer());
557             item->updateRepr();
558         }
560         sp_document_done(doc);
561     }
563     sp_curve_unref(c);
565     /* Flush pending updates */
566     sp_document_ensure_up_to_date(doc);
569 /**
570  * Returns FIRST active anchor (the activated one).
571  */
572 SPDrawAnchor *
573 spdc_test_inside(SPDrawContext *dc, NR::Point p)
575     SPDrawAnchor *active = NULL;
577     /* Test green anchor */
578     if (dc->green_anchor) {
579         active = sp_draw_anchor_test(dc->green_anchor, p, TRUE);
580     }
582     for (GSList *l = dc->white_anchors; l != NULL; l = l->next) {
583         SPDrawAnchor *na = sp_draw_anchor_test((SPDrawAnchor *) l->data, p, !active);
584         if ( !active && na ) {
585             active = na;
586         }
587     }
589     return active;
592 static void
593 spdc_reset_white(SPDrawContext *dc)
595     if (dc->white_item) {
596         /* We do not hold refcount */
597         dc->white_item = NULL;
598     }
599     while (dc->white_curves) {
600         sp_curve_unref((SPCurve *) dc->white_curves->data);
601         dc->white_curves = g_slist_remove(dc->white_curves, dc->white_curves->data);
602     }
603     while (dc->white_anchors) {
604         sp_draw_anchor_destroy((SPDrawAnchor *) dc->white_anchors->data);
605         dc->white_anchors = g_slist_remove(dc->white_anchors, dc->white_anchors->data);
606     }
609 static void
610 spdc_free_colors(SPDrawContext *dc)
612     /* Red */
613     if (dc->red_bpath) {
614         gtk_object_destroy(GTK_OBJECT(dc->red_bpath));
615         dc->red_bpath = NULL;
616     }
617     if (dc->red_curve) {
618         dc->red_curve = sp_curve_unref(dc->red_curve);
619     }
620     /* Blue */
621     if (dc->blue_bpath) {
622         gtk_object_destroy(GTK_OBJECT(dc->blue_bpath));
623         dc->blue_bpath = NULL;
624     }
625     if (dc->blue_curve) {
626         dc->blue_curve = sp_curve_unref(dc->blue_curve);
627     }
628     /* Green */
629     while (dc->green_bpaths) {
630         gtk_object_destroy(GTK_OBJECT(dc->green_bpaths->data));
631         dc->green_bpaths = g_slist_remove(dc->green_bpaths, dc->green_bpaths->data);
632     }
633     if (dc->green_curve) {
634         dc->green_curve = sp_curve_unref(dc->green_curve);
635     }
636     if (dc->green_anchor) {
637         dc->green_anchor = sp_draw_anchor_destroy(dc->green_anchor);
638     }
639     /* White */
640     if (dc->white_item) {
641         /* We do not hold refcount */
642         dc->white_item = NULL;
643     }
644     while (dc->white_curves) {
645         sp_curve_unref((SPCurve *) dc->white_curves->data);
646         dc->white_curves = g_slist_remove(dc->white_curves, dc->white_curves->data);
647     }
648     while (dc->white_anchors) {
649         sp_draw_anchor_destroy((SPDrawAnchor *) dc->white_anchors->data);
650         dc->white_anchors = g_slist_remove(dc->white_anchors, dc->white_anchors->data);
651     }
655 /*
656   Local Variables:
657   mode:c++
658   c-file-style:"stroustrup"
659   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
660   indent-tabs-mode:nil
661   fill-column:99
662   End:
663 */
664 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :