File: gwymoduleutils.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 (1360 lines) | stat: -rw-r--r-- 45,609 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
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
/*
 *  $Id: gwymoduleutils.c 25037 2022-09-22 12:25:33Z yeti-dn $
 *  Copyright (C) 2007-2022 David Necas (Yeti), Petr Klapetek.
 *  E-mail: yeti@gwyddion.net, klapetek@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 <errno.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#include <glib/gstdio.h>
#include <gtk/gtk.h>
#include <libgwyddion/gwymacros.h>
#include <libgwydgets/gwylayer-basic.h>
#include <libgwydgets/gwylayer-mask.h>
#include <libgwydgets/gwydataview.h>
#include <libgwydgets/gwydgetutils.h>
#include "file.h"
#include "data-browser.h"
#include "settings.h"
#include "wait.h"
#include "dialog.h"
#include "param-internal.h"
#include "gwymoduleutils.h"

typedef struct {
    const gchar *data;
    gssize len;
} GwySaveAuxiliaryData;

static gchar*
gwy_save_auxiliary_data_create(gpointer user_data,
                               gssize *data_len)
{
    GwySaveAuxiliaryData *savedata = (GwySaveAuxiliaryData*)user_data;

    *data_len = savedata->len;

    return (gchar*)savedata->data;
}

/**
 * gwy_save_auxiliary_data:
 * @title: File chooser dialog title.
 * @parent: Parent window for the file chooser dialog (may be %NULL).
 * @data_len: The length of @data in bytes.  Pass -1 if @data is text, it must be nul-terminated then and it will be
 *            saved in text mode (this matters if the operating system distinguishes between text and binary).
 *            A non-negative value causes the data to be saved as binary.
 * @data: The data to save.
 *
 * Saves a report or other auxiliary data to a user specified file.
 *
 * This is actually a simple gwy_save_auxiliary_with_callback() wrapper, see its description for details.
 *
 * Returns: %TRUE if the data was saved, %FALSE if it was not saved for any reason.
 *
 * Since: 2.3
 **/
gboolean
gwy_save_auxiliary_data(const gchar *title,
                        GtkWindow *parent,
                        gssize data_len,
                        const gchar *data)
{
    GwySaveAuxiliaryData savedata;

    g_return_val_if_fail(data, FALSE);
    savedata.data = data;
    savedata.len = data_len;

    return gwy_save_auxiliary_with_callback(title, parent, &gwy_save_auxiliary_data_create, NULL, &savedata);
}

/**
 * gwy_save_auxiliary_with_callback:
 * @title: File chooser dialog title.
 * @parent: Parent window for the file chooser dialog (may be %NULL).
 * @create: Function to create the data (it will not be called if the user cancels the saving).
 * @destroy: Function to destroy the data (if will be called iff @create will be called), it may be %NULL.
 * @user_data: User data passed to @create and @destroy.
 *
 * Saves a report or other auxiliary data to a user specified file.
 *
 * Returns: %TRUE if the data was saved, %FALSE if it was not saved for any reason (I/O error, cancellation, overwrite
 *          cancellation, etc.).
 *
 * Since: 2.3
 **/
gboolean
gwy_save_auxiliary_with_callback(const gchar *title,
                                 GtkWindow *parent,
                                 GwySaveAuxiliaryCreate create,
                                 GwySaveAuxiliaryDestroy destroy,
                                 gpointer user_data)
{
    gchar *data;
    gchar *filename_sys, *filename_utf8;
    gssize data_len;
    gint myerrno;
    GtkWidget *dialog, *chooser;
    gint response;
    FILE *fh;

    g_return_val_if_fail(!parent || GTK_IS_WINDOW(parent), FALSE);
    g_return_val_if_fail(create, FALSE);

    chooser = gtk_file_chooser_dialog_new(title, parent,
                                          GTK_FILE_CHOOSER_ACTION_SAVE,
                                          GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
                                          GTK_STOCK_SAVE, GTK_RESPONSE_OK,
                                          NULL);
    gtk_dialog_set_default_response(GTK_DIALOG(chooser), GTK_RESPONSE_OK);
    gtk_file_chooser_set_current_folder(GTK_FILE_CHOOSER(chooser), gwy_app_get_current_directory());
    response = gtk_dialog_run(GTK_DIALOG(chooser));
    filename_sys = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(chooser));

    if (!gwy_app_file_confirm_overwrite(chooser))
        response = GTK_RESPONSE_CANCEL;

    gtk_widget_destroy(chooser);

    if (!filename_sys || response != GTK_RESPONSE_OK) {
        g_free(filename_sys);
        return FALSE;
    }

    data_len = -1;
    data = create(user_data, &data_len);
    g_return_val_if_fail(data, FALSE);

    if ((fh = gwy_fopen(filename_sys, "wb"))) {
        gchar *mydata = NULL;

        /* Write everything in binary and just convert the EOLs by manually.
         * This seems to actually work as we want. */
        if (data_len <= 0) {
#ifdef G_OS_WIN32
            mydata = gwy_strreplace(data, "\n", "\r\n", (gsize)-1);
            data_len = strlen(mydata);
#else
            data_len = strlen(data);
#endif
        }
        if (fwrite(mydata ? mydata : data, data_len, 1, fh) != 1) {
            myerrno = errno;
            /* This is just best-effort clean-up */
            fclose(fh);
            g_unlink(filename_sys);
            fh = NULL;
        }
        else
            myerrno = 0;  /* GCC */

        g_free(mydata);
    }
    else
        myerrno = errno;

    if (destroy)
        destroy(data, user_data);

    if (fh) {
        /* Everything went all right. */
        fclose(fh);
        gwy_app_set_current_directory(filename_sys);
        g_free(filename_sys);
        return TRUE;
    }

    filename_utf8 = g_filename_to_utf8(filename_sys, -1, NULL, NULL, NULL);
    dialog = gtk_message_dialog_new(parent, 0, GTK_MESSAGE_ERROR, GTK_BUTTONS_OK,
                                    _("Saving of `%s' failed"), filename_utf8);
    g_free(filename_sys);
    g_free(filename_utf8);
    gtk_message_dialog_format_secondary_text(GTK_MESSAGE_DIALOG(dialog),
                                             _("Cannot write to file: %s."), g_strerror(myerrno));
    gtk_widget_show_all(dialog);
    gtk_dialog_run(GTK_DIALOG(dialog));
    gtk_widget_destroy(dialog);

    return FALSE;
}

/**
 * gwy_module_data_load:
 * @modname: Module name (determines the subdirectory).
 * @filename: Name of the file to load.  In GLib encoding, but it really should be just ASCII.
 * @contents: Location to store the allocated file contents.  Use g_free() to free it.  It is set to %NULL when the
 *            file cannot be loaded.
 * @length: Location to the length of the contents in bytes, or %NULL.
 * @error: Location for error, or %NULL.
 *
 * Load module data file from the user directory.
 *
 * The function wraps g_file_get_contents(), forming the full file name automatically.
 *
 * The error can be from %G_FILE_ERROR domain.  Usually, however, you only need the return value and consider the file
 * simply not existing yet when the function fails.
 *
 * Returns: %TRUE if the file was loaded.
 *
 * Since: 2.51
 **/
gboolean
gwy_module_data_load(const gchar *modname,
                     const gchar *filename,
                     gchar **contents,
                     gsize *length,
                     GError **error)
{
    gchar *path;
    gboolean ok;

    path = g_build_filename(gwy_get_user_dir(), modname, filename, NULL);
    /* Do not bother creating the directory in the load function.  We only
     * need it in the save function. */
    ok = g_file_get_contents(path, contents, length, error);
    g_free(path);

    return ok;
}

static gboolean
ensure_module_directory(const gchar *userdir,
                        const gchar *modname,
                        GError **error)
{
    gchar *path;

    path = g_build_filename(userdir, modname, NULL);
    if (g_file_test(path, G_FILE_TEST_IS_DIR)) {
        g_free(path);
        return TRUE;
    }

    if (g_mkdir(path, 0700) == 0) {
        g_free(path);
        return TRUE;
    }

    g_set_error_literal(error, G_FILE_ERROR, g_file_error_from_errno(errno), g_strerror(errno));
    g_free(path);
    return FALSE;
}

/**
 * gwy_module_data_save:
 * @modname: Module name (determines the subdirectory).
 * @filename: Name of the file to save.  In GLib encoding, but it really should be just ASCII.
 * @contents: File contents to write.
 * @length: Length of @contents, or -1 if it is a NUL-terminated string.
 * @error: Location for error, or %NULL.
 *
 * Saves module data file to the user directory.
 *
 * The function wraps g_file_set_contents(), forming the full file name automatically and handling subdirectory
 * creation.
 *
 * The error can be from %G_FILE_ERROR domain.
 *
 * Returns: %TRUE if the file was saved.
 *
 * Since: 2.51
 **/
gboolean
gwy_module_data_save(const gchar *modname,
                     const gchar *filename,
                     gchar *contents,
                     gssize length,
                     GError **error)
{
    const gchar *userdir;
    gchar *path;
    gboolean ok;

    userdir = gwy_get_user_dir();
    if (!ensure_module_directory(userdir, modname, error))
        return FALSE;

    path = g_build_filename(userdir, modname, filename, NULL);
    ok = g_file_set_contents(path, contents, length, error);
    g_free(path);

    return ok;
}

/**
 * gwy_module_data_fopen:
 * @modname: Module name (determines the subdirectory).
 * @filename: Name of the file to save.  In GLib encoding, but it really should be just ASCII.
 * @mode: File open mode, as in fopen().
 * @error: Location for error, or %NULL.
 *
 * Opens a module data file in the user directory.
 *
 * The function wraps gwy_fopen(), forming the full file name automatically and handling subdirectory creation.
 *
 * The error can be from %G_FILE_ERROR domain.
 *
 * Returns: A file handle if the file was opened as requested, %NULL on failure.
 *
 * Since: 2.51
 **/
FILE*
gwy_module_data_fopen(const gchar *modname,
                      const gchar *filename,
                      const gchar *mode,
                      GError **error)
{
    const gchar *userdir;
    gchar *path;
    FILE *fh;

    userdir = gwy_get_user_dir();
    if (!ensure_module_directory(userdir, modname, error))
        return FALSE;

    path = g_build_filename(userdir, modname, filename, NULL);
    if (!(fh = gwy_fopen(path, mode)))
        g_set_error_literal(error, G_FILE_ERROR, g_file_error_from_errno(errno), g_strerror(errno));
    g_free(path);

    return fh;
}

/**
 * gwy_set_data_preview_size:
 * @data_view: A data view used for module preview.
 * @max_size: Maximum allowed @data_view size (width and height).
 *
 * Sets up data view zoom to not exceed specified size.
 *
 * Before calling this function, data keys have be set, data fields and layers have to be present and physically
 * square mode set in the container. Sizing of both pixel-wise square and physically square displays is performed
 * correctly.
 *
 * Since: 2.7
 **/
void
gwy_set_data_preview_size(GwyDataView *data_view,
                          gint max_size)
{
    GwyContainer *container;
    GwyDataField *data_field;
    GwyPixmapLayer *layer;
    gdouble zoomval, scale, xreal, yreal;
    gboolean realsquare;
    gint xres, yres;
    const gchar *prefix;
    gchar *key;

    g_return_if_fail(GWY_IS_DATA_VIEW(data_view));
    g_return_if_fail(max_size >= 2);

    container = gwy_data_view_get_data(data_view);
    g_return_if_fail(GWY_IS_CONTAINER(container));

    layer = gwy_data_view_get_base_layer(data_view);
    g_return_if_fail(GWY_IS_PIXMAP_LAYER(layer));
    prefix = gwy_pixmap_layer_get_data_key(layer);
    g_return_if_fail(prefix);

    data_field = gwy_container_get_object_by_name(container, prefix);
    g_return_if_fail(GWY_IS_DATA_FIELD(data_field));

    prefix = gwy_data_view_get_data_prefix(data_view);
    g_return_if_fail(prefix);
    key = g_strconcat(prefix, "/realsquare", NULL);
    realsquare = FALSE;
    gwy_container_gis_boolean_by_name(container, key, &realsquare);
    g_free(key);

    xres = gwy_data_field_get_xres(data_field);
    yres = gwy_data_field_get_yres(data_field);
    if (!realsquare)
        zoomval = max_size/(gdouble)MAX(xres, yres);
    else {
        xreal = gwy_data_field_get_xreal(data_field);
        yreal = gwy_data_field_get_yreal(data_field);
        scale = MAX(xres/xreal, yres/yreal);
        zoomval = max_size/(scale*MAX(xreal, yreal));
    }
    gwy_data_view_set_zoom(data_view, zoomval);
}

static gboolean
clear_data_id(GwyAppDataId *id)
{
    id->datano = 0;
    id->id = -1;
    return FALSE;
}

/**
 * gwy_app_data_id_verify_channel:
 * @id: Numerical identifiers of a channel in data managed by the data browser.
 *
 * Checks if numerical channel identifiers correspond to an existing channel.
 *
 * If either the data contained referenced in @id or the channel does not exist the structure is cleared to
 * %GWY_APP_DATA_ID_NONE and the function returns %FALSE.  If it represents an existing channel it is kept intact and
 * the function returns %TRUE.
 *
 * Returns: Whether @id refers to an existing channel now.
 *
 * Since: 2.41
 **/
gboolean
gwy_app_data_id_verify_channel(GwyAppDataId *id)
{
    GwyContainer *container;
    GObject *object;
    GQuark quark;

    g_return_val_if_fail(id, FALSE);

    container = gwy_app_data_browser_get(id->datano);
    if (!container)
        return clear_data_id(id);

    quark = gwy_app_get_data_key_for_id(id->id);
    if (!gwy_container_gis_object(container, quark, &object))
        return clear_data_id(id);
    if (!GWY_IS_DATA_FIELD(object))
        return clear_data_id(id);

    return TRUE;
}

/**
 * gwy_app_data_id_verify_graph:
 * @id: Numerical identifiers of a graph in data managed by the data browser.
 *
 * Checks if numerical graph identifiers correspond to an existing graph.
 *
 * If either the data contained referenced in @id or the graph model does not exist the structure is cleared to
 * %GWY_APP_DATA_ID_NONE and the function returns %FALSE.  If it represents an existing graph it is kept intact and
 * the function returns %TRUE.
 *
 * Returns: Whether @id refers to an existing graph now.
 *
 * Since: 2.41
 **/
gboolean
gwy_app_data_id_verify_graph(GwyAppDataId *id)
{
    GwyContainer *container;
    GObject *object;
    GQuark quark;

    g_return_val_if_fail(id, FALSE);

    container = gwy_app_data_browser_get(id->datano);
    if (!container)
        return clear_data_id(id);

    quark = gwy_app_get_graph_key_for_id(id->id);
    if (!gwy_container_gis_object(container, quark, &object))
        return clear_data_id(id);
    if (!GWY_IS_GRAPH_MODEL(object))
        return clear_data_id(id);

    return TRUE;
}

/**
 * gwy_app_data_id_verify_volume:
 * @id: Numerical identifiers of volume data in data managed by the data browser.
 *
 * Checks if numerical volume data identifiers correspond to existing volume data.
 *
 * If either the data contained referenced in @id or the volume data does not exist the structure is cleared to
 * %GWY_APP_DATA_ID_NONE and the function returns %FALSE.  If it represents existing volume data it is kept intact and
 * the function returns %TRUE.
 *
 * Returns: Whether @id refers to existing volume data now.
 *
 * Since: 2.41
 **/
gboolean
gwy_app_data_id_verify_volume(GwyAppDataId *id)
{
    GwyContainer *container;
    GObject *object;
    GQuark quark;

    g_return_val_if_fail(id, FALSE);

    container = gwy_app_data_browser_get(id->datano);
    if (!container)
        return clear_data_id(id);

    quark = gwy_app_get_brick_key_for_id(id->id);
    if (!gwy_container_gis_object(container, quark, &object))
        return clear_data_id(id);
    if (!GWY_IS_BRICK(object))
        return clear_data_id(id);

    return TRUE;
}

/**
 * gwy_app_data_id_verify_xyz:
 * @id: Numerical identifiers of XYZ data in data managed by the data browser.
 *
 * Checks if numerical XYZ data identifiers correspond to existing XYZ data.
 *
 * If either the data contained referenced in @id or the XYZ data does not exist the structure is cleared to
 * %GWY_APP_DATA_ID_NONE and the function returns %FALSE.  If it represents existing XYZ data it is kept intact and
 * the function returns %TRUE.
 *
 * Returns: Whether @id refers to existing XYZ data now.
 *
 * Since: 2.46
 **/
gboolean
gwy_app_data_id_verify_xyz(GwyAppDataId *id)
{
    GwyContainer *container;
    GObject *object;
    GQuark quark;

    g_return_val_if_fail(id, FALSE);

    container = gwy_app_data_browser_get(id->datano);
    if (!container)
        return clear_data_id(id);

    quark = gwy_app_get_surface_key_for_id(id->id);
    if (!gwy_container_gis_object(container, quark, &object))
        return clear_data_id(id);
    if (!GWY_IS_SURFACE(object))
        return clear_data_id(id);

    return TRUE;
}

/**
 * gwy_app_data_id_verify_curve_map:
 * @id: Numerical identifiers of curve map data in data managed by the data browser.
 *
 * Checks if numerical curve map data identifiers correspond to existing curve map data.
 *
 * If either the data contained referenced in @id or the curve map data does not exist the structure is cleared to
 * %GWY_APP_DATA_ID_NONE and the function returns %FALSE.  If it represents existing curve map data it is kept intact
 * and the function returns %TRUE.
 *
 * Returns: Whether @id refers to existing curve map data now.
 *
 * Since: 2.46
 **/
gboolean
gwy_app_data_id_verify_curve_map(GwyAppDataId *id)
{
    GwyContainer *container;
    GObject *object;
    GQuark quark;

    g_return_val_if_fail(id, FALSE);

    container = gwy_app_data_browser_get(id->datano);
    if (!container)
        return clear_data_id(id);

    quark = gwy_app_get_lawn_key_for_id(id->id);
    if (!gwy_container_gis_object(container, quark, &object))
        return clear_data_id(id);
    if (!GWY_IS_LAWN(object))
        return clear_data_id(id);

    return TRUE;
}

/**
 * gwy_app_data_id_verify_spectra:
 * @id: Numerical identifiers of spectra in data managed by the data browser.
 *
 * Checks if numerical spectra identifiers correspond to existing spectra.
 *
 * If either the data contained referenced in @id or the spectra does not exist the structure is cleared to
 * %GWY_APP_DATA_ID_NONE and the function returns %FALSE.  If it represents existing spectra it is kept intact and the
 * function return %TRUE.
 *
 * Returns: Whether @id refers to existing spectra now.
 *
 * Since: 2.41
 **/
gboolean
gwy_app_data_id_verify_spectra(GwyAppDataId *id)
{
    GwyContainer *container;
    GObject *object;
    GQuark quark;

    g_return_val_if_fail(id, FALSE);

    container = gwy_app_data_browser_get(id->datano);
    if (!container)
        return clear_data_id(id);

    quark = gwy_app_get_spectra_key_for_id(id->id);
    if (!gwy_container_gis_object(container, quark, &object))
        return clear_data_id(id);
    if (!GWY_IS_SPECTRA(object))
        return clear_data_id(id);

    return TRUE;
}

/**
 * gwy_app_add_graph_or_curves:
 * @gmodel: A graph model with curves to add.
 * @data: Data container where the graph would be added.
 * @target_graph: Graph where curves would be added.
 * @colorstep: Curve block size as in gwy_graph_model_append_curves().
 *
 * Puts the curves of a graph to another graph if possible, or adds the graph as new.
 *
 * If the units of @gmodel are compatible with the units of the graph identified by @target_graph the curves are
 * copied to the target graph with gwy_graph_model_append_curves().
 *
 * In all other cases, including when @target_graph does not refer to any existing graph, the graph model is added to
 * @data as a new graph.
 *
 * Either way, the caller usually need to release its own reference afterwards.
 *
 * This function is useful particularly in modules that create graphs and can be run non-interactively.
 *
 * Returns: The numerical identifier of the newly-created graph of one was created.  Value -1 is returned if curves
 *          were added to @target_graph.
 *
 * Since: 2.41
 **/
gint
gwy_app_add_graph_or_curves(GwyGraphModel *gmodel,
                            GwyContainer *data,
                            const GwyAppDataId *target_graph,
                            gint colorstep)
{
    GwyAppDataId tgtgraph = *target_graph;

    if (gwy_app_data_id_verify_graph(&tgtgraph)) {
        GQuark quark = gwy_app_get_graph_key_for_id(tgtgraph.id);
        GwyContainer *data2 = gwy_app_data_browser_get(tgtgraph.datano);
        GwyGraphModel *target_gmodel = gwy_container_get_object(data2, quark);

        g_return_val_if_fail(GWY_IS_GRAPH_MODEL(target_gmodel), -1);
        if (gwy_graph_model_units_are_compatible(gmodel, target_gmodel)) {
            gwy_graph_model_append_curves(target_gmodel, gmodel, colorstep);
            return -1;
        }
    }
    g_return_val_if_fail(GWY_IS_CONTAINER(data), FALSE);
    return gwy_app_data_browser_add_graph_model(gmodel, data, TRUE);
}

/**
 * gwy_preview_surface_to_datafield:
 * @surface: A surface representing a XYZ data.
 * @dfield: A data field to fill with @surface preview.
 * @max_xres: Maximum width of the preview, it must be at least 2.
 * @max_yres: Maximum height of the preview, it must be at least 2.
 * @flags: Flags modifying the behaviour.
 *
 * Renders a preview of a XYZ data surface to a data field.
 *
 * Since: 2.46
 **/
void
gwy_preview_surface_to_datafield(GwySurface *surface,
                                 GwyDataField *dfield,
                                 gint max_xres, gint max_yres,
                                 GwyPreviewSurfaceFlags flags)
{
    gdouble q, h, xmin, xmax, ymin, ymax;
    guint n = gwy_surface_get_npoints(surface);
    gboolean do_fill = (flags & GWY_PREVIEW_SURFACE_FILL);
    gboolean want_densitymap = (flags & GWY_PREVIEW_SURFACE_DENSITY);
    gboolean xrange_normal, yrange_normal;
    GwyDataField *densitymap = NULL;
    guint xres, yres;

    gwy_surface_get_xrange(surface, &xmin, &xmax);
    xrange_normal = (xmin < xmax);

    gwy_surface_get_yrange(surface, &ymin, &ymax);
    yrange_normal = (ymin < ymax);

    if (!xrange_normal) {
        if (yrange_normal) {
            xmin = xmax - (ymax - ymin)/n;
            xmax = xmax + (ymax - ymin)/n;
        }
        else if (xmax) {
            xmin = 1.5*xmax;
            xmax = 0.5*xmax;
        }
        else {
            xmin = -1.0;
            xmax = 1.0;
        }
    }

    if (!yrange_normal) {
        if (xrange_normal) {
            ymin = ymax - (xmax - xmin)/n;
            ymax = ymax + (xmax - xmin)/n;
        }
        else if (ymax) {
            ymin = 0.5*ymax;
            ymax = 1.5*ymax;
        }
        else {
            ymin = -1.0;
            ymax = 1.0;
        }
    }

    if (do_fill) {
        h = fmax((xmax - xmin)/(max_xres - 1.0), (ymax - ymin)/(max_yres - 1.0));
        xmin -= 0.5*h;
        ymin -= 0.5*h;
        xmax += 0.5*h;
        ymax += 0.5*h;
        xres = GWY_ROUND((xmax - xmin)/h);
        xres = CLAMP(xres, 2, max_xres);
        yres = GWY_ROUND((ymax - ymin)/h);
        yres = CLAMP(yres, 2, max_yres);
    }
    else {
        q = (ymax - ymin)/(xmax - xmin);
        if (q <= 1.0) {
            yres = GWY_ROUND(sqrt(3.0*q*n));
            yres = MAX(yres, 2);
            h = (ymax - ymin)/yres;
            xres = GWY_ROUND((xmax - xmin)/h);
            if (CLAMP(xres, 2, max_xres) != xres) {
                xres = CLAMP(xres, 2, max_xres);
                h = (xmax - xmin)/xres;
                yres = (gint)ceil((ymax - ymin)/h);
            }
        }
        else {
            xres = GWY_ROUND(sqrt(3.0/q*n));
            xres = MAX(xres, 2);
            h = (xmax - xmin)/xres;
            yres = GWY_ROUND((ymax - ymin)/h);
            if (CLAMP(yres, 2, max_yres) != yres) {
                yres = CLAMP(yres, 2, max_yres);
                h = (ymax - ymin)/yres;
                xres = (gint)ceil((xmax - xmin)/h);
            }
        }

        xmin -= 0.5*h;
        ymin -= 0.5*h;
        xmax += 0.5*h;
        ymax += 0.5*h;
        if ((xmax - xmin)/xres < (ymax - ymin)/yres) {
            gdouble excess = (ymax - ymin)/yres*xres - (xmax - xmin);
            xmin -= 0.5*excess;
            xmax += 0.5*excess;
        }
        else {
            gdouble excess = (xmax - xmin)/xres*yres - (ymax - ymin);
            ymin -= 0.5*excess;
            ymax += 0.5*excess;
        }
    }

    gwy_data_field_resample(dfield, xres, yres, GWY_INTERPOLATION_NONE);
    gwy_data_field_set_xreal(dfield, xmax - xmin);
    gwy_data_field_set_yreal(dfield, ymax - ymin);
    gwy_data_field_set_xoffset(dfield, xmin);
    gwy_data_field_set_yoffset(dfield, ymin);
    if (want_densitymap)
        densitymap = gwy_data_field_new_alike(dfield, FALSE);

    gwy_data_field_average_xyz(dfield, densitymap, gwy_surface_get_data_const(surface), n);
    gwy_si_unit_assign(gwy_data_field_get_si_unit_xy(dfield), gwy_surface_get_si_unit_xy(surface));

    if (want_densitymap) {
        gwy_data_field_copy(densitymap, dfield, FALSE);
        GWY_OBJECT_UNREF(densitymap);
        gwy_si_unit_set_from_string(gwy_data_field_get_si_unit_z(dfield), NULL);
    }
    else
        gwy_si_unit_assign(gwy_data_field_get_si_unit_z(dfield), gwy_surface_get_si_unit_z(surface));
}

/**
 * gwy_app_wait_preview_data_field:
 * @dfield: A data field used for preview.
 * @data: Data container with source image (or %NULL).
 * @id: Source image id (or -1).
 *
 * Helper function for progressive animated preview.
 *
 * This is a wrapper for gwy_app_wait_set_preview_widget() which creates a simple image preview displaying @dfield.
 * Call gwy_data_field_data_changed() on it to redraw the preview.
 *
 * No preview is created if progress bars are disabled, see gwy_app_wait_set_enabled().
 *
 * Returns: The created #GwyDataView with the preview (possibly %NULL if not preview was actually created).  Usually
 *          you can ignore it.
 *
 * Since: 2.59
 **/
GtkWidget*
gwy_app_wait_preview_data_field(GwyDataField *dfield,
                                GwyContainer *data,
                                gint id)
{
    GwyContainer *mydata;
    GtkWidget *preview;

    if (!gwy_app_wait_get_enabled())
        return NULL;

    mydata = gwy_container_new();
    gwy_container_set_object(mydata, gwy_app_get_data_key_for_id(0), dfield);
    preview = gwy_create_preview(mydata, 0, 360, FALSE);
    if (data && id >= 0) {
        gwy_app_sync_data_items(data, mydata, id, 0, FALSE,
                                GWY_DATA_ITEM_GRADIENT,
                                0);
    }
    gwy_app_wait_set_preview_widget(preview);

    return preview;
}

/**
 * gwy_run_subdialog:
 * @dialog: A data dialog to be run as modal.
 *
 * Runs a modal dialog transient for another another dialog, trying to work around bugs.
 *
 * If both dialogs are modal, bad things can happen in some graphical environments, such as the second being hidden
 * under the first one and inaccessible. This function attempts to work around this by temporarily setting the parent
 * dialog (the one @dialog is transient for) non-modal.
 *
 * If the dialog is not transient for anything or its parent is not modal it is just run normally.
 *
 * When the function resturns only the dialog has been destroyed.
 *
 * Returns: The response of @dialog.
 *
 * Since: 2.62
 **/
gint
gwy_run_subdialog(GtkDialog *dialog)
{
    GtkWindow *parent;
    gint response;

    g_return_val_if_fail(GTK_IS_DIALOG(dialog), GTK_RESPONSE_NONE);
    parent = gtk_window_get_transient_for(GTK_WINDOW(dialog));
    if (parent && GTK_IS_WINDOW(parent) && gtk_window_get_modal(parent))
        gtk_window_set_modal(GTK_WINDOW(parent), FALSE);
    else
        parent = NULL;

    response = gtk_dialog_run(dialog);
    if (parent)
        gtk_window_set_modal(GTK_WINDOW(parent), TRUE);
    if (response != GTK_RESPONSE_NONE)
        gtk_widget_destroy(GTK_WIDGET(dialog));

    return response;
}

/**
 * gwy_require_image_same_units:
 * @field: The data field to check.
 * @data: Data container with the data field.
 * @id: The id of @field in @data.
 * @name: Error message prefix, usually module function name.
 *
 * Checks if data field has equal lateral and value units, possibly showing error message.
 *
 * If the data field does not have the same lateral and value units a simple error message dialog is shown for @data
 * and @id.  This is only done if other GUI functions (like progress bars for waiting) are enabled.
 *
 * Returns: %TRUE if the units are the same, %FALSE otherwise.
 *
 * Since: 2.59
 **/
gboolean
gwy_require_image_same_units(GwyDataField *field, GwyContainer *data, gint id,
                             const gchar *name)
{
    GtkWidget *dialog;

    if (gwy_si_unit_equal(gwy_data_field_get_si_unit_xy(field), gwy_data_field_get_si_unit_z(field)))
        return TRUE;

    if (!gwy_app_data_browser_get_gui_enabled() && !gwy_app_wait_get_enabled())
        return FALSE;

    dialog = gtk_message_dialog_new(gwy_app_find_window_for_channel(data, id),
                                    GTK_DIALOG_DESTROY_WITH_PARENT | GTK_DIALOG_MODAL,
                                    GTK_MESSAGE_ERROR,
                                    GTK_BUTTONS_OK,
                                    _("%s: Lateral dimensions and value must be the same physical quantity."), name);
    if (gtk_dialog_run(GTK_DIALOG(dialog)) != GTK_RESPONSE_NONE)
        gtk_widget_destroy(dialog);

    return FALSE;
}

/**
 * gwy_require_square_image:
 * @field: The data field to check.
 * @data: Data container with the data field.
 * @id: The id of @field in @data.
 * @name: Error message prefix, usually module function name.
 *
 * Checks if data field has the same horizontal and vertical pixel dimensions, possibly showing error message.
 *
 * If the data field is not square a simple error message dialog is shown for @data and @id.  This is only done if
 * other GUI functions (like progress bars for waiting) are enabled.
 *
 * Returns: %TRUE if the data field is square, %FALSE otherwise.
 *
 * Since: 2.59
 **/
gboolean
gwy_require_square_image(GwyDataField *field, GwyContainer *data, gint id,
                         const gchar *name)
{
    GtkWidget *dialog;

    if (gwy_data_field_get_xres(field) == gwy_data_field_get_yres(field))
        return TRUE;

    if (!gwy_app_data_browser_get_gui_enabled() && !gwy_app_wait_get_enabled())
        return FALSE;

    dialog = gtk_message_dialog_new(gwy_app_find_window_for_channel(data, id),
                                    GTK_DIALOG_DESTROY_WITH_PARENT | GTK_DIALOG_MODAL,
                                    GTK_MESSAGE_ERROR,
                                    GTK_BUTTONS_OK,
                                    _("%s: Data must be square."), name);
    if (gtk_dialog_run(GTK_DIALOG(dialog)) != GTK_RESPONSE_NONE)
        gtk_widget_destroy(dialog);

    return FALSE;
}

static GwyPixmapLayer*
create_basic_layer(GwyDataView *dataview, gint id)
{
    GwyPixmapLayer *layer = gwy_layer_basic_new();
    GQuark quark = gwy_app_get_data_key_for_id(id);
    const gchar *key = g_quark_to_string(quark);
    gchar buf[24];

    gwy_pixmap_layer_set_data_key(layer, key);
    key = g_quark_to_string(gwy_app_get_data_palette_key_for_id(id));
    gwy_layer_basic_set_gradient_key(GWY_LAYER_BASIC(layer), key);
    key = g_quark_to_string(gwy_app_get_data_range_type_key_for_id(id));
    gwy_layer_basic_set_range_type_key(GWY_LAYER_BASIC(layer), key);
    g_snprintf(buf, sizeof(buf), "/%d/base", id);
    gwy_layer_basic_set_min_max_key(GWY_LAYER_BASIC(layer), buf);
    gwy_data_view_set_base_layer(dataview, layer);

    return layer;
}

static GwyPixmapLayer*
create_mask_layer(GwyDataView *dataview, gint id)
{
    GwyPixmapLayer *layer = gwy_layer_mask_new();
    GQuark quark = gwy_app_get_mask_key_for_id(id);
    const gchar *key = g_quark_to_string(quark);
    GwyContainer *data;
    GwyRGBA rgba;

    gwy_pixmap_layer_set_data_key(layer, key);
    gwy_layer_mask_set_color_key(GWY_LAYER_MASK(layer), key);
    gwy_data_view_set_alpha_layer(dataview, layer);

    data = gwy_data_view_get_data(dataview);
    if (!gwy_rgba_get_from_container(&rgba, data, key)) {
        gwy_rgba_get_from_container(&rgba, gwy_app_settings_get(), "/mask");
        gwy_rgba_store_to_container(&rgba, data, key);
    }

    return layer;
}

/**
 * gwy_create_preview:
 * @data: Data container with images to preview.
 * @id: Data id of preview image in @data.
 * @size: Preview size.  Prefrably one of the standard sizes.
 * @have_mask: %TRUE if the preview will have mask and should be set up so.
 *
 * Creates and sets up a preview widget for use in modules.
 *
 * Returns: A new data view widget with the preview.
 *
 * Since: 2.59
 **/
GtkWidget*
gwy_create_preview(GwyContainer *data,
                   gint id,
                   gint size,
                   gboolean have_mask)
{
    GQuark quark = gwy_app_get_data_key_for_id(id);
    const gchar *key = g_quark_to_string(quark);
    GwyDataView *dataview;
    GtkWidget *widget;

    widget = gwy_data_view_new(data);
    dataview = GWY_DATA_VIEW(widget);
    gwy_data_view_set_data_prefix(dataview, key);
    create_basic_layer(dataview, id);
    if (have_mask)
        create_mask_layer(dataview, id);
    gwy_set_data_preview_size(dataview, size);
    g_object_set_data(G_OBJECT(widget), "gwy-preview-size", GINT_TO_POINTER(size));

    return widget;
}

/**
 * gwy_create_dialog_preview_hbox:
 * @dialog: A data processing dialog.
 * @dataview: Preview data view, usually created by gwy_create_preview().
 * @pack_end: %TRUE to pack the data view to the end; %FALSE to pack it to the start.
 *
 * Creates the typical data processing dialog hbox with a preview.
 *
 * The box is added to the dialog.
 *
 * Returns: A new #GtkBox widget.
 *
 * Since: 2.59
 **/
GtkWidget*
gwy_create_dialog_preview_hbox(GtkDialog *dialog,
                               GwyDataView *dataview,
                               gboolean pack_end)
{
    GtkWidget *hbox, *alignment, *vbox;
    gint size;

    hbox = gwy_hbox_new(8);
    gtk_container_set_border_width(GTK_CONTAINER(hbox), 4);

    g_return_val_if_fail(GTK_IS_DIALOG(dialog), hbox);
    g_return_val_if_fail(GWY_IS_DATA_VIEW(dataview), hbox);

    if (GWY_IS_DIALOG(dialog))
        gwy_dialog_add_content(GWY_DIALOG(dialog), hbox, FALSE, FALSE, 0);
    else {
        vbox = gtk_dialog_get_content_area(GTK_DIALOG(dialog));
        gtk_box_pack_start(GTK_BOX(vbox), hbox, FALSE, FALSE, 0);
    }

    alignment = gtk_alignment_new(0.0, 0.0, 0.0, 0.0);
    if ((size = GPOINTER_TO_INT(g_object_get_data(G_OBJECT(dataview), "gwy-preview-size"))))
        gtk_widget_set_size_request(alignment, size, -1);
    gtk_container_add(GTK_CONTAINER(alignment), GTK_WIDGET(dataview));
    if (pack_end)
        gtk_box_pack_end(GTK_BOX(hbox), alignment, FALSE, FALSE, 0);
    else
        gtk_box_pack_start(GTK_BOX(hbox), alignment, FALSE, FALSE, 0);

    return hbox;
}

/**
 * gwy_create_preview_vector_layer:
 * @dataview: Preview data view, usually created by gwy_create_preview().
 * @id: Data id of preview image in @dataview's data.
 * @name: Layer/selection type name, without the GwyLayer/GwySelection prefix.  So usually "Point", "Line" or
 *        "Rectangle".
 * @max_objects: Maximum number of objects in the selection.
 * @editable: %TRUE for a user-editable selection, %FALSE to disable editing.
 *
 * Creates and sets up a vector layer for use in module previews.
 *
 * The selection's key will have the form "/0/select/lcname", where @lcname is the lowercase version of @name.  You
 * can query the layer using #GwyDataView functions.
 *
 * Parameters @max_objects and @editable exist for convenience.  The corresponding properties can be modified later.
 *
 * In typical scenarios this function is also suitable for switching vector layers in the preview.  Simply create
 * a different layer and the current one will be discarded – this assumes you do not keep the old layer object around.
 * Selections are kept in @dataview's data, so they will be automatically restored when switching back and forth.
 *
 * Returns: The layer's selection.  No reference is added; use g_object_ref() if you want to keep the selection
 *          around after the preview is destroyed.
 *
 * Since: 2.61
 **/
GwySelection*
gwy_create_preview_vector_layer(GwyDataView *dataview,
                                gint id,
                                const gchar *name,
                                gint max_objects,
                                gboolean editable)
{
    GwyVectorLayer *layer;
    GwySelection *selection;
    GType type;
    gchar *s, *t;

    s = g_strconcat("GwyLayer", name, NULL);
    type = g_type_from_name(s);
    g_free(s);
    g_return_val_if_fail(type, NULL);
    g_return_val_if_fail(g_type_is_a(type, GWY_TYPE_VECTOR_LAYER), NULL);

    layer = GWY_VECTOR_LAYER(g_object_new(type, NULL));
    s = g_strdup_printf("/%d/select/%s", id, name);
    t = strrchr(s, '/');
    g_assert(t);
    t++;
    *t = g_ascii_tolower(*t);
    gwy_vector_layer_set_selection_key(layer, s);
    g_free(s);
    gwy_vector_layer_set_editable(layer, editable);
    gwy_data_view_set_top_layer(dataview, layer);

    selection = gwy_vector_layer_ensure_selection(layer);
    gwy_selection_set_max_objects(selection, max_objects);

    return selection;
}

static void
active_page_changed(GtkNotebook *notebook, G_GNUC_UNUSED gpointer some_gtk_shit, gint pageno, GwyParams *params)
{
    gint id = GPOINTER_TO_INT(g_object_get_data(G_OBJECT(notebook), "gwy-active-page-param-id"));
    gwy_params_set_int(params, id, pageno);
}

static void
switch_active_page(GtkNotebook *notebook, GwyParams *params)
{
    gint id = GPOINTER_TO_INT(g_object_get_data(G_OBJECT(notebook), "gwy-active-page-param-id"));
    gtk_notebook_set_current_page(notebook, gwy_params_get_int(params, id));
}

/**
 * gwy_param_active_page_link_to_notebook:
 * @params: A parameter value set.
 * @id: Parameter identifier.
 * @notebook: A notebook widget.
 *
 * Connects an active page parameter to a notebook.
 *
 * This function should be called after the notebook was fully constructed.  The active notebook page is set according
 * to the parameter (clamping values that refer to non-existent pages).  Future page switches will update the
 * parameter value, allowing to simply save it to settings when the module dialog is finished.
 *
 * Since: 2.59
 **/
void
gwy_param_active_page_link_to_notebook(GwyParams *params,
                                       gint id,
                                       GtkNotebook *notebook)
{
    GwyParamDef *pardef;
    const GwyParamDefItem *def;
    gint pageno, npages;

    g_return_if_fail(GWY_IS_PARAMS(params));
    g_return_if_fail(GTK_IS_NOTEBOOK(notebook));
    g_return_if_fail(!g_object_get_data(G_OBJECT(notebook), "gwy-active-page-param-id"));

    pardef = gwy_params_get_def(params);
    def = _gwy_param_def_item(pardef, _gwy_param_def_index(pardef, id));
    g_return_if_fail(def && def->type == GWY_PARAM_ACTIVE_PAGE);

    npages = gtk_notebook_get_n_pages(notebook);
    pageno = gwy_params_get_int(params, id);
    pageno = CLAMP(pageno, 0, npages-1);
    gwy_params_set_int(params, id, pageno);

    /* Here we assume params will outlive notebook. */
    g_object_set_data(G_OBJECT(notebook), "gwy-active-page-param-id", GINT_TO_POINTER(id));
    /* NB: Switching pages before the notebook is shown has no effect.  See GtkNotebook docs. */
    g_signal_connect(notebook, "show", G_CALLBACK(switch_active_page), params);
    g_signal_connect(notebook, "switch-page", G_CALLBACK(active_page_changed), params);
}

static void
expander_expanded(GtkExpander *expander,
                  G_GNUC_UNUSED GParamSpec *pspec,
                  GwyParams *params)
{
    gint id = GPOINTER_TO_INT(g_object_get_data(G_OBJECT(expander), "gwy-expander-param-id"));

    gwy_params_set_boolean(params, id, gtk_expander_get_expanded(expander));
}

/**
 * gwy_create_expander_with_param:
 * @label: Expander label markup. Usually boldface Options.
 * @params: A parameter value set.
 * @id: Parameter identifier.
 *
 * Creates an expander linked to a boolean parameter.
 *
 * This is a convenience function for making an expander whose state is remembered in settings. The parameter
 * identified by @id must be a boolean parameter. The expander initial state will be set from the parameter and,
 * conversely, the parameter will be updated according to the expander state.
 *
 * Returns: A newly created #GtkExpander widget.
 *
 * Since: 2.62
 **/
GtkWidget*
gwy_create_expander_with_param(const gchar *label,
                               GwyParams *params,
                               gint id)
{
    GtkWidget *expander;

    expander = gtk_expander_new(label);
    gtk_expander_set_use_markup(GTK_EXPANDER(expander), TRUE);
    gtk_expander_set_expanded(GTK_EXPANDER(expander), gwy_params_get_boolean(params, id));
    g_object_set_data(G_OBJECT(expander), "gwy-expander-param-id", GINT_TO_POINTER(id));
    g_signal_connect(expander, "notify::expanded", G_CALLBACK(expander_expanded), params);

    return expander;
}

static gboolean
item_is_visible(GtkTreeModel *model, GtkTreeIter *iter, gpointer default_item)
{
    gpointer item;

    gtk_tree_model_get(model, iter, 0, &item, -1);
    return item != default_item;
}

/**
 * gwy_create_inventory_model_without_default:
 * @store: An inventory store.
 *
 * Creates a tree model filter around an inventory store which hides the default item.
 *
 * The model can be used to create resource lists without the default item if it is special and should not be shown to
 * users. Remember you need to translate iters between the models using
 * gtk_tree_model_filter_convert_child_iter_to_iter() and gtk_tree_model_filter_convert_iter_to_child_iter().
 *
 * Returns: A newly created #GtkTreeModelFilter wrapping @store.
 *
 * Since: 2.62
 **/
GtkTreeModel*
gwy_create_inventory_model_without_default(GwyInventoryStore *store)
{
    GtkTreeModel *filtermodel;
    gpointer default_item;

    g_return_val_if_fail(GWY_IS_INVENTORY_STORE(store), NULL);
    default_item = gwy_inventory_get_default_item(gwy_inventory_store_get_inventory(store));
    filtermodel = gtk_tree_model_filter_new(GTK_TREE_MODEL(store), NULL);
    gtk_tree_model_filter_set_visible_func(GTK_TREE_MODEL_FILTER(filtermodel), &item_is_visible, default_item, NULL);

    return filtermodel;
}

/**
 * gwy_select_in_filtered_inventory_treeeview:
 * @treeview: A filtered tree view showing an inventory.
 * @name: Item name to select.
 *
 * Selects an item in filtered tree view showing an inventory.
 *
 * Usually the tree view would show a #GtkTreeModelFilter model created by
 * gwy_create_inventory_model_without_default(). However, this function works also for other filter models around
 * a #GwyInventoryStore.
 *
 * Since: 2.62
 **/
void
gwy_select_in_filtered_inventory_treeeview(GtkTreeView *treeview,
                                           const gchar *name)
{
    GtkTreeModelFilter *filtermodel;
    GwyInventoryStore *store;
    GtkTreeIter storeiter, filteriter;
    GtkTreeSelection *selection;

    filtermodel = GTK_TREE_MODEL_FILTER(gtk_tree_view_get_model(treeview));
    store = GWY_INVENTORY_STORE(gtk_tree_model_filter_get_model(filtermodel));
    if (gwy_inventory_store_get_iter(store, name, &storeiter)
        && gtk_tree_model_filter_convert_child_iter_to_iter(filtermodel, &filteriter, &storeiter)) {
        selection = gtk_tree_view_get_selection(treeview);
        gtk_tree_selection_select_iter(selection, &filteriter);
    }
}

/************************** Documentation ****************************/

/**
 * SECTION:gwymoduleutils
 * @title: module utils
 * @short_description: Module utility functions
 * @include: app/gwymoduleutils.h
 **/

/**
 * GwySaveAuxiliaryCreate:
 * @user_data: The data passed to gwy_save_auxiliary_with_callback() as @user_data.
 * @data_len: The length of the returned data in bytes.  Leaving it unset has the same effect as setting it to
 *            a negative value.  See gwy_save_auxiliary_data() for details.
 *
 * The type of auxiliary saved data creation function.
 *
 * Returns: The data to save.  It must not return %NULL.
 *
 * Since: 2.3
 **/

/**
 * GwySaveAuxiliaryDestroy:
 * @data: The data returned by the corresponding #GwySaveAuxiliaryCreate function.
 * @user_data: The data passed to gwy_save_auxiliary_with_callback() as @user_data.
 *
 * The type of auxiliary saved data destruction function.
 *
 * Since: 2.3
 **/

/**
 * GwyPreviewSurfaceFlags:
 * @GWY_PREVIEW_SURFACE_DENSITY: Render a point density map instead of the data.
 * @GWY_PREVIEW_SURFACE_FILL: Make the data field as large as the specified resolutions at least in one dimension (it
 *                            can be prevented in the other by different aspect ratio).
 *
 * Type of behaviour modifying flags that can be passed to
 * gwy_preview_surface_to_datafield().
 *
 * Since: 2.46
 **/

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