File: undo.c

package info (click to toggle)
gwyddion 2.47-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 38,180 kB
  • ctags: 37,276
  • sloc: ansic: 317,531; sh: 5,122; xml: 3,583; python: 3,067; makefile: 2,694; cpp: 2,550; pascal: 418; perl: 154; ruby: 130; sed: 17
file content (1189 lines) | stat: -rw-r--r-- 33,926 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
/*
 *  @(#) $Id: undo.c 19043 2016-10-08 18:58:43Z yeti-dn $
 *  Copyright (C) 2003-2006,2014 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.
 */

/* FIXME: non-object code paths are untested and may leak memory or even
 * crash */

#include "config.h"
#include <stdarg.h>
#include <string.h>
#include <libgwyddion/gwymacros.h>
#include <libprocess/datafield.h>
#include <app/menu.h>
#include <app/log.h>
#include <app/undo.h>
#include "gwyappinternal.h"

enum {
#if (SIZEOF_VOIDP > 4)
    UNDO_LEVELS = 8
#else
    UNDO_LEVELS = 4
#endif
};

typedef struct {
    GQuark key;
    GValue value;
} GwyAppUndoItem;

typedef struct {
    gulong id;
    guint nitems;
    GwyAppUndoItem *items;
} GwyAppUndoLevel;

typedef struct {
    gpointer container;
    GList *undo;
    GList *redo;
    gint modif;
} GwyAppUndo;

static void        undo_log_container              (GwyContainer *data);
static void        redo_log_container              (GwyContainer *data);
static void        gwy_app_undo_reuse_levels       (GwyAppUndoLevel *level,
                                                    GList *available);
static void        gwy_app_undo_or_redo            (GwyContainer *data,
                                                    GwyAppUndoLevel *level);
static GList*      gwy_list_split                  (GList *list,
                                                    guint n,
                                                    GList **tail);
static void        gwy_app_undo_container_finalized(gpointer userdata,
                                                    GObject *deceased_data);
static void        gwy_app_undo_list_free          (GList *list);
static gint        gwy_app_undo_compare_data       (gconstpointer a,
                                                    gconstpointer b);
static GwyAppUndo* gwy_undo_get_for_data           (GwyContainer *data,
                                                    gboolean do_create);
static void        gwy_app_log_undo_or_redo        (GwyContainer *data,
                                                    GwyAppUndoLevel *level,
                                                    const gchar *qualname);

static GList *container_list = NULL;
static gboolean undo_disabled = FALSE;

/**
 * gwy_app_undo_checkpoint:
 * @data: A data container.
 * @...: %NULL-terminated list of container item names to save.
 *
 * Create a point in the undo history it is possible to return to.
 *
 * In addition to what gwy_undo_checkpoint() does, this function takes care
 * of updating application controls state.
 *
 * Returns: Undo level id (zero if undo/redo is disabled).  Not useful (yet).
 **/
gulong
gwy_app_undo_checkpoint(GwyContainer *data,
                        ...)
{
    va_list ap;
    GQuark *keys;
    guint i, n;
    gulong id;

    if (undo_disabled)
        return 0;

    n = 0;
    va_start(ap, data);
    while (TRUE) {
        if (!va_arg(ap, const gchar*))
            break;
        n++;
    };
    va_end(ap);

    keys = g_newa(GQuark, n);
    va_start(ap, data);
    for (i = 0; i < n; i++) {
        keys[i] = g_quark_from_string(va_arg(ap, const gchar*));
    }
    va_end(ap);

    id = gwy_app_undo_qcheckpointv(data, n, keys);

    return id;
}

/**
 * gwy_app_undo_checkpointv:
 * @data: A data container.
 * @n: The number of strings in @keys.
 * @keys: An array of container string keys to save data.
 *        It can contain holes, that is NUL's, they are ignored.  However, it
 *        should contain at least one real key.
 *
 * Create a point in the undo history it is possible to return to.
 *
 * In addition to what gwy_undo_checkpointv() does, this function takes care
 * of updating application controls state.
 *
 * Returns: Undo level id.  Not useful (yet).
 **/
gulong
gwy_app_undo_checkpointv(GwyContainer *data,
                         guint n,
                         const gchar **keys)
{
    gulong id;

    id = gwy_undo_checkpointv(data, n, keys);
    if (id)
        gwy_app_sensitivity_set_state(GWY_MENU_FLAG_UNDO | GWY_MENU_FLAG_REDO,
                                      GWY_MENU_FLAG_UNDO);

    return id;
}

/**
 * gwy_app_undo_qcheckpoint:
 * @data: A data container.
 * @...: 0-terminated list of container item quark keys to save.
 *
 * Create a point in the undo history it is possible to return to.
 *
 * In addition to what gwy_undo_checkpoint() does, this function takes care
 * of updating application controls state.
 *
 * Returns: Undo level id.  Not useful (yet).
 **/
gulong
gwy_app_undo_qcheckpoint(GwyContainer *data,
                         ...)
{
    va_list ap;
    GQuark *keys;
    guint i, n;
    gulong id;

    if (undo_disabled)
        return 0;

    n = 0;
    va_start(ap, data);
    while (TRUE) {
        if (!va_arg(ap, GQuark))
            break;
        n++;
    };
    va_end(ap);

    keys = g_newa(GQuark, n);
    va_start(ap, data);
    for (i = 0; i < n; i++) {
        keys[i] = va_arg(ap, GQuark);
    }
    va_end(ap);

    id = gwy_app_undo_qcheckpointv(data, n, keys);

    return id;
}

/* Create a list of calibration keys corresponding to channel keys in @keys.
 * If @only_calib_keys is true then only these keys are returned
 * otherwise a list that contains all original keys plus any missing
 * calibration keys is returned. */
static GQuark*
construct_calibrations_keys(GwyContainer *data,
                            guint *pn, const GQuark *keys,
                            gboolean only_calib_keys)
{
    static const gchar *calib_keys[] = {
        "cal_xerr", "cal_yerr", "cal_zerr", "cal_xunc", "cal_yunc", "cal_zunc",
    };

    GArray *newkeys;
    guint n = *pn;
    GwyAppKeyType type;
    gint len, i, j, k, id;

    newkeys = g_array_new(FALSE, FALSE, sizeof(GQuark));
    for (i = 0; i < n; i++) {
        GQuark key = keys[i];
        if (!key)
            continue;

        id = _gwy_app_analyse_data_key(g_quark_to_string(key), &type, &len);
        if (!only_calib_keys)
            g_array_append_val(newkeys, key);
        if (type != KEY_IS_DATA)
            continue;

        for (k = 0; k < G_N_ELEMENTS(calib_keys); k++) {
            gchar buf[40];
            GQuark calkey;

            g_snprintf(buf, sizeof(buf), "/%d/data/%s", id, calib_keys[k]);
            calkey = g_quark_from_string(buf);
            if (!gwy_container_contains(data, calkey))
                continue;

            if (only_calib_keys)
                g_array_append_val(newkeys, calkey);
            else {
                for (j = 0; j < n; j++) {
                    if (keys[j] == calkey)
                        break;
                }
                if (j == n)
                    g_array_append_val(newkeys, calkey);
            }
        }
    }

    *pn = newkeys->len;
    return (GQuark*)g_array_free(newkeys, FALSE);
}

/**
 * gwy_app_undo_qcheckpointv:
 * @data: A data container.
 * @n: The number of strings in @keys.
 * @keys: An array of container quark keys to save data.
 *        It can contain holes, that is 0's, they are ignored.  However, it
 *        should contain at least one real key.
 *
 * Create a point in the undo history it is possible to return to.
 *
 * In addition to what gwy_undo_checkpointv() does, this function takes care
 * of updating application controls state.
 *
 * If @keys include channel keys the corresponding channel calibration data is
 * saved together with the data and then removed from the container.  This
 * prevents mismatch between a data field and its calibration data.  Therefore,
 * if you perform a data operation that can also meaningfully transform the
 * corresponding calibration data take care to obtain it before saving undo.
 *
 * Returns: Undo level id.  Not useful (yet).
 **/
gulong
gwy_app_undo_qcheckpointv(GwyContainer *data,
                          guint n,
                          const GQuark *keys)
{
    GQuark *calkeys;
    gulong id;
    guint nwcal, i;

    nwcal = n;
    calkeys = construct_calibrations_keys(data, &nwcal, keys, FALSE);
    id = gwy_undo_qcheckpointv(data, nwcal, calkeys);
    g_free(calkeys);

    if (id)
        gwy_app_sensitivity_set_state(GWY_MENU_FLAG_UNDO | GWY_MENU_FLAG_REDO,
                                      GWY_MENU_FLAG_UNDO);

    nwcal = n;
    calkeys = construct_calibrations_keys(data, &nwcal, keys, TRUE);
    for (i = 0; i < nwcal; i++)
        gwy_container_remove(data, calkeys[i]);
    g_free(calkeys);

    return id;
}

/**
 * gwy_app_undo_undo_container:
 * @data: A data container.
 *
 * Performs undo on a data container.
 *
 * It must have undo available.
 *
 * In addition to what gwy_undo_undo_container() does, this function takes care
 * of updating application controls state.
 **/
void
gwy_app_undo_undo_container(GwyContainer *data)
{
    GwyAppUndo *appundo;

    undo_log_container(data);
    gwy_undo_undo_container(data);
    appundo = gwy_undo_get_for_data(data, FALSE);
    if (!appundo)
        return;
    gwy_app_sensitivity_set_state(GWY_MENU_FLAG_UNDO | GWY_MENU_FLAG_REDO,
                                  GWY_MENU_FLAG_REDO
                                  | (appundo->undo ? GWY_MENU_FLAG_UNDO : 0));
}

/**
 * gwy_app_undo_redo_container:
 * @data: A data container.
 *
 * Performs undo on a data container.
 *
 * It must have redo available.
 *
 * In addition to what gwy_undo_redo_container() does, this function takes care
 * of updating application controls state.
 **/
void
gwy_app_undo_redo_container(GwyContainer *data)
{
    GwyAppUndo *appundo;

    redo_log_container(data);
    gwy_undo_redo_container(data);
    appundo = gwy_undo_get_for_data(data, FALSE);
    if (!appundo)
        return;
    gwy_app_sensitivity_set_state(GWY_MENU_FLAG_UNDO | GWY_MENU_FLAG_REDO,
                                  GWY_MENU_FLAG_UNDO
                                  | (appundo->redo ? GWY_MENU_FLAG_REDO : 0));
}

/**
 * gwy_undo_checkpoint:
 * @data: A data container.
 * @...: %NULL-terminated list of container item names to save.
 *
 * Create a point in the undo history it is possible to return to.
 *
 * Returns: Undo level id.  Not useful (yet).
 **/
gulong
gwy_undo_checkpoint(GwyContainer *data,
                    ...)
{
    va_list ap;
    GQuark *keys;
    guint i, n;
    gulong id;

    if (undo_disabled)
        return 0;

    n = 0;
    va_start(ap, data);
    while (TRUE) {
        if (!va_arg(ap, const gchar*))
            break;
        n++;
    };
    va_end(ap);

    keys = g_newa(GQuark, n);
    va_start(ap, data);
    for (i = 0; i < n; i++) {
        keys[i] = g_quark_from_string(va_arg(ap, const gchar*));
    }
    va_end(ap);

    id = gwy_undo_qcheckpointv(data, n, keys);

    return id;
}

/**
 * gwy_undo_qcheckpoint:
 * @data: A data container.
 * @...: 0-terminated list of container item quark keys to save.
 *
 * Create a point in the undo history it is possible to return to.
 *
 * Returns: Undo level id.  Not useful (yet).
 **/
gulong
gwy_undo_qcheckpoint(GwyContainer *data,
                     ...)
{
    va_list ap;
    GQuark *keys;
    guint i, n;
    gulong id;

    if (undo_disabled)
        return 0;

    n = 0;
    va_start(ap, data);
    while (TRUE) {
        if (!va_arg(ap, GQuark))
            break;
        n++;
    };
    va_end(ap);

    keys = g_newa(GQuark, n);
    va_start(ap, data);
    for (i = 0; i < n; i++) {
        keys[i] = va_arg(ap, GQuark);
    }
    va_end(ap);

    id = gwy_undo_qcheckpointv(data, n, keys);

    return id;
}

/**
 * gwy_undo_checkpointv:
 * @data: A data container.
 * @n: The number of strings in @keys.
 * @keys: An array of container string keys to save data.
 *        It can contain holes, that is NUL's, they are ignored.  However, it
 *        should contain at least one real key.
 *
 * Create a point in the undo history it is possible to return to.
 *
 * Returns: Undo level id.  Not useful (yet).
 **/
gulong
gwy_undo_checkpointv(GwyContainer *data,
                     guint n,
                     const gchar **keys)
{
    GQuark *qkeys;
    guint i, j;

    if (!UNDO_LEVELS || undo_disabled)
        return 0;

    g_return_val_if_fail(GWY_IS_CONTAINER(data), 0UL);
    if (!n) {
        g_warning("Nothing to save for undo, no undo level will be created.");
        return 0UL;
    }

    qkeys = g_newa(GQuark, n);
    for (i = j = 0; i < n; i++) {
        if (!keys[i])
            continue;

        qkeys[j] = g_quark_from_string(keys[i]);
        j++;
    }

    return gwy_undo_qcheckpointv(data, j, qkeys);
}

/**
 * gwy_undo_qcheckpointv:
 * @data: A data container.
 * @n: The number of strings in @keys.
 * @keys: An array of container quark keys to save data.
 *        It can contain holes, that is 0's, they are ignored.  However, it
 *        should contain at least one real key.
 *
 * Create a point in the undo history it is possible to return to.
 *
 * Returns: Undo level id.  Not useful (yet).
 **/
gulong
gwy_undo_qcheckpointv(GwyContainer *data,
                      guint n,
                      const GQuark *keys)
{
    static gulong undo_level_id = 0;

    GwyAppUndo *appundo;
    GwyAppUndoLevel *level;
    GList *available;
    guint i, j;

    if (!UNDO_LEVELS || undo_disabled)
        return 0;

    g_return_val_if_fail(GWY_IS_CONTAINER(data), 0UL);
    for (i = j = 0; i < n; i++) {
        if (keys[i])
            j++;
    }

    if (!j) {
        g_warning("Nothing to save for undo, no undo level will be created.");
        return 0UL;
    }

    /* Create new undo level */
    undo_level_id++;
    gwy_debug("Creating a new appundo->undo level #%lu", undo_level_id);
    level = g_new(GwyAppUndoLevel, 1);
    level->nitems = j;
    level->items = g_new0(GwyAppUndoItem, level->nitems);
    level->id = undo_level_id;

    /* Fill the things to save, but don't duplicate objects yet */
    for (i = j = 0; i < n; i++) {
        GwyAppUndoItem *item = level->items + j;

        if (!keys[i])
            continue;
        item->key = keys[i];
        memset(&item->value, 0, sizeof(GValue));
        /* This call itself creates a copy for non-objects; for objects it
         * increases reference count.  However, if we are saving nonexistence,
         * item->value is left zero-filled. */
        gwy_container_gis_value(data, item->key, &item->value);
        j++;
    }
    g_assert(j == level->nitems);

    /* add to the undo queue */
    appundo = gwy_undo_get_for_data(data, TRUE);

    /* gather undo/redo levels we are going to free for potential reuse */
    appundo->undo = gwy_list_split(appundo->undo, UNDO_LEVELS-1, &available);
    available = g_list_concat(available, appundo->redo);
    appundo->redo = NULL;

    gwy_app_undo_reuse_levels(level, available);
    appundo->undo = g_list_prepend(appundo->undo, level);
    appundo->modif++;    /* TODO */

    return level->id;
}

/**
 * gwy_app_undo_reuse_levels:
 * @level: An undo level with objects that have to be either duplicated or
 *         reused from to-be-discarded levels.
 * @available: A list of to-be-discarded levels to eventually reuse.
 *
 * Actually duplicates data in @level, eventually reusing @available.
 **/
static void
gwy_app_undo_reuse_levels(GwyAppUndoLevel *level,
                          GList *available)
{
    GType type;
    GList *l;
    guint i, j;
    GwyAppUndoItem *item, *jtem;
    GObject *iobject, *jobject;
    GwyAppUndoLevel *lvl;
    gboolean found;

    for (i = 0; i < level->nitems; i++) {
        item = level->items + i;
        if (!G_VALUE_HOLDS_OBJECT(&item->value))
            continue;

        found = FALSE;
        iobject = g_value_get_object(&item->value);
        type = G_TYPE_FROM_INSTANCE(iobject);
        /* scan through all available levels and all objects inside */
        for (l = available; l; l = g_list_next(l)) {
            lvl = (GwyAppUndoLevel*)l->data;
            for (j = 0; j < lvl->nitems; j++) {
                jtem = lvl->items + j;
                if (!G_VALUE_HOLDS_OBJECT(&jtem->value))
                    continue;
                jobject = g_value_get_object(&jtem->value);
                if (G_TYPE_FROM_INSTANCE(jobject) != type)
                    continue;

                /* we've found a reusable item
                 * FIXME: for datafields, we normally know they are all
                 * all the same size, but otherwise there should be some
                 * real compatibility check */
                gwy_serializable_clone(iobject, jobject);
                g_value_copy(&jtem->value, &item->value);
                g_value_unset(&jtem->value);
                found = TRUE;
                gwy_debug("Item (%lu,%x) reused from (%lu,%x)",
                          level->id, item->key, lvl->id, jtem->key);

                l = NULL;    /* break from outer cycle */
                break;
            }
        }
        if (!found) {
            if (G_VALUE_HOLDS_OBJECT(&item->value)) {
                iobject = g_value_get_object(&item->value);
                g_value_take_object(&item->value,
                                    gwy_serializable_duplicate(iobject));
            }
            gwy_debug("Item (%lu,%x) created as new", level->id, item->key);
        }
    }

    gwy_app_undo_list_free(available);
}

/**
 * gwy_undo_undo_container:
 * @data: A data container.
 *
 * Performs undo on a data container.
 *
 * It must have undo available.
 **/
void
gwy_undo_undo_container(GwyContainer *data)
{
    GwyAppUndo *appundo;
    GwyAppUndoLevel *level;
    GList *l;

    if (undo_disabled)
        return;

    appundo = gwy_undo_get_for_data(data, FALSE);
    g_return_if_fail(appundo && appundo->undo);

    level = (GwyAppUndoLevel*)appundo->undo->data;
    gwy_debug("Undoing to undo level id #%lu", level->id);
    gwy_app_undo_or_redo(data, level);

    l = appundo->undo;
    appundo->undo = g_list_remove_link(appundo->undo, l);
    appundo->redo = g_list_concat(l, appundo->redo);
    appundo->modif--;    /* TODO */
}

static void
undo_log_container(GwyContainer *data)
{
    GwyAppUndo *appundo;

    if (undo_disabled)
        return;

    appundo = gwy_undo_get_for_data(data, FALSE);
    g_return_if_fail(appundo && appundo->undo);
    gwy_app_log_undo_or_redo(data, (GwyAppUndoLevel*)appundo->undo->data,
                             "builtin::undo");
}

/**
 * gwy_undo_redo_container:
 * @data: A data container.
 *
 * Performs undo on a data container.
 *
 * It must have redo available.
 **/
void
gwy_undo_redo_container(GwyContainer *data)
{
    GwyAppUndo *appundo;
    GwyAppUndoLevel *level;
    GList *l;

    if (undo_disabled)
        return;

    appundo = gwy_undo_get_for_data(data, FALSE);
    g_return_if_fail(appundo && appundo->redo);

    level = (GwyAppUndoLevel*)appundo->redo->data;
    gwy_debug("Redoing to undo level id #%lu", level->id);
    gwy_app_undo_or_redo(data, level);

    l = appundo->redo;
    appundo->redo = g_list_remove_link(appundo->redo, l);
    appundo->undo = g_list_concat(l, appundo->undo);
    appundo->modif++;    /* TODO */
}

static void
redo_log_container(GwyContainer *data)
{
    GwyAppUndo *appundo;

    if (undo_disabled)
        return;

    appundo = gwy_undo_get_for_data(data, FALSE);
    g_return_if_fail(appundo && appundo->redo);
    gwy_app_log_undo_or_redo(data, (GwyAppUndoLevel*)appundo->redo->data,
                             "builtin::redo");
}

static void
gwy_app_undo_or_redo(GwyContainer *data,
                     GwyAppUndoLevel *level)
{
    GValue value;
    gboolean app, undo;
    guint i;

    memset(&value, 0, sizeof(GValue));
    for (i = 0; i < level->nitems; i++) {
        GwyAppUndoItem *item = level->items + i;

        /* This call itself creates a copy for non-objects; for objects
         * it increases reference count.  However, if we are restoring
         * nonexistence, item->value is left zero-filled. */
        app = gwy_container_gis_value(data, item->key, &value);
        undo = G_VALUE_TYPE(&item->value) != 0;
        if (undo && app) {
            if (G_VALUE_TYPE(&item->value) != G_VALUE_TYPE(&value)) {
                g_critical("Types of undone/redone and current object "
                           "don't match");
                continue;
            }
            gwy_debug("Changing item <%s>", g_quark_to_string(item->key));
            /* Note: we have to use duplicate to destroy object identity
             * (user data, signals, ...) */
            if (G_VALUE_HOLDS_OBJECT(&item->value)) {
                GObject *object;

                object = g_value_get_object(&item->value);
                gwy_debug("saved object: %p", object);
                object = gwy_serializable_duplicate(object);
                gwy_container_set_object(data, item->key, object);
                g_object_unref(object);

                g_value_copy(&value, &item->value);
                g_value_unset(&value);
            }
            else {
                gwy_container_set_value(data, item->key, &item->value, 0);
                g_value_copy(&item->value, &value);
                g_value_unset(&value);
            }
        }
        else if (undo && !app) {
            gwy_debug("Restoring item <%s>", g_quark_to_string(item->key));
            gwy_container_set_value(data, item->key, &item->value, 0);
            g_value_unset(&item->value);
        }
        else if (!undo && app) {
            gwy_debug("Deleting item <%s>", g_quark_to_string(item->key));
            g_value_init(&item->value, G_VALUE_TYPE(&value));
            g_value_copy(&value, &item->value);
            gwy_container_remove(data, item->key);
            g_value_unset(&value);
        }
        else
            g_warning("Undoing/redoing NULL to another NULL");
    }
}

static void
gwy_app_log_undo_or_redo(GwyContainer *data,
                         GwyAppUndoLevel *level,
                         const gchar *qualname)
{
    GSList *channel_ids = NULL, *l;
    guint i;

    for (i = 0; i < level->nitems; i++) {
        GwyAppUndoItem *item = level->items + i;
        GwyAppKeyType type;
        gint id, len;
        gpointer p;

        id = _gwy_app_analyse_data_key(g_quark_to_string(item->key),
                                       &type, &len);
        p = GINT_TO_POINTER(id);

        if ((type == KEY_IS_DATA
             || type == KEY_IS_MASK
             || type == KEY_IS_SHOW)
            && !g_slist_find(channel_ids, p))
            channel_ids = g_slist_append(channel_ids, p);
    }

    for (l = channel_ids; l; l = g_slist_next(l)) {
        gint id = GPOINTER_TO_INT(l->data);
        gwy_app_channel_log_add(data, id, id, qualname, NULL);
    }

    g_slist_free(channel_ids);
}

/**
 * gwy_list_split:
 * @list: A list.
 * @n: Length to split list at.
 * @tail: Pointer to store list tail to.
 *
 * Splits a list at given position.
 *
 * Returns: New list head.
 **/
static GList*
gwy_list_split(GList *list,
               guint n,
               GList **tail)
{
    GList *l;

    g_return_val_if_fail(tail, list);
    *tail = NULL;
    if (!list)
        return NULL;

    list = g_list_first(list);
    l = g_list_nth(list, n);
    if (!l)
        return list;

    l->prev->next = NULL;
    l->prev = NULL;
    *tail = l;

    return list;
}

/**
 * gwy_undo_container_has_undo:
 * @data: Data container to get undo infomation of.
 *
 * Returns whether there is any undo available for a container.
 *
 * Returns: %TRUE if there is undo, %FALSE otherwise.
 **/
gboolean
gwy_undo_container_has_undo(GwyContainer *data)
{
    GwyAppUndo *appundo;

    appundo = gwy_undo_get_for_data(data, FALSE);
    return appundo && appundo->undo;
}

/**
 * gwy_undo_container_has_redo:
 * @data: Data container to get redo infomation of.
 *
 * Returns whether there is any redo available for a container.
 *
 * Returns: %TRUE if there is redo, %FALSE otherwise.
 **/
gboolean
gwy_undo_container_has_redo(GwyContainer *data)
{
    GwyAppUndo *appundo;

    appundo = gwy_undo_get_for_data(data, FALSE);
    return appundo && appundo->redo;
}

/**
 * gwy_undo_container_get_modified:
 * @data: Data container to get modification infomation of.
 *
 * Tests whether a container was modified.
 *
 * FIXME: it may not work.
 *
 * Returns: %TRUE if container was modified, %FALSE otherwise.
 **/
gint
gwy_undo_container_get_modified(GwyContainer *data)
{
    GwyAppUndo *appundo;

    appundo = gwy_undo_get_for_data(data, FALSE);
    return appundo ? appundo->modif : 0;
}

/**
 * gwy_undo_container_set_unmodified:
 * @data: Data container to set modification infomation of.
 *
 * Marks a data container as umodified (that is, saved).
 **/
void
gwy_undo_container_set_unmodified(GwyContainer *data)
{
    GwyAppUndo *appundo;

    appundo = gwy_undo_get_for_data(data, FALSE);
    if (appundo)
        appundo->modif = 0;
}

/**
 * gwy_app_undo_container_finalized:
 * @userdata: Item from @container_list corresponding to finalized data.
 * @deceased_data: A #GwyContainer pointer (the object may not longer exits).
 *
 * Removes all undo and redo information for a container.
 **/
static void
gwy_app_undo_container_finalized(gpointer userdata,
                                 GObject *deceased_data)
{
    GList *item = (GList*)userdata;
    GwyAppUndo *appundo = (GwyAppUndo*)item->data;

    // We could also remove the weak refs when disabling undo, but this seems
    // easier.
    if (undo_disabled)
        return;

    gwy_debug("Freeing undo for Container %p", deceased_data);
    g_assert(appundo->container == (gpointer)deceased_data);
    container_list = g_list_delete_link(container_list, item);
    gwy_app_undo_list_free(appundo->redo);
    gwy_app_undo_list_free(appundo->undo);
    g_free(appundo);
}

static void
gwy_app_undo_list_free(GList *list)
{
    GwyAppUndoLevel *level;
    GList *l;
    guint i;

    if (!list)
        return;

    for (l = g_list_first(list); l; l = g_list_next(l)) {
        level = (GwyAppUndoLevel*)l->data;
        for (i = 0; i < level->nitems; i++) {
            GwyAppUndoItem *item = level->items + i;

            if (G_VALUE_TYPE(&item->value)) {
                gwy_debug("Item (%lu,%x) destroyed", level->id, item->key);
                g_value_unset(&item->value);
            }
            /* FIXME: GWY_OBJECT_UNREF(level->items[i].object); */
        }
        g_free(level->items);
        g_free(level);
    }
    g_list_free(list);
}

static gint
gwy_app_undo_compare_data(gconstpointer a,
                          gconstpointer b)
{
    GwyAppUndo *ua = (GwyAppUndo*)a;

    /* sign does not matter, only used for equality test */
    return (guchar*)ua->container - (guchar*)b;
}

static GwyAppUndo*
gwy_undo_get_for_data(GwyContainer *data,
                      gboolean do_create)
{
    GwyAppUndo *appundo;
    GList *l;

    l = g_list_find_custom(container_list, data, &gwy_app_undo_compare_data);
    if (!l) {
        if (!do_create)
            return NULL;

        gwy_debug("Creating undo for Container %p", data);
        appundo = g_new0(GwyAppUndo, 1);
        appundo->container = data;
        container_list = g_list_prepend(container_list, appundo);
        g_object_weak_ref(G_OBJECT(data), gwy_app_undo_container_finalized,
                          container_list);

        return appundo;
    }

    /* move container to head */
    if (l != container_list) {
        container_list = g_list_remove_link(container_list, l);
        container_list = g_list_concat(l, container_list);
    }

    return (GwyAppUndo*)l->data;
}

static GList*
gwy_undo_container_remove_from_list(GList *list,
                                    const gchar *prefix)
{
    guint i, j, len;
    const gchar *key;
    GList *l;

    len = strlen(prefix);

    for (l = list; l; l = g_list_next(l)) {
        GwyAppUndoLevel *level = (GwyAppUndoLevel*)l->data;

        for (i = j = 0; i < level->nitems; i++) {
            key = g_quark_to_string(level->items[i].key);
            if (g_str_has_prefix(key, prefix)
                && (key[len] == '\0'
                    || key[len] == '/')) {
                if (G_VALUE_TYPE(&level->items[i].value))
                    g_value_unset(&level->items[i].value);
            }
            else {
                if (j != i)
                    level->items[j] = level->items[i];
                j++;
            }
        }
        /* Update nitems but don't realloc items, typically it's a waste of
         * CPU */
        level->nitems = j;

        if (!level->nitems) {
            g_free(level->items);
            g_free(level);
            l->data = NULL;
        }
    }

    return g_list_remove_all(list, NULL);
}

/**
 * gwy_undo_container_remove:
 * @data: A data container.
 * @prefix: Prefix to remove undo/redo information under.  Pass %NULL to remove
 *          undo/redo information altogether.
 *
 * Removes undo/redo information for a data container.
 **/
void
gwy_undo_container_remove(GwyContainer *data,
                          const gchar *prefix)
{
    GwyAppUndo *appundo;

    if (undo_disabled)
        return;

    gwy_debug("Removing undo for Container %p and prefix %s", data, prefix);
    appundo = gwy_undo_get_for_data(data, FALSE);
    if (!appundo)
        return;

    if (!prefix || !*prefix) {
        /* Remove head item placed there by gwy_undo_get_for_data() */
        container_list = g_list_delete_link(container_list, container_list);
        gwy_app_undo_list_free(appundo->redo);
        gwy_app_undo_list_free(appundo->undo);
        g_free(appundo);
        return;
    }

    appundo->undo = gwy_undo_container_remove_from_list(appundo->undo, prefix);
    appundo->redo = gwy_undo_container_remove_from_list(appundo->redo, prefix);
}

/**
 * gwy_app_undo_container_remove:
 * @data: A data container managed by the data-browser.
 * @prefix: Prefix to remove undo/redo information under.  Pass %NULL to remove
 *          undo/redo information altogether.
 *
 * Removes undo/redo information for a data container.
 *
 * In addition to what gwy_undo_container_remove() does, this function takes
 * care of updating application controls state.
 *
 * Since: 2.23
 **/
void
gwy_app_undo_container_remove(GwyContainer *data,
                              const gchar *prefix)
{
    GwyAppUndo *appundo;

    gwy_undo_container_remove(data, prefix);
    appundo = gwy_undo_get_for_data(data, FALSE);
    if (!appundo)
        return;
    gwy_app_sensitivity_set_state(GWY_MENU_FLAG_UNDO | GWY_MENU_FLAG_REDO,
                                  (appundo->undo ? GWY_MENU_FLAG_UNDO : 0)
                                  | (appundo->redo ? GWY_MENU_FLAG_REDO : 0));
}

/**
 * gwy_undo_get_enabled:
 *
 * Reports whether undo/redo is globally enabled.
 *
 * Returns: %TRUE if undo/redo is enabled, %FALSE if it is disabled.
 *
 * Since: 2.21
 **/
gboolean
gwy_undo_get_enabled(void)
{
    return !undo_disabled;
}

/**
 * gwy_undo_set_enabled:
 * @setting: %TRUE to enable undo, %FALSE to disable it.
 *
 * Globally enables or disables undo/redo.
 *
 * By default, undo/redo is enabled.  Non-GUI applications that run module
 * functions may wish to disable it to conserve resources.
 *
 * If undo/redo is disabled undo information manipulating functions such as
 * gwy_app_undo_qcheckpoint() become no-op and
 * gwy_undo_container_get_modified() always returns zero. Disabling undo also
 * removes saved undo data of all containers.
 *
 * Since: 2.21
 **/
void
gwy_undo_set_enabled(gboolean setting)
{
    undo_disabled = !setting;
    /* Remove all data when disabling */
    if (undo_disabled) {
        while (container_list) {
            GwyAppUndo *appundo = (GwyAppUndo*)container_list->data;
            container_list = g_list_delete_link(container_list, container_list);
            gwy_app_undo_list_free(appundo->redo);
            gwy_app_undo_list_free(appundo->undo);
            g_free(appundo);
        }
        gwy_app_sensitivity_set_state(GWY_MENU_FLAG_UNDO | GWY_MENU_FLAG_REDO,
                                      0);
    }
}

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

/**
 * SECTION:undo
 * @title: undo
 * @short_description: Undo and redo facility
 *
 * For a module developer, the only two useful undo/redo functions are probably
 * gwy_app_undo_checkpoint() and gwy_app_undo_checkpointv() creating a
 * checkpoint in the undo history to which is possible to return to later. You
 * should use these functions before commiting changes to data.
 *
 * The other functions actually perform undo or redo, and has little use
 * outside main application, unless it wishes to implement its local undo.
 *
 * There are two types of functions app-level and container-level.  App-level
 * functions (have `app' in their names) should be generally used only by the
 * main application as they update menus and toolboxes according to undo and
 * redo state.  Container-level functions only perform the actual undo or redo
 * and can be used for local undo implementation.
 *
 * Undo information for a #GwyContainer is automatically destroyed when the
 * container is finalized.
 **/

/* 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 : */