File: path.c

package info (click to toggle)
gwyddion 2.62-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 51,952 kB
  • sloc: ansic: 398,486; python: 7,877; sh: 5,492; makefile: 4,723; xml: 3,883; cpp: 1,969; pascal: 418; perl: 154; ruby: 130
file content (1023 lines) | stat: -rw-r--r-- 34,896 bytes parent folder | download
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
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
/*
 *  $Id: path.c 24732 2022-03-23 20:01:21Z yeti-dn $
 *  Copyright (C) 2016-2019 David Necas (Yeti).
 *  E-mail: yeti@gwyddion.net.
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin Street, Fifth Floor,
 *  Boston, MA 02110-1301, USA.
 */

#include "config.h"
#include <string.h>
#include <gdk/gdkkeysyms.h>
#include <libgwyddion/gwymacros.h>
#include <libgwyddion/gwymath.h>
#include <libprocess/spline.h>
#include <libgwydgets/gwydataview.h>
#include <libgwydgets/gwydgetutils.h>
#include <libgwymodule/gwymodule-layer.h>

#include "layer.h"

#define GWY_SELECTION_PATH_TYPE_NAME "GwySelectionPath"

#define GWY_TYPE_LAYER_PATH            (gwy_layer_path_get_type())
#define GWY_LAYER_PATH(obj)            (G_TYPE_CHECK_INSTANCE_CAST((obj), GWY_TYPE_LAYER_PATH, GwyLayerPath))
#define GWY_IS_LAYER_PATH(obj)         (G_TYPE_CHECK_INSTANCE_TYPE((obj), GWY_TYPE_LAYER_PATH))
#define GWY_LAYER_PATH_GET_CLASS(obj)  (G_TYPE_INSTANCE_GET_CLASS((obj), GWY_TYPE_LAYER_PATH, GwyLayerPathClass))

#define GWY_TYPE_SELECTION_PATH            (gwy_selection_path_get_type())
#define GWY_SELECTION_PATH(obj)            (G_TYPE_CHECK_INSTANCE_CAST((obj), GWY_TYPE_SELECTION_PATH, GwySelectionPath))
#define GWY_IS_SELECTION_PATH(obj)         (G_TYPE_CHECK_INSTANCE_TYPE((obj), GWY_TYPE_SELECTION_PATH))
#define GWY_SELECTION_PATH_GET_CLASS(obj)  (G_TYPE_INSTANCE_GET_CLASS((obj), GWY_TYPE_SELECTION_PATH, GwySelectionPathClass))

enum {
    OBJECT_SIZE = 2
};

enum {
    PROP_0,
    PROP_SLACKNESS,
    PROP_CLOSED,
};

enum {
    PROP_00,
    PROP_THICKNESS,
};

typedef struct _GwyLayerPath          GwyLayerPath;
typedef struct _GwyLayerPathClass     GwyLayerPathClass;
typedef struct _GwySelectionPath      GwySelectionPath;
typedef struct _GwySelectionPathClass GwySelectionPathClass;

struct _GwyLayerPath {
    GwyVectorLayer parent_instance;

    GdkCursor *near_cursor;
    GdkCursor *move_cursor;

    /* Properties */
    gint thickness;
    gboolean point_numbers;

    /* Dynamic state */
    GwySpline *spline;
};

struct _GwyLayerPathClass {
    GwyVectorLayerClass parent_class;
};

struct _GwySelectionPath {
    GwySelection parent_instance;

    gdouble slackness;
    gboolean closed;
};

struct _GwySelectionPathClass {
    GwySelectionClass parent_class;
};

static gboolean    module_register                     (void);
static GType       gwy_layer_path_get_type             (void)                         G_GNUC_CONST;
static GType       gwy_selection_path_get_type         (void)                         G_GNUC_CONST;
static void        gwy_selection_path_set_property     (GObject *object,
                                                        guint prop_id,
                                                        const GValue *value,
                                                        GParamSpec *pspec);
static void        gwy_selection_path_get_property     (GObject*object,
                                                        guint prop_id,
                                                        GValue *value,
                                                        GParamSpec *pspec);
static void        gwy_selection_path_serializable_init(GwySerializableIface *iface);
static GByteArray* gwy_selection_path_serialize        (GObject *serializable,
                                                        GByteArray *buffer);
static GObject*    gwy_selection_path_deserialize      (const guchar *buffer,
                                                        gsize size,
                                                        gsize *position);
static GObject*    gwy_selection_path_duplicate        (GObject *object);
static void        gwy_selection_path_clone            (GObject *source,
                                                        GObject *copy);
static gboolean    gwy_selection_path_crop_object      (GwySelection *selection,
                                                        gint i,
                                                        gpointer user_data);
static void        gwy_selection_path_crop             (GwySelection *selection,
                                                        gdouble xmin,
                                                        gdouble ymin,
                                                        gdouble xmax,
                                                        gdouble ymax);
static void        gwy_selection_path_move             (GwySelection *selection,
                                                        gdouble vx,
                                                        gdouble vy);
static void        gwy_selection_path_set_slackness    (GwySelectionPath *selection,
                                                        gdouble slackness);
static void        gwy_selection_path_set_closed       (GwySelectionPath *selection,
                                                        gboolean closed);
static void        gwy_layer_path_finalize             (GObject *object);
static void        gwy_layer_path_set_property         (GObject *object,
                                                        guint prop_id,
                                                        const GValue *value,
                                                        GParamSpec *pspec);
static void        gwy_layer_path_get_property         (GObject*object,
                                                        guint prop_id,
                                                        GValue *value,
                                                        GParamSpec *pspec);
static void        gwy_layer_path_draw                 (GwyVectorLayer *layer,
                                                        GdkDrawable *drawable,
                                                        GwyRenderingTarget target);
static void        gwy_layer_path_draw_single_point    (GwyVectorLayer *layer,
                                                        GdkDrawable *drawable,
                                                        GwyDataView *data_view,
                                                        GwyRenderingTarget target);
static gboolean    gwy_layer_path_motion_notify        (GwyVectorLayer *layer,
                                                        GdkEventMotion *event);
static gboolean    gwy_layer_path_button_pressed       (GwyVectorLayer *layer,
                                                        GdkEventButton *event);
static gboolean    gwy_layer_path_button_released      (GwyVectorLayer *layer,
                                                        GdkEventButton *event);
static gboolean    gwy_layer_path_key_pressed          (GwyVectorLayer *layer,
                                                        GdkEventKey *event);
static void        gwy_layer_path_set_thickness        (GwyLayerPath *layer,
                                                        gint thickness);
static void        gwy_layer_path_realize              (GwyDataViewLayer *dlayer);
static void        gwy_layer_path_unrealize            (GwyDataViewLayer *dlayer);
static void        add_point_to_either_end             (GwyVectorLayer *layer,
                                                        gdouble xreal,
                                                        gdouble yreal,
                                                        gdouble *xy);
static gint        gwy_layer_path_near_point           (GwyVectorLayer *layer,
                                                        gdouble xreal,
                                                        gdouble yreal);

/* Allow to express intent. */
#define gwy_layer_path_undraw        gwy_layer_path_draw

static GwySerializableIface *gwy_selection_path_serializable_parent_iface;

static GwyModuleInfo module_info = {
    GWY_MODULE_ABI_VERSION,
    &module_register,
    N_("Layer allowing selection of a single long curve."),
    "Yeti <yeti@gwyddion.net>",
    "1.2",
    "David Nečas (Yeti)",
    "2016",
};

GWY_MODULE_QUERY2(module_info, path)

G_DEFINE_TYPE_EXTENDED
    (GwySelectionPath, gwy_selection_path, GWY_TYPE_SELECTION, 0,
     GWY_IMPLEMENT_SERIALIZABLE(gwy_selection_path_serializable_init))
G_DEFINE_TYPE(GwyLayerPath, gwy_layer_path, GWY_TYPE_VECTOR_LAYER)

static gboolean
module_register(void)
{
    gwy_layer_func_register(GWY_TYPE_LAYER_PATH);
    return TRUE;
}

static void
gwy_selection_path_class_init(GwySelectionPathClass *klass)
{
    GObjectClass *gobject_class = G_OBJECT_CLASS(klass);
    GwySelectionClass *sel_class = GWY_SELECTION_CLASS(klass);

    gobject_class->set_property = gwy_selection_path_set_property;
    gobject_class->get_property = gwy_selection_path_get_property;

    sel_class->object_size = OBJECT_SIZE;
    sel_class->crop = gwy_selection_path_crop;
    sel_class->move = gwy_selection_path_move;

    g_object_class_install_property
        (gobject_class,
         PROP_SLACKNESS,
         g_param_spec_double("slackness",
                             "Slackness",
                             "Slackness parameter of the spline curve",
                             0.0, G_SQRT2, 1.0/G_SQRT2,
                             G_PARAM_READABLE | G_PARAM_WRITABLE));

    g_object_class_install_property
        (gobject_class,
         PROP_CLOSED,
         g_param_spec_boolean("closed",
                              "Closed",
                              "Whether the curve is closed, as opposed to "
                              "open-ended.",
                              FALSE,
                              G_PARAM_READWRITE));
}

static void
gwy_selection_path_serializable_init(GwySerializableIface *iface)
{
    gwy_selection_path_serializable_parent_iface
        = g_type_interface_peek_parent(iface);

    iface->serialize = gwy_selection_path_serialize;
    iface->deserialize = gwy_selection_path_deserialize;
    iface->duplicate = gwy_selection_path_duplicate;
    iface->clone = gwy_selection_path_clone;
}

static void
gwy_layer_path_class_init(GwyLayerPathClass *klass)
{
    GObjectClass *gobject_class = G_OBJECT_CLASS(klass);
    GwyDataViewLayerClass *layer_class = GWY_DATA_VIEW_LAYER_CLASS(klass);
    GwyVectorLayerClass *vector_class = GWY_VECTOR_LAYER_CLASS(klass);

    gwy_debug("");

    gobject_class->finalize = gwy_layer_path_finalize;
    gobject_class->set_property = gwy_layer_path_set_property;
    gobject_class->get_property = gwy_layer_path_get_property;

    layer_class->realize = gwy_layer_path_realize;
    layer_class->unrealize = gwy_layer_path_unrealize;

    vector_class->selection_type = GWY_TYPE_SELECTION_PATH;
    vector_class->draw = gwy_layer_path_draw;
    vector_class->motion_notify = gwy_layer_path_motion_notify;
    vector_class->button_press = gwy_layer_path_button_pressed;
    vector_class->button_release = gwy_layer_path_button_released;
    vector_class->key_press = gwy_layer_path_key_pressed;

    g_object_class_install_property
        (gobject_class,
         PROP_THICKNESS,
         g_param_spec_int("thickness",
                          "Thickness",
                          "Radius of marker to draw",
                          -1, 1024, 1,
                          G_PARAM_READWRITE));
}

static void
gwy_selection_path_init(GwySelectionPath *selection)
{
    /* Set max. number of objects to one */
    g_array_set_size(GWY_SELECTION(selection)->objects, OBJECT_SIZE);
    selection->slackness = 1.0/G_SQRT2;
    selection->closed = FALSE;
}

static GByteArray*
gwy_selection_path_serialize(GObject *serializable,
                             GByteArray *buffer)
{
    GwySelection *selection;

    g_return_val_if_fail(GWY_IS_SELECTION_PATH(serializable), NULL);

    selection = GWY_SELECTION(serializable);
    {
        guint32 len = selection->n * OBJECT_SIZE;
        guint32 max = selection->objects->len/OBJECT_SIZE;
        gboolean closed = GWY_SELECTION_PATH(selection)->closed;
        gdouble slackness = GWY_SELECTION_PATH(selection)->slackness;
        gpointer pdata = len ? &selection->objects->data : NULL;
        GwySerializeSpec spec[] = {
            { 'i', "max",       &max,       NULL, },
            { 'b', "closed",    &closed,    NULL, },
            { 'd', "slackness", &slackness, NULL, },
            { 'D', "data",      pdata,      &len, },
        };

        return gwy_serialize_pack_object_struct(buffer,
                                                GWY_SELECTION_PATH_TYPE_NAME,
                                                G_N_ELEMENTS(spec), spec);
    }
}

static GObject*
gwy_selection_path_deserialize(const guchar *buffer,
                               gsize size,
                               gsize *position)
{
    gdouble *data = NULL;
    guint32 len = 0, max = 0;
    gdouble slackness = 1.0/G_SQRT2;
    gboolean closed = FALSE;
    GwySerializeSpec spec[] = {
        { 'i', "max",       &max,       NULL, },
        { 'b', "closed",    &closed,    NULL, },
        { 'd', "slackness", &slackness, NULL, },
        { 'D', "data",      &data,      &len, },
    };
    GwySelection *selection;

    g_return_val_if_fail(buffer, NULL);

    if (!gwy_serialize_unpack_object_struct(buffer, size, position,
                                            GWY_SELECTION_PATH_TYPE_NAME,
                                            G_N_ELEMENTS(spec), spec)) {
        g_free(data);
        return NULL;
    }

    selection = g_object_new(GWY_TYPE_SELECTION_PATH, NULL);
    GWY_SELECTION_PATH(selection)->closed = closed;
    GWY_SELECTION_PATH(selection)->slackness = slackness;
    g_array_set_size(selection->objects, 0);
    if (data && len) {
        if (len % OBJECT_SIZE)
            g_warning("Selection data size not multiple of object size. "
                      "Ignoring it.");
        else {
            g_array_append_vals(selection->objects, data, len);
            selection->n = len/OBJECT_SIZE;
        }
        g_free(data);
    }
    if (max > selection->n)
        g_array_set_size(selection->objects, max*OBJECT_SIZE);

    return (GObject*)selection;
}

static GObject*
gwy_selection_path_duplicate(GObject *object)
{
    GObject *copy;

    copy = gwy_selection_path_serializable_parent_iface->duplicate(object);
    GWY_SELECTION_PATH(copy)->closed = GWY_SELECTION_PATH(object)->closed;
    GWY_SELECTION_PATH(copy)->slackness
        = GWY_SELECTION_PATH(object)->slackness;

    return copy;
}

static void
gwy_selection_path_clone(GObject *source,
                         GObject *copy)
{
    GWY_SELECTION_PATH(copy)->closed
        = GWY_SELECTION_PATH(source)->closed;
    GWY_SELECTION_PATH(copy)->slackness
        = GWY_SELECTION_PATH(source)->slackness;
    /* Must do this at the end, it emits a signal. */
    gwy_selection_path_serializable_parent_iface->clone(source, copy);
}

static void
gwy_selection_path_set_property(GObject *object,
                                guint prop_id,
                                const GValue *value,
                                GParamSpec *pspec)
{
    GwySelectionPath *selection = GWY_SELECTION_PATH(object);

    switch (prop_id) {
        case PROP_SLACKNESS:
        gwy_selection_path_set_slackness(selection, g_value_get_double(value));
        break;

        case PROP_CLOSED:
        gwy_selection_path_set_closed(selection, g_value_get_boolean(value));
        break;

        default:
        G_OBJECT_WARN_INVALID_PROPERTY_ID(object, prop_id, pspec);
        break;
    }
}

static void
gwy_selection_path_get_property(GObject*object,
                                guint prop_id,
                                GValue *value,
                                GParamSpec *pspec)
{
    GwySelectionPath *selection = GWY_SELECTION_PATH(object);

    switch (prop_id) {
        case PROP_SLACKNESS:
        g_value_set_double(value, selection->slackness);
        break;

        case PROP_CLOSED:
        g_value_set_boolean(value, selection->closed);
        break;

        default:
        G_OBJECT_WARN_INVALID_PROPERTY_ID(object, prop_id, pspec);
        break;
    }
}

/* FIXME: Is this reasonable?  The entire selection is one line so we may
 * just want to kill it as a whole if it sticks outside. */
static gboolean
gwy_selection_path_crop_object(GwySelection *selection,
                               gint i,
                               gpointer user_data)
{
    const gdouble *minmax = (const gdouble*)user_data;
    gdouble xy[OBJECT_SIZE];

    gwy_selection_get_object(selection, i, xy);
    return (xy[1] >= minmax[1] && xy[1] <= minmax[3]
            && xy[0] >= minmax[0] && xy[0] <= minmax[2]);
}

static void
gwy_selection_path_crop(GwySelection *selection,
                        gdouble xmin,
                        gdouble ymin,
                        gdouble xmax,
                        gdouble ymax)
{
    gdouble minmax[4] = { xmin, ymin, xmax, ymax };

    gwy_selection_filter(selection, gwy_selection_path_crop_object, minmax);
}

static void
gwy_selection_path_move(GwySelection *selection,
                        gdouble vx,
                        gdouble vy)
{
    gdouble *data = (gdouble*)selection->objects->data;
    guint i, n = selection->objects->len/OBJECT_SIZE;

    for (i = 0; i < n; i++) {
        data[OBJECT_SIZE*i + 0] += vx;
        data[OBJECT_SIZE*i + 1] += vy;
    }
}

static void
gwy_selection_path_set_slackness(GwySelectionPath *selection,
                                 gdouble slackness)
{
    g_return_if_fail(slackness >= 0.0 && slackness <= G_SQRT2);
    if (slackness == selection->slackness)
        return;

    selection->slackness = slackness;
    g_object_notify(G_OBJECT(selection), "slackness");
}

static void
gwy_selection_path_set_closed(GwySelectionPath *selection,
                              gboolean closed)
{
    if (!closed == !selection->closed)
        return;

    selection->closed = !!closed;
    g_object_notify(G_OBJECT(selection), "closed");
}

static void
gwy_layer_path_init(GwyLayerPath *layer)
{
    layer->point_numbers = FALSE;
    layer->thickness = 0;
    layer->spline = gwy_spline_new();
}

static void
gwy_layer_path_finalize(GObject *object)
{
    GwyLayerPath *layer = GWY_LAYER_PATH(object);

    gwy_spline_free(layer->spline);
    if (G_OBJECT_CLASS(gwy_layer_path_parent_class)->finalize)
        G_OBJECT_CLASS(gwy_layer_path_parent_class)->finalize(object);
}

static void
gwy_layer_path_set_property(GObject *object,
                            guint prop_id,
                            const GValue *value,
                            GParamSpec *pspec)
{
    GwyLayerPath *layer = GWY_LAYER_PATH(object);

    switch (prop_id) {
        case PROP_THICKNESS:
        gwy_layer_path_set_thickness(layer, g_value_get_int(value));
        break;

        default:
        G_OBJECT_WARN_INVALID_PROPERTY_ID(object, prop_id, pspec);
        break;
    }
}

static void
gwy_layer_path_get_property(GObject*object,
                            guint prop_id,
                            GValue *value,
                            GParamSpec *pspec)
{
    GwyLayerPath *layer = GWY_LAYER_PATH(object);

    switch (prop_id) {
        case PROP_THICKNESS:
        g_value_set_int(value, layer->thickness);
        break;

        default:
        G_OBJECT_WARN_INVALID_PROPERTY_ID(object, prop_id, pspec);
        break;
    }
}

static void
gwy_layer_path_draw(GwyVectorLayer *layer,
                    GdkDrawable *drawable,
                    GwyRenderingTarget target)
{
    GwyDataView *data_view;
    GwyLayerPath *layer_path;
    GwySelection *selection = layer->selection;
    GwySelectionPath *selpath = GWY_SELECTION_PATH(selection);
    GwySpline *spline;
    gdouble xy[OBJECT_SIZE];
    GwyXY *screenxy;
    const GwyXY *segmentxy;
    GdkPoint *ixy;
    gint width, height, xsize, ysize, thickness;
    gdouble xreal, yreal;
    guint i, n, nseg;

    if (!layer->selection)
        return;

    g_return_if_fail(GDK_IS_DRAWABLE(drawable));
    data_view = GWY_DATA_VIEW(GWY_DATA_VIEW_LAYER(layer)->parent);
    g_return_if_fail(data_view);

    layer_path = GWY_LAYER_PATH(layer);
    thickness = layer_path->thickness;
    n = selection->n;
    if (!n)
        return;

    if (n == 1) {
        /* If there is just a single point draw it as a cross. */
        gwy_layer_path_draw_single_point(layer, drawable, data_view, target);
        return;
    }

    /* Scale coordinates to screen/image pixels. */
    gdk_drawable_get_size(drawable, &width, &height);
    gwy_data_view_get_pixel_data_sizes(data_view, &xsize, &ysize);
    screenxy = g_new(GwyXY, n);
    gwy_data_view_get_real_data_sizes(data_view, &xreal, &yreal);

    for (i = 0; i < n; i++) {
        GwyXY *pt = screenxy + i;

        gwy_selection_get_object(selection, i, xy);
        switch (target) {
            case GWY_RENDERING_TARGET_SCREEN:
            gwy_data_view_coords_real_to_xy_float(data_view, xy[0], xy[1],
                                                  &pt->x, &pt->y);
            break;

            case GWY_RENDERING_TARGET_PIXMAP_IMAGE:
            pt->x = xy[0]*width/xreal;
            pt->y = xy[1]*height/yreal;
            break;

            default:
            g_return_if_reached();
            break;
        }
    }

    /* Construct a segmented approximation of the spline. */
    spline = layer_path->spline;
    gwy_spline_set_points(spline, screenxy, n);

    gwy_spline_set_closed(spline, selpath->closed);
    gwy_spline_set_slackness(spline, selpath->slackness);

    if (n == 2 && selpath->closed) {
        /* Do not draw the back line for closed two-point spline because it
         * undraws the first line. */
        gwy_spline_set_closed(spline, FALSE);
    }

    segmentxy = gwy_spline_sample_naturally(spline, &nseg);

    /* Draw the segments. */
    ixy = g_new(GdkPoint, nseg);
    for (i = 0; i < nseg; i++) {
        ixy[i].x = (gint)floor(segmentxy[i].x + 0.001);
        ixy[i].y = (gint)floor(segmentxy[i].y + 0.001);
    }
    gdk_draw_lines(drawable, layer->gc, ixy, nseg);
    g_free(ixy);

    if (thickness > 1) {
        const GwyXY *tangents
            = gwy_spline_get_tangents(spline);

        for (i = 0; i < n; i++) {
            const GwyXY *t = tangents + i;
            gint xl0, yl0, xl1, yl1;
            gdouble xd, yd;

            if (t->x == 0.0 && t->y == 0.0)
                continue;

            xd = thickness*t->y/2;
            yd = -thickness*t->x/2;

            xl0 = (gint)floor(screenxy[i].x + xd + 0.001);
            yl0 = (gint)floor(screenxy[i].y + yd + 0.001);
            xl1 = (gint)floor(screenxy[i].x - xd + 0.001);
            yl1 = (gint)floor(screenxy[i].y - yd + 0.001);

            gdk_draw_line(drawable, layer->gc, xl0, yl0, xl1, yl1);
        }
    }

    g_free(screenxy);
}

static void
gwy_layer_path_draw_single_point(GwyVectorLayer *layer,
                                 GdkDrawable *drawable,
                                 GwyDataView *data_view,
                                 GwyRenderingTarget target)
{
    gint xc, yc, xmin, xmax, ymin, ymax, size;
    gint dwidth, dheight, xsize, ysize;
    gdouble xreal, yreal, xm, ym;
    gdouble xy[2];

    g_return_if_fail(gwy_vector_layer_n_selected(layer) == 1);
    gwy_selection_get_object(layer->selection, 0, xy);

    gdk_drawable_get_size(drawable, &dwidth, &dheight);
    gwy_data_view_get_pixel_data_sizes(data_view, &xsize, &ysize);
    switch (target) {
        case GWY_RENDERING_TARGET_SCREEN:
        gwy_data_view_coords_real_to_xy(data_view, xy[0], xy[1], &xc, &yc);
        xmin = xc - CROSS_SIZE + 1;
        xmax = xc + CROSS_SIZE - 1;
        ymin = yc - CROSS_SIZE + 1;
        ymax = yc + CROSS_SIZE - 1;
        gwy_data_view_coords_xy_clamp(data_view, &xmin, &ymin);
        gwy_data_view_coords_xy_clamp(data_view, &xmax, &ymax);
        break;

        case GWY_RENDERING_TARGET_PIXMAP_IMAGE:
        xm = (gdouble)dwidth/xsize;
        ym = (gdouble)dheight/ysize;
        size = GWY_ROUND(fmax(sqrt(xm*ym)*(CROSS_SIZE - 1), 1.0));
        gwy_data_view_get_real_data_sizes(data_view, &xreal, &yreal);
        xc = floor(xy[0]*dwidth/xreal);
        yc = floor(xy[1]*dheight/yreal);

        xmin = xc - size;
        xmax = xc + size;
        ymin = yc - size;
        ymax = yc + size;
        break;

        default:
        g_return_if_reached();
        break;
    }
    gdk_draw_line(drawable, layer->gc, xmin, yc, xmax, yc);
    gdk_draw_line(drawable, layer->gc, xc, ymin, xc, ymax);
}

static gboolean
gwy_layer_path_motion_notify(GwyVectorLayer *layer,
                             GdkEventMotion *event)
{
    GwyDataView *data_view;
    GdkWindow *window;
    GdkCursor *cursor;
    gint x, y, i;
    gdouble xreal, yreal, xy[OBJECT_SIZE];

    if (!layer->selection)
        return FALSE;

    /* FIXME: No cursor change hint -- a bit too crude? */
    if (!layer->editable)
        return FALSE;

    data_view = GWY_DATA_VIEW(GWY_DATA_VIEW_LAYER(layer)->parent);
    g_return_val_if_fail(data_view, FALSE);
    window = GTK_WIDGET(data_view)->window;

    i = layer->selecting;
    if (event->is_hint)
        gdk_window_get_pointer(window, &x, &y, NULL);
    else {
        x = event->x;
        y = event->y;
    }
    gwy_debug("x = %d, y = %d", x, y);
    gwy_data_view_coords_xy_clamp(data_view, &x, &y);
    gwy_data_view_coords_xy_to_real(data_view, x, y, &xreal, &yreal);
    if (i > -1)
        gwy_selection_get_object(layer->selection, i, xy);
    if (i > -1 && xreal == xy[0] && yreal == xy[1])
        return FALSE;

    if (!layer->button) {
        i = gwy_layer_path_near_point(layer, xreal, yreal);
        cursor = GWY_LAYER_PATH(layer)->near_cursor;
        gdk_window_set_cursor(window, i == -1 ? NULL : cursor);
        return FALSE;
    }

    gwy_layer_path_undraw(layer, window, GWY_RENDERING_TARGET_SCREEN);
    g_assert(layer->selecting != -1);
    xy[0] = xreal;
    xy[1] = yreal;
    gwy_selection_set_object(layer->selection, i, xy);
    gwy_layer_path_draw(layer, window, GWY_RENDERING_TARGET_SCREEN);

    return FALSE;
}

static gboolean
gwy_layer_path_button_pressed(GwyVectorLayer *layer,
                              GdkEventButton *event)
{
    GwyDataView *data_view;
    GdkWindow *window;
    gint x, y, i;
    gdouble xreal, yreal, xy[OBJECT_SIZE];

    if (!layer->selection)
        return FALSE;

    if (event->button != 1)
        return FALSE;

    data_view = GWY_DATA_VIEW(GWY_DATA_VIEW_LAYER(layer)->parent);
    g_return_val_if_fail(data_view, FALSE);
    window = GTK_WIDGET(data_view)->window;

    x = event->x;
    y = event->y;
    gwy_data_view_coords_xy_clamp(data_view, &x, &y);
    gwy_debug("[%d,%d]", x, y);
    /* do nothing when we are outside */
    if (x != event->x || y != event->y)
        return FALSE;

    gwy_data_view_coords_xy_to_real(data_view, x, y, &xreal, &yreal);
    xy[0] = xreal;
    xy[1] = yreal;

    i = gwy_layer_path_near_point(layer, xreal, yreal);
    /* just emit "object-chosen" when selection is not editable */
    if (!layer->editable) {
        if (i >= 0)
            gwy_vector_layer_object_chosen(layer, i);
        return FALSE;
    }
    /* handle existing selection */
    if (i >= 0) {
        layer->selecting = i;
    }
    else {
        /* add an object, or do nothing when maximum is reached */
        i = -1;
        if (gwy_selection_is_full(layer->selection)) {
            if (gwy_selection_get_max_objects(layer->selection) > 1)
                return FALSE;
            i = 0;
        }
        gwy_layer_path_undraw(layer, window, GWY_RENDERING_TARGET_SCREEN);
        add_point_to_either_end(layer, xreal, yreal, xy);
        gwy_layer_path_draw(layer, window, GWY_RENDERING_TARGET_SCREEN);
    }
    layer->button = event->button;

    gdk_window_set_cursor(window, GWY_LAYER_PATH(layer)->move_cursor);
    gwy_vector_layer_object_chosen(layer, layer->selecting);

    return FALSE;
}

static gboolean
gwy_layer_path_button_released(GwyVectorLayer *layer,
                               GdkEventButton *event)
{
    GwyDataView *data_view;
    GdkWindow *window;
    GdkCursor *cursor;
    gint x, y, i;
    gdouble xreal, yreal, xy[OBJECT_SIZE];
    gboolean outside;

    if (!layer->selection)
        return FALSE;

    if (!layer->button)
        return FALSE;

    data_view = GWY_DATA_VIEW(GWY_DATA_VIEW_LAYER(layer)->parent);
    g_return_val_if_fail(data_view, FALSE);
    window = GTK_WIDGET(data_view)->window;

    gwy_layer_path_undraw(layer, window, GWY_RENDERING_TARGET_SCREEN);
    layer->button = 0;
    x = event->x;
    y = event->y;
    i = layer->selecting;
    gwy_debug("i = %d", i);
    gwy_data_view_coords_xy_clamp(data_view, &x, &y);
    outside = (event->x != x) || (event->y != y);
    gwy_data_view_coords_xy_to_real(data_view, x, y, &xreal, &yreal);
    xy[0] = xreal;
    xy[1] = yreal;
    gwy_selection_set_object(layer->selection, i, xy);
    gwy_layer_path_draw(layer, window, GWY_RENDERING_TARGET_SCREEN);

    layer->selecting = -1;
    i = gwy_layer_path_near_point(layer, xreal, yreal);
    outside = outside || (i == -1);
    cursor = GWY_LAYER_PATH(layer)->near_cursor;
    gdk_window_set_cursor(window, outside ? NULL : cursor);
    gwy_selection_finished(layer->selection);

    return FALSE;
}

static gboolean
gwy_layer_path_key_pressed(GwyVectorLayer *layer,
                           GdkEventKey *event)
{
    gboolean large_step = (event->state & (GDK_CONTROL_MASK | GDK_MOD1_MASK));
    GwyDataView *data_view;
    guint keyval = event->keyval;
    gint chosen = layer->chosen, xcurr, ycurr, xnew, ynew, move_distance;
    gdouble xy[2];

    if (chosen < 0
        || chosen >= gwy_selection_get_data(layer->selection, NULL))
        return FALSE;

    if (keyval != GDK_Left && keyval != GDK_Right
        && keyval != GDK_Up && keyval != GDK_Down)
        return FALSE;

    data_view = GWY_DATA_VIEW(GWY_DATA_VIEW_LAYER(layer)->parent);
    g_return_val_if_fail(data_view, FALSE);

    gwy_selection_get_object(layer->selection, chosen, xy);
    gwy_data_view_coords_real_to_xy(data_view, xy[0], xy[1], &xcurr, &ycurr);
    xnew = xcurr;
    ynew = ycurr;
    move_distance = (large_step ? 16 : 1);
    if (keyval == GDK_Left)
        xnew -= move_distance;
    else if (keyval == GDK_Right)
        xnew += move_distance;
    else if (keyval == GDK_Up)
        ynew -= move_distance;
    else if (keyval == GDK_Down)
        ynew += move_distance;
    gwy_data_view_coords_xy_clamp(data_view, &xnew, &ynew);

    if (xnew != xcurr || ynew != ycurr) {
        gwy_data_view_coords_xy_to_real(data_view, xnew, ynew, xy+0, xy+1);
        gwy_selection_set_object(layer->selection, chosen, xy);
    }

    return TRUE;
}

