File: gwymodule-file.c

package info (click to toggle)
gwyddion 2.57-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, sid
  • size: 48,860 kB
  • sloc: ansic: 405,916; python: 7,867; sh: 5,241; makefile: 4,507; xml: 3,786; cpp: 2,572; pascal: 418; perl: 154; ruby: 130
file content (1175 lines) | stat: -rw-r--r-- 37,744 bytes parent folder | download | duplicates (2)
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
/*
 *  $Id: gwymodule-file.c 20678 2017-12-18 18:26:55Z yeti-dn $
 *  Copyright (C) 2003,2004 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>
#include <sys/stat.h>
#include <sys/types.h>
#include <glib/gstdio.h>
#include <libgwyddion/gwymacros.h>
#include <libgwyddion/gwyutils.h>
#include <libgwyddion/gwycontainer.h>
#include <libprocess/datafield.h>
#include <libgwydgets/gwygraphmodel.h>
#include <libgwymodule/gwymodule-file.h>
#include "gwymoduleinternal.h"

/* The file function information. */
typedef struct {
    const gchar *name;
    const gchar *description;
    GwyFileDetectFunc detect;
    GwyFileLoadFunc load;
    GwyFileSaveFunc save;
    GwyFileSaveFunc export_;
    gboolean is_detectable;
} GwyFileFuncInfo;

/* Information about current file, passed around during detection */
typedef struct {
    const gchar *winner;
    gint score;
    gboolean only_name;
    GwyFileOperationType mode;
    GwyFileDetectInfo *fileinfo;
} FileDetectData;

/* Information about successful loads and saves of a Container, kept in
 * container_list */
typedef struct {
    gpointer container;
    GQuark name;
    gchar *filename_sys;
} FileTypeInfo;

/* Auxiliary structure to pass both user callback function and data to
 * g_hash_table_foreach() lambda argument in gwy_file_func_foreach() */
typedef struct {
    GFunc function;
    gpointer user_data;
} FuncForeachData;

static gboolean gwy_file_detect_fill_info  (GwyFileDetectInfo *fileinfo,
                                            gboolean only_name);
static void     gwy_file_detect_free_info  (GwyFileDetectInfo *fileinfo);
static void     file_detect_max_score_cb   (const gchar *key,
                                            GwyFileFuncInfo *func_info,
                                            FileDetectData *ddata);
static GwyFileOperationType get_operations (const GwyFileFuncInfo *func_info);
static void     gwy_file_type_info_set     (GwyContainer *data,
                                            const gchar *name,
                                            const gchar *filename_sys);
static FileTypeInfo* gwy_file_type_info_get(GwyContainer *data,
                                            gboolean do_create);
static void    gwy_file_container_finalized(gpointer userdata,
                                            GObject *deceased_data);

static GHashTable *file_funcs = NULL;
static GList *container_list = NULL;
static GPtrArray *call_stack = NULL;

/**
 * gwy_file_func_register:
 * @name: Name of function to register.  It should be a valid identifier and
 *        if a module registers only one function, module and function names
 *        should be the same.
 * @description: File type description (will be used in file type selectors).
 * @detect: Detection function.  It may be %NULL, files of such a type can
 *          can be then loaded and saved only on explict user request.
 * @load: File load/import function.
 * @save: File save function.
 * @export_: File export function.
 *
 * Registered a file function.
 *
 * At least one of @load, @save, and @export_ must be non-%NULL.  See
 * #GwyFileOperationType for differences between save and export.
 *
 * Note: the string arguments are not copied as modules are not expected to
 * vanish.  If they are constructed (non-constant) strings, do not free them.
 * Should modules ever become unloadable they will get chance to clean-up.
 *
 * Returns: Normally %TRUE; %FALSE on failure.
 **/
gboolean
gwy_file_func_register(const gchar *name,
                       const gchar *description,
                       GwyFileDetectFunc detect,
                       GwyFileLoadFunc load,
                       GwyFileSaveFunc save,
                       GwyFileSaveFunc export_)
{
    GwyFileFuncInfo *func_info;

    g_return_val_if_fail(name, FALSE);
    g_return_val_if_fail(load || save || export_, FALSE);
    g_return_val_if_fail(description, FALSE);
    gwy_debug("name = %s, desc = %s, detect = %p, "
              "load = %p, save = %p, export = %p",
              name, description, detect, load, save, export_);

    if (!file_funcs) {
        gwy_debug("Initializing...");
        file_funcs = g_hash_table_new_full(g_str_hash, g_str_equal,
                                           NULL, &g_free);
        call_stack = g_ptr_array_new();
    }

    if (!gwy_strisident(name, "_-", NULL))
        g_warning("Function name `%s' is not a valid identifier. "
                  "It may be rejected in future.", name);
    if (g_hash_table_lookup(file_funcs, name)) {
        g_warning("Duplicate function %s, keeping only first", name);
        return FALSE;
    }

    func_info = g_new0(GwyFileFuncInfo, 1);
    func_info->name = name;
    func_info->description = description;
    func_info->detect = detect;
    func_info->load = load;
    func_info->save = save;
    func_info->export_ = export_;
    func_info->is_detectable = !!func_info->detect;

    g_hash_table_insert(file_funcs, (gpointer)func_info->name, func_info);
    if (!_gwy_module_add_registered_function(GWY_MODULE_PREFIX_FILE, name)) {
        g_hash_table_remove(file_funcs, func_info->name);
        return FALSE;
    }

    return TRUE;
}

/**
 * gwy_file_func_run_detect:
 * @name: A file type function name.
 * @filename: A file name to detect.
 * @only_name: Whether to use only file name for a guess, or try to actually
 *             access the file.
 *
 * Runs a file type detection function identified by @name.
 *
 * Value of @only_name should be %TRUE if the file doesn't exist (is to be
 * written) so its contents can't be used for file type detection.
 *
 * This is a low-level function, consider using gwy_file_detect() if you
 * simply want to detect a file type.
 *
 * Returns: An integer score expressing the likehood of the file being
 *          loadable as this type. A basic scale is 20 for a good extension,
 *          100 for good magic header, more for more thorough tests.
 **/
gint
gwy_file_func_run_detect(const gchar *name,
                         const gchar *filename,
                         gboolean only_name)
{
    GwyFileFuncInfo *func_info;
    GwyFileDetectInfo fileinfo;
    gint score = 0;

    g_return_val_if_fail(filename, 0);
    func_info = g_hash_table_lookup(file_funcs, name);
    g_return_val_if_fail(func_info, 0);
    if (!func_info->detect)
        return 0;

    fileinfo.name = filename;
    /* File must exist if not only_name */
    if (gwy_file_detect_fill_info(&fileinfo, only_name)) {
        score = func_info->detect(&fileinfo, only_name, name);
        gwy_file_detect_free_info(&fileinfo);
    }

    return score;
}

/**
 * gwy_file_func_run_load:
 * @name: A file load function name.
 * @filename: A file name to load data from.
 * @mode: Run mode.
 * @error: Return location for a #GError (or %NULL).
 *
 * Runs a file load function identified by @name.
 *
 * This is a low-level function, consider using gwy_file_load() if you
 * simply want to load a file.
 *
 * Returns: A new #GwyContainer with data from @filename, or %NULL.
 **/
GwyContainer*
gwy_file_func_run_load(const gchar *name,
                       const gchar *filename,
                       GwyRunType mode,
                       GError **error)
{
    GwyFileFuncInfo *func_info;
    GwyContainer *data;

    g_return_val_if_fail(!error || !*error, NULL);
    g_return_val_if_fail(filename, NULL);
    func_info = g_hash_table_lookup(file_funcs, name);
    g_return_val_if_fail(func_info, NULL);
    g_return_val_if_fail(func_info->load, NULL);

    g_ptr_array_add(call_stack, func_info);
    data = func_info->load(filename, mode, error, name);
    if (data)
        gwy_file_type_info_set(data, name, filename);

    g_return_val_if_fail(call_stack->len, data);
    g_ptr_array_set_size(call_stack, call_stack->len-1);

    return data;
}

/**
 * gwy_file_func_run_save:
 * @name: A file save function name.
 * @data: A #GwyContainer to save.
 * @filename: A file name to save @data as.
 * @mode: Run mode.
 * @error: Return location for a #GError (or %NULL).
 *
 * Runs a file save function identified by @name.
 *
 * It guarantees the container lifetime spans through the actual file saving,
 * so the module function doesn't have to care about it.
 *
 * This is a low-level function, consider using gwy_file_save() if you
 * simply want to save a file.
 *
 * Returns: %TRUE if file save succeeded, %FALSE otherwise.
 **/
gboolean
gwy_file_func_run_save(const gchar *name,
                       GwyContainer *data,
                       const gchar *filename,
                       GwyRunType mode,
                       GError **error)
{
    GwyFileFuncInfo *func_info;
    gboolean status;

    g_return_val_if_fail(!error || !*error, FALSE);
    g_return_val_if_fail(filename, FALSE);
    g_return_val_if_fail(GWY_IS_CONTAINER(data), FALSE);
    func_info = g_hash_table_lookup(file_funcs, name);
    g_return_val_if_fail(func_info, FALSE);
    g_return_val_if_fail(func_info->save, FALSE);

    g_object_ref(data);
    g_ptr_array_add(call_stack, func_info);
    status = func_info->save(data, filename, mode, error, name);
    if (status)
        gwy_file_type_info_set(data, name, filename);
    g_object_unref(data);

    g_return_val_if_fail(call_stack->len, status);
    g_ptr_array_set_size(call_stack, call_stack->len-1);

    return status;
}

/**
 * gwy_file_func_run_export:
 * @name: A file save function name.
 * @data: A #GwyContainer to save.
 * @filename: A file name to save @data as.
 * @mode: Run mode.
 * @error: Return location for a #GError (or %NULL).
 *
 * Runs a file export function identified by @name.
 *
 * It guarantees the container lifetime spans through the actual file saving,
 * so the module function doesn't have to care about it.
 *
 * This is a low-level function, consider using gwy_file_save() if you
 * simply want to save a file.
 *
 * Returns: %TRUE if file save succeeded, %FALSE otherwise.
 **/
gboolean
gwy_file_func_run_export(const gchar *name,
                         GwyContainer *data,
                         const gchar *filename,
                         GwyRunType mode,
                         GError **error)
{
    GwyFileFuncInfo *func_info;
    gboolean status;

    g_return_val_if_fail(!error || !*error, FALSE);
    g_return_val_if_fail(filename, FALSE);
    g_return_val_if_fail(GWY_IS_CONTAINER(data), FALSE);
    func_info = g_hash_table_lookup(file_funcs, name);
    g_return_val_if_fail(func_info, FALSE);
    g_return_val_if_fail(func_info->export_, FALSE);

    g_object_ref(data);
    g_ptr_array_add(call_stack, func_info);
    status = func_info->export_(data, filename, mode, error, name);
    g_object_unref(data);

    g_return_val_if_fail(call_stack->len, status);
    g_ptr_array_set_size(call_stack, call_stack->len-1);

    return status;
}

static void
file_detect_max_score_cb(const gchar *key,
                         GwyFileFuncInfo *func_info,
                         FileDetectData *ddata)
{
    gint score;

    g_assert(gwy_strequal(key, func_info->name));

    if (!func_info->detect)
        return;
    if ((ddata->mode & GWY_FILE_OPERATION_LOAD) && !func_info->load)
        return;
    if ((ddata->mode & GWY_FILE_OPERATION_SAVE) && !func_info->save)
        return;
    if ((ddata->mode & GWY_FILE_OPERATION_EXPORT) && !func_info->export_)
        return;

    score = func_info->detect(ddata->fileinfo, ddata->only_name,
                                   func_info->name);
    if (score > ddata->score) {
        ddata->winner = func_info->name;
        ddata->score = score;
    }
}

/**
 * gwy_file_detect:
 * @filename: A file name to detect type of.
 * @only_name: Whether to use only file name for a guess, or try to actually
 *             access the file.
 * @operations: The file operations the file type must support (it must
 *              support all of them to be considered).
 *
 * Detects the type of a file.
 *
 * Returns: The type name (i.e., the same name as passed to
 *          e.g. gwy_file_func_run_load()) of most probable type of @filename,
 *          or %NULL if there's no probable one.
 **/
const gchar*
gwy_file_detect(const gchar *filename,
                gboolean only_name,
                GwyFileOperationType operations)
{
    return gwy_file_detect_with_score(filename, only_name, operations, NULL);
}

/**
 * gwy_file_detect_with_score:
 * @filename: A file name to detect type of.
 * @only_name: Whether to use only file name for a guess, or try to actually
 * @operations: The file operations the file type must support (it must
 * @score: Location to store the maximum score (corresponding to the returned
 *         type) to.
 *
 * Detects the type of a file and gives the score.
 *
 * Returns: The type name (i.e., the same name as passed to
 *          e.g. gwy_file_func_run_load()) of most probable type of @filename,
 *          or %NULL if there's no probable one.
 *
 * Since: 2.1
 **/
const gchar*
gwy_file_detect_with_score(const gchar *filename,
                           gboolean only_name,
                           GwyFileOperationType operations,
                           gint *score)
{
    FileDetectData ddata;
    GwyFileDetectInfo fileinfo;

    if (!file_funcs)
        return NULL;

    fileinfo.name = filename;
    /* File must exist if not only_name */
    if (!gwy_file_detect_fill_info(&fileinfo, only_name))
        return NULL;

    ddata.fileinfo = &fileinfo;
    ddata.winner = NULL;
    ddata.score = 0;
    ddata.only_name = only_name;
    ddata.mode = operations;
    g_hash_table_foreach(file_funcs, (GHFunc)file_detect_max_score_cb, &ddata);
    gwy_file_detect_free_info(&fileinfo);

    if (score)
        *score = ddata.score;
    return ddata.score ? ddata.winner : NULL;
}

static gboolean
gwy_file_detect_fill_info(GwyFileDetectInfo *fileinfo,
                          gboolean only_name)
{
    GStatBuf st;
    FILE *fh;

    g_return_val_if_fail(fileinfo && fileinfo->name, FALSE);

    /* FIXME: What if it isn't ASCII-compatible? */
    fileinfo->name_lowercase = g_ascii_strdown(fileinfo->name, -1);
    fileinfo->file_size = 0;
    fileinfo->buffer_len = 0;
    fileinfo->head = NULL;
    fileinfo->tail = NULL;
    if (only_name)
        return TRUE;

    if (g_stat(fileinfo->name, &st) != 0) {
        gwy_file_detect_free_info(fileinfo);
        return FALSE;
    }
    fileinfo->file_size = st.st_size;
    if (!fileinfo->file_size) {
        gwy_file_detect_free_info(fileinfo);
        return FALSE;
    }

    if (!(fh = gwy_fopen(fileinfo->name, "rb"))) {
        gwy_file_detect_free_info(fileinfo);
        return FALSE;
    }

    fileinfo->buffer_len = MIN(fileinfo->file_size + 1,
                               GWY_FILE_DETECT_BUFFER_SIZE);
    fileinfo->head = g_new0(guchar, 2*fileinfo->buffer_len);
    fileinfo->tail = fileinfo->head + fileinfo->buffer_len;
    if (fread((gchar*)fileinfo->head, fileinfo->buffer_len - 1, 1, fh) < 1
        || fseek(fh, 1-(gint)fileinfo->buffer_len, SEEK_END) != 0
        || fread((gchar*)fileinfo->tail, fileinfo->buffer_len - 1, 1, fh) < 1) {
        fclose(fh);
        gwy_file_detect_free_info(fileinfo);
        return FALSE;
    }

    fclose(fh);
    ((gchar*)fileinfo->head)[fileinfo->buffer_len - 1] = '\0';
    ((gchar*)fileinfo->tail)[fileinfo->buffer_len - 1] = '\0';

    return TRUE;
}

static void
gwy_file_detect_free_info(GwyFileDetectInfo *fileinfo)
{
    g_free((gpointer)fileinfo->name_lowercase);
    g_free((gpointer)fileinfo->head);
    fileinfo->head = NULL;
    fileinfo->tail = NULL;
    fileinfo->name_lowercase = NULL;
    fileinfo->buffer_len = 0;
}

/**
 * gwy_file_load:
 * @filename: A file name to load data from, in GLib encoding.
 * @mode: Run mode.
 * @error: Return location for a #GError (or %NULL).
 *
 * Loads a data file, autodetecting its type.
 *
 * Returns: A new #GwyContainer with data from @filename, or %NULL.
 **/
GwyContainer*
gwy_file_load(const gchar *filename,
              GwyRunType mode,
              GError **error)
{
    return gwy_file_load_with_func(filename, mode, NULL, error);
}

/**
 * gwy_file_load_with_func:
 * @filename: A file name to load data from, in GLib encoding.
 * @mode: Run mode.
 * @name: Location to store the name of file load function used to load the
 *        file, or %NULL.  If an error occurs outside the module, e.g. failure
 *        to recognise the file type, %NULL is stored to @name.
 * @error: Return location for a #GError (or %NULL).
 *
 * Loads a data file, autodetecting its type.
 *
 * Returns: A new #GwyContainer with data from @filename, or %NULL.
 *
 * Since: 2.25
 **/
GwyContainer*
gwy_file_load_with_func(const gchar *filename,
                        GwyRunType mode,
                        const gchar **name,
                        GError **error)
{
    const gchar *winner;
    FILE *fh;

    if (name)
        *name = NULL;

    g_return_val_if_fail(filename, NULL);

    /* When the file does not exist (for instance), we would get a correct but
     * very unheplful message that no module can load such a file. */
    if (!(fh = gwy_fopen(filename, "rb"))) {
        g_set_error(error, GWY_MODULE_FILE_ERROR, GWY_MODULE_FILE_ERROR_IO,
                    _("Cannot open file for reading: %s."), g_strerror(errno));
        return NULL;
    }
    fclose(fh);

    winner = gwy_file_detect(filename, FALSE, GWY_FILE_OPERATION_LOAD);
    if (!winner) {
        g_set_error(error, GWY_MODULE_FILE_ERROR,
                    GWY_MODULE_FILE_ERROR_UNIMPLEMENTED,
                    _("No module can load this file type."));
        return NULL;
    }
    if (name)
        *name = winner;

    return gwy_file_func_run_load(winner, filename, mode, error);
}

/**
 * gwy_file_save:
 * @data: A #GwyContainer to save.
 * @filename: A file name to save the data as, in GLib encoding.
 * @mode: Run mode.
 * @error: Return location for a #GError (or %NULL).
 *
 * Saves a data file, deciding to save as what type from the file name.
 *
 * It tries to find a module implementing %GWY_FILE_OPERATION_SAVE first, when
 * it does not succeed, it falls back to %GWY_FILE_OPERATION_EXPORT.
 *
 * Returns: The save operation that was actually realized on success, zero
 *          on failure.
 **/
GwyFileOperationType
gwy_file_save(GwyContainer *data,
              const gchar *filename,
              GwyRunType mode,
              GError **error)
{
    return gwy_file_save_with_func(data, filename, mode, NULL, error);
}

/**
 * gwy_file_save_with_func:
 * @data: A #GwyContainer to save.
 * @filename: A file name to save the data as, in GLib encoding.
 * @mode: Run mode.
 * @name: Location to store the name of file load function used to save the
 *        file, or %NULL.  If an error occurs outside the module, e.g. failure
 *        to recognise the file type, %NULL is stored to @name.
 * @error: Return location for a #GError (or %NULL).
 *
 * Saves a data file, deciding to save as what type from the file name.
 *
 * It tries to find a module implementing %GWY_FILE_OPERATION_SAVE first, when
 * it does not succeed, it falls back to %GWY_FILE_OPERATION_EXPORT.
 *
 * Returns: The save operation that was actually realized on success, zero
 *          on failure.
 *
 * Since: 2.25
 **/
GwyFileOperationType
gwy_file_save_with_func(GwyContainer *data,
                        const gchar *filename,
                        GwyRunType mode,
                        const gchar **name,
                        GError **error)
{
    FileDetectData ddata;
    GwyFileDetectInfo fileinfo;

    if (name)
        *name = NULL;

    if (!file_funcs)
        goto gwy_file_save_fail;

    fileinfo.name = filename;
    gwy_file_detect_fill_info(&fileinfo, TRUE);

    ddata.fileinfo = &fileinfo;
    ddata.winner = NULL;
    ddata.score = 0;
    ddata.only_name = TRUE;
    ddata.mode = GWY_FILE_OPERATION_SAVE;
    g_hash_table_foreach(file_funcs, (GHFunc)file_detect_max_score_cb, &ddata);

    if (ddata.winner) {
        if (name)
            *name = ddata.winner;

        gwy_file_detect_free_info(&fileinfo);
        if (gwy_file_func_run_save(ddata.winner,
                                   data, filename, mode, error))
            return ddata.mode;
        return 0;
    }

    ddata.mode = GWY_FILE_OPERATION_EXPORT;
    g_hash_table_foreach(file_funcs, (GHFunc)file_detect_max_score_cb, &ddata);
    gwy_file_detect_free_info(&fileinfo);

    if (ddata.winner) {
        if (name)
            *name = ddata.winner;

        if (gwy_file_func_run_export(ddata.winner,
                                     data, filename, mode, error))
            return ddata.mode;
        return 0;
    }

gwy_file_save_fail:
    g_set_error(error, GWY_MODULE_FILE_ERROR,
                GWY_MODULE_FILE_ERROR_UNIMPLEMENTED,
                _("No module can save to this file type."));

    return 0;
}

static void
gwy_file_func_user_cb(gpointer key,
                      G_GNUC_UNUSED gpointer value,
                      gpointer user_data)
{
    FuncForeachData *ffd = (FuncForeachData*)user_data;

    ffd->function(key, ffd->user_data);
}

/**
 * gwy_file_func_foreach:
 * @function: Function to run for each file function.  It will get function
 *            name (constant string owned by module system) as its first
 *            argument, @user_data as the second argument.
 * @user_data: Data to pass to @function.
 *
 * Calls a function for each file function.
 **/
void
gwy_file_func_foreach(GFunc function,
                      gpointer user_data)
{
    FuncForeachData ffd;

    if (!file_funcs)
        return;

    ffd.user_data = user_data;
    ffd.function = function;
    g_hash_table_foreach(file_funcs, gwy_file_func_user_cb, &ffd);
}

/**
 * gwy_file_func_exists:
 * @name: File type function name.
 *
 * Checks whether a file type function exists.
 *
 * Returns: %TRUE if function @name exists, %FALSE otherwise.
 **/
gboolean
gwy_file_func_exists(const gchar *name)
{
    return file_funcs && g_hash_table_lookup(file_funcs, name);
}

/**
 * gwy_file_func_get_operations:
 * @name: File type function name.
 *
 * Returns operations supported by a file type function.
 *
 * Returns: The file operation bit mask, zero if @name does not exist.
 **/
GwyFileOperationType
gwy_file_func_get_operations(const gchar *name)
{
    GwyFileFuncInfo *func_info;

    g_return_val_if_fail(file_funcs, 0);
    func_info = g_hash_table_lookup(file_funcs, name);
    g_return_val_if_fail(func_info, 0);

    return get_operations(func_info);
}

static GwyFileOperationType
get_operations(const GwyFileFuncInfo *func_info)
{
    GwyFileOperationType capable = 0;

    if (!func_info)
        return capable;

    capable |= func_info->load ? GWY_FILE_OPERATION_LOAD : 0;
    capable |= func_info->save ? GWY_FILE_OPERATION_SAVE : 0;
    capable |= func_info->export_ ? GWY_FILE_OPERATION_EXPORT : 0;
    capable |= func_info->detect ? GWY_FILE_OPERATION_DETECT : 0;

    return capable;
}

/**
 * gwy_file_func_get_description:
 * @name: File type function name.
 *
 * Gets file function description.
 *
 * That is, the @description argument of gwy_file_func_register() .
 *
 * Returns: File function description, as a string owned by module loader.
 **/
const gchar*
gwy_file_func_get_description(const gchar *name)
{
    GwyFileFuncInfo *func_info;

    g_return_val_if_fail(file_funcs, NULL);
    func_info = g_hash_table_lookup(file_funcs, name);
    g_return_val_if_fail(func_info, NULL);

    return func_info->description;
}

/**
 * gwy_file_func_get_is_detectable:
 * @name: File type function name.
 *
 * Returns if the file format is reasonably detectable.
 *
 * This is %TRUE for all file types that define a detection method unless they
 * explicitly call gwy_file_func_set_is_detectable() to set the file format
 * non-detectable in spite of providing a detection method.
 *
 * If files that can be actually loaded as a given type form a subset of files
 * that are detected as this format, which is normaly the case, it makes no
 * sense to let the user explicitly choose between these formats.  Hence,
 * detectable formats normally are not explicitly offered.
 *
 * Returns: If the file format is detectable.
 *
 * Since: 2.18
 **/
gboolean
gwy_file_func_get_is_detectable(const gchar *name)
{
    GwyFileFuncInfo *func_info;

    g_return_val_if_fail(file_funcs, FALSE);
    func_info = g_hash_table_lookup(file_funcs, name);
    g_return_val_if_fail(func_info, FALSE);

    return func_info->is_detectable;
}

/**
 * gwy_file_func_set_is_detectable:
 * @name: File type function name.
 * @is_detectable: %TRUE to define format as detectable, %FALSE as
 *                 non-detectable.
 *
 * Sets the detectability status of a file format.
 *
 * See gwy_file_func_get_is_detectable() for details.  The only rare case when
 * it makes sense to call this function is when a detection function is
 * provided for some reason, however, this function is not really able to
 * detect the format.  For instance, the fallback detection method of the
 * Gwyddion rawfile module.
 *
 * Since: 2.18
 **/
void
gwy_file_func_set_is_detectable(const gchar *name,
                                gboolean is_detectable)
{
    GwyFileFuncInfo *func_info;

    g_return_if_fail(file_funcs);
    func_info = g_hash_table_lookup(file_funcs, name);
    g_return_if_fail(func_info);
    func_info->is_detectable = is_detectable;
}

/**
 * gwy_file_func_current:
 *
 * Obtains the name of currently running file type function.
 *
 * Detection routines are not included, only load, save and export functions.
 *
 * If no file type function is currently running, %NULL is returned.
 *
 * If multiple nested functions are running (which is not usual but technically
 * possible), the innermost function name is returned.
 *
 * Returns: The name of currently running file type function or %NULL.
 *
 * Since: 2.38
 **/
const gchar*
gwy_file_func_current(void)
{
    GwyFileFuncInfo *func_info;

    if (!call_stack || !call_stack->len)
        return NULL;

    func_info = (GwyFileFuncInfo*)g_ptr_array_index(call_stack,
                                                     call_stack->len-1);
    return func_info->name;
}

gboolean
_gwy_file_func_remove(const gchar *name)
{
    gwy_debug("%s", name);
    if (!g_hash_table_remove(file_funcs, name)) {
        g_warning("Cannot remove function %s", name);
        return FALSE;
    }
    return TRUE;
}

/**
 * gwy_file_get_data_info:
 * @data: A #GwyContainer.
 * @name: Location to store file type (that is file function name) of @data,
 *        or %NULL.  The returned string is owned by module system.
 * @filename_sys: Location to store file name of @data (in GLib encoding), or
 *                %NULL.  The returned string is owned by module system and is
 *                valid only until the container is destroyed or saved again.
 *
 * Gets file information about a data.
 *
 * The information is set on two ocasions: file load and successful file save.
 * File export does not set it.
 *
 * Returns: %TRUE if information about @data was found and @name and/or
 *          @filename was filled.
 **/
gboolean
gwy_file_get_data_info(GwyContainer *data,
                       const gchar **name,
                       const gchar **filename_sys)
{
    FileTypeInfo *fti;

    fti = gwy_file_type_info_get(data, FALSE);
    if (fti) {
        if (name)
            *name = g_quark_to_string(fti->name);
        if (filename_sys)
            *filename_sys = fti->filename_sys;

        return TRUE;
    }

    if (name)
        *name = NULL;
    if (filename_sys)
        *filename_sys = NULL;

    return FALSE;
}

/**
 * gwy_file_get_filename_sys:
 * @data: A #GwyContainer.
 *
 * Gets the file name corresponding to a data container.
 *
 * The file name is set on two ocasions: file load and successful file save.
 * File export does not set it.
 *
 * Returns: File name of @data (in GLib encoding), or %NULL.  The returned
 *          string is owned by module system and is valid only until the
 *          container is destroyed or saved again.
 *
 * Since: 2.36
 **/
const gchar*
gwy_file_get_filename_sys(GwyContainer *data)
{
    FileTypeInfo *fti;

    g_return_val_if_fail(GWY_IS_CONTAINER(data), NULL);

    fti = gwy_file_type_info_get(data, FALSE);
    return fti ? fti->filename_sys : NULL;
}

/**
 * gwy_module_file_error_quark:
 *
 * Returns error domain for file module functions.
 *
 * See and use %GWY_MODULE_FILE_ERROR.
 *
 * Returns: The error domain.
 **/
GQuark
gwy_module_file_error_quark(void)
{
    static GQuark error_domain = 0;

    if (!error_domain)
        error_domain = g_quark_from_static_string("gwy-module-file-"
                                                  "error-quark");

    return error_domain;
}

static void
gwy_file_type_info_set(GwyContainer *data,
                       const gchar *name,
                       const gchar *filename_sys)
{
    FileTypeInfo *fti;

    fti = gwy_file_type_info_get(data, TRUE);
    fti->name = g_quark_from_string(name);
    /* filename_sys can be *physically* the same string as fti->filename_sys */
    if (fti->filename_sys == filename_sys)
        return;
    if (fti->filename_sys)
        g_free(fti->filename_sys);
    fti->filename_sys = g_strdup(filename_sys);
}

static FileTypeInfo*
gwy_file_type_info_get(GwyContainer *data,
                       gboolean do_create)
{
    FileTypeInfo *fti;
    GList *l;

    for (l = container_list; l; l = g_list_next(l)) {
        fti = (FileTypeInfo*)l->data;
        if ((gpointer)data == fti->container)
            break;
    }
    if (!l) {
        if (!do_create)
            return NULL;

        fti = g_new0(FileTypeInfo, 1);
        fti->container = data;
        container_list = g_list_prepend(container_list, fti);
        g_object_weak_ref(G_OBJECT(data), gwy_file_container_finalized, NULL);

        return fti;
    }

    /* 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 fti;
}

static void
gwy_file_container_finalized(G_GNUC_UNUSED gpointer userdata,
                             GObject *deceased_data)
{
    FileTypeInfo *fti;

    /* must not typecast with GWY_CONTAINER(), it doesn't exist any more */
    fti = gwy_file_type_info_get((GwyContainer*)deceased_data, FALSE);
    g_return_if_fail(fti);
    /* gwy_file_type_info_get() moves the item to list head */
    g_assert(fti == container_list->data);
    container_list = g_list_delete_link(container_list, container_list);
    g_free(fti->filename_sys);
    g_free(fti);
}

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

/**
 * SECTION:gwymodule-file
 * @title: gwymodule-file
 * @short_description: File loading and saving modules
 *
 * File modules implement file loading, saving and file type detection
 * functions.  Not all fuctions has to be implemented, a file module can be
 * import-only or export-only.  If it does not implement file type detection,
 * files of this type can be read/written only on user's explicite request.
 *
 * For file module writers, the only useful function here is the registration
 * function gwy_file_func_register() and the signatures of particular file
 * operations: #GwyFileDetectFunc, #GwyFileLoadFunc, and #GwyFileSaveFunc.
 **/

/**
 * GwyFileDetectFunc:
 * @fileinfo: Information about file to detect the filetype of,
 *            see #GwyFileDetectInfo.
 * @only_name: Whether the type should be guessed only from file name.
 * @name: Function name from as registered with gwy_file_func_register()
 *        (single-function modules can safely ignore this argument).
 *
 * The type of file type detection function.
 *
 * When called with %TRUE @only_name it should not try to access the file.
 *
 * Returns: An integer likehood score (see gwy_file_func_run_detect() for
 *          description).
 **/

/**
 * GwyFileLoadFunc:
 * @filename: A file name to load data from.
 * @mode: Run mode, this is either @GWY_RUN_NONINTERACTIVE
 *        or @GWY_RUN_INTERACTIVE.
 * @error: Return location for a #GError (or %NULL).
 * @name: Function name from as registered with gwy_file_func_register()
 *        (single-function modules can safely ignore this argument).
 *
 * The type of file loading function.
 *
 * Returns: A newly created data container, or %NULL on failure.
 **/

