File: polydistort.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 (807 lines) | stat: -rw-r--r-- 28,106 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
/*
 *  $Id: polydistort.c 23556 2021-04-21 08:00:51Z yeti-dn $
 *  Copyright (C) 2007,2008 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 <gtk/gtk.h>
#include <libgwyddion/gwymacros.h>
#include <libgwyddion/gwymath.h>
#include <libgwymodule/gwymodule-process.h>
#include <libprocess/gwyprocesstypes.h>
#include <libprocess/stats.h>
#include <libprocess/correct.h>
#include <libgwydgets/gwyradiobuttons.h>
#include <libgwydgets/gwycombobox.h>
#include <libgwydgets/gwystock.h>
#include <app/gwymoduleutils.h>
#include <app/gwyapp.h>
#include "preview.h"

#define DISTORT_RUN_MODES (GWY_RUN_INTERACTIVE | GWY_RUN_IMMEDIATE)

enum {
    MAX_DEGREE   = 3,
    NCOEFF       = (MAX_DEGREE + 1)*(MAX_DEGREE + 1)
};

typedef enum {
    PREVIEW_TRANSFORMED = 0,
    PREVIEW_ORIGINAL  = 1,
    PREVIEW_LAST
} DistortPreviewType;

/* Data for this function. */
typedef struct {
    DistortPreviewType preview_type;
    GwyInterpolationType interp;
    GwyExteriorType exterior;
    gboolean update;
    gdouble *xcoeff;
    gdouble *ycoeff;
} DistortArgs;

typedef struct {
    GtkWidget *dialog;
    GtkWidget *view;
    GtkWidget *interp;
    GtkWidget *exterior;
    GtkWidget *update;
    GtkWidget **xcoeff;
    GtkWidget **ycoeff;
    GSList *preview_type;
    GwyContainer *mydata;
    GwyDataField *result;
    gboolean computed;
    gulong preview_id;
    DistortArgs *args;
} DistortControls;

static gboolean   module_register               (void);
static void       polydistort                   (GwyContainer *data,
                                                 GwyRunType run);
static void       distort_dialog                (DistortArgs *args,
                                                 GwyContainer *data,
                                                 GwyDataField *dfield,
                                                 GwyDataField *mfield,
                                                 GwyDataField *sfield,
                                                 gint id);
static GtkWidget* coeff_table_new               (GtkWidget **entry,
                                                 gpointer id,
                                                 DistortControls *controls);
static void       distort_fetch_coeff           (DistortControls *controls);
static void       interp_changed                (GtkComboBox *combo,
                                                 DistortControls *controls);
static void       exterior_changed              (GtkComboBox *combo,
                                                 DistortControls *controls);
static void       update_changed                (GtkToggleButton *check,
                                                 DistortControls *controls);
static void       run_noninteractive            (DistortArgs *args,
                                                 GwyContainer *data,
                                                 GwyDataField *dfield,
                                                 GwyDataField *mfield,
                                                 GwyDataField *sfield,
                                                 GwyDataField *result,
                                                 gint id);
static void       distort_dialog_update_controls(DistortControls *controls,
                                                 DistortArgs *args);
static void       distort_coeff_changed         (GtkEntry *entry,
                                                 DistortControls *controls);
static void       distort_invalidate            (DistortControls *controls);
static void       preview_type_changed          (GtkToggleButton *button,
                                                 DistortControls *controls);
static void       preview                       (DistortControls *controls,
                                                 DistortArgs *args);
static void       distort_do                    (DistortArgs *args,
                                                 GwyDataField *dfield,
                                                 GwyDataField *result);
static void       distort_load_args             (GwyContainer *container,
                                                 DistortArgs *args);
static void       distort_save_args             (GwyContainer *container,
                                                 DistortArgs *args);
static void       distort_sanitize_args         (DistortArgs *args);
static void       reset_coeffs                  (DistortArgs *args);

static const DistortArgs distort_defaults = {
    PREVIEW_TRANSFORMED,
    GWY_INTERPOLATION_BSPLINE,
    GWY_EXTERIOR_FIXED_VALUE,
    TRUE,
    NULL,
    NULL
};

static GwyModuleInfo module_info = {
    GWY_MODULE_ABI_VERSION,
    &module_register,
    N_("Applies polynomial distortion in the horizontal plane."),
    "Yeti <yeti@gwyddion.net>",
    "1.5",
    "David Nečas (Yeti) & Petr Klapetek",
    "2007",
};

GWY_MODULE_QUERY2(module_info, polydistort)

static gboolean
module_register(void)
{
    gwy_process_func_register("polydistort",
                              (GwyProcessFunc)&polydistort,
                              N_("/_Distortion/Pol_ynomial..."),
                              GWY_STOCK_POLY_DISTORT,
                              DISTORT_RUN_MODES,
                              GWY_MENU_FLAG_DATA,
                              N_("Applies polynomial distortion in the "
                                 "horizontal plane"));

    return TRUE;
}

static void
polydistort(GwyContainer *data, GwyRunType run)
{
    DistortArgs args;
    GwyDataField *dfield, *mfield, *sfield;
    gint id;

    g_return_if_fail(run & DISTORT_RUN_MODES);
    args.xcoeff = g_new(gdouble, NCOEFF);
    args.ycoeff = g_new(gdouble, NCOEFF);
    distort_load_args(gwy_app_settings_get(), &args);
    gwy_app_data_browser_get_current(GWY_APP_DATA_FIELD, &dfield,
                                     GWY_APP_MASK_FIELD, &mfield,
                                     GWY_APP_SHOW_FIELD, &sfield,
                                     GWY_APP_DATA_FIELD_ID, &id,
                                     0);
    g_return_if_fail(dfield);

    if (run == GWY_RUN_IMMEDIATE)
        run_noninteractive(&args, data, dfield, mfield, sfield, NULL, id);
    else
        distort_dialog(&args, data, dfield, mfield, sfield, id);

    g_free(args.xcoeff);
    g_free(args.ycoeff);
}

static void
distort_dialog(DistortArgs *args,
               GwyContainer *data,
               GwyDataField *dfield,
               GwyDataField *mfield,
               GwyDataField *sfield,
               gint id)
{
    GtkWidget *dialog, *table, *hbox, *label, *align;
    DistortControls controls;
    gint response;
    GSList *l;
    gint row;

    memset(&controls, 0, sizeof(DistortControls));
    controls.args = args;

    dialog = gtk_dialog_new_with_buttons(_("Distort by Polynomial"),
                                         NULL, 0, NULL);
    gtk_dialog_add_action_widget(GTK_DIALOG(dialog),
                                 gwy_stock_like_button_new(_("_Update"),
                                                           GTK_STOCK_EXECUTE),
                                 RESPONSE_PREVIEW);
    gtk_dialog_set_response_sensitive(GTK_DIALOG(dialog), RESPONSE_PREVIEW,
                                      !args->update);
    gtk_dialog_add_button(GTK_DIALOG(dialog), _("_Reset"), RESPONSE_RESET);
    gtk_dialog_add_button(GTK_DIALOG(dialog),
                          GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL);
    gtk_dialog_add_button(GTK_DIALOG(dialog),
                          GTK_STOCK_OK, GTK_RESPONSE_OK);
    gtk_dialog_set_default_response(GTK_DIALOG(dialog), GTK_RESPONSE_OK);
    gwy_help_add_to_proc_dialog(GTK_DIALOG(dialog), GWY_HELP_DEFAULT);
    controls.dialog = dialog;

    hbox = gtk_hbox_new(FALSE, 2);

    gtk_box_pack_start(GTK_BOX(GTK_DIALOG(dialog)->vbox), hbox,
                       FALSE, FALSE, 4);

    align = gtk_alignment_new(0.0, 0.0, 0.0, 0.0);
    gtk_box_pack_start(GTK_BOX(hbox), align, FALSE, FALSE, 4);

    controls.mydata = gwy_container_new();
    gwy_container_set_object_by_name(controls.mydata, "/0/data", dfield);
    gwy_app_sync_data_items(data, controls.mydata, id, 0, FALSE,
                            GWY_DATA_ITEM_PALETTE,
                            GWY_DATA_ITEM_MASK_COLOR,
                            GWY_DATA_ITEM_RANGE,
                            GWY_DATA_ITEM_REAL_SQUARE,
                            0);
    controls.view = gwy_create_preview(controls.mydata, 0, PREVIEW_SIZE, FALSE);
    g_object_unref(controls.mydata);
    gtk_container_add(GTK_CONTAINER(align), controls.view);

    table = gtk_table_new(7, 3, FALSE);
    gtk_table_set_row_spacings(GTK_TABLE(table), 2);
    gtk_table_set_col_spacings(GTK_TABLE(table), 6);
    gtk_container_set_border_width(GTK_CONTAINER(table), 4);
    gtk_box_pack_start(GTK_BOX(hbox), table, TRUE, TRUE, 4);
    row = 0;

    controls.interp
        = gwy_enum_combo_box_new(gwy_interpolation_type_get_enum(), -1,
                                 G_CALLBACK(interp_changed), &controls,
                                 args->interp, TRUE);
    gwy_table_attach_adjbar(table, row, _("_Interpolation type:"), NULL,
                            GTK_OBJECT(controls.interp),
                            GWY_HSCALE_WIDGET_NO_EXPAND);
    row++;

    controls.exterior
        = gwy_enum_combo_box_newl(G_CALLBACK(exterior_changed), &controls,
                                  args->exterior,
                                  _("Minimum"), GWY_EXTERIOR_FIXED_VALUE,
                                  gwy_sgettext("exterior|Border"),
                                  GWY_EXTERIOR_BORDER_EXTEND,
                                  gwy_sgettext("exterior|Mirror"),
                                  GWY_EXTERIOR_MIRROR_EXTEND,
                                  gwy_sgettext("exterior|Periodic"),
                                  GWY_EXTERIOR_PERIODIC,
                                  NULL);
    gwy_table_attach_adjbar(table, row, _("_Exterior type:"), NULL,
                            GTK_OBJECT(controls.exterior),
                            GWY_HSCALE_WIDGET_NO_EXPAND);
    gtk_table_set_row_spacing(GTK_TABLE(table), row, 8);
    row++;

    hbox = gtk_hbox_new(FALSE, 6);
    gtk_table_attach(GTK_TABLE(table), hbox,
                     0, 2, row, row+1, GTK_FILL, 0, 0, 0);
    gtk_table_set_row_spacing(GTK_TABLE(table), row, 8);
    row++;

    label = gtk_label_new(_("Preview:"));
    gtk_misc_set_alignment(GTK_MISC(label), 0.0, 0.5);
    gtk_box_pack_start(GTK_BOX(hbox), label, FALSE, FALSE, 0);

    controls.preview_type
        = gwy_radio_buttons_createl(G_CALLBACK(preview_type_changed), &controls,
                                    args->preview_type,
                                    _("Ori_ginal"), PREVIEW_ORIGINAL,
                                    _("_Transformed"), PREVIEW_TRANSFORMED,
                                    NULL);
    for (l = controls.preview_type; l; l = g_slist_next(l))
        gtk_box_pack_start(GTK_BOX(hbox), GTK_WIDGET(l->data), FALSE, FALSE, 0);

    gtk_table_attach(GTK_TABLE(table),
                     gwy_label_new_header(_("X Coefficients")),
                     0, 3, row, row+1, GTK_FILL, 0, 0, 0);
    row++;

    controls.xcoeff = g_new0(GtkWidget*, NCOEFF);
    g_signal_connect_swapped(dialog, "destroy",
                             G_CALLBACK(g_free), controls.xcoeff);
    gtk_table_attach(GTK_TABLE(table),
                     coeff_table_new(controls.xcoeff, (gpointer)"x", &controls),
                     0, 3, row, row+1, GTK_FILL, 0, 0, 0);
    gtk_table_set_row_spacing(GTK_TABLE(table), row, 8);
    row++;

    gtk_table_attach(GTK_TABLE(table),
                     gwy_label_new_header(_("Y Coefficients")),
                     0, 2, row, row+1, GTK_FILL, 0, 0, 0);
    row++;

    controls.ycoeff = g_new0(GtkWidget*, NCOEFF);
    g_signal_connect_swapped(dialog, "destroy",
                             G_CALLBACK(g_free), controls.ycoeff);
    gtk_table_attach(GTK_TABLE(table),
                     coeff_table_new(controls.ycoeff, (gpointer)"y", &controls),
                     0, 3, row, row+1, GTK_FILL, 0, 0, 0);
    gtk_table_set_row_spacing(GTK_TABLE(table), row, 8);
    row++;

    controls.update = gtk_check_button_new_with_mnemonic(_("I_nstant updates"));
    gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(controls.update),
                                 args->update);
    gtk_table_attach(GTK_TABLE(table), controls.update,
                     0, 2, row, row+1, GTK_FILL, 0, 0, 0);
    g_signal_connect(controls.update, "toggled",
                     G_CALLBACK(update_changed), &controls);
    row++;

    distort_dialog_update_controls(&controls, args);
    /* Set up initial layer keys properly */
    preview_type_changed(NULL, &controls);
    distort_invalidate(&controls);

    gtk_widget_show_all(dialog);
    do {
        response = gtk_dialog_run(GTK_DIALOG(dialog));
        distort_fetch_coeff(&controls);
        switch (response) {
            case GTK_RESPONSE_CANCEL:
            case GTK_RESPONSE_DELETE_EVENT:
            gtk_widget_destroy(dialog);
            GWY_OBJECT_UNREF(controls.result);
            case GTK_RESPONSE_NONE:
            distort_save_args(gwy_app_settings_get(), args);
            return;
            break;

            case GTK_RESPONSE_OK:
            break;

            case RESPONSE_RESET:
            args->interp = distort_defaults.interp;
            args->exterior = distort_defaults.exterior;
            reset_coeffs(args);
            distort_dialog_update_controls(&controls, args);
            distort_invalidate(&controls);
            break;

            case RESPONSE_PREVIEW:
            preview(&controls, args);
            break;

            default:
            g_assert_not_reached();
            break;
        }
    } while (response != GTK_RESPONSE_OK);

    if (controls.preview_id) {
        g_source_remove(controls.preview_id);
        controls.preview_id = 0;
    }
    gtk_widget_destroy(dialog);
    distort_save_args(gwy_app_settings_get(), args);

    if (controls.computed)
        run_noninteractive(args, data, dfield, mfield, sfield,
                           controls.result, id);
    else {
        GWY_OBJECT_UNREF(controls.result);
        run_noninteractive(args, data, dfield, mfield, sfield, NULL, id);
    }
}

static GtkWidget*
coeff_table_new(GtkWidget **entry,
                gpointer id,
                DistortControls *controls)
{
    GtkWidget *widget, *label;
    GtkTable *table;
    gchar buf[24];
    gint i, j, k;

    widget = gtk_table_new(MAX_DEGREE + 2, MAX_DEGREE + 2, FALSE);
    table = GTK_TABLE(widget);
    gtk_table_set_row_spacings(table, 2);
    gtk_table_set_col_spacings(table, 6);

    for (i = 0; i < MAX_DEGREE + 1; i++) {
        for (j = 0; j < MAX_DEGREE + 1; j++) {
            if (i + j > MAX_DEGREE)
                continue;

            k = i*(MAX_DEGREE + 1) + j;
            entry[k] = gtk_entry_new();
            gtk_entry_set_width_chars(GTK_ENTRY(entry[k]), 6);
            gtk_table_attach(table, entry[k], j+1, j+2, i+1, i+2, 0, 0, 0, 0);
            g_object_set_data(G_OBJECT(entry[k]), "y", GINT_TO_POINTER(i));
            g_object_set_data(G_OBJECT(entry[k]), "x", GINT_TO_POINTER(j));
            g_object_set_data(G_OBJECT(entry[k]), "id", id);
            g_signal_connect(entry[k], "activate",
                             G_CALLBACK(distort_coeff_changed), controls);
            gwy_widget_set_activate_on_unfocus(entry[k], TRUE);
        }
    }

    for (i = 0; i < MAX_DEGREE + 1; i++) {
        label = gtk_label_new(NULL);
        if (i == 0)
            strcpy(buf, "1");
        else if (i == 1)
            strcpy(buf, "y");
        else
            g_snprintf(buf, sizeof(buf), "y<sup>%d</sup>", i);
        gtk_label_set_markup(GTK_LABEL(label), buf);
        gtk_table_attach(table, label, 0, 1, i+1, i+2, 0, 0, 0, 0);
    }

    for (j = 0; j < MAX_DEGREE + 1; j++) {
        label = gtk_label_new(NULL);
        if (j == 0)
            strcpy(buf, "1");
        else if (j == 1)
            strcpy(buf, "x");
        else
            g_snprintf(buf, sizeof(buf), "x<sup>%d</sup>", j);
        gtk_label_set_markup(GTK_LABEL(label), buf);
        gtk_table_attach(table, label, j+1, j+2, 0, 1, 0, 0, 0, 0);
    }

    return widget;
}

static void
distort_fetch_coeff(DistortControls *controls)
{
    GtkWidget *entry;

    entry = gtk_window_get_focus(GTK_WINDOW(controls->dialog));
    if (entry
        && GTK_IS_ENTRY(entry)
        && g_object_get_data(G_OBJECT(entry), "id"))
        distort_coeff_changed(GTK_ENTRY(entry), controls);
}

static void
interp_changed(GtkComboBox *combo,
               DistortControls *controls)
{
    controls->args->interp = gwy_enum_combo_box_get_active(combo);
    distort_invalidate(controls);
}

static void
exterior_changed(GtkComboBox *combo,
                 DistortControls *controls)
{
    controls->args->exterior = gwy_enum_combo_box_get_active(combo);
    distort_invalidate(controls);
}

static void
update_changed(GtkToggleButton *check,
               DistortControls *controls)
{
    controls->args->update = gtk_toggle_button_get_active(check);
    gtk_dialog_set_response_sensitive(GTK_DIALOG(controls->dialog),
                                      RESPONSE_PREVIEW,
                                      !controls->args->update);
    if (controls->args->update)
        preview(controls, controls->args);
}

/* XXX: Eats result */
static void
run_noninteractive(DistortArgs *args,
                   GwyContainer *data,
                   GwyDataField *dfield,
                   GwyDataField *mfield,
                   GwyDataField *sfield,
                   GwyDataField *result,
                   gint id)
{
    gint newid;

    if (!result) {
        result = gwy_data_field_new_alike(dfield, FALSE);
        distort_do(args, dfield, result);
    }

    newid = gwy_app_data_browser_add_data_field(result, data, TRUE);
    gwy_app_set_data_field_title(data, newid, _("Distorted"));
    gwy_app_sync_data_items(data, data, id, newid, FALSE,
                            GWY_DATA_ITEM_GRADIENT,
                            GWY_DATA_ITEM_RANGE,
                            GWY_DATA_ITEM_MASK_COLOR,
                            GWY_DATA_ITEM_REAL_SQUARE,
                            0);
    gwy_app_channel_log_add_proc(data, id, newid);

    g_object_unref(result);

    if (mfield) {
        GwyInterpolationType interp = args->interp;

        result = gwy_data_field_duplicate(mfield);
        args->interp = GWY_INTERPOLATION_ROUND;
        distort_do(args, mfield, result);
        args->interp = interp;
        gwy_container_set_object(data, gwy_app_get_mask_key_for_id(newid),
                                 result);
        g_object_unref(result);
    }

    if (sfield) {
        result = gwy_data_field_duplicate(sfield);
        distort_do(args, sfield, result);
        gwy_container_set_object(data, gwy_app_get_show_key_for_id(newid),
                                 result);
        g_object_unref(result);
    }
}

static void
distort_dialog_update_controls(DistortControls *controls,
                               DistortArgs *args)
{
    gchar buf[24];
    guint i, j, k;

    gwy_enum_combo_box_set_active(GTK_COMBO_BOX(controls->interp),
                                  args->interp);

    for (i = 0; i < MAX_DEGREE + 1; i++) {
        for (j = 0; j < MAX_DEGREE + 1; j++) {
            if (i + j > MAX_DEGREE)
                continue;

            k = i*(MAX_DEGREE + 1) + j;
            g_snprintf(buf, sizeof(buf), "%g", args->xcoeff[k]);
            gtk_entry_set_text(GTK_ENTRY(controls->xcoeff[k]), buf);
            g_snprintf(buf, sizeof(buf), "%g", args->ycoeff[k]);
            gtk_entry_set_text(GTK_ENTRY(controls->ycoeff[k]), buf);
        }
    }
}

static void
distort_coeff_changed(GtkEntry *entry,
                      DistortControls *controls)
{
    gint i, j, k;
    const gchar *id;
    gchar *end;
    gdouble val;
    gdouble *coeff;

    i = GPOINTER_TO_INT(g_object_get_data(G_OBJECT(entry), "y"));
    j = GPOINTER_TO_INT(g_object_get_data(G_OBJECT(entry), "x"));
    id = g_object_get_data(G_OBJECT(entry), "id");
    if (gwy_strequal(id, "x"))
        coeff = controls->args->xcoeff;
    else if (gwy_strequal(id, "y"))
        coeff = controls->args->ycoeff;
    else
        g_return_if_reached();

    val = g_strtod(gtk_entry_get_text(entry), &end);
    k = i*(MAX_DEGREE + 1) + j;
    if (val == coeff[k])
        return;

    coeff[k] = val;
    distort_invalidate(controls);
}

static gboolean
execute_preview(gpointer user_data)
{
    DistortControls *controls = (DistortControls*)user_data;

    preview(controls, controls->args);
    controls->preview_id = 0;

    return FALSE;
}

static void
distort_invalidate(DistortControls *controls)
{
    controls->computed = FALSE;
    if (controls->args->update) {
        if (!controls->preview_id)
            controls->preview_id = g_idle_add(execute_preview, controls);
    }
}

static void
preview_type_changed(GtkToggleButton *button,
                     DistortControls *controls)
{
    GwyPixmapLayer *blayer;

    if (button && !gtk_toggle_button_get_active(button))
        return;

    controls->args->preview_type
        = gwy_radio_buttons_get_current(controls->preview_type);

    blayer = gwy_data_view_get_base_layer(GWY_DATA_VIEW(controls->view));
    switch (controls->args->preview_type) {
        case PREVIEW_TRANSFORMED:
        gwy_layer_basic_set_presentation_key(GWY_LAYER_BASIC(blayer),
                                             "/1/data");
        break;

        case PREVIEW_ORIGINAL:
        gwy_layer_basic_set_presentation_key(GWY_LAYER_BASIC(blayer), NULL);
        break;

        default:
        g_return_if_reached();
        break;
    }
}

static void
preview(DistortControls *controls,
        DistortArgs *args)
{
    GwyDataField *dfield;

    dfield = GWY_DATA_FIELD(gwy_container_get_object_by_name(controls->mydata,
                                                             "/0/data"));
    if (GTK_WIDGET_REALIZED(controls->dialog))
        gwy_app_wait_cursor_start(GTK_WINDOW(controls->dialog));
    if (!controls->result) {
        controls->result = gwy_data_field_duplicate(dfield);
        gwy_container_set_object_by_name(controls->mydata, "/1/data",
                                         controls->result);
    }
    else
        gwy_data_field_copy(dfield, controls->result, FALSE);
    distort_do(args, dfield, controls->result);
    gwy_data_field_data_changed(controls->result);
    if (GTK_WIDGET_REALIZED(controls->dialog))
        gwy_app_wait_cursor_finish(GTK_WINDOW(controls->dialog));

    controls->computed = TRUE;
}

static inline gdouble
distort_coord(gdouble x,
              gdouble y,
              const gdouble *a)
{
    return (a[0]
            + x*(a[1] + x*(a[2] + x*a[3]))
            + y*(a[4] + x*(a[5] + x*a[6])
                 + y*(a[8] + x*a[9] + y*a[12])));
}

static void
distort_transform(gdouble x, gdouble y,
                  gdouble *px, gdouble *py,
                  gpointer user_data)
{
    const gdouble *param = (const gdouble*)user_data;

    x /= param[2*NCOEFF + 0];
    y /= param[2*NCOEFF + 1];
    *px = param[2*NCOEFF + 0]*distort_coord(x, y, param);
    *py = param[2*NCOEFF + 1]*distort_coord(x, y, param + NCOEFF);
}

static void
distort_do(DistortArgs *args,
           GwyDataField *dfield,
           GwyDataField *result)
{
    gdouble *param;
    gdouble val;

    /* XXX: Degree hardcoded in distort_coord() to avoid cycles and if-elses. */
    g_assert(MAX_DEGREE == 3);

    param = g_new(gdouble, 2*(NCOEFF + 1));
    gwy_assign(param, args->xcoeff, NCOEFF);
    gwy_assign(param + NCOEFF, args->ycoeff, NCOEFF);
    param[2*NCOEFF + 0] = gwy_data_field_get_xres(result);
    param[2*NCOEFF + 1] = gwy_data_field_get_yres(result);

    val = gwy_data_field_get_min(dfield);
    gwy_data_field_distort(dfield, result, distort_transform, param,
                           args->interp, args->exterior, val);
    g_free(param);
}

static const gchar interp_key[]   = "/module/polydistort/interp";
static const gchar exterior_key[] = "/module/polydistort/exterior";
static const gchar update_key[]   = "/module/polydistort/update";
static const gchar coeff_key[]    = "/module/polydistort/%ccoeff-%d-%d";

static void
distort_sanitize_args(DistortArgs *args)
{
    args->interp = gwy_enum_sanitize_value(args->interp,
                                           GWY_TYPE_INTERPOLATION_TYPE);
    args->exterior = CLAMP(args->exterior,
                           GWY_EXTERIOR_BORDER_EXTEND,
                           GWY_EXTERIOR_FIXED_VALUE);
    args->update = !!args->update;
}

static void
reset_coeffs(DistortArgs *args)
{
    memset(args->xcoeff, 0, NCOEFF*sizeof(gdouble));
    args->xcoeff[1] = 1.0;

    memset(args->ycoeff, 0, NCOEFF*sizeof(gdouble));
    args->ycoeff[4] = 1.0;
}

static void
load_coeffs(gdouble *coeff,
            gchar type,
            GwyContainer *settings)
{
    gchar buf[40];
    gint i, j, k;

    for (i = 0; i < MAX_DEGREE + 1; i++) {
        for (j = 0; j < MAX_DEGREE + 1; j++) {
            if (i + j > MAX_DEGREE)
                continue;

            k = i*(MAX_DEGREE + 1) + j;
            g_snprintf(buf, sizeof(buf), coeff_key, type, i, j);
            gwy_container_gis_double_by_name(settings, buf, coeff + k);
        }
    }
}

static void
distort_load_args(GwyContainer *container,
                  DistortArgs *args)
{
    args->interp = distort_defaults.interp;
    args->exterior = distort_defaults.exterior;
    args->update = distort_defaults.update;

    reset_coeffs(args);
    gwy_container_gis_enum_by_name(container, interp_key, &args->interp);
    gwy_container_gis_enum_by_name(container, exterior_key, &args->exterior);
    gwy_container_gis_boolean_by_name(container, update_key, &args->update);
    load_coeffs(args->xcoeff, 'x', container);
    load_coeffs(args->ycoeff, 'y', container);

    distort_sanitize_args(args);
}

static void
save_coeffs(const gdouble *coeff,
            gchar type,
            GwyContainer *settings)
{
    gchar buf[40];
    gint i, j, k;

    for (i = 0; i < MAX_DEGREE + 1; i++) {
        for (j = 0; j < MAX_DEGREE + 1; j++) {
            if (i + j > MAX_DEGREE)
                continue;

            k = i*(MAX_DEGREE + 1) + j;
            g_snprintf(buf, sizeof(buf), coeff_key, type, i, j);
            if (coeff[k])
                gwy_container_set_double_by_name(settings, buf, coeff[k]);
            else
                gwy_container_remove_by_name(settings, buf);
        }
    }
}

static void
distort_save_args(GwyContainer *container,
                  DistortArgs *args)
{
    gwy_container_set_enum_by_name(container, interp_key, args->interp);
    gwy_container_set_enum_by_name(container, exterior_key, args->exterior);
    gwy_container_set_boolean_by_name(container, update_key, args->update);
    save_coeffs(args->xcoeff, 'x', container);
    save_coeffs(args->ycoeff, 'y', container);
}

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