Code

A simple layout document as to what, why and how is cppification.
[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-crosshairs.xpm"
26 #include <gtk/gtk.h>
27 #include "desktop.h"
28 #include "message-context.h"
29 #include "preferences.h"
30 #include "shape-editor.h"
31 #include "selection.h"
32 #include "desktop-handles.h"
33 #include "document.h"
34 #include "display/curve.h"
35 #include "display/canvas-bpath.h"
36 #include "display/canvas-text.h"
37 #include "message-stack.h"
38 #include "sp-path.h"
39 #include "helper/units.h"
41 #include "lpe-tool-context.h"
43 static void sp_lpetool_context_class_init(SPLPEToolContextClass *klass);
44 static void sp_lpetool_context_init(SPLPEToolContext *erc);
45 static void sp_lpetool_context_dispose(GObject *object);
47 static void sp_lpetool_context_setup(SPEventContext *ec);
48 static void sp_lpetool_context_set(SPEventContext *ec, Inkscape::Preferences::Entry *);
49 static gint sp_lpetool_context_item_handler(SPEventContext *ec, SPItem *item, GdkEvent *event);
50 static gint sp_lpetool_context_root_handler(SPEventContext *ec, GdkEvent *event);
52 void sp_lpetool_context_selection_changed(Inkscape::Selection *selection, gpointer data);
54 const int num_subtools = 8;
56 SubtoolEntry lpesubtools[] = {
57     // this must be here to account for the "all inactive" action
58     {Inkscape::LivePathEffect::INVALID_LPE, "draw-geometry-inactive"},
59     {Inkscape::LivePathEffect::LINE_SEGMENT, "draw-geometry-line-segment"},
60     {Inkscape::LivePathEffect::CIRCLE_3PTS, "draw-geometry-circle-from-three-points"},
61     {Inkscape::LivePathEffect::CIRCLE_WITH_RADIUS, "draw-geometry-circle-from-radius"},
62     {Inkscape::LivePathEffect::PARALLEL, "draw-geometry-line-parallel"},
63     {Inkscape::LivePathEffect::PERP_BISECTOR, "draw-geometry-line-perpendicular"},
64     {Inkscape::LivePathEffect::ANGLE_BISECTOR, "draw-geometry-angle-bisector"},
65     {Inkscape::LivePathEffect::MIRROR_SYMMETRY, "draw-geometry-mirror"}
66 };
68 static SPPenContextClass *lpetool_parent_class = 0;
70 GType sp_lpetool_context_get_type(void)
71 {
72     static GType type = 0;
73     if (!type) {
74         GTypeInfo info = {
75             sizeof(SPLPEToolContextClass),
76             0, // base_init
77             0, // base_finalize
78             (GClassInitFunc)sp_lpetool_context_class_init,
79             0, // class_finalize
80             0, // class_data
81             sizeof(SPLPEToolContext),
82             0, // n_preallocs
83             (GInstanceInitFunc)sp_lpetool_context_init,
84             0 // value_table
85         };
86         type = g_type_register_static(SP_TYPE_PEN_CONTEXT, "SPLPEToolContext", &info, static_cast<GTypeFlags>(0));
87     }
88     return type;
89 }
91 static void
92 sp_lpetool_context_class_init(SPLPEToolContextClass *klass)
93 {
94     GObjectClass *object_class = (GObjectClass *) klass;
95     SPEventContextClass *event_context_class = (SPEventContextClass *) klass;
97     lpetool_parent_class = (SPPenContextClass*)g_type_class_peek_parent(klass);
99     object_class->dispose = sp_lpetool_context_dispose;
101     event_context_class->setup = sp_lpetool_context_setup;
102     event_context_class->set = sp_lpetool_context_set;
103     event_context_class->root_handler = sp_lpetool_context_root_handler;
104     event_context_class->item_handler = sp_lpetool_context_item_handler;
107 static void
108 sp_lpetool_context_init(SPLPEToolContext *lc)
110     lc->cursor_shape = cursor_crosshairs_xpm;
111     lc->hot_x = 7;
112     lc->hot_y = 7;
114     lc->canvas_bbox = NULL;
115     lc->measuring_items = new std::map<SPPath *, SPCanvasItem*>;
117     new (&lc->sel_changed_connection) sigc::connection();
120 static void
121 sp_lpetool_context_dispose(GObject *object)
123     SPLPEToolContext *lc = SP_LPETOOL_CONTEXT(object);
124     delete lc->shape_editor;
126     if (lc->canvas_bbox) {
127         gtk_object_destroy(GTK_OBJECT(lc->canvas_bbox));
128         lc->canvas_bbox = NULL;
129     }
131     lpetool_delete_measuring_items(lc);
132     delete lc->measuring_items;
133     lc->measuring_items = NULL;
135     lc->sel_changed_connection.disconnect();
136     lc->sel_changed_connection.~connection();
138     if (lc->_lpetool_message_context) {
139         delete lc->_lpetool_message_context;
140     }
142     G_OBJECT_CLASS(lpetool_parent_class)->dispose(object);
145 static void
146 sp_lpetool_context_setup(SPEventContext *ec)
148     SPLPEToolContext *lc = SP_LPETOOL_CONTEXT(ec);
150     if (((SPEventContextClass *) lpetool_parent_class)->setup)
151         ((SPEventContextClass *) lpetool_parent_class)->setup(ec);
153     Inkscape::Selection *selection = sp_desktop_selection (ec->desktop);
154     SPItem *item = selection->singleItem();
156     lc->sel_changed_connection.disconnect();
157     lc->sel_changed_connection =
158         selection->connectChanged(sigc::bind(sigc::ptr_fun(&sp_lpetool_context_selection_changed), (gpointer)lc));
160     lc->shape_editor = new ShapeEditor(ec->desktop);
162     lpetool_context_switch_mode(lc, Inkscape::LivePathEffect::INVALID_LPE);
163     lpetool_context_reset_limiting_bbox(lc);
164     lpetool_create_measuring_items(lc);
166 // TODO temp force:
167     ec->enableSelectionCue();
168     
169     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
171     if (item) {
172         lc->shape_editor->set_item(item, SH_NODEPATH);
173         lc->shape_editor->set_item(item, SH_KNOTHOLDER);
174     }
176     if (prefs->getBool("/tools/lpetool/selcue")) {
177         ec->enableSelectionCue();
178     }
180     lc->_lpetool_message_context = new Inkscape::MessageContext((ec->desktop)->messageStack());
183 /**
184 \brief  Callback that processes the "changed" signal on the selection;
185 destroys old and creates new nodepath and reassigns listeners to the new selected item's repr
186 */
187 void
188 sp_lpetool_context_selection_changed(Inkscape::Selection *selection, gpointer data)
190     SPLPEToolContext *lc = SP_LPETOOL_CONTEXT(data);
192     lc->shape_editor->unset_item(SH_KNOTHOLDER);
193     SPItem *item = selection->singleItem();
194     lc->shape_editor->set_item(item, SH_KNOTHOLDER);
197 static void
198 sp_lpetool_context_set(SPEventContext *ec, Inkscape::Preferences::Entry *val)
200     if (val->getEntryName() == "mode") {
201         Inkscape::Preferences::get()->setString("/tools/geometric/mode", "drag");
202         SP_PEN_CONTEXT(ec)->mode = SP_PEN_CONTEXT_MODE_DRAG;
203     }
205     /*
206     //pass on up to parent class to handle common attributes.
207     if ( lpetool_parent_class->set ) {
208         lpetool_parent_class->set(ec, key, val);
209     }
210     */
213 static gint 
214 sp_lpetool_context_item_handler(SPEventContext *ec, SPItem *item, GdkEvent *event)
216     gint ret = FALSE;
218     switch (event->type) {
219         case GDK_BUTTON_PRESS:
220         {
221             // select the clicked item but do nothing else
222             Inkscape::Selection * const selection = sp_desktop_selection(ec->desktop);
223             selection->clear();
224             selection->add(item);
225             ret = TRUE;
226             break;
227         }
228         case GDK_BUTTON_RELEASE:
229             // TODO: do we need to catch this or can we pass it on to the parent handler?
230             ret = TRUE;
231             break;
232         default:
233             break;
234     }
236     if (!ret) {
237         if (((SPEventContextClass *) lpetool_parent_class)->item_handler)
238             ret = ((SPEventContextClass *) lpetool_parent_class)->item_handler(ec, item, event);
239     }
241     return ret;
244 gint
245 sp_lpetool_context_root_handler(SPEventContext *event_context, GdkEvent *event)
247     SPLPEToolContext *lc = SP_LPETOOL_CONTEXT(event_context);
248     SPDesktop *desktop = event_context->desktop;
249     Inkscape::Selection *selection = sp_desktop_selection (desktop);
251     bool ret = false;
253     if (sp_pen_context_has_waiting_LPE(lc)) {
254         // quit when we are waiting for a LPE to be applied
255         ret = ((SPEventContextClass *) lpetool_parent_class)->root_handler(event_context, event);
256         return ret;
257     }
259     switch (event->type) {
260         case GDK_BUTTON_PRESS:
261             if (event->button.button == 1 && !event_context->space_panning) {
262                 if (lc->mode == Inkscape::LivePathEffect::INVALID_LPE) {
263                     // don't do anything for now if we are inactive (except clearing the selection
264                     // since this was a click into empty space)
265                     selection->clear();
266                     desktop->messageStack()->flash(Inkscape::WARNING_MESSAGE, _("Choose a construction tool from the toolbar."));
267                     ret = true;
268                     break;
269                 }
271                 // save drag origin
272                 event_context->xp = (gint) event->button.x;
273                 event_context->yp = (gint) event->button.y;
274                 event_context->within_tolerance = true;
276                 using namespace Inkscape::LivePathEffect;
278                 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
279                 int mode = prefs->getInt("/tools/lpetool/mode");
280                 EffectType type = lpesubtools[mode].type;
282                 //bool over_stroke = lc->shape_editor->is_over_stroke(Geom::Point(event->button.x, event->button.y), true);
284                 sp_pen_context_wait_for_LPE_mouse_clicks(lc, type, Inkscape::LivePathEffect::Effect::acceptsNumClicks(type));
286                 // we pass the mouse click on to pen tool as the first click which it should collect
287                 ret = ((SPEventContextClass *) lpetool_parent_class)->root_handler(event_context, event);
288             }
289             break;
292     case GDK_BUTTON_RELEASE:
293     {
294         /**
295         break;
296         **/
297     }
299     case GDK_KEY_PRESS:
300         /**
301         switch (get_group0_keyval (&event->key)) {
302         }
303         break;
304         **/
306     case GDK_KEY_RELEASE:
307         /**
308         switch (get_group0_keyval(&event->key)) {
309             case GDK_Control_L:
310             case GDK_Control_R:
311                 dc->_message_context->clear();
312                 break;
313             default:
314                 break;
315         }
316         **/
318     default:
319         break;
320     }
322     if (!ret) {
323         if (((SPEventContextClass *) lpetool_parent_class)->root_handler) {
324             ret = ((SPEventContextClass *) lpetool_parent_class)->root_handler(event_context, event);
325         }
326     }
328     return ret;
331 /*
332  * Finds the index in the list of geometric subtools corresponding to the given LPE type.
333  * Returns -1 if no subtool is found.
334  */
335 int
336 lpetool_mode_to_index(Inkscape::LivePathEffect::EffectType const type) {
337     for (int i = 0; i < num_subtools; ++i) {
338         if (lpesubtools[i].type == type) {
339             return i;
340         }
341     }
342     return -1;
345 /*
346  * Checks whether an item has a construction applied as LPE and if so returns the index in
347  * lpesubtools of this construction
348  */
349 int lpetool_item_has_construction(SPLPEToolContext */*lc*/, SPItem *item)
351     if (!SP_IS_LPE_ITEM(item)) {
352         return -1;
353     }
355     Inkscape::LivePathEffect::Effect* lpe = sp_lpe_item_get_current_lpe(SP_LPE_ITEM(item));
356     if (!lpe) {
357         return -1;
358     }
359     return lpetool_mode_to_index(lpe->effectType());
362 /*
363  * Attempts to perform the construction of the given type (i.e., to apply the corresponding LPE) to
364  * a single selected item. Returns whether we succeeded.
365  */
366 bool
367 lpetool_try_construction(SPLPEToolContext *lc, Inkscape::LivePathEffect::EffectType const type)
369     Inkscape::Selection *selection = sp_desktop_selection(lc->desktop);
370     SPItem *item = selection->singleItem();
372     // TODO: should we check whether type represents a valid geometric construction?
373     if (item && SP_IS_LPE_ITEM(item) && Inkscape::LivePathEffect::Effect::acceptsNumClicks(type) == 0) {
374         Inkscape::LivePathEffect::Effect::createAndApply(type, sp_desktop_document(lc->desktop), item);
375         return true;
376     }
377     return false;
380 void
381 lpetool_context_switch_mode(SPLPEToolContext *lc, Inkscape::LivePathEffect::EffectType const type)
383     int index = lpetool_mode_to_index(type);
384     if (index != -1) {
385         lc->mode = type;
386         lc->desktop->setToolboxSelectOneValue ("lpetool_mode_action", index);
387     } else {
388         g_warning ("Invalid mode selected: %d", type);
389         return;
390     }
393 void
394 lpetool_get_limiting_bbox_corners(SPDocument *document, Geom::Point &A, Geom::Point &B) {
395     Geom::Coord w = document->getWidth();
396     Geom::Coord h = document->getHeight();
397     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
399     double ulx = prefs->getDouble("/tools/lpetool/bbox_upperleftx", 0);
400     double uly = prefs->getDouble("/tools/lpetool/bbox_upperlefty", 0);
401     double lrx = prefs->getDouble("/tools/lpetool/bbox_lowerrightx", w);
402     double lry = prefs->getDouble("/tools/lpetool/bbox_lowerrighty", h);
404     A = Geom::Point(ulx, uly);
405     B = Geom::Point(lrx, lry);
408 /*
409  * Reads the limiting bounding box from preferences and draws it on the screen
410  */
411 // TODO: Note that currently the bbox is not user-settable; we simply use the page borders
412 void
413 lpetool_context_reset_limiting_bbox(SPLPEToolContext *lc)
415     if (lc->canvas_bbox) {
416         gtk_object_destroy(GTK_OBJECT(lc->canvas_bbox));
417         lc->canvas_bbox = NULL;
418     }
420     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
421     if (!prefs->getBool("/tools/lpetool/show_bbox", true))
422         return;
424     SPDocument *document = sp_desktop_document(lc->desktop);
426     Geom::Point A, B;
427     lpetool_get_limiting_bbox_corners(document, A, B);
428     Geom::Matrix doc2dt(lc->desktop->doc2dt());
429     A *= doc2dt;
430     B *= doc2dt;
432     Geom::Rect rect(A, B);
433     SPCurve *curve = SPCurve::new_from_rect(rect);
435     lc->canvas_bbox = sp_canvas_bpath_new (sp_desktop_controls(lc->desktop), curve);
436     sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(lc->canvas_bbox), 0x0000ffff, 0.8, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT, 5, 5);
439 static void
440 set_pos_and_anchor(SPCanvasText *canvas_text, const Geom::Piecewise<Geom::D2<Geom::SBasis> > &pwd2,
441                    const double t, const double length, bool /*use_curvature*/ = false)
443     using namespace Geom;
445     Piecewise<D2<SBasis> > pwd2_reparam = arc_length_parametrization(pwd2, 2 , 0.1);
446     double t_reparam = pwd2_reparam.cuts.back() * t;
447     Point pos = pwd2_reparam.valueAt(t_reparam);
448     Point dir = unit_vector(derivative(pwd2_reparam).valueAt(t_reparam));
449     Point n = -rot90(dir);
450     double angle = Geom::angle_between(dir, Point(1,0));
452     sp_canvastext_set_coords(canvas_text, pos + n * length);
453     sp_canvastext_set_anchor(canvas_text, std::sin(angle), -std::cos(angle));
456 void
457 lpetool_create_measuring_items(SPLPEToolContext *lc, Inkscape::Selection *selection)
459     if (!selection) {
460         selection = sp_desktop_selection(lc->desktop);
461     }
462     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
463     bool show = prefs->getBool("/tools/lpetool/show_measuring_info",  true);
465     SPPath *path;
466     SPCurve *curve;
467     SPCanvasText *canvas_text;
468     SPCanvasGroup *tmpgrp = sp_desktop_tempgroup(lc->desktop);
469     gchar *arc_length;
470     double lengthval;
472     for (GSList const *i = selection->itemList(); i != NULL; i = i->next) {
473         if (SP_IS_PATH(i->data)) {
474             path = SP_PATH(i->data);
475             curve = SP_SHAPE(path)->getCurve();
476             Geom::Piecewise<Geom::D2<Geom::SBasis> > pwd2 = paths_to_pw(curve->get_pathvector());
477             canvas_text = (SPCanvasText *) sp_canvastext_new(tmpgrp, lc->desktop, Geom::Point(0,0), "");
478             if (!show)
479                 sp_canvas_item_hide(SP_CANVAS_ITEM(canvas_text));
481             SPUnitId unitid = static_cast<SPUnitId>(prefs->getInt("/tools/lpetool/unitid", SP_UNIT_PX));
482             SPUnit unit = sp_unit_get_by_id(unitid);
484             lengthval = Geom::length(pwd2);
485             gboolean success;
486             success = sp_convert_distance(&lengthval, &sp_unit_get_by_id(SP_UNIT_PX), &unit);
487             arc_length = g_strdup_printf("%.2f %s", lengthval, success ? sp_unit_get_abbreviation(&unit) : "px");
488             sp_canvastext_set_text (canvas_text, arc_length);
489             set_pos_and_anchor(canvas_text, pwd2, 0.5, 10);
490             // TODO: must we free arc_length?
491             (*lc->measuring_items)[path] = SP_CANVAS_ITEM(canvas_text);
492         }
493     }
496 void
497 lpetool_delete_measuring_items(SPLPEToolContext *lc)
499     std::map<SPPath *, SPCanvasItem*>::iterator i;
500     for (i = lc->measuring_items->begin(); i != lc->measuring_items->end(); ++i) {
501         gtk_object_destroy(GTK_OBJECT(i->second));
502     }
503     lc->measuring_items->clear();
506 void
507 lpetool_update_measuring_items(SPLPEToolContext *lc)
509     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
510     SPPath *path;
511     SPCurve *curve;
512     double lengthval;
513     gchar *arc_length;
514     std::map<SPPath *, SPCanvasItem*>::iterator i;
515     for (i = lc->measuring_items->begin(); i != lc->measuring_items->end(); ++i) {
516         path = i->first;
517         curve = SP_SHAPE(path)->getCurve();
518         Geom::Piecewise<Geom::D2<Geom::SBasis> > pwd2 = Geom::paths_to_pw(curve->get_pathvector());
519         SPUnitId unitid = static_cast<SPUnitId>(prefs->getInt("/tools/lpetool/unitid", SP_UNIT_PX));
520         SPUnit unit = sp_unit_get_by_id(unitid);
521         lengthval = Geom::length(pwd2);
522         gboolean success;
523         success = sp_convert_distance(&lengthval, &sp_unit_get_by_id(SP_UNIT_PX), &unit);
524         arc_length = g_strdup_printf("%.2f %s", lengthval, success ? sp_unit_get_abbreviation(&unit) : "px");
525         sp_canvastext_set_text (SP_CANVASTEXT(i->second), arc_length);
526         set_pos_and_anchor(SP_CANVASTEXT(i->second), pwd2, 0.5, 10);
527         // TODO: must we free arc_length?
528     }
531 void
532 lpetool_show_measuring_info(SPLPEToolContext *lc, bool show)
534     std::map<SPPath *, SPCanvasItem*>::iterator i;
535     for (i = lc->measuring_items->begin(); i != lc->measuring_items->end(); ++i) {
536         if (show) {
537             sp_canvas_item_show(i->second);
538         } else {
539             sp_canvas_item_hide(i->second);
540         }
541     }
544 /*
545   Local Variables:
546   mode:c++
547   c-file-style:"stroustrup"
548   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
549   indent-tabs-mode:nil
550   fill-column:99
551   End:
552 */
553 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :