1 #define __SP_DYNA_DRAW_CONTEXT_C__
3 /*
4 * Handwriting-like drawing mode
5 *
6 * Authors:
7 * Mitsuru Oka <oka326@parkcity.ne.jp>
8 * Lauris Kaplinski <lauris@kaplinski.com>
9 * bulia byak <buliabyak@users.sf.net>
10 *
11 * The original dynadraw code:
12 * Paul Haeberli <paul@sgi.com>
13 *
14 * Copyright (C) 1998 The Free Software Foundation
15 * Copyright (C) 1999-2005 authors
16 * Copyright (C) 2001-2002 Ximian, Inc.
17 *
18 * Released under GNU GPL, read the file 'COPYING' for more information
19 */
21 #define noDYNA_DRAW_VERBOSE
23 #include "config.h"
25 #include <gtk/gtk.h>
26 #include <gdk/gdkkeysyms.h>
28 #include "svg/svg.h"
29 #include "display/canvas-bpath.h"
30 #include "display/bezier-utils.h"
32 #include <glib/gmem.h>
33 #include "macros.h"
34 #include "document.h"
35 #include "selection.h"
36 #include "desktop.h"
37 #include "desktop-events.h"
38 #include "desktop-handles.h"
39 #include "desktop-affine.h"
40 #include "desktop-style.h"
41 #include "message-context.h"
42 #include "pixmaps/cursor-calligraphy.xpm"
43 #include "pixmaps/cursor-calligraphy.pixbuf"
44 #include "dyna-draw-context.h"
45 #include "libnr/n-art-bpath.h"
46 #include "libnr/nr-path.h"
47 #include "xml/repr.h"
48 #include "context-fns.h"
49 #include "sp-item.h"
50 #include "inkscape.h"
51 #include "color.h"
53 #define DDC_RED_RGBA 0xff0000ff
55 #define SAMPLE_TIMEOUT 10
56 #define TOLERANCE_LINE 1.0
57 #define TOLERANCE_CALLIGRAPHIC 3.0
58 #define DYNA_EPSILON 1.0e-2
60 #define DYNA_MIN_WIDTH 1.0e-6
62 #define DRAG_MIN 0.0
63 #define DRAG_DEFAULT 1.0
64 #define DRAG_MAX 1.0
66 static void sp_dyna_draw_context_class_init(SPDynaDrawContextClass *klass);
67 static void sp_dyna_draw_context_init(SPDynaDrawContext *ddc);
68 static void sp_dyna_draw_context_dispose(GObject *object);
70 static void sp_dyna_draw_context_setup(SPEventContext *ec);
71 static void sp_dyna_draw_context_set(SPEventContext *ec, gchar const *key, gchar const *val);
72 static gint sp_dyna_draw_context_root_handler(SPEventContext *ec, GdkEvent *event);
74 static void clear_current(SPDynaDrawContext *dc);
75 static void set_to_accumulated(SPDynaDrawContext *dc);
76 static void accumulate_calligraphic(SPDynaDrawContext *dc);
78 static void fit_and_split(SPDynaDrawContext *ddc, gboolean release);
79 static void fit_and_split_calligraphics(SPDynaDrawContext *ddc, gboolean release);
81 static void sp_dyna_draw_reset(SPDynaDrawContext *ddc, NR::Point p);
82 static NR::Point sp_dyna_draw_get_npoint(SPDynaDrawContext const *ddc, NR::Point v);
83 static NR::Point sp_dyna_draw_get_vpoint(SPDynaDrawContext const *ddc, NR::Point n);
84 static void draw_temporary_box(SPDynaDrawContext *dc);
87 static SPEventContextClass *parent_class;
89 GtkType
90 sp_dyna_draw_context_get_type(void)
91 {
92 static GType type = 0;
93 if (!type) {
94 GTypeInfo info = {
95 sizeof(SPDynaDrawContextClass),
96 NULL, NULL,
97 (GClassInitFunc) sp_dyna_draw_context_class_init,
98 NULL, NULL,
99 sizeof(SPDynaDrawContext),
100 4,
101 (GInstanceInitFunc) sp_dyna_draw_context_init,
102 NULL, /* value_table */
103 };
104 type = g_type_register_static(SP_TYPE_EVENT_CONTEXT, "SPDynaDrawContext", &info, (GTypeFlags)0);
105 }
106 return type;
107 }
109 static void
110 sp_dyna_draw_context_class_init(SPDynaDrawContextClass *klass)
111 {
112 GObjectClass *object_class = (GObjectClass *) klass;
113 SPEventContextClass *event_context_class = (SPEventContextClass *) klass;
115 parent_class = (SPEventContextClass*)g_type_class_peek_parent(klass);
117 object_class->dispose = sp_dyna_draw_context_dispose;
119 event_context_class->setup = sp_dyna_draw_context_setup;
120 event_context_class->set = sp_dyna_draw_context_set;
121 event_context_class->root_handler = sp_dyna_draw_context_root_handler;
122 }
124 static void
125 sp_dyna_draw_context_init(SPDynaDrawContext *ddc)
126 {
127 SPEventContext *event_context = SP_EVENT_CONTEXT(ddc);
129 event_context->cursor_shape = cursor_calligraphy_xpm;
130 event_context->cursor_pixbuf = gdk_pixbuf_new_from_inline(
131 -1,
132 cursor_calligraphy_pixbuf,
133 FALSE,
134 NULL);
135 event_context->hot_x = 4;
136 event_context->hot_y = 4;
138 ddc->accumulated = NULL;
139 ddc->segments = NULL;
140 ddc->currentcurve = NULL;
141 ddc->currentshape = NULL;
142 ddc->npoints = 0;
143 ddc->cal1 = NULL;
144 ddc->cal2 = NULL;
145 ddc->repr = NULL;
147 /* DynaDraw values */
148 ddc->cur = NR::Point(0,0);
149 ddc->last = NR::Point(0,0);
150 ddc->vel = NR::Point(0,0);
151 ddc->acc = NR::Point(0,0);
152 ddc->ang = NR::Point(0,0);
153 ddc->del = NR::Point(0,0);
155 /* attributes */
156 ddc->dragging = FALSE;
158 ddc->mass = 0.3;
159 ddc->drag = DRAG_DEFAULT;
160 ddc->angle = 30.0;
161 ddc->width = 0.2;
163 ddc->vel_thin = 0.1;
164 ddc->flatness = 0.9;
165 ddc->cap_rounding = 0.0;
167 ddc->abs_width = false;
168 ddc->keep_selected = true;
169 }
171 static void
172 sp_dyna_draw_context_dispose(GObject *object)
173 {
174 SPDynaDrawContext *ddc = SP_DYNA_DRAW_CONTEXT(object);
176 if (ddc->accumulated) {
177 ddc->accumulated = sp_curve_unref(ddc->accumulated);
178 }
180 while (ddc->segments) {
181 gtk_object_destroy(GTK_OBJECT(ddc->segments->data));
182 ddc->segments = g_slist_remove(ddc->segments, ddc->segments->data);
183 }
185 if (ddc->currentcurve) ddc->currentcurve = sp_curve_unref(ddc->currentcurve);
186 if (ddc->cal1) ddc->cal1 = sp_curve_unref(ddc->cal1);
187 if (ddc->cal2) ddc->cal2 = sp_curve_unref(ddc->cal2);
189 if (ddc->currentshape) {
190 gtk_object_destroy(GTK_OBJECT(ddc->currentshape));
191 ddc->currentshape = NULL;
192 }
194 if (ddc->_message_context) {
195 delete ddc->_message_context;
196 }
198 G_OBJECT_CLASS(parent_class)->dispose(object);
199 }
201 static void
202 sp_dyna_draw_context_setup(SPEventContext *ec)
203 {
204 SPDynaDrawContext *ddc = SP_DYNA_DRAW_CONTEXT(ec);
206 if (((SPEventContextClass *) parent_class)->setup)
207 ((SPEventContextClass *) parent_class)->setup(ec);
209 ddc->accumulated = sp_curve_new_sized(32);
210 ddc->currentcurve = sp_curve_new_sized(4);
212 ddc->cal1 = sp_curve_new_sized(32);
213 ddc->cal2 = sp_curve_new_sized(32);
215 ddc->currentshape = sp_canvas_item_new(sp_desktop_sketch(ec->desktop), SP_TYPE_CANVAS_BPATH, NULL);
216 sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(ddc->currentshape), DDC_RED_RGBA, SP_WIND_RULE_EVENODD);
217 sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(ddc->currentshape), 0x00000000, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
218 /* fixme: Cannot we cascade it to root more clearly? */
219 g_signal_connect(G_OBJECT(ddc->currentshape), "event", G_CALLBACK(sp_desktop_root_handler), ec->desktop);
221 sp_event_context_read(ec, "mass");
222 sp_event_context_read(ec, "drag");
223 sp_event_context_read(ec, "angle");
224 sp_event_context_read(ec, "width");
225 sp_event_context_read(ec, "thinning");
226 sp_event_context_read(ec, "tremor");
227 sp_event_context_read(ec, "flatness");
228 sp_event_context_read(ec, "usepressure");
229 sp_event_context_read(ec, "usetilt");
230 sp_event_context_read(ec, "abs_width");
231 sp_event_context_read(ec, "keep_selected");
232 sp_event_context_read(ec, "cap_rounding");
234 ddc->is_drawing = false;
236 ddc->_message_context = new Inkscape::MessageContext((ec->desktop)->messageStack());
237 }
239 static void
240 sp_dyna_draw_context_set(SPEventContext *ec, gchar const *key, gchar const *val)
241 {
242 SPDynaDrawContext *ddc = SP_DYNA_DRAW_CONTEXT(ec);
244 if (!strcmp(key, "mass")) {
245 double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.2 );
246 ddc->mass = CLAMP(dval, -1000.0, 1000.0);
247 } else if (!strcmp(key, "drag")) {
248 double const dval = ( val ? g_ascii_strtod (val, NULL) : DRAG_DEFAULT );
249 ddc->drag = CLAMP(dval, DRAG_MIN, DRAG_MAX);
250 } else if (!strcmp(key, "angle")) {
251 double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.0);
252 ddc->angle = CLAMP (dval, -90, 90);
253 } else if (!strcmp(key, "width")) {
254 double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.1 );
255 ddc->width = CLAMP(dval, -1000.0, 1000.0);
256 } else if (!strcmp(key, "thinning")) {
257 double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.1 );
258 ddc->vel_thin = CLAMP(dval, -1.0, 1.0);
259 } else if (!strcmp(key, "tremor")) {
260 double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.0 );
261 ddc->tremor = CLAMP(dval, 0.0, 1.0);
262 } else if (!strcmp(key, "flatness")) {
263 double const dval = ( val ? g_ascii_strtod (val, NULL) : 1.0 );
264 ddc->flatness = CLAMP(dval, 0, 1.0);
265 } else if (!strcmp(key, "usepressure")) {
266 ddc->usepressure = (val && strcmp(val, "0"));
267 } else if (!strcmp(key, "usetilt")) {
268 ddc->usetilt = (val && strcmp(val, "0"));
269 } else if (!strcmp(key, "abs_width")) {
270 ddc->abs_width = (val && strcmp(val, "0"));
271 } else if (!strcmp(key, "keep_selected")) {
272 ddc->keep_selected = (val && strcmp(val, "0"));
273 } else if (!strcmp(key, "cap_rounding")) {
274 ddc->cap_rounding = ( val ? g_ascii_strtod (val, NULL) : 0.0 );
275 }
277 //g_print("DDC: %g %g %g %g\n", ddc->mass, ddc->drag, ddc->angle, ddc->width);
278 }
280 static double
281 flerp(double f0, double f1, double p)
282 {
283 return f0 + ( f1 - f0 ) * p;
284 }
286 /* Get normalized point */
287 static NR::Point
288 sp_dyna_draw_get_npoint(SPDynaDrawContext const *dc, NR::Point v)
289 {
290 NR::Rect drect = SP_EVENT_CONTEXT(dc)->desktop->get_display_area();
291 double const max = MAX ( drect.dimensions()[NR::X], drect.dimensions()[NR::Y] );
292 return NR::Point(( v[NR::X] - drect.min()[NR::X] ) / max, ( v[NR::Y] - drect.min()[NR::Y] ) / max);
293 }
295 /* Get view point */
296 static NR::Point
297 sp_dyna_draw_get_vpoint(SPDynaDrawContext const *dc, NR::Point n)
298 {
299 NR::Rect drect = SP_EVENT_CONTEXT(dc)->desktop->get_display_area();
300 double const max = MAX ( drect.dimensions()[NR::X], drect.dimensions()[NR::Y] );
301 return NR::Point(n[NR::X] * max + drect.min()[NR::X], n[NR::Y] * max + drect.min()[NR::Y]);
302 }
304 static void
305 sp_dyna_draw_reset(SPDynaDrawContext *dc, NR::Point p)
306 {
307 dc->last = dc->cur = sp_dyna_draw_get_npoint(dc, p);
308 dc->vel = NR::Point(0,0);
309 dc->acc = NR::Point(0,0);
310 dc->ang = NR::Point(0,0);
311 dc->del = NR::Point(0,0);
312 }
314 static void
315 sp_dyna_draw_extinput(SPDynaDrawContext *dc, GdkEvent *event)
316 {
317 if (gdk_event_get_axis (event, GDK_AXIS_PRESSURE, &dc->pressure))
318 dc->pressure = CLAMP (dc->pressure, DDC_MIN_PRESSURE, DDC_MAX_PRESSURE);
319 else
320 dc->pressure = DDC_DEFAULT_PRESSURE;
322 if (gdk_event_get_axis (event, GDK_AXIS_XTILT, &dc->xtilt))
323 dc->xtilt = CLAMP (dc->xtilt, DDC_MIN_TILT, DDC_MAX_TILT);
324 else
325 dc->xtilt = DDC_DEFAULT_TILT;
327 if (gdk_event_get_axis (event, GDK_AXIS_YTILT, &dc->ytilt))
328 dc->ytilt = CLAMP (dc->ytilt, DDC_MIN_TILT, DDC_MAX_TILT);
329 else
330 dc->ytilt = DDC_DEFAULT_TILT;
331 }
334 static gboolean
335 sp_dyna_draw_apply(SPDynaDrawContext *dc, NR::Point p)
336 {
337 NR::Point n = sp_dyna_draw_get_npoint(dc, p);
339 /* Calculate mass and drag */
340 double const mass = flerp(1.0, 160.0, dc->mass);
341 double const drag = flerp(0.0, 0.5, dc->drag * dc->drag);
343 /* Calculate force and acceleration */
344 NR::Point force = n - dc->cur;
345 if ( NR::L2(force) < DYNA_EPSILON ) {
346 return FALSE;
347 }
349 dc->acc = force / mass;
351 /* Calculate new velocity */
352 dc->vel += dc->acc;
354 /* Calculate angle of drawing tool */
356 double a1;
357 if (dc->usetilt) {
358 // 1a. calculate nib angle from input device tilt:
359 gdouble length = std::sqrt(dc->xtilt*dc->xtilt + dc->ytilt*dc->ytilt);;
361 if (length > 0) {
362 NR::Point ang1 = NR::Point(dc->ytilt/length, dc->xtilt/length);
363 a1 = atan2(ang1);
364 }
365 else
366 a1 = 0.0;
367 }
368 else {
369 // 1b. fixed dc->angle (absolutely flat nib):
370 double const radians = ( (dc->angle - 90) / 180.0 ) * M_PI;
371 NR::Point ang1 = NR::Point(-sin(radians), cos(radians));
372 a1 = atan2(ang1);
373 }
375 // 2. perpendicular to dc->vel (absolutely non-flat nib):
376 gdouble const mag_vel = NR::L2(dc->vel);
377 if ( mag_vel < DYNA_EPSILON ) {
378 return FALSE;
379 }
380 NR::Point ang2 = NR::rot90(dc->vel) / mag_vel;
382 // 3. Average them using flatness parameter:
383 // calculate angles
384 double a2 = atan2(ang2);
385 // flip a2 to force it to be in the same half-circle as a1
386 bool flipped = false;
387 if (fabs (a2-a1) > 0.5*M_PI) {
388 a2 += M_PI;
389 flipped = true;
390 }
391 // normalize a2
392 if (a2 > M_PI)
393 a2 -= 2*M_PI;
394 if (a2 < -M_PI)
395 a2 += 2*M_PI;
396 // find the flatness-weighted bisector angle, unflip if a2 was flipped
397 // FIXME: when dc->vel is oscillating around the fixed angle, the new_ang flips back and forth. How to avoid this?
398 double new_ang = a1 + (1 - dc->flatness) * (a2 - a1) - (flipped? M_PI : 0);
399 // convert to point
400 dc->ang = NR::Point (cos (new_ang), sin (new_ang));
402 /* Apply drag */
403 dc->vel *= 1.0 - drag;
405 /* Update position */
406 dc->last = dc->cur;
407 dc->cur += dc->vel;
409 return TRUE;
410 }
412 static void
413 sp_dyna_draw_brush(SPDynaDrawContext *dc)
414 {
415 g_assert( dc->npoints >= 0 && dc->npoints < SAMPLING_SIZE );
417 // How much velocity thins strokestyle
418 double vel_thin = flerp (0, 160, dc->vel_thin);
420 // Influence of pressure on thickness
421 double pressure_thick = (dc->usepressure ? dc->pressure : 1.0);
423 double width = ( pressure_thick - vel_thin * NR::L2(dc->vel) ) * dc->width;
425 double tremble_left = 0, tremble_right = 0;
426 if (dc->tremor > 0) {
427 // obtain two normally distributed random variables, using polar Box-Muller transform
428 double x1, x2, w, y1, y2;
429 do {
430 x1 = 2.0 * g_random_double_range(0,1) - 1.0;
431 x2 = 2.0 * g_random_double_range(0,1) - 1.0;
432 w = x1 * x1 + x2 * x2;
433 } while ( w >= 1.0 );
434 w = sqrt( (-2.0 * log( w ) ) / w );
435 y1 = x1 * w;
436 y2 = x2 * w;
438 // deflect both left and right edges randomly and independently, so that:
439 // (1) dc->tremor=1 corresponds to sigma=1, decreasing dc->tremor narrows the bell curve;
440 // (2) deflection depends on width, but is upped for small widths for better visual uniformity across widths;
441 // (3) deflection somewhat depends on speed, to prevent fast strokes looking
442 // comparatively smooth and slow ones excessively jittery
443 tremble_left = (y1)*dc->tremor * (0.15 + 0.8*width) * (0.35 + 14*NR::L2(dc->vel));
444 tremble_right = (y2)*dc->tremor * (0.15 + 0.8*width) * (0.35 + 14*NR::L2(dc->vel));
445 }
447 if ( width < 0.02 * dc->width ) {
448 width = 0.02 * dc->width;
449 }
451 double dezoomify_factor = 0.05 * 1000;
452 if (!dc->abs_width) {
453 dezoomify_factor /= SP_EVENT_CONTEXT(dc)->desktop->current_zoom();
454 }
456 NR::Point del_left = dezoomify_factor * (width + tremble_left) * dc->ang;
457 NR::Point del_right = dezoomify_factor * (width + tremble_right) * dc->ang;
459 NR::Point abs_middle = sp_dyna_draw_get_vpoint(dc, dc->cur);
461 dc->point1[dc->npoints] = abs_middle + del_left;
462 dc->point2[dc->npoints] = abs_middle - del_right;
464 dc->del = 0.5*(del_left + del_right);
466 dc->npoints++;
467 }
469 void
470 sp_ddc_update_toolbox (SPDesktop *desktop, const gchar *id, double value)
471 {
472 desktop->setToolboxAdjustmentValue (id, value);
473 }
475 gint
476 sp_dyna_draw_context_root_handler(SPEventContext *event_context,
477 GdkEvent *event)
478 {
479 SPDynaDrawContext *dc = SP_DYNA_DRAW_CONTEXT(event_context);
480 SPDesktop *desktop = event_context->desktop;
482 gint ret = FALSE;
484 switch (event->type) {
485 case GDK_BUTTON_PRESS:
486 if ( event->button.button == 1 ) {
488 SPDesktop *desktop = SP_EVENT_CONTEXT_DESKTOP(dc);
490 if (Inkscape::have_viable_layer(desktop, dc->_message_context) == false) {
491 return TRUE;
492 }
494 NR::Point const button_w(event->button.x,
495 event->button.y);
496 NR::Point const button_dt(desktop->w2d(button_w));
497 sp_dyna_draw_reset(dc, button_dt);
498 sp_dyna_draw_extinput(dc, event);
499 sp_dyna_draw_apply(dc, button_dt);
500 sp_curve_reset(dc->accumulated);
501 if (dc->repr) {
502 dc->repr = NULL;
503 }
505 /* initialize first point */
506 dc->npoints = 0;
508 sp_canvas_item_grab(SP_CANVAS_ITEM(desktop->acetate),
509 ( GDK_KEY_PRESS_MASK |
510 GDK_BUTTON_RELEASE_MASK |
511 GDK_POINTER_MOTION_MASK |
512 GDK_BUTTON_PRESS_MASK ),
513 NULL,
514 event->button.time);
516 ret = TRUE;
518 dc->is_drawing = true;
519 }
520 break;
521 case GDK_MOTION_NOTIFY:
522 if ( dc->is_drawing && ( event->motion.state & GDK_BUTTON1_MASK ) ) {
523 dc->dragging = TRUE;
525 NR::Point const motion_w(event->motion.x,
526 event->motion.y);
527 NR::Point const motion_dt(desktop->w2d(motion_w));
529 sp_dyna_draw_extinput(dc, event);
530 if (!sp_dyna_draw_apply(dc, motion_dt)) {
531 ret = TRUE;
532 break;
533 }
535 if ( dc->cur != dc->last ) {
536 sp_dyna_draw_brush(dc);
537 g_assert( dc->npoints > 0 );
538 fit_and_split(dc, FALSE);
539 }
540 ret = TRUE;
541 }
542 break;
544 case GDK_BUTTON_RELEASE:
545 sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate), event->button.time);
546 dc->is_drawing = false;
547 if ( dc->dragging && event->button.button == 1 ) {
548 dc->dragging = FALSE;
550 /* Remove all temporary line segments */
551 while (dc->segments) {
552 gtk_object_destroy(GTK_OBJECT(dc->segments->data));
553 dc->segments = g_slist_remove(dc->segments, dc->segments->data);
554 }
555 /* Create object */
556 fit_and_split(dc, TRUE);
557 accumulate_calligraphic(dc);
558 set_to_accumulated(dc); /* temporal implementation */
559 /* reset accumulated curve */
560 sp_curve_reset(dc->accumulated);
561 clear_current(dc);
562 if (dc->repr) {
563 dc->repr = NULL;
564 }
565 ret = TRUE;
566 }
567 break;
568 case GDK_KEY_PRESS:
569 switch (get_group0_keyval (&event->key)) {
570 case GDK_Up:
571 case GDK_KP_Up:
572 if (!MOD__CTRL_ONLY) {
573 dc->angle += 5.0;
574 if (dc->angle > 90.0)
575 dc->angle = 90.0;
576 sp_ddc_update_toolbox (desktop, "calligraphy-angle", dc->angle);
577 ret = TRUE;
578 }
579 break;
580 case GDK_Down:
581 case GDK_KP_Down:
582 if (!MOD__CTRL_ONLY) {
583 dc->angle -= 5.0;
584 if (dc->angle < -90.0)
585 dc->angle = -90.0;
586 sp_ddc_update_toolbox (desktop, "calligraphy-angle", dc->angle);
587 ret = TRUE;
588 }
589 break;
590 case GDK_Right:
591 case GDK_KP_Right:
592 if (!MOD__CTRL_ONLY) {
593 dc->width += 0.01;
594 if (dc->width > 1.0)
595 dc->width = 1.0;
596 sp_ddc_update_toolbox (desktop, "altx-calligraphy", dc->width * 100); // the same spinbutton is for alt+x
597 ret = TRUE;
598 }
599 break;
600 case GDK_Left:
601 case GDK_KP_Left:
602 if (!MOD__CTRL_ONLY) {
603 dc->width -= 0.01;
604 if (dc->width < 0.01)
605 dc->width = 0.01;
606 sp_ddc_update_toolbox (desktop, "altx-calligraphy", dc->width * 100);
607 ret = TRUE;
608 }
609 break;
610 case GDK_x:
611 case GDK_X:
612 if (MOD__ALT_ONLY) {
613 desktop->setToolboxFocusTo ("altx-calligraphy");
614 ret = TRUE;
615 }
616 break;
617 case GDK_Escape:
618 sp_desktop_selection(desktop)->clear();
619 break;
621 default:
622 break;
623 }
624 default:
625 break;
626 }
628 if (!ret) {
629 if (((SPEventContextClass *) parent_class)->root_handler) {
630 ret = ((SPEventContextClass *) parent_class)->root_handler(event_context, event);
631 }
632 }
634 return ret;
635 }
638 static void
639 clear_current(SPDynaDrawContext *dc)
640 {
641 /* reset bpath */
642 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), NULL);
643 /* reset curve */
644 sp_curve_reset(dc->currentcurve);
645 sp_curve_reset(dc->cal1);
646 sp_curve_reset(dc->cal2);
647 /* reset points */
648 dc->npoints = 0;
649 }
651 static void
652 set_to_accumulated(SPDynaDrawContext *dc)
653 {
654 SPDesktop *desktop = SP_EVENT_CONTEXT(dc)->desktop;
656 if (!sp_curve_empty(dc->accumulated)) {
657 NArtBpath *abp;
658 gchar *str;
660 if (!dc->repr) {
661 /* Create object */
662 Inkscape::XML::Node *repr = sp_repr_new("svg:path");
664 /* Set style */
665 sp_desktop_apply_style_tool (desktop, repr, "tools.calligraphic", false);
667 dc->repr = repr;
669 SPItem *item=SP_ITEM(desktop->currentLayer()->appendChildRepr(dc->repr));
670 Inkscape::GC::release(dc->repr);
671 item->transform = SP_ITEM(desktop->currentRoot())->getRelativeTransform(desktop->currentLayer());
672 item->updateRepr();
673 if (dc->keep_selected) {
674 sp_desktop_selection(desktop)->set(dc->repr);
675 } else {
676 sp_desktop_selection(desktop)->clear();
677 }
678 }
679 abp = nr_artpath_affine(sp_curve_first_bpath(dc->accumulated), sp_desktop_dt2root_affine(desktop));
680 str = sp_svg_write_path(abp);
681 g_assert( str != NULL );
682 g_free(abp);
683 dc->repr->setAttribute("d", str);
684 g_free(str);
685 } else {
686 if (dc->repr) {
687 sp_repr_unparent(dc->repr);
688 }
689 dc->repr = NULL;
690 }
692 sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_CALLIGRAPHIC,
693 /* TODO: annotate */ "dyna-draw-context.cpp:689");
694 }
696 static void
697 add_cap(SPCurve *curve, NR::Point const &from, NR::Point const &to,
698 double rounding)
699 {
700 NR::Point vec = rounding * NR::rot90( ( to - from ) / sqrt(2.0) );
702 if ( NR::L2(vec) > DYNA_EPSILON ) {
703 sp_curve_curveto(curve, from + vec, to + vec, to);
704 }
705 }
707 static void
708 accumulate_calligraphic(SPDynaDrawContext *dc)
709 {
710 if ( !sp_curve_empty(dc->cal1) && !sp_curve_empty(dc->cal2) ) {
711 sp_curve_reset(dc->accumulated); /* Is this required ?? */
712 SPCurve *rev_cal2 = sp_curve_reverse(dc->cal2);
713 sp_curve_append(dc->accumulated, dc->cal1, FALSE);
714 add_cap(dc->accumulated, sp_curve_last_point(dc->cal1), sp_curve_first_point(rev_cal2), dc->cap_rounding);
715 sp_curve_append(dc->accumulated, rev_cal2, TRUE);
716 add_cap(dc->accumulated, sp_curve_last_point(rev_cal2), sp_curve_first_point(dc->cal1), dc->cap_rounding);
717 sp_curve_closepath(dc->accumulated);
719 sp_curve_unref(rev_cal2);
721 sp_curve_reset(dc->cal1);
722 sp_curve_reset(dc->cal2);
723 }
724 }
726 static void
727 fit_and_split(SPDynaDrawContext *dc,
728 gboolean release)
729 {
730 fit_and_split_calligraphics(dc, release);
731 }
733 static double square(double const x)
734 {
735 return x * x;
736 }
738 static void
739 fit_and_split_calligraphics(SPDynaDrawContext *dc, gboolean release)
740 {
741 double const tolerance_sq = square( NR::expansion(SP_EVENT_CONTEXT(dc)->desktop->w2d()) * TOLERANCE_CALLIGRAPHIC );
743 #ifdef DYNA_DRAW_VERBOSE
744 g_print("[F&S:R=%c]", release?'T':'F');
745 #endif
747 if (!( dc->npoints > 0 && dc->npoints < SAMPLING_SIZE ))
748 return; // just clicked
750 if ( dc->npoints == SAMPLING_SIZE - 1 || release ) {
751 #define BEZIER_SIZE 4
752 #define BEZIER_MAX_BEZIERS 8
753 #define BEZIER_MAX_LENGTH ( BEZIER_SIZE * BEZIER_MAX_BEZIERS )
755 #ifdef DYNA_DRAW_VERBOSE
756 g_print("[F&S:#] dc->npoints:%d, release:%s\n",
757 dc->npoints, release ? "TRUE" : "FALSE");
758 #endif
760 /* Current calligraphic */
761 if ( dc->cal1->end == 0 || dc->cal2->end == 0 ) {
762 /* dc->npoints > 0 */
763 /* g_print("calligraphics(1|2) reset\n"); */
764 sp_curve_reset(dc->cal1);
765 sp_curve_reset(dc->cal2);
767 sp_curve_moveto(dc->cal1, dc->point1[0]);
768 sp_curve_moveto(dc->cal2, dc->point2[0]);
769 }
771 NR::Point b1[BEZIER_MAX_LENGTH];
772 gint const nb1 = sp_bezier_fit_cubic_r(b1, dc->point1, dc->npoints,
773 tolerance_sq, BEZIER_MAX_BEZIERS);
774 g_assert( nb1 * BEZIER_SIZE <= gint(G_N_ELEMENTS(b1)) );
776 NR::Point b2[BEZIER_MAX_LENGTH];
777 gint const nb2 = sp_bezier_fit_cubic_r(b2, dc->point2, dc->npoints,
778 tolerance_sq, BEZIER_MAX_BEZIERS);
779 g_assert( nb2 * BEZIER_SIZE <= gint(G_N_ELEMENTS(b2)) );
781 if ( nb1 != -1 && nb2 != -1 ) {
782 /* Fit and draw and reset state */
783 #ifdef DYNA_DRAW_VERBOSE
784 g_print("nb1:%d nb2:%d\n", nb1, nb2);
785 #endif
786 /* CanvasShape */
787 if (! release) {
788 sp_curve_reset(dc->currentcurve);
789 sp_curve_moveto(dc->currentcurve, b1[0]);
790 for (NR::Point *bp1 = b1; bp1 < b1 + BEZIER_SIZE * nb1; bp1 += BEZIER_SIZE) {
791 sp_curve_curveto(dc->currentcurve, bp1[1],
792 bp1[2], bp1[3]);
793 }
794 sp_curve_lineto(dc->currentcurve,
795 b2[BEZIER_SIZE*(nb2-1) + 3]);
796 for (NR::Point *bp2 = b2 + BEZIER_SIZE * ( nb2 - 1 ); bp2 >= b2; bp2 -= BEZIER_SIZE) {
797 sp_curve_curveto(dc->currentcurve, bp2[2], bp2[1], bp2[0]);
798 }
799 sp_curve_closepath(dc->currentcurve);
800 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), dc->currentcurve);
801 }
803 /* Current calligraphic */
804 for (NR::Point *bp1 = b1; bp1 < b1 + BEZIER_SIZE * nb1; bp1 += BEZIER_SIZE) {
805 sp_curve_curveto(dc->cal1, bp1[1], bp1[2], bp1[3]);
806 }
807 for (NR::Point *bp2 = b2; bp2 < b2 + BEZIER_SIZE * nb2; bp2 += BEZIER_SIZE) {
808 sp_curve_curveto(dc->cal2, bp2[1], bp2[2], bp2[3]);
809 }
810 } else {
811 /* fixme: ??? */
812 #ifdef DYNA_DRAW_VERBOSE
813 g_print("[fit_and_split_calligraphics] failed to fit-cubic.\n");
814 #endif
815 draw_temporary_box(dc);
817 for (gint i = 1; i < dc->npoints; i++) {
818 sp_curve_lineto(dc->cal1, dc->point1[i]);
819 }
820 for (gint i = 1; i < dc->npoints; i++) {
821 sp_curve_lineto(dc->cal2, dc->point2[i]);
822 }
823 }
825 /* Fit and draw and copy last point */
826 #ifdef DYNA_DRAW_VERBOSE
827 g_print("[%d]Yup\n", dc->npoints);
828 #endif
829 if (!release) {
830 g_assert(!sp_curve_empty(dc->currentcurve));
832 SPCanvasItem *cbp = sp_canvas_item_new(sp_desktop_sketch(SP_EVENT_CONTEXT(dc)->desktop),
833 SP_TYPE_CANVAS_BPATH,
834 NULL);
835 SPCurve *curve = sp_curve_copy(dc->currentcurve);
836 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH (cbp), curve);
837 sp_curve_unref(curve);
839 guint32 fillColor = sp_desktop_get_color_tool (SP_ACTIVE_DESKTOP, "tools.calligraphic", true);
840 //guint32 strokeColor = sp_desktop_get_color_tool (SP_ACTIVE_DESKTOP, "tools.calligraphic", false);
841 double opacity = sp_desktop_get_master_opacity_tool (SP_ACTIVE_DESKTOP, "tools.calligraphic");
842 double fillOpacity = sp_desktop_get_opacity_tool (SP_ACTIVE_DESKTOP, "tools.calligraphic", true);
843 //double strokeOpacity = sp_desktop_get_opacity_tool (SP_ACTIVE_DESKTOP, "tools.calligraphic", false);
844 sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(cbp), ((fillColor & 0xffffff00) | SP_COLOR_F_TO_U(opacity*fillOpacity)), SP_WIND_RULE_EVENODD);
845 //on second thougtht don't do stroke yet because we don't have stoke-width yet and because stoke appears between segments while drawing
846 //sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(cbp), ((strokeColor & 0xffffff00) | SP_COLOR_F_TO_U(opacity*strokeOpacity)), 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
847 sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(cbp), 0x00000000, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
848 /* fixme: Cannot we cascade it to root more clearly? */
849 g_signal_connect(G_OBJECT(cbp), "event", G_CALLBACK(sp_desktop_root_handler), SP_EVENT_CONTEXT(dc)->desktop);
851 dc->segments = g_slist_prepend(dc->segments, cbp);
852 }
854 dc->point1[0] = dc->point1[dc->npoints - 1];
855 dc->point2[0] = dc->point2[dc->npoints - 1];
856 dc->npoints = 1;
857 } else {
858 draw_temporary_box(dc);
859 }
860 }
862 static void
863 draw_temporary_box(SPDynaDrawContext *dc)
864 {
865 sp_curve_reset(dc->currentcurve);
866 sp_curve_moveto(dc->currentcurve, dc->point1[0]);
867 for (gint i = 1; i < dc->npoints; i++) {
868 sp_curve_lineto(dc->currentcurve, dc->point1[i]);
869 }
870 for (gint i = dc->npoints-1; i >= 0; i--) {
871 sp_curve_lineto(dc->currentcurve, dc->point2[i]);
872 }
873 sp_curve_closepath(dc->currentcurve);
874 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), dc->currentcurve);
875 }
877 /*
878 Local Variables:
879 mode:c++
880 c-file-style:"stroustrup"
881 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
882 indent-tabs-mode:nil
883 fill-column:99
884 End:
885 */
886 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :