File: selectionmanager.c

package info (click to toggle)
gwyddion 2.67-1
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 54,152 kB
  • sloc: ansic: 412,023; python: 7,885; sh: 5,492; makefile: 4,957; xml: 3,954; cpp: 2,107; pascal: 418; perl: 154; ruby: 130
file content (813 lines) | stat: -rw-r--r-- 30,111 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
/*
 *  $Id: selectionmanager.c 26745 2024-10-18 15:17:53Z yeti-dn $
 *  Copyright (C) 2009-2022 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 <gtk/gtk.h>
#include <libgwyddion/gwymacros.h>
#include <libgwymodule/gwymodule-tool.h>
#include <libgwydgets/gwystock.h>
#include <app/gwymoduleutils.h>
#include <app/gwyapp.h>

/* The GtkTargetEntry for tree model drags.
 * FIXME: Is it Gtk+ private or what? */
#define GTK_TREE_MODEL_ROW \
    { "GTK_TREE_MODEL_ROW", GTK_TARGET_SAME_APP, 0 }

/* XXX: Copied from data browser. Kind of internal. */
#define page_id_key "gwy-app-data-browser-page-id"
#define container_key "gwy-app-data-browser-container"

enum {
    PAGENO_SHIFT = 16,
};

enum {
    NLAYERTYPES = 9
};

enum {
    COLUMN_ID, COLUMN_OBJECT, NCOLUMNS
};

enum {
    PARAM_ALL_FILES,
};

typedef struct {
    GwySelection *selection;
    const gchar *name;
    GwySIUnit *xyunit;
    gdouble origin[2];
} DistributeData;

#define GWY_TYPE_TOOL_SELECTION_MANAGER            (gwy_tool_selection_manager_get_type())
#define GWY_TOOL_SELECTION_MANAGER(obj)            (G_TYPE_CHECK_INSTANCE_CAST((obj), GWY_TYPE_TOOL_SELECTION_MANAGER, GwyToolSelectionManager))
#define GWY_IS_TOOL_SELECTION_MANAGER(obj)         (G_TYPE_CHECK_INSTANCE_TYPE((obj), GWY_TYPE_TOOL_SELECTION_MANAGER))
#define GWY_TOOL_SELECTION_MANAGER_GET_CLASS(obj)  (G_TYPE_INSTANCE_GET_CLASS((obj), GWY_TYPE_TOOL_SELECTION_MANAGER, GwyToolSelectionManagerClass))

typedef struct _GwyToolSelectionManager      GwyToolSelectionManager;
typedef struct _GwyToolSelectionManagerClass GwyToolSelectionManagerClass;

struct _GwyToolSelectionManager {
    GwyPlainTool parent_instance;

    GwyParams *params;
    gboolean in_setup;

    GtkListStore *model;
    GtkWidget *treeview;
    GtkWidget *allfiles;
    GtkWidget *distribute;
    GtkWidget *copy;
    GtkWidget *export;
    GtkWidget *delete;

    /* potential class data */
    GType layer_types[NLAYERTYPES];
    GType selection_types[NLAYERTYPES];
};

struct _GwyToolSelectionManagerClass {
    GwyPlainToolClass parent_class;
};

static gboolean     module_register                             (void);
static GwyParamDef* define_module_params                        (void);
static GType        gwy_tool_selection_manager_get_type         (void)                           G_GNUC_CONST;
static void         gwy_tool_selection_manager_finalize         (GObject *object);
static void         gwy_tool_selection_manager_init_dialog      (GwyToolSelectionManager *tool);
static void         gwy_tool_selection_manager_data_switched    (GwyTool *gwytool,
                                                                 GwyDataView *data_view);
static void         gwy_tool_selection_manager_response         (GwyTool *gwytool,
                                                                 gint response_id);
static void         clear_selection                             (GwyToolSelectionManager *tool);
static void         gwy_tool_selection_manager_selection_changed(GwyToolSelectionManager *tool,
                                                                 GtkTreeSelection *selection);
static void         gwy_tool_selection_manager_all_files_changed(GwyToolSelectionManager *tool,
                                                                 GtkToggleButton *button);
static gboolean     key_pressed                                 (GwyToolSelectionManager *tool,
                                                                 GdkEventKey *event,
                                                                 GtkTreeView *treeview);
static void         distribute                                  (GwyToolSelectionManager *tool);
static void         distribute_one                              (GwyContainer *container,
                                                                 DistributeData *distdata);
static void         copy_selection_to_clipboard                 (GwyToolSelectionManager *tool);
static void         export_selection                            (GwyToolSelectionManager *tool);
static void         delete_selection                            (GwyToolSelectionManager *tool);
static gchar*       create_report                               (GwyToolSelectionManager *tool);
static void         setup_layer                                 (GwyToolSelectionManager *tool,
                                                                 guint current,
                                                                 GQuark quark);

static GwyModuleInfo module_info = {
    GWY_MODULE_ABI_VERSION,
    &module_register,
    N_("Selection manager tool which lists, clears and copies selections."),
    "Yeti <yeti@gwyddion.net>",
    "3.1",
    "David Nečas (Yeti)",
    "2009",
};

static const gchar *const layer_types[NLAYERTYPES] = {
    "GwyLayerAxis",
    "GwyLayerCross",
    "GwyLayerEllipse",
    "GwyLayerLattice",
    "GwyLayerLine",
    "GwyLayerPath",
    "GwyLayerPoint",
    "GwyLayerProjective",
    "GwyLayerRectangle",
};

GWY_MODULE_QUERY2(module_info, selectionmanager)

G_DEFINE_TYPE(GwyToolSelectionManager, gwy_tool_selection_manager, GWY_TYPE_PLAIN_TOOL)

static gboolean
module_register(void)
{
    gwy_tool_func_register(GWY_TYPE_TOOL_SELECTION_MANAGER);

    return TRUE;
}

static GwyParamDef*
define_module_params(void)
{
    static GwyParamDef *paramdef = NULL;

    if (paramdef)
        return paramdef;

    paramdef = gwy_param_def_new();
    gwy_param_def_set_function_name(paramdef, "selectionmanager");
    gwy_param_def_add_boolean(paramdef, PARAM_ALL_FILES, "allfiles", _("to _all files"), FALSE);

    return paramdef;
}

static void
gwy_tool_selection_manager_class_init(GwyToolSelectionManagerClass *klass)
{
    GwyToolClass *tool_class = GWY_TOOL_CLASS(klass);
    GObjectClass *gobject_class = G_OBJECT_CLASS(klass);

    gobject_class->finalize = gwy_tool_selection_manager_finalize;

    tool_class->stock_id = GWY_STOCK_SELECTIONS;
    tool_class->title = _("Selection Manager");
    tool_class->tooltip = _("Display, copy and export selections");
    tool_class->prefix = "/module/selectionmanager";
    tool_class->default_height = 280;
    tool_class->data_switched = gwy_tool_selection_manager_data_switched;
    tool_class->response = gwy_tool_selection_manager_response;
}

static void
gwy_tool_selection_manager_finalize(GObject *object)
{
    GwyToolSelectionManager *tool = GWY_TOOL_SELECTION_MANAGER(object);

    gwy_params_save_to_settings(tool->params);
    GWY_OBJECT_UNREF(tool->params);
    GWY_OBJECT_UNREF(tool->model);

    G_OBJECT_CLASS(gwy_tool_selection_manager_parent_class)->finalize(object);
}

static void
gwy_tool_selection_manager_init(GwyToolSelectionManager *tool)
{
    GwyPlainTool *plain_tool = GWY_PLAIN_TOOL(tool);
    GtkTreeSelection *selection;
    guint i;

    for (i = 0; i < NLAYERTYPES; i++) {
        GwyVectorLayerClass *klass;
        GType type;

        if (!(type = gwy_plain_tool_check_layer_type(plain_tool, layer_types[i])))
            return;

        tool->layer_types[i] = type;
        klass = g_type_class_ref(type);
        tool->selection_types[i] = gwy_vector_layer_class_get_selection_type(klass);
        g_type_class_unref(klass);
    }
    tool->in_setup = TRUE;
    tool->params = gwy_params_new_from_settings(define_module_params());

    tool->model = gtk_list_store_new(NCOLUMNS, G_TYPE_INT, G_TYPE_OBJECT);
    g_object_set_data(G_OBJECT(tool->model), page_id_key, GUINT_TO_POINTER(GWY_PAGE_NOPAGE + PAGENO_SHIFT));

    gwy_tool_selection_manager_init_dialog(tool);
    tool->in_setup = FALSE;

    selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(tool->treeview));
    gwy_tool_selection_manager_selection_changed(tool, selection);
}

static void
render_name(G_GNUC_UNUSED GtkTreeViewColumn *column,
            GtkCellRenderer *renderer,
            GtkTreeModel *model,
            GtkTreeIter *iter,
            G_GNUC_UNUSED gpointer user_data)
{
    GQuark quark;
    const gchar *s;

    gtk_tree_model_get(model, iter, COLUMN_ID, &quark, -1);
    s = g_quark_to_string(quark);
    g_return_if_fail(s);
    s = strrchr(s, GWY_CONTAINER_PATHSEP);
    g_return_if_fail(s);
    g_object_set(renderer, "text", s+1, NULL);
}

static void
render_type(G_GNUC_UNUSED GtkTreeViewColumn *column,
            GtkCellRenderer *renderer,
            GtkTreeModel *model,
            GtkTreeIter *iter,
            G_GNUC_UNUSED gpointer user_data)
{
    static const struct {
        const gchar *typename;
        const gchar *humanname;
    }
    type_names[] = {
        { "GwySelectionAxis",       N_("Horiz./vert. lines"),    },
        { "GwySelectionCross",      N_("Crosses"),               },
        { "GwySelectionEllipse",    N_("Ellipses"),              },
        { "GwySelectionLattice",    N_("Lattice"),               },
        { "GwySelectionLine",       N_("Lines"),                 },
        { "GwySelectionPath",       N_("Spline path"),           },
        { "GwySelectionPoint",      N_("Points"),                },
        { "GwySelectionProjective", N_("Projective rectangles"), },
        { "GwySelectionRectangle",  N_("Rectangles"),            },
    };

    GwySelection *sel;
    const gchar *name;
    guint i;

    gtk_tree_model_get(model, iter, COLUMN_OBJECT, &sel, -1);
    g_return_if_fail(GWY_IS_SELECTION(sel));
    name = G_OBJECT_TYPE_NAME(sel);
    for (i = 0; i < G_N_ELEMENTS(type_names); i++) {
        if (gwy_strequal(name, type_names[i].typename)) {
            name = _(type_names[i].humanname);
            break;
        }
    }
    g_object_set(renderer, "text", name, NULL);
    g_object_unref(sel);
}

static void
render_objects(G_GNUC_UNUSED GtkTreeViewColumn *column,
               GtkCellRenderer *renderer,
               GtkTreeModel *model,
               GtkTreeIter *iter,
               G_GNUC_UNUSED gpointer user_data)
{
    gchar buffer[16];
    GwySelection *sel;

    gtk_tree_model_get(model, iter, COLUMN_OBJECT, &sel, -1);
    g_return_if_fail(GWY_IS_SELECTION(sel));
    g_snprintf(buffer, sizeof(buffer), "%d", gwy_selection_get_data(sel, NULL));
    g_object_set(renderer, "text", buffer, NULL);
    g_object_unref(sel);
}

static void
gwy_tool_selection_manager_init_dialog(GwyToolSelectionManager *tool)
{
    static const GtkTargetEntry dnd_target_table[] = { GTK_TREE_MODEL_ROW };

    GtkDialog *dialog = GTK_DIALOG(GWY_TOOL(tool)->dialog);
    GtkWidget *scwin, *hbox, *label;
    GtkCellRenderer *renderer;
    GtkTreeViewColumn *column;
    GtkTreeSelection *selection;

    scwin = gtk_scrolled_window_new(NULL, NULL);
    gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scwin), GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC);
    gtk_box_pack_start(GTK_BOX(gtk_dialog_get_content_area(dialog)), scwin, TRUE, TRUE, 0);

    tool->treeview = gtk_tree_view_new_with_model(GTK_TREE_MODEL(tool->model));
    gtk_container_add(GTK_CONTAINER(scwin), tool->treeview);
    gtk_tree_view_enable_model_drag_source(GTK_TREE_VIEW(tool->treeview), GDK_BUTTON1_MASK,
                                           dnd_target_table, G_N_ELEMENTS(dnd_target_table),
                                           GDK_ACTION_COPY);

    selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(tool->treeview));
    gtk_tree_selection_set_mode(selection, GTK_SELECTION_SINGLE);

    column = gtk_tree_view_column_new();
    gtk_tree_view_column_set_title(column, _("Name"));
    gtk_tree_view_append_column(GTK_TREE_VIEW(tool->treeview), column);
    renderer = gtk_cell_renderer_text_new();
    gtk_tree_view_column_pack_start(column, renderer, TRUE);
    gtk_tree_view_column_set_cell_data_func(column, renderer, render_name, tool, NULL);

    column = gtk_tree_view_column_new();
    gtk_tree_view_column_set_title(column, "Type");
    gtk_tree_view_append_column(GTK_TREE_VIEW(tool->treeview), column);
    renderer = gtk_cell_renderer_text_new();
    gtk_tree_view_column_pack_start(column, renderer, TRUE);
    gtk_tree_view_column_set_cell_data_func(column, renderer, render_type, tool, NULL);

    column = gtk_tree_view_column_new();
    gtk_tree_view_column_set_title(column, _("Objects"));
    gtk_tree_view_append_column(GTK_TREE_VIEW(tool->treeview), column);
    renderer = gtk_cell_renderer_text_new();
    gtk_tree_view_column_pack_start(column, renderer, TRUE);
    gtk_tree_view_column_set_cell_data_func(column, renderer, render_objects, tool, NULL);

    label = gtk_label_new(_("Manage chosen selection"));
    gtk_misc_set_alignment(GTK_MISC(label), 0.0, 0.5);
    gtk_misc_set_padding(GTK_MISC(label), 0, 2);
    gtk_box_pack_start(GTK_BOX(gtk_dialog_get_content_area(dialog)), label, FALSE, FALSE, 0);

    hbox = gwy_hbox_new(6);
    gtk_box_pack_start(GTK_BOX(gtk_dialog_get_content_area(dialog)), hbox, FALSE, FALSE, 2);

    tool->distribute = gtk_button_new_with_mnemonic(_("_Distribute"));
    gtk_box_pack_start(GTK_BOX(hbox), tool->distribute, FALSE, FALSE, 0);

    tool->allfiles = gtk_check_button_new_with_mnemonic(_("to _all files"));
    gtk_box_pack_start(GTK_BOX(hbox), tool->allfiles, FALSE, FALSE, 0);
    gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(tool->allfiles),
                                 gwy_params_get_boolean(tool->params, PARAM_ALL_FILES));

    hbox = gwy_hbox_new(6);
    gtk_box_pack_start(GTK_BOX(gtk_dialog_get_content_area(dialog)), hbox, FALSE, FALSE, 2);

    tool->copy = gwy_stock_like_button_new(_("_Copy"), GTK_STOCK_COPY);
    gtk_box_pack_start(GTK_BOX(hbox), tool->copy, FALSE, FALSE, 0);

    tool->export = gwy_stock_like_button_new(_("_Export"), GTK_STOCK_SAVE);
    gtk_box_pack_start(GTK_BOX(hbox), tool->export, FALSE, FALSE, 0);

    tool->delete = gwy_stock_like_button_new(_("_Delete"), GTK_STOCK_DELETE);
    gtk_box_pack_start(GTK_BOX(hbox), tool->delete, FALSE, FALSE, 0);

    gwy_tool_add_hide_button(GWY_TOOL(tool), TRUE);
    gtk_dialog_add_button(GTK_DIALOG(GWY_TOOL(tool)->dialog), GTK_STOCK_CLEAR, GWY_TOOL_RESPONSE_CLEAR);
    gwy_help_add_to_tool_dialog(dialog, GWY_TOOL(tool), GWY_HELP_DEFAULT);

    g_signal_connect_swapped(tool->distribute, "clicked", G_CALLBACK(distribute), tool);
    g_signal_connect_swapped(tool->delete, "clicked", G_CALLBACK(delete_selection), tool);
    g_signal_connect_swapped(tool->copy, "clicked", G_CALLBACK(copy_selection_to_clipboard), tool);
    g_signal_connect_swapped(tool->allfiles, "toggled", G_CALLBACK(gwy_tool_selection_manager_all_files_changed), tool);
    g_signal_connect_swapped(tool->export, "clicked", G_CALLBACK(export_selection), tool);
    g_signal_connect_swapped(tool->treeview, "key-press-event", G_CALLBACK(key_pressed), tool);
    g_signal_connect(tool->treeview, "drag-begin", G_CALLBACK(gwy_app_data_browser_block_switching), NULL);
    g_signal_connect(tool->treeview, "drag-end", G_CALLBACK(gwy_app_data_browser_unblock_switching), NULL);
    g_signal_connect_swapped(selection, "changed", G_CALLBACK(gwy_tool_selection_manager_selection_changed), tool);

    gtk_widget_show_all(gtk_dialog_get_content_area(dialog));
}

static void
add_selection(gpointer hkey, gpointer hvalue, gpointer data)
{
    GwyToolSelectionManager *tool = (GwyToolSelectionManager*)data;
    GwyPlainTool *plain_tool = GWY_PLAIN_TOOL(tool);
    GQuark quark = GPOINTER_TO_UINT(hkey);
    GValue *value = (GValue*)hvalue;
    GwySelection *sel = g_value_get_object(value);
    GtkTreeIter iter;
    const gchar *name;

    name = g_quark_to_string(quark);
    g_return_if_fail(*name == '/');
    name++;
    while (g_ascii_isdigit(*name))
        name++;
    g_return_if_fail(strncmp(name, "/select/", sizeof("/select/")-1) == 0);
    name += sizeof("/select/")-1;
    /* Ignore selections with names starting with an underscore. */
    if (*name == '_')
        return;

    g_object_set_data(G_OBJECT(sel), container_key, plain_tool->container);
    gtk_list_store_insert_with_values(tool->model, &iter, G_MAXINT,
                                      COLUMN_ID, quark,
                                      COLUMN_OBJECT, sel,
                                      -1);
}

static void
gwy_tool_selection_manager_data_switched(GwyTool *gwytool,
                                         GwyDataView *data_view)
{
    GwyPlainTool *plain_tool = GWY_PLAIN_TOOL(gwytool);
    GwyToolSelectionManager *tool = GWY_TOOL_SELECTION_MANAGER(gwytool);
    gboolean ignore = (data_view == plain_tool->data_view);
    GtkTreeSelection *selection;

    GWY_TOOL_CLASS(gwy_tool_selection_manager_parent_class)->data_switched(gwytool, data_view);

    if (ignore || plain_tool->init_failed)
        return;

    /* FIXME: This is very naive because the tool cannot react to selections changed by something else.  Hopefully
     * only other tools do such things -- and then we get a chance to re-read the selection list.  */
    gtk_list_store_clear(tool->model);
    if (data_view) {
        gchar *basekey = g_strdup_printf("/%d/select", plain_tool->id);
        gwy_container_foreach(plain_tool->container, basekey, (GHFunc)&add_selection, tool);
        g_free(basekey);
    }

    selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(tool->treeview));
    gwy_tool_selection_manager_selection_changed(tool, selection);
}

static void
gwy_tool_selection_manager_response(GwyTool *gwytool,
                                    gint response_id)
{
    GwyToolSelectionManager *tool = GWY_TOOL_SELECTION_MANAGER(gwytool);

    GWY_TOOL_CLASS(gwy_tool_selection_manager_parent_class)->response(gwytool, response_id);

    if (response_id == GWY_TOOL_RESPONSE_CLEAR)
        clear_selection(tool);
}

static void
clear_selection(GwyToolSelectionManager *tool)
{
    GtkTreeModel *model = GTK_TREE_MODEL(tool->model);
    GwyPlainTool *plain_tool;
    GtkTreeIter iter;
    GQuark quark;

    if (!gtk_tree_model_get_iter_first(model, &iter))
        return;

    plain_tool = GWY_PLAIN_TOOL(tool);
    do {
        gtk_tree_model_get(model, &iter, COLUMN_ID, &quark, -1);
        gwy_container_remove(plain_tool->container, quark);
    } while (gtk_tree_model_iter_next(model, &iter));

    /* XXX: Since the model is not auto-updated, clear it manually. */
    gtk_list_store_clear(tool->model);
}

static void
gwy_tool_selection_manager_selection_changed(GwyToolSelectionManager *tool,
                                             GtkTreeSelection *selection)
{
    GtkTreeIter iter;
    gboolean is_selected = gtk_tree_selection_get_selected(selection, NULL, &iter);
    guint current = G_MAXUINT;
    GQuark quark = 0;

    gtk_widget_set_sensitive(tool->distribute, is_selected);
    gtk_widget_set_sensitive(tool->copy, is_selected);
    gtk_widget_set_sensitive(tool->export, is_selected);
    gtk_widget_set_sensitive(tool->delete, is_selected);

    if (tool->in_setup)
        return;

    if (is_selected) {
        GwySelection *sel;
        GType type;
        guint i, n;

        gtk_tree_model_get(GTK_TREE_MODEL(tool->model), &iter,
                           COLUMN_OBJECT, &sel,
                           COLUMN_ID, &quark,
                           -1);
        n = gwy_selection_get_data(sel, NULL);
        if (!n) {
            gtk_widget_set_sensitive(tool->distribute, FALSE);
            gtk_widget_set_sensitive(tool->copy, FALSE);
            gtk_widget_set_sensitive(tool->export, FALSE);
        }

        type = G_OBJECT_TYPE(sel);
        for (i = 0; i < NLAYERTYPES; i++) {
            if (type == tool->selection_types[i]) {
                current = i;
                break;
            }
        }
        g_object_unref(sel);
    }

    setup_layer(tool, current, quark);
}

static void
gwy_tool_selection_manager_all_files_changed(GwyToolSelectionManager *tool,
                                             GtkToggleButton *button)
{
    gwy_params_set_boolean(tool->params, PARAM_ALL_FILES, gtk_toggle_button_get_active(button));
}

static gboolean
key_pressed(GwyToolSelectionManager *tool,
            GdkEventKey *event,
            G_GNUC_UNUSED GtkTreeView *treeview)
{
    if (event->keyval != GDK_Delete)
        return FALSE;

    delete_selection(tool);
    return TRUE;
}

static void
distribute(GwyToolSelectionManager *tool)
{
    GwyPlainTool *plain_tool;
    GtkTreeSelection *treesel;
    GwyDataField *field;
    DistributeData distdata;
    GtkTreeIter iter;
    GQuark quark;
    const gchar *s;

    treesel = gtk_tree_view_get_selection(GTK_TREE_VIEW(tool->treeview));
    if (!gtk_tree_selection_get_selected(treesel, NULL, &iter))
        return;

    gtk_tree_model_get(GTK_TREE_MODEL(tool->model), &iter,
                       COLUMN_ID, &quark,
                       COLUMN_OBJECT, &distdata.selection,
                       -1);
    s = g_quark_to_string(quark);
    g_return_if_fail(s);
    distdata.name = strrchr(s, GWY_CONTAINER_PATHSEP);
    g_return_if_fail(distdata.name);

    plain_tool = GWY_PLAIN_TOOL(tool);
    field = plain_tool->data_field;
    distdata.xyunit = gwy_data_field_get_si_unit_xy(field);
    distdata.origin[0] = gwy_data_field_get_xoffset(field);
    distdata.origin[1] = gwy_data_field_get_yoffset(field);
    gwy_debug("source: %p %s", field, s);

    if (gwy_params_get_boolean(tool->params, PARAM_ALL_FILES))
        gwy_app_data_browser_foreach((GwyAppDataForeachFunc)distribute_one, &distdata);
    else
        distribute_one(plain_tool->container, &distdata);
}

static void
distribute_one(GwyContainer *container, DistributeData *distdata)
{
    GObject *object, *selobject;
    GwySelection *selection;
    GwyDataField *field;
    GString *str;
    GQuark quark;
    gint *ids;
    gint i;

    gwy_debug("dest: %p", container);
    ids = gwy_app_data_browser_get_data_ids(container);
    str = g_string_new(NULL);
    selobject = G_OBJECT(distdata->selection);
    for (i = 0; ids[i] >= 0; i++) {
        gdouble xoff, yoff, xreal, yreal;

        g_string_printf(str, "/%d/select%s", ids[i], distdata->name);
        gwy_debug("%p %s", container, str->str);
        quark = g_quark_from_string(str->str);

        /* Avoid copying to self */
        if (gwy_container_gis_object(container, quark, &object) && object == selobject) {
            gwy_debug("avoiding copy-to-self");
            continue;
        }

        /* Check units */
        g_string_printf(str, "/%d/data", ids[i]);
        if (!gwy_container_gis_object_by_name(container, str->str, &object) || !GWY_IS_DATA_FIELD(object)) {
            gwy_debug("data field not found?!");
            continue;
        }
        field = GWY_DATA_FIELD(object);
        if (!gwy_si_unit_equal(gwy_data_field_get_si_unit_xy(field), distdata->xyunit)) {
            gwy_debug("units differ");
            continue;
        }

        xoff = gwy_data_field_get_xoffset(field);
        yoff = gwy_data_field_get_yoffset(field);
        xreal = gwy_data_field_get_xreal(field);
        yreal = gwy_data_field_get_yreal(field);
        object = gwy_serializable_duplicate(selobject);
        selection = GWY_SELECTION(object);

        /* Crop the selection, taking into account that the coordinates do not include field offset, and move it
         * relative to the new origin. But for Lattice, which is origin-free, just limit it so that it fits inside. */
        if (gwy_strequal(G_OBJECT_TYPE_NAME(object), "GwySelectionLattice"))
            gwy_selection_crop(selection, -0.5*xreal, -0.5*yreal, 0.5*xreal, 0.5*yreal);
        else {
            gwy_selection_move(selection, distdata->origin[0], distdata->origin[1]);
            gwy_selection_crop(selection, xoff, yoff, xoff + xreal, yoff + yreal);
            gwy_selection_move(selection, -xoff, -yoff);
        }

        if (gwy_selection_get_data(selection, NULL))
            gwy_container_set_object(container, quark, object);
        else {
            gwy_debug("selection empty after cropping");
        }
        g_object_unref(object);
    }
    g_string_free(str, TRUE);
    g_free(ids);
}

static void
copy_selection_to_clipboard(GwyToolSelectionManager *tool)
{
    GtkClipboard *clipboard;
    GdkDisplay *display;
    gchar *text;

    text = create_report(tool);
    if (!text)
        return;

    display = gtk_widget_get_display(GTK_WIDGET(GWY_TOOL(tool)->dialog));
    clipboard = gtk_clipboard_get_for_display(display, GDK_SELECTION_CLIPBOARD);
    gtk_clipboard_set_text(clipboard, text, -1);
    g_free(text);
}

static void
export_selection(GwyToolSelectionManager *tool)
{
    gchar *text;

    text = create_report(tool);
    if (!text)
        return;

    gwy_save_auxiliary_data(_("Save Table"), GTK_WINDOW(GWY_TOOL(tool)->dialog), -1, text);
    g_free(text);
}

static void
add_coordinate_header(GString *text, GwySelection *selection, GwySIUnit *unit)
{
    const gchar *typename = G_OBJECT_TYPE_NAME(selection);
    gchar *unitstr = gwy_si_unit_get_string(unit, GWY_SI_UNIT_FORMAT_PLAIN);
    gchar *s = (strlen(unitstr) ? g_strconcat(" [", unitstr, "]", NULL) : g_strdup(""));

    if (gwy_stramong(typename, "GwySelectionProjective", NULL))
        g_string_append_printf(text, "x0%s\ty0%s\tx1%s\ty1%s\tx2%s\ty2%s\tx3%s\ty3%s\n", s, s, s, s, s, s, s, s);
    else if (gwy_stramong(typename,
                          "GwySelectionRectangle", "GwySelectionEllipse", "GwySelectionLine", "GwySelectionLattice",
                          NULL))
        g_string_append_printf(text, "x0%s\ty0%s\tx1%s\ty1%s\n", s, s, s, s);
    else if (gwy_stramong(typename, "GwySelectionCross", "GwySelectionPoint", "GwySelectionPath", NULL))
        g_string_append_printf(text, "x%s\ty%s\n", s, s);
    else if (gwy_strequal(typename, "GwySelectionAxis")) {
        GwyOrientation orientation;

        g_object_get(selection, "orientation", &orientation, NULL);
        g_string_append_printf(text, "%c%s\n", orientation == GWY_ORIENTATION_VERTICAL ? 'y' : 'x', s);
    }
    else {
        guint j, objsize = gwy_selection_get_object_size(selection);

        for (j = 0; j < objsize; j++) {
            g_string_append_printf(text, "c%u%s", j, s);
            g_string_append_c(text, (j == objsize-1) ? '\n' : '\t');
        }
    }

    g_free(s);
    g_free(unitstr);
}

static gchar*
create_report(GwyToolSelectionManager *tool)
{
    GwyPlainTool *plain_tool = GWY_PLAIN_TOOL(tool);
    GwyDataField *field = plain_tool->data_field;
    GtkTreeSelection *treesel;
    GwySelection *selection, *movedselection = NULL;
    GwySIUnit *xyunit;
    gdouble xoff, yoff;
    GtkTreeIter iter;
    GString *text;
    guint i, j, n, objsize;
    gdouble *coords;
    const gchar *typename;
    gchar buf[64];

    treesel = gtk_tree_view_get_selection(GTK_TREE_VIEW(tool->treeview));
    if (!gtk_tree_selection_get_selected(treesel, NULL, &iter))
        return NULL;

    gtk_tree_model_get(GTK_TREE_MODEL(tool->model), &iter, COLUMN_OBJECT, &selection, -1);
    typename = G_OBJECT_TYPE_NAME(selection);
    n = gwy_selection_get_data(selection, NULL);
    if (!n)
        return NULL;

    xyunit = gwy_data_field_get_si_unit_xy(field);
    xoff = gwy_data_field_get_xoffset(field);
    yoff = gwy_data_field_get_yoffset(field);
    /* Apply the data field offset in a generic manner. */
    if ((xoff != 0.0 || yoff != 0.0) && !gwy_strequal(typename, "GwySelectionLattice")) {
        movedselection = gwy_selection_duplicate(selection);
        gwy_selection_move(movedselection, xoff, yoff);
        selection = movedselection;
    }

    text = g_string_new(NULL);
    add_coordinate_header(text, selection, xyunit);

    objsize = gwy_selection_get_object_size(selection);
    coords = g_new(gdouble, objsize);
    for (i = 0; i < n; i++) {
        gwy_selection_get_object(selection, i, coords);
        for (j = 0; j < objsize; j++) {
            g_ascii_formatd(buf, sizeof(buf), "%g", coords[j]);
            g_string_append(text, buf);
            g_string_append_c(text, (j == objsize-1) ? '\n' : '\t');
        }
    }

    g_free(coords);
    GWY_OBJECT_UNREF(movedselection);

    return g_string_free(text, FALSE);
}

static void
delete_selection(GwyToolSelectionManager *tool)
{
    GtkTreeSelection *treesel;
    GtkTreeModel *model;
    GtkTreeIter iter;
    GQuark quark;

    treesel = gtk_tree_view_get_selection(GTK_TREE_VIEW(tool->treeview));
    if (gtk_tree_selection_get_selected(treesel, &model, &iter)) {
        gtk_tree_model_get(model, &iter, COLUMN_ID, &quark, -1);
        gwy_container_remove(GWY_PLAIN_TOOL(tool)->container, quark);
        /* XXX: Since the model is not auto-updated, clear it manually. */
        gtk_list_store_remove(tool->model, &iter);
    }
}

static void
setup_layer(GwyToolSelectionManager *tool,
            guint current,
            GQuark quark)
{
    GwyPlainTool *plain_tool = GWY_PLAIN_TOOL(tool);
    const gchar *s;

    if (!plain_tool->data_view || current >= NLAYERTYPES || !quark)
        return;

    s = g_quark_to_string(quark);
    g_return_if_fail(s);
    s = strrchr(s, GWY_CONTAINER_PATHSEP);
    g_return_if_fail(s);

    gwy_plain_tool_connect_selection(plain_tool, tool->layer_types[current], s+1);
    gwy_object_set_or_reset(plain_tool->layer, tool->layer_types[current],
                            "editable", TRUE,
                            "focus", -1,
                            NULL);
}

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