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