/**
 * GwyFileSaveFunc:
 * @data: A #GwyContainer to save.
 * @filename: A file name to save @data as.
 * @mode: Run mode, this is either @GWY_RUN_NONINTERACTIVE
 *        or @GWY_RUN_INTERACTIVE.
 * @error: Return location for a #GError (or %NULL).
 * @name: Function name from as registered with gwy_file_func_register()
 *        (single-function modules can safely ignore this argument).
 *
 * The type of file saving function.
 *
 * Returns: %TRUE if file save succeeded, %FALSE otherwise.
 **/

/**
 * GwyFileOperationType:
 * @GWY_FILE_OPERATION_DETECT: Posibility to detect files are of this file type,
 * @GWY_FILE_OPERATION_LOAD: Posibility to load files of this type.
 * @GWY_FILE_OPERATION_SAVE: Posibility to save files of this type.
 * @GWY_FILE_OPERATION_EXPORT: Posibility to export files of this type.
 * @GWY_FILE_OPERATION_MASK: The mask for all the flags.
 *
 * File type function file operations (capabilities).
 *
 * The difference between save and export is that save is supposed to create
 * a file containing fairly complete representation of the container, while
 * export is the possibility to write some information to given file type.
 * Generally only native file format module implements
 * %GWY_FILE_OPERATION_SAVE, all others implement %GWY_FILE_OPERATION_EXPORT.
 **/

/**
 * GwyFileDetectInfo:
 * @name: File name, in GLib filename encoding.
 * @name_lowercase: File name in lowercase (for eventual case-insensitive
 *                  name check).
 * @file_size: File size in bytes.  Undefined if @only_name.
 * @buffer_len: The size of @head and @tail in bytes.  Normally it's
 *              @GWY_FILE_DETECT_BUFFER_SIZE except when file is shorter than
 *              that.  Undefined if @only_name.
 * @head: Initial part of file.  Undefined if @only_name.
 * @tail: Final part of file.  Undefined if @only_name.
 *
 * File detection data for #GwyFileDetectFunc.
 *
 * It contains the common information file type detection routines need to
 * obtain.  It is shared between file detection functions and they must not
 * modify its contents.  Some fields are set only when the detection routines
 * are to check the file contents, these are marked `Undefined if @only_name'.
 *
 * The @head and @tail buffers are always nul-terminated and thus safely usable
 * with string functions.  When file is shorter than
 * @GWY_FILE_DETECT_BUFFER_SIZE bytes, <literal>'\0'</literal> is appended
 * to the end (therefore @buffer_len = @file_size + 1), otherwise the last
 * byte is overwritten with <literal>'\0'</literal>.  In either case the
 * last byte of @head and @tail cannot be assumed to be identical as in
 * the file (or being a part of the file at all).
 **/

/**
 * GWY_FILE_DETECT_BUFFER_SIZE:
 *
 * The size of #GwyFileDetectInfo buffer for initial part of file.  It should
 * be enough for any normal kind of magic header test.
 **/

/**
 * GWY_MODULE_FILE_ERROR:
 *
 * Error domain for file module operations.  Errors in this domain will be from
 * the #GwyModuleFileError enumeration. See #GError for information on
 * error domains.
 **/

/**
 * GwyModuleFileError:
 * @GWY_MODULE_FILE_ERROR_CANCELED: Interactive operation was cancelled by
 *                                  user.  (Since 2.45)
 * @GWY_MODULE_FILE_ERROR_CANCELLED: Alias for %GWY_MODULE_FILE_ERROR_CANCELED.
 * @GWY_MODULE_FILE_ERROR_UNIMPLEMENTED: No module implements requested
 *                                       operation.
 * @GWY_MODULE_FILE_ERROR_IO: Input/output error occured.
 * @GWY_MODULE_FILE_ERROR_DATA: Data is corrupted or in an unsupported format.
 * @GWY_MODULE_FILE_ERROR_INTERACTIVE: Operation requires user input, but
 *                                     it was run as %GWY_RUN_NONINTERACTIVE.
 * @GWY_MODULE_FILE_ERROR_SPECIFIC: Specific module errors that do not fall
 *                                  into any other category (such as the
 *                                  failure to initialize a library used to
 *                                  read the data).  Seldom used.
 *
 * Error codes returned by file module operations.
 *
 * File module functions can return any of these codes, except
 * @GWY_MODULE_FILE_ERROR_UNIMPLEMENTED which is normally only returned by
 * high-level functions gwy_file_load() and gwy_file_save().  Module functions
 * can return it only when they are called with a wrong function name.
 **/

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