Esempio n. 1
0
    def read_time(self):

        self.time_start = min(
            [self.sygnals[i].x_data[0] for i in range(len(self.sygnals))])
        self.time_fin = max(
            [self.sygnals[i].x_data[-1] for i in range(len(self.sygnals))])

        time_str = 'от ' + mk_to_str(self.time_start) + ' до ' + mk_to_str(
            self.time_fin)
        labelT = "Введите интервал для отбора по времени:"
        while True:
            dlg = QInputDialog(self)
            dlg.setInputMode(QInputDialog.TextInput)
            dlg.setWindowTitle("Установка времени отбора")
            dlg.setLabelText(labelT)
            dlg.resize(500, 200)
            dlg.setTextValue(time_str)
            ok = dlg.exec_()
            if not (ok):
                break
            time_str2 = dlg.textValue()
            try:
                time_start, time_fin = time_str2.split(
                    ' ')[1], time_str2.split(' ')[3]
                time_start, time_fin = str_to_mkt([time_start, time_fin])

                time_start, time_fin = time_start + 3600 * 3, time_fin + 3600 * 3

            except Exception:
                labelT = "Неверный формат ввода, повторите:"
                dlg.setTextValue(time_str)
            else:
                break

        self.selection_by_time(time_start, time_fin)
Esempio n. 2
0
    def select_btn(self):
        self.full_values()
        self.time_start = self.vertical_headers[0]
        self.time_fin = self.vertical_headers[-1]


        time_str = 'от '+ mk_to_str(self.time_start) + ' до ' + mk_to_str(self.time_fin)
        labelT = "Введите интервал для отбора по времени:"
        while True:
            dlg = QInputDialog(self)
            dlg.setInputMode(QInputDialog.TextInput)
            dlg.setWindowTitle("Установка времени отбора")
            dlg.setLabelText(labelT)
            dlg.resize(500,200)
            dlg.setTextValue(time_str)
            ok = dlg.exec_()
            if not(ok):
                break
            time_str2 = dlg.textValue()
            try:
                time_start,time_fin = time_str2.split(' ')[1],time_str2.split(' ')[3]
                time_start,time_fin = str_to_mkt(time_start),str_to_mkt(time_fin)

                self.time_start,self.time_fin = time_start+3600*3,time_fin+3600*3

            except Exception:
                labelT = "Неверный формат ввода, повторите:"
                dlg.setTextValue(time_str)
            else:
                break
        self.select_by_time()
Esempio n. 3
0
 def ask_for_password(self):
     input_dlg = QInputDialog(parent=self)
     input_dlg.setTextEchoMode(QLineEdit.Password)
     input_dlg.setWindowTitle("Enter WebREPL password")
     input_dlg.setLabelText("Password")
     input_dlg.resize(500, 100)
     input_dlg.exec()
     return input_dlg.textValue()
Esempio n. 4
0
    def ask_for_password(self, title, label="Password"):
        if self._preset_password is not None:
            return self._preset_password

        input_dlg = QInputDialog(parent=self, flags=Qt.Dialog)
        input_dlg.setTextEchoMode(QLineEdit.Password)
        input_dlg.setWindowTitle(title)
        input_dlg.setLabelText(label)
        input_dlg.resize(500, 100)
        input_dlg.exec()
        return input_dlg.textValue()
Esempio n. 5
0
 def on_action_save_configuration_as_triggered(self):
     text = _("Save configuration as...")
     if self.tabframe.about_to_change(text):
         dlg = QInputDialog(self)
         dlg.setInputMode(QInputDialog.TextInput)
         dlg.setWindowTitle(text)
         dlg.setLabelText(_("Configuration name:"))
         dlg.setTextValue(self.paras.configuration_name())
         dlg.resize(300, 100)
         if dlg.exec_():
             self.ctrl.save_configuration_as(dlg.textValue())
Esempio n. 6
0
def intes():
    try:
        dialog = QInputDialog()
        dialog.resize(QtCore.QSize(700, 100))
        ID_Sito = dialog.getText(
            None, 'Intestazione',
            "Aggiungi una intestazione al tuo diagramma stratigrafico")
        Sito = str(ID_Sito[0])
        return Sito
    except KeyError as e:
        print(str(e))
Esempio n. 7
0
 def addRow(self):
     dlg = QInputDialog(self)
     dlg.setInputMode(QInputDialog.TextInput)
     dlg.setLabelText("Channel:")
     dlg.resize(500, 100)
     ok = dlg.exec_()
     pv = dlg.textValue()
     #pv, ok = QInputDialog.getText(self, "Input", "Enter channel")
     if ok:
         print(pv)
         self.parent.addPv(pv)
Esempio n. 8
0
    def ask_for_password(self, title, label="Password"):
        if self._preset_password is not None:
            return self._preset_password

        input_dlg = QInputDialog(parent=self, flags=Qt.Dialog)
        input_dlg.setTextEchoMode(QLineEdit.Password)
        input_dlg.setWindowTitle(title)
        input_dlg.setLabelText(label)
        input_dlg.resize(500, 100)
        input_dlg.exec()
        return input_dlg.textValue()
Esempio n. 9
0
 def handle_doubleClickTab(self, index):
     """Edit Application name, tab only, the dictinary key remains unchanged"""
     old_name = self.ApplicationtabWidget.tabText(index)
     dlg = QInputDialog(self)
     dlg.setWindowTitle("Change Application Name")
     dlg.setLabelText("New Application Name:")
     dlg.setTextValue(old_name)
     dlg.resize(400, 100)
     success = dlg.exec()
     new_tab_name = dlg.textValue()
     if (success and new_tab_name != ""):
         self.ApplicationtabWidget.setTabText(index, new_tab_name)
Esempio n. 10
0
def inputTextCustom(title='No title',
                    label='Input',
                    text='',
                    width=500,
                    height=200,
                    parent=None):
    dlg = QInputDialog(parent)
    dlg.setInputMode(QInputDialog.TextInput)
    dlg.setLabelText(label)
    dlg.setTextValue(text)
    dlg.resize(width, height)
    dlg.exec_()
    return dlg.textValue()
Esempio n. 11
0
 def on_click_saveFacebookID(self):
     FacebookIDValue = readConfig('notify', 'facebookID', 'config.ini')
     inputbox = QInputDialog(self)
     inputbox.setWindowTitle('Facebook ID')
     inputbox.setInputMode(QInputDialog.TextInput)
     inputbox.setLabelText('Input Facebook ID')
     inputbox.setTextValue(FacebookIDValue)
     inputbox.resize(250, 100)
     ok = inputbox.exec_()
     FacebookID = inputbox.textValue()
     if ok:
         saveConfig('notify', 'facebookID', FacebookID, 'config.ini')
     else:
         pass
Esempio n. 12
0
 def on_click_saveLineToken(self):
     LineValue = readConfig('notify', 'tokenline', 'config.ini')
     inputbox = QInputDialog(self)
     inputbox.setWindowTitle('Line token')
     inputbox.setInputMode(QInputDialog.TextInput)
     inputbox.setLabelText('Input Line token')
     inputbox.setTextValue(LineValue)
     inputbox.resize(400, 100)
     ok = inputbox.exec_()
     lineToken = inputbox.textValue()
     if ok:
         saveConfig('notify', 'tokenline', lineToken, 'config.ini')
     else:
         pass
Esempio n. 13
0
    def handle_thTabBarDoubleClicked(self, index):
        """Edit Theory name

        Edit the theory tab name, leave 'theories' dictionary keys unchanged.
        Two tabs can share the same name"""
        old_name = self.TheorytabWidget.tabText(index)
        dlg = QInputDialog(self)
        dlg.setWindowTitle("Change Theory Name")
        dlg.setLabelText("New Theory Name:")
        dlg.setTextValue(old_name)
        dlg.resize(400, 100)
        success = dlg.exec()
        new_tab_name = dlg.textValue()
        if success and new_tab_name != "":
            self.TheorytabWidget.setTabText(index, new_tab_name)
Esempio n. 14
0
 def newWorkspaceClicked(self):
     dlg = QInputDialog(self.ui)
     dlg.setInputMode(QInputDialog.TextInput)
     dlg.setLabelText(self._tr("Workspace name:"))
     dlg.resize(rt(300), rt(100))
     ok = dlg.exec_()
     name = dlg.textValue()
     if ok:
         try:
             workspace = workspace_service.createWorkspace(name)
             self.onWorkspaceChanged(workspace_name=workspace.name)
             self.loadWorkspaces()
         except WorkspaceAlreadyExistsException:
             message_utils.error(
                 self._tr('Workspace already exists'),
                 self._tr('Please choose a different workspace\'s name'))
Esempio n. 15
0
def reverse():
    '''return true or false about the order epoch  '''
    try:
        dialog = QInputDialog()
        dialog.resize(QtCore.QSize(700, 100))
        ID_rev = dialog.getText(
            None, 'Ordinamento',
            "Scrivi true se il Periodo 1 corrisponde all'utima epoca scavata.\n Altrimeti lascia vuoto e clicca 'ok'"
        )
        rev = str(ID_rev[0])
        if rev == 'true':
            return 1
        else:
            return 0
    except KeyError as e:
        print(str(e))
Esempio n. 16
0
    def new(self):
        row = self.listWidget.currentRow()

        inputDialog = QInputDialog()
        inputDialog.setWindowIcon(QIcon(ICON))
        inputDialog.setWindowTitle("New Clause"), inputDialog.setLabelText("Enter a new clause")
        inputDialog.setInputMode(QInputDialog.TextInput)
        inputDialog.setFont(DIALOG_FONT)
        inputDialog.resize(500, 0)

        ok = inputDialog.exec_()
        text = inputDialog.textValue()

        if ok and text is not None:
            self.listWidget.insertItem(row + 1, text)
            self.listWidget.setCurrentRow(row + 1)
Esempio n. 17
0
def ask_root_password(context: ApplicationContext, i18n: I18n, app_config: dict = None) -> Tuple[str, bool]:

    cur_config = read_config() if not app_config else app_config
    store_password = bool(cur_config['store_root_password'])

    if store_password and context.root_password and validate_password(context.root_password):
        return context.root_password, True

    diag = QInputDialog()
    diag.setStyleSheet("""QLineEdit {  border-radius: 5px; font-size: 16px; border: 1px solid lightblue }""")
    diag.setInputMode(QInputDialog.TextInput)
    diag.setTextEchoMode(QLineEdit.Password)
    diag.setWindowIcon(util.get_default_icon()[1])
    diag.setWindowTitle(i18n['popup.root.title'])
    diag.setLabelText('')
    diag.setOkButtonText(i18n['popup.root.continue'].capitalize())
    diag.setCancelButtonText(i18n['popup.button.cancel'].capitalize())
    diag.resize(400, 200)

    for attempt in range(3):

        ok = diag.exec_()

        if ok:
            if not validate_password(diag.textValue()):

                body = i18n['popup.root.bad_password.body']

                if attempt == 2:
                    body += '. ' + i18n['popup.root.bad_password.last_try']

                show_message(title=i18n['popup.root.bad_password.title'],
                             body=body,
                             type_=MessageType.ERROR)
                ok = False
                diag.setTextValue('')

            if ok:
                if store_password:
                    context.root_password = diag.textValue()

                return diag.textValue(), ok
        else:
            break

    return '', False
Esempio n. 18
0
    def edit_nickname(parent):
        s = settings.Setting_Custom_General_NICKNAME

        dialog = QInputDialog(parent)
        dialog.setInputMode(QInputDialog.TextInput)
        dialog.setWindowTitle(_translate("SettingsDialogNickname", "Edit Nickname"))
        dialog.setLabelText(_translate("SettingsDialogNickname", "New nickname:"))
        dialog.resize(400, 0)
        dialog.setTextValue(s.value)

        ok = dialog.exec_()
        txt = dialog.textValue()

        if ok:
            if txt:
                s.value = txt
            else:
                s.reset()
Esempio n. 19
0
    def edit(self):
        row = self.listWidget.currentRow()
        item = self.listWidget.item(row)

        if item is not None:
            inputDialog = QInputDialog()
            inputDialog.setWindowIcon(QIcon(ICON))
            inputDialog.setWindowTitle("Edit Clause"), inputDialog.setLabelText("Edit clause")
            inputDialog.setInputMode(QInputDialog.TextInput)
            inputDialog.setTextValue(item.text())
            inputDialog.setFont(DIALOG_FONT)
            inputDialog.resize(500, 0)

            ok = inputDialog.exec_()
            string = inputDialog.textValue()

            if ok and string is not None:
                item.setText(string)
Esempio n. 20
0
def ask_root_password(locale_keys: dict):

    dialog_pwd = QInputDialog()
    dialog_pwd.setInputMode(QInputDialog.TextInput)
    dialog_pwd.setTextEchoMode(QLineEdit.Password)
    dialog_pwd.setWindowTitle(locale_keys['popup.root.title'])
    dialog_pwd.setLabelText(locale_keys['popup.root.password'] + ':')
    dialog_pwd.setCancelButtonText(locale_keys['popup.button.cancel'])
    dialog_pwd.resize(400, 200)

    ok = dialog_pwd.exec_()

    if ok:
        if not validate_password(dialog_pwd.textValue()):
            show_error(title=locale_keys['popup.root.bad_password.title'],
                       body=locale_keys['popup.root.bad_password.body'])
            ok = False

    return dialog_pwd.textValue(), ok
Esempio n. 21
0
    def set_cursor(self):
        time_str = mk_to_str(
            max([self.sygnals[i].x_data[-1]
                 for i in range(len(self.sygnals))]))
        labelT = "Выберите время для установки курсора:"
        while True:
            dlg = QInputDialog(self)
            dlg = QInputDialog(self)
            dlg.setInputMode(QInputDialog.TextInput)
            dlg.setWindowTitle("Установка курсора")
            dlg.setLabelText(labelT)
            dlg.resize(500, 200)
            dlg.setTextValue(time_str)
            ok = dlg.exec_()
            if not (ok):
                break
            else:
                cursor_time_str = dlg.textValue()
                try:
                    cursor_time = str_to_mkt([cursor_time_str])[0] + 3600 * 3
                except Exception:
                    labelT = "Неверный формат ввода, повторите:"
                    dlg.setTextValue(time_str)
                else:
                    self.cursor = self.cursor_by_value(cursor_time)
                    break

        for i in range(len(self.sygnals)):
            sygnal = self.sygnals[i]
            try:
                cursor_value_i = sygnal.x_data.index(cursor_time + 3600 * 3)
            except Exception:
                k = 1
                while k < (len(sygnal.x_data)
                           ) and cursor_time + 3600 * 3 < sygnal.x_data[k]:
                    k += 1
                cursor_value_i = k - 1

            cursor_value = sygnal.y_data[cursor_value_i]
            self.legend_table.setItem(i, 7,
                                      QTableWidgetItem(str(cursor_value)))
Esempio n. 22
0
File: root.py Progetto: jayvdb/bauh
def ask_root_password(locale_keys: dict):

    diag = QInputDialog()
    diag.setInputMode(QInputDialog.TextInput)
    diag.setTextEchoMode(QLineEdit.Password)
    diag.setWindowIcon(QIcon(resource.get_path('img/lock.svg')))
    diag.setWindowTitle(locale_keys['popup.root.title'])
    diag.setLabelText(locale_keys['popup.root.password'] + ':')
    diag.setCancelButtonText(locale_keys['popup.button.cancel'])
    diag.resize(400, 200)

    ok = diag.exec_()

    if ok:
        if not validate_password(diag.textValue()):
            show_message(title=locale_keys['popup.root.bad_password.title'],
                         body=locale_keys['popup.root.bad_password.body'],
                         type_=MessageType.ERROR)
            ok = False

    return diag.textValue(), ok
Esempio n. 23
0
def ask_root_password(i18n: I18n):
    diag = QInputDialog()
    diag.setStyleSheet(
        """QLineEdit {  border-radius: 5px; font-size: 16px; border: 1px solid lightblue }"""
    )
    diag.setInputMode(QInputDialog.TextInput)
    diag.setTextEchoMode(QLineEdit.Password)
    diag.setWindowIcon(QIcon(resource.get_path('img/lock.png')))
    diag.setWindowTitle(i18n['popup.root.title'])
    diag.setLabelText('')
    diag.setOkButtonText(i18n['popup.root.continue'].capitalize())
    diag.setCancelButtonText(i18n['popup.button.cancel'].capitalize())
    diag.resize(400, 200)

    for attempt in range(3):

        ok = diag.exec_()

        if ok:
            if not validate_password(diag.textValue()):

                body = i18n['popup.root.bad_password.body']

                if attempt == 2:
                    body += '. ' + i18n['popup.root.bad_password.last_try']

                show_message(title=i18n['popup.root.bad_password.title'],
                             body=body,
                             type_=MessageType.ERROR)
                ok = False
                diag.setTextValue('')

            if ok:
                return diag.textValue(), ok
        else:
            break

    return '', False
Esempio n. 24
0
    def start_dropbox(self, url):

        click_url = QLabel()
        click_url.setTextFormat(Qt.RichText)
        click_url.setTextInteractionFlags(Qt.TextBrowserInteraction)
        click_url.setTextInteractionFlags(Qt.LinksAccessibleByMouse)
        click_url.setOpenExternalLinks(True)
        click_url.setText(
            '1. Go to: <a target="_blank" href="{}">Dropbox Authentication Link</a><br>'
            '2. Click "Allow" (you might have to log in first)<br>'
            '3. Copy the authorization code.<br><br>'
            'Enter the authorization code here: '.format(url))

        dlg = QInputDialog(self.notes[0])
        dlg.setWindowTitle('Dropbox Authorization')
        dlg.setInputMode(QInputDialog.TextInput)
        dlg.setLabelText(click_url.text())
        dlg.resize(500, 50)

        screenGeometry = self.app.desktop().screenGeometry()
        x = (screenGeometry.width() - dlg.width()) / 2
        y = (screenGeometry.height() - dlg.height()) / 2
        dlg.move(x, y - 100)

        ok = dlg.exec_()
        code = dlg.textValue()

        if ok:
            for m in self.notes:
                m.updateStatusBar('Connecting ...')

            c = self.dropbox.connect(FIRST_TIME, code)

            if c == 0:
                reply = QMessageBox.question(
                    self.notes[0], 'Note Addition',
                    "Current notes will be closed. Do you want to continue?",
                    QMessageBox.Yes | QMessageBox.No, QMessageBox.No)

                if reply == QMessageBox.Yes:
                    self.closeCurrentNotes(0)
                    self.dropbox.startBG_Dropbox_Thread()
                else:
                    self.LogFile(
                        "CONTROLLER: start_dropbox. Connection cancelled")
                    for m in self.notes:
                        m.updateStatusBar('Connection cancelled')

                    self.dropbox.client = None
                    return False
            else:
                for m in self.notes:
                    m.updateStatusBar('Failed connection to Dropbox')

                self.dropbox.client = None
                return False

        else:
            for m in self.notes:
                m.updateStatusBar('Connection cancelled')

            self.dropbox.client = None
            return False

        return True
Esempio n. 25
0
def ask_root_password(context: ApplicationContext,
                      i18n: I18n,
                      app_config: dict = None) -> Tuple[str, bool]:

    cur_config = read_config() if not app_config else app_config
    store_password = bool(cur_config['store_root_password'])

    if store_password and context.root_password and validate_password(
            context.root_password):
        return context.root_password, True

    diag = QInputDialog(flags=Qt.CustomizeWindowHint | Qt.WindowTitleHint)
    diag.setStyleSheet(
        """QLineEdit {  border-radius: 5px; font-size: 16px; border: 1px solid lightblue }"""
    )
    diag.setInputMode(QInputDialog.TextInput)
    diag.setTextEchoMode(QLineEdit.Password)
    diag.setWindowIcon(util.get_default_icon()[1])
    diag.setWindowTitle(i18n['popup.root.title'])
    diag.setLabelText('')
    diag.setOkButtonText(i18n['popup.root.continue'].capitalize())
    diag.setCancelButtonText(i18n['popup.button.cancel'].capitalize())

    bt_box = [c for c in diag.children() if isinstance(c, QDialogButtonBox)][0]

    for bt in bt_box.buttons():
        if bt_box.buttonRole(bt) == QDialogButtonBox.AcceptRole:
            bt.setStyleSheet(css.OK_BUTTON)

        bt.setCursor(QCursor(Qt.PointingHandCursor))
        bt.setIcon(QIcon())

    diag.resize(400, 200)

    for attempt in range(3):

        ok = diag.exec_()

        if ok:
            if not validate_password(diag.textValue()):

                body = i18n['popup.root.bad_password.body']

                if attempt == 2:
                    body += '. ' + i18n['popup.root.bad_password.last_try']

                show_message(title=i18n['popup.root.bad_password.title'],
                             body=body,
                             type_=MessageType.ERROR)
                ok = False
                diag.setTextValue('')

            if ok:
                if store_password:
                    context.root_password = diag.textValue()

                return diag.textValue(), ok
        else:
            break

    return '', False
Esempio n. 26
0
class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        # needed variable
        self.db_connection = None
        self.setup_working_folder()
        self.buttonCalledAction = None

        # Main body
        self.bodyQVBoxLayout = QVBoxLayout()
        self.body = QWidget()

        # -----------------
        # Header
        self.headerQHBoxLayout = QHBoxLayout()
        self.header = QWidget()
        self.headerQHBoxLayout.setSpacing(10)
        self.headerQHBoxLayout.setContentsMargins(20, 11, 20, 11)

        # Add Book Button
        self.addBookQButton = QPushButton()
        ColorsRegulator().set_icon_color(self.addBookQButton,
                                         'design/images/add.png',
                                         'design/images/night/night_add.png')
        self.addBookQButton.setIconSize(QSize(24, 24))
        self.addBookQButton.setFocusPolicy(Qt.NoFocus)

        # Line-Delimiter
        self.lineDelimiterFrame = QFrame()
        self.lineDelimiterFrame.setFrameShape(QFrame.VLine)
        self.lineDelimiterFrame.setFrameShadow(QFrame.Sunken)

        # Remove Book Button
        self.removeBookQButton = QPushButton()
        ColorsRegulator().set_icon_color(
            self.removeBookQButton, 'design/images/removeBook.png',
            'design/images/night/night_removeBook.png')
        self.removeBookQButton.setIconSize(QSize(24, 24))
        self.removeBookQButton.setFocusPolicy(Qt.NoFocus)

        # Add Book TO Category Button
        self.addToCategoryQButton = QPushButton()
        ColorsRegulator().set_icon_color(self.addToCategoryQButton,
                                         'design/images/plus.png',
                                         'design/images/night/night_plus.png')
        self.addToCategoryQButton.setIconSize(QSize(24, 24))
        self.addToCategoryQButton.setFocusPolicy(Qt.NoFocus)

        # Remove book from category Button
        self.removeFromCategoryQButton = QPushButton()
        ColorsRegulator().set_icon_color(
            self.removeFromCategoryQButton, 'design/images/minus.png',
            'design/images/night/night_minus.png')
        self.removeFromCategoryQButton.setIconSize(QSize(24, 24))
        self.removeFromCategoryQButton.setFocusPolicy(Qt.NoFocus)

        # Search Bar
        self.searchBar = QLineEdit()
        self.searchBar.setClearButtonEnabled(True)
        self.searchBar.setFocusPolicy(Qt.ClickFocus)
        self.searchBar.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)

        # Settings
        self.settingsQButton = QPushButton()
        ColorsRegulator().set_icon_color(
            self.settingsQButton, 'design/images/settings.png',
            'design/images/night/night_settings.png')
        self.settingsQButton.setIconSize(QSize(32, 32))
        self.settingsQButton.setFocusPolicy(Qt.NoFocus)

        # -----------------
        # Container
        self.containerQHBoxLayout = QHBoxLayout()
        self.container = QWidget()
        self.containerQHBoxLayout.setContentsMargins(20, 20, 20, 40)
        self.containerQHBoxLayout.setSpacing(0)

        # Side Bar
        self.sideBar = QWidget()
        self.sideBarQVBoxLayout = QVBoxLayout()
        self.sideBarQVBoxLayout.setContentsMargins(0, 10, 0, 0)

        # Library Label
        self.libLabel = QLabel()
        self.libLabel.setAlignment(Qt.AlignCenter)

        # Context menu
        self.context_menu = QMenu()
        self.open_act = self.context_menu.addAction('')
        self.edit_act = self.context_menu.addAction('')
        self.delete_act = self.context_menu.addAction('')

        # Context menu for table
        self.context_table_menu = QMenu()
        self.open_book_action = self.context_table_menu.addAction('')
        self.context_table_menu.addSeparator()
        self.add_book_to_lib_action = self.context_table_menu.addAction('')
        self.remove_book_from_lib_action = self.context_table_menu.addAction(
            '')
        self.context_table_menu.addSeparator()
        self.rename_book_action = self.context_table_menu.addAction('')
        self.rete_book_action = self.context_table_menu.addAction('')
        self.delete_book_action = self.context_table_menu.addAction('')

        self.set_context_menu_styles()

        # Categories
        self.categoriesQWidget = QWidget()
        self.categoriesQVBoxLayout = QVBoxLayout()
        self.categoriesQVBoxLayout.setContentsMargins(0, 20, 0, 0)
        self.categoriesQVBoxLayout.setSpacing(0)

        # Categories buttons
        self.categories = []
        self.allQButton = QPushButton()
        self.favouritesQButton = QPushButton()

        # Create Category Button
        self.createCategoryQButton = QPushButton()

        # Create Category Dialog
        self.categoryQDialog = QInputDialog()
        self.categoryQDialog.setInputMode(QInputDialog.TextInput)
        self.categoryQDialog.setWindowIcon(QIcon('design/images/icon.ico'))
        self.categoryQDialog.resize(600, 480)
        ColorsRegulator().set_colors(self.categoryQDialog,
                                     styles.Styles.set_dialog_style,
                                     night_styles.NightStyles.set_dialog_style)
        localize.set_add_category_localization(self.categoryQDialog)

        # Content
        self.content = QWidget()
        self.contentQVBoxLayout = QVBoxLayout()
        self.contentQVBoxLayout.setContentsMargins(0, 0, 0, 0)

        # Category title in Content
        self.categoryQLabel = QLabel()
        self.categoryQLabel.setAlignment(Qt.AlignCenter)

        # Table
        self.table = QTableWidget()
        self.table.setColumnCount(7)

        # ScrollBar in Table
        self.tableScrollBar = QScrollBar()
        self.table.setVerticalScrollBar(self.tableScrollBar)
        self.table.setFocusPolicy(Qt.NoFocus)
        self.table.setEditTriggers(QAbstractItemView.NoEditTriggers)

        # Main run
        self.init_body()

        # Settings window
        self.sett_menu = None

    @staticmethod
    def connect_to_db():
        """
        Method creates a connection to database
        :return: Connection object
        """
        path_to_db = os.path.expanduser("~/Documents/LNUReader")
        if not os.path.exists(path_to_db):
            os.makedirs(path_to_db)
        return db.create_connection(path_to_db + r'\ReaderDatabase.db')

    def init_header(self):
        self.headerQHBoxLayout.addWidget(self.addBookQButton)
        self.headerQHBoxLayout.addWidget(self.removeBookQButton)
        self.headerQHBoxLayout.addWidget(self.lineDelimiterFrame)
        self.headerQHBoxLayout.addWidget(self.addToCategoryQButton)
        self.headerQHBoxLayout.addWidget(self.removeFromCategoryQButton)
        self.headerQHBoxLayout.addStretch()
        self.headerQHBoxLayout.addWidget(self.searchBar)
        self.headerQHBoxLayout.addWidget(self.settingsQButton)
        self.header.setLayout(self.headerQHBoxLayout)

    def init_categories(self):
        self.set_category_button_options(self.allQButton)
        self.set_category_button_options(self.favouritesQButton)
        self.categoriesQVBoxLayout.addWidget(self.allQButton)
        self.categoriesQVBoxLayout.addWidget(self.favouritesQButton)
        user_categories = [
            x[0] for x in db.select_all_data(self.db_connection, "library")[1:]
        ]
        for ctg in user_categories:
            added_button = QPushButton(ctg)
            self.set_category_button_options(added_button)
            self.categoriesQVBoxLayout.addWidget(added_button)
        self.categoriesQWidget.setLayout(self.categoriesQVBoxLayout)

    def init_sidebar(self):
        self.init_categories()
        self.sideBarQVBoxLayout.addWidget(self.libLabel)
        self.sideBarQVBoxLayout.addWidget(self.categoriesQWidget)
        self.sideBarQVBoxLayout.addStretch()
        self.sideBarQVBoxLayout.addWidget(self.createCategoryQButton)
        self.sideBar.setLayout(self.sideBarQVBoxLayout)

    def init_table(self):
        header = self.table.horizontalHeader()
        self.table.setColumnHidden(6, True)
        self.table.verticalHeader().setVisible(False)
        self.table.setShowGrid(False)
        header.setSectionResizeMode(QHeaderView.Fixed)
        header.setHighlightSections(False)
        header.setSectionResizeMode(0, QHeaderView.Stretch)
        header.setSectionResizeMode(1, QHeaderView.Stretch)
        header.resizeSection(2, 120)
        header.resizeSection(3, 120)
        header.resizeSection(4, 80)
        header.resizeSection(5, 50)

    def init_content(self):
        self.init_table()
        self.contentQVBoxLayout.addWidget(self.categoryQLabel)
        self.contentQVBoxLayout.addWidget(self.table)
        self.content.setLayout(self.contentQVBoxLayout)

    def init_container(self):
        self.init_sidebar()
        self.init_content()
        self.containerQHBoxLayout.addWidget(self.sideBar)
        self.containerQHBoxLayout.addWidget(self.content)
        self.container.setLayout(self.containerQHBoxLayout)

    def init_body(self):
        self.init_header()
        self.init_container()
        self.bodyQVBoxLayout.addWidget(self.header)
        self.bodyQVBoxLayout.addWidget(self.container)
        self.body.setLayout(self.bodyQVBoxLayout)
        self.setCentralWidget(self.body)

    def setup_working_folder(self):
        """
        Checks existence of all necessary files in
        C:/Users/User/Documents/LNUReader
        and opens connection to database.
        If any of files/folder are missing, creates a default/empty ones.
        :return: None
        """
        self.check_folder()
        self.db_connection = self.connect_to_db()
        db.create_db(self.db_connection)
        self.check_json()

    def set_category_button_options(self, category_button):
        ColorsRegulator().set_colors(
            category_button, styles.Styles.set_category_button_styles,
            night_styles.NightStyles.set_category_button_styles)
        category_button.setFocusPolicy(Qt.ClickFocus)
        category_button.setContextMenuPolicy(Qt.CustomContextMenu)
        category_button.customContextMenuRequested.connect(
            self.on_context_menu)
        if category_button not in self.categories:
            self.categories.append(category_button)
        category_button.clicked.connect(self.category_button_clicked)

    def on_context_menu(self, point):
        """
        Method that show context menu when user does right mouse click on category.
        :param point: cursor coordinates
        :return: None
        """
        self.buttonCalledAction = self.sender()
        if not self.is_standard_category():
            self.delete_act.setEnabled(True)
            self.edit_act.setEnabled(True)
        else:
            self.delete_act.setEnabled(False)
            self.edit_act.setEnabled(False)
        self.context_menu.exec_(self.buttonCalledAction.mapToGlobal(point))

    def is_standard_category(self):
        """
        Method checks if right clicked category is standard (All + Favourites).
        :return: boolean
        """
        return self.buttonCalledAction in [
            button for button in self.categories[:2]
        ]

    @staticmethod
    def check_folder():
        """
        Method checks if the folder with database and settings file exists.
        If it doesn't, creates one.
        :return: None
        """
        folder_path = os.path.expanduser("~/Documents/LNUReader")
        if not os.path.exists(folder_path):
            os.makedirs(folder_path)

    def check_json(self):
        """
        Method checks if file with settings exists.
        If not, creates a default one.
        :return: None
        """
        settings_path = (
            os.path.expanduser("~/Documents/LNUReader/settings.json"))
        if not os.path.exists(settings_path):
            self.create_default_json()

    @staticmethod
    def create_default_json():
        """
        Creates a json file with default settings.
        :return: None
        """
        settings = {"language": "EN", "color mode": "White"}
        with open(os.path.expanduser("~/Documents/LNUReader/settings.json"),
                  'w') as outfile:
            json.dump(settings, outfile)

    def reload_book_section(self, category):
        """
        Clears the table with books and fills it
        with books corresponding to the category pressed.

        :param category: category button pressed (from self.categories)
        :return: None
        """
        while self.table.rowCount() > 0:
            self.table.removeRow(0)
        if category == self.categories[0]:
            added_books = db.select_all_data(self.db_connection, 'Book')
        elif category == self.categories[1]:
            added_books = db.select_data_with_nonkey(self.db_connection,
                                                     'book', 'favourite', True)
        else:
            added_books = db.select_books_from_library(self.db_connection,
                                                       category.text())
        self.load_books(added_books[1:])

    def category_button_clicked(self):
        is_first_time = True
        try:
            main.lastPickedCategory = self.sender().text()
        except Exception as e:
            main.lastPickedCategory = self.allQButton.text()

        for ctg in self.categories:
            ColorsRegulator().set_colors(
                ctg, styles.Styles.set_category_button_styles,
                night_styles.NightStyles.set_category_button_styles)

            if self.categoryQLabel.text() == self.sender().text():
                is_first_time = False
        if is_first_time:
            ColorsRegulator().set_colors(
                self, styles.Styles.set_init_table_styles,
                night_styles.NightStyles.set_init_table_styles)

        ColorsRegulator().set_colors(
            self.sender(), styles.Styles.set_clicked_category_button_styles,
            night_styles.NightStyles.set_clicked_category_button_styles)

        self.categoryQLabel.setText(self.sender().text())
        self.reload_book_section(self.sender())
        if self.sender().text() == self.categories[0].text():
            self.remove_book_from_lib_action.setDisabled(True)
            return
        self.remove_book_from_lib_action.setDisabled(False)

    def set_context_menu_styles(self):
        ColorsRegulator().set_icon_color(
            self.open_act, 'design/images/openedBook.png',
            'design/images/night/night_openedBook.png')

        ColorsRegulator().set_icon_color(
            self.edit_act, 'design/images/pencil.png',
            'design/images/night/night_pencil.png')

        ColorsRegulator().set_icon_color(
            self.delete_act, 'design/images/removeBook.png',
            'design/images/night/night_removeBook.png')

        ColorsRegulator().set_colors(
            self.context_menu, styles.Styles.set_context_menu_styles,
            night_styles.NightStyles.set_context_menu_styles)

        ColorsRegulator().set_icon_color(
            self.open_book_action, 'design/images/openedBook.png',
            'design/images/night/night_openedBook.png')

        ColorsRegulator().set_icon_color(self.add_book_to_lib_action,
                                         'design/images/plus.png',
                                         'design/images/night/night_plus.png')

        ColorsRegulator().set_icon_color(
            self.remove_book_from_lib_action, 'design/images/minus.png',
            'design/images/night/night_minus.png')

        ColorsRegulator().set_icon_color(
            self.rename_book_action, 'design/images/pencil.png',
            'design/images/night/night_pencil.png')

        ColorsRegulator().set_icon_color(
            self.rete_book_action, 'design/images/trophy.png',
            'design/images/night/night_trophy.png')

        ColorsRegulator().set_icon_color(
            self.delete_book_action, 'design/images/removeBook.png',
            'design/images/night/night_removeBook.png')

        ColorsRegulator().set_colors(
            self.context_table_menu, styles.Styles.set_context_menu_styles,
            night_styles.NightStyles.set_context_menu_styles)

    def category_by_text(self, text):
        """
        :param text: text of the category_button
        :return: returns category by its str name
        """
        for ctg in self.categories:
            if ctg.text() == text:
                return ctg
        return None

    def last_category_display(self, category_button):
        """
        Displays books and all functionality of the window
        as it was before we moved to another window

        :param category_button: takes QPushButton of the last clicked category
        """
        is_first_time = True
        try:
            main.lastPickedCategory = category_button.text()
        except:
            main.lastPickedCategory = self.allQButton.text()

        for ctg in self.categories:
            ColorsRegulator().set_colors(
                ctg, styles.Styles.set_category_button_styles,
                night_styles.NightStyles.set_category_button_styles)

            if self.categoryQLabel.text() == category_button.text():
                is_first_time = False
        if is_first_time:
            ColorsRegulator().set_colors(
                self, styles.Styles.set_init_table_styles,
                night_styles.NightStyles.set_init_table_styles)

        ColorsRegulator().set_colors(
            category_button, styles.Styles.set_clicked_category_button_styles,
            night_styles.NightStyles.set_clicked_category_button_styles)

        self.categoryQLabel.setText(category_button.text())
        self.reload_book_section(category_button)
        if category_button.text() == self.categories[0].text():
            self.remove_book_from_lib_action.setDisabled(True)
            return
        self.remove_book_from_lib_action.setDisabled(False)
Esempio n. 27
0
class ContentWindow(QWidget):
    def __init__(self, book):
        super().__init__()

        self.setMinimumSize(700, 400)
        self.resize(1000, 600)

        self.book = book
        self.db_connection = db.create_connection(
            os.path.expanduser("~/Documents/LNUReader/ReaderDatabase.db"))

        self.mainLayout = QVBoxLayout()
        self.bookmarksTable = QTableWidget()
        self.notesTable = QTableWidget()

        self.tabWidget = QTabWidget()
        self.tabWidget.addTab(self.bookmarksTable, '')
        self.tabWidget.addTab(self.notesTable, '')

        # Back Button
        self.backQButton = QPushButton()
        ColorsRegulator().set_icon_color(self.backQButton,
                                         'design/images/back.png',
                                         'design/images/night/night_back.png')
        ColorsRegulator().set_colors(
            self.backQButton, styles.Styles.set_back_button_styles,
            night_styles.NightStyles.set_back_button_styles)
        self.backQButton.setIconSize(QSize(32, 32))
        self.backQButton.setFocusPolicy(Qt.NoFocus)
        self.backQButton.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)

        self.contextMenu = QMenu()
        self.openAct = self.contextMenu.addAction("")
        self.deleteAct = self.contextMenu.addAction("")
        ColorsRegulator().set_icon_color(
            self.openAct, 'design/images/pencil.png',
            'design/images/night/night_pencil.png')

        ColorsRegulator().set_icon_color(
            self.deleteAct, 'design/images/removeBook.png',
            'design/images/night/night_removeBook.png')
        ColorsRegulator().set_colors(
            self.contextMenu, styles.Styles.set_context_menu_styles,
            night_styles.NightStyles.set_context_menu_styles)

        self.openAct.triggered.connect(self.edit_obj)
        self.deleteAct.triggered.connect(self.delete_obj)
        QShortcut("Del", self).activated.connect(self.delete_obj)

        self.editNoteQDialog = QTwoFieldDialog()
        self.editNoteQDialog.setWindowIcon(QIcon('design/images/icon.ico'))
        self.editNoteQDialog.resize(600, 480)

        self.editBookmarkQDialog = QInputDialog()
        self.editBookmarkQDialog.setInputMode(QInputDialog.TextInput)
        self.editBookmarkQDialog.setWindowIcon(QIcon('design/images/icon.ico'))
        self.editBookmarkQDialog.resize(600, 480)
        ColorsRegulator().set_colors(
            self.editBookmarkQDialog, styles.Styles.set_dialog_styles,
            night_styles.NightStyles.set_dialog_styles)

        ColorsRegulator().set_colors(
            self, styles.Styles.set_content_window_style,
            night_styles.NightStyles.set_content_window_style)

        localize.set_content_localization(self)

        self.notesTable.itemDoubleClicked.connect(self.edit_note)

        # Bookmark / note delete confirmation dialog
        self.deleteDialog = ConfirmDialog()
        self.deleteDialog.setWindowIcon(QIcon('design/images/icon.ico'))

        self.main_init()

    def main_init(self):
        self.init_content_tables()
        self.mainLayout.addWidget(self.backQButton)
        self.mainLayout.addWidget(self.tabWidget)
        self.setLayout(self.mainLayout)

    def init_content_tables(self):
        self.init_table(self.notesTable)
        self.init_table(self.bookmarksTable)
        bookmarks_data = db.select_data_with_nonkey(self.db_connection,
                                                    'bookmark',
                                                    'bookmark_book_path',
                                                    self.book)[1:]
        for x in bookmarks_data:
            self.insert_into_bookmarks_table(x)

        notes_data = db.select_data_with_nonkey(self.db_connection, 'note',
                                                'note_book_path',
                                                self.book)[1:]
        for x in notes_data:
            self.insert_into_notes_table(x)

    def init_table(self, table):
        table.setColumnCount(3)
        table.setColumnHidden(2, True)
        table.clicked.connect(lambda index: table.selectRow(index.row()))
        table.setEditTriggers(QAbstractItemView.NoEditTriggers)
        table.setSelectionBehavior(QAbstractItemView.SelectRows)
        table.installEventFilter(self)
        ColorsRegulator().set_colors(
            table, styles.Styles.set_content_table_styles,
            night_styles.NightStyles.set_content_table_styles)

        localize.set_content_table_localization(table)

        header = table.horizontalHeader()
        table.verticalHeader().setVisible(False)
        table.setShowGrid(False)
        header.setSectionResizeMode(QHeaderView.Stretch)
        header.setSectionResizeMode(1, QHeaderView.Fixed)
        header.resizeSection(1, 300)
        header.setHighlightSections(False)

    def insert_into_bookmarks_table(self, data):
        index = self.bookmarksTable.rowCount()
        self.bookmarksTable.insertRow(index)
        self.bookmarksTable.setItem(index, 0, QTableWidgetItem(f'{data[1]}'))
        item = QTableWidgetItem(f'{data[2] + 1}')
        item.setTextAlignment(Qt.AlignCenter)
        self.bookmarksTable.setItem(index, 1, item)
        self.bookmarksTable.setItem(index, 2, QTableWidgetItem(f'{data[0]}'))

    def insert_into_notes_table(self, data):
        index = self.notesTable.rowCount()
        self.notesTable.insertRow(index)
        self.notesTable.setItem(index, 0, QTableWidgetItem(f'{data[1]}'))

        item = QTableWidgetItem(f'{data[3] + 1}')
        item.setTextAlignment(Qt.AlignCenter)
        self.notesTable.setItem(index, 1, item)
        self.notesTable.setItem(index, 2, QTableWidgetItem(f'{data[0]}'))

    def eventFilter(self, source: QObject, event: QEvent) -> bool:
        if event.type() != QEvent.ContextMenu or (source is not self.bookmarksTable and source is not self.notesTable) \
                or (self.bookmarksTable.currentIndex().row() < 0 and self.notesTable.currentIndex().row() < 0):
            return super().eventFilter(source, event)
        index = source.currentIndex().row()
        source.selectRow(index)
        if not self.contextMenu.exec_(event.globalPos()):
            source.setCurrentIndex(QModelIndex())
        return True

    def edit_obj(self):
        if self.tabWidget.currentIndex() == 0:
            self.edit_bookmark()
        elif self.tabWidget.currentIndex() == 1:
            self.edit_note()
        else:
            raise Exception('something wtf')

    def edit_note(self):
        index = self.notesTable.selectedItems()[0].row()
        note_id = self.notesTable.item(index, 2).text()
        data = db.select_data(self.db_connection, "note", note_id)[1:]
        self.editNoteQDialog.set_fields_text(data[0][1], data[0][2])
        ok = self.editNoteQDialog.exec_()
        text = self.editNoteQDialog.get_inputs()
        self.editNoteQDialog.clear_input_fields()
        if ok:
            if text[0] == "" or text[1] == "":
                message = WarningMessage()
                localize.set_empty_note_warning_localization(message)
                message.exec_()
                return
            try:
                db.update_data(self.db_connection, "note", "note_title",
                               text[0], note_id)
            except db.Error:
                message = WarningMessage()
                localize.set_note_warning_localization(message)
                message.exec_()
                return
            db.update_data(self.db_connection, "note", "note_text", text[1],
                           note_id)
            self.notesTable.setItem(index, 0, QTableWidgetItem(text[0]))

    def edit_bookmark(self):
        index = self.bookmarksTable.selectedItems()[0].row()
        bookmark_title = self.bookmarksTable.item(index, 0).text()
        self.editBookmarkQDialog.setTextValue(bookmark_title)
        ok = self.editBookmarkQDialog.exec_()
        text = self.editBookmarkQDialog.textValue()
        self.editBookmarkQDialog.setTextValue("")
        if ok:
            if text == "":
                message = WarningMessage()
                localize.set_empty_bookmark_warning_localization(message)
                message.exec_()
                return
            bookmark_id = self.bookmarksTable.item(index, 2).text()
            try:
                db.update_data(self.db_connection, "bookmark",
                               "bookmark_title", text, bookmark_id)
            except db.Error:
                message = WarningMessage()
                localize.set_second_bookmark_warning_localization(message)
                message.exec_()
                return
            self.bookmarksTable.setItem(index, 0, QTableWidgetItem(text))

    def delete_obj(self):
        if self.tabWidget.currentIndex() == 0:
            self.delete_bookmark()
        elif self.tabWidget.currentIndex() == 1:
            self.delete_note()
        else:
            raise Exception('something wtf')

    def delete_bookmark(self):
        if not self.bookmarksTable.selectedItems():
            return
        localize.set_bookmark_delete_localization(self.deleteDialog)
        ok = self.deleteDialog.exec_()
        if ok:
            index = self.bookmarksTable.selectedItems()[0].row()
            key = int(self.bookmarksTable.item(index, 2).text())
            db.delete_data(self.db_connection, "bookmark", key)
            self.bookmarksTable.removeRow(index)

    def delete_note(self):
        if not self.notesTable.selectedItems():
            return
        localize.set_note_delete_localization(self.deleteDialog)
        ok = self.deleteDialog.exec_()
        if ok:
            index = self.notesTable.selectedItems()[0].row()
            key = int(self.notesTable.item(index, 2).text())
            db.delete_data(self.db_connection, "note", key)
            self.notesTable.removeRow(index)
class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        # needed variable
        self.db_connection = None
        self.buttonCalledAction = None

        # Main body
        self.bodyQVBoxLayout = QVBoxLayout()
        self.body = QWidget()

        # -----------------
        # Header
        self.headerQHBoxLayout = QHBoxLayout()
        self.header = QWidget()
        self.headerQHBoxLayout.setSpacing(20)
        self.headerQHBoxLayout.setContentsMargins(20, 11, 20, 11)

        # Add Book Button
        self.addBookQButton = QPushButton()
        self.addBookQButton.setIcon(QIcon('design/images/add.png'))
        self.addBookQButton.setIconSize(QSize(28, 28))
        self.addBookQButton.setFocusPolicy(Qt.NoFocus)

        # Remove Book Button
        self.removeBookQButton = QPushButton()
        self.removeBookQButton.setIcon(QIcon('design/images/removeBook.png'))
        self.removeBookQButton.setIconSize(QSize(28, 28))
        self.removeBookQButton.setFocusPolicy(Qt.NoFocus)

        # Search Bar
        self.searchBar = QLineEdit()
        self.searchBar.setClearButtonEnabled(True)
        self.searchBar.setFocusPolicy(Qt.ClickFocus)

        # Settings
        self.settingsQButton = QPushButton()
        self.settingsQButton.setIcon(QIcon('design/images/settings.png'))
        self.settingsQButton.setIconSize(QSize(32, 32))
        self.settingsQButton.setFocusPolicy(Qt.NoFocus)
        # -----------------
        # Container
        self.containerQHBoxLayout = QHBoxLayout()
        self.container = QWidget()
        self.containerQHBoxLayout.setContentsMargins(20, 20, 20, 40)
        self.containerQHBoxLayout.setSpacing(0)

        # Side Bar
        self.sideBar = QWidget()
        self.sideBarQVBoxLayout = QVBoxLayout()
        self.sideBarQVBoxLayout.setContentsMargins(0, 10, 0, 0)

        # Library Label
        self.libLabel = QLabel()
        self.libLabel.setAlignment(Qt.AlignCenter)

        # Context menu
        self.context_menu = QMenu()
        self.open_act = self.context_menu.addAction("")
        self.edit_act = self.context_menu.addAction("")
        self.delete_act = self.context_menu.addAction("")
        styles.Styles.set_context_menu_styles(self.context_menu)

        # Categories
        self.categoriesQWidget = QWidget()
        self.categoriesQVBoxLayout = QVBoxLayout()
        self.categoriesQVBoxLayout.setContentsMargins(0, 20, 0, 0)
        self.categoriesQVBoxLayout.setSpacing(0)

        # Categories buttons
        self.categories = []
        self.allQButton = QPushButton()
        self.favouritesQButton = QPushButton()

        # Create Category Button
        self.createCategoryQButton = QPushButton()

        # Create Category Dialog
        self.categoryQDialog = QInputDialog()
        self.categoryQDialog.setInputMode(QInputDialog.TextInput)
        self.categoryQDialog.setWindowIcon(QIcon('design/images/icon.ico'))
        self.categoryQDialog.resize(600, 400)

        # Content
        self.content = QWidget()
        self.contentQVBoxLayout = QVBoxLayout()
        self.contentQVBoxLayout.setContentsMargins(0, 0, 0, 0)

        # Category title in Content
        self.categoryQLabel = QLabel()
        self.categoryQLabel.setAlignment(Qt.AlignCenter)

        # Table
        self.table = QTableWidget()
        self.table.setColumnCount(6)

        # ScrollBar in Table
        self.tableScrollBar = QScrollBar()
        self.table.setVerticalScrollBar(self.tableScrollBar)
        self.table.setFocusPolicy(Qt.NoFocus)
        self.table.setEditTriggers(QAbstractItemView.NoEditTriggers)

        # Main run
        self.setup_working_folder()
        localize.set_main_menu_localization(self)
        styles.Styles.set_main_menu_styles(self)
        self.init_body()

        # Settings window
        self.sett_menu = None

    @staticmethod
    def connect_to_db():
        path_to_db = os.path.expanduser("~/Documents/LNUReader")
        if not os.path.exists(path_to_db):
            os.makedirs(path_to_db)
        return db.create_connection(path_to_db + r'\ReaderDatabase.db')

    def set_size(self):
        with open(os.path.expanduser(
                "~/Documents/LNUReader/settings.json")) as json_file:
            lg_info = json.load(json_file)
        self.resize(lg_info["screen"][0], lg_info["screen"][1])

    def init_header(self):
        self.headerQHBoxLayout.addWidget(self.addBookQButton)
        self.headerQHBoxLayout.addWidget(self.removeBookQButton)
        self.headerQHBoxLayout.addStretch()
        self.headerQHBoxLayout.addWidget(self.searchBar)
        self.headerQHBoxLayout.addWidget(self.settingsQButton)
        self.header.setLayout(self.headerQHBoxLayout)

    def init_categories(self):
        self.set_category_button_options(self.allQButton)
        self.set_category_button_options(self.favouritesQButton)
        self.categoriesQVBoxLayout.addWidget(self.allQButton)
        self.categoriesQVBoxLayout.addWidget(self.favouritesQButton)
        user_categories = db.select_all_data(self.db_connection,
                                             "library")["library_name"]
        for ctg in user_categories:
            added_button = QPushButton(ctg)
            self.set_category_button_options(added_button)
            self.categoriesQVBoxLayout.addWidget(added_button)
        self.categoriesQWidget.setLayout(self.categoriesQVBoxLayout)

    def init_sidebar(self):
        self.init_categories()
        self.sideBarQVBoxLayout.addWidget(self.libLabel)
        self.sideBarQVBoxLayout.addWidget(self.categoriesQWidget)
        self.sideBarQVBoxLayout.addStretch()
        self.sideBarQVBoxLayout.addWidget(self.createCategoryQButton)
        self.sideBar.setLayout(self.sideBarQVBoxLayout)

    def init_table(self):
        header = self.table.horizontalHeader()
        self.table.verticalHeader().setVisible(False)
        self.table.setShowGrid(False)
        header.setSectionResizeMode(QHeaderView.Fixed)
        header.setHighlightSections(False)
        header.setSectionResizeMode(0, QHeaderView.Stretch)
        header.setSectionResizeMode(1, QHeaderView.Stretch)
        header.resizeSection(2, 120)
        header.resizeSection(3, 100)
        header.resizeSection(4, 80)
        header.resizeSection(5, 50)

        for i in range(30):
            self.table.insertRow(i)
            self.table.setItem(i, 0, QTableWidgetItem(f'text{i}'))
            self.table.setItem(i, 1, QTableWidgetItem(f'author{i}'))

    def init_content(self):
        self.init_table()
        self.contentQVBoxLayout.addWidget(self.categoryQLabel)
        self.contentQVBoxLayout.addWidget(self.table)
        self.content.setLayout(self.contentQVBoxLayout)

    def init_container(self):
        self.init_sidebar()
        self.init_content()
        self.containerQHBoxLayout.addWidget(self.sideBar)
        self.containerQHBoxLayout.addWidget(self.content)
        self.container.setLayout(self.containerQHBoxLayout)

    def init_body(self):
        self.init_header()
        self.init_container()
        self.bodyQVBoxLayout.addWidget(self.header)
        self.bodyQVBoxLayout.addWidget(self.container)
        self.body.setLayout(self.bodyQVBoxLayout)
        self.setCentralWidget(self.body)

    def setup_working_folder(self):
        """
        Checks existance of all necessary files in
        C:/Users/User/Documents/LNUReader
        and opens connection to database.
        If any of files/folder are missing, creates a default/empty ones.
        :return: None
        """
        self.check_folder()
        self.db_connection = self.connect_to_db()
        db.create_db(self.db_connection)
        self.check_json()

    def set_category_button_options(self, category_button):
        styles.Styles.set_category_button_styles(category_button)
        category_button.setFocusPolicy(Qt.ClickFocus)
        category_button.setContextMenuPolicy(Qt.CustomContextMenu)
        category_button.customContextMenuRequested.connect(
            self.on_context_menu)
        self.categories.append(category_button)
        category_button.clicked.connect(self.category_button_clicked)

    def category_button_clicked(self):
        for ctg in self.categories:
            styles.Styles.set_category_button_styles(ctg)
        styles.Styles.set_clicked_category_button_styles(self.sender())
        self.categoryQLabel.setText(self.sender().text())

    def on_context_menu(self, point):
        """
        Method that show context menu when user does right mouse click on category.
        :param point: cursor coordinates
        :return: None
        """
        self.buttonCalledAction = self.sender()
        if not self.is_standard_category():
            self.delete_act.setEnabled(True)
            self.edit_act.setEnabled(True)
        else:
            self.delete_act.setEnabled(False)
            self.edit_act.setEnabled(False)
        self.context_menu.exec_(self.buttonCalledAction.mapToGlobal(point))

    def is_standard_category(self):
        """
        Method checks if right clicked category is standard (All + Favourites).
        :return: boolean
        """
        return self.buttonCalledAction in [
            button for button in self.categories[:2]
        ]

    @staticmethod
    def check_folder():
        """
        Method checks if the folder with database and settings file exists.
        If it doesn't, creates one.
        :return: None
        """
        folder_path = os.path.expanduser("~/Documents/LNUReader")
        if not os.path.exists(folder_path):
            os.makedirs(folder_path)

    @staticmethod
    def connect_to_db():
        """
        Method creates a connection to database
        :return: Connection object
        """
        database_path = os.path.expanduser(
            "~/Documents/LNUReader/ReaderDatabase.db")
        return db.create_connection(database_path)

    def check_json(self):
        """
        Method checks if file with settings exists.
        If not, creates a default one.
        :return: None
        """
        settings_path = (
            os.path.expanduser("~/Documents/LNUReader/settings.json"))
        if not os.path.exists(settings_path):
            self.create_default_json()

    @staticmethod
    def create_default_json():
        """
        Creates a json file with default settings.
        :return: None
        """
        settings = {"language": "EN"}
        with open(os.path.expanduser("~/Documents/LNUReader/settings.json"),
                  'w') as outfile:
            json.dump(settings, outfile)
Esempio n. 29
0
class ReaderWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        self.noteQDialog = QTwoFieldDialog()
        self.noteQDialog.setWindowIcon(QIcon('design/images/icon.ico'))
        self.noteQDialog.resize(600, 480)
        localize.set_add_note_localization(self.noteQDialog)

        self.bookmarkQDialog = QInputDialog()
        self.bookmarkQDialog.setInputMode(QInputDialog.TextInput)
        self.bookmarkQDialog.setWindowIcon(QIcon('design/images/icon.ico'))
        self.bookmarkQDialog.resize(600, 480)
        localize.set_add_bookmark_localization(self.bookmarkQDialog)
        ColorsRegulator().set_colors(self.bookmarkQDialog,
                                     styles.Styles.set_dialog_styles,
                                     night_styles.NightStyles.set_dialog_styles)

        # Main body
        self.bodyQHBoxLayout = QVBoxLayout()
        self.body = QWidget()

        self.stack = QStackedWidget()
        self.stack.addWidget(self.body)

        # Container
        self.containerQHBoxLayout = QHBoxLayout()
        self.containerQHBoxLayout.setSpacing(50)
        self.container = QWidget()

        # SideBar
        self.sidebarQVBoxLayout = QVBoxLayout()
        self.sidebar = QWidget()
        self.sidebar.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        self.sidebarQVBoxLayout.setSpacing(50)

        # Back Button
        self.backQButton = QPushButton()
        ColorsRegulator().set_icon_color(self.backQButton,
                                         'design/images/back.png',
                                         'design/images/night/night_back.png')
        ColorsRegulator().set_colors(self.backQButton,
                                     styles.Styles.set_back_button_styles,
                                     night_styles.NightStyles.set_back_button_styles)
        self.backQButton.setIconSize(QSize(32, 32))
        self.backQButton.setFocusPolicy(Qt.NoFocus)
        self.backQButton.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)

        # Button menu
        self.buttonMenuQVBoxLayout = QVBoxLayout()
        self.buttonMenuQVBoxLayout.setContentsMargins(0, 0, 0, 0)
        self.buttonMenu = QWidget()

        # Fullscreen Button
        self.fullscreenQButton = QPushButton()
        ColorsRegulator().set_icon_color(self.fullscreenQButton,
                                         'design/images/fullscreen.png',
                                         'design/images/night/night_fullscreen.png')
        ColorsRegulator().set_colors(self.fullscreenQButton,
                                     styles.Styles.set_button_style,
                                     night_styles.NightStyles.set_button_style)
        self.fullscreenQButton.setIconSize(QSize(32, 32))
        self.fullscreenQButton.setFocusPolicy(Qt.NoFocus)

        # Zoom In Button
        self.zoomInQButton = QPushButton()
        ColorsRegulator().set_icon_color(self.zoomInQButton,
                                         'design/images/zoom-in.png',
                                         'design/images/night/night_zoom-in.png')
        ColorsRegulator().set_colors(self.zoomInQButton,
                                     styles.Styles.set_button_style,
                                     night_styles.NightStyles.set_button_style)
        self.zoomInQButton.setIconSize(QSize(32, 32))
        self.zoomInQButton.setFocusPolicy(Qt.NoFocus)

        # Zoom Out Button
        self.zoomOutQButton = QPushButton()
        ColorsRegulator().set_icon_color(self.zoomOutQButton,
                                         'design/images/zoom-out.png',
                                         'design/images/night/night_zoom-out.png')
        ColorsRegulator().set_colors(self.zoomOutQButton,
                                     styles.Styles.set_button_style,
                                     night_styles.NightStyles.set_button_style)
        self.zoomOutQButton.setIconSize(QSize(32, 32))
        self.zoomOutQButton.setFocusPolicy(Qt.NoFocus)

        # Show Content Button
        self.contentQButton = QPushButton()
        ColorsRegulator().set_icon_color(self.contentQButton,
                                         'design/images/content.png',
                                         'design/images/night/night_content.png')
        ColorsRegulator().set_colors(self.contentQButton,
                                     styles.Styles.set_button_style,
                                     night_styles.NightStyles.set_button_style)
        self.contentQButton.setIconSize(QSize(32, 32))
        self.contentQButton.setFocusPolicy(Qt.NoFocus)

        # Add Bookmarks Button
        self.addBookmarkQButton = QPushButton()
        ColorsRegulator().set_icon_color(self.addBookmarkQButton,
                                         'design/images/bookmark.png',
                                         'design/images/night/night_bookmark.png')
        ColorsRegulator().set_colors(self.addBookmarkQButton,
                                     styles.Styles.set_button_style,
                                     night_styles.NightStyles.set_button_style)
        self.addBookmarkQButton.setIconSize(QSize(32, 32))
        self.addBookmarkQButton.setFocusPolicy(Qt.NoFocus)

        # Add Notes Button
        self.addNoteQButton = QPushButton()
        ColorsRegulator().set_icon_color(self.addNoteQButton,
                                         'design/images/notes.png',
                                         'design/images/night/night_notes.png')
        ColorsRegulator().set_colors(self.addNoteQButton,
                                     styles.Styles.set_button_style,
                                     night_styles.NightStyles.set_button_style)
        self.addNoteQButton.setIconSize(QSize(32, 32))
        self.addNoteQButton.setFocusPolicy(Qt.NoFocus)

        # Switch mode Button
        self.switchModeQButton = QPushButton()
        ColorsRegulator().set_icon_color(self.switchModeQButton,
                                         'design/images/switch.png',
                                         'design/images/night/night_switch.png')
        ColorsRegulator().set_colors(self.switchModeQButton,
                                     styles.Styles.set_button_style,
                                     night_styles.NightStyles.set_button_style)

        self.switchModeQButton.setIconSize(QSize(32, 32))
        self.switchModeQButton.setFocusPolicy(Qt.NoFocus)

        # Content
        self.content = QLabel()
        self.content.setAlignment(Qt.AlignCenter)
        self.content.adjustSize()
        self.content.setWordWrap(True)

        # Scroll Area for Reader Window
        self.scrollArea = QScrollArea()
        self.scrollArea.setWidget(self.content)
        self.scrollArea.setWidgetResizable(True)

        # Content window
        self.content_window = None

        # Fullscreen Window
        self.fullscreen_window = None

        # Footer
        self.footerQHBoxLayout = QHBoxLayout()
        self.footerQHBoxLayout.setSpacing(20)
        self.footer = QWidget()
        self.footer.setContentsMargins(11, 0, 0, 0)

        # Show progress Label
        self.progressLabel = QLabel()
        self.progressLabel.setAlignment(Qt.AlignCenter)
        self.progressLabel.setFixedSize(QSize(95, 100))

        # Switch page block
        self.switchPageQHBoxLayout = QHBoxLayout()
        self.switchPageWidget = QWidget()
        self.switchPageQHBoxLayout.setSpacing(20)

        # Previous Page Button
        self.previousPageQButton = QPushButton()
        ColorsRegulator().set_icon_color(self.previousPageQButton,
                                         'design/images/back.png',
                                         'design/images/night/night_back.png')
        ColorsRegulator().set_colors(self.previousPageQButton,
                                     styles.Styles.set_switch_buttons_style,
                                     night_styles.NightStyles.set_switch_buttons_style)
        self.previousPageQButton.setIconSize(QSize(32, 32))
        self.previousPageQButton.setFocusPolicy(Qt.NoFocus)

        # Next Page Button
        self.nextPageQButton = QPushButton()
        ColorsRegulator().set_icon_color(self.nextPageQButton,
                                         'design/images/front.png',
                                         'design/images/night/night_front.png')
        ColorsRegulator().set_colors(self.nextPageQButton,
                                     styles.Styles.set_switch_buttons_style,
                                     night_styles.NightStyles.set_switch_buttons_style)

        self.nextPageQButton.setIconSize(QSize(32, 32))
        self.nextPageQButton.setFocusPolicy(Qt.NoFocus)

        localize.set_reader_localization(self)
        ColorsRegulator().set_colors(self,
                                     styles.Styles.set_window_styles,
                                     night_styles.NightStyles.set_window_styles)
        styles.Styles.set_content_colors(self)
        self.init_body()

    def init_sidebar(self):
        self.sidebarQVBoxLayout.addWidget(self.backQButton)
        self.buttonMenuQVBoxLayout.addWidget(self.fullscreenQButton)
        self.buttonMenuQVBoxLayout.addWidget(self.zoomInQButton)
        self.buttonMenuQVBoxLayout.addWidget(self.zoomOutQButton)
        self.buttonMenuQVBoxLayout.addWidget(self.contentQButton)
        self.buttonMenuQVBoxLayout.addWidget(self.addBookmarkQButton)
        self.buttonMenuQVBoxLayout.addWidget(self.addNoteQButton)
        self.buttonMenuQVBoxLayout.addWidget(self.switchModeQButton)
        self.buttonMenu.setLayout(self.buttonMenuQVBoxLayout)
        self.sidebarQVBoxLayout.addWidget(self.buttonMenu)
        self.sidebarQVBoxLayout.addStretch()
        self.sidebar.setLayout(self.sidebarQVBoxLayout)

    def init_container(self):
        self.init_sidebar()
        self.containerQHBoxLayout.addWidget(self.sidebar)
        self.containerQHBoxLayout.addWidget(self.scrollArea)
        self.container.setLayout(self.containerQHBoxLayout)

    def init_footer(self):
        self.footerQHBoxLayout.addWidget(self.progressLabel)

        self.switchPageQHBoxLayout.addWidget(self.previousPageQButton)
        self.switchPageQHBoxLayout.addWidget(self.nextPageQButton)
        self.switchPageWidget.setLayout(self.switchPageQHBoxLayout)
        self.footerQHBoxLayout.addStretch()
        self.footerQHBoxLayout.addWidget(self.switchPageWidget)
        self.footerQHBoxLayout.addStretch()
        self.footer.setLayout(self.footerQHBoxLayout)

    def init_body(self):
        self.init_container()
        self.init_footer()
        self.bodyQHBoxLayout.addWidget(self.container)
        self.bodyQHBoxLayout.addWidget(self.footer)
        self.body.setLayout(self.bodyQHBoxLayout)
        self.setCentralWidget(self.stack)
Esempio n. 30
0
 def HandleInput(self, data):
     if type(data) == tuple and len(data) > 0:
         msg = data[0]
     else:
         if type(data) == int:
             msg = data
     if msg == messagetypes.LAUNCHER_ERROR:
         details = data[1]
         box = QMessageBox(QMessageBox.Critical,
                           localizer.GUI_Error,
                           data[1],
                           QMessageBox.Ok,
                           parent=self).exec_()
         if len(data) > 2 and data[2]:
             self.frame.close()
         self.SetLoginControlsEditable(True)
     else:
         if msg == messagetypes.LAUNCHER_VERSION_UPDATE:
             version = data[1]
             changelog = data[2]
             url = data[3]
             QMessageBox(QMessageBox.Critical,
                         localizer.LauncherUpdateHeader,
                         localizer.LauncherUpdateAvailabile %
                         (version, changelog),
                         QMessageBox.Ok,
                         parent=self).exec_()
             webbrowser.open(url)
             self.frame.close()
         else:
             if msg == messagetypes.LAUNCHER_REQUEST_TFA:
                 dlg = QInputDialog(parent=self)
                 dlg.setLabelText(data[1])
                 dlg.setWindowTitle(localizer.GUI_TFA)
                 dlg.setWhatsThis(localizer.GUI_TFAWhatsThis)
                 dlg.resize(360, 130)
                 ok = dlg.exec_()
                 if ok:
                     val = dlg.textValue()
                     self.output.put(str(val), block=True, timeout=1.0)
                 else:
                     self.output.put(None, block=True, timeout=1.0)
                     self.SetLoginControlsEditable(True)
             else:
                 if msg == messagetypes.LAUNCHER_STATUS:
                     self.SetStatusLabel(data[1])
                 else:
                     if msg == messagetypes.LAUNCHER_PROGRESS:
                         pcent = int(data[1])
                         if pcent == -1:
                             self.progress.hide()
                         else:
                             self.progress.show()
                             self.progress.setValue(pcent)
                     else:
                         if msg == messagetypes.LAUNCHER_PLAY_RETRY:
                             dlg = QMessageBox(
                                 QMessageBox.Question,
                                 localizer.GUI_CrashedTitle,
                                 localizer.GUI_CrashedQuestion,
                                 QMessageBox.No | QMessageBox.Yes,
                                 parent=self)
                             dlg.setDefaultButton(QMessageBox.Yes)
                             val = dlg.exec_()
                             if val == QMessageBox.Yes:
                                 self.output.put(True,
                                                 block=True,
                                                 timeout=1.0)
                             else:
                                 self.frame.close()
                         else:
                             if msg == messagetypes.LAUNCHER_ENABLE_CONTROLS:
                                 self.SetLoginControlsEditable(True)
                             else:
                                 if msg == messagetypes.LAUNCHER_CLEAR_PASSWORD:
                                     self.pbox.setText('')
                                 else:
                                     if msg == messagetypes.LAUNCHER_HIDE:
                                         self.frame.hide()
                                     else:
                                         if msg == messagetypes.LAUNCHER_SHOW:
                                             self.frame.show()
                                         else:
                                             if msg == messagetypes.LAUNCHER_EXIT:
                                                 self.frame.close()
     return