Code

Added test script I thought was already added.
[inkscape.git] / src / lpe-tool-context.cpp
1 /*
2  * LPEToolContext: a context for a generic tool composed of subtools that are given by LPEs
3  *
4  * Authors:
5  *   Maximilian Albert <maximilian.albert@gmail.com>
6  *   Lauris Kaplinski <lauris@kaplinski.com>
7  *
8  * Copyright (C) 1998 The Free Software Foundation
9  * Copyright (C) 1999-2005 authors
10  * Copyright (C) 2001-2002 Ximian, Inc.
11  * Copyright (C) 2008 Maximilian Albert
12  *
13  * Released under GNU GPL, read the file 'COPYING' for more information
14  */
16 #ifdef HAVE_CONFIG_H
17 #include "config.h"
18 #endif
20 #include <2geom/sbasis-geometric.h>
21 #include <gdk/gdkkeysyms.h>
23 #include "macros.h"
24 #include "forward.h"
25 #include "pixmaps/cursor-node.xpm"
26 #include "pixmaps/cursor-crosshairs.xpm"
27 #include <gtk/gtk.h>
28 #include "desktop.h"
29 #include "message-context.h"
30 #include "preferences.h"
31 #include "shape-editor.h"
32 #include "selection.h"
33 #include "desktop-handles.h"
34 #include "document.h"
35 #include "display/curve.h"
36 #include "display/canvas-bpath.h"
37 #include "display/canvas-text.h"
38 #include "message-stack.h"
39 #include "sp-path.h"
40 #include "helper/units.h"
42 #include "lpe-tool-context.h"
44 static void sp_lpetool_context_class_init(SPLPEToolContextClass *klass);
45 static void sp_lpetool_context_init(SPLPEToolContext *erc);
46 static void sp_lpetool_context_dispose(GObject *object);
48 static void sp_lpetool_context_setup(SPEventContext *ec);
49 static void sp_lpetool_context_set(SPEventContext *ec, Inkscape::Preferences::Entry *);
50 static gint sp_lpetool_context_item_handler(SPEventContext *ec, SPItem *item, GdkEvent *event);
51 static gint sp_lpetool_context_root_handler(SPEventContext *ec, GdkEvent *event);
53 void sp_lpetool_context_selection_changed(Inkscape::Selection *selection, gpointer data);
55 const int num_subtools = 8;
57 SubtoolEntry lpesubtools[] = {
58     // this must be here to account for the "all inactive" action
59     {Inkscape::LivePathEffect::INVALID_LPE, "draw-geometry-inactive"},
60     {Inkscape::LivePathEffect::LINE_SEGMENT, "draw-geometry-line-segment"},
61     {Inkscape::LivePathEffect::CIRCLE_3PTS, "draw-geometry-circle-from-three-points"},
62     {Inkscape::LivePathEffect::CIRCLE_WITH_RADIUS, "draw-geometry-circle-from-radius"},
63     {Inkscape::LivePathEffect::PARALLEL, "draw-geometry-line-parallel"},
64     {Inkscape::LivePathEffect::PERP_BISECTOR, "draw-geometry-line-perpendicular"},
65     {Inkscape::LivePathEffect::ANGLE_BISECTOR, "draw-geometry-angle-bisector"},
66     {Inkscape::LivePathEffect::MIRROR_SYMMETRY, "draw-geometry-mirror"}
67 };
69 static SPPenContextClass *lpetool_parent_class = 0;
71 GType sp_lpetool_context_get_type(void)
72 {
73     static GType type = 0;
74     if (!type) {
75         GTypeInfo info = {
76             sizeof(SPLPEToolContextClass),
77             0, // base_init
78             0, // base_finalize
79             (GClassInitFunc)sp_lpetool_context_class_init,
80             0, // class_finalize
81             0, // class_data
82             sizeof(SPLPEToolContext),
83             0, // n_preallocs
84             (GInstanceInitFunc)sp_lpetool_context_init,
85             0 // value_table
86         };
87         type = g_type_register_static(SP_TYPE_PEN_CONTEXT, "SPLPEToolContext", &info, static_cast<GTypeFlags>(0));
88     }
89     return type;
90 }
92 static void
93 sp_lpetool_context_class_init(SPLPEToolContextClass *klass)
94 {
95     GObjectClass *object_class = (GObjectClass *) klass;
96     SPEventContextClass *event_context_class = (SPEventContextClass *) klass;
98     lpetool_parent_class = (SPPenContextClass*)g_type_class_peek_parent(klass);
100     object_class->dispose = sp_lpetool_context_dispose;
102     event_context_class->setup = sp_lpetool_context_setup;
103     event_context_class->set = sp_lpetool_context_set;
104     event_context_class->root_handler = sp_lpetool_context_root_handler;
105     event_context_class->item_handler = sp_lpetool_context_item_handler;
108 static void
109 sp_lpetool_context_init(SPLPEToolContext *lc)
111     lc->cursor_shape = cursor_crosshairs_xpm;
112     lc->hot_x = 7;
113     lc->hot_y = 7;
115     lc->canvas_bbox = NULL;
116     lc->measuring_items = new std::map<SPPath *, SPCanvasItem*>;
118     new (&lc->sel_changed_connection) sigc::connection();
121 static void
122 sp_lpetool_context_dispose(GObject *object)
124     SPLPEToolContext *lc = SP_LPETOOL_CONTEXT(object);
125     delete lc->shape_editor;
127     if (lc->canvas_bbox) {
128         gtk_object_destroy(GTK_OBJECT(lc->canvas_bbox));
129         lc->canvas_bbox = NULL;
130     }
132     lpetool_delete_measuring_items(lc);
133     delete lc->measuring_items;
134     lc->measuring_items = NULL;
136     lc->sel_changed_connection.disconnect();
137     lc->sel_changed_connection.~connection();
139     if (lc->_lpetool_message_context) {
140         delete lc->_lpetool_message_context;
141     }
143     G_OBJECT_CLASS(lpetool_parent_class)->dispose(object);
146 static void
147 sp_lpetool_context_setup(SPEventContext *ec)
149     SPLPEToolContext *lc = SP_LPETOOL_CONTEXT(ec);
151     if (((SPEventContextClass *) lpetool_parent_class)->setup)
152         ((SPEventContextClass *) lpetool_parent_class)->setup(ec);
154     Inkscape::Selection *selection = sp_desktop_selection (ec->desktop);
155     SPItem *item = selection->singleItem();
157     lc->sel_changed_connection.disconnect();
158     lc->sel_changed_connection =
159         selection->connectChanged(sigc::bind(sigc::ptr_fun(&sp_lpetool_context_selection_changed), (gpointer)lc));
161     lc->shape_editor = new ShapeEditor(ec->desktop);
163     lpetool_context_switch_mode(lc, Inkscape::LivePathEffect::INVALID_LPE);
164     lpetool_context_reset_limiting_bbox(lc);
165     lpetool_create_measuring_items(lc);
167 // TODO temp force:
168     ec->enableSelectionCue();
169     
170     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
172     if (item) {
173         lc->shape_editor->set_item(item, SH_NODEPATH);
174         lc->shape_editor->set_item(item, SH_KNOTHOLDER);
175     }
177     if (prefs->getBool("/tools/lpetool/selcue")) {
178         ec->enableSelectionCue();
179     }
181     lc->_lpetool_message_context = new Inkscape::MessageContext((ec->desktop)->messageStack());
184     lc->shape_editor->update_statusbar();
187 /**
188 \brief  Callback that processes the "changed" signal on the selection;
189 destroys old and creates new nodepath and reassigns listeners to the new selected item's repr
190 */
191 void
192 sp_lpetool_context_selection_changed(Inkscape::Selection *selection, gpointer data)
194     SPLPEToolContext *lc = SP_LPETOOL_CONTEXT(data);
196     // TODO: update ShapeEditorsCollective instead
197     lc->shape_editor->unset_item(SH_NODEPATH);
198     lc->shape_editor->unset_item(SH_KNOTHOLDER);
199     SPItem *item = selection->singleItem();
200     lc->shape_editor->set_item(item, SH_NODEPATH);
201     lc->shape_editor->set_item(item, SH_KNOTHOLDER);
202     lc->shape_editor->update_statusbar();
205 static void
206 sp_lpetool_context_set(SPEventContext *ec, Inkscape::Preferences::Entry *val)
208     if (val->getEntryName() == "mode") {
209         Inkscape::Preferences::get()->setString("/tools/geometric/mode", "drag");
210         SP_PEN_CONTEXT(ec)->mode = SP_PEN_CONTEXT_MODE_DRAG;
211     }
213     /*
214     //pass on up to parent class to handle common attributes.
215     if ( lpetool_parent_class->set ) {
216         lpetool_parent_class->set(ec, key, val);
217     }
218     */
221 static gint 
222 sp_lpetool_context_item_handler(SPEventContext *ec, SPItem *item, GdkEvent *event)
224     gint ret = FALSE;
226     switch (event->type) {
227         case GDK_BUTTON_PRESS:
228         {
229             // select the clicked item but do nothing else
230             Inkscape::Selection * const selection = sp_desktop_selection(ec->desktop);
231             selection->clear();
232             selection->add(item);
233             ret = TRUE;
234             break;
235         }
236         case GDK_BUTTON_RELEASE:
237             // TODO: do we need to catch this or can we pass it on to the parent handler?
238             ret = TRUE;
239             break;
240         default:
241             break;
242     }
244     if (!ret) {
245         if (((SPEventContextClass *) lpetool_parent_class)->item_handler)
246             ret = ((SPEventContextClass *) lpetool_parent_class)->item_handler(ec, item, event);
247     }
249     return ret;
252 gint
253 sp_lpetool_context_root_handler(SPEventContext *event_context, GdkEvent *event)
255     SPLPEToolContext *lc = SP_LPETOOL_CONTEXT(event_context);
256     SPDesktop *desktop = event_context->desktop;
257     Inkscape::Selection *selection = sp_desktop_selection (desktop);
259     bool ret = false;
261     if (sp_pen_context_has_waiting_LPE(lc)) {
262         // quit when we are waiting for a LPE to be applied
263         ret = ((SPEventContextClass *) lpetool_parent_class)->root_handler(event_context, event);
264         return ret;
265     }
267     switch (event->type) {
268         case GDK_BUTTON_PRESS:
269             if (event->button.button == 1 && !event_context->space_panning) {
270                 if (lc->mode == Inkscape::LivePathEffect::INVALID_LPE) {
271                     // don't do anything for now if we are inactive (except clearing the selection
272                     // since this was a click into empty space)
273                     selection->clear();
274                     desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Choose a construction tool from the toolbar."));
275                     ret = true;
276                     break;
277                 }
279                 // save drag origin
280                 event_context->xp = (gint) event->button.x;
281                 event_context->yp = (gint) event->button.y;
282                 event_context->within_tolerance = true;
283                 lc->shape_editor->cancel_hit();
285                 using namespace Inkscape::LivePathEffect;
287                 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
288                 int mode = prefs->getInt("/tools/lpetool/mode");
289                 EffectType type = lpesubtools[mode].type;
291                 //bool over_stroke = lc->shape_editor->is_over_stroke(Geom::Point(event->button.x, event->button.y), true);
293                 sp_pen_context_wait_for_LPE_mouse_clicks(lc, type, Inkscape::LivePathEffect::Effect::acceptsNumClicks(type));
295                 // we pass the mouse click on to pen tool as the first click which it should collect
296                 ret = ((SPEventContextClass *) lpetool_parent_class)->root_handler(event_context, event);
297             }
298             break;
299         case GDK_MOTION_NOTIFY:
300         {
301             if (!lc->shape_editor->has_nodepath() || selection->singleItem() == NULL) {
302                 break;
303             }
305             bool over_stroke = false;
306             over_stroke = lc->shape_editor->is_over_stroke(Geom::Point(event->motion.x, event->motion.y), false);
308             if (over_stroke) {
309                 event_context->cursor_shape = cursor_node_xpm;
310                 event_context->hot_x = 1;
311                 event_context->hot_y = 1;
312                 sp_event_context_update_cursor(event_context);
313             } else {
314                 lc->cursor_shape = cursor_crosshairs_xpm;
315                 lc->hot_x = 7;
316                 lc->hot_y = 7;
317                 sp_event_context_update_cursor(event_context);
318             }
319         }
320         break;
323     case GDK_BUTTON_RELEASE:
324     {
325         /**
326         break;
327         **/
328     }
330     case GDK_KEY_PRESS:
331         /**
332         switch (get_group0_keyval (&event->key)) {
333         }
334         break;
335         **/
337     case GDK_KEY_RELEASE:
338         /**
339         switch (get_group0_keyval(&event->key)) {
340             case GDK_Control_L:
341             case GDK_Control_R:
342                 dc->_message_context->clear();
343                 break;
344             default:
345                 break;
346         }
347         **/
349     default:
350         break;
351     }
353     if (!ret) {
354         if (((SPEventContextClass *) lpetool_parent_class)->root_handler) {
355             ret = ((SPEventContextClass *) lpetool_parent_class)->root_handler(event_context, event);
356         }
357     }
359     return ret;
362 /*
363  * Finds the index in the list of geometric subtools corresponding to the given LPE type.
364  * Returns -1 if no subtool is found.
365  */
366 int
367 lpetool_mode_to_index(Inkscape::LivePathEffect::EffectType const type) {
368     for (int i = 0; i < num_subtools; ++i) {
369         if (lpesubtools[i].type == type) {
370             return i;
371         }
372     }
373     return -1;
376 /*
377  * Checks whether an item has a construction applied as LPE and if so returns the index in
378  * lpesubtools of this construction
379  */
380 int lpetool_item_has_construction(SPLPEToolContext */*lc*/, SPItem *item)
382     if (!SP_IS_LPE_ITEM(item)) {
383         return -1;
384     }
386     Inkscape::LivePathEffect::Effect* lpe = sp_lpe_item_get_current_lpe(SP_LPE_ITEM(item));
387     if (!lpe) {
388         return -1;
389     }
390     return lpetool_mode_to_index(lpe->effectType());
393 /*
394  * Attempts to perform the construction of the given type (i.e., to apply the corresponding LPE) to
395  * a single selected item. Returns whether we succeeded.
396  */
397 bool
398 lpetool_try_construction(SPLPEToolContext *lc, Inkscape::LivePathEffect::EffectType const type)
400     Inkscape::Selection *selection = sp_desktop_selection(lc->desktop);
401     SPItem *item = selection->singleItem();
403     // TODO: should we check whether type represents a valid geometric construction?
404     if (item && SP_IS_LPE_ITEM(item) && Inkscape::LivePathEffect::Effect::acceptsNumClicks(type) == 0) {
405         Inkscape::LivePathEffect::Effect::createAndApply(type, sp_desktop_document(lc->desktop), item);
406         return true;
407     }
408     return false;
411 void
412 lpetool_context_switch_mode(SPLPEToolContext *lc, Inkscape::LivePathEffect::EffectType const type)
414     int index = lpetool_mode_to_index(type);
415     if (index != -1) {
416         lc->mode = type;
417         lc->desktop->setToolboxSelectOneValue ("lpetool_mode_action", index);
418     } else {
419         g_warning ("Invalid mode selected: %d", type);
420         return;
421     }
424 void
425 lpetool_get_limiting_bbox_corners(SPDocument *document, Geom::Point &A, Geom::Point &B) {
426     Geom::Coord w = sp_document_width(document);
427     Geom::Coord h = sp_document_height(document);
428     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
430     double ulx = prefs->getDouble("/tools/lpetool/bbox_upperleftx", 0);
431     double uly = prefs->getDouble("/tools/lpetool/bbox_upperlefty", 0);
432     double lrx = prefs->getDouble("/tools/lpetool/bbox_lowerrightx", w);
433     double lry = prefs->getDouble("/tools/lpetool/bbox_lowerrighty", h);
435     A = Geom::Point(ulx, uly);
436     B = Geom::Point(lrx, lry);
439 /*
440  * Reads the limiting bounding box from preferences and draws it on the screen
441  */
442 // TODO: Note that currently the bbox is not user-settable; we simply use the page borders
443 void
444 lpetool_context_reset_limiting_bbox(SPLPEToolContext *lc)
446     if (lc->canvas_bbox) {
447         gtk_object_destroy(GTK_OBJECT(lc->canvas_bbox));
448         lc->canvas_bbox = NULL;
449     }
451     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
452     if (!prefs->getBool("/tools/lpetool/show_bbox", true))
453         return;
455     SPDocument *document = sp_desktop_document(lc->desktop);
457     Geom::Point A, B;
458     lpetool_get_limiting_bbox_corners(document, A, B);
459     Geom::Matrix doc2dt(lc->desktop->doc2dt());
460     A *= doc2dt;
461     B *= doc2dt;
463     Geom::Rect rect(A, B);
464     SPCurve *curve = SPCurve::new_from_rect(rect);
466     lc->canvas_bbox = sp_canvas_bpath_new (sp_desktop_controls(lc->desktop), curve);
467     sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(lc->canvas_bbox), 0x0000ffff, 0.8, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT, 5, 5);
470 static void
471 set_pos_and_anchor(SPCanvasText *canvas_text, const Geom::Piecewise<Geom::D2<Geom::SBasis> > &pwd2,
472                    const double t, const double length, bool /*use_curvature*/ = false)
474     using namespace Geom;
476     Piecewise<D2<SBasis> > pwd2_reparam = arc_length_parametrization(pwd2, 2 , 0.1);
477     double t_reparam = pwd2_reparam.cuts.back() * t;
478     Point pos = pwd2_reparam.valueAt(t_reparam);
479     Point dir = unit_vector(derivative(pwd2_reparam).valueAt(t_reparam));
480     Point n = -rot90(dir);
481     double angle = Geom::angle_between(dir, Point(1,0));
483     sp_canvastext_set_coords(canvas_text, pos + n * length);
484     sp_canvastext_set_anchor(canvas_text, std::sin(angle), -std::cos(angle));
487 void
488 lpetool_create_measuring_items(SPLPEToolContext *lc, Inkscape::Selection *selection)
490     if (!selection) {
491         selection = sp_desktop_selection(lc->desktop);
492     }
493     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
494     bool show = prefs->getBool("/tools/lpetool/show_measuring_info",  true);
496     SPPath *path;
497     SPCurve *curve;
498     SPCanvasText *canvas_text;
499     SPCanvasGroup *tmpgrp = sp_desktop_tempgroup(lc->desktop);
500     gchar *arc_length;
501     double lengthval;
503     for (GSList const *i = selection->itemList(); i != NULL; i = i->next) {
504         if (SP_IS_PATH(i->data)) {
505             path = SP_PATH(i->data);
506             curve = sp_shape_get_curve(SP_SHAPE(path));
507             Geom::Piecewise<Geom::D2<Geom::SBasis> > pwd2 = paths_to_pw(curve->get_pathvector());
508             canvas_text = (SPCanvasText *) sp_canvastext_new(tmpgrp, lc->desktop, Geom::Point(0,0), "");
509             if (!show)
510                 sp_canvas_item_hide(SP_CANVAS_ITEM(canvas_text));
512             SPUnitId unitid = static_cast<SPUnitId>(prefs->getInt("/tools/lpetool/unitid", SP_UNIT_PX));
513             SPUnit unit = sp_unit_get_by_id(unitid);
515             lengthval = Geom::length(pwd2);
516             gboolean success;
517             success = sp_convert_distance(&lengthval, &sp_unit_get_by_id(SP_UNIT_PX), &unit);
518             arc_length = g_strdup_printf("%.2f %s", lengthval, success ? sp_unit_get_abbreviation(&unit) : "px");
519             sp_canvastext_set_text (canvas_text, arc_length);
520             set_pos_and_anchor(canvas_text, pwd2, 0.5, 10);
521             // TODO: must we free arc_length?
522             (*lc->measuring_items)[path] = SP_CANVAS_ITEM(canvas_text);
523         }
524     }
527 void
528 lpetool_delete_measuring_items(SPLPEToolContext *lc)
530     std::map<SPPath *, SPCanvasItem*>::iterator i;
531     for (i = lc->measuring_items->begin(); i != lc->measuring_items->end(); ++i) {
532         gtk_object_destroy(GTK_OBJECT(i->second));
533     }
534     lc->measuring_items->clear();
537 void
538 lpetool_update_measuring_items(SPLPEToolContext *lc)
540     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
541     SPPath *path;
542     SPCurve *curve;
543     double lengthval;
544     gchar *arc_length;
545     std::map<SPPath *, SPCanvasItem*>::iterator i;
546     for (i = lc->measuring_items->begin(); i != lc->measuring_items->end(); ++i) {
547         path = i->first;
548         curve = sp_shape_get_curve(SP_SHAPE(path));
549         Geom::Piecewise<Geom::D2<Geom::SBasis> > pwd2 = Geom::paths_to_pw(curve->get_pathvector());
550         SPUnitId unitid = static_cast<SPUnitId>(prefs->getInt("/tools/lpetool/unitid", SP_UNIT_PX));
551         SPUnit unit = sp_unit_get_by_id(unitid);
552         lengthval = Geom::length(pwd2);
553         gboolean success;
554         success = sp_convert_distance(&lengthval, &sp_unit_get_by_id(SP_UNIT_PX), &unit);
555         arc_length = g_strdup_printf("%.2f %s", lengthval, success ? sp_unit_get_abbreviation(&unit) : "px");
556         sp_canvastext_set_text (SP_CANVASTEXT(i->second), arc_length);
557         set_pos_and_anchor(SP_CANVASTEXT(i->second), pwd2, 0.5, 10);
558         // TODO: must we free arc_length?
559     }
562 void
563 lpetool_show_measuring_info(SPLPEToolContext *lc, bool show)
565     std::map<SPPath *, SPCanvasItem*>::iterator i;
566     for (i = lc->measuring_items->begin(); i != lc->measuring_items->end(); ++i) {
567         if (show) {
568             sp_canvas_item_show(i->second);
569         } else {
570             sp_canvas_item_hide(i->second);
571         }
572     }
575 /*
576   Local Variables:
577   mode:c++
578   c-file-style:"stroustrup"
579   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
580   indent-tabs-mode:nil
581   fill-column:99
582   End:
583 */
584 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :