/* Chrysalide - Outil d'analyse de fichiers binaires
 * helpers.h - prototypes pour la simplification des interactions de base avec Python
 *
 * Copyright (C) 2018-2020 Cyrille Bagard
 *
 *  This file is part of Chrysalide.
 *
 *  Chrysalide 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 3 of the License, or
 *  (at your option) any later version.
 *
 *  Chrysalide 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 Chrysalide.  If not, see <http://www.gnu.org/licenses/>.
 */


#ifndef _PLUGINS_PYCHRYSALIDE_HELPERS_H
#define _PLUGINS_PYCHRYSALIDE_HELPERS_H


#include <Python.h>
#include <assert.h>
#include <glib-object.h>
#include <stdbool.h>



/* ---------------------- ACCELERATEURS POUR PYTHON UNIQUEMENT ---------------------- */


/* Traduit pour Python le bilan d'une comparaison riche. */
PyObject *status_to_rich_cmp_state(int, int);

/* Tente de convertir en élément appelable. */
int convert_to_callable(PyObject *, void *);

/* Indique si une routine Python existe ou non. */
bool has_python_method(PyObject *, const char *);

/* Appelle une routine Python. */
PyObject *run_python_method(PyObject *, const char *, PyObject *);

/* Ajoute une constante au dictionnaire d'un type Python donné. */
bool PyDict_AddULongConstant(PyObject *, const char *, unsigned long);

/* Ajoute une constante au dictionnaire d'un type Python donné. */
bool PyDict_AddStringConstant(PyObject *, const char *, const char *);


#define PyDict_AddULongMacro(tp, c) PyDict_AddULongConstant(tp->tp_dict, #c, c)
#define PyDict_AddStringMacro(tp, c) PyDict_AddStringConstant(tp->tp_dict, #c, c)

#define PyModDict_AddULongMacro(d, c) PyDict_AddULongConstant(d, #c, c)
#define PyModDict_AddStringMacro(d, c) PyDict_AddStringConstant(d, #c, c)



/* ---------------------------- MISE EN PLACE DE MODULES ---------------------------- */


/* Met en place un nouveau module Python. */
PyObject *build_python_module(PyObject *, PyModuleDef *);

/* Met en place une série de méthodes pour un module Python. */
bool register_python_module_methods(PyObject *, PyMethodDef *);

/* Met en place un objet au sein d'un module Python. */
bool register_python_module_object(PyObject *, PyTypeObject *);



/* --------------------------- CONFORTS CIBLANT PYGOBJECT --------------------------- */


/**
 * Aide à la définition de documentation pour Python.
 */

#define PYTHON_METHOD_DEF(name, args, flags, base, doc) \
    {                                                   \
        #name, (PyCFunction)base ## _ ## name,          \
        flags,                                          \
        #name "(" args ")\n--\n\n" doc                  \
    }

#define PYTHON_GETSET_DEF(name, get, set, doc, closure) \
    {                                                   \
        name, get, set,                                 \
        doc,                                            \
        closure                                         \
    }

#define PYTHON_IS_DEF_FULL(name, base, doc)            \
    PYTHON_GETSET_DEF("is_" #name, base ## _is_ ## name, NULL, doc, NULL)

#define PYTHON_GET_DEF_FULL(name, base, doc)            \
    PYTHON_GETSET_DEF(#name, base ## _get_ ## name, NULL, doc, NULL)

#define PYTHON_GETSET_DEF_FULL(name, base, doc)         \
    PYTHON_GETSET_DEF(#name, base ## _get_ ## name, base ## _set_ ## name, doc, NULL)

/**
 * Quelque chose est mal fait au niveau de l'abstraction GObject.
 * Du coup, Py_TPFLAGS_IS_ABSTRACT n'est pas pris en compte.
 * On force alors la méthode de base pour obtenir un traitement correct.
 *
 * Cf. http://stackoverflow.com/questions/20432335/can-python-abstract-base-classes-inherit-from-c-extensions
 */
#define APPLY_ABSTRACT_FLAG(tp) tp->tp_new = PyBaseObject_Type.tp_new


/* Marque l'interdiction d'une instanciation depuis Python. */
PyObject *no_python_constructor_allowed(PyTypeObject *, PyObject *, PyObject *);

/* Marque l'absence d'implémentation pour une méthode donnée. */
PyObject *not_yet_implemented_method(PyObject *, PyObject *);

/* Définit dans le tas de Python un nouveau type. */
PyTypeObject *define_python_dynamic_type(const PyTypeObject *);


/**
 * pygobject_new() prend en compte les références flottantes au moment de la
 * construction d'un objet Python.
 *
 * Et cela pose problème dans la mesure où on ne veut pas transférer à Python
 * la propriété d'un objet, même si celui-ci a une référence flotante.
 *
 * Dans les faits, c'est toujours uniquement le cas pour les composants graphiques,
 * puisque GtkWidget hérite de GInitiallyUnowned, qui force le décompte flottant
 * dans g_initially_unowned_init().
 */
#define new_pygobject_widget(o)             \
    ({                                      \
        if (g_object_is_floating(o))        \
            g_object_ref_sink(o);           \
        pygobject_new(G_OBJECT(o));         \
    })


/* Enregistre correctement une surcouche de conversion GObject. */
bool _register_class_for_pygobject(PyObject *, GType, PyTypeObject *, PyTypeObject *, ...);

#define register_class_for_pygobject(dict, gtype, type, base) \
    _register_class_for_pygobject(dict, gtype, type, base, NULL)

/* Enregistre correctement une interface GObject pour Python. */
bool register_interface_for_pygobject(PyObject *, GType, PyTypeObject *);

/* Enregistre un type Python dérivant d'un type GLib dynamique. */
bool register_class_for_dynamic_pygobject(GType, PyTypeObject *, PyTypeObject *);

/* Fait suivre à la partie GObject une initialisation nouvelle. */
int forward_pygobjet_init(PyObject *);



/* ----------------------- TRANSFERT DES VALEURS CONSTANTES ------------------------- */


/* Simplification d'un ajout de constante pour l'appelant */
#define add_const_to_group(d, n, v)                         \
    ({                                                      \
        bool __result;                                      \
        PyObject *__val;                                    \
        int __ret;                                          \
        __val = PyLong_FromUnsignedLong(v);                 \
        if (__val == NULL)                                  \
            __result = false;                               \
        else                                                \
        {                                                   \
            __ret = PyDict_SetItemString(d, n, __val);      \
            Py_DECREF(__val);                               \
            __result = (__ret == 0);                        \
        }                                                   \
        __result;                                           \
    })

/* Officialise un groupe de constantes avec sémentique. */
bool _attach_constants_group(const char *, PyObject *, bool, const char *, PyObject *, const char *);

#define attach_constants_group_to_type(type, flags, name, values, doc) \
    _attach_constants_group(type->tp_name, type->tp_dict, flags, name, values, doc)

#define attach_constants_group_to_module(mod, flags, name, values, doc)                 \
    ({                                                                                  \
        bool __result;                                                                  \
        const char *__owner;                                                            \
        PyObject *__dict;                                                               \
        __owner = PyModule_GetName(mod);                                                \
        __dict = PyModule_GetDict(mod);                                                 \
        __result = _attach_constants_group(__owner, __dict, flags, name, values, doc);  \
        __result;                                                                       \
    })

/* Traduit une valeur constante C en équivalent Python. */
PyObject *_cast_with_constants_group(const char *, const char *, unsigned long);

#define cast_with_constants_group_from_type(type, name, value) \
    _cast_with_constants_group(type->tp_name, name, value)

#define cast_with_constants_group_from_module(owner, name, value) \
    _cast_with_constants_group(owner, name, value)



#endif  /* _PLUGINS_PYCHRYSALIDE_HELPERS_H */