static void
gwy_layer_path_set_thickness(GwyLayerPath *layer, gint thickness)
{
    GwyVectorLayer *vector_layer;
    GtkWidget *parent;

    g_return_if_fail(GWY_IS_LAYER_PATH(layer));
    vector_layer = GWY_VECTOR_LAYER(layer);
    parent = GWY_DATA_VIEW_LAYER(layer)->parent;

    if (thickness == layer->thickness)
        return;

    if (parent && GTK_WIDGET_REALIZED(parent))
        gwy_layer_path_undraw(vector_layer, parent->window,
                               GWY_RENDERING_TARGET_SCREEN);
    layer->thickness = thickness;
    if (parent && GTK_WIDGET_REALIZED(parent))
        gwy_layer_path_draw(vector_layer, parent->window,
                             GWY_RENDERING_TARGET_SCREEN);
    g_object_notify(G_OBJECT(layer), "thickness");
}

static void
gwy_layer_path_realize(GwyDataViewLayer *dlayer)
{
    GwyLayerPath *layer;
    GdkDisplay *display;

    GWY_DATA_VIEW_LAYER_CLASS(gwy_layer_path_parent_class)->realize(dlayer);
    layer = GWY_LAYER_PATH(dlayer);
    display = gtk_widget_get_display(dlayer->parent);
    layer->near_cursor = gdk_cursor_new_for_display(display, GDK_FLEUR);
    layer->move_cursor = gdk_cursor_new_for_display(display, GDK_CROSS);
}

static void
gwy_layer_path_unrealize(GwyDataViewLayer *dlayer)
{
    GwyLayerPath *layer;

    layer = GWY_LAYER_PATH(dlayer);
    gdk_cursor_unref(layer->near_cursor);
    gdk_cursor_unref(layer->move_cursor);

    GWY_DATA_VIEW_LAYER_CLASS(gwy_layer_path_parent_class)->unrealize(dlayer);
}

static void
add_point_to_either_end(GwyVectorLayer *layer, gdouble xreal, gdouble yreal,
                        gdouble *xy)
{
    gdouble metric[4];
    gdouble firstlast[2*OBJECT_SIZE];
    gdouble *data;
    gint n, i;

    layer->selecting = 0;    /* avoid "update" signal emission */

    if ((n = gwy_vector_layer_n_selected(layer)) < 2) {
        layer->selecting = gwy_selection_set_object(layer->selection, -1, xy);
        return;
    }

    gwy_data_view_get_metric(GWY_DATA_VIEW(GWY_DATA_VIEW_LAYER(layer)->parent),
                             metric);
    gwy_selection_get_object(layer->selection, 0, firstlast+0);
    gwy_selection_get_object(layer->selection, n-1, firstlast+OBJECT_SIZE);
    i = gwy_math_find_nearest_point(xreal, yreal, NULL, 2, firstlast, metric);
    if (i == 1) {
        layer->selecting = gwy_selection_set_object(layer->selection, -1, xy);
        return;
    }

    data = g_new(gdouble, OBJECT_SIZE*(n + 1));
    gwy_selection_get_data(layer->selection, data + OBJECT_SIZE);
    memcpy(data, xy, OBJECT_SIZE*sizeof(gdouble));
    gwy_selection_set_data(layer->selection, n+1, data);
    g_free(data);
}

static gint
gwy_layer_path_near_point(GwyVectorLayer *layer,
                          gdouble xreal, gdouble yreal)
{
    gdouble d2min, metric[4];
    gint i, n;

    if (!(n = gwy_vector_layer_n_selected(layer)) || layer->focus >= n)
        return -1;

    gwy_data_view_get_metric(GWY_DATA_VIEW(GWY_DATA_VIEW_LAYER(layer)->parent),
                             metric);
    if (layer->focus >= 0) {
        gdouble xy[OBJECT_SIZE];

        gwy_selection_get_object(layer->selection, layer->focus, xy);
        i = gwy_math_find_nearest_point(xreal, yreal, &d2min, 1, xy, metric);
    }
    else {
        const gdouble *xy = gwy_vector_layer_selection_data(layer);
        i = gwy_math_find_nearest_point(xreal, yreal, &d2min, n, xy, metric);
    }
    if (d2min > PROXIMITY_DISTANCE*PROXIMITY_DISTANCE)
        return -1;
    return i;
}

/* vim: set cin et ts=4 sw=4 cino=>1s,e0,n0,f0,{0,}0,^0,\:1s,=0,g1s,h0,t0,+1s,c3,(0,u0 : */