File: gsffile.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 (430 lines) | stat: -rw-r--r-- 12,599 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
/*
 *  $Id: gsffile.c 22877 2020-07-10 15:31:35Z yeti-dn $
 *  Copyright (C) 2009-2020 David Necas (Yeti).
 *
 *  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.
 */

/**
 * [FILE-MAGIC-FREEDESKTOP]
 * <mime-type type="application/x-gsf-spm">
 *   <comment>Gwyddion Simple Field data</comment>
 *   <magic priority="80">
 *     <match type="string" offset="0" value="Gwyddion Simple Field 1.0\n"/>
 *   </magic>
 *   <glob pattern="*.gsf"/>
 *   <glob pattern="*.GSF"/>
 * </mime-type>
 **/

/**
 * [FILE-MAGIC-FILEMAGIC]
 * # Gwyddion simple field files (GSF), see http://gwyddion.net/
 * 0 string Gwyddion\ Simple\ Field\ 1.0\x0d\x0a Gwyddion simple field SPM data version 1.0
 **/

/**
 * [FILE-MAGIC-USERGUIDE]
 * Gwyddion Simple Field
 * .gsf
 * Read Export
 **/

#include "config.h"
#include <string.h>
#include <stdlib.h>

#include <glib/gstdio.h>
#include <libgwyddion/gwymacros.h>
#include <libgwyddion/gwymath.h>
#include <libgwyddion/gwyutils.h>
#include <libgwymodule/gwymodule-file.h>
#include <app/gwymoduleutils-file.h>
#include <app/data-browser.h>

#include "err.h"

#define MAGIC "Gwyddion Simple Field 1.0\n"
#define MAGIC_SIZE (sizeof(MAGIC)-1)
#define EXTENSION ".gsf"

static gboolean      module_register (void);
static gint          gsf_detect      (const GwyFileDetectInfo *fileinfo,
                                      gboolean only_name);
static GwyContainer* gsf_load        (const gchar *filename,
                                      GwyRunType mode,
                                      GError **error);
static gboolean      gsf_export      (GwyContainer *container,
                                      const gchar *filename,
                                      GwyRunType mode,
                                      GError **error);
static guint         read_pixel_size (GHashTable *hash,
                                      const gchar *key,
                                      GError **error);
static void          add_meta        (gpointer hkey,
                                      gpointer hvalue,
                                      gpointer user_data);
static gdouble       read_real_size  (GHashTable *hash,
                                      const gchar *key);
static gdouble       read_real_offset(GHashTable *hash,
                                      const gchar *key);
static void          append_num      (GString *str,
                                      const gchar *key,
                                      gdouble d);

static GwyModuleInfo module_info = {
    GWY_MODULE_ABI_VERSION,
    &module_register,
    N_("Reads and exports Gwyddion Simple Field files."),
    "Yeti <yeti@gwyddion.net>",
    "1.3",
    "David Nečas (Yeti)",
    "2010",
};

GWY_MODULE_QUERY2(module_info, gsffile)

static gboolean
module_register(void)
{
    gwy_file_func_register("gsffile",
                           N_("Gwyddion Simple Field (.gsf)"),
                           (GwyFileDetectFunc)&gsf_detect,
                           (GwyFileLoadFunc)&gsf_load,
                           NULL,
                           (GwyFileSaveFunc)&gsf_export);

    return TRUE;
}

static gint
gsf_detect(const GwyFileDetectInfo *fileinfo,
           gboolean only_name)
{
    if (only_name)
        return g_str_has_suffix(fileinfo->name_lowercase, EXTENSION) ? 15 : 0;

    if (fileinfo->file_size < MAGIC_SIZE
        || memcmp(fileinfo->head, MAGIC, MAGIC_SIZE) != 0)
        return 0;

    return 100;
}

static GwyContainer*
gsf_load(const gchar *filename,
         G_GNUC_UNUSED GwyRunType mode,
         GError **error)
{
    GwyContainer *container = NULL, *meta = NULL;
    GwyDataField *dfield = NULL, *mask;
    GwyTextHeaderParser parser;
    GwySIUnit *unit;
    guchar *p, *value, *buffer = NULL, *header = NULL;
    const guchar *datap;
    GHashTable *hash = NULL;
    gsize size, expected_size;
    GError *err = NULL;
    GQuark quark;
    gdouble xreal, yreal, xoff, yoff;
    guint i, xres, yres;
    gdouble *d;

    if (!gwy_file_get_contents(filename, &buffer, &size, &err)) {
        err_GET_FILE_CONTENTS(error, &err);
        return NULL;
    }

    if (size < MAGIC_SIZE || memcmp(buffer, MAGIC, MAGIC_SIZE) != 0) {
        err_FILE_TYPE(error, "Gwyddion Simple Field");
        goto fail;
    }

    p = buffer + MAGIC_SIZE;
    datap = memchr(p, '\0', size - (p - buffer));
    if (!datap) {
        err_TRUNCATED_HEADER(error);
        goto fail;
    }
    header = g_strdup(p);
    datap += 4 - ((datap - buffer) % 4);

    gwy_clear(&parser, 1);
    parser.key_value_separator = "=";
    if (!(hash = gwy_text_header_parse(header, &parser, NULL, NULL))) {
        g_propagate_error(error, err);
        goto fail;
    }

    xres = read_pixel_size(hash, "XRes", error);
    yres = read_pixel_size(hash, "YRes", error);
    if (!xres || !yres)
        goto fail;

    expected_size = (datap - buffer) + sizeof(gfloat)*xres*yres;
    if (err_SIZE_MISMATCH(error, expected_size, size, TRUE))
        goto fail;

    xreal = read_real_size(hash, "XReal");
    yreal = read_real_size(hash, "YReal");
    dfield = gwy_data_field_new(xres, yres, xreal, yreal, FALSE);

    xoff = read_real_offset(hash, "XOffset");
    yoff = read_real_offset(hash, "YOffset");
    gwy_data_field_set_xoffset(dfield, xoff);
    gwy_data_field_set_yoffset(dfield, yoff);

    value = g_hash_table_lookup(hash, "XYUnits");
    unit = gwy_si_unit_new(value);
    gwy_data_field_set_si_unit_xy(dfield, unit);
    g_object_unref(unit);

    value = g_hash_table_lookup(hash, "ZUnits");
    unit = gwy_si_unit_new(value);
    gwy_data_field_set_si_unit_z(dfield, unit);
    g_object_unref(unit);

    d = gwy_data_field_get_data(dfield);
    for (i = xres*yres; i; i--)
        *(d++) = gwy_get_gfloat_le(&datap);

    container = gwy_container_new();
    quark = gwy_app_get_data_key_for_id(0);
    gwy_container_set_object(container, quark, dfield);
    if ((mask = gwy_app_channel_mask_of_nans(dfield, TRUE))) {
        quark = gwy_app_get_mask_key_for_id(0);
        gwy_container_set_object(container, quark, mask);
        g_object_unref(mask);
    }
    g_object_unref(dfield);

    if ((value = g_hash_table_lookup(hash, "Title"))
        && g_utf8_validate(value, -1, NULL)) {
        quark = gwy_app_get_data_title_key_for_id(0);
        gwy_container_set_const_string(container, quark, value);
    }
    else
        gwy_app_channel_title_fall_back(container, 0);

    meta = gwy_container_new();
    g_hash_table_foreach(hash, add_meta, meta);
    if (gwy_container_get_n_items(meta)) {
        quark = gwy_app_get_data_meta_key_for_id(0);
        gwy_container_set_object(container, quark, meta);
    }
    g_object_unref(meta);

    gwy_file_channel_import_log_add(container, 0, NULL, filename);

fail:
    gwy_file_abandon_contents(buffer, size, NULL);
    if (header)
        g_free(header);
    if (hash)
        g_hash_table_destroy(hash);

    return container;
}

static void
add_meta(gpointer hkey, gpointer hvalue, gpointer user_data)
{
    if (gwy_stramong((gchar*)hkey,
                     "XRes", "YRes", "XReal", "YReal", "XOffset", "YOffset",
                     "XYUnits", "ZUnits", "Title",
                     NULL))
        return;

    gwy_container_set_string_by_name(GWY_CONTAINER(user_data),
                                     (gchar*)hkey, g_strdup((gchar*)hvalue));
}

static guint
read_pixel_size(GHashTable *hash,
                const gchar *key,
                GError **error)
{
    gchar *value;
    guint size;

    if (!(value = g_hash_table_lookup(hash, key))) {
        err_MISSING_FIELD(error, key);
        return 0;
    }
    size = atoi(g_hash_table_lookup(hash, key));
    if (err_DIMENSION(error, size))
       return 0;

    return size;
}

static gdouble
read_real_size(GHashTable *hash,
               const gchar *key)
{
    gchar *value;
    gdouble dim = 1.0;

    if ((value = g_hash_table_lookup(hash, key))) {
        dim = g_ascii_strtod(value, NULL);
        /* Use negated positive conditions to catch NaNs */
        if (!((dim = fabs(dim)) > 0)) {
            g_warning("%s is 0.0 or NaN, fixing to 1.0", key);
            dim = 1.0;
        }
    }
    return dim;
}

static gdouble
read_real_offset(GHashTable *hash,
                 const gchar *key)
{
    gchar *value;
    gdouble off = 0.0;

    if ((value = g_hash_table_lookup(hash, key))) {
        off = g_ascii_strtod(value, NULL);
        /* Catch NaNs */
        if (!(off == off)) {
            g_warning("%s is NaN, fixing to 0.0", key);
            off = 0.0;
        }
    }
    return off;
}

static gboolean
gsf_export(GwyContainer *container,
           const gchar *filename,
           G_GNUC_UNUSED GwyRunType mode,
           GError **error)
{
    static const gchar zeroes[4] = { 0, 0, 0, 0 };
    GString *header = NULL;
    gfloat *dfl = NULL;
    guint i, xres, yres, padding;
    gint id;
    GwyDataField *dfield;
    const gdouble *d;
    gdouble v;
    gchar *s;
    GwySIUnit *unit;
    FILE *fh;

    gwy_app_data_browser_get_current(GWY_APP_DATA_FIELD, &dfield,
                                     GWY_APP_DATA_FIELD_ID, &id,
                                     0);
    if (!dfield) {
        err_NO_CHANNEL_EXPORT(error);
        return FALSE;
    }

    if (!(fh = gwy_fopen(filename, "wb"))) {
        err_OPEN_WRITE(error);
        return FALSE;
    }

    xres = gwy_data_field_get_xres(dfield);
    yres = gwy_data_field_get_yres(dfield);

    header = g_string_new(MAGIC);
    g_string_append_printf(header, "XRes = %u\n", xres);
    g_string_append_printf(header, "YRes = %u\n", yres);
    append_num(header, "XReal", gwy_data_field_get_xreal(dfield));
    append_num(header, "YReal", gwy_data_field_get_yreal(dfield));
    if ((v = gwy_data_field_get_xoffset(dfield)))
        append_num(header, "XOffset", v);
    if ((v = gwy_data_field_get_yoffset(dfield)))
        append_num(header, "YOffset", v);

    unit = gwy_data_field_get_si_unit_xy(dfield);
    if (!gwy_si_unit_equal_string(unit, NULL)) {
        s = gwy_si_unit_get_string(unit, GWY_SI_UNIT_FORMAT_PLAIN);
        g_string_append_printf(header, "XYUnits = %s\n", s);
        g_free(s);
    }
    unit = gwy_data_field_get_si_unit_z(dfield);
    if (!gwy_si_unit_equal_string(unit, NULL)) {
        s = gwy_si_unit_get_string(unit, GWY_SI_UNIT_FORMAT_PLAIN);
        g_string_append_printf(header, "ZUnits = %s\n", s);
        g_free(s);
    }

    s = gwy_app_get_data_field_title(container, id);
    g_string_append_printf(header, "Title = %s\n", s);
    g_free(s);

    if (fwrite(header->str, 1, header->len, fh) != header->len) {
        err_WRITE(error);
        goto fail;
    }

    padding = 4 - (header->len % 4);
    if (fwrite(zeroes, 1, padding, fh) != padding) {
        err_WRITE(error);
        goto fail;
    }
    g_string_free(header, TRUE);
    header = NULL;

    dfl = g_new(gfloat, xres*yres);
    d = gwy_data_field_get_data_const(dfield);
    for (i = 0; i < xres*yres; i++) {
        union { guchar pp[4]; float f; } z;
        z.f = d[i];
#if (G_BYTE_ORDER == G_BIG_ENDIAN)
        GWY_SWAP(guchar, z.pp[0], z.pp[3]);
        GWY_SWAP(guchar, z.pp[1], z.pp[2]);
#endif
        dfl[i] = z.f;
    }

    if (fwrite(dfl, sizeof(gfloat), xres*yres, fh) != xres*yres) {
        err_WRITE(error);
        goto fail;
    }
    g_free(dfl);
    fclose(fh);

    return TRUE;

fail:
    if (fh)
        fclose(fh);
    g_unlink(filename);
    if (header)
        g_string_free(header, TRUE);
    g_free(dfl);

    return FALSE;
}

static void
append_num(GString *str,
           const gchar *key,
           gdouble d)
{
    gchar buf[32];

    g_string_append(str, key);
    g_string_append(str, " = ");
    g_ascii_formatd(buf, sizeof(buf), "%.14g", d);
    g_string_append(str, buf);
    g_string_append_c(str, '\n');
}

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