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 0.5e-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 add_cap(SPCurve *curve, NR::Point const &from, NR::Point const &to, double rounding);
77 static void accumulate_calligraphic(SPDynaDrawContext *dc);
79 static void fit_and_split(SPDynaDrawContext *ddc, gboolean release);
80 static void fit_and_split_calligraphics(SPDynaDrawContext *ddc, gboolean release);
82 static void sp_dyna_draw_reset(SPDynaDrawContext *ddc, NR::Point p);
83 static NR::Point sp_dyna_draw_get_npoint(SPDynaDrawContext const *ddc, NR::Point v);
84 static NR::Point sp_dyna_draw_get_vpoint(SPDynaDrawContext const *ddc, NR::Point n);
85 static void draw_temporary_box(SPDynaDrawContext *dc);
88 static SPEventContextClass *parent_class;
90 GtkType
91 sp_dyna_draw_context_get_type(void)
92 {
93 static GType type = 0;
94 if (!type) {
95 GTypeInfo info = {
96 sizeof(SPDynaDrawContextClass),
97 NULL, NULL,
98 (GClassInitFunc) sp_dyna_draw_context_class_init,
99 NULL, NULL,
100 sizeof(SPDynaDrawContext),
101 4,
102 (GInstanceInitFunc) sp_dyna_draw_context_init,
103 NULL, /* value_table */
104 };
105 type = g_type_register_static(SP_TYPE_EVENT_CONTEXT, "SPDynaDrawContext", &info, (GTypeFlags)0);
106 }
107 return type;
108 }
110 static void
111 sp_dyna_draw_context_class_init(SPDynaDrawContextClass *klass)
112 {
113 GObjectClass *object_class = (GObjectClass *) klass;
114 SPEventContextClass *event_context_class = (SPEventContextClass *) klass;
116 parent_class = (SPEventContextClass*)g_type_class_peek_parent(klass);
118 object_class->dispose = sp_dyna_draw_context_dispose;
120 event_context_class->setup = sp_dyna_draw_context_setup;
121 event_context_class->set = sp_dyna_draw_context_set;
122 event_context_class->root_handler = sp_dyna_draw_context_root_handler;
123 }
125 static void
126 sp_dyna_draw_context_init(SPDynaDrawContext *ddc)
127 {
128 SPEventContext *event_context = SP_EVENT_CONTEXT(ddc);
130 event_context->cursor_shape = cursor_calligraphy_xpm;
131 event_context->cursor_pixbuf = gdk_pixbuf_new_from_inline(
132 -1,
133 cursor_calligraphy_pixbuf,
134 FALSE,
135 NULL);
136 event_context->hot_x = 4;
137 event_context->hot_y = 4;
139 ddc->accumulated = NULL;
140 ddc->segments = NULL;
141 ddc->currentcurve = NULL;
142 ddc->currentshape = NULL;
143 ddc->npoints = 0;
144 ddc->cal1 = NULL;
145 ddc->cal2 = NULL;
146 ddc->repr = NULL;
148 /* DynaDraw values */
149 ddc->cur = NR::Point(0,0);
150 ddc->last = NR::Point(0,0);
151 ddc->vel = NR::Point(0,0);
152 ddc->acc = NR::Point(0,0);
153 ddc->ang = NR::Point(0,0);
154 ddc->del = NR::Point(0,0);
156 /* attributes */
157 ddc->dragging = FALSE;
159 ddc->mass = 0.3;
160 ddc->drag = DRAG_DEFAULT;
161 ddc->angle = 30.0;
162 ddc->width = 0.2;
164 ddc->vel_thin = 0.1;
165 ddc->flatness = 0.9;
166 ddc->cap_rounding = 0.0;
168 ddc->abs_width = false;
169 ddc->keep_selected = true;
170 }
172 static void
173 sp_dyna_draw_context_dispose(GObject *object)
174 {
175 SPDynaDrawContext *ddc = SP_DYNA_DRAW_CONTEXT(object);
177 if (ddc->accumulated) {
178 ddc->accumulated = sp_curve_unref(ddc->accumulated);
179 }
181 while (ddc->segments) {
182 gtk_object_destroy(GTK_OBJECT(ddc->segments->data));
183 ddc->segments = g_slist_remove(ddc->segments, ddc->segments->data);
184 }
186 if (ddc->currentcurve) ddc->currentcurve = sp_curve_unref(ddc->currentcurve);
187 if (ddc->cal1) ddc->cal1 = sp_curve_unref(ddc->cal1);
188 if (ddc->cal2) ddc->cal2 = sp_curve_unref(ddc->cal2);
190 if (ddc->currentshape) {
191 gtk_object_destroy(GTK_OBJECT(ddc->currentshape));
192 ddc->currentshape = NULL;
193 }
195 if (ddc->_message_context) {
196 delete ddc->_message_context;
197 }
199 G_OBJECT_CLASS(parent_class)->dispose(object);
200 }
202 static void
203 sp_dyna_draw_context_setup(SPEventContext *ec)
204 {
205 SPDynaDrawContext *ddc = SP_DYNA_DRAW_CONTEXT(ec);
207 if (((SPEventContextClass *) parent_class)->setup)
208 ((SPEventContextClass *) parent_class)->setup(ec);
210 ddc->accumulated = sp_curve_new_sized(32);
211 ddc->currentcurve = sp_curve_new_sized(4);
213 ddc->cal1 = sp_curve_new_sized(32);
214 ddc->cal2 = sp_curve_new_sized(32);
216 ddc->currentshape = sp_canvas_item_new(sp_desktop_sketch(ec->desktop), SP_TYPE_CANVAS_BPATH, NULL);
217 sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(ddc->currentshape), DDC_RED_RGBA, SP_WIND_RULE_EVENODD);
218 sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(ddc->currentshape), 0x00000000, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
219 /* fixme: Cannot we cascade it to root more clearly? */
220 g_signal_connect(G_OBJECT(ddc->currentshape), "event", G_CALLBACK(sp_desktop_root_handler), ec->desktop);
222 sp_event_context_read(ec, "mass");
223 sp_event_context_read(ec, "drag");
224 sp_event_context_read(ec, "angle");
225 sp_event_context_read(ec, "width");
226 sp_event_context_read(ec, "thinning");
227 sp_event_context_read(ec, "tremor");
228 sp_event_context_read(ec, "flatness");
229 sp_event_context_read(ec, "usepressure");
230 sp_event_context_read(ec, "usetilt");
231 sp_event_context_read(ec, "abs_width");
232 sp_event_context_read(ec, "keep_selected");
233 sp_event_context_read(ec, "cap_rounding");
235 ddc->is_drawing = false;
237 ddc->_message_context = new Inkscape::MessageContext((ec->desktop)->messageStack());
238 }
240 static void
241 sp_dyna_draw_context_set(SPEventContext *ec, gchar const *key, gchar const *val)
242 {
243 SPDynaDrawContext *ddc = SP_DYNA_DRAW_CONTEXT(ec);
245 if (!strcmp(key, "mass")) {
246 double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.2 );
247 ddc->mass = CLAMP(dval, -1000.0, 1000.0);
248 } else if (!strcmp(key, "drag")) {
249 double const dval = ( val ? g_ascii_strtod (val, NULL) : DRAG_DEFAULT );
250 ddc->drag = CLAMP(dval, DRAG_MIN, DRAG_MAX);
251 } else if (!strcmp(key, "angle")) {
252 double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.0);
253 ddc->angle = CLAMP (dval, -90, 90);
254 } else if (!strcmp(key, "width")) {
255 double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.1 );
256 ddc->width = CLAMP(dval, -1000.0, 1000.0);
257 } else if (!strcmp(key, "thinning")) {
258 double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.1 );
259 ddc->vel_thin = CLAMP(dval, -1.0, 1.0);
260 } else if (!strcmp(key, "tremor")) {
261 double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.0 );
262 ddc->tremor = CLAMP(dval, 0.0, 1.0);
263 } else if (!strcmp(key, "flatness")) {
264 double const dval = ( val ? g_ascii_strtod (val, NULL) : 1.0 );
265 ddc->flatness = CLAMP(dval, 0, 1.0);
266 } else if (!strcmp(key, "usepressure")) {
267 ddc->usepressure = (val && strcmp(val, "0"));
268 } else if (!strcmp(key, "usetilt")) {
269 ddc->usetilt = (val && strcmp(val, "0"));
270 } else if (!strcmp(key, "abs_width")) {
271 ddc->abs_width = (val && strcmp(val, "0"));
272 } else if (!strcmp(key, "keep_selected")) {
273 ddc->keep_selected = (val && strcmp(val, "0"));
274 } else if (!strcmp(key, "cap_rounding")) {
275 ddc->cap_rounding = ( val ? g_ascii_strtod (val, NULL) : 0.0 );
276 }
278 //g_print("DDC: %g %g %g %g\n", ddc->mass, ddc->drag, ddc->angle, ddc->width);
279 }
281 static double
282 flerp(double f0, double f1, double p)
283 {
284 return f0 + ( f1 - f0 ) * p;
285 }
287 /* Get normalized point */
288 static NR::Point
289 sp_dyna_draw_get_npoint(SPDynaDrawContext const *dc, NR::Point v)
290 {
291 NR::Rect drect = SP_EVENT_CONTEXT(dc)->desktop->get_display_area();
292 double const max = MAX ( drect.dimensions()[NR::X], drect.dimensions()[NR::Y] );
293 return NR::Point(( v[NR::X] - drect.min()[NR::X] ) / max, ( v[NR::Y] - drect.min()[NR::Y] ) / max);
294 }
296 /* Get view point */
297 static NR::Point
298 sp_dyna_draw_get_vpoint(SPDynaDrawContext const *dc, NR::Point n)
299 {
300 NR::Rect drect = SP_EVENT_CONTEXT(dc)->desktop->get_display_area();
301 double const max = MAX ( drect.dimensions()[NR::X], drect.dimensions()[NR::Y] );
302 return NR::Point(n[NR::X] * max + drect.min()[NR::X], n[NR::Y] * max + drect.min()[NR::Y]);
303 }
305 static void
306 sp_dyna_draw_reset(SPDynaDrawContext *dc, NR::Point p)
307 {
308 dc->last = dc->cur = sp_dyna_draw_get_npoint(dc, p);
309 dc->vel = NR::Point(0,0);
310 dc->acc = NR::Point(0,0);
311 dc->ang = NR::Point(0,0);
312 dc->del = NR::Point(0,0);
313 }
315 static void
316 sp_dyna_draw_extinput(SPDynaDrawContext *dc, GdkEvent *event)
317 {
318 if (gdk_event_get_axis (event, GDK_AXIS_PRESSURE, &dc->pressure))
319 dc->pressure = CLAMP (dc->pressure, DDC_MIN_PRESSURE, DDC_MAX_PRESSURE);
320 else
321 dc->pressure = DDC_DEFAULT_PRESSURE;
323 if (gdk_event_get_axis (event, GDK_AXIS_XTILT, &dc->xtilt))
324 dc->xtilt = CLAMP (dc->xtilt, DDC_MIN_TILT, DDC_MAX_TILT);
325 else
326 dc->xtilt = DDC_DEFAULT_TILT;
328 if (gdk_event_get_axis (event, GDK_AXIS_YTILT, &dc->ytilt))
329 dc->ytilt = CLAMP (dc->ytilt, DDC_MIN_TILT, DDC_MAX_TILT);
330 else
331 dc->ytilt = DDC_DEFAULT_TILT;
332 }
335 static gboolean
336 sp_dyna_draw_apply(SPDynaDrawContext *dc, NR::Point p)
337 {
338 NR::Point n = sp_dyna_draw_get_npoint(dc, p);
340 /* Calculate mass and drag */
341 double const mass = flerp(1.0, 160.0, dc->mass);
342 double const drag = flerp(0.0, 0.5, dc->drag * dc->drag);
344 /* Calculate force and acceleration */
345 NR::Point force = n - dc->cur;
346 if ( NR::L2(force) < DYNA_EPSILON ) {
347 return FALSE;
348 }
350 dc->acc = force / mass;
352 /* Calculate new velocity */
353 dc->vel += dc->acc;
355 /* Calculate angle of drawing tool */
357 double a1;
358 if (dc->usetilt) {
359 // 1a. calculate nib angle from input device tilt:
360 gdouble length = std::sqrt(dc->xtilt*dc->xtilt + dc->ytilt*dc->ytilt);;
362 if (length > 0) {
363 NR::Point ang1 = NR::Point(dc->ytilt/length, dc->xtilt/length);
364 a1 = atan2(ang1);
365 }
366 else
367 a1 = 0.0;
368 }
369 else {
370 // 1b. fixed dc->angle (absolutely flat nib):
371 double const radians = ( (dc->angle - 90) / 180.0 ) * M_PI;
372 NR::Point ang1 = NR::Point(-sin(radians), cos(radians));
373 a1 = atan2(ang1);
374 }
376 // 2. perpendicular to dc->vel (absolutely non-flat nib):
377 gdouble const mag_vel = NR::L2(dc->vel);
378 if ( mag_vel < DYNA_EPSILON ) {
379 return FALSE;
380 }
381 NR::Point ang2 = NR::rot90(dc->vel) / mag_vel;
383 // 3. Average them using flatness parameter:
384 // calculate angles
385 double a2 = atan2(ang2);
386 // flip a2 to force it to be in the same half-circle as a1
387 bool flipped = false;
388 if (fabs (a2-a1) > 0.5*M_PI) {
389 a2 += M_PI;
390 flipped = true;
391 }
392 // normalize a2
393 if (a2 > M_PI)
394 a2 -= 2*M_PI;
395 if (a2 < -M_PI)
396 a2 += 2*M_PI;
397 // find the flatness-weighted bisector angle, unflip if a2 was flipped
398 // FIXME: when dc->vel is oscillating around the fixed angle, the new_ang flips back and forth. How to avoid this?
399 double new_ang = a1 + (1 - dc->flatness) * (a2 - a1) - (flipped? M_PI : 0);
400 // convert to point
401 dc->ang = NR::Point (cos (new_ang), sin (new_ang));
403 /* Apply drag */
404 dc->vel *= 1.0 - drag;
406 /* Update position */
407 dc->last = dc->cur;
408 dc->cur += dc->vel;
410 return TRUE;
411 }
413 static void
414 sp_dyna_draw_brush(SPDynaDrawContext *dc)
415 {
416 g_assert( dc->npoints >= 0 && dc->npoints < SAMPLING_SIZE );
418 // How much velocity thins strokestyle
419 double vel_thin = flerp (0, 160, dc->vel_thin);
421 // Influence of pressure on thickness
422 double pressure_thick = (dc->usepressure ? dc->pressure : 1.0);
424 double width = ( pressure_thick - vel_thin * NR::L2(dc->vel) ) * dc->width;
426 double tremble_left = 0, tremble_right = 0;
427 if (dc->tremor > 0) {
428 // obtain two normally distributed random variables, using polar Box-Muller transform
429 double x1, x2, w, y1, y2;
430 do {
431 x1 = 2.0 * g_random_double_range(0,1) - 1.0;
432 x2 = 2.0 * g_random_double_range(0,1) - 1.0;
433 w = x1 * x1 + x2 * x2;
434 } while ( w >= 1.0 );
435 w = sqrt( (-2.0 * log( w ) ) / w );
436 y1 = x1 * w;
437 y2 = x2 * w;
439 // deflect both left and right edges randomly and independently, so that:
440 // (1) dc->tremor=1 corresponds to sigma=1, decreasing dc->tremor narrows the bell curve;
441 // (2) deflection depends on width, but is upped for small widths for better visual uniformity across widths;
442 // (3) deflection somewhat depends on speed, to prevent fast strokes looking
443 // comparatively smooth and slow ones excessively jittery
444 tremble_left = (y1)*dc->tremor * (0.15 + 0.8*width) * (0.35 + 14*NR::L2(dc->vel));
445 tremble_right = (y2)*dc->tremor * (0.15 + 0.8*width) * (0.35 + 14*NR::L2(dc->vel));
446 }
448 if ( width < 0.02 * dc->width ) {
449 width = 0.02 * dc->width;
450 }
452 double dezoomify_factor = 0.05 * 1000;
453 if (!dc->abs_width) {
454 dezoomify_factor /= SP_EVENT_CONTEXT(dc)->desktop->current_zoom();
455 }
457 NR::Point del_left = dezoomify_factor * (width + tremble_left) * dc->ang;
458 NR::Point del_right = dezoomify_factor * (width + tremble_right) * dc->ang;
460 NR::Point abs_middle = sp_dyna_draw_get_vpoint(dc, dc->cur);
462 dc->point1[dc->npoints] = abs_middle + del_left;
463 dc->point2[dc->npoints] = abs_middle - del_right;
465 dc->del = 0.5*(del_left + del_right);
467 dc->npoints++;
468 }
470 void
471 sp_ddc_update_toolbox (SPDesktop *desktop, const gchar *id, double value)
472 {
473 desktop->setToolboxAdjustmentValue (id, value);
474 }
476 gint
477 sp_dyna_draw_context_root_handler(SPEventContext *event_context,
478 GdkEvent *event)
479 {
480 SPDynaDrawContext *dc = SP_DYNA_DRAW_CONTEXT(event_context);
481 SPDesktop *desktop = event_context->desktop;
483 gint ret = FALSE;
485 switch (event->type) {
486 case GDK_BUTTON_PRESS:
487 if ( event->button.button == 1 ) {
489 SPDesktop *desktop = SP_EVENT_CONTEXT_DESKTOP(dc);
491 if (Inkscape::have_viable_layer(desktop, dc->_message_context) == false) {
492 return TRUE;
493 }
495 NR::Point const button_w(event->button.x,
496 event->button.y);
497 NR::Point const button_dt(desktop->w2d(button_w));
498 sp_dyna_draw_reset(dc, button_dt);
499 sp_dyna_draw_extinput(dc, event);
500 sp_dyna_draw_apply(dc, button_dt);
501 sp_curve_reset(dc->accumulated);
502 if (dc->repr) {
503 dc->repr = NULL;
504 }
506 /* initialize first point */
507 dc->npoints = 0;
509 sp_canvas_item_grab(SP_CANVAS_ITEM(desktop->acetate),
510 ( GDK_KEY_PRESS_MASK |
511 GDK_BUTTON_RELEASE_MASK |
512 GDK_POINTER_MOTION_MASK |
513 GDK_BUTTON_PRESS_MASK ),
514 NULL,
515 event->button.time);
517 ret = TRUE;
519 dc->is_drawing = true;
520 }
521 break;
522 case GDK_MOTION_NOTIFY:
523 if ( dc->is_drawing && ( event->motion.state & GDK_BUTTON1_MASK ) ) {
524 dc->dragging = TRUE;
526 NR::Point const motion_w(event->motion.x,
527 event->motion.y);
528 NR::Point const motion_dt(desktop->w2d(motion_w));
530 sp_dyna_draw_extinput(dc, event);
531 if (!sp_dyna_draw_apply(dc, motion_dt)) {
532 ret = TRUE;
533 break;
534 }
536 if ( dc->cur != dc->last ) {
537 sp_dyna_draw_brush(dc);
538 g_assert( dc->npoints > 0 );
539 fit_and_split(dc, FALSE);
540 }
541 ret = TRUE;
542 }
543 break;
545 case GDK_BUTTON_RELEASE:
546 sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate), event->button.time);
547 dc->is_drawing = false;
548 if ( dc->dragging && event->button.button == 1 ) {
549 dc->dragging = FALSE;
551 /* Remove all temporary line segments */
552 while (dc->segments) {
553 gtk_object_destroy(GTK_OBJECT(dc->segments->data));
554 dc->segments = g_slist_remove(dc->segments, dc->segments->data);
555 }
556 /* Create object */
557 fit_and_split(dc, TRUE);
558 accumulate_calligraphic(dc);
559 set_to_accumulated(dc); /* temporal implementation */
560 /* reset accumulated curve */
561 sp_curve_reset(dc->accumulated);
562 clear_current(dc);
563 if (dc->repr) {
564 dc->repr = NULL;
565 }
566 ret = TRUE;
567 }
568 break;
569 case GDK_KEY_PRESS:
570 switch (get_group0_keyval (&event->key)) {
571 case GDK_Up:
572 case GDK_KP_Up:
573 if (!MOD__CTRL_ONLY) {
574 dc->angle += 5.0;
575 if (dc->angle > 90.0)
576 dc->angle = 90.0;
577 sp_ddc_update_toolbox (desktop, "calligraphy-angle", dc->angle);
578 ret = TRUE;
579 }
580 break;
581 case GDK_Down:
582 case GDK_KP_Down:
583 if (!MOD__CTRL_ONLY) {
584 dc->angle -= 5.0;
585 if (dc->angle < -90.0)
586 dc->angle = -90.0;
587 sp_ddc_update_toolbox (desktop, "calligraphy-angle", dc->angle);
588 ret = TRUE;
589 }
590 break;
591 case GDK_Right:
592 case GDK_KP_Right:
593 if (!MOD__CTRL_ONLY) {
594 dc->width += 0.01;
595 if (dc->width > 1.0)
596 dc->width = 1.0;
597 sp_ddc_update_toolbox (desktop, "altx-calligraphy", dc->width * 100); // the same spinbutton is for alt+x
598 ret = TRUE;
599 }
600 break;
601 case GDK_Left:
602 case GDK_KP_Left:
603 if (!MOD__CTRL_ONLY) {
604 dc->width -= 0.01;
605 if (dc->width < 0.01)
606 dc->width = 0.01;
607 sp_ddc_update_toolbox (desktop, "altx-calligraphy", dc->width * 100);
608 ret = TRUE;
609 }
610 break;
611 case GDK_x:
612 case GDK_X:
613 if (MOD__ALT_ONLY) {
614 desktop->setToolboxFocusTo ("altx-calligraphy");
615 ret = TRUE;
616 }
617 break;
618 case GDK_Escape:
619 sp_desktop_selection(desktop)->clear();
620 break;
622 default:
623 break;
624 }
625 default:
626 break;
627 }
629 if (!ret) {
630 if (((SPEventContextClass *) parent_class)->root_handler) {
631 ret = ((SPEventContextClass *) parent_class)->root_handler(event_context, event);
632 }
633 }
635 return ret;
636 }
639 static void
640 clear_current(SPDynaDrawContext *dc)
641 {
642 /* reset bpath */
643 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), NULL);
644 /* reset curve */
645 sp_curve_reset(dc->currentcurve);
646 sp_curve_reset(dc->cal1);
647 sp_curve_reset(dc->cal2);
648 /* reset points */
649 dc->npoints = 0;
650 }
652 static void
653 set_to_accumulated(SPDynaDrawContext *dc)
654 {
655 SPDesktop *desktop = SP_EVENT_CONTEXT(dc)->desktop;
657 if (!sp_curve_empty(dc->accumulated)) {
658 NArtBpath *abp;
659 gchar *str;
661 if (!dc->repr) {
662 /* Create object */
663 Inkscape::XML::Node *repr = sp_repr_new("svg:path");
665 /* Set style */
666 sp_desktop_apply_style_tool (desktop, repr, "tools.calligraphic", false);
668 dc->repr = repr;
670 SPItem *item=SP_ITEM(desktop->currentLayer()->appendChildRepr(dc->repr));
671 Inkscape::GC::release(dc->repr);
672 item->transform = SP_ITEM(desktop->currentRoot())->getRelativeTransform(desktop->currentLayer());
673 item->updateRepr();
674 if (dc->keep_selected) {
675 sp_desktop_selection(desktop)->set(dc->repr);
676 } else {
677 sp_desktop_selection(desktop)->clear();
678 }
679 }
680 abp = nr_artpath_affine(sp_curve_first_bpath(dc->accumulated), sp_desktop_dt2root_affine(desktop));
681 str = sp_svg_write_path(abp);
682 g_assert( str != NULL );
683 g_free(abp);
684 dc->repr->setAttribute("d", str);
685 g_free(str);
686 } else {
687 if (dc->repr) {
688 sp_repr_unparent(dc->repr);
689 }
690 dc->repr = NULL;
691 }
693 sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_CALLIGRAPHIC,
694 /* TODO: annotate */ "dyna-draw-context.cpp:689");
695 }
697 static void
698 add_cap(SPCurve *curve, NR::Point const &from, NR::Point const &to,
699 double rounding)
700 {
701 NR::Point vec = rounding * NR::rot90( ( to - from ) / sqrt(2.0) );
703 if ( NR::L2(vec) > DYNA_EPSILON ) {
704 sp_curve_curveto(curve, from + vec, to + vec, to);
705 }
706 }
708 static void
709 accumulate_calligraphic(SPDynaDrawContext *dc)
710 {
711 if ( !sp_curve_empty(dc->cal1) && !sp_curve_empty(dc->cal2) ) {
712 sp_curve_reset(dc->accumulated); /* Is this required ?? */
713 SPCurve *rev_cal2 = sp_curve_reverse(dc->cal2);
714 sp_curve_append(dc->accumulated, dc->cal1, FALSE);
715 add_cap(dc->accumulated, sp_curve_last_point(dc->cal1), sp_curve_first_point(rev_cal2), dc->cap_rounding);
716 sp_curve_append(dc->accumulated, rev_cal2, TRUE);
717 add_cap(dc->accumulated, sp_curve_last_point(rev_cal2), sp_curve_first_point(dc->cal1), dc->cap_rounding);
718 sp_curve_closepath(dc->accumulated);
720 sp_curve_unref(rev_cal2);
722 sp_curve_reset(dc->cal1);
723 sp_curve_reset(dc->cal2);
724 }
725 }
727 static void
728 fit_and_split(SPDynaDrawContext *dc,
729 gboolean release)
730 {
731 fit_and_split_calligraphics(dc, release);
732 }
734 static double square(double const x)
735 {
736 return x * x;
737 }
739 static void
740 fit_and_split_calligraphics(SPDynaDrawContext *dc, gboolean release)
741 {
742 double const tolerance_sq = square( NR::expansion(SP_EVENT_CONTEXT(dc)->desktop->w2d()) * TOLERANCE_CALLIGRAPHIC );
744 #ifdef DYNA_DRAW_VERBOSE
745 g_print("[F&S:R=%c]", release?'T':'F');
746 #endif
748 if (!( dc->npoints > 0 && dc->npoints < SAMPLING_SIZE ))
749 return; // just clicked
751 if ( dc->npoints == SAMPLING_SIZE - 1 || release ) {
752 #define BEZIER_SIZE 4
753 #define BEZIER_MAX_BEZIERS 8
754 #define BEZIER_MAX_LENGTH ( BEZIER_SIZE * BEZIER_MAX_BEZIERS )
756 #ifdef DYNA_DRAW_VERBOSE
757 g_print("[F&S:#] dc->npoints:%d, release:%s\n",
758 dc->npoints, release ? "TRUE" : "FALSE");
759 #endif
761 /* Current calligraphic */
762 if ( dc->cal1->end == 0 || dc->cal2->end == 0 ) {
763 /* dc->npoints > 0 */
764 /* g_print("calligraphics(1|2) reset\n"); */
765 sp_curve_reset(dc->cal1);
766 sp_curve_reset(dc->cal2);
768 sp_curve_moveto(dc->cal1, dc->point1[0]);
769 sp_curve_moveto(dc->cal2, dc->point2[0]);
770 }
772 NR::Point b1[BEZIER_MAX_LENGTH];
773 gint const nb1 = sp_bezier_fit_cubic_r(b1, dc->point1, dc->npoints,
774 tolerance_sq, BEZIER_MAX_BEZIERS);
775 g_assert( nb1 * BEZIER_SIZE <= gint(G_N_ELEMENTS(b1)) );
777 NR::Point b2[BEZIER_MAX_LENGTH];
778 gint const nb2 = sp_bezier_fit_cubic_r(b2, dc->point2, dc->npoints,
779 tolerance_sq, BEZIER_MAX_BEZIERS);
780 g_assert( nb2 * BEZIER_SIZE <= gint(G_N_ELEMENTS(b2)) );
782 if ( nb1 != -1 && nb2 != -1 ) {
783 /* Fit and draw and reset state */
784 #ifdef DYNA_DRAW_VERBOSE
785 g_print("nb1:%d nb2:%d\n", nb1, nb2);
786 #endif
787 /* CanvasShape */
788 if (! release) {
789 sp_curve_reset(dc->currentcurve);
790 sp_curve_moveto(dc->currentcurve, b1[0]);
791 for (NR::Point *bp1 = b1; bp1 < b1 + BEZIER_SIZE * nb1; bp1 += BEZIER_SIZE) {
792 sp_curve_curveto(dc->currentcurve, bp1[1],
793 bp1[2], bp1[3]);
794 }
795 sp_curve_lineto(dc->currentcurve,
796 b2[BEZIER_SIZE*(nb2-1) + 3]);
797 for (NR::Point *bp2 = b2 + BEZIER_SIZE * ( nb2 - 1 ); bp2 >= b2; bp2 -= BEZIER_SIZE) {
798 sp_curve_curveto(dc->currentcurve, bp2[2], bp2[1], bp2[0]);
799 }
800 if (!dc->segments) {
801 add_cap(dc->currentcurve, b2[0], b1[0], dc->cap_rounding);
802 }
803 sp_curve_closepath(dc->currentcurve);
804 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), dc->currentcurve);
805 }
807 /* Current calligraphic */
808 for (NR::Point *bp1 = b1; bp1 < b1 + BEZIER_SIZE * nb1; bp1 += BEZIER_SIZE) {
809 sp_curve_curveto(dc->cal1, bp1[1], bp1[2], bp1[3]);
810 }
811 for (NR::Point *bp2 = b2; bp2 < b2 + BEZIER_SIZE * nb2; bp2 += BEZIER_SIZE) {
812 sp_curve_curveto(dc->cal2, bp2[1], bp2[2], bp2[3]);
813 }
814 } else {
815 /* fixme: ??? */
816 #ifdef DYNA_DRAW_VERBOSE
817 g_print("[fit_and_split_calligraphics] failed to fit-cubic.\n");
818 #endif
819 draw_temporary_box(dc);
821 for (gint i = 1; i < dc->npoints; i++) {
822 sp_curve_lineto(dc->cal1, dc->point1[i]);
823 }
824 for (gint i = 1; i < dc->npoints; i++) {
825 sp_curve_lineto(dc->cal2, dc->point2[i]);
826 }
827 }
829 /* Fit and draw and copy last point */
830 #ifdef DYNA_DRAW_VERBOSE
831 g_print("[%d]Yup\n", dc->npoints);
832 #endif
833 if (!release) {
834 g_assert(!sp_curve_empty(dc->currentcurve));
836 SPCanvasItem *cbp = sp_canvas_item_new(sp_desktop_sketch(SP_EVENT_CONTEXT(dc)->desktop),
837 SP_TYPE_CANVAS_BPATH,
838 NULL);
839 SPCurve *curve = sp_curve_copy(dc->currentcurve);
840 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH (cbp), curve);
841 sp_curve_unref(curve);
843 guint32 fillColor = sp_desktop_get_color_tool (SP_ACTIVE_DESKTOP, "tools.calligraphic", true);
844 //guint32 strokeColor = sp_desktop_get_color_tool (SP_ACTIVE_DESKTOP, "tools.calligraphic", false);
845 double opacity = sp_desktop_get_master_opacity_tool (SP_ACTIVE_DESKTOP, "tools.calligraphic");
846 double fillOpacity = sp_desktop_get_opacity_tool (SP_ACTIVE_DESKTOP, "tools.calligraphic", true);
847 //double strokeOpacity = sp_desktop_get_opacity_tool (SP_ACTIVE_DESKTOP, "tools.calligraphic", false);
848 sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(cbp), ((fillColor & 0xffffff00) | SP_COLOR_F_TO_U(opacity*fillOpacity)), SP_WIND_RULE_EVENODD);
849 //on second thougtht don't do stroke yet because we don't have stoke-width yet and because stoke appears between segments while drawing
850 //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);
851 sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(cbp), 0x00000000, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
852 /* fixme: Cannot we cascade it to root more clearly? */
853 g_signal_connect(G_OBJECT(cbp), "event", G_CALLBACK(sp_desktop_root_handler), SP_EVENT_CONTEXT(dc)->desktop);
855 dc->segments = g_slist_prepend(dc->segments, cbp);
856 }
858 dc->point1[0] = dc->point1[dc->npoints - 1];
859 dc->point2[0] = dc->point2[dc->npoints - 1];
860 dc->npoints = 1;
861 } else {
862 draw_temporary_box(dc);
863 }
864 }
866 static void
867 draw_temporary_box(SPDynaDrawContext *dc)
868 {
869 sp_curve_reset(dc->currentcurve);
870 sp_curve_moveto(dc->currentcurve, dc->point1[0]);
871 for (gint i = 1; i < dc->npoints; i++) {
872 sp_curve_lineto(dc->currentcurve, dc->point1[i]);
873 }
874 for (gint i = dc->npoints-1; i >= 0; i--) {
875 sp_curve_lineto(dc->currentcurve, dc->point2[i]);
876 }
877 add_cap(dc->currentcurve, dc->point2[0], dc->point1[0], dc->cap_rounding);
878 sp_curve_closepath(dc->currentcurve);
879 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), dc->currentcurve);
880 }
882 /*
883 Local Variables:
884 mode:c++
885 c-file-style:"stroustrup"
886 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
887 indent-tabs-mode:nil
888 fill-column:99
889 End:
890 */
891 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :