Code

93e7e8470905f4c7ace2660ad4577b3b01d60b14
[inkscape.git] / src / rect-context.cpp
1 #define __SP_RECT_CONTEXT_C__
3 /*
4  * Rectangle drawing context
5  *
6  * Author:
7  *   Lauris Kaplinski <lauris@kaplinski.com>
8  *   bulia byak <buliabyak@users.sf.net>
9  *
10  * Copyright (C) 2006      Johan Engelen <johan@shouraizou.nl>
11  * Copyright (C) 2000-2005 authors
12  * Copyright (C) 2000-2001 Ximian, Inc.
13  *
14  * Released under GNU GPL, read the file 'COPYING' for more information
15  */
17 #include "config.h"
19 #include <gdk/gdkkeysyms.h>
20 #include <cstring>
21 #include <string>
23 #include "macros.h"
24 #include "display/sp-canvas.h"
25 #include "sp-rect.h"
26 #include "document.h"
27 #include "sp-namedview.h"
28 #include "selection.h"
29 #include "selection-chemistry.h"
30 #include "desktop-handles.h"
31 #include "snap.h"
32 #include "desktop.h"
33 #include "desktop-style.h"
34 #include "message-context.h"
35 #include "pixmaps/cursor-rect.xpm"
36 #include "rect-context.h"
37 #include "sp-metrics.h"
38 #include <glibmm/i18n.h>
39 #include "object-edit.h"
40 #include "xml/repr.h"
41 #include "xml/node-event-vector.h"
42 #include "preferences.h"
43 #include "context-fns.h"
45 //static const double goldenratio = 1.61803398874989484820; // golden ratio
47 static void sp_rect_context_class_init(SPRectContextClass *klass);
48 static void sp_rect_context_init(SPRectContext *rect_context);
49 static void sp_rect_context_dispose(GObject *object);
51 static void sp_rect_context_setup(SPEventContext *ec);
52 static void sp_rect_context_set(SPEventContext *ec, Inkscape::Preferences::Entry *val);
54 static gint sp_rect_context_root_handler(SPEventContext *event_context, GdkEvent *event);
55 static gint sp_rect_context_item_handler(SPEventContext *event_context, SPItem *item, GdkEvent *event);
57 static void sp_rect_drag(SPRectContext &rc, NR::Point const pt, guint state);
58 static void sp_rect_finish(SPRectContext *rc);
60 static SPEventContextClass *parent_class;
63 GtkType sp_rect_context_get_type()
64 {
65     static GType type = 0;
66     if (!type) {
67         GTypeInfo info = {
68             sizeof(SPRectContextClass),
69             NULL, NULL,
70             (GClassInitFunc) sp_rect_context_class_init,
71             NULL, NULL,
72             sizeof(SPRectContext),
73             4,
74             (GInstanceInitFunc) sp_rect_context_init,
75             NULL,    /* value_table */
76         };
77         type = g_type_register_static(SP_TYPE_EVENT_CONTEXT, "SPRectContext", &info, (GTypeFlags) 0);
78     }
79     return type;
80 }
82 static void sp_rect_context_class_init(SPRectContextClass *klass)
83 {
84     GObjectClass *object_class = (GObjectClass *) klass;
85     SPEventContextClass *event_context_class = (SPEventContextClass *) klass;
87     parent_class = (SPEventContextClass *) g_type_class_peek_parent(klass);
89     object_class->dispose = sp_rect_context_dispose;
91     event_context_class->setup = sp_rect_context_setup;
92     event_context_class->set = sp_rect_context_set;
93     event_context_class->root_handler  = sp_rect_context_root_handler;
94     event_context_class->item_handler  = sp_rect_context_item_handler;
95 }
97 static void sp_rect_context_init(SPRectContext *rect_context)
98 {
99     SPEventContext *event_context = SP_EVENT_CONTEXT(rect_context);
101     event_context->cursor_shape = cursor_rect_xpm;
102     event_context->hot_x = 4;
103     event_context->hot_y = 4;
104     event_context->xp = 0;
105     event_context->yp = 0;
106     event_context->tolerance = 0;
107     event_context->within_tolerance = false;
108     event_context->item_to_select = NULL;
110     event_context->shape_repr = NULL;
111     event_context->shape_knot_holder = NULL;
113     rect_context->item = NULL;
115     rect_context->rx = 0.0;
116     rect_context->ry = 0.0;
118     new (&rect_context->sel_changed_connection) sigc::connection();
121 static void sp_rect_context_dispose(GObject *object)
123     SPRectContext *rc = SP_RECT_CONTEXT(object);
124     SPEventContext *ec = SP_EVENT_CONTEXT(object);
126     ec->enableGrDrag(false);
128     rc->sel_changed_connection.disconnect();
129     rc->sel_changed_connection.~connection();
131     /* fixme: This is necessary because we do not grab */
132     if (rc->item) {
133         sp_rect_finish(rc);
134     }
136     if (ec->shape_knot_holder) {
137         delete ec->shape_knot_holder;
138         ec->shape_knot_holder = NULL;
139     }
141     if (ec->shape_repr) { // remove old listener
142         sp_repr_remove_listener_by_data(ec->shape_repr, ec);
143         Inkscape::GC::release(ec->shape_repr);
144         ec->shape_repr = 0;
145     }
147     if (rc->_message_context) {
148         delete rc->_message_context;
149     }
151     G_OBJECT_CLASS(parent_class)->dispose(object);
154 static Inkscape::XML::NodeEventVector ec_shape_repr_events = {
155     NULL, /* child_added */
156     NULL, /* child_removed */
157     ec_shape_event_attr_changed,
158     NULL, /* content_changed */
159     NULL  /* order_changed */
160 };
162 /**
163 \brief  Callback that processes the "changed" signal on the selection;
164 destroys old and creates new knotholder
165 */
166 void sp_rect_context_selection_changed(Inkscape::Selection *selection, gpointer data)
168     SPRectContext *rc = SP_RECT_CONTEXT(data);
169     SPEventContext *ec = SP_EVENT_CONTEXT(rc);
171     if (ec->shape_knot_holder) { // destroy knotholder
172         delete ec->shape_knot_holder;
173         ec->shape_knot_holder = NULL;
174     }
176     if (ec->shape_repr) { // remove old listener
177         sp_repr_remove_listener_by_data(ec->shape_repr, ec);
178         Inkscape::GC::release(ec->shape_repr);
179         ec->shape_repr = 0;
180     }
182     SPItem *item = selection->singleItem();
183     if (item) {
184         ec->shape_knot_holder = sp_item_knot_holder(item, ec->desktop);
185         Inkscape::XML::Node *shape_repr = SP_OBJECT_REPR(item);
186         if (shape_repr) {
187             ec->shape_repr = shape_repr;
188             Inkscape::GC::anchor(shape_repr);
189             sp_repr_add_listener(shape_repr, &ec_shape_repr_events, ec);
190         }
191     }
194 static void sp_rect_context_setup(SPEventContext *ec)
196     SPRectContext *rc = SP_RECT_CONTEXT(ec);
198     if (((SPEventContextClass *) parent_class)->setup) {
199         ((SPEventContextClass *) parent_class)->setup(ec);
200     }
202     SPItem *item = sp_desktop_selection(ec->desktop)->singleItem();
203     if (item) {
204         ec->shape_knot_holder = sp_item_knot_holder(item, ec->desktop);
205         Inkscape::XML::Node *shape_repr = SP_OBJECT_REPR(item);
206         if (shape_repr) {
207             ec->shape_repr = shape_repr;
208             Inkscape::GC::anchor(shape_repr);
209             sp_repr_add_listener(shape_repr, &ec_shape_repr_events, ec);
210         }
211     }
213     rc->sel_changed_connection.disconnect();
214     rc->sel_changed_connection = sp_desktop_selection(ec->desktop)->connectChanged(
215         sigc::bind(sigc::ptr_fun(&sp_rect_context_selection_changed), (gpointer)rc)
216     );
218     sp_event_context_read(ec, "rx");
219     sp_event_context_read(ec, "ry");
221     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
222     if (prefs->getBool("/tools/shapes/selcue")) {
223         ec->enableSelectionCue();
224     }
226     if (prefs->getBool("/tools/shapes/gradientdrag")) {
227         ec->enableGrDrag();
228     }
230     rc->_message_context = new Inkscape::MessageContext((ec->desktop)->messageStack());
233 static void sp_rect_context_set(SPEventContext *ec, Inkscape::Preferences::Entry *val)
235     SPRectContext *rc = SP_RECT_CONTEXT(ec);
237     /* fixme: Proper error handling for non-numeric data.  Use a locale-independent function like
238      * g_ascii_strtod (or a thin wrapper that does the right thing for invalid values inf/nan). */
239     Glib::ustring name = val->getEntryName();
240     if ( name == "rx" ) {
241         rc->rx = val->getDoubleLimited(); // prevents NaN and +/-Inf from messing up
242     } else if ( name == "ry" ) {
243         rc->ry = val->getDoubleLimited();
244     }
247 static gint sp_rect_context_item_handler(SPEventContext *event_context, SPItem *item, GdkEvent *event)
249     SPDesktop *desktop = event_context->desktop;
251     gint ret = FALSE;
253     switch (event->type) {
254     case GDK_BUTTON_PRESS:
255         if ( event->button.button == 1 && !event_context->space_panning) {
256             Inkscape::setup_for_drag_start(desktop, event_context, event);
257             ret = TRUE;
258         }
259         break;
260         // motion and release are always on root (why?)
261     default:
262         break;
263     }
265     if (((SPEventContextClass *) parent_class)->item_handler) {
266         ret = ((SPEventContextClass *) parent_class)->item_handler(event_context, item, event);
267     }
269     return ret;
272 static gint sp_rect_context_root_handler(SPEventContext *event_context, GdkEvent *event)
274     static bool dragging;
276     SPDesktop *desktop = event_context->desktop;
277     Inkscape::Selection *selection = sp_desktop_selection (desktop);
279     SPRectContext *rc = SP_RECT_CONTEXT(event_context);
280     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
282     event_context->tolerance = prefs->getIntLimited("/options/dragtolerance/value", 0, 0, 100);
284     gint ret = FALSE;
285     switch (event->type) {
286     case GDK_BUTTON_PRESS:
287         if (event->button.button == 1 && !event_context->space_panning) {
288             NR::Point const button_w(event->button.x,
289                                      event->button.y);
291             // save drag origin
292             event_context->xp = (gint) button_w[NR::X];
293             event_context->yp = (gint) button_w[NR::Y];
294             event_context->within_tolerance = true;
296             // remember clicked item, disregarding groups, honoring Alt
297             event_context->item_to_select = sp_event_context_find_item (desktop, button_w, event->button.state & GDK_MOD1_MASK, TRUE);
299             dragging = true;
301             /* Position center */
302             Geom::Point button_dt(desktop->w2d(button_w));
303             rc->center = from_2geom(button_dt);
304             
305             /* Snap center */
306             SnapManager &m = desktop->namedview->snap_manager;
307             m.setup(desktop);
308             m.freeSnapReturnByRef(Inkscape::SnapPreferences::SNAPPOINT_NODE, button_dt);
309             rc->center = from_2geom(button_dt);
310             
311             sp_canvas_item_grab(SP_CANVAS_ITEM(desktop->acetate),
312                                 ( GDK_KEY_PRESS_MASK |
313                                   GDK_BUTTON_RELEASE_MASK       |
314                                   GDK_POINTER_MOTION_MASK       |
315                                   GDK_POINTER_MOTION_HINT_MASK       |
316                                   GDK_BUTTON_PRESS_MASK ),
317                                 NULL, event->button.time);
318                                 
319             ret = TRUE;
320         }
321         break;
322     case GDK_MOTION_NOTIFY:
323         if ( dragging
324              && (event->motion.state & GDK_BUTTON1_MASK) && !event_context->space_panning)
325         {
326             if ( event_context->within_tolerance
327                  && ( abs( (gint) event->motion.x - event_context->xp ) < event_context->tolerance )
328                  && ( abs( (gint) event->motion.y - event_context->yp ) < event_context->tolerance ) ) {
329                 break; // do not drag if we're within tolerance from origin
330             }
331             // Once the user has moved farther than tolerance from the original location
332             // (indicating they intend to draw, not click), then always process the
333             // motion notify coordinates as given (no snapping back to origin)
334             event_context->within_tolerance = false;
336             NR::Point const motion_w(event->motion.x, event->motion.y);
337             NR::Point motion_dt(desktop->w2d(motion_w));
338             
339             sp_rect_drag(*rc, motion_dt, event->motion.state); // this will also handle the snapping
340             gobble_motion_events(GDK_BUTTON1_MASK);
341             ret = TRUE;
342         }
343         break;
344     case GDK_BUTTON_RELEASE:
345         event_context->xp = event_context->yp = 0;
346         if (event->button.button == 1 && !event_context->space_panning) {
347             dragging = false;
349             if (!event_context->within_tolerance) {
350                 // we've been dragging, finish the rect
351                 sp_rect_finish(rc);
352             } else if (event_context->item_to_select) {
353                 // no dragging, select clicked item if any
354                 if (event->button.state & GDK_SHIFT_MASK) {
355                     selection->toggle(event_context->item_to_select);
356                 } else {
357                     selection->set(event_context->item_to_select);
358                 }
359             } else {
360                 // click in an empty space
361                 selection->clear();
362             }
364             event_context->item_to_select = NULL;
365             ret = TRUE;
366             sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate),
367                                   event->button.time);
368         }
369         break;
370     case GDK_KEY_PRESS:
371         switch (get_group0_keyval (&event->key)) {
372         case GDK_Alt_L:
373         case GDK_Alt_R:
374         case GDK_Control_L:
375         case GDK_Control_R:
376         case GDK_Shift_L:
377         case GDK_Shift_R:
378         case GDK_Meta_L:  // Meta is when you press Shift+Alt (at least on my machine)
379         case GDK_Meta_R:
380             if (!dragging){
381                 sp_event_show_modifier_tip (event_context->defaultMessageContext(), event,
382                                             _("<b>Ctrl</b>: make square or integer-ratio rect, lock a rounded corner circular"),
383                                             _("<b>Shift</b>: draw around the starting point"),
384                                             NULL);
385             }
386             break;
387         case GDK_Up:
388         case GDK_Down:
389         case GDK_KP_Up:
390         case GDK_KP_Down:
391             // prevent the zoom field from activation
392             if (!MOD__CTRL_ONLY)
393                 ret = TRUE;
394             break;
396         case GDK_x:
397         case GDK_X:
398             if (MOD__ALT_ONLY) {
399                 desktop->setToolboxFocusTo ("altx-rect");
400                 ret = TRUE;
401             }
402             break;
404         case GDK_g:
405         case GDK_G:
406             if (MOD__SHIFT_ONLY) {
407                 sp_selection_to_guides(desktop);
408                 ret = true;
409             }
410             break;
412         case GDK_Escape:
413             sp_desktop_selection(desktop)->clear();
414             //TODO: make dragging escapable by Esc
415             break;
417         case GDK_space:
418             if (dragging) {
419                 sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate),
420                                       event->button.time);
421                 dragging = false;
422                 if (!event_context->within_tolerance) {
423                     // we've been dragging, finish the rect
424                     sp_rect_finish(rc);
425                 }
426                 // do not return true, so that space would work switching to selector
427             }
428             break;
430         default:
431             break;
432         }
433         break;
434     case GDK_KEY_RELEASE:
435         switch (get_group0_keyval (&event->key)) {
436         case GDK_Alt_L:
437         case GDK_Alt_R:
438         case GDK_Control_L:
439         case GDK_Control_R:
440         case GDK_Shift_L:
441         case GDK_Shift_R:
442         case GDK_Meta_L:  // Meta is when you press Shift+Alt
443         case GDK_Meta_R:
444             event_context->defaultMessageContext()->clear();
445             break;
446         default:
447             break;
448         }
449         break;
450     default:
451         break;
452     }
454     if (!ret) {
455         if (((SPEventContextClass *) parent_class)->root_handler) {
456             ret = ((SPEventContextClass *) parent_class)->root_handler(event_context, event);
457         }
458     }
460     return ret;
463 static void sp_rect_drag(SPRectContext &rc, NR::Point const pt, guint state)
465     SPDesktop *desktop = SP_EVENT_CONTEXT(&rc)->desktop;
467     if (!rc.item) {
469         if (Inkscape::have_viable_layer(desktop, rc._message_context) == false) {
470             return;
471         }
473         /* Create object */
474         Inkscape::XML::Document *xml_doc = sp_document_repr_doc(SP_EVENT_CONTEXT_DOCUMENT(&rc));
475         Inkscape::XML::Node *repr = xml_doc->createElement("svg:rect");
477         /* Set style */
478         sp_desktop_apply_style_tool (desktop, repr, "/tools/shapes/rect", false);
480         rc.item = (SPItem *) desktop->currentLayer()->appendChildRepr(repr);
481         Inkscape::GC::release(repr);
482         rc.item->transform = SP_ITEM(desktop->currentRoot())->getRelativeTransform(desktop->currentLayer());
483         rc.item->updateRepr();
485         sp_canvas_force_full_redraw_after_interruptions(desktop->canvas, 5);
486     }
488     Geom::Rect const r = Inkscape::snap_rectangular_box(desktop, rc.item, pt, rc.center, state);
490     sp_rect_position_set(SP_RECT(rc.item), r.min()[Geom::X], r.min()[Geom::Y], r.dimensions()[Geom::X], r.dimensions()[Geom::Y]);
491     if ( rc.rx != 0.0 ) {
492         sp_rect_set_rx (SP_RECT(rc.item), TRUE, rc.rx);
493     }
494     if ( rc.ry != 0.0 ) {
495         if (rc.rx == 0.0)
496             sp_rect_set_ry (SP_RECT(rc.item), TRUE, CLAMP(rc.ry, 0, MIN(r.dimensions()[Geom::X], r.dimensions()[Geom::Y])/2));
497         else
498             sp_rect_set_ry (SP_RECT(rc.item), TRUE, CLAMP(rc.ry, 0, r.dimensions()[Geom::Y]));
499     }
501     // status text
502     double rdimx = r.dimensions()[Geom::X];
503     double rdimy = r.dimensions()[Geom::Y];
504     GString *xs = SP_PX_TO_METRIC_STRING(rdimx, desktop->namedview->getDefaultMetric());
505     GString *ys = SP_PX_TO_METRIC_STRING(rdimy, desktop->namedview->getDefaultMetric());
506     if (state & GDK_CONTROL_MASK) {
507         int ratio_x, ratio_y;
508         bool is_golden_ratio = false;
509         if (fabs (rdimx) > fabs (rdimy)) {
510             if (fabs(rdimx / rdimy - goldenratio) < 1e-6) {
511                 is_golden_ratio = true;
512             }
513             ratio_x = (int) rint (rdimx / rdimy);
514             ratio_y = 1;
515         } else {
516             if (fabs(rdimy / rdimx - goldenratio) < 1e-6) {
517                 is_golden_ratio = true;
518             }
519             ratio_x = 1;
520             ratio_y = (int) rint (rdimy / rdimx);
521         }
522         if (!is_golden_ratio) {
523             rc._message_context->setF(Inkscape::IMMEDIATE_MESSAGE, _("<b>Rectangle</b>: %s &#215; %s (constrained to ratio %d:%d); with <b>Shift</b> to draw around the starting point"), xs->str, ys->str, ratio_x, ratio_y);
524         } else {
525             if (ratio_y == 1) {
526                 rc._message_context->setF(Inkscape::IMMEDIATE_MESSAGE, _("<b>Rectangle</b>: %s &#215; %s (constrained to golden ratio 1.618 : 1); with <b>Shift</b> to draw around the starting point"), xs->str, ys->str);
527             } else {
528                 rc._message_context->setF(Inkscape::IMMEDIATE_MESSAGE, _("<b>Rectangle</b>: %s &#215; %s (constrained to golden ratio 1 : 1.618); with <b>Shift</b> to draw around the starting point"), xs->str, ys->str);
529             }
530         }
531     } else {
532         rc._message_context->setF(Inkscape::IMMEDIATE_MESSAGE, _("<b>Rectangle</b>: %s &#215; %s; with <b>Ctrl</b> to make square or integer-ratio rectangle; with <b>Shift</b> to draw around the starting point"), xs->str, ys->str);
533     }
534     g_string_free(xs, FALSE);
535     g_string_free(ys, FALSE);
538 static void sp_rect_finish(SPRectContext *rc)
540     rc->_message_context->clear();
542     if ( rc->item != NULL ) {
543         SPDesktop * desktop;
545         desktop = SP_EVENT_CONTEXT_DESKTOP(rc);
547         SP_OBJECT(rc->item)->updateRepr();
549         sp_canvas_end_forced_full_redraws(desktop->canvas);
551         sp_desktop_selection(desktop)->set(rc->item);
552         sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_RECT,
553                          _("Create rectangle"));
555         rc->item = NULL;
556     }
559 /*
560   Local Variables:
561   mode:c++
562   c-file-style:"stroustrup"
563   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
564   indent-tabs-mode:nil
565   fill-column:99
566   End:
567 */
568 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :