#!/usr/pkg/bin/python3.13

# Copyright (C) 2002-2006 Stephen Kennedy <stevek@gnome.org>
# Copyright (C) 2009-2014 Kai Willadsen <kai.willadsen@gmail.com>
#
# 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, see <http://www.gnu.org/licenses/>.

import locale
import logging
import os
import signal
import subprocess
import sys
from multiprocessing import freeze_support

# On Windows, pythonw.exe (which doesn't display a console window) supplies
# dummy stdout and stderr streams that silently throw away any output. However,
# these streams seem to have issues with flush() so we just redirect stdout and
# stderr to actual dummy files (the equivalent of /dev/null).
# Regarding pythonw.exe stdout, see also http://bugs.python.org/issue706263
# Also cx_Freeze built with Win32GUI base sets sys.stdout to None
# leading to exceptions in print() and freeze_support() that uses flush()
if sys.executable.endswith("pythonw.exe") or sys.stdout is None:
    devnull = open(os.devnull, "w")
    sys.stdout = sys.stderr = devnull

# Main module hasn't multiprocessing workers, so not imported in subprocesses.
# This allows skipping '__name__ == "main"' guard, but freezed case is special.
freeze_support()


def disable_stdout_buffering():

    class Unbuffered:

        def __init__(self, file):
            self.file = file

        def write(self, arg):
            self.file.write(arg)
            self.file.flush()

        def __getattr__(self, attr):
            return getattr(self.file, attr)

    sys.stdout = Unbuffered(sys.stdout)


def get_meld_dir():
    global frozen
    if frozen:
        return os.path.dirname(sys.executable)

    # Support running from an uninstalled version
    self_path = os.path.realpath(__file__)
    return os.path.abspath(os.path.join(os.path.dirname(self_path), ".."))


frozen = getattr(sys, 'frozen', False)
melddir = get_meld_dir()

uninstalled = False
if os.path.exists(os.path.join(melddir, "meld.doap")):
    sys.path[0:0] = [melddir]
    uninstalled = True
devel = os.path.exists(os.path.join(melddir, ".git"))

if uninstalled:
    # Import system hackery to import conf.py.in without copying it to
    # have a .py suffix. This is entirely so that we can run from a git
    # checkout without any user intervention.
    import importlib.machinery
    import importlib.util

    loader = importlib.machinery.SourceFileLoader(
        'meld.conf', os.path.join(melddir, 'meld/conf.py.in'))
    spec = importlib.util.spec_from_loader(loader.name, loader)
    mod = importlib.util.module_from_spec(spec)
    loader.exec_module(mod)

    import meld
    meld.conf = mod
    sys.modules['meld.conf'] = mod

import meld.conf  # noqa: E402

# Silence warnings on non-devel releases (minor version is divisible by 2)
is_stable = not bool(int(meld.conf.__version__.split('.')[1]) % 2)
if is_stable:
    import warnings
    warnings.simplefilter("ignore")

if uninstalled:
    meld.conf.uninstalled()
elif frozen:
    meld.conf.frozen()

# TODO: Possibly move to elib.intl
import gettext  # noqa: E402, I001
locale_domain = meld.conf.__package__
locale_dir = meld.conf.LOCALEDIR

gettext.bindtextdomain(locale_domain, locale_dir)
try:
    locale.setlocale(locale.LC_ALL, '')
except locale.Error as e:
    print("Couldn't set the locale: %s; falling back to 'C' locale" % e)
    locale.setlocale(locale.LC_ALL, 'C')
gettext.textdomain(locale_domain)
trans = gettext.translation(
    locale_domain, localedir=str(locale_dir), fallback=True)
_ = meld.conf._ = trans.gettext
meld.conf.ngettext = trans.ngettext

try:
    if os.name == 'nt':
        from ctypes import cdll
        if frozen:
            libintl = cdll['libintl-8']
        else:
            try:
                libintl = cdll.intl
            except FileNotFoundError:
                libintl = cdll['libintl-8']
        libintl.bindtextdomain(locale_domain, str(locale_dir))
        libintl.bind_textdomain_codeset(locale_domain, 'UTF-8')
        libintl.textdomain(locale_domain)
        del libintl
    else:
        locale.bindtextdomain(locale_domain, str(locale_dir))
        locale.bind_textdomain_codeset(locale_domain, 'UTF-8')
        locale.textdomain(locale_domain)
except AttributeError as e:
    # Python builds linked without libintl (i.e., OSX) don't have
    # bindtextdomain(), which causes Gtk.Builder translations to fail.
    print(
        "Couldn't bind the translation domain. Some translations won't "
        "work.\n{}".format(e))
except locale.Error as e:
    print(
        "Couldn't bind the translation domain. Some translations won't "
        "work.\n{}".format(e))
except WindowsError as e:
    # Accessing cdll.intl sometimes fails on Windows for unknown reasons.
    # Let's just continue, as translations are non-essential.
    print(
        "Couldn't bind the translation domain. Some translations won't "
        "work.\n{}".format(e))


def show_error_and_exit(error_text):
    """
    Show error in a robust way: always print to stdout and try to
    display gui message via gtk or tkinter (first available).
    Empty toplevel window is used as message box parent since
    parentless message box cause toolkit and windowing system problems.
    This function is both python 2 and python 3 compatible since it is used
    to display wrong python version.
    """
    print(error_text)
    raise_as_last_resort_to_display = False
    try:
        import gi
        gi.require_version("Gtk", "3.0")
        from gi.repository import Gtk
        Gtk.MessageDialog(
            message_type=Gtk.MessageType.ERROR,
            buttons=Gtk.ButtonsType.CLOSE,
            text=error_text,
        ).run()
    except Exception:
        # tkinter is imported here only to show a UI warning about
        # missing dependencies.
        try:
            from tkinter import Tk
            from tkinter.messagebox import showerror
            toplevel = Tk(className="Meld")
            toplevel.wait_visibility()
            showerror("Meld", error_text, parent=toplevel)
        except Exception:
            # Displaying with tkinter failed too, just exit if not frozen.
            # Frozen app may lack console but be able to show exceptions.
            raise_as_last_resort_to_display = frozen
    if raise_as_last_resort_to_display:
        raise Exception(error_text)
    sys.exit(1)


def check_requirements():

    import importlib
    from typing import NamedTuple, Optional

    class Requirement(NamedTuple):
        name: str
        module: Optional[str]
        gi_version: Optional[str]
        major_version: int
        minor_version: int

        def check(self):
            if self.gi_version:
                import gi
                gi.require_version(self.module, self.gi_version)
                module = 'gi.repository.{}'.format(self.module)
            else:
                module = self.module

            mod = importlib.import_module(module)
            if mod.__name__ == 'gi.repository.Gtk':
                version = (mod.get_major_version(), mod.get_minor_version())
            elif mod.__name__ == 'gi.repository.GLib':
                version = (mod.MAJOR_VERSION, mod.MINOR_VERSION)
            elif mod.__name__ == 'gi.repository.GtkSource':
                # There's no accessors for GtkSource, so we try a 4.0 API
                # call and just set the version so it will pass
                mod.init()
                version = (self.major_version, self.minor_version)
            elif mod.__name__ in ('cairo', 'gi', 'sys'):
                version = mod.version_info

            if version < (self.major_version, self.minor_version):
                raise RuntimeError('Unsupported version')

        def __str__(self):
            return '{} {}.{}'.format(
                self.name, self.major_version, self.minor_version)

    # These requirements are kept in both `bin/meld` and `meson.build`. If you
    # update one, update the other.
    requirements = (
        Requirement('Python', 'sys', None, 3, 6),
        Requirement('Gtk+', 'Gtk', '3.0', 3, 20),
        Requirement('GLib', 'GLib', '2.0', 2, 48),
        Requirement('GtkSourceView', 'GtkSource', '4', 4, 0),
        Requirement('pygobject', 'gi', None, 3, 30),
        Requirement('pycairo', 'cairo', None, 1, 15),
    )

    try:
        for r in requirements:
            r.check()
    except (AttributeError, ImportError, RuntimeError, ValueError):
        show_error_and_exit(_('Meld requires %s or higher.') % str(r))


def setup_resources():
    from gi.repository import Gio, GtkSource

    resource_filename = meld.conf.APPLICATION_ID + ".gresource"
    resource_file = os.path.join(meld.conf.DATADIR, resource_filename)

    if not os.path.exists(resource_file) and uninstalled:
        subprocess.call(
            [
                "glib-compile-resources",
                "--target={}".format(resource_file),
                "--sourcedir=meld/resources",
                "--sourcedir=data/icons/hicolor",
                "meld/resources/meld.gresource.xml",
            ],
            cwd=melddir
        )

    try:
        resources = Gio.resource_load(resource_file)
        Gio.resources_register(resources)
    except Exception:
        # Allow resources to be missing when running uninstalled
        if not uninstalled:
            raise

    style_path = os.path.join(meld.conf.DATADIR, "styles")
    GtkSource.StyleSchemeManager.get_default().append_search_path(style_path)

    # Just copy style schemes to the file ending expected by
    # GtkSourceView if we're uninstalled and they're missing
    if uninstalled:
        for style in {'meld-base', 'meld-dark'}:
            path = os.path.join(
                style_path, '{}.style-scheme.xml'.format(style))
            if not os.path.exists(path):
                import shutil
                shutil.copyfile(path + '.in', path)


def setup_settings():
    import meld.conf

    schema_path = os.path.join(meld.conf.DATADIR, "org.gnome.meld.gschema.xml")
    compiled_schema_path = os.path.join(meld.conf.DATADIR, "gschemas.compiled")

    try:
        schema_mtime = os.path.getmtime(schema_path)
        compiled_mtime = os.path.getmtime(compiled_schema_path)
        have_schema = schema_mtime < compiled_mtime
    except OSError:
        have_schema = False

    if uninstalled and not have_schema:
        subprocess.call(["glib-compile-schemas", meld.conf.DATADIR],
                        cwd=melddir)

    import meld.settings
    meld.settings.create_settings()


def setup_logging():
    log = logging.getLogger()

    # If we're running uninstalled and from Git, turn up the logging level
    if uninstalled and devel:
        log.setLevel(logging.INFO)
    else:
        log.setLevel(logging.CRITICAL)

    if sys.platform == 'win32':
        from gi.repository import GLib

        log_path = os.path.join(GLib.get_user_data_dir(), "meld.log")
        handler = logging.FileHandler(log_path)
        log.setLevel(logging.INFO)

        # Set excepthook so that we get exceptions on Windows
        def logging_except_hook(exc_type, exc_instance, tb):
            log.error(
                'Unhandled exception', exc_info=(exc_type, exc_instance, tb))

        sys.excepthook = logging_except_hook
    else:
        handler = logging.StreamHandler()

    formatter = logging.Formatter("%(asctime)s %(levelname)s "
                                  "%(name)s: %(message)s")
    handler.setFormatter(formatter)
    log.addHandler(handler)


def setup_glib_logging():
    from gi.repository import GLib
    levels = {
        GLib.LogLevelFlags.LEVEL_DEBUG: logging.DEBUG,
        GLib.LogLevelFlags.LEVEL_INFO: logging.INFO,
        GLib.LogLevelFlags.LEVEL_MESSAGE: logging.INFO,
        GLib.LogLevelFlags.LEVEL_WARNING: logging.WARNING,
        GLib.LogLevelFlags.LEVEL_ERROR: logging.ERROR,
        GLib.LogLevelFlags.LEVEL_CRITICAL: logging.CRITICAL,
    }
    level_flag = (
        GLib.LogLevelFlags.LEVEL_WARNING |
        GLib.LogLevelFlags.LEVEL_ERROR |
        GLib.LogLevelFlags.LEVEL_CRITICAL
    )

    log_domain = "Gtk"
    log = logging.getLogger(log_domain)

    def silence(message):
        if "Drawing a gadget with negative dimensions" in message:
            return True
        if "resource overlay" in message:
            return True
        return False

    # This logging handler is for "old" glib logging using a simple
    # syslog-style API.
    def log_adapter(domain, level, message, user_data):
        if not silence(message):
            log.log(levels.get(level, logging.WARNING), message)

    try:
        GLib.log_set_handler(log_domain, level_flag, log_adapter, None)
    except AttributeError:
        # Only present in glib 2.46+
        pass

    # This logging handler is for new glib logging using a structured
    # API. Unfortunately, it was added in such a way that the old
    # redirection API became a no-op, so we need to hack both of these
    # handlers to get it to work.
    def structured_log_adapter(level, fields, field_count, user_data):
        # Don't even format the message if it will be discarded
        py_logging_level = levels.get(level, logging.WARNING)
        if log.isEnabledFor(py_logging_level):
            # at least glib 2.52 log_writer_format_fields can raise on win32
            try:
                message = GLib.log_writer_format_fields(level, fields, True)
                if not silence(message):
                    log.log(py_logging_level, message)
            except Exception:
                GLib.log_writer_standard_streams(level, fields, user_data)
        return GLib.LogWriterOutput.HANDLED

    try:
        GLib.log_set_writer_func(structured_log_adapter, None)
    except AttributeError:
        # Only present in glib 2.50+
        pass


def environment_hacks():
    # MSYSTEM is set by git, and confuses our
    # msys-packaged version's library search path -
    # for frozen build the lib subdirectory is excluded.
    # workaround it by adding as first path element.
    # This may confuse vc utils run from meld
    # but otherwise meld just crash on start, see #267

    global frozen
    if frozen and "MSYSTEM" in os.environ:
        lib_dir = os.path.join(get_meld_dir(), "lib")
        os.environ["PATH"] = lib_dir + os.pathsep + os.environ["PATH"]
    # We manage cwd ourselves for git operations, and GIT_DIR in particular
    # can mess with this when set.
    for var in ('GIT_DIR', 'GIT_WORK_TREE'):
        try:
            del os.environ[var]
        except KeyError:
            pass

    # Force the fontconfig backend for font fallback and metric handling
    if sys.platform == 'win32' and 'PANGOCAIRO_BACKEND' not in os.environ:
        os.environ['PANGOCAIRO_BACKEND'] = 'fontconfig'


def run_application():
    from meld.meldapp import MeldApp

    app = MeldApp()

    if sys.platform != 'win32':
        from gi.repository import GLib
        GLib.unix_signal_add(
            GLib.PRIORITY_DEFAULT, signal.SIGINT, lambda *args: app.quit())

    return app.run(sys.argv)


def main():
    environment_hacks()
    setup_logging()
    disable_stdout_buffering()
    check_requirements()
    setup_glib_logging()
    setup_resources()
    setup_settings()
    return run_application()


if __name__ == '__main__':
    sys.exit(main())
