/*
 *  $Id: tipops.c 30047 2026-06-11 08:30:45Z yeti-dn $
 *  Copyright (C) 2004-2026 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 <glib/gi18n-lib.h>
#include <gtk/gtk.h>
#include <gwy.h>

#define RUN_MODES GWY_RUN_INTERACTIVE

typedef enum {
    DILATION,
    EROSION,
    CERTAINTY_MAP
} TipOperation;

enum {
    PARAM_TIP,

    MESSAGE_RESAMPLING,
};

typedef struct {
    GwyParams *params;
    GwyField *field;
    GObject *result;
} ModuleArgs;

typedef struct {
    ModuleArgs *args;
    GtkWidget *dialog;
    GwyParamTable *table;
} ModuleGUI;

static gboolean         module_register     (void);
static GwyParamDef*     define_module_params(void);
static void             module_main         (GwyFile *data,
                                             GwyRunModeFlags mode);
static gboolean         execute             (ModuleArgs *args,
                                             TipOperation op,
                                             GtkWindow *wait_window);
static GwyDialogOutcome run_gui             (ModuleArgs *args,
                                             TipOperation op);
static void             param_changed       (ModuleGUI *gui,
                                             gint id);
static gboolean         tip_image_filter    (GwyFile *data,
                                             gint id,
                                             gpointer user_data);

static GwyModuleInfo module_info = {
    GWY_MODULE_ABI_VERSION,
    &module_register,
    N_("Tip operations: dilation (convolution), erosion (reconstruction) and certainty map."),
    "Petr Klapetek <klapetek@gwyddion.net>, Yeti <yeti@gwyddion.net>",
    "2.2",
    "David Nečas (Yeti) & Petr Klapetek",
    "2006",
};

GWY_MODULE_QUERY2(module_info, tipops)

static gboolean
module_register(void)
{
    gwy_image_func_register("tip_dilation",
                            module_main,
                            N_("/SPM M_odes/_Tip/_Dilation..."),
                            GWY_ICON_TIP_DILATION,
                            RUN_MODES,
                            GWY_MENU_FLAG_IMAGE,
                            N_("Surface dilation by defined tip"));
    gwy_image_func_register("tip_reconstruction",
                            module_main,
                            N_("/SPM M_odes/_Tip/_Surface Reconstruction..."),
                            GWY_ICON_TIP_EROSION,
                            RUN_MODES,
                            GWY_MENU_FLAG_IMAGE,
                            N_("Surface reconstruction by defined tip"));
    gwy_image_func_register("tip_map",
                            module_main,
                            N_("/SPM M_odes/_Tip/_Certainty Map..."),
                            GWY_ICON_TIP_MAP,
                            RUN_MODES,
                            GWY_MENU_FLAG_IMAGE,
                            N_("Tip certainty map"));

    return TRUE;
}

static GwyParamDef*
define_module_params(void)
{
    static GwyParamDef *paramdef = NULL;

    if (paramdef)
        return paramdef;

    paramdef = gwy_param_def_new();
    gwy_param_def_set_function_name(paramdef, "tipops");    /* Share tip settings. */
    gwy_param_def_add_image_id(paramdef, PARAM_TIP, "tip", _("_Tip morphology"));
    return paramdef;
}

static void
module_main(GwyFile *data, GwyRunModeFlags mode)
{
    static const GwyEnum ops[] = {
        { "tip_dilation",       DILATION,      },
        { "tip_reconstruction", EROSION,       },
        { "tip_map",            CERTAINTY_MAP, },
    };
    static const GwyEnum data_titles[] = {
        { N_("Dilated data"),           DILATION,      },
        { N_("Surface reconstruction"), EROSION,       },
    };
    const gchar *name = gwy_image_func_current();
    GwyDialogOutcome outcome = GWY_DIALOG_PROCEED;
    TipOperation op;
    ModuleArgs args;
    gint id, newid;
    GQuark quark;

    g_return_if_fail(mode & RUN_MODES);
    gwy_clear1(args);
    if ((op = gwy_string_to_enum(name, ops, G_N_ELEMENTS(ops))) == (TipOperation)-1) {
        g_warning("tipops does not provide function `%s'", name);
        return;
    }

    gwy_data_browser_get_current(GWY_APP_FIELD, &args.field,
                                 GWY_APP_FIELD_ID, &id,
                                 0);
    g_return_if_fail(args.field);

    args.params = gwy_params_new_from_settings(define_module_params());
    outcome = run_gui(&args, op);
    gwy_params_save_to_settings(args.params);
    if (outcome == GWY_DIALOG_CANCEL)
        goto end;
    if (!execute(&args, op, gwy_data_browser_get_window_for_data(data, GWY_FILE_IMAGE, id)))
        goto end;

    if (op == DILATION || op == EROSION) {
        newid = gwy_file_add_image(data, GWY_FIELD(args.result));
        gwy_file_set_visible(data, GWY_FILE_IMAGE, newid, TRUE);
        gwy_file_sync_items(data, GWY_FILE_IMAGE, id,
                            data, GWY_FILE_IMAGE, newid,
                            GWY_FILE_ITEM_PALETTE | GWY_FILE_ITEM_MASK_COLOR, FALSE);
        gwy_file_set_title(data, GWY_FILE_IMAGE, newid,
                           gwy_enum_to_string(op, data_titles, G_N_ELEMENTS(data_titles)), TRUE);
        gwy_log_add(data, GWY_FILE_IMAGE, id, newid);
    }
    else {
        quark = gwy_file_key_image_mask(id);
        gwy_app_undo_qcheckpointv(GWY_DICT(data), 1, &quark);
        gwy_file_set_image_mask(data, id, GWY_NIELD(args.result));
        gwy_log_add(data, GWY_FILE_IMAGE, id, id);
    }

end:
    g_clear_object(&args.result);
    g_object_unref(args.params);
}

static GwyDialogOutcome
run_gui(ModuleArgs *args, TipOperation op)
{
    static const GwyEnum titles[] = {
        { N_("Tip Dilation"),           DILATION,      },
        { N_("Surface Reconstruction"), EROSION,       },
        { N_("Certainty Map Analysis"), CERTAINTY_MAP, },
    };
    ModuleGUI gui;
    GwyDialog *dialog;
    GwyParamTable *table;

    gui.args = args;
    gui.dialog = gwy_dialog_new(gwy_enum_to_string(op, titles, G_N_ELEMENTS(titles)));
    dialog = GWY_DIALOG(gui.dialog);
    gwy_dialog_add_stock_buttons(dialog, GWY_STOCK_CANCEL, GWY_STOCK_OK, 0);

    table = gui.table = gwy_param_table_new(args->params);
    gwy_param_table_append_image_id(table, PARAM_TIP);
    gwy_param_table_data_id_set_filter(table, PARAM_TIP, tip_image_filter, args->field, NULL);
    gwy_param_table_append_message(table, MESSAGE_RESAMPLING, NULL);
    gwy_param_table_message_set_type(table, MESSAGE_RESAMPLING, GTK_MESSAGE_WARNING);
    gwy_dialog_add_content(dialog, gwy_param_table_widget(table), TRUE, TRUE, 0);
    g_signal_connect_swapped(table, "param-changed", G_CALLBACK(param_changed), &gui);

    return gwy_dialog_run(dialog);
}

static gboolean
tip_image_filter(GwyFile *data, gint id, gpointer user_data)
{
    GwyField *field = (GwyField*)user_data;
    GwyField *tip = gwy_file_get_image(data, id);

    if (gwy_field_get_xreal(tip) > gwy_field_get_xreal(field)/3
        || gwy_field_get_yreal(tip) > gwy_field_get_yreal(field)/3)
        return FALSE;

    return !gwy_field_is_incompatible(tip, field, GWY_DATA_MISMATCH_LATERAL | GWY_DATA_MISMATCH_VALUE);
}

static gboolean
tip_needs_resampling(GwyField *surface, GwyField *tip, gint *newxres, gint *newyres)
{
    if (gwy_field_is_incompatible(tip, surface, GWY_DATA_MISMATCH_MEASURE)) {
        *newxres = gwy_field_get_xres(tip);
        *newyres = gwy_field_get_yres(tip);
        return FALSE;
    }

    *newxres = GWY_ROUND(gwy_field_get_xreal(tip)/gwy_field_get_dx(surface));
    *newxres = MAX(*newxres, 1);

    *newyres = GWY_ROUND(gwy_field_get_yreal(tip)/gwy_field_get_dy(surface));
    *newyres = MAX(*newyres, 1);

    // Return FALSE in stupid edge cases like 1×1 tips or when the mismatch is so small that resampling does not
    // change the pixel size.
    return (*newxres != gwy_field_get_xres(tip) || *newyres != gwy_field_get_yres(tip));
}

static void
param_changed(ModuleGUI *gui, gint id)
{
    ModuleArgs *args = gui->args;
    GwyParams *params = args->params;

    if (id < 0 || id == PARAM_TIP) {
        if (gwy_params_data_id_is_none(params, PARAM_TIP))
            gtk_dialog_set_response_sensitive(GTK_DIALOG(gui->dialog), GTK_RESPONSE_OK, FALSE);
        else {
            GwyField *tip = gwy_params_get_image(params, PARAM_TIP), *field = args->field;
            gint txres, tyres;

            if (tip_needs_resampling(field, tip, &txres, &tyres)) {
                gchar *s = g_strdup_printf(_("Tip pixel size does not match data.\n"
                                             "It will be resampled from %d×%d to %d×%d."),
                                           gwy_field_get_xres(tip), gwy_field_get_yres(tip), txres, tyres);
                gwy_param_table_set_label(gui->table, MESSAGE_RESAMPLING, s);
                g_free(s);
            }
            else
                gwy_param_table_set_label(gui->table, MESSAGE_RESAMPLING, NULL);
        }
    }
}

static gboolean
execute(ModuleArgs *args, TipOperation op, GtkWindow *wait_window)
{
    GwyField *field = args->field, *tip = gwy_params_get_image(args->params, PARAM_TIP);
    gboolean ok = FALSE;

    g_return_val_if_fail(tip, FALSE);

    gwy_app_wait_start(wait_window, _("Initializing..."));

    gint txres, tyres;
    if (tip_needs_resampling(field, tip, &txres, &tyres))
        tip = gwy_field_new_resampled(tip, txres, tyres, GWY_INTERPOLATION_BSPLINE);
    else
        g_object_ref(tip);

    if (op == DILATION) {
        GwyField *result = gwy_field_new_alike(field, FALSE);
        args->result = G_OBJECT(result);
        ok = gwy_field_tip_dilation(field, tip, result, TRUE, gwy_app_wait_set_fraction, gwy_app_wait_set_message);
    }
    else if (op == EROSION) {
        GwyField *result = gwy_field_new_alike(field, FALSE);
        args->result = G_OBJECT(result);
        ok = gwy_field_tip_erosion(field, tip, result, TRUE, gwy_app_wait_set_fraction, gwy_app_wait_set_message);
    }
    else if (op == CERTAINTY_MAP) {
        GwyNield *result = gwy_field_new_nield_alike(field);
        args->result = G_OBJECT(result);
        ok = gwy_field_tip_certainty_map(field, tip, result, TRUE, gwy_app_wait_set_fraction, gwy_app_wait_set_message);
    }
    else {
        g_assert_not_reached();
    }
    gwy_app_wait_finish();

    g_object_unref(tip);

    return ok;
}

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