/*
 *  $Id: grain_mark.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 <string.h>
#include <gtk/gtk.h>
#include <gwy.h>
#include "../preview.h"

#define RUN_MODES (GWY_RUN_IMMEDIATE | GWY_RUN_INTERACTIVE)

enum {
    PARAM_HEIGHT,
    PARAM_USE_HEIGHT,
    PARAM_RANK,
    PARAM_USE_RANK,
    PARAM_SLOPE,
    PARAM_USE_SLOPE,
    PARAM_CURVATURE,
    PARAM_USE_CURVATURE,
    PARAM_INVERTED,
    PARAM_MERGE_TYPE,
    PARAM_COMBINE_TYPE,
    PARAM_COMBINE,
    PARAM_UPDATE,
    PARAM_MASK_COLOR,
};

typedef struct {
    GwyParams *params;
    GwyField *field;
    GwyNield *mask;
    GwyNield *result;
    /* Cached precalculated fields. */
    GwyField *slope;
    GwyField *curvature;
    GwyNield *rank;
} 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 void             execute             (ModuleArgs *args);
static GwyDialogOutcome run_gui             (ModuleArgs *args,
                                             GwyFile *data,
                                             gint id);
static void             param_changed       (ModuleGUI *gui,
                                             gint id);
static void             preview             (gpointer user_data);
static GwyNield*        calculate_rank      (GwyField *field);
static GwyField*        calculate_slope     (GwyField *field);
static GwyField*        calculate_curvature (GwyField *field);
static void             mark_by_rank        (GwyNield *rank,
                                             GwyNield *result,
                                             gdouble rank_frac,
                                             gboolean inverted);

static GwyModuleInfo module_info = {
    GWY_MODULE_ABI_VERSION,
    &module_register,
    N_("Marks grains by thresholding (height, slope, curvature)."),
    "Petr Klapetek <petr@klapetek.cz>",
    "3.1",
    "David Nečas (Yeti) & Petr Klapetek",
    "2003",
};

GWY_MODULE_QUERY2(module_info, grain_mark)

static gboolean
module_register(void)
{
    gwy_image_func_register("grain_mark",
                            module_main,
                            N_("/_Grains/_Mark by Threshold..."),
                            GWY_ICON_GRAINS,
                            RUN_MODES,
                            GWY_MENU_FLAG_IMAGE,
                            N_("Mark grains by threshold"));

    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, gwy_image_func_current());
    gwy_param_def_add_percentage(paramdef, PARAM_HEIGHT, "height", _("_Height"), 0.5);
    gwy_param_def_add_boolean(paramdef, PARAM_USE_HEIGHT, "use_height", NULL, TRUE);
    gwy_param_def_add_percentage(paramdef, PARAM_RANK, "rank", _("_Rank"), 0.5);
    gwy_param_def_add_boolean(paramdef, PARAM_USE_RANK, "use_rank", NULL, TRUE);
    gwy_param_def_add_percentage(paramdef, PARAM_SLOPE, "slope", _("_Slope"), 0.5);
    gwy_param_def_add_boolean(paramdef, PARAM_USE_SLOPE, "use_slope", NULL, FALSE);
    gwy_param_def_add_percentage(paramdef, PARAM_CURVATURE, "curvature", _("_Curvature"), 0.5);
    gwy_param_def_add_boolean(paramdef, PARAM_USE_CURVATURE, "use_curvature", NULL, FALSE);
    gwy_param_def_add_boolean(paramdef, PARAM_INVERTED, "inverted", _("_Invert height"), FALSE);
    gwy_param_def_add_basic_merge(paramdef, PARAM_MERGE_TYPE, "merge_type", _("Criteria combination"),
                                  TRUE, GWY_MERGE_UNION);
    gwy_param_def_add_basic_merge(paramdef, PARAM_COMBINE_TYPE, "combine_type", NULL, FALSE, GWY_MERGE_UNION);
    gwy_param_def_add_boolean(paramdef, PARAM_COMBINE, "combine", NULL, FALSE);
    gwy_param_def_add_instant_updates(paramdef, PARAM_UPDATE, "update", NULL, TRUE);
    gwy_param_def_add_mask_color(paramdef, PARAM_MASK_COLOR, NULL, NULL);
    return paramdef;
}

static void
module_main(GwyFile *data, GwyRunModeFlags mode)
{
    ModuleArgs args;
    GwyDialogOutcome outcome = GWY_DIALOG_PROCEED;
    GQuark mquark;
    gint id;

    g_return_if_fail(mode & RUN_MODES);
    gwy_clear1(args);
    gwy_data_browser_get_current(GWY_APP_FIELD, &args.field,
                                 GWY_APP_FIELD_ID, &id,
                                 GWY_APP_MASK_FIELD_KEY, &mquark,
                                 GWY_APP_MASK_FIELD, &args.mask,
                                 0);
    g_return_if_fail(args.field && mquark);

    args.result = gwy_field_new_nield_alike(args.field);
    args.params = gwy_params_new_from_settings(define_module_params());

    if (mode == GWY_RUN_INTERACTIVE) {
        outcome = run_gui(&args, data, id);
        gwy_params_save_to_settings(args.params);
        if (outcome == GWY_DIALOG_CANCEL)
            goto end;
    }
    if (outcome != GWY_DIALOG_HAVE_RESULT)
        execute(&args);

    gwy_app_undo_qcheckpointv(GWY_DICT(data), 1, &mquark);
    gint ngrains = gwy_nield_number_contiguous(args.result);
    gwy_file_set_image_mask(data, id, ngrains ? args.result : NULL);
    gwy_log_add(data, GWY_FILE_IMAGE, id, id);

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

static GwyDialogOutcome
run_gui(ModuleArgs *args, GwyFile *data, gint id)
{
    GtkWidget *hbox, *dataview;
    GwyDialog *dialog;
    GwyParamTable *table;
    ModuleGUI gui;

    gwy_clear1(gui);
    gui.args = args;

    gui.dialog = gwy_dialog_new(_("Mark Grains by Threshold"));
    dialog = GWY_DIALOG(gui.dialog);
    gwy_dialog_add_stock_buttons(dialog, GWY_STOCK_UPDATE, GWY_STOCK_RESET, GWY_STOCK_CANCEL, GWY_STOCK_OK, 0);

    dataview = gwy_create_preview(args->field, args->result, PREVIEW_SIZE);
    gwy_setup_data_view(GWY_DATA_VIEW(dataview), data, GWY_FILE_IMAGE, id,
                        GWY_FILE_ITEM_PALETTE | GWY_FILE_ITEM_RANGE | GWY_FILE_ITEM_REAL_SQUARE);
    hbox = gwy_create_dialog_preview_hbox(GTK_DIALOG(dialog), GWY_DATA_VIEW(dataview), FALSE);

    table = gui.table = gwy_param_table_new(args->params);
    gwy_param_table_append_header(table, -1, _("Threshold by"));
    gwy_param_table_append_slider(table, PARAM_HEIGHT);
    gwy_param_table_add_enabler(table, PARAM_USE_HEIGHT, PARAM_HEIGHT);
    gwy_param_table_slider_add_alt(table, PARAM_HEIGHT);
    gwy_param_table_alt_set_field_frac_z(table, PARAM_HEIGHT, args->field);
    gwy_param_table_append_slider(table, PARAM_RANK);
    gwy_param_table_add_enabler(table, PARAM_USE_RANK, PARAM_RANK);
    gwy_param_table_append_slider(table, PARAM_SLOPE);
    gwy_param_table_add_enabler(table, PARAM_USE_SLOPE, PARAM_SLOPE);
    gwy_param_table_append_slider(table, PARAM_CURVATURE);
    gwy_param_table_add_enabler(table, PARAM_USE_CURVATURE, PARAM_CURVATURE);

    gwy_param_table_append_separator(table);
    gwy_param_table_append_checkbox(table, PARAM_INVERTED);
    gwy_param_table_append_radio_buttons(table, PARAM_MERGE_TYPE, NULL);

    gwy_param_table_append_header(table, -1, _("Options"));
    gwy_param_table_append_image_mask_color(table, PARAM_MASK_COLOR, GWY_DATA_VIEW(dataview), data, id);
    if (args->mask) {
        gwy_param_table_append_radio_buttons(table, PARAM_COMBINE_TYPE, NULL);
        gwy_param_table_add_enabler(table, PARAM_COMBINE, PARAM_COMBINE_TYPE);
    }
    gwy_param_table_append_checkbox(table, PARAM_UPDATE);

    gtk_box_pack_start(GTK_BOX(hbox), gwy_param_table_widget(table), TRUE, TRUE, 0);

    g_signal_connect_swapped(table, "param-changed", G_CALLBACK(param_changed), &gui);
    gwy_dialog_set_preview_func(dialog, GWY_PREVIEW_IMMEDIATE, preview, &gui, NULL);

    return gwy_dialog_run(dialog);
}

static void
param_changed(ModuleGUI *gui, gint id)
{
    if (id != PARAM_MASK_COLOR && id != PARAM_UPDATE)
        gwy_dialog_invalidate(GWY_DIALOG(gui->dialog));
}

static void
preview(gpointer user_data)
{
    ModuleGUI *gui = (ModuleGUI*)user_data;
    ModuleArgs *args = gui->args;

    execute(args);
    gwy_nield_data_changed(args->result);
    gwy_dialog_have_result(GWY_DIALOG(gui->dialog));
}

static void
mark_using_field(GwyNield *mask, GwyField *field, GwyNield **tmp,
                 gdouble frac_threshold, gboolean inverted, GwyMergeType merge,
                 gboolean *field_been_set)
{
    /* Convert old-style percentage threshold to an absolute value. */
    gdouble min, max;
    gwy_field_min_max(field, &min, &max);
    gdouble threshold = min + frac_threshold*(max - min);

    if (*field_been_set) {
        if (!*tmp)
            *tmp = gwy_nield_new_alike(mask);
        gwy_nield_mark_by_threshold(*tmp, field, threshold, !inverted);
        gwy_nield_merge(mask, *tmp, merge);
    }
    else
        gwy_nield_mark_by_threshold(mask, field, threshold, !inverted);

    *field_been_set = TRUE;
}

static void
execute(ModuleArgs *args)
{
    GwyParams *params = args->params;
    gdouble height_frac = gwy_params_get_double(params, PARAM_HEIGHT);
    gdouble rank_frac = gwy_params_get_double(params, PARAM_RANK);
    gdouble slope_frac = gwy_params_get_double(params, PARAM_SLOPE);
    gdouble curvature_frac = gwy_params_get_double(params, PARAM_CURVATURE);
    gboolean inverted = gwy_params_get_boolean(params, PARAM_INVERTED);
    GwyMergeType merge_type = gwy_params_get_enum(params, PARAM_MERGE_TYPE);
    GwyMergeType combine_type = gwy_params_get_enum(params, PARAM_COMBINE_TYPE);
    GwyField *field = args->field;
    GwyNield *mask = args->mask, *result = args->result, *tmp = NULL;
    gboolean field_been_set = FALSE;

    if (gwy_params_get_boolean(params, PARAM_USE_HEIGHT))
        mark_using_field(result, field, &tmp, height_frac, inverted, merge_type, &field_been_set);

    if (gwy_params_get_boolean(params, PARAM_USE_RANK)) {
        if (!args->rank)
            args->rank = calculate_rank(field);
        if (field_been_set) {
            if (!tmp)
                tmp = gwy_field_new_nield_alike(field);
            mark_by_rank(args->rank, tmp, rank_frac, inverted);
            gwy_nield_merge(result, tmp, merge_type);
        }
        else
            mark_by_rank(args->rank, result, rank_frac, inverted);
        field_been_set = TRUE;
    }

    /* Only heights can be inverted. */
    if (gwy_params_get_boolean(params, PARAM_USE_SLOPE)) {
        if (!args->slope)
            args->slope = calculate_slope(field);
        mark_using_field(result, args->slope, &tmp, slope_frac, FALSE, merge_type, &field_been_set);
    }
    if (gwy_params_get_boolean(params, PARAM_USE_CURVATURE)) {
        if (!args->curvature)
            args->curvature = calculate_curvature(field);
        mark_using_field(result, args->curvature, &tmp, curvature_frac, FALSE, merge_type, &field_been_set);
    }

    if (!field_been_set)
        gwy_nield_clear(result);

    if (gwy_params_get_boolean(params, PARAM_COMBINE)) {
        if (combine_type == GWY_MERGE_SUBTRACT)
            combine_type = GWY_MERGE_REVSUBTRACT;
        gwy_nield_merge(result, mask, combine_type);
    }

    g_clear_object(&tmp);
}

static GwyNield*
calculate_rank(GwyField *field)
{
    gint xres = gwy_field_get_xres(field), yres = gwy_field_get_yres(field);
    gint n = xres*yres;
    gdouble *d = g_new(gdouble, n);
    GwyNield *rank = gwy_nield_new(xres, yres);
    gint *r = gwy_nield_get_data(rank);

    gwy_assign(d, gwy_field_get_data_const(field), n);
    for (gint i = 0; i < n; i++)
        r[i] = i;
    gwy_math_sort_with_index(d, n, r);

    return rank;
}

static GwyField*
calculate_slope(GwyField *field)
{
    GwyField *result = gwy_field_new_alike(field, FALSE);
    gwy_field_derivative_filter(field, result, GWY_DERIVATIVE_FILTER_SOBEL, FALSE);
    return result;
}

static GwyField*
calculate_curvature(GwyField *field)
{
    GwyField *result = gwy_field_new_alike(field, FALSE);
    gwy_field_derivative_filter(field, result, GWY_DERIVATIVE_FILTER_LAPLACE, FALSE);
    return result;
}

static void
mark_by_rank(GwyNield *rank, GwyNield *result,
             gdouble rank_frac, gboolean inverted)
{
    gint n = gwy_nield_get_xres(result)*gwy_nield_get_yres(result);
    gint ifrom, ito;

    if (inverted) {
        ifrom = 0;
        ito = GWY_ROUND(rank_frac*n);
    }
    else {
        ifrom = MIN(n, GWY_ROUND(rank_frac*n) + 1);
        ito = n;
    }

    gwy_nield_clear(result);
    gint *m = gwy_nield_get_data(result);
    const gint *r = gwy_nield_get_data(rank);
    for (gint i = ifrom; i < ito; i++)
        m[r[i]] = 1;
}

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