init.py 4.12 KiB
# init.py -- Pamhyr
# Copyright (C) 2023  INRAE
#
# 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 3 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 <https://www.gnu.org/licenses/>.

# -*- coding: utf-8 -*-

import sys, os
import locale
import logging

from PyQt5.QtCore import QTranslator, QLibraryInfo

from tools import (
    reset_timers, display_timers, timer,
    logger_color_blue, logger_color_red, logger_color_green, logger_color_reset
)
from config import Config

from View.MainWindow import ApplicationWindow
from Model.Study import Study


# Configure logger

logging.basicConfig(
    level=logging.DEBUG,
    format=(f'[{logger_color_blue()}PAMHYR{logger_color_reset()}]' +
            f'[{logger_color_green()}%(levelname)s{logger_color_reset()}]' +
            ' %(message)s')
)
logger = logging.getLogger()
logger.setLevel(logging.INFO)

try:
    log = os.path.join(
        os.path.dirname(Config.filename()), "log.txt"
    )
    logfile = open(log, "w+")
    handler = logging.StreamHandler(logfile)
    formatter = logging.Formatter('[%(asctime)s][%(levelname)s] %(message)s')
    handler.setFormatter(formatter)
    handler.setLevel(logging.DEBUG)
    logger.addHandler(handler)
except:
    logger.error("Failed to create logfile...")


def legal_info():
    "Display in stdout Pamhyr infomation about licence and version"
    blue = lambda s: logger.info(f"{logger_color_blue()}{s}{logger_color_reset()}")

    blue("""`7MM\"""Mq.   db      `7MMM.     ,MMF'`7MMF'  `7MMF'`YMM'   `MM'`7MM\"""Mq.""")
    blue("""  MM   `MM. ;MM:       MMMb    dPMM    MM      MM    VMA   ,V    MM   `MM.""")
    blue("""  MM   ,M9 ,V^MM.      M YM   ,M MM    MM      MM     VMA ,V     MM   ,M9     pd*"*b.""")
    blue("""  MMmmdM9 ,M  `MM      M  Mb  M' MM    MMmmmmmmMM      VMMP      MMmmdM9     (O)   j8""")
    blue("""  MM      AbmmmqMA     M  YM.P'  MM    MM      MM       MM       MM  YM.         ,;j9""")
    blue("""  MM     A'     VML    M  `YM'   MM    MM      MM       MM       MM   `Mb.    ,-='""")
    blue(""".JMML. .AMA.   .AMMA..JML. `'  .JMML..JMML.  .JMML.   .JMML.   .JMML. .JMM.  Ammmmmmm""")

    with open(os.path.abspath(
            os.path.join(
                os.path.dirname(__file__),
                "VERSION"
            )
    ), "r") as f:
        version = f.readline().strip()
        logger.info(f"version:  {logger_color_green()}{version}{logger_color_reset()}")

    logger.info("license: pamhyr  Copyright (C) 2023  INRAE")
    logger.info("license: This program comes with ABSOLUTELY NO WARRANTY.")
    logger.info("license: This is free software, and you are welcome to redistribute it")
    logger.info("license: under certain conditions.")


def debug_info():
    py_version = sys.version.split("\n")[0]
    logger.debug(f"python: {py_version}")

    info = QLibraryInfo
    logger.debug(f"Qt PrefixPath: {info.location(QLibraryInfo.PrefixPath)}")
    logger.debug(f"Qt LibExecPath: {info.location(QLibraryInfo.LibraryExecutablesPath)}")

def setup_lang(app, conf:Config):
    "Return QTranslator configured for current language"
    lang_file = ""
    translator = QTranslator()

    if conf.lang == "":
        # System language
        sys_lang = locale.getdefaultlocale()
        if "fr" in sys_lang[0]:
            lang_file = os.path.dirname(__file__) + "/lang/fr.qm"
    elif conf.lang == "fr":
        # French
        lang_file = os.path.dirname(__file__) + "/lang/fr.qm"
    else:
        # English default language
        lang_file = ""

    if lang_file != "":
        logger.info(f"Load lang file: {lang_file}")
        ok = translator.load(lang_file)
        if not ok:
            logger.error("Failed to load translate file")

    return translator