Code

Merge and cleanup of GSoC C++-ification project.
[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  *   Abhishek Sharma
8  *
9  * Copyright (C) 1998 The Free Software Foundation
10  * Copyright (C) 1999-2005 authors
11  * Copyright (C) 2001-2002 Ximian, Inc.
12  * Copyright (C) 2008 Maximilian Albert
13  *
14  * Released under GNU GPL, read the file 'COPYING' for more information
15  */
17 #ifdef HAVE_CONFIG_H
18 #include "config.h"
19 #endif
21 #include <2geom/sbasis-geometric.h>
22 #include <gdk/gdkkeysyms.h>
24 #include "macros.h"
25 #include "forward.h"
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 /**
185 \brief  Callback that processes the "changed" signal on the selection;
186 destroys old and creates new nodepath and reassigns listeners to the new selected item's repr
187 */
188 void
189 sp_lpetool_context_selection_changed(Inkscape::Selection *selection, gpointer data)
191     SPLPEToolContext *lc = SP_LPETOOL_CONTEXT(data);
193     lc->shape_editor->unset_item(SH_KNOTHOLDER);
194     SPItem *item = selection->singleItem();
195     lc->shape_editor->set_item(item, SH_KNOTHOLDER);
198 static void
199 sp_lpetool_context_set(SPEventContext *ec, Inkscape::Preferences::Entry *val)
201     if (val->getEntryName() == "mode") {
202         Inkscape::Preferences::get()->setString("/tools/geometric/mode", "drag");
203         SP_PEN_CONTEXT(ec)->mode = SP_PEN_CONTEXT_MODE_DRAG;
204     }
206     /*
207     //pass on up to parent class to handle common attributes.
208     if ( lpetool_parent_class->set ) {
209         lpetool_parent_class->set(ec, key, val);
210     }
211     */
214 static gint 
215 sp_lpetool_context_item_handler(SPEventContext *ec, SPItem *item, GdkEvent *event)
217     gint ret = FALSE;
219     switch (event->type) {
220         case GDK_BUTTON_PRESS:
221         {
222             // select the clicked item but do nothing else
223             Inkscape::Selection * const selection = sp_desktop_selection(ec->desktop);
224             selection->clear();
225             selection->add(item);
226             ret = TRUE;
227             break;
228         }
229         case GDK_BUTTON_RELEASE:
230             // TODO: do we need to catch this or can we pass it on to the parent handler?
231             ret = TRUE;
232             break;
233         default:
234             break;
235     }
237     if (!ret) {
238         if (((SPEventContextClass *) lpetool_parent_class)->item_handler)
239             ret = ((SPEventContextClass *) lpetool_parent_class)->item_handler(ec, item, event);
240     }
242     return ret;
245 gint
246 sp_lpetool_context_root_handler(SPEventContext *event_context, GdkEvent *event)
248     SPLPEToolContext *lc = SP_LPETOOL_CONTEXT(event_context);
249     SPDesktop *desktop = event_context->desktop;
250     Inkscape::Selection *selection = sp_desktop_selection (desktop);
252     bool ret = false;
254     if (sp_pen_context_has_waiting_LPE(lc)) {
255         // quit when we are waiting for a LPE to be applied
256         ret = ((SPEventContextClass *) lpetool_parent_class)->root_handler(event_context, event);
257         return ret;
258     }
260     switch (event->type) {
261         case GDK_BUTTON_PRESS:
262             if (event->button.button == 1 && !event_context->space_panning) {
263                 if (lc->mode == Inkscape::LivePathEffect::INVALID_LPE) {
264                     // don't do anything for now if we are inactive (except clearing the selection
265                     // since this was a click into empty space)
266                     selection->clear();
267                     desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Choose a construction tool from the toolbar."));
268                     ret = true;
269                     break;
270                 }
272                 // save drag origin
273                 event_context->xp = (gint) event->button.x;
274                 event_context->yp = (gint) event->button.y;
275                 event_context->within_tolerance = true;
277                 using namespace Inkscape::LivePathEffect;
279                 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
280                 int mode = prefs->getInt("/tools/lpetool/mode");
281                 EffectType type = lpesubtools[mode].type;
283                 //bool over_stroke = lc->shape_editor->is_over_stroke(Geom::Point(event->button.x, event->button.y), true);
285                 sp_pen_context_wait_for_LPE_mouse_clicks(lc, type, Inkscape::LivePathEffect::Effect::acceptsNumClicks(type));
287                 // we pass the mouse click on to pen tool as the first click which it should collect
288                 ret = ((SPEventContextClass *) lpetool_parent_class)->root_handler(event_context, event);
289             }
290             break;
293     case GDK_BUTTON_RELEASE:
294     {
295         /**
296         break;
297         **/
298     }
300     case GDK_KEY_PRESS:
301         /**
302         switch (get_group0_keyval (&event->key)) {
303         }
304         break;
305         **/
307     case GDK_KEY_RELEASE:
308         /**
309         switch (get_group0_keyval(&event->key)) {
310             case GDK_Control_L:
311             case GDK_Control_R:
312                 dc->_message_context->clear();
313                 break;
314             default:
315                 break;
316         }
317         **/
319     default:
320         break;
321     }
323     if (!ret) {
324         if (((SPEventContextClass *) lpetool_parent_class)->root_handler) {
325             ret = ((SPEventContextClass *) lpetool_parent_class)->root_handler(event_context, event);
326         }
327     }
329     return ret;
332 /*
333  * Finds the index in the list of geometric subtools corresponding to the given LPE type.
334  * Returns -1 if no subtool is found.
335  */
336 int
337 lpetool_mode_to_index(Inkscape::LivePathEffect::EffectType const type) {
338     for (int i = 0; i < num_subtools; ++i) {
339         if (lpesubtools[i].type == type) {
340             return i;
341         }
342     }
343     return -1;
346 /*
347  * Checks whether an item has a construction applied as LPE and if so returns the index in
348  * lpesubtools of this construction
349  */
350 int lpetool_item_has_construction(SPLPEToolContext */*lc*/, SPItem *item)
352     if (!SP_IS_LPE_ITEM(item)) {
353         return -1;
354     }
356     Inkscape::LivePathEffect::Effect* lpe = sp_lpe_item_get_current_lpe(SP_LPE_ITEM(item));
357     if (!lpe) {
358         return -1;
359     }
360     return lpetool_mode_to_index(lpe->effectType());
363 /*
364  * Attempts to perform the construction of the given type (i.e., to apply the corresponding LPE) to
365  * a single selected item. Returns whether we succeeded.
366  */
367 bool
368 lpetool_try_construction(SPLPEToolContext *lc, Inkscape::LivePathEffect::EffectType const type)
370     Inkscape::Selection *selection = sp_desktop_selection(lc->desktop);
371     SPItem *item = selection->singleItem();
373     // TODO: should we check whether type represents a valid geometric construction?
374     if (item && SP_IS_LPE_ITEM(item) && Inkscape::LivePathEffect::Effect::acceptsNumClicks(type) == 0) {
375         Inkscape::LivePathEffect::Effect::createAndApply(type, sp_desktop_document(lc->desktop), item);
376         return true;
377     }
378     return false;
381 void
382 lpetool_context_switch_mode(SPLPEToolContext *lc, Inkscape::LivePathEffect::EffectType const type)
384     int index = lpetool_mode_to_index(type);
385     if (index != -1) {
386         lc->mode = type;
387         lc->desktop->setToolboxSelectOneValue ("lpetool_mode_action", index);
388     } else {
389         g_warning ("Invalid mode selected: %d", type);
390         return;
391     }
394 void
395 lpetool_get_limiting_bbox_corners(SPDocument *document, Geom::Point &A, Geom::Point &B) {
396     Geom::Coord w = document->getWidth();
397     Geom::Coord h = document->getHeight();
398     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
400     double ulx = prefs->getDouble("/tools/lpetool/bbox_upperleftx", 0);
401     double uly = prefs->getDouble("/tools/lpetool/bbox_upperlefty", 0);
402     double lrx = prefs->getDouble("/tools/lpetool/bbox_lowerrightx", w);
403     double lry = prefs->getDouble("/tools/lpetool/bbox_lowerrighty", h);
405     A = Geom::Point(ulx, uly);
406     B = Geom::Point(lrx, lry);
409 /*
410  * Reads the limiting bounding box from preferences and draws it on the screen
411  */
412 // TODO: Note that currently the bbox is not user-settable; we simply use the page borders
413 void
414 lpetool_context_reset_limiting_bbox(SPLPEToolContext *lc)
416     if (lc->canvas_bbox) {
417         gtk_object_destroy(GTK_OBJECT(lc->canvas_bbox));
418         lc->canvas_bbox = NULL;
419     }
421     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
422     if (!prefs->getBool("/tools/lpetool/show_bbox", true))
423         return;
425     SPDocument *document = sp_desktop_document(lc->desktop);
427     Geom::Point A, B;
428     lpetool_get_limiting_bbox_corners(document, A, B);
429     Geom::Matrix doc2dt(lc->desktop->doc2dt());
430     A *= doc2dt;
431     B *= doc2dt;
433     Geom::Rect rect(A, B);
434     SPCurve *curve = SPCurve::new_from_rect(rect);
436     lc->canvas_bbox = sp_canvas_bpath_new (sp_desktop_controls(lc->desktop), curve);
437     sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(lc->canvas_bbox), 0x0000ffff, 0.8, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT, 5, 5);
440 static void
441 set_pos_and_anchor(SPCanvasText *canvas_text, const Geom::Piecewise<Geom::D2<Geom::SBasis> > &pwd2,
442                    const double t, const double length, bool /*use_curvature*/ = false)
444     using namespace Geom;
446     Piecewise<D2<SBasis> > pwd2_reparam = arc_length_parametrization(pwd2, 2 , 0.1);
447     double t_reparam = pwd2_reparam.cuts.back() * t;
448     Point pos = pwd2_reparam.valueAt(t_reparam);
449     Point dir = unit_vector(derivative(pwd2_reparam).valueAt(t_reparam));
450     Point n = -rot90(dir);
451     double angle = Geom::angle_between(dir, Point(1,0));
453     sp_canvastext_set_coords(canvas_text, pos + n * length);
454     sp_canvastext_set_anchor(canvas_text, std::sin(angle), -std::cos(angle));
457 void
458 lpetool_create_measuring_items(SPLPEToolContext *lc, Inkscape::Selection *selection)
460     if (!selection) {
461         selection = sp_desktop_selection(lc->desktop);
462     }
463     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
464     bool show = prefs->getBool("/tools/lpetool/show_measuring_info",  true);
466     SPPath *path;
467     SPCurve *curve;
468     SPCanvasText *canvas_text;
469     SPCanvasGroup *tmpgrp = sp_desktop_tempgroup(lc->desktop);
470     gchar *arc_length;
471     double lengthval;
473     for (GSList const *i = selection->itemList(); i != NULL; i = i->next) {
474         if (SP_IS_PATH(i->data)) {
475             path = SP_PATH(i->data);
476             curve = SP_SHAPE(path)->getCurve();
477             Geom::Piecewise<Geom::D2<Geom::SBasis> > pwd2 = paths_to_pw(curve->get_pathvector());
478             canvas_text = (SPCanvasText *) sp_canvastext_new(tmpgrp, lc->desktop, Geom::Point(0,0), "");
479             if (!show)
480                 sp_canvas_item_hide(SP_CANVAS_ITEM(canvas_text));
482             SPUnitId unitid = static_cast<SPUnitId>(prefs->getInt("/tools/lpetool/unitid", SP_UNIT_PX));
483             SPUnit unit = sp_unit_get_by_id(unitid);
485             lengthval = Geom::length(pwd2);
486             gboolean success;
487             success = sp_convert_distance(&lengthval, &sp_unit_get_by_id(SP_UNIT_PX), &unit);
488             arc_length = g_strdup_printf("%.2f %s", lengthval, success ? sp_unit_get_abbreviation(&unit) : "px");
489             sp_canvastext_set_text (canvas_text, arc_length);
490             set_pos_and_anchor(canvas_text, pwd2, 0.5, 10);
491             // TODO: must we free arc_length?
492             (*lc->measuring_items)[path] = SP_CANVAS_ITEM(canvas_text);
493         }
494     }
497 void
498 lpetool_delete_measuring_items(SPLPEToolContext *lc)
500     std::map<SPPath *, SPCanvasItem*>::iterator i;
501     for (i = lc->measuring_items->begin(); i != lc->measuring_items->end(); ++i) {
502         gtk_object_destroy(GTK_OBJECT(i->second));
503     }
504     lc->measuring_items->clear();
507 void
508 lpetool_update_measuring_items(SPLPEToolContext *lc)
510     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
511     SPPath *path;
512     SPCurve *curve;
513     double lengthval;
514     gchar *arc_length;
515     std::map<SPPath *, SPCanvasItem*>::iterator i;
516     for (i = lc->measuring_items->begin(); i != lc->measuring_items->end(); ++i) {
517         path = i->first;
518         curve = SP_SHAPE(path)->getCurve();
519         Geom::Piecewise<Geom::D2<Geom::SBasis> > pwd2 = Geom::paths_to_pw(curve->get_pathvector());
520         SPUnitId unitid = static_cast<SPUnitId>(prefs->getInt("/tools/lpetool/unitid", SP_UNIT_PX));
521         SPUnit unit = sp_unit_get_by_id(unitid);
522         lengthval = Geom::length(pwd2);
523         gboolean success;
524         success = sp_convert_distance(&lengthval, &sp_unit_get_by_id(SP_UNIT_PX), &unit);
525         arc_length = g_strdup_printf("%.2f %s", lengthval, success ? sp_unit_get_abbreviation(&unit) : "px");
526         sp_canvastext_set_text (SP_CANVASTEXT(i->second), arc_length);
527         set_pos_and_anchor(SP_CANVASTEXT(i->second), pwd2, 0.5, 10);
528         // TODO: must we free arc_length?
529     }
532 void
533 lpetool_show_measuring_info(SPLPEToolContext *lc, bool show)
535     std::map<SPPath *, SPCanvasItem*>::iterator i;
536     for (i = lc->measuring_items->begin(); i != lc->measuring_items->end(); ++i) {
537         if (show) {
538             sp_canvas_item_show(i->second);
539         } else {
540             sp_canvas_item_hide(i->second);
541         }
542     }
545 /*
546   Local Variables:
547   mode:c++
548   c-file-style:"stroustrup"
549   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
550   indent-tabs-mode:nil
551   fill-column:99
552   End:
553 */
554 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 :