~centralelyon2010/inkscape/imagelinks2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
/** \file
 * Pencil event context implementation.
 */

/*
 * Authors:
 *   Lauris Kaplinski <lauris@kaplinski.com>
 *   bulia byak <buliabyak@users.sf.net>
 *
 * Copyright (C) 2000 Lauris Kaplinski
 * Copyright (C) 2000-2001 Ximian, Inc.
 * Copyright (C) 2002 Lauris Kaplinski
 * Copyright (C) 2004 Monash University
 *
 * Released under GNU GPL, read the file 'COPYING' for more information
 */

#include <gdk/gdkkeysyms.h>

#include "pencil-context.h"
#include "desktop.h"
#include "desktop-handles.h"
#include "selection.h"
#include "selection-chemistry.h"
#include "draw-anchor.h"
#include "message-stack.h"
#include "message-context.h"
#include "modifier-fns.h"
#include "sp-path.h"
#include "preferences.h"
#include "snap.h"
#include "pixmaps/cursor-pencil.xpm"
#include <2geom/sbasis-to-bezier.h>
#include <2geom/bezier-utils.h>
#include "display/canvas-bpath.h"
#include <glibmm/i18n.h>
#include "context-fns.h"
#include "sp-namedview.h"
#include "xml/repr.h"
#include "document.h"
#include "desktop-style.h"
#include "macros.h"
#include "display/sp-canvas.h"
#include "display/curve.h"
#include "livarot/Path.h"

static void sp_pencil_context_class_init(SPPencilContextClass *klass);
static void sp_pencil_context_init(SPPencilContext *pc);
static void sp_pencil_context_setup(SPEventContext *ec);
static void sp_pencil_context_dispose(GObject *object);

static gint sp_pencil_context_root_handler(SPEventContext *event_context, GdkEvent *event);
static gint pencil_handle_button_press(SPPencilContext *const pc, GdkEventButton const &bevent);
static gint pencil_handle_motion_notify(SPPencilContext *const pc, GdkEventMotion const &mevent);
static gint pencil_handle_button_release(SPPencilContext *const pc, GdkEventButton const &revent);
static gint pencil_handle_key_press(SPPencilContext *const pc, guint const keyval, guint const state);
static gint pencil_handle_key_release(SPPencilContext *const pc, guint const keyval, guint const state);

static void spdc_set_startpoint(SPPencilContext *pc, Geom::Point const &p);
static void spdc_set_endpoint(SPPencilContext *pc, Geom::Point const &p);
static void spdc_finish_endpoint(SPPencilContext *pc);
static void spdc_add_freehand_point(SPPencilContext *pc, Geom::Point const &p, guint state);
static void fit_and_split(SPPencilContext *pc);
static void interpolate(SPPencilContext *pc);
static void sketch_interpolate(SPPencilContext *pc);

static SPDrawContextClass *pencil_parent_class;
static Geom::Point pencil_drag_origin_w(0, 0);
static bool pencil_within_tolerance = false;

static bool in_svg_plane(Geom::Point const &p) { return Geom::LInfty(p) < 1e18; }

/**
 * Register SPPencilContext class with Gdk and return its type number.
 */
GType
sp_pencil_context_get_type()
{
    static GType type = 0;
    if (!type) {
        GTypeInfo info = {
            sizeof(SPPencilContextClass),
            NULL, NULL,
            (GClassInitFunc) sp_pencil_context_class_init,
            NULL, NULL,
            sizeof(SPPencilContext),
            4,
            (GInstanceInitFunc) sp_pencil_context_init,
            NULL,   /* value_table */
        };
        type = g_type_register_static(SP_TYPE_DRAW_CONTEXT, "SPPencilContext", &info, (GTypeFlags)0);
    }
    return type;
}

/**
 * Initialize SPPencilContext vtable.
 */
static void
sp_pencil_context_class_init(SPPencilContextClass *klass)
{
    GObjectClass *object_class;
    SPEventContextClass *event_context_class;

    object_class = (GObjectClass *) klass;
    event_context_class = (SPEventContextClass *) klass;

    pencil_parent_class = (SPDrawContextClass*)g_type_class_peek_parent(klass);

    object_class->dispose = sp_pencil_context_dispose;

    event_context_class->setup = sp_pencil_context_setup;
    event_context_class->root_handler = sp_pencil_context_root_handler;
}

/**
 * Callback to initialize SPPencilContext object.
 */
static void
sp_pencil_context_init(SPPencilContext *pc)
{
    SPEventContext *event_context = SP_EVENT_CONTEXT(pc);

    event_context->cursor_shape = cursor_pencil_xpm;
    event_context->hot_x = 4;
    event_context->hot_y = 4;

    pc->npoints = 0;
    pc->state = SP_PENCIL_CONTEXT_IDLE;
    pc->req_tangent = Geom::Point(0, 0);

    // since SPPencilContext is not properly constructed...
    pc->sketch_interpolation = Geom::Piecewise<Geom::D2<Geom::SBasis> >();
    pc->sketch_n = 0;
}

/**
 * Callback to setup SPPencilContext object.
 */
static void
sp_pencil_context_setup(SPEventContext *ec)
{
    Inkscape::Preferences *prefs = Inkscape::Preferences::get();
    if (prefs->getBool("/tools/freehand/pencil/selcue")) {
        ec->enableSelectionCue();
    }

    if (((SPEventContextClass *) pencil_parent_class)->setup) {
        ((SPEventContextClass *) pencil_parent_class)->setup(ec);
    }

    SPPencilContext *const pc = SP_PENCIL_CONTEXT(ec);
    pc->is_drawing = false;

    pc->anchor_statusbar = false;
}

static void
sp_pencil_context_dispose(GObject *object)
{
    G_OBJECT_CLASS(pencil_parent_class)->dispose(object);
}

/** Snaps new node relative to the previous node. */
static void
spdc_endpoint_snap(SPPencilContext const *pc, Geom::Point &p, guint const state)
{
    if ((state & GDK_CONTROL_MASK)) { //CTRL enables constrained snapping
        spdc_endpoint_snap_rotation(pc, p, pc->p[0], state);
    } else {
        if (!(state & GDK_SHIFT_MASK)) { //SHIFT disables all snapping, except the angular snapping above
                                         //After all, the user explicitely asked for angular snapping by
                                         //pressing CTRL
            spdc_endpoint_snap_free(pc, p, state);
        }
    }
}

/**
 * Callback for handling all pencil context events.
 */
gint
sp_pencil_context_root_handler(SPEventContext *const ec, GdkEvent *event)
{
    SPPencilContext *const pc = SP_PENCIL_CONTEXT(ec);

    gint ret = FALSE;

    switch (event->type) {
        case GDK_BUTTON_PRESS:
            ret = pencil_handle_button_press(pc, event->button);
            break;

        case GDK_MOTION_NOTIFY:
            ret = pencil_handle_motion_notify(pc, event->motion);
            break;

        case GDK_BUTTON_RELEASE:
            ret = pencil_handle_button_release(pc, event->button);
            break;

        case GDK_KEY_PRESS:
            ret = pencil_handle_key_press(pc, get_group0_keyval (&event->key), event->key.state);
            break;

        case GDK_KEY_RELEASE:
            ret = pencil_handle_key_release(pc, get_group0_keyval (&event->key), event->key.state);
            break;

        default:
            break;
    }

    if (!ret) {
        gint (*const parent_root_handler)(SPEventContext *, GdkEvent *)
            = ((SPEventContextClass *) pencil_parent_class)->root_handler;
        if (parent_root_handler) {
            ret = parent_root_handler(ec, event);
        }
    }

    return ret;
}

static gint
pencil_handle_button_press(SPPencilContext *const pc, GdkEventButton const &bevent)
{
    gint ret = FALSE;
    SPEventContext *event_context = SP_EVENT_CONTEXT(pc);
    if ( bevent.button == 1  && !event_context->space_panning) {

        SPDrawContext *dc = SP_DRAW_CONTEXT (pc);
        SPDesktop *desktop = SP_EVENT_CONTEXT_DESKTOP(dc);
        Inkscape::Selection *selection = sp_desktop_selection(desktop);

        if (Inkscape::have_viable_layer(desktop, dc->_message_context) == false) {
            return TRUE;
        }

        if (!pc->grab) {
            /* Grab mouse, so release will not pass unnoticed */
            pc->grab = SP_CANVAS_ITEM(desktop->acetate);
            sp_canvas_item_grab(pc->grab, ( GDK_KEY_PRESS_MASK | GDK_BUTTON_PRESS_MASK   |
                                            GDK_BUTTON_RELEASE_MASK |
                                            GDK_POINTER_MOTION_MASK  ),
                                NULL, bevent.time);
        }

        Geom::Point const button_w(bevent.x, bevent.y);

        /* Find desktop coordinates */
        Geom::Point p = pc->desktop->w2d(button_w);

        /* Test whether we hit any anchor. */
        SPDrawAnchor *anchor = spdc_test_inside(pc, button_w);

        pencil_drag_origin_w = Geom::Point(bevent.x,bevent.y);
        pencil_within_tolerance = true;

        switch (pc->state) {
            case SP_PENCIL_CONTEXT_ADDLINE:
                /* Current segment will be finished with release */
                ret = TRUE;
                break;
            default:
                /* Set first point of sequence */
                SnapManager &m = desktop->namedview->snap_manager;

                if (bevent.state & GDK_CONTROL_MASK) {
                    m.setup(desktop);
                    if (!(bevent.state & GDK_SHIFT_MASK)) {
                        m.freeSnapReturnByRef(p, Inkscape::SNAPSOURCE_NODE_HANDLE);
                      }
                    spdc_create_single_dot(event_context, p, "/tools/freehand/pencil", bevent.state);
                    m.unSetup();
                    ret = true;
                    break;
                }
                if (anchor) {
                    p = anchor->dp;
                    desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Continuing selected path"));
                } else {
                    m.setup(desktop);
                    if (!(bevent.state & GDK_SHIFT_MASK)) {
                        // This is the first click of a new curve; deselect item so that
                        // this curve is not combined with it (unless it is drawn from its
                        // anchor, which is handled by the sibling branch above)
                        selection->clear();
                        desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Creating new path"));
                        m.freeSnapReturnByRef(p, Inkscape::SNAPSOURCE_NODE_HANDLE);
                    } else if (selection->singleItem() && SP_IS_PATH(selection->singleItem())) {
                        desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Appending to selected path"));
                        m.freeSnapReturnByRef(p, Inkscape::SNAPSOURCE_NODE_HANDLE);
                    }
                    m.unSetup();
                }
                pc->sa = anchor;
                spdc_set_startpoint(pc, p);
                ret = TRUE;
                break;
        }

        pc->is_drawing = true;
    }
    return ret;
}

static gint
pencil_handle_motion_notify(SPPencilContext *const pc, GdkEventMotion const &mevent)
{
    SPDesktop *const dt = pc->desktop;

    if ((mevent.state & GDK_CONTROL_MASK) && (mevent.state & GDK_BUTTON1_MASK)) {
        // mouse was accidentally moved during Ctrl+click;
        // ignore the motion and create a single point
        pc->is_drawing = false;
        return TRUE;
    }
    gint ret = FALSE;

    SPEventContext *event_context = SP_EVENT_CONTEXT(pc);
    if (event_context->space_panning || mevent.state & GDK_BUTTON2_MASK || mevent.state & GDK_BUTTON3_MASK) {
        // allow scrolling
        return FALSE;
    }

    if ( ( mevent.state & GDK_BUTTON1_MASK ) && !pc->grab && pc->is_drawing) {
        /* Grab mouse, so release will not pass unnoticed */
        pc->grab = SP_CANVAS_ITEM(dt->acetate);
        sp_canvas_item_grab(pc->grab, ( GDK_KEY_PRESS_MASK | GDK_BUTTON_PRESS_MASK   |
                                        GDK_BUTTON_RELEASE_MASK |
                                        GDK_POINTER_MOTION_MASK  ),
                            NULL, mevent.time);
    }

    /* Find desktop coordinates */
    Geom::Point p = dt->w2d(Geom::Point(mevent.x, mevent.y));

    /* Test whether we hit any anchor. */
    SPDrawAnchor *anchor = spdc_test_inside(pc, Geom::Point(mevent.x, mevent.y));

    if (pencil_within_tolerance) {
        Inkscape::Preferences *prefs = Inkscape::Preferences::get();
        gint const tolerance = prefs->getIntLimited("/options/dragtolerance/value", 0, 0, 100);
        if ( Geom::LInfty( Geom::Point(mevent.x,mevent.y) - pencil_drag_origin_w ) < tolerance ) {
            return FALSE;   // Do not drag if we're within tolerance from origin.
        }
    }

    // Once the user has moved farther than tolerance from the original location
    // (indicating they intend to move the object, not click), then always process the
    // motion notify coordinates as given (no snapping back to origin)
    pencil_within_tolerance = false;

    switch (pc->state) {
        case SP_PENCIL_CONTEXT_ADDLINE:
            /* Set red endpoint */
            if (anchor) {
                p = anchor->dp;
            } else {
                Geom::Point ptnr(p);
                spdc_endpoint_snap(pc, ptnr, mevent.state);
                p = ptnr;
            }
            spdc_set_endpoint(pc, p);
            ret = TRUE;
            break;
        default:
            /* We may be idle or already freehand */
            if ( mevent.state & GDK_BUTTON1_MASK && pc->is_drawing ) {
                if (pc->state == SP_PENCIL_CONTEXT_IDLE) {
                    sp_event_context_discard_delayed_snap_event(event_context);
                }
                pc->state = SP_PENCIL_CONTEXT_FREEHAND;

                if ( !pc->sa && !pc->green_anchor ) {
                    /* Create green anchor */
                    pc->green_anchor = sp_draw_anchor_new(pc, pc->green_curve, TRUE, pc->p[0]);
                }
                if (anchor) {
                    p = anchor->dp;
                }

                if ( pc->npoints != 0) { // buttonpress may have happened before we entered draw context!
                    if (pc->ps.size() == 0) {
                        // Only in freehand mode we have to add the first point also to pc->ps (apparently)
                        // - We cannot add this point in spdc_set_startpoint, because we only need it for freehand
                        // - We cannot do this in the button press handler because at that point we don't know yet
                        //   wheter we're going into freehand mode or not
                        pc->ps.push_back(pc->p[0]);
                    }
                    spdc_add_freehand_point(pc, p, mevent.state);
                    ret = TRUE;
                }

                if (anchor && !pc->anchor_statusbar) {
                    pc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Release</b> here to close and finish the path."));
                    pc->anchor_statusbar = true;
                } else if (!anchor && pc->anchor_statusbar) {
                    pc->_message_context->clear();
                    pc->anchor_statusbar = false;
                } else if (!anchor) {
                    pc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("Drawing a freehand path"));
                }

            } else {
                if (anchor && !pc->anchor_statusbar) {
                    pc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Drag</b> to continue the path from this point."));
                    pc->anchor_statusbar = true;
                } else if (!anchor && pc->anchor_statusbar) {
                    pc->_message_context->clear();
                    pc->anchor_statusbar = false;
                }
            }

            // Show the pre-snap indicator to communicate to the user where we would snap to if he/she were to
            // a) press the mousebutton to start a freehand drawing, or
            // b) release the mousebutton to finish a freehand drawing
            if (!sp_event_context_knot_mouseover(pc)) {
                SnapManager &m = dt->namedview->snap_manager;
                m.setup(dt);
                m.preSnap(Inkscape::SnapCandidatePoint(p, Inkscape::SNAPSOURCE_NODE_HANDLE));
                m.unSetup();
            }
            break;
    }
    return ret;
}

static gint
pencil_handle_button_release(SPPencilContext *const pc, GdkEventButton const &revent)
{
    gint ret = FALSE;

    SPEventContext *event_context = SP_EVENT_CONTEXT(pc);
    if ( revent.button == 1 && pc->is_drawing && !event_context->space_panning) {
        SPDesktop *const dt = pc->desktop;

        pc->is_drawing = false;

        /* Find desktop coordinates */
        Geom::Point p = dt->w2d(Geom::Point(revent.x, revent.y));

        /* Test whether we hit any anchor. */
        SPDrawAnchor *anchor = spdc_test_inside(pc, Geom::Point(revent.x,
                                                              revent.y));

        switch (pc->state) {
            case SP_PENCIL_CONTEXT_IDLE:
                /* Releasing button in idle mode means single click */
                /* We have already set up start point/anchor in button_press */
                if (!(revent.state & GDK_CONTROL_MASK)) {
                    // Ctrl+click creates a single point so only set context in ADDLINE mode when Ctrl isn't pressed
                    pc->state = SP_PENCIL_CONTEXT_ADDLINE;
                }
                ret = TRUE;
                break;
            case SP_PENCIL_CONTEXT_ADDLINE:
                /* Finish segment now */
                if (anchor) {
                    p = anchor->dp;
                } else {
                    spdc_endpoint_snap(pc, p, revent.state);
                }
                pc->ea = anchor;
                spdc_set_endpoint(pc, p);
                spdc_finish_endpoint(pc);
                pc->state = SP_PENCIL_CONTEXT_IDLE;
                sp_event_context_discard_delayed_snap_event(event_context);
                ret = TRUE;
                break;
            case SP_PENCIL_CONTEXT_FREEHAND:
                if (revent.state & GDK_MOD1_MASK) {
                    /* sketch mode: interpolate the sketched path and improve the current output path with the new interpolation. don't finish sketch */

                    sketch_interpolate(pc);

                    if (pc->green_anchor) {
                        pc->green_anchor = sp_draw_anchor_destroy(pc->green_anchor);
                    }

                    pc->state = SP_PENCIL_CONTEXT_SKETCH;
                } else {
                    /* Finish segment now */
                    /// \todo fixme: Clean up what follows (Lauris)
                    if (anchor) {
                        p = anchor->dp;
                    } else {
                        Geom::Point p_end = p;
                        spdc_endpoint_snap(pc, p_end, revent.state);
                        if (p_end != p) {
                            // then we must have snapped!
                            spdc_add_freehand_point(pc, p_end, revent.state);
                        }
                    }

                    pc->ea = anchor;
                    /* Write curves to object */

                    dt->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Finishing freehand"));

                    interpolate(pc);
                    spdc_concat_colors_and_flush(pc, FALSE);
                    pc->sa = NULL;
                    pc->ea = NULL;
                    if (pc->green_anchor) {
                        pc->green_anchor = sp_draw_anchor_destroy(pc->green_anchor);
                    }
                    pc->state = SP_PENCIL_CONTEXT_IDLE;
                    // reset sketch mode too
                    pc->sketch_n = 0;
                }
                ret = TRUE;
                break;
            case SP_PENCIL_CONTEXT_SKETCH:
            default:
                break;
        }

        if (pc->grab) {
            /* Release grab now */
            sp_canvas_item_ungrab(pc->grab, revent.time);
            pc->grab = NULL;
        }

        ret = TRUE;
    }
    return ret;
}

static void
pencil_cancel (SPPencilContext *const pc)
{
    if (pc->grab) {
        /* Release grab now */
        sp_canvas_item_ungrab(pc->grab, 0);
        pc->grab = NULL;
    }

    pc->is_drawing = false;
    pc->state = SP_PENCIL_CONTEXT_IDLE;
    sp_event_context_discard_delayed_snap_event(SP_EVENT_CONTEXT(pc));

    pc->red_curve->reset();
    sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(pc->red_bpath), NULL);
    while (pc->green_bpaths) {
        gtk_object_destroy(GTK_OBJECT(pc->green_bpaths->data));
        pc->green_bpaths = g_slist_remove(pc->green_bpaths, pc->green_bpaths->data);
    }
    pc->green_curve->reset();
    if (pc->green_anchor) {
        pc->green_anchor = sp_draw_anchor_destroy(pc->green_anchor);
    }

    pc->_message_context->clear();
    pc->_message_context->flash(Inkscape::NORMAL_MESSAGE, _("Drawing cancelled"));

    sp_canvas_end_forced_full_redraws(pc->desktop->canvas);
}

static gint
pencil_handle_key_press(SPPencilContext *const pc, guint const keyval, guint const state)
{
    gint ret = FALSE;
    switch (keyval) {
        case GDK_Up:
        case GDK_Down:
        case GDK_KP_Up:
        case GDK_KP_Down:
            // Prevent the zoom field from activation.
            if (!mod_ctrl_only(state)) {
                ret = TRUE;
            }
            break;
        case GDK_Escape:
            if (pc->npoints != 0) {
                // if drawing, cancel, otherwise pass it up for deselecting
                if (pc->state != SP_PENCIL_CONTEXT_IDLE) {
                    pencil_cancel (pc);
                    ret = TRUE;
                }
            }
            break;
        case GDK_z:
        case GDK_Z:
            if (mod_ctrl_only(state) && pc->npoints != 0) {
                // if drawing, cancel, otherwise pass it up for undo
                if (pc->state != SP_PENCIL_CONTEXT_IDLE) {
                    pencil_cancel (pc);
                    ret = TRUE;
                }
            }
            break;
        case GDK_g:
        case GDK_G:
            if (mod_shift_only(state)) {
                sp_selection_to_guides(SP_EVENT_CONTEXT(pc)->desktop);
                ret = true;
            }
            break;
        case GDK_Alt_L:
        case GDK_Alt_R:
        case GDK_Meta_L:
        case GDK_Meta_R:
            if (pc->state == SP_PENCIL_CONTEXT_IDLE) {
                pc->desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("<b>Sketch mode</b>: holding <b>Alt</b> interpolates between sketched paths. Release <b>Alt</b> to finalize."));
            }
            break;
        default:
            break;
    }
    return ret;
}

static gint
pencil_handle_key_release(SPPencilContext *const pc, guint const keyval, guint const /*state*/)
{
    gint ret = FALSE;
    switch (keyval) {
        case GDK_Alt_L:
        case GDK_Alt_R:
        case GDK_Meta_L:
        case GDK_Meta_R:
            if (pc->state == SP_PENCIL_CONTEXT_SKETCH) {
                spdc_concat_colors_and_flush(pc, FALSE);
                pc->sketch_n = 0;
                pc->sa = NULL;
                pc->ea = NULL;
                if (pc->green_anchor) {
                    pc->green_anchor = sp_draw_anchor_destroy(pc->green_anchor);
                }
                pc->state = SP_PENCIL_CONTEXT_IDLE;
                sp_event_context_discard_delayed_snap_event(SP_EVENT_CONTEXT(pc));
                pc->desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Finishing freehand sketch"));
                ret = TRUE;
            }
            break;
        default:
            break;
    }
    return ret;
}

/**
 * Reset points and set new starting point.
 */
static void
spdc_set_startpoint(SPPencilContext *const pc, Geom::Point const &p)
{
    pc->npoints = 0;
    pc->red_curve_is_valid = false;
    if (in_svg_plane(p)) {
        pc->p[pc->npoints++] = p;
    }
}

/**
 * Change moving endpoint position.
 * <ul>
 * <li>Ctrl constrains to moving to H/V direction, snapping in given direction.
 * <li>Otherwise we snap freely to whatever attractors are available.
 * </ul>
 *
 * Number of points is (re)set to 2 always, 2nd point is modified.
 * We change RED curve.
 */
static void
spdc_set_endpoint(SPPencilContext *const pc, Geom::Point const &p)
{
    if (pc->npoints == 0) {
        return;
        /* May occur if first point wasn't in SVG plane (e.g. weird w2d transform, perhaps from bad
         * zoom setting).
         */
    }
    g_return_if_fail( pc->npoints > 0 );

    pc->red_curve->reset();
    if ( ( p == pc->p[0] )
         || !in_svg_plane(p) )
    {
        pc->npoints = 1;
    } else {
        pc->p[1] = p;
        pc->npoints = 2;

        pc->red_curve->moveto(pc->p[0]);
        pc->red_curve->lineto(pc->p[1]);
        pc->red_curve_is_valid = true;

        sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(pc->red_bpath), pc->red_curve);
    }
}

/**
 * Finalize addline.
 *
 * \todo
 * fixme: I'd like remove red reset from concat colors (lauris).
 * Still not sure, how it will make most sense.
 */
static void
spdc_finish_endpoint(SPPencilContext *const pc)
{
    if ( ( pc->red_curve->is_empty() )
         || ( *(pc->red_curve->first_point()) == *(pc->red_curve->second_point())   ) )
    {
        pc->red_curve->reset();
        sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(pc->red_bpath), NULL);
    } else {
        /* Write curves to object. */
        spdc_concat_colors_and_flush(pc, FALSE);
        pc->sa = NULL;
        pc->ea = NULL;
    }
}


static void
spdc_add_freehand_point(SPPencilContext *pc, Geom::Point const &p, guint /*state*/)
{
    g_assert( pc->npoints > 0 );
    g_return_if_fail(unsigned(pc->npoints) < G_N_ELEMENTS(pc->p));

    if ( ( p != pc->p[ pc->npoints - 1 ] )
         && in_svg_plane(p) )
    {
        pc->ps.push_back(p);
        pc->p[pc->npoints++] = p;
        fit_and_split(pc);
    }
}

static inline double
square(double const x)
{
    return x * x;
}

static void
interpolate(SPPencilContext *pc)
{
    if ( pc->ps.size() <= 1 ) {
        return;
    }

    Inkscape::Preferences *prefs = Inkscape::Preferences::get();
    double const tol = prefs->getDoubleLimited("/tools/freehand/pencil/tolerance", 10.0, 1.0, 100.0) * 0.4;
    double const tolerance_sq = 0.02 * square( pc->desktop->w2d().descrim() *
                                               tol) * exp(0.2*tol - 2);

    g_assert(is_zero(pc->req_tangent)
             || is_unit_vector(pc->req_tangent));
    Geom::Point const tHatEnd(0, 0);

    guint n_points  = pc->ps.size();
    pc->green_curve->reset();
    pc->red_curve->reset();
    pc->red_curve_is_valid = false;

    Geom::Point * b = g_new(Geom::Point, 4*n_points);
    Geom::Point * points = g_new(Geom::Point, 4*n_points);
    for (unsigned int i = 0; i < pc->ps.size(); i++) {
        points[i] = pc->ps[i];
    }

    // worst case gives us a segment per point
    int max_segs = 4*n_points;

    int const n_segs = Geom::bezier_fit_cubic_r(b, points, n_points,
                                             tolerance_sq, max_segs);

    if ( n_segs > 0)
    {
        /* Fit and draw and reset state */
        pc->green_curve->moveto(b[0]);
        for (int c = 0; c < n_segs; c++) {
            pc->green_curve->curveto(b[4*c+1], b[4*c+2], b[4*c+3]);
        }
        sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(pc->red_bpath), pc->green_curve);

        /* Fit and draw and copy last point */
        g_assert(!pc->green_curve->is_empty());

        /* Set up direction of next curve. */
        {
            Geom::CubicBezier const * last_seg = dynamic_cast<Geom::CubicBezier const *>(pc->green_curve->last_segment());
            g_assert( last_seg );      // Relevance: validity of (*last_seg)[2]
            pc->p[0] = last_seg->finalPoint();
            pc->npoints = 1;
            Geom::Point const req_vec( pc->p[0] - (*last_seg)[2] );
            pc->req_tangent = ( ( Geom::is_zero(req_vec) || !in_svg_plane(req_vec) )
                                ? Geom::Point(0, 0)
                                : Geom::unit_vector(req_vec) );
        }
    }
    g_free(b);
    g_free(points);
    pc->ps.clear();
}


/* interpolates the sketched curve and tweaks the current sketch interpolation*/
static void
sketch_interpolate(SPPencilContext *pc)
{
    if ( pc->ps.size() <= 1 ) {
        return;
    }

    Inkscape::Preferences *prefs = Inkscape::Preferences::get();
    double const tol = prefs->getDoubleLimited("/tools/freehand/pencil/tolerance", 10.0, 1.0, 100.0) * 0.4;
    double const tolerance_sq = 0.02 * square( pc->desktop->w2d().descrim() *
                                               tol) * exp(0.2*tol - 2);

    bool average_all_sketches = prefs->getBool("/tools/freehand/pencil/average_all_sketches", true);

    g_assert(is_zero(pc->req_tangent)
             || is_unit_vector(pc->req_tangent));
    Geom::Point const tHatEnd(0, 0);

    guint n_points  = pc->ps.size();
    pc->red_curve->reset();
    pc->red_curve_is_valid = false;

    Geom::Point * b = g_new(Geom::Point, 4*n_points);
    Geom::Point * points = g_new(Geom::Point, 4*n_points);
    for (unsigned i = 0; i < pc->ps.size(); i++) {
        points[i] = pc->ps[i];
    }

    // worst case gives us a segment per point
    int max_segs = 4*n_points;

    int const n_segs = Geom::bezier_fit_cubic_r(b, points, n_points,
                                             tolerance_sq, max_segs);

    if ( n_segs > 0)
    {
        Geom::Path fit(b[0]);
        for (int c = 0; c < n_segs; c++) {
            fit.appendNew<Geom::CubicBezier>(b[4*c+1], b[4*c+2], b[4*c+3]);
        }
        Geom::Piecewise<Geom::D2<Geom::SBasis> > fit_pwd2 = fit.toPwSb();

        double t =0.;
        if ( pc->sketch_n > 0 ) {
            if (average_all_sketches) {
                // Average = (sum of all) / n
                //         = (sum of all + new one) / n+1
                //         = ((old average)*n + new one) / n+1
                t = pc->sketch_n / (pc->sketch_n + 1.);
            } else {
                t = 0.5;
            }
            pc->sketch_interpolation = Geom::lerp(t, fit_pwd2, pc->sketch_interpolation);
            // simplify path, to eliminate small segments
            Path *path = new Path;
            path->LoadPathVector(Geom::path_from_piecewise(pc->sketch_interpolation, 0.01));
            path->Simplify(0.5);
            Geom::PathVector *pathv = path->MakePathVector();
            pc->sketch_interpolation = (*pathv)[0].toPwSb();
            delete path;
            delete pathv;
        } else {
            pc->sketch_interpolation = fit_pwd2;
        }
        pc->sketch_n++;

        pc->green_curve->reset();
        pc->green_curve->set_pathvector(Geom::path_from_piecewise(pc->sketch_interpolation, 0.01));
        sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(pc->red_bpath), pc->green_curve);

        /* Fit and draw and copy last point */
        g_assert(!pc->green_curve->is_empty());

        /* Set up direction of next curve. */
        {
            Geom::CubicBezier const * last_seg = dynamic_cast<Geom::CubicBezier const *>(pc->green_curve->last_segment());
            g_assert( last_seg );      // Relevance: validity of (*last_seg)[2]
            pc->p[0] = last_seg->finalPoint();
            pc->npoints = 1;
            Geom::Point const req_vec( pc->p[0] - (*last_seg)[2] );
            pc->req_tangent = ( ( Geom::is_zero(req_vec) || !in_svg_plane(req_vec) )
                                ? Geom::Point(0, 0)
                                : Geom::unit_vector(req_vec) );
        }
    }
    g_free(b);
    g_free(points);
    pc->ps.clear();
}

static void
fit_and_split(SPPencilContext *pc)
{
    g_assert( pc->npoints > 1 );

    double const tolerance_sq = 0;

    Geom::Point b[4];
    g_assert(is_zero(pc->req_tangent)
             || is_unit_vector(pc->req_tangent));
    Geom::Point const tHatEnd(0, 0);
    int const n_segs = Geom::bezier_fit_cubic_full(b, NULL, pc->p, pc->npoints,
                                                pc->req_tangent, tHatEnd,
                                                tolerance_sq, 1);
    if ( n_segs > 0
         && unsigned(pc->npoints) < G_N_ELEMENTS(pc->p) )
    {
        /* Fit and draw and reset state */
        pc->red_curve->reset();
        pc->red_curve->moveto(b[0]);
        pc->red_curve->curveto(b[1], b[2], b[3]);
        sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(pc->red_bpath), pc->red_curve);
        pc->red_curve_is_valid = true;
    } else {
        /* Fit and draw and copy last point */

        g_assert(!pc->red_curve->is_empty());

        /* Set up direction of next curve. */
        {
            Geom::CubicBezier const * last_seg = dynamic_cast<Geom::CubicBezier const *>(pc->red_curve->last_segment());
            g_assert( last_seg );      // Relevance: validity of (*last_seg)[2]
            pc->p[0] = last_seg->finalPoint();
            pc->npoints = 1;
            Geom::Point const req_vec( pc->p[0] - (*last_seg)[2] );
            pc->req_tangent = ( ( Geom::is_zero(req_vec) || !in_svg_plane(req_vec) )
                                ? Geom::Point(0, 0)
                                : Geom::unit_vector(req_vec) );
        }

        pc->green_curve->append_continuous(pc->red_curve, 0.0625);
        SPCurve *curve = pc->red_curve->copy();

        /// \todo fixme:
        SPCanvasItem *cshape = sp_canvas_bpath_new(sp_desktop_sketch(pc->desktop), curve);
        curve->unref();
        sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(cshape), pc->green_color, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);

        pc->green_bpaths = g_slist_prepend(pc->green_bpaths, cshape);

        pc->red_curve_is_valid = false;
    }
}


/*
  Local Variables:
  mode:c++
  c-file-style:"stroustrup"
  c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
  indent-tabs-mode:nil
  fill-column:99
  End:
*/
// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 :