sbk.gui

src/sbk/gui.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#!/usr/bin/env python3
# This file is part of the SBK project
# https://github.com/mbarkhau/sbk
#
# Copyright (c) 2019-2021 Manuel Barkhau (mbarkhau@gmail.com) - MIT License
# SPDX-License-Identifier: MIT

# type: ignore

"""GUI for SBK.

PyQT docs:
- https://realpython.com/python-pyqt-gui-calculator/
- https://zetcode.com/gui/pyqt5/
"""
import os
import sys
import typing as typ
import logging

import PyQt5.Qt as qt
import PyQt5.QtGui as qtg
import PyQt5.QtWidgets as qtw

from . import gui_panels as gp
from . import gui_panels_base as gpb

logger = logging.getLogger("sbk.gui")


class MainGUI(qtw.QStackedWidget):
    def __init__(self) -> None:
        super().__init__()

        self.setWindowTitle("SBK")
        self.setWindowIcon(qtg.QIcon(str(gp.ICON_PATH)))
        self.setFixedSize(1000, 1000)
        x, y = map(int, os.getenv('SBK_WIN_OFFSET', "200x200").split("x"))
        self.setGeometry(x, y, 800, 600)

        select_command_panel = gp.SelectCommandPanel(0)
        self.addWidget(select_command_panel)
        select_command_panel.switch()

    def get_or_init_panel(self, clazz: typ.Type[gpb.Panel]) -> gpb.Panel:
        _panel      = self.findChild(clazz)
        maybe_panel = typ.cast(typ.Optional[gpb.Panel], _panel)
        if maybe_panel is None:
            logger.info(f"get_or_init_panel init: {clazz.__name__}")
            index = self.count()
            panel = clazz(index)
            self.addWidget(panel)
            return panel
        else:
            logger.info(f"get_or_init_panel get : {clazz.__name__}")
            return maybe_panel

    def keyPressEvent(self, e):
        val     = e.key()
        mod     = e.modifiers()
        is_ctrl = mod & qt.Qt.ControlModifier
        is_alt  = mod & qt.Qt.AltModifier
        if val == qt.Qt.Key_Q and (is_ctrl or is_alt):
            self.close()


def _screen_size(app: qtw.QApplication) -> typ.Tuple[int, int]:
    screen = app.primaryScreen()
    size   = screen.size()
    return (size.width(), size.height())


def gui() -> None:
    app = qtw.QApplication([])
    # w, h = _screen_size(app)

    sbk_dialog = MainGUI()
    sbk_dialog.show()
    app.exec()
    sys.exit()


def selftest() -> None:
    import sbk.cli

    sbk.cli._configure_logging(verbosity=2)
    gui()


if __name__ == '__main__':
    selftest()