ASubWindow.py 10.29 KiB
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 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414
# -*- coding: utf-8 -*-

import os
import csv

from io import StringIO

from tools import trace

from PyQt5.QtCore import Qt

from PyQt5.QtWidgets import (
    QMainWindow, QApplication, QDesktopWidget,
    QMdiArea, QMdiSubWindow, QDialog,
    QPushButton, QLineEdit, QCheckBox,
    QTimeEdit, QSpinBox, QTextEdit,
    QRadioButton, QComboBox, QFileDialog,
    QMessageBox, QTableView, QAction,
)
from PyQt5.QtCore import (
    QTime,
)
from PyQt5.uic import loadUi

from Model.Except import ClipboardFormatError

class WindowToolKit(object):
    def __init__(self, parent=None):
        super(WindowToolKit, self).__init__()

    def copyTableIntoClipboard(self, table):
        stream = StringIO()
        csv.writer(stream, delimiter='\t').writerows(table)
        QApplication.clipboard().setText(stream.getvalue())

    def parseClipboardTable(self):
        clip = QApplication.clipboard()
        mime = clip.mimeData()
        if 'text/plain' not in mime.formats():
            raise ClipboardFormatError(mime='text/plain')

        data = mime.data('text/plain').data().decode()
        has_header = csv.Sniffer().has_header(data)

        header = []
        values = []

        stream = StringIO(data)
        rows = csv.reader(stream, delimiter='\t')
        for l, row in enumerate(rows):
            if has_header and l == 0:
                header = row.copy()
                continue

            values.append(row)

        return header, values

    def file_dialog(self, select_file=True, callback=lambda x: None):
        """Open a new file dialog and send result to callback function

        Args:
            select_file: Select a file if True, else select a dir
            callback: The callback function with one arguments, files
                      selection list

        Returns:
            The returns of callback
        """
        dialog = QFileDialog(self)

        if select_file:
            mode = QFileDialog.FileMode.ExistingFile
        else:
            mode = QFileDialog.FileMode.Directory

        dialog.setFileMode(mode)

        if dialog.exec_():
            file_names = dialog.selectedFiles()
            return callback(file_names)

    def message_box(self, text: str,
                    informative_text: str,
                    window_title: str = "Warning"):
        """Open a new message box

        Args:
            text: Short text string
            informative_text: Verbose text string
            window_title: Title of message box window

        Returns:
            Nothing
        """
        msg = QMessageBox()

        msg.setIcon(QMessageBox.Warning)
        msg.setText(text)
        msg.setInformativeText(informative_text)
        msg.setWindowTitle(window_title)

        msg.exec_()


class ASubWindowFeatures(object):
    def __init__(self, parent=None):
        super(ASubWindowFeatures, self).__init__()

    # Commun use features

    def _qtype_from_component_name(self, name):
        qtype = None

        if "action" in name:
            qtype = QAction
        elif "lineEdit" in name:
            qtype = QLineEdit
        elif "pushButton" in name:
            qtype = QPushButton
        elif "radioButton" in name:
            qtype = QRadioButton
        elif "tableView" in name:
            qtype = QTableView

        return qtype

    def set_line_edit_text(self, name:str, text:str):
        """Set text of line edit component

        Args:
            line_edit: The line edit component name
            text: The text

        Returns:
            Nothing
        """
        try:
            self.find(QLineEdit, name).setText(text)
        except AttributeError as e:
            print(e)

    def get_line_edit_text(self, name:str):
        """Get text of line edit component

        Args:
            line_edit: The line edit component name

        Returns:
            Text
        """
        return self.find(QLineEdit, name).text()

    def set_text_edit_text(self, name:str, text:str):
        """Set text of text edit component

        Args:
            text_edit: The text edit component name
            text: The text

        Returns:
            Nothing
        """
        self.find(QTextEdit, name).setText(text)

    def get_text_edit_text(self, name:str):
        """Get text of text edit component

        Args:
            text_edit: The text edit component name

        Returns:
            Text
        """
        return self.find(QTextEdit, name).toHtml()

    def set_check_box(self, name:str, checked:bool):
        """Set status of checkbox component

        Args:
            name: The check box component name
            checked: Bool

        Returns:
            Nothing
        """
        self.find(QCheckBox, name).setChecked(checked)

    def get_check_box(self, name:str):
        """Get status of checkbox component

        Args:
            name: The check box component name

        Returns:
            Status of checkbox (bool)
        """
        return self.find(QCheckBox, name).isChecked()


    def set_time_edit(self, name:str, time:str):
        """Set time of timeedit component

        Args:
            name: The timeedit component name
            time: The new time in format "HH:mm:ss"

        Returns:
            Nothing
        """
        qtime = QTime.fromString(time)
        self.find(QTimeEdit, name).setTime(qtime)

    def get_time_edit(self, name:str):
        """Get time of timeedit component

        Args:
            name: The timeedit component name

        Returns:
            The time of timeedit in format "HH:mm:ss"
        """
        return self.find(QTimeEdit, name).time().toString()

    def set_spin_box(self, name:str, value:int):
        """Set value of spinbox component

        Args:
            name: The spinbox component name
            value: The new value

        Returns:
            Nothing
        """
        self.find(QSpinBox, name).setValue(value)

    def get_spin_box(self, name:str):
        """Get time of spin box component

        Args:
            name: The spin box component

        Returns:
            The value of spin box
        """
        return self.find(QSpinBox, name).value()

    def set_action_checkable(self, name:str, checked:bool):
        """Set value of action

        Args:
            name: The action component name
            value: The new value

        Returns:
            Nothing
        """
        self.find(QAction, name).setChecked(checked)

    def get_action_checkable(self, name:str):
        """Get status of action

        Args:
            name: The action component name

        Returns:
            The status of action
        """
        return self.find(QAction, name).isChecked()


    def set_push_button_checkable(self, name:str, checked:bool):
        """Set value of push button component

        Args:
            name: The push button component name
            value: The new value

        Returns:
            Nothing
        """
        self.find(QPushButton, name).setChecked(checked)

    def get_push_button_checkable(self, name:str):
        """Get status of push button

        Args:
            name: The push button component name

        Returns:
            The status of push button
        """
        return self.find(QPushButton, name).isChecked()

    def set_radio_button(self, name:str, checked:bool):
        """Set value of radio button component

        Args:
            name: The radio button component name
            checked: Checked

        Returns:
            Nothing
        """
        self.find(QRadioButton, name).setChecked(checked)

    def get_radio_button(self, name:str):
        """Get status of radio button

        Args:
            name: The radio button component name

        Returns:
            The status of radio button
        """
        return self.find(QRadioButton, name).isChecked()

    def combobox_add_item(self, name:str, item:str):
        """Add item in combo box

        Args:
            name: The combo box component name
            item: The item to add

        Returns:
            Nothing
        """
        self.find(QComboBox, name).addItem(item)

    def set_combobox_text(self, name:str, item:str):
        """Set current text of combo box

        Args:
            name: The combo box component name
            item: The item to add

        Returns:
            Nothing
        """
        self.find(QComboBox, name).setCurrentText(item)

    def get_combobox_text(self, name:str):
        """Get current text of combo box

        Args:
            name: The combo box component name

        Returns:
            Current text
        """
        return self.find(QComboBox, name).currentText()

# Top level interface

class ASubMainWindow(QMainWindow, ASubWindowFeatures, WindowToolKit):
    def __init__(self, name="", ui="dummy", parent=None):
        super(ASubMainWindow, self).__init__(parent=parent)
        self.ui = loadUi(
            os.path.join(os.path.dirname(__file__), "ui", f"{ui}.ui"),
            self
        )
        self.name = name
        self.parent = parent
        self.parent.sub_win_add(name, self)

    def closeEvent(self, event):
        if not self.parent is None:
            self.parent.sub_win_del(self.name)

    def find(self, qtype, name):
        """Find an ui component

        Args:
            qtype: Type of QT component
            name: Name for component

        Returns:
            return the component
        """
        if qtype is None:
            qtype = self._qtype_from_component_name(name)

        return self.ui.findChild(qtype, name)


class ASubWindow(QDialog, ASubWindowFeatures, WindowToolKit):
    def __init__(self, name="", ui="dummy", parent=None):
        super(ASubWindow, self).__init__(parent=parent)
        self.ui = loadUi(
            os.path.join(os.path.dirname(__file__), "ui", f"{ui}.ui"),
            self
        )
        self.name = name
        self.parent = parent
        self.parent.sub_win_add(name, self)

    def closeEvent(self, event):
        if not self.parent is None:
            self.parent.sub_win_del(self.name)

    def find(self, qtype, name):
        """Find an ui component

        Args:
            qtype: Type of QT component
            name: Name for component

        Returns:
            return the component
        """
        if qtype is None:
            qtype = self._qtype_from_component_name(name)

        return self.ui.findChild(qtype, name)