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 /*
22 * TODO: Tue Oct 2 22:57:15 2001
23 * - Decide control point behavior when use_calligraphic==1.
24 * - Decide to use NORMALIZED_COORDINATE or not.
25 * - Bug fix.
26 */
28 #define noDYNA_DRAW_VERBOSE
30 #include "config.h"
32 #include <gtk/gtk.h>
33 #include <gdk/gdkkeysyms.h>
35 #include "svg/svg.h"
36 #include "display/canvas-bpath.h"
37 #include "display/bezier-utils.h"
39 #include "macros.h"
40 #include "document.h"
41 #include "selection.h"
42 #include "desktop.h"
43 #include "desktop-events.h"
44 #include "desktop-handles.h"
45 #include "desktop-affine.h"
46 #include "desktop-style.h"
47 #include "message-context.h"
48 #include "pixmaps/cursor-calligraphy.xpm"
49 #include "dyna-draw-context.h"
50 #include "libnr/n-art-bpath.h"
51 #include "libnr/nr-path.h"
52 #include "xml/repr.h"
53 #include "context-fns.h"
54 #include "sp-item.h"
56 #define DDC_RED_RGBA 0xff0000ff
57 #define DDC_GREEN_RGBA 0x000000ff
59 #define SAMPLE_TIMEOUT 10
60 #define TOLERANCE_LINE 1.0
61 #define TOLERANCE_CALLIGRAPHIC 3.0
62 #define DYNA_EPSILON 1.0e-6
64 #define DYNA_MIN_WIDTH 1.0e-6
66 #define DRAG_MIN 0.0
67 #define DRAG_DEFAULT 1.0
68 #define DRAG_MAX 1.0
70 static void sp_dyna_draw_context_class_init(SPDynaDrawContextClass *klass);
71 static void sp_dyna_draw_context_init(SPDynaDrawContext *ddc);
72 static void sp_dyna_draw_context_dispose(GObject *object);
74 static void sp_dyna_draw_context_setup(SPEventContext *ec);
75 static void sp_dyna_draw_context_set(SPEventContext *ec, gchar const *key, gchar const *val);
76 static gint sp_dyna_draw_context_root_handler(SPEventContext *ec, GdkEvent *event);
78 static void clear_current(SPDynaDrawContext *dc);
79 static void set_to_accumulated(SPDynaDrawContext *dc);
80 static void concat_current_line(SPDynaDrawContext *dc);
81 static void accumulate_calligraphic(SPDynaDrawContext *dc);
83 static void fit_and_split(SPDynaDrawContext *ddc, gboolean release);
84 static void fit_and_split_line(SPDynaDrawContext *ddc, gboolean release);
85 static void fit_and_split_calligraphics(SPDynaDrawContext *ddc, gboolean release);
87 static void sp_dyna_draw_reset(SPDynaDrawContext *ddc, NR::Point p);
88 static NR::Point sp_dyna_draw_get_npoint(SPDynaDrawContext const *ddc, NR::Point v);
89 static NR::Point sp_dyna_draw_get_vpoint(SPDynaDrawContext const *ddc, NR::Point n);
90 static NR::Point sp_dyna_draw_get_curr_vpoint(SPDynaDrawContext const *ddc);
91 static void draw_temporary_box(SPDynaDrawContext *dc);
94 static SPEventContextClass *parent_class;
96 GtkType
97 sp_dyna_draw_context_get_type(void)
98 {
99 static GType type = 0;
100 if (!type) {
101 GTypeInfo info = {
102 sizeof(SPDynaDrawContextClass),
103 NULL, NULL,
104 (GClassInitFunc) sp_dyna_draw_context_class_init,
105 NULL, NULL,
106 sizeof(SPDynaDrawContext),
107 4,
108 (GInstanceInitFunc) sp_dyna_draw_context_init,
109 NULL, /* value_table */
110 };
111 type = g_type_register_static(SP_TYPE_EVENT_CONTEXT, "SPDynaDrawContext", &info, (GTypeFlags)0);
112 }
113 return type;
114 }
116 static void
117 sp_dyna_draw_context_class_init(SPDynaDrawContextClass *klass)
118 {
119 GObjectClass *object_class = (GObjectClass *) klass;
120 SPEventContextClass *event_context_class = (SPEventContextClass *) klass;
122 parent_class = (SPEventContextClass*)g_type_class_peek_parent(klass);
124 object_class->dispose = sp_dyna_draw_context_dispose;
126 event_context_class->setup = sp_dyna_draw_context_setup;
127 event_context_class->set = sp_dyna_draw_context_set;
128 event_context_class->root_handler = sp_dyna_draw_context_root_handler;
129 }
131 static void
132 sp_dyna_draw_context_init(SPDynaDrawContext *ddc)
133 {
134 SPEventContext *event_context = SP_EVENT_CONTEXT(ddc);
136 event_context->cursor_shape = cursor_calligraphy_xpm;
137 event_context->hot_x = 4;
138 event_context->hot_y = 4;
140 ddc->accumulated = NULL;
141 ddc->segments = NULL;
142 ddc->currentcurve = NULL;
143 ddc->currentshape = NULL;
144 ddc->npoints = 0;
145 ddc->cal1 = NULL;
146 ddc->cal2 = NULL;
147 ddc->repr = NULL;
149 /* DynaDraw values */
150 ddc->cur = NR::Point(0,0);
151 ddc->last = NR::Point(0,0);
152 ddc->vel = NR::Point(0,0);
153 ddc->acc = NR::Point(0,0);
154 ddc->ang = NR::Point(0,0);
155 ddc->del = NR::Point(0,0);
157 /* attributes */
158 ddc->use_timeout = FALSE;
159 ddc->use_calligraphic = TRUE;
160 ddc->timer_id = 0;
161 ddc->dragging = FALSE;
162 ddc->dynahand = FALSE;
164 ddc->mass = 0.3;
165 ddc->drag = DRAG_DEFAULT;
166 ddc->angle = 30.0;
167 ddc->width = 0.2;
169 ddc->vel_thin = 0.1;
170 ddc->flatness = 0.9;
171 }
173 static void
174 sp_dyna_draw_context_dispose(GObject *object)
175 {
176 SPDynaDrawContext *ddc = SP_DYNA_DRAW_CONTEXT(object);
178 if (ddc->accumulated) {
179 ddc->accumulated = sp_curve_unref(ddc->accumulated);
180 }
182 while (ddc->segments) {
183 gtk_object_destroy(GTK_OBJECT(ddc->segments->data));
184 ddc->segments = g_slist_remove(ddc->segments, ddc->segments->data);
185 }
187 if (ddc->currentcurve) ddc->currentcurve = sp_curve_unref(ddc->currentcurve);
188 if (ddc->cal1) ddc->cal1 = sp_curve_unref(ddc->cal1);
189 if (ddc->cal2) ddc->cal2 = sp_curve_unref(ddc->cal2);
191 if (ddc->currentshape) {
192 gtk_object_destroy(GTK_OBJECT(ddc->currentshape));
193 ddc->currentshape = NULL;
194 }
196 if (ddc->_message_context) {
197 delete ddc->_message_context;
198 }
200 G_OBJECT_CLASS(parent_class)->dispose(object);
201 }
203 static void
204 sp_dyna_draw_context_setup(SPEventContext *ec)
205 {
206 SPDynaDrawContext *ddc = SP_DYNA_DRAW_CONTEXT(ec);
208 if (((SPEventContextClass *) parent_class)->setup)
209 ((SPEventContextClass *) parent_class)->setup(ec);
211 ddc->accumulated = sp_curve_new_sized(32);
212 ddc->currentcurve = sp_curve_new_sized(4);
214 ddc->cal1 = sp_curve_new_sized(32);
215 ddc->cal2 = sp_curve_new_sized(32);
217 /* style should be changed when dc->use_calligraphc is touched */
218 ddc->currentshape = sp_canvas_item_new(SP_DT_SKETCH(ec->desktop), SP_TYPE_CANVAS_BPATH, NULL);
219 sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(ddc->currentshape), DDC_RED_RGBA, SP_WIND_RULE_EVENODD);
220 sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(ddc->currentshape), 0x00000000, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
221 /* fixme: Cannot we cascade it to root more clearly? */
222 g_signal_connect(G_OBJECT(ddc->currentshape), "event", G_CALLBACK(sp_desktop_root_handler), ec->desktop);
224 sp_event_context_read(ec, "mass");
225 sp_event_context_read(ec, "drag");
226 sp_event_context_read(ec, "angle");
227 sp_event_context_read(ec, "width");
228 sp_event_context_read(ec, "thinning");
229 sp_event_context_read(ec, "tremor");
230 sp_event_context_read(ec, "flatness");
231 sp_event_context_read(ec, "usepressure");
232 sp_event_context_read(ec, "usetilt");
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 }
271 //g_print("DDC: %g %g %g %g\n", ddc->mass, ddc->drag, ddc->angle, ddc->width);
272 }
274 static double
275 flerp(double f0, double f1, double p)
276 {
277 return f0 + ( f1 - f0 ) * p;
278 }
280 /* Get normalized point */
281 static NR::Point
282 sp_dyna_draw_get_npoint(SPDynaDrawContext const *dc, NR::Point v)
283 {
284 NR::Rect drect = SP_EVENT_CONTEXT(dc)->desktop->get_display_area();
285 double const max = MAX ( drect.dimensions()[NR::X], drect.dimensions()[NR::Y] );
286 return NR::Point(( v[NR::X] - drect.min()[NR::X] ) / max, ( v[NR::Y] - drect.min()[NR::Y] ) / max);
287 }
289 /* Get view point */
290 static NR::Point
291 sp_dyna_draw_get_vpoint(SPDynaDrawContext const *dc, NR::Point n)
292 {
293 NR::Rect drect = SP_EVENT_CONTEXT(dc)->desktop->get_display_area();
294 double const max = MAX ( drect.dimensions()[NR::X], drect.dimensions()[NR::Y] );
295 return NR::Point(n[NR::X] * max + drect.min()[NR::X], n[NR::Y] * max + drect.min()[NR::Y]);
296 }
298 /* Get current view point */
299 static NR::Point sp_dyna_draw_get_curr_vpoint(SPDynaDrawContext const *dc)
300 {
301 NR::Rect drect = SP_EVENT_CONTEXT(dc)->desktop->get_display_area();
302 double const max = MAX ( drect.dimensions()[NR::X], drect.dimensions()[NR::Y] );
303 return NR::Point(dc->cur[NR::X] * max + drect.min()[NR::X], dc->cur[NR::Y] * max + drect.min()[NR::Y]);
304 }
306 static void
307 sp_dyna_draw_reset(SPDynaDrawContext *dc, NR::Point p)
308 {
309 dc->last = dc->cur = sp_dyna_draw_get_npoint(dc, p);
310 dc->vel = NR::Point(0,0);
311 dc->acc = NR::Point(0,0);
312 dc->ang = NR::Point(0,0);
313 dc->del = NR::Point(0,0);
314 }
316 static void
317 sp_dyna_draw_extinput(SPDynaDrawContext *dc, GdkEvent *event)
318 {
319 if (gdk_event_get_axis (event, GDK_AXIS_PRESSURE, &dc->pressure))
320 dc->pressure = CLAMP (dc->pressure, DDC_MIN_PRESSURE, DDC_MAX_PRESSURE);
321 else
322 dc->pressure = DDC_DEFAULT_PRESSURE;
324 if (gdk_event_get_axis (event, GDK_AXIS_XTILT, &dc->xtilt))
325 dc->xtilt = CLAMP (dc->xtilt, DDC_MIN_TILT, DDC_MAX_TILT);
326 else
327 dc->xtilt = DDC_DEFAULT_TILT;
329 if (gdk_event_get_axis (event, GDK_AXIS_YTILT, &dc->ytilt))
330 dc->ytilt = CLAMP (dc->ytilt, DDC_MIN_TILT, DDC_MAX_TILT);
331 else
332 dc->ytilt = DDC_DEFAULT_TILT;
333 }
336 static gboolean
337 sp_dyna_draw_apply(SPDynaDrawContext *dc, NR::Point p)
338 {
339 NR::Point n = sp_dyna_draw_get_npoint(dc, p);
341 /* Calculate mass and drag */
342 double const mass = flerp(1.0, 160.0, dc->mass);
343 double const drag = flerp(0.0, 0.5, dc->drag * dc->drag);
345 /* Calculate force and acceleration */
346 NR::Point force = n - dc->cur;
347 if ( NR::L2(force) < DYNA_EPSILON ) {
348 return FALSE;
349 }
351 dc->acc = force / mass;
353 /* Calculate new velocity */
354 dc->vel += dc->acc;
356 /* Calculate angle of drawing tool */
358 double a1;
359 if (dc->usetilt) {
360 // 1a. calculate nib angle from input device tilt:
361 gdouble length = std::sqrt(dc->xtilt*dc->xtilt + dc->ytilt*dc->ytilt);;
363 if (length > 0) {
364 NR::Point ang1 = NR::Point(dc->ytilt/length, dc->xtilt/length);
365 a1 = atan2(ang1);
366 }
367 else
368 a1 = 0.0;
369 }
370 else {
371 // 1b. fixed dc->angle (absolutely flat nib):
372 double const radians = ( (dc->angle - 90) / 180.0 ) * M_PI;
373 NR::Point ang1 = NR::Point(-sin(radians), cos(radians));
374 a1 = atan2(ang1);
375 }
377 // 2. perpendicular to dc->vel (absolutely non-flat nib):
378 gdouble const mag_vel = NR::L2(dc->vel);
379 if ( mag_vel < DYNA_EPSILON ) {
380 return FALSE;
381 }
382 NR::Point ang2 = NR::rot90(dc->vel) / mag_vel;
384 // 3. Average them using flatness parameter:
385 // calculate angles
386 double a2 = atan2(ang2);
387 // flip a2 to force it to be in the same half-circle as a1
388 bool flipped = false;
389 if (fabs (a2-a1) > 0.5*M_PI) {
390 a2 += M_PI;
391 flipped = true;
392 }
393 // normalize a2
394 if (a2 > M_PI)
395 a2 -= 2*M_PI;
396 if (a2 < -M_PI)
397 a2 += 2*M_PI;
398 // find the flatness-weighted bisector angle, unflip if a2 was flipped
399 // FIXME: when dc->vel is oscillating around the fixed angle, the new_ang flips back and forth. How to avoid this?
400 double new_ang = a1 + (1 - dc->flatness) * (a2 - a1) - (flipped? M_PI : 0);
401 // convert to point
402 dc->ang = NR::Point (cos (new_ang), sin (new_ang));
404 /* Apply drag */
405 dc->vel *= 1.0 - drag;
407 /* Update position */
408 dc->last = dc->cur;
409 dc->cur += dc->vel;
411 return TRUE;
412 }
414 static void
415 sp_dyna_draw_brush(SPDynaDrawContext *dc)
416 {
417 g_assert( dc->npoints >= 0 && dc->npoints < SAMPLING_SIZE );
419 if (dc->use_calligraphic) {
420 /* calligraphics */
422 // How much velocity thins strokestyle
423 double vel_thin = flerp (0, 160, dc->vel_thin);
425 // Influence of pressure on thickness
426 double pressure_thick = (dc->usepressure ? dc->pressure : 1.0);
428 double width = ( pressure_thick - vel_thin * NR::L2(dc->vel) ) * dc->width;
430 double tremble_left = 0, tremble_right = 0;
431 if (dc->tremor > 0) {
432 // obtain two normally distributed random variables, using polar Box-Muller transform
433 double x1, x2, w, y1, y2;
434 do {
435 x1 = 2.0 * g_random_double_range(0,1) - 1.0;
436 x2 = 2.0 * g_random_double_range(0,1) - 1.0;
437 w = x1 * x1 + x2 * x2;
438 } while ( w >= 1.0 );
439 w = sqrt( (-2.0 * log( w ) ) / w );
440 y1 = x1 * w;
441 y2 = x2 * w;
443 // deflect both left and right edges randomly and independently, so that:
444 // (1) dc->tremor=1 corresponds to sigma=1, decreasing dc->tremor narrows the bell curve;
445 // (2) deflection depends on width, but is upped for small widths for better visual uniformity across widths;
446 // (3) deflection somewhat depends on speed, to prevent fast strokes looking
447 // comparatively smooth and slow ones excessively jittery
448 tremble_left = (y1)*dc->tremor * (0.15 + 0.8*width) * (0.35 + 14*NR::L2(dc->vel));
449 tremble_right = (y2)*dc->tremor * (0.15 + 0.8*width) * (0.35 + 14*NR::L2(dc->vel));
450 }
452 if ( width < 0.02 * dc->width ) {
453 width = 0.02 * dc->width;
454 }
456 NR::Point del_left = 0.05 * (width + tremble_left) * dc->ang;
457 NR::Point del_right = 0.05 * (width + tremble_right) * dc->ang;
459 dc->point1[dc->npoints] = sp_dyna_draw_get_vpoint(dc, dc->cur + del_left);
460 dc->point2[dc->npoints] = sp_dyna_draw_get_vpoint(dc, dc->cur - del_right);
462 dc->del = 0.5*(del_left + del_right);
463 } else {
464 dc->point1[dc->npoints] = sp_dyna_draw_get_curr_vpoint(dc);
465 }
467 dc->npoints++;
468 }
470 static gint
471 sp_dyna_draw_timeout_handler(gpointer data)
472 {
473 SPDynaDrawContext *dc = SP_DYNA_DRAW_CONTEXT(data);
474 SPDesktop *desktop = SP_EVENT_CONTEXT(dc)->desktop;
475 SPCanvas *canvas = SP_CANVAS(SP_DT_CANVAS(desktop));
477 dc->dragging = TRUE;
478 dc->dynahand = TRUE;
480 int x, y;
481 gtk_widget_get_pointer(GTK_WIDGET(canvas), &x, &y);
482 NR::Point p = sp_canvas_window_to_world(canvas, NR::Point(x, y));
483 p = desktop->w2d(p);
484 if (! sp_dyna_draw_apply(dc, p)) {
485 return TRUE;
486 }
488 if ( dc->cur != dc->last ) {
489 sp_dyna_draw_brush(dc);
490 g_assert( dc->npoints > 0 );
491 fit_and_split(dc, FALSE);
492 }
494 return TRUE;
495 }
497 void
498 sp_ddc_update_toolbox (SPDesktop *desktop, const gchar *id, double value)
499 {
500 desktop->setToolboxAdjustmentValue (id, value);
501 }
503 gint
504 sp_dyna_draw_context_root_handler(SPEventContext *event_context,
505 GdkEvent *event)
506 {
507 SPDynaDrawContext *dc = SP_DYNA_DRAW_CONTEXT(event_context);
508 SPDesktop *desktop = event_context->desktop;
510 gint ret = FALSE;
512 switch (event->type) {
513 case GDK_BUTTON_PRESS:
514 if ( event->button.button == 1 ) {
516 SPDesktop *desktop = SP_EVENT_CONTEXT_DESKTOP(dc);
518 if (Inkscape::have_viable_layer(desktop, dc->_message_context) == false) {
519 return TRUE;
520 }
522 NR::Point const button_w(event->button.x,
523 event->button.y);
524 NR::Point const button_dt(desktop->w2d(button_w));
525 sp_dyna_draw_reset(dc, button_dt);
526 sp_dyna_draw_extinput(dc, event);
527 sp_dyna_draw_apply(dc, button_dt);
528 sp_curve_reset(dc->accumulated);
529 if (dc->repr) {
530 dc->repr = NULL;
531 }
533 /* initialize first point */
534 dc->npoints = 0;
536 sp_canvas_item_grab(SP_CANVAS_ITEM(desktop->acetate),
537 ( dc->use_timeout
538 ? ( GDK_KEY_PRESS_MASK |
539 GDK_BUTTON_RELEASE_MASK |
540 GDK_BUTTON_PRESS_MASK )
541 : ( GDK_KEY_PRESS_MASK |
542 GDK_BUTTON_RELEASE_MASK |
543 GDK_POINTER_MOTION_MASK |
544 GDK_BUTTON_PRESS_MASK ) ),
545 NULL,
546 event->button.time);
548 if ( dc->use_timeout && !dc->timer_id ) {
549 dc->timer_id = gtk_timeout_add(SAMPLE_TIMEOUT, sp_dyna_draw_timeout_handler, dc);
550 }
551 ret = TRUE;
553 dc->is_drawing = true;
554 }
555 break;
556 case GDK_MOTION_NOTIFY:
557 if ( dc->is_drawing && !dc->use_timeout && ( event->motion.state & GDK_BUTTON1_MASK ) ) {
558 dc->dragging = TRUE;
559 dc->dynahand = TRUE;
561 NR::Point const motion_w(event->motion.x,
562 event->motion.y);
563 NR::Point const motion_dt(desktop->w2d(motion_w));
565 sp_dyna_draw_extinput(dc, event);
566 if (!sp_dyna_draw_apply(dc, motion_dt)) {
567 ret = TRUE;
568 break;
569 }
571 if ( dc->cur != dc->last ) {
572 sp_dyna_draw_brush(dc);
573 g_assert( dc->npoints > 0 );
574 fit_and_split(dc, FALSE);
575 }
576 ret = TRUE;
577 }
578 break;
580 case GDK_BUTTON_RELEASE:
581 sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate), event->button.time);
582 dc->is_drawing = false;
583 if ( event->button.button == 1
584 && dc->use_timeout
585 && dc->timer_id != 0 )
586 {
587 gtk_timeout_remove(dc->timer_id);
588 dc->timer_id = 0;
589 }
590 if ( dc->dragging && event->button.button == 1 ) {
591 dc->dragging = FALSE;
593 /* release */
594 if (dc->dynahand) {
595 dc->dynahand = FALSE;
596 /* Remove all temporary line segments */
597 while (dc->segments) {
598 gtk_object_destroy(GTK_OBJECT(dc->segments->data));
599 dc->segments = g_slist_remove(dc->segments, dc->segments->data);
600 }
601 /* Create object */
602 fit_and_split(dc, TRUE);
603 if (dc->use_calligraphic) {
604 accumulate_calligraphic(dc);
605 } else {
606 concat_current_line(dc);
607 }
608 set_to_accumulated(dc); /* temporal implementation */
609 if (dc->use_calligraphic /* || dc->cinside*/) {
610 /* reset accumulated curve */
611 sp_curve_reset(dc->accumulated);
612 clear_current(dc);
613 if (dc->repr) {
614 dc->repr = NULL;
615 }
616 }
617 }
618 ret = TRUE;
619 }
620 break;
621 case GDK_KEY_PRESS:
622 switch (get_group0_keyval (&event->key)) {
623 case GDK_Up:
624 case GDK_KP_Up:
625 if (!MOD__CTRL_ONLY) {
626 dc->angle += 5.0;
627 if (dc->angle > 90.0)
628 dc->angle = 90.0;
629 sp_ddc_update_toolbox (desktop, "calligraphy-angle", dc->angle);
630 ret = TRUE;
631 }
632 break;
633 case GDK_Down:
634 case GDK_KP_Down:
635 if (!MOD__CTRL_ONLY) {
636 dc->angle -= 5.0;
637 if (dc->angle < -90.0)
638 dc->angle = -90.0;
639 sp_ddc_update_toolbox (desktop, "calligraphy-angle", dc->angle);
640 ret = TRUE;
641 }
642 break;
643 case GDK_Right:
644 case GDK_KP_Right:
645 if (!MOD__CTRL_ONLY) {
646 dc->width += 0.01;
647 if (dc->width > 1.0)
648 dc->width = 1.0;
649 sp_ddc_update_toolbox (desktop, "altx-calligraphy", dc->width); // the same spinbutton is for alt+x
650 ret = TRUE;
651 }
652 break;
653 case GDK_Left:
654 case GDK_KP_Left:
655 if (!MOD__CTRL_ONLY) {
656 dc->width -= 0.01;
657 if (dc->width < 0.01)
658 dc->width = 0.01;
659 sp_ddc_update_toolbox (desktop, "altx-calligraphy", dc->width);
660 ret = TRUE;
661 }
662 break;
663 case GDK_x:
664 case GDK_X:
665 if (MOD__ALT_ONLY) {
666 desktop->setToolboxFocusTo ("altx-calligraphy");
667 ret = TRUE;
668 }
669 break;
670 case GDK_Escape:
671 SP_DT_SELECTION(desktop)->clear();
672 break;
674 default:
675 break;
676 }
677 default:
678 break;
679 }
681 if (!ret) {
682 if (((SPEventContextClass *) parent_class)->root_handler) {
683 ret = ((SPEventContextClass *) parent_class)->root_handler(event_context, event);
684 }
685 }
687 return ret;
688 }
691 static void
692 clear_current(SPDynaDrawContext *dc)
693 {
694 /* reset bpath */
695 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), NULL);
696 /* reset curve */
697 sp_curve_reset(dc->currentcurve);
698 sp_curve_reset(dc->cal1);
699 sp_curve_reset(dc->cal2);
700 /* reset points */
701 dc->npoints = 0;
702 }
704 static void
705 set_to_accumulated(SPDynaDrawContext *dc)
706 {
707 SPDesktop *desktop = SP_EVENT_CONTEXT(dc)->desktop;
709 if (!sp_curve_empty(dc->accumulated)) {
710 NArtBpath *abp;
711 gchar *str;
713 if (!dc->repr) {
714 /* Create object */
715 Inkscape::XML::Node *repr = sp_repr_new("svg:path");
717 /* Set style */
718 sp_desktop_apply_style_tool (desktop, repr, "tools.calligraphic", false);
720 dc->repr = repr;
722 SPItem *item=SP_ITEM(desktop->currentLayer()->appendChildRepr(dc->repr));
723 Inkscape::GC::release(dc->repr);
724 item->transform = SP_ITEM(desktop->currentRoot())->getRelativeTransform(desktop->currentLayer());
725 item->updateRepr();
726 SP_DT_SELECTION(desktop)->set(dc->repr);
727 }
728 abp = nr_artpath_affine(sp_curve_first_bpath(dc->accumulated), sp_desktop_dt2root_affine(desktop));
729 str = sp_svg_write_path(abp);
730 g_assert( str != NULL );
731 nr_free(abp);
732 dc->repr->setAttribute("d", str);
733 g_free(str);
734 } else {
735 if (dc->repr) {
736 sp_repr_unparent(dc->repr);
737 }
738 dc->repr = NULL;
739 }
741 sp_document_done(SP_DT_DOCUMENT(desktop));
742 }
744 static void
745 concat_current_line(SPDynaDrawContext *dc)
746 {
747 if (!sp_curve_empty(dc->currentcurve)) {
748 NArtBpath *bpath;
749 if (sp_curve_empty(dc->accumulated)) {
750 bpath = sp_curve_first_bpath(dc->currentcurve);
751 g_assert( bpath->code == NR_MOVETO_OPEN );
752 sp_curve_moveto(dc->accumulated, bpath->x3, bpath->y3);
753 }
754 bpath = sp_curve_last_bpath(dc->currentcurve);
755 if ( bpath->code == NR_CURVETO ) {
756 sp_curve_curveto(dc->accumulated,
757 bpath->x1, bpath->y1,
758 bpath->x2, bpath->y2,
759 bpath->x3, bpath->y3);
760 } else if ( bpath->code == NR_LINETO ) {
761 sp_curve_lineto(dc->accumulated, bpath->x3, bpath->y3);
762 } else {
763 g_assert_not_reached();
764 }
765 }
766 }
768 static void
769 accumulate_calligraphic(SPDynaDrawContext *dc)
770 {
771 if ( !sp_curve_empty(dc->cal1) && !sp_curve_empty(dc->cal2) ) {
772 sp_curve_reset(dc->accumulated); /* Is this required ?? */
773 SPCurve *rev_cal2 = sp_curve_reverse(dc->cal2);
774 sp_curve_append(dc->accumulated, dc->cal1, FALSE);
775 sp_curve_append(dc->accumulated, rev_cal2, TRUE);
776 sp_curve_closepath(dc->accumulated);
778 sp_curve_unref(rev_cal2);
780 sp_curve_reset(dc->cal1);
781 sp_curve_reset(dc->cal2);
782 }
783 }
785 static void
786 fit_and_split(SPDynaDrawContext *dc,
787 gboolean release)
788 {
789 if (dc->use_calligraphic) {
790 fit_and_split_calligraphics(dc, release);
791 } else {
792 fit_and_split_line(dc, release);
793 }
794 }
796 static double square(double const x)
797 {
798 return x * x;
799 }
801 static void
802 fit_and_split_line(SPDynaDrawContext *dc,
803 gboolean release)
804 {
805 double const tolerance_sq = square( NR::expansion(SP_EVENT_CONTEXT(dc)->desktop->w2d()) * TOLERANCE_LINE );
807 NR::Point b[4];
808 double const n_segs = sp_bezier_fit_cubic(b, dc->point1, dc->npoints, tolerance_sq);
809 if ( n_segs > 0
810 && dc->npoints < SAMPLING_SIZE )
811 {
812 /* Fit and draw and reset state */
813 #ifdef DYNA_DRAW_VERBOSE
814 g_print("%d", dc->npoints);
815 #endif
816 sp_curve_reset(dc->currentcurve);
817 sp_curve_moveto(dc->currentcurve, b[0]);
818 sp_curve_curveto(dc->currentcurve, b[1], b[2], b[3]);
819 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), dc->currentcurve);
820 } else {
821 /* Fit and draw and copy last point */
822 #ifdef DYNA_DRAW_VERBOSE
823 g_print("[%d]Yup\n", dc->npoints);
824 #endif
825 g_assert(!sp_curve_empty(dc->currentcurve));
826 concat_current_line(dc);
828 SPCanvasItem *cbp = sp_canvas_item_new(SP_DT_SKETCH(SP_EVENT_CONTEXT(dc)->desktop),
829 SP_TYPE_CANVAS_BPATH,
830 NULL);
831 SPCurve *curve = sp_curve_copy(dc->currentcurve);
832 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(cbp), curve);
833 sp_curve_unref(curve);
834 /* fixme: We have to parse style color somehow */
835 sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(cbp), DDC_GREEN_RGBA, SP_WIND_RULE_EVENODD);
836 sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(cbp), 0x000000ff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
837 /* fixme: Cannot we cascade it to root more clearly? */
838 g_signal_connect(G_OBJECT(cbp), "event", G_CALLBACK(sp_desktop_root_handler), SP_EVENT_CONTEXT(dc)->desktop);
840 dc->segments = g_slist_prepend(dc->segments, cbp);
841 dc->point1[0] = dc->point1[dc->npoints - 2];
842 dc->npoints = 1;
843 }
844 }
846 static void
847 fit_and_split_calligraphics(SPDynaDrawContext *dc, gboolean release)
848 {
849 double const tolerance_sq = square( NR::expansion(SP_EVENT_CONTEXT(dc)->desktop->w2d()) * TOLERANCE_CALLIGRAPHIC );
851 #ifdef DYNA_DRAW_VERBOSE
852 g_print("[F&S:R=%c]", release?'T':'F');
853 #endif
855 if (!( dc->npoints > 0 && dc->npoints < SAMPLING_SIZE ))
856 return; // just clicked
858 if ( dc->npoints == SAMPLING_SIZE - 1 || release ) {
859 #define BEZIER_SIZE 4
860 #define BEZIER_MAX_BEZIERS 8
861 #define BEZIER_MAX_LENGTH ( BEZIER_SIZE * BEZIER_MAX_BEZIERS )
863 #ifdef DYNA_DRAW_VERBOSE
864 g_print("[F&S:#] dc->npoints:%d, release:%s\n",
865 dc->npoints, release ? "TRUE" : "FALSE");
866 #endif
868 /* Current calligraphic */
869 if ( dc->cal1->end == 0 || dc->cal2->end == 0 ) {
870 /* dc->npoints > 0 */
871 /* g_print("calligraphics(1|2) reset\n"); */
872 sp_curve_reset(dc->cal1);
873 sp_curve_reset(dc->cal2);
875 sp_curve_moveto(dc->cal1, dc->point1[0]);
876 sp_curve_moveto(dc->cal2, dc->point2[0]);
877 }
879 NR::Point b1[BEZIER_MAX_LENGTH];
880 gint const nb1 = sp_bezier_fit_cubic_r(b1, dc->point1, dc->npoints,
881 tolerance_sq, BEZIER_MAX_BEZIERS);
882 g_assert( nb1 * BEZIER_SIZE <= gint(G_N_ELEMENTS(b1)) );
884 NR::Point b2[BEZIER_MAX_LENGTH];
885 gint const nb2 = sp_bezier_fit_cubic_r(b2, dc->point2, dc->npoints,
886 tolerance_sq, BEZIER_MAX_BEZIERS);
887 g_assert( nb2 * BEZIER_SIZE <= gint(G_N_ELEMENTS(b2)) );
889 if ( nb1 != -1 && nb2 != -1 ) {
890 /* Fit and draw and reset state */
891 #ifdef DYNA_DRAW_VERBOSE
892 g_print("nb1:%d nb2:%d\n", nb1, nb2);
893 #endif
894 /* CanvasShape */
895 if (! release) {
896 sp_curve_reset(dc->currentcurve);
897 sp_curve_moveto(dc->currentcurve, b1[0]);
898 for (NR::Point *bp1 = b1; bp1 < b1 + BEZIER_SIZE * nb1; bp1 += BEZIER_SIZE) {
899 sp_curve_curveto(dc->currentcurve, bp1[1],
900 bp1[2], bp1[3]);
901 }
902 sp_curve_lineto(dc->currentcurve,
903 b2[BEZIER_SIZE*(nb2-1) + 3]);
904 for (NR::Point *bp2 = b2 + BEZIER_SIZE * ( nb2 - 1 ); bp2 >= b2; bp2 -= BEZIER_SIZE) {
905 sp_curve_curveto(dc->currentcurve, bp2[2], bp2[1], bp2[0]);
906 }
907 sp_curve_closepath(dc->currentcurve);
908 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), dc->currentcurve);
909 }
911 /* Current calligraphic */
912 for (NR::Point *bp1 = b1; bp1 < b1 + BEZIER_SIZE * nb1; bp1 += BEZIER_SIZE) {
913 sp_curve_curveto(dc->cal1, bp1[1], bp1[2], bp1[3]);
914 }
915 for (NR::Point *bp2 = b2; bp2 < b2 + BEZIER_SIZE * nb2; bp2 += BEZIER_SIZE) {
916 sp_curve_curveto(dc->cal2, bp2[1], bp2[2], bp2[3]);
917 }
918 } else {
919 /* fixme: ??? */
920 #ifdef DYNA_DRAW_VERBOSE
921 g_print("[fit_and_split_calligraphics] failed to fit-cubic.\n");
922 #endif
923 draw_temporary_box(dc);
925 for (gint i = 1; i < dc->npoints; i++) {
926 sp_curve_lineto(dc->cal1, dc->point1[i]);
927 }
928 for (gint i = 1; i < dc->npoints; i++) {
929 sp_curve_lineto(dc->cal2, dc->point2[i]);
930 }
931 }
933 /* Fit and draw and copy last point */
934 #ifdef DYNA_DRAW_VERBOSE
935 g_print("[%d]Yup\n", dc->npoints);
936 #endif
937 if (!release) {
938 g_assert(!sp_curve_empty(dc->currentcurve));
940 SPCanvasItem *cbp = sp_canvas_item_new(SP_DT_SKETCH(SP_EVENT_CONTEXT(dc)->desktop),
941 SP_TYPE_CANVAS_BPATH,
942 NULL);
943 SPCurve *curve = sp_curve_copy(dc->currentcurve);
944 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH (cbp), curve);
945 sp_curve_unref(curve);
946 sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(cbp), 0x000000ff, SP_WIND_RULE_EVENODD);
947 sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(cbp), 0x00000000, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
948 /* fixme: Cannot we cascade it to root more clearly? */
949 g_signal_connect(G_OBJECT(cbp), "event", G_CALLBACK(sp_desktop_root_handler), SP_EVENT_CONTEXT(dc)->desktop);
951 dc->segments = g_slist_prepend(dc->segments, cbp);
952 }
954 dc->point1[0] = dc->point1[dc->npoints - 1];
955 dc->point2[0] = dc->point2[dc->npoints - 1];
956 dc->npoints = 1;
957 } else {
958 draw_temporary_box(dc);
959 }
960 }
962 static void
963 draw_temporary_box(SPDynaDrawContext *dc)
964 {
965 sp_curve_reset(dc->currentcurve);
966 sp_curve_moveto(dc->currentcurve, dc->point1[0]);
967 for (gint i = 1; i < dc->npoints; i++) {
968 sp_curve_lineto(dc->currentcurve, dc->point1[i]);
969 }
970 for (gint i = dc->npoints-1; i >= 0; i--) {
971 sp_curve_lineto(dc->currentcurve, dc->point2[i]);
972 }
973 sp_curve_closepath(dc->currentcurve);
974 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), dc->currentcurve);
975 }
977 /*
978 Local Variables:
979 mode:c++
980 c-file-style:"stroustrup"
981 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
982 indent-tabs-mode:nil
983 fill-column:99
984 End:
985 */
986 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :