Code

From trunk
[inkscape.git] / src / connector-context.cpp
1 /*
2  * Connector creation tool
3  *
4  * Authors:
5  *   Michael Wybrow <mjwybrow@users.sourceforge.net>
6  *
7  * Copyright (C) 2005 Michael Wybrow
8  *
9  * Released under GNU GPL, read the file 'COPYING' for more information
10  *
11  * TODO:
12  *  o  Have shapes avoid convex hulls of objects, rather than their
13  *     bounding box.  Possibly implement the unfinished ConvexHull
14  *     class in libnr.
15  *     (HOWEVER, using the convex hull C of a shape S does the wrong thing if a
16  *     connector starts outside of S but inside C, or if the best route around
17  *     an object involves going inside C but without entering S.)
18  *  o  Draw connectors to shape edges rather than bounding box.
19  *  o  Show a visual indicator for objects with the 'avoid' property set.
20  *  o  Allow user to change a object between a path and connector through
21  *     the interface.
22  *  o  Create an interface for setting markers (arrow heads).
23  *  o  Better distinguish between paths and connectors to prevent problems
24  *     in the node tool and paths accidently being turned into connectors
25  *     in the connector tool.  Perhaps have a way to convert between.
26  *  o  Only call libavoid's updateEndPoint as required.  Currently we do it
27  *     for both endpoints, even if only one is moving.
28  *  o  Allow user-placeable connection points.
29  *  o  Deal sanely with connectors with both endpoints attached to the
30  *     same connection point, and drawing of connectors attaching
31  *     overlaping shapes (currently tries to adjust connector to be
32  *     outside both bounding boxes).
33  *  o  Fix many special cases related to connectors updating,
34  *     e.g., copying a couple of shapes and a connector that are
35  *           attached to each other.
36  *     e.g., detach connector when it is moved or transformed in
37  *           one of the other contexts.
38  *  o  Cope with shapes whose ids change when they have attached
39  *     connectors.
40  *  o  gobble_motion_events(GDK_BUTTON1_MASK)?;
41  *
42  */
44 #include <gdk/gdkkeysyms.h>
45 #include <string>
46 #include <cstring>
48 #include "connector-context.h"
49 #include "pixmaps/cursor-connector.xpm"
50 #include "xml/node-event-vector.h"
51 #include "xml/repr.h"
52 #include "svg/svg.h"
53 #include "desktop.h"
54 #include "desktop-style.h"
55 #include "desktop-affine.h"
56 #include "desktop-handles.h"
57 #include "document.h"
58 #include "message-context.h"
59 #include "message-stack.h"
60 #include "selection.h"
61 #include "inkscape.h"
62 #include "preferences.h"
63 #include "sp-path.h"
64 #include "display/canvas-bpath.h"
65 #include "display/sodipodi-ctrl.h"
66 #include <glibmm/i18n.h>
67 #include "snap.h"
68 #include "knot.h"
69 #include "sp-conn-end.h"
70 #include "conn-avoid-ref.h"
71 #include "libavoid/vertices.h"
72 #include "context-fns.h"
73 #include "sp-namedview.h"
74 #include "sp-text.h"
75 #include "sp-flowtext.h"
76 #include "display/curve.h"
78 static void sp_connector_context_class_init(SPConnectorContextClass *klass);
79 static void sp_connector_context_init(SPConnectorContext *conn_context);
80 static void sp_connector_context_dispose(GObject *object);
82 static void sp_connector_context_setup(SPEventContext *ec);
83 static void sp_connector_context_finish(SPEventContext *ec);
84 static gint sp_connector_context_root_handler(SPEventContext *ec, GdkEvent *event);
85 static gint sp_connector_context_item_handler(SPEventContext *event_context, SPItem *item, GdkEvent *event);
87 // Stuff borrowed from DrawContext
88 static void spcc_connector_set_initial_point(SPConnectorContext *cc, Geom::Point const p);
89 static void spcc_connector_set_subsequent_point(SPConnectorContext *cc, Geom::Point const p);
90 static void spcc_connector_finish_segment(SPConnectorContext *cc, Geom::Point p);
91 static void spcc_reset_colors(SPConnectorContext *cc);
92 static void spcc_connector_finish(SPConnectorContext *cc);
93 static void spcc_concat_colors_and_flush(SPConnectorContext *cc);
94 static void spcc_flush_white(SPConnectorContext *cc, SPCurve *gc);
96 // Context event handlers
97 static gint connector_handle_button_press(SPConnectorContext *const cc, GdkEventButton const &bevent);
98 static gint connector_handle_motion_notify(SPConnectorContext *const cc, GdkEventMotion const &mevent);
99 static gint connector_handle_button_release(SPConnectorContext *const cc, GdkEventButton const &revent);
100 static gint connector_handle_key_press(SPConnectorContext *const cc, guint const keyval);
102 static void cc_set_active_shape(SPConnectorContext *cc, SPItem *item);
103 static void cc_clear_active_shape(SPConnectorContext *cc);
104 static void cc_set_active_conn(SPConnectorContext *cc, SPItem *item);
105 static void cc_clear_active_conn(SPConnectorContext *cc);
106 static gchar *conn_pt_handle_test(SPConnectorContext *cc, Geom::Point& w);
107 static bool cc_item_is_shape(SPItem *item);
108 static void cc_selection_changed(Inkscape::Selection *selection, gpointer data);
109 static void cc_connector_rerouting_finish(SPConnectorContext *const cc,
110         Geom::Point *const p);
112 static void shape_event_attr_deleted(Inkscape::XML::Node *repr,
113         Inkscape::XML::Node *child, Inkscape::XML::Node *ref, gpointer data);
114 static void shape_event_attr_changed(Inkscape::XML::Node *repr, gchar const *name,
115         gchar const *old_value, gchar const *new_value, bool is_interactive,
116         gpointer data);
119 static Geom::Point connector_drag_origin_w(0, 0);
120 static bool connector_within_tolerance = false;
121 static SPEventContextClass *parent_class;
124 static Inkscape::XML::NodeEventVector shape_repr_events = {
125     NULL, /* child_added */
126     NULL, /* child_added */
127     shape_event_attr_changed,
128     NULL, /* content_changed */
129     NULL  /* order_changed */
130 };
132 static Inkscape::XML::NodeEventVector layer_repr_events = {
133     NULL, /* child_added */
134     shape_event_attr_deleted,
135     NULL, /* child_added */
136     NULL, /* content_changed */
137     NULL  /* order_changed */
138 };
141 GType
142 sp_connector_context_get_type(void)
144     static GType type = 0;
145     if (!type) {
146         GTypeInfo info = {
147             sizeof(SPConnectorContextClass),
148             NULL, NULL,
149             (GClassInitFunc) sp_connector_context_class_init,
150             NULL, NULL,
151             sizeof(SPConnectorContext),
152             4,
153             (GInstanceInitFunc) sp_connector_context_init,
154             NULL,   /* value_table */
155         };
156         type = g_type_register_static(SP_TYPE_EVENT_CONTEXT, "SPConnectorContext", &info, (GTypeFlags)0);
157     }
158     return type;
161 static void
162 sp_connector_context_class_init(SPConnectorContextClass *klass)
164     GObjectClass *object_class;
165     SPEventContextClass *event_context_class;
167     object_class = (GObjectClass *) klass;
168     event_context_class = (SPEventContextClass *) klass;
170     parent_class = (SPEventContextClass*)g_type_class_peek_parent(klass);
172     object_class->dispose = sp_connector_context_dispose;
174     event_context_class->setup = sp_connector_context_setup;
175     event_context_class->finish = sp_connector_context_finish;
176     event_context_class->root_handler = sp_connector_context_root_handler;
177     event_context_class->item_handler = sp_connector_context_item_handler;
181 static void
182 sp_connector_context_init(SPConnectorContext *cc)
184     SPEventContext *ec = SP_EVENT_CONTEXT(cc);
186     ec->cursor_shape = cursor_connector_xpm;
187     ec->hot_x = 1;
188     ec->hot_y = 1;
189     ec->xp = 0;
190     ec->yp = 0;
192     cc->red_color = 0xff00007f;
194     cc->newconn = NULL;
195     cc->newConnRef = NULL;
197     cc->sel_changed_connection = sigc::connection();
199     cc->active_shape = NULL;
200     cc->active_shape_repr = NULL;
201     cc->active_shape_layer_repr = NULL;
203     cc->active_conn = NULL;
204     cc->active_conn_repr = NULL;
206     cc->active_handle = NULL;
208     cc->clickeditem = NULL;
209     cc->clickedhandle = NULL;
211     cc->connpthandle = NULL;
212     for (int i = 0; i < 2; ++i) {
213         cc->endpt_handle[i] = NULL;
214         cc->endpt_handler_id[i] = 0;
215     }
216     cc->sid = NULL;
217     cc->eid = NULL;
218     cc->npoints = 0;
219     cc->state = SP_CONNECTOR_CONTEXT_IDLE;
223 static void
224 sp_connector_context_dispose(GObject *object)
226     SPConnectorContext *cc = SP_CONNECTOR_CONTEXT(object);
228     cc->sel_changed_connection.disconnect();
230     if (cc->connpthandle) {
231         g_object_unref(cc->connpthandle);
232         cc->connpthandle = NULL;
233     }
234     for (int i = 0; i < 2; ++i) {
235         if (cc->endpt_handle[1]) {
236             g_object_unref(cc->endpt_handle[i]);
237             cc->endpt_handle[i] = NULL;
238         }
239     }
240     if (cc->sid) {
241         g_free(cc->sid);
242         cc->sid = NULL;
243     }
244     if (cc->eid) {
245         g_free(cc->eid);
246         cc->eid = NULL;
247     }
248     g_assert( cc->newConnRef == NULL );
250     G_OBJECT_CLASS(parent_class)->dispose(object);
254 static void
255 sp_connector_context_setup(SPEventContext *ec)
257     SPConnectorContext *cc = SP_CONNECTOR_CONTEXT(ec);
258     SPDesktop *dt = ec->desktop;
260     if (((SPEventContextClass *) parent_class)->setup) {
261         ((SPEventContextClass *) parent_class)->setup(ec);
262     }
264     cc->selection = sp_desktop_selection(dt);
266     cc->sel_changed_connection.disconnect();
267     cc->sel_changed_connection = cc->selection->connectChanged(
268             sigc::bind(sigc::ptr_fun(&cc_selection_changed),
269             (gpointer) cc));
271     /* Create red bpath */
272     cc->red_bpath = sp_canvas_bpath_new(sp_desktop_sketch(ec->desktop), NULL);
273     sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(cc->red_bpath), cc->red_color,
274             1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
275     sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(cc->red_bpath), 0x00000000,
276             SP_WIND_RULE_NONZERO);
277     /* Create red curve */
278     cc->red_curve = new SPCurve();
280     /* Create green curve */
281     cc->green_curve = new SPCurve();
283     // Notice the initial selection.
284     cc_selection_changed(cc->selection, (gpointer) cc);
286     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
287     if (prefs->getBool("/tools/connector/selcue", 0)) {
288         ec->enableSelectionCue();
289     }
291     // Make sure we see all enter events for canvas items,
292     // even if a mouse button is depressed.
293     dt->canvas->gen_all_enter_events = true;
297 static void
298 sp_connector_context_finish(SPEventContext *ec)
300     SPConnectorContext *cc = SP_CONNECTOR_CONTEXT(ec);
302     spcc_connector_finish(cc);
304     if (((SPEventContextClass *) parent_class)->finish) {
305         ((SPEventContextClass *) parent_class)->finish(ec);
306     }
308     if (cc->selection) {
309         cc->selection = NULL;
310     }
311     cc_clear_active_shape(cc);
312     cc_clear_active_conn(cc);
314     // Restore the default event generating behaviour.
315     SPDesktop *desktop = SP_EVENT_CONTEXT_DESKTOP(ec);
316     desktop->canvas->gen_all_enter_events = false;
320 //-----------------------------------------------------------------------------
323 static void
324 cc_clear_active_shape(SPConnectorContext *cc)
326     if (cc->active_shape == NULL) {
327         return;
328     }
329     g_assert( cc->active_shape_repr );
330     g_assert( cc->active_shape_layer_repr );
332     cc->active_shape = NULL;
334     if (cc->active_shape_repr) {
335         sp_repr_remove_listener_by_data(cc->active_shape_repr, cc);
336         Inkscape::GC::release(cc->active_shape_repr);
337         cc->active_shape_repr = NULL;
339         sp_repr_remove_listener_by_data(cc->active_shape_layer_repr, cc);
340         Inkscape::GC::release(cc->active_shape_layer_repr);
341         cc->active_shape_layer_repr = NULL;
342     }
344     // Hide the center connection point if it exists.
345     if (cc->connpthandle) {
346         sp_knot_hide(cc->connpthandle);
347     }
351 static void
352 cc_clear_active_conn(SPConnectorContext *cc)
354     if (cc->active_conn == NULL) {
355         return;
356     }
357     g_assert( cc->active_conn_repr );
359     cc->active_conn = NULL;
361     if (cc->active_conn_repr) {
362         sp_repr_remove_listener_by_data(cc->active_conn_repr, cc);
363         Inkscape::GC::release(cc->active_conn_repr);
364         cc->active_conn_repr = NULL;
365     }
367     // Hide the endpoint handles.
368     for (int i = 0; i < 2; ++i) {
369         if (cc->endpt_handle[i]) {
370             sp_knot_hide(cc->endpt_handle[i]);
371         }
372     }
376 static gchar *
377 conn_pt_handle_test(SPConnectorContext *cc, Geom::Point& p)
379     // TODO: this will need to change when there are more connection
380     //       points available for each shape.
382     SPKnot *centerpt = cc->connpthandle;
383     if (cc->active_handle && (cc->active_handle == centerpt))
384     {
385         p = centerpt->pos;
386         return g_strdup_printf("#%s", SP_OBJECT_ID(cc->active_shape));
387     }
388     return NULL;
393 static gint
394 sp_connector_context_item_handler(SPEventContext *event_context, SPItem *item, GdkEvent *event)
396     gint ret = FALSE;
398     SPDesktop *desktop = event_context->desktop;
400     SPConnectorContext *cc = SP_CONNECTOR_CONTEXT(event_context);
402     Geom::Point p(event->button.x, event->button.y);
404     switch (event->type) {
405         case GDK_BUTTON_RELEASE:
406             if (event->button.button == 1 && !event_context->space_panning) {
407                 if ((cc->state == SP_CONNECTOR_CONTEXT_DRAGGING) &&
408                         (connector_within_tolerance))
409                 {
410                     spcc_reset_colors(cc);
411                     cc->state = SP_CONNECTOR_CONTEXT_IDLE;
412                 }
413                 if (cc->state != SP_CONNECTOR_CONTEXT_IDLE) {
414                     // Doing simething else like rerouting.
415                     break;
416                 }
417                 // find out clicked item, disregarding groups, honoring Alt
418                 SPItem *item_ungrouped = sp_event_context_find_item(desktop,
419                         p, event->button.state & GDK_MOD1_MASK, TRUE);
421                 if (event->button.state & GDK_SHIFT_MASK) {
422                     cc->selection->toggle(item_ungrouped);
423                 } else {
424                     cc->selection->set(item_ungrouped);
425                 }
426                 ret = TRUE;
427             }
428             break;
429         case GDK_ENTER_NOTIFY:
430         {
431             if (cc_item_is_shape(item)) {
432                 // This is a shape, so show connection point(s).
433                 if (!(cc->active_shape) ||
434                         // Don't show handle for another handle.
435                         (item != ((SPItem *) cc->connpthandle))) {
436                     cc_set_active_shape(cc, item);
437                 }
438             }
439             ret = TRUE;
440             break;
441         }
442         default:
443             break;
444     }
446     return ret;
450 gint
451 sp_connector_context_root_handler(SPEventContext *ec, GdkEvent *event)
453     SPConnectorContext *const cc = SP_CONNECTOR_CONTEXT(ec);
455     gint ret = FALSE;
457     switch (event->type) {
458         case GDK_BUTTON_PRESS:
459             ret = connector_handle_button_press(cc, event->button);
460             break;
462         case GDK_MOTION_NOTIFY:
463             ret = connector_handle_motion_notify(cc, event->motion);
464             break;
466         case GDK_BUTTON_RELEASE:
467             ret = connector_handle_button_release(cc, event->button);
468             break;
469         case GDK_KEY_PRESS:
470             ret = connector_handle_key_press(cc, get_group0_keyval (&event->key));
471             break;
473         default:
474             break;
475     }
477     if (!ret) {
478         gint (*const parent_root_handler)(SPEventContext *, GdkEvent *)
479             = ((SPEventContextClass *) parent_class)->root_handler;
480         if (parent_root_handler) {
481             ret = parent_root_handler(ec, event);
482         }
483     }
485     return ret;
489 static gint
490 connector_handle_button_press(SPConnectorContext *const cc, GdkEventButton const &bevent)
492     Geom::Point const event_w(bevent.x, bevent.y);
493     /* Find desktop coordinates */
494     Geom::Point p = cc->desktop->w2d(event_w);
495     SPEventContext *event_context = SP_EVENT_CONTEXT(cc);
497     gint ret = FALSE;
498     if ( bevent.button == 1 && !event_context->space_panning ) {
500         SPDesktop *desktop = SP_EVENT_CONTEXT_DESKTOP(cc);
502         if (Inkscape::have_viable_layer(desktop, cc->_message_context) == false) {
503             return TRUE;
504         }
506         Geom::Point const event_w(bevent.x,
507                                 bevent.y);
508         connector_drag_origin_w = event_w;
509         connector_within_tolerance = true;
511         Geom::Point const event_dt = cc->desktop->w2d(event_w);
512         switch (cc->state) {
513             case SP_CONNECTOR_CONTEXT_STOP:
514                 /* This is allowed, if we just cancelled curve */
515             case SP_CONNECTOR_CONTEXT_IDLE:
516             {
517                 if ( cc->npoints == 0 ) {
518                     cc_clear_active_conn(cc);
520                     SP_EVENT_CONTEXT_DESKTOP(cc)->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Creating new connector"));
522                     /* Set start anchor */
523                     /* Create green anchor */
524                     Geom::Point p = event_dt;
526                     // Test whether we clicked on a connection point
527                     cc->sid = conn_pt_handle_test(cc, p);
528                     
529                     Geom::Point pt2g = to_2geom(p);
531                     if (!cc->sid) {
532                         // This is the first point, so just snap it to the grid
533                         // as there's no other points to go off.
534                         SnapManager &m = cc->desktop->namedview->snap_manager;
535                         m.setup(cc->desktop);
536                         m.freeSnapReturnByRef(Inkscape::SnapPreferences::SNAPPOINT_NODE, pt2g);
537                     }
538                     spcc_connector_set_initial_point(cc, from_2geom(pt2g));
540                 }
541                 cc->state = SP_CONNECTOR_CONTEXT_DRAGGING;
542                 ret = TRUE;
543                 break;
544             }
545             case SP_CONNECTOR_CONTEXT_DRAGGING:
546             {
547                 // This is the second click of a connector creation.
549                 spcc_connector_set_subsequent_point(cc, p);
550                 spcc_connector_finish_segment(cc, p);
551                 // Test whether we clicked on a connection point
552                 cc->eid = conn_pt_handle_test(cc, p);
553                 if (cc->npoints != 0) {
554                     spcc_connector_finish(cc);
555                 }
556                 cc_set_active_conn(cc, cc->newconn);
557                 cc->state = SP_CONNECTOR_CONTEXT_IDLE;
558                 ret = TRUE;
559                 break;
560             }
561             case SP_CONNECTOR_CONTEXT_CLOSE:
562             {
563                 g_warning("Button down in CLOSE state");
564                 break;
565             }
566             default:
567                 break;
568         }
569     } else if (bevent.button == 3) {
570         if (cc->state == SP_CONNECTOR_CONTEXT_REROUTING) {
571             // A context menu is going to be triggered here, 
572             // so end the rerouting operation.
573             cc_connector_rerouting_finish(cc, &p);
574                 
575             cc->state = SP_CONNECTOR_CONTEXT_IDLE;
576             
577             // Don't set ret to TRUE, so we drop through to the
578             // parent handler which will open the context menu.
579         }
580         else if (cc->npoints != 0) {
581             spcc_connector_finish(cc);
582             ret = TRUE;
583         }
584     }
585     return ret;
589 static gint
590 connector_handle_motion_notify(SPConnectorContext *const cc, GdkEventMotion const &mevent)
592     gint ret = FALSE;
593     SPEventContext *event_context = SP_EVENT_CONTEXT(cc);
594     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
596     if (event_context->space_panning || mevent.state & GDK_BUTTON2_MASK || mevent.state & GDK_BUTTON3_MASK) {
597         // allow middle-button scrolling
598         return FALSE;
599     }
601     Geom::Point const event_w(mevent.x, mevent.y);
603     if (connector_within_tolerance) {
604         gint const tolerance = prefs->getIntLimited("/options/dragtolerance/value", 0, 0, 100);
605         if ( NR::LInfty( event_w - connector_drag_origin_w ) < tolerance ) {
606             return FALSE;   // Do not drag if we're within tolerance from origin.
607         }
608     }
609     // Once the user has moved farther than tolerance from the original location
610     // (indicating they intend to move the object, not click), then always process
611     // the motion notify coordinates as given (no snapping back to origin)
612     connector_within_tolerance = false;
614     SPDesktop *const dt = cc->desktop;
616     /* Find desktop coordinates */
617     Geom::Point p = dt->w2d(event_w);
619     switch (cc->state) {
620         case SP_CONNECTOR_CONTEXT_DRAGGING:
621         {
622             // This is movement during a connector creation.
624             if ( cc->npoints > 0 ) {
625                 cc->selection->clear();
626                 spcc_connector_set_subsequent_point(cc, p);
627                 ret = TRUE;
628             }
629             break;
630         }
631         case SP_CONNECTOR_CONTEXT_REROUTING:
632         {
633             g_assert( SP_IS_PATH(cc->clickeditem));
635             // Update the hidden path
636             Geom::Matrix i2d = sp_item_i2d_affine(cc->clickeditem);
637             Geom::Matrix d2i = i2d.inverse();
638             SPPath *path = SP_PATH(cc->clickeditem);
639             SPCurve *curve = (SP_SHAPE(path))->curve;
640             if (cc->clickedhandle == cc->endpt_handle[0]) {
641                 Geom::Point o = cc->endpt_handle[1]->pos;
642                 curve->stretch_endpoints(p * d2i, o * d2i);
643             }
644             else {
645                 Geom::Point o = cc->endpt_handle[0]->pos;
646                 curve->stretch_endpoints(o * d2i, p * d2i);
647             }
648             sp_conn_adjust_path(path);
650             // Copy this to the temporary visible path
651             cc->red_curve = SP_SHAPE(path)->curve->copy();
652             cc->red_curve->transform(i2d);
654             sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(cc->red_bpath), cc->red_curve);
655             ret = TRUE;
656             break;
657         }
658         case SP_CONNECTOR_CONTEXT_STOP:
659             /* This is perfectly valid */
660             break;
661         default:
662             break;
663     }
665     return ret;
669 static gint
670 connector_handle_button_release(SPConnectorContext *const cc, GdkEventButton const &revent)
672     gint ret = FALSE;
673     SPEventContext *event_context = SP_EVENT_CONTEXT(cc);
674     if ( revent.button == 1 && !event_context->space_panning ) {
676         SPDesktop *desktop = SP_EVENT_CONTEXT_DESKTOP(cc);
677         SPDocument *doc = sp_desktop_document(desktop);
679         Geom::Point const event_w(revent.x, revent.y);
681         /* Find desktop coordinates */
682         Geom::Point p = cc->desktop->w2d(event_w);
684         switch (cc->state) {
685             //case SP_CONNECTOR_CONTEXT_POINT:
686             case SP_CONNECTOR_CONTEXT_DRAGGING:
687             {
688                 if (connector_within_tolerance)
689                 {
690                     spcc_connector_finish_segment(cc, p);
691                     return TRUE;
692                 }
693                 // Connector has been created via a drag, end it now.
694                 spcc_connector_set_subsequent_point(cc, p);
695                 spcc_connector_finish_segment(cc, p);
696                 // Test whether we clicked on a connection point
697                 cc->eid = conn_pt_handle_test(cc, p);
698                 if (cc->npoints != 0) {
699                     spcc_connector_finish(cc);
700                 }
701                 cc_set_active_conn(cc, cc->newconn);
702                 cc->state = SP_CONNECTOR_CONTEXT_IDLE;
703                 break;
704             }
705             case SP_CONNECTOR_CONTEXT_REROUTING:
706             {
707                 cc_connector_rerouting_finish(cc, &p);
708                 
709                 sp_document_ensure_up_to_date(doc);
710                 cc->state = SP_CONNECTOR_CONTEXT_IDLE;
711                 return TRUE;
712                 break;
713             }
714             case SP_CONNECTOR_CONTEXT_STOP:
715                 /* This is allowed, if we just cancelled curve */
716                 break;
717             default:
718                 break;
719         }
720         ret = TRUE;
721     }
723     return ret;
727 static gint
728 connector_handle_key_press(SPConnectorContext *const cc, guint const keyval)
730     gint ret = FALSE;
731     /* fixme: */
732     switch (keyval) {
733         case GDK_Return:
734         case GDK_KP_Enter:
735             if (cc->npoints != 0) {
736                 spcc_connector_finish(cc);
737                 ret = TRUE;
738             }
739             break;
740         case GDK_Escape:
741             if (cc->state == SP_CONNECTOR_CONTEXT_REROUTING) {
742                 
743                 SPDesktop *desktop = SP_EVENT_CONTEXT_DESKTOP(cc);
744                 SPDocument *doc = sp_desktop_document(desktop);
746                 cc_connector_rerouting_finish(cc, NULL);
747                 
748                 sp_document_undo(doc);
749                 
750                 cc->state = SP_CONNECTOR_CONTEXT_IDLE;
751                 desktop->messageStack()->flash( Inkscape::NORMAL_MESSAGE,
752                         _("Connector endpoint drag cancelled."));
753                 ret = TRUE;
754             }
755             else if (cc->npoints != 0) {
756                 // if drawing, cancel, otherwise pass it up for deselecting
757                 cc->state = SP_CONNECTOR_CONTEXT_STOP;
758                 spcc_reset_colors(cc);
759                 ret = TRUE;
760             }
761             break;
762         default:
763             break;
764     }
765     return ret;
769 static void
770 cc_connector_rerouting_finish(SPConnectorContext *const cc, Geom::Point *const p)
772     SPDesktop *desktop = SP_EVENT_CONTEXT_DESKTOP(cc);
773     SPDocument *doc = sp_desktop_document(desktop);
774     
775     // Clear the temporary path:
776     cc->red_curve->reset();
777     sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(cc->red_bpath), NULL);
779     if (p != NULL)
780     {
781         // Test whether we clicked on a connection point
782         gchar *shape_label = conn_pt_handle_test(cc, *p);
784         if (shape_label) {
785             if (cc->clickedhandle == cc->endpt_handle[0]) {
786                 sp_object_setAttribute(cc->clickeditem,
787                         "inkscape:connection-start",shape_label, false);
788             }
789             else {
790                 sp_object_setAttribute(cc->clickeditem,
791                         "inkscape:connection-end",shape_label, false);
792             }
793             g_free(shape_label);
794         }
795     }
796     cc->clickeditem->setHidden(false);
797     sp_conn_adjust_path(SP_PATH(cc->clickeditem));
798     cc->clickeditem->updateRepr();
799     sp_document_done(doc, SP_VERB_CONTEXT_CONNECTOR, 
800                      _("Reroute connector"));
801     cc_set_active_conn(cc, cc->clickeditem);
805 static void
806 spcc_reset_colors(SPConnectorContext *cc)
808     /* Red */
809     cc->red_curve->reset();
810     sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(cc->red_bpath), NULL);
812     cc->green_curve->reset();
813     cc->npoints = 0;
817 static void
818 spcc_connector_set_initial_point(SPConnectorContext *const cc, Geom::Point const p)
820     g_assert( cc->npoints == 0 );
822     cc->p[0] = p;
823     cc->p[1] = p;
824     cc->npoints = 2;
825     sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(cc->red_bpath), NULL);
829 static void
830 spcc_connector_set_subsequent_point(SPConnectorContext *const cc, Geom::Point const p)
832     g_assert( cc->npoints != 0 );
834     SPDesktop *dt = cc->desktop;
835     Geom::Point o = dt->dt2doc(cc->p[0]);
836     Geom::Point d = dt->dt2doc(p);
837     Avoid::Point src(o[Geom::X], o[Geom::Y]);
838     Avoid::Point dst(d[Geom::X], d[Geom::Y]);
840     if (!cc->newConnRef) {
841         Avoid::Router *router = sp_desktop_document(dt)->router;
842         cc->newConnRef = new Avoid::ConnRef(router, 0, src, dst);
843         cc->newConnRef->updateEndPoint(Avoid::VertID::src, src);
844     }
845     cc->newConnRef->updateEndPoint(Avoid::VertID::tar, dst);
847     cc->newConnRef->makePathInvalid();
848     cc->newConnRef->generatePath(src, dst);
850     Avoid::PolyLine route = cc->newConnRef->route();
851     cc->newConnRef->calcRouteDist();
853     cc->red_curve->reset();
854     Geom::Point pt(route.ps[0].x, route.ps[0].y);
855     cc->red_curve->moveto(pt);
857     for (int i = 1; i < route.pn; ++i) {
858         Geom::Point p(route.ps[i].x, route.ps[i].y);
859         cc->red_curve->lineto(p);
860     }
861     cc->red_curve->transform(dt->doc2dt());
862     sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(cc->red_bpath), cc->red_curve);
866 /**
867  * Concats red, blue and green.
868  * If any anchors are defined, process these, optionally removing curves from white list
869  * Invoke _flush_white to write result back to object.
870  */
871 static void
872 spcc_concat_colors_and_flush(SPConnectorContext *cc)
874     SPCurve *c = cc->green_curve;
875     cc->green_curve = new SPCurve();
877     cc->red_curve->reset();
878     sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(cc->red_bpath), NULL);
880     if (c->is_empty()) {
881         c->unref();
882         return;
883     }
885     spcc_flush_white(cc, c);
887     c->unref();
891 /*
892  * Flushes white curve(s) and additional curve into object
893  *
894  * No cleaning of colored curves - this has to be done by caller
895  * No rereading of white data, so if you cannot rely on ::modified, do it in caller
896  *
897  */
899 static void
900 spcc_flush_white(SPConnectorContext *cc, SPCurve *gc)
902     SPCurve *c;
904     if (gc) {
905         c = gc;
906         c->ref();
907     } else {
908         return;
909     }
911     /* Now we have to go back to item coordinates at last */
912     c->transform(sp_desktop_dt2root_affine(SP_EVENT_CONTEXT_DESKTOP(cc)));
914     SPDesktop *desktop = SP_EVENT_CONTEXT_DESKTOP(cc);
915     SPDocument *doc = sp_desktop_document(desktop);
916     Inkscape::XML::Document *xml_doc = sp_document_repr_doc(doc);
918     if ( c && !c->is_empty() ) {
919         /* We actually have something to write */
921         Inkscape::XML::Node *repr = xml_doc->createElement("svg:path");
922         /* Set style */
923         sp_desktop_apply_style_tool(desktop, repr, "/tools/connector", false);
925         gchar *str = sp_svg_write_path( c->get_pathvector() );
926         g_assert( str != NULL );
927         repr->setAttribute("d", str);
928         g_free(str);
930         /* Attach repr */
931         cc->newconn = SP_ITEM(desktop->currentLayer()->appendChildRepr(repr));
932         cc->selection->set(repr);
933         Inkscape::GC::release(repr);
934         cc->newconn->transform = i2i_affine(desktop->currentRoot(), desktop->currentLayer());
935         cc->newconn->updateRepr();
937         bool connection = false;
938         sp_object_setAttribute(cc->newconn, "inkscape:connector-type",
939                 "polyline", false);
940         if (cc->sid)
941         {
942             sp_object_setAttribute(cc->newconn, "inkscape:connection-start",
943                     cc->sid, false);
944             connection = true;
945         }
947         if (cc->eid)
948         {
949             sp_object_setAttribute(cc->newconn, "inkscape:connection-end",
950                     cc->eid, false);
951             connection = true;
952         }
953         cc->newconn->updateRepr();
954         if (connection) {
955             // Adjust endpoints to shape edge.
956             sp_conn_adjust_path(SP_PATH(cc->newconn));
957         }
958         cc->newconn->updateRepr();
959     }
961     c->unref();
963     /* Flush pending updates */
964     sp_document_done(doc, SP_VERB_CONTEXT_CONNECTOR, _("Create connector"));
965     sp_document_ensure_up_to_date(doc);
969 static void
970 spcc_connector_finish_segment(SPConnectorContext *const cc, Geom::Point const /*p*/)
972     if (!cc->red_curve->is_empty()) {
973         cc->green_curve->append_continuous(cc->red_curve, 0.0625);
975         cc->p[0] = cc->p[3];
976         cc->p[1] = cc->p[4];
977         cc->npoints = 2;
979         cc->red_curve->reset();
980     }
984 static void
985 spcc_connector_finish(SPConnectorContext *const cc)
987     SPDesktop *const desktop = cc->desktop;
988     desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Finishing connector"));
990     cc->red_curve->reset();
991     spcc_concat_colors_and_flush(cc);
993     cc->npoints = 0;
995     if (cc->newConnRef) {
996         cc->newConnRef->removeFromGraph();
997         delete cc->newConnRef;
998         cc->newConnRef = NULL;
999     }
1000     cc->state = SP_CONNECTOR_CONTEXT_IDLE;
1004 static gboolean
1005 cc_generic_knot_handler(SPCanvasItem *, GdkEvent *event, SPKnot *knot)
1007     g_assert (knot != NULL);
1008     
1009     g_object_ref(knot);
1011     SPConnectorContext *cc = SP_CONNECTOR_CONTEXT(
1012             knot->desktop->event_context);
1014     gboolean consumed = FALSE;
1016     switch (event->type) {
1017         case GDK_ENTER_NOTIFY:
1018             sp_knot_set_flag(knot, SP_KNOT_MOUSEOVER, TRUE);
1019             
1020             cc->active_handle = knot;
1022             if (knot->tip)
1023             {
1024                 knot->desktop->event_context->defaultMessageContext()->set(
1025                         Inkscape::NORMAL_MESSAGE, knot->tip);
1026             }
1027             
1028             consumed = TRUE;
1029             break;
1030         case GDK_LEAVE_NOTIFY:
1031             sp_knot_set_flag(knot, SP_KNOT_MOUSEOVER, FALSE);
1033             cc->active_handle = NULL;
1034             
1035             if (knot->tip) {
1036                 knot->desktop->event_context->defaultMessageContext()->clear();
1037             }
1038             
1039             consumed = TRUE;
1040             break;
1041         default:
1042             break;
1043     }
1044     
1045     g_object_unref(knot);
1047     return consumed;
1051 static gboolean
1052 endpt_handler(SPKnot */*knot*/, GdkEvent *event, SPConnectorContext *cc)
1054     g_assert( SP_IS_CONNECTOR_CONTEXT(cc) );
1056     gboolean consumed = FALSE;
1058     switch (event->type) {
1059         case GDK_BUTTON_PRESS:
1060             g_assert( (cc->active_handle == cc->endpt_handle[0]) ||
1061                       (cc->active_handle == cc->endpt_handle[1]) );
1062             if (cc->state == SP_CONNECTOR_CONTEXT_IDLE) {
1063                 cc->clickeditem = cc->active_conn;
1064                 cc->clickedhandle = cc->active_handle;
1065                 cc_clear_active_conn(cc);
1066                 cc->state = SP_CONNECTOR_CONTEXT_REROUTING;
1068                 // Disconnect from attached shape
1069                 unsigned ind = (cc->active_handle == cc->endpt_handle[0]) ? 0 : 1;
1070                 sp_conn_end_detach(cc->clickeditem, ind);
1072                 Geom::Point origin;
1073                 if (cc->clickedhandle == cc->endpt_handle[0]) {
1074                     origin = cc->endpt_handle[1]->pos;
1075                 }
1076                 else {
1077                     origin = cc->endpt_handle[0]->pos;
1078                 }
1080                 // Show the red path for dragging.
1081                 cc->red_curve = SP_PATH(cc->clickeditem)->curve->copy();
1082                 Geom::Matrix i2d = sp_item_i2d_affine(cc->clickeditem);
1083                 cc->red_curve->transform(i2d);
1084                 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(cc->red_bpath), cc->red_curve);
1086                 cc->clickeditem->setHidden(true);
1088                 // The rest of the interaction rerouting the connector is
1089                 // handled by the context root handler.
1090                 consumed = TRUE;
1091             }
1092             break;
1093         default:
1094             break;
1095     }
1097     return consumed;
1101 static void cc_set_active_shape(SPConnectorContext *cc, SPItem *item)
1103     g_assert(item != NULL );
1105     cc->active_shape = item;
1107     // Remove existing active shape listeners
1108     if (cc->active_shape_repr) {
1109         sp_repr_remove_listener_by_data(cc->active_shape_repr, cc);
1110         Inkscape::GC::release(cc->active_shape_repr);
1112         sp_repr_remove_listener_by_data(cc->active_shape_layer_repr, cc);
1113         Inkscape::GC::release(cc->active_shape_layer_repr);
1114     }
1116     // Listen in case the active shape changes
1117     cc->active_shape_repr = SP_OBJECT_REPR(item);
1118     if (cc->active_shape_repr) {
1119         Inkscape::GC::anchor(cc->active_shape_repr);
1120         sp_repr_add_listener(cc->active_shape_repr, &shape_repr_events, cc);
1122         cc->active_shape_layer_repr = cc->active_shape_repr->parent();
1123         Inkscape::GC::anchor(cc->active_shape_layer_repr);
1124         sp_repr_add_listener(cc->active_shape_layer_repr, &layer_repr_events, cc);
1125     }
1128     // Set center connection point.
1129     if ( cc->connpthandle == NULL ) {
1130         SPKnot *knot = sp_knot_new(cc->desktop, 
1131                 _("<b>Connection point</b>: click or drag to create a new connector"));
1133         knot->setShape(SP_KNOT_SHAPE_SQUARE);
1134         knot->setSize(8);
1135         knot->setAnchor(GTK_ANCHOR_CENTER);
1136         knot->setFill(0xffffff00, 0xff0000ff, 0xff0000ff);
1137         sp_knot_update_ctrl(knot);
1139         // We don't want to use the standard knot handler,
1140         //since we don't want this knot to be draggable.
1141         g_signal_handler_disconnect(G_OBJECT(knot->item),
1142                 knot->_event_handler_id);
1143         knot->_event_handler_id = 0;
1145         gtk_signal_connect(GTK_OBJECT(knot->item), "event",
1146                 GTK_SIGNAL_FUNC(cc_generic_knot_handler), knot);
1148         cc->connpthandle = knot;
1149     }
1152     boost::optional<Geom::Rect> bbox = sp_item_bbox_desktop(cc->active_shape);
1153     if (bbox) {
1154         Geom::Point center = bbox->midpoint();
1155         sp_knot_set_position(cc->connpthandle, center, 0);
1156         sp_knot_show(cc->connpthandle);
1157     } else {
1158         sp_knot_hide(cc->connpthandle);
1159     }
1163 static void
1164 cc_set_active_conn(SPConnectorContext *cc, SPItem *item)
1166     g_assert( SP_IS_PATH(item) );
1168     SPCurve *curve = SP_SHAPE(SP_PATH(item))->curve;
1169     Geom::Matrix i2d = sp_item_i2d_affine(item);
1171     if (cc->active_conn == item)
1172     {
1173         // Just adjust handle positions.
1174         Geom::Point startpt = *(curve->first_point()) * i2d;
1175         sp_knot_set_position(cc->endpt_handle[0], startpt, 0);
1177         Geom::Point endpt = *(curve->last_point()) * i2d;
1178         sp_knot_set_position(cc->endpt_handle[1], endpt, 0);
1180         return;
1181     }
1183     cc->active_conn = item;
1185     // Remove existing active conn listeners
1186     if (cc->active_conn_repr) {
1187         sp_repr_remove_listener_by_data(cc->active_conn_repr, cc);
1188         Inkscape::GC::release(cc->active_conn_repr);
1189         cc->active_conn_repr = NULL;
1190     }
1192     // Listen in case the active conn changes
1193     cc->active_conn_repr = SP_OBJECT_REPR(item);
1194     if (cc->active_conn_repr) {
1195         Inkscape::GC::anchor(cc->active_conn_repr);
1196         sp_repr_add_listener(cc->active_conn_repr, &shape_repr_events, cc);
1197     }
1199     for (int i = 0; i < 2; ++i) {
1201         // Create the handle if it doesn't exist
1202         if ( cc->endpt_handle[i] == NULL ) {
1203             SPKnot *knot = sp_knot_new(cc->desktop, 
1204                     _("<b>Connector endpoint</b>: drag to reroute or connect to new shapes"));
1206             knot->setShape(SP_KNOT_SHAPE_SQUARE);
1207             knot->setSize(7);
1208             knot->setAnchor(GTK_ANCHOR_CENTER);
1209             knot->setFill(0xffffff00, 0xff0000ff, 0xff0000ff);
1210             knot->setStroke(0x000000ff, 0x000000ff, 0x000000ff);
1211             sp_knot_update_ctrl(knot);
1213             // We don't want to use the standard knot handler,
1214             //since we don't want this knot to be draggable.
1215             g_signal_handler_disconnect(G_OBJECT(knot->item),
1216                     knot->_event_handler_id);
1217             knot->_event_handler_id = 0;
1219             gtk_signal_connect(GTK_OBJECT(knot->item), "event",
1220                     GTK_SIGNAL_FUNC(cc_generic_knot_handler), knot);
1222             cc->endpt_handle[i] = knot;
1223         }
1225         // Remove any existing handlers
1226         if (cc->endpt_handler_id[i]) {
1227             g_signal_handlers_disconnect_by_func(
1228                     G_OBJECT(cc->endpt_handle[i]->item),
1229                     (void*)G_CALLBACK(endpt_handler), (gpointer) cc );
1230             cc->endpt_handler_id[i] = 0;
1231         }
1233         // Setup handlers for connector endpoints, this is
1234         // is as 'after' so that cc_generic_knot_handler is
1235         // triggered first for any endpoint.
1236         cc->endpt_handler_id[i] = g_signal_connect_after(
1237                 G_OBJECT(cc->endpt_handle[i]->item), "event",
1238                 G_CALLBACK(endpt_handler), cc);
1239     }
1241     Geom::Point startpt = *(curve->first_point()) * i2d;
1242     sp_knot_set_position(cc->endpt_handle[0], startpt, 0);
1244     Geom::Point endpt = *(curve->last_point()) * i2d;
1245     sp_knot_set_position(cc->endpt_handle[1], endpt, 0);
1247     sp_knot_show(cc->endpt_handle[0]);
1248     sp_knot_show(cc->endpt_handle[1]);
1252 static bool cc_item_is_shape(SPItem *item)
1254     if (SP_IS_PATH(item)) {
1255         SPCurve *curve = (SP_SHAPE(item))->curve;
1256         if ( curve && !(curve->is_closed()) ) {
1257             // Open paths are connectors.
1258             return false;
1259         }
1260     }
1261     else if (SP_IS_TEXT(item) || SP_IS_FLOWTEXT(item)) {
1262         Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1263         if (prefs->getBool("/tools/connector/ignoretext", true)) {
1264             // Don't count text as a shape we can connect connector to.
1265             return false;
1266         }
1267     }
1268     return true;
1272 bool cc_item_is_connector(SPItem *item)
1274     if (SP_IS_PATH(item)) {
1275         if (SP_PATH(item)->connEndPair.isAutoRoutingConn()) {
1276             g_assert( !(SP_SHAPE(item)->curve->is_closed()) );
1277             return true;
1278         }
1279     }
1280     return false;
1284 void cc_selection_set_avoid(bool const set_avoid)
1286     SPDesktop *desktop = inkscape_active_desktop();
1287     if (desktop == NULL) {
1288         return;
1289     }
1291     SPDocument *document = sp_desktop_document(desktop);
1293     Inkscape::Selection *selection = sp_desktop_selection(desktop);
1295     GSList *l = (GSList *) selection->itemList();
1297     int changes = 0;
1299     while (l) {
1300         SPItem *item = (SPItem *) l->data;
1302         char const *value = (set_avoid) ? "true" : NULL;
1304         if (cc_item_is_shape(item)) {
1305             sp_object_setAttribute(item, "inkscape:connector-avoid",
1306                     value, false);
1307             item->avoidRef->handleSettingChange();
1308             changes++;
1309         }
1311         l = l->next;
1312     }
1314     if (changes == 0) {
1315         desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE,
1316                 _("Select <b>at least one non-connector object</b>."));
1317         return;
1318     }
1320     char *event_desc = (set_avoid) ?
1321             _("Make connectors avoid selected objects") :
1322             _("Make connectors ignore selected objects");
1323     sp_document_done(document, SP_VERB_CONTEXT_CONNECTOR, event_desc);
1327 static void
1328 cc_selection_changed(Inkscape::Selection *selection, gpointer data)
1330     SPConnectorContext *cc = SP_CONNECTOR_CONTEXT(data);
1331     //SPEventContext *ec = SP_EVENT_CONTEXT(cc);
1333     SPItem *item = selection->singleItem();
1335     if (cc->active_conn == item)
1336     {
1337         // Nothing to change.
1338         return;
1339     }
1340     if (item == NULL)
1341     {
1342         cc_clear_active_conn(cc);
1343         return;
1344     }
1346     if (cc_item_is_connector(item)) {
1347         cc_set_active_conn(cc, item);
1348     }
1352 static void
1353 shape_event_attr_deleted(Inkscape::XML::Node */*repr*/, Inkscape::XML::Node *child,
1354                          Inkscape::XML::Node */*ref*/, gpointer data)
1356     g_assert(data);
1357     SPConnectorContext *cc = SP_CONNECTOR_CONTEXT(data);
1359     if (child == cc->active_shape_repr) {
1360         // The active shape has been deleted.  Clear active shape.
1361         cc_clear_active_shape(cc);
1362     }
1366 static void
1367 shape_event_attr_changed(Inkscape::XML::Node *repr, gchar const *name,
1368                          gchar const */*old_value*/, gchar const */*new_value*/,
1369                          bool /*is_interactive*/, gpointer data)
1371     g_assert(data);
1372     SPConnectorContext *cc = SP_CONNECTOR_CONTEXT(data);
1374     // Look for changes than result in onscreen movement.
1375     if (!strcmp(name, "d") || !strcmp(name, "x") || !strcmp(name, "y") ||
1376             !strcmp(name, "width") || !strcmp(name, "height") ||
1377             !strcmp(name, "transform"))
1378     {
1379         if (repr == cc->active_shape_repr) {
1380             // Active shape has moved. Clear active shape.
1381             cc_clear_active_shape(cc);
1382         }
1383         else if (repr == cc->active_conn_repr) {
1384             // The active conn has been moved.
1385             // Set it again, which just sets new handle positions.
1386             cc_set_active_conn(cc, cc->active_conn);
1387         }
1388     }
1392 /*
1393   Local Variables:
1394   mode:c++
1395   c-file-style:"stroustrup"
1396   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1397   indent-tabs-mode:nil
1398   fill-column:99
1399   End:
1400 */
1401 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :