Пример #1
0
 def __init__(self, icon, title, text, modal=False,
              buttons=QMessageBox.StandardButtons(QMessageBox.NoButton),
              parent=None):
     """
     Constructor
     
     @param icon type of icon to be shown (QMessageBox.Icon)
     @param title caption of the message box (string)
     @param text text to be shown by the message box (string)
     @keyparam modal flag indicating a modal dialog (boolean)
     @keyparam buttons set of standard buttons to generate (StandardButtons)
     @keyparam parent parent widget of the message box (QWidget)
     """
     super(E5MessageBox, self).__init__(parent)
     self.setIcon(icon)
     if modal:
         if parent is not None:
             self.setWindowModality(Qt.WindowModal)
         else:
             self.setWindowModality(Qt.ApplicationModal)
     else:
         self.setWindowModality(Qt.NonModal)
     if title == "":
         self.setWindowTitle("{0}".format(
             QApplication.applicationName()))
     else:
         self.setWindowTitle("{0} - {1}".format(
             QApplication.applicationName(), title))
     self.setText(text)
     self.setStandardButtons(buttons)
Пример #2
0
 def saveFileDialog(self):
     fname = self.filename()
     if fname == None:
         directory = "."
     else:
         directory = QFileInfo(fname).path()
     if util.isWindows():  # required for native looking file window
         fname = QFileDialog.getSaveFileName(
                         self.win,
                         "%s - Save As" % QApplication.applicationName(),
                         directory,
                         "%s (*.json)" % QApplication.applicationName())
         self.writeDocumentToFile(fname)
     else:  # access through non-blocking callback
         fdialog = QFileDialog(
                         self.win,
                         "%s - Save As" % QApplication.applicationName(),
                         directory,
                         "%s (*.json)" % QApplication.applicationName())
         fdialog.setAcceptMode(QFileDialog.AcceptSave)
         fdialog.setWindowFlags(Qt.Sheet)
         fdialog.setWindowModality(Qt.WindowModal)
         self.filesavedialog = fdialog
         self.filesavedialog.filesSelected.connect(
                                             self.saveFileDialogCallback)
         fdialog.open()
Пример #3
0
 def __init__(self, icon, title, text, modal=False,
              buttons=QMessageBox.NoButton,
              parent=None):
     """
     Constructor
     
     @param icon type of icon to be shown (QMessageBox.Icon)
     @param title caption of the message box (string)
     @param text text to be shown by the message box (string)
     @keyparam modal flag indicating a modal dialog (boolean)
     @keyparam buttons set of standard buttons to generate (StandardButtons)
     @keyparam parent parent widget of the message box (QWidget)
     """
     super(E5MessageBox, self).__init__(parent)
     self.setIcon(icon)
     if modal:
         if parent is not None:
             self.setWindowModality(Qt.WindowModal)
         else:
             self.setWindowModality(Qt.ApplicationModal)
     else:
         self.setWindowModality(Qt.NonModal)
     if title == "":
         self.setWindowTitle("{0}".format(
             QApplication.applicationName()))
     else:
         self.setWindowTitle("{0} - {1}".format(
             QApplication.applicationName(), title))
     self.setText(text)
     self.setStandardButtons(buttons)
Пример #4
0
    def actionExportStaplesSlot(self):
        """
        Triggered by clicking Export Staples button. Opens a file dialog to
        determine where the staples should be saved. The callback is
        exportStaplesCallback which collects the staple sequences and exports
        the file.
        """
        # Validate that no staple oligos are loops.
        part = self.activePart()
        if part is None:
            return
        stap_loop_olgs = part.getStapleLoopOligos()
        if stap_loop_olgs:
            from ui.dialogs.ui_warning import Ui_Warning
            dialog = QDialog()
            dialogWarning = Ui_Warning()  # reusing this dialog, should rename
            dialog.setStyleSheet("QDialog { background-image: url(ui/dialogs/images/cadnano2-about.png); background-repeat: none; }")
            dialogWarning.setupUi(dialog)

            locs = ", ".join([o.locString() for o in stap_loop_olgs])
            msg = "Part contains staple loop(s) at %s.\n\nUse the break tool to introduce 5' & 3' ends before exporting. Loops have been colored red; use undo to revert." % locs
            dialogWarning.title.setText("Staple validation failed")
            dialogWarning.message.setText(msg)
            for o in stap_loop_olgs:
                o.applyColor(styles.stapColors[0].name())
            dialog.exec_()
            return

        # Proceed with staple export.
        fname = self.filename()
        if fname == None:
            directory = "."
        else:
            directory = QFileInfo(fname).path()
        if util.isWindows():  # required for native looking file window
            fname = QFileDialog.getSaveFileName(
                            self.win,
                            "%s - Export As" % QApplication.applicationName(),
                            directory,
                            "(*.csv)")
            self.saveStaplesDialog = None
            self.exportStaplesCallback(fname)
        else:  # access through non-blocking callback
            fdialog = QFileDialog(
                            self.win,
                            "%s - Export As" % QApplication.applicationName(),
                            directory,
                            "(*.csv)")
            fdialog.setAcceptMode(QFileDialog.AcceptSave)
            fdialog.setWindowFlags(Qt.Sheet)
            fdialog.setWindowModality(Qt.WindowModal)
            self.saveStaplesDialog = fdialog
            self.saveStaplesDialog.filesSelected.connect(self.exportStaplesCallback)
            fdialog.open()
Пример #5
0
 def on_aboutAction(self):
     msg = (
         "{} v{}<br>"
         "<br>"
         "Copyright (C) 2018 <a href=\"mailto:[email protected]\">Eero Molkoselkä</a><br>"
         "<br>"
         "This software is licensed under WTFPL. See COPYING file for details.<br>"
     )
     QMessageBox.about(
         self, "About %s" % QApplication.applicationName(),
         msg.format(QApplication.applicationName(),
                    QApplication.applicationVersion()))
Пример #6
0
    def actionExportSequencesSlot(self):
        """
        Triggered by clicking Export Staples button. Opens a file dialog to
        determine where the staples should be saved. The callback is
        exportStaplesCallback which collects the staple sequences and exports
        the file.
        """
        # Validate that no staple oligos are circular.
        part = self._document.activePart()
        if part is None:
            return
        circ_olgs = part.getCircularOligos()
        if circ_olgs:
            from cadnano.gui.ui.dialogs.ui_warning import Ui_Warning
            dialog = QDialog()
            dialogWarning = Ui_Warning()  # reusing this dialog, should rename
            dialog.setStyleSheet(
                "QDialog { background-image: url(ui/dialogs/images/cadnano2-about.png); background-repeat: none; }"
            )
            dialogWarning.setupUi(dialog)

            locs = ", ".join([o.locString() for o in circ_olgs])
            msg = "Part contains staple loop(s) at %s.\n\nUse the break tool to introduce 5' & 3' ends before exporting. Loops have been colored red; use undo to revert." % locs
            dialogWarning.title.setText("Staple validation failed")
            dialogWarning.message.setText(msg)
            for o in circ_olgs:
                o.applyColor(styles.stapColors[0])
            dialog.exec_()
            return

        # Proceed with staple export.
        fname = self.fileName()
        if fname is None:
            directory = "."
        else:
            directory = QFileInfo(fname).path()
        if util.isWindows():  # required for native looking file window
            fname = QFileDialog.getSaveFileName(
                self.win, "%s - Export As" % QApplication.applicationName(),
                directory, "(*.txt)")
            self.saveStaplesDialog = None
            self.exportStaplesCallback(fname)
        else:  # access through non-blocking callback
            fdialog = QFileDialog(
                self.win, "%s - Export As" % QApplication.applicationName(),
                directory, "(*.txt)")
            fdialog.setAcceptMode(QFileDialog.AcceptSave)
            fdialog.setWindowFlags(Qt.Sheet)
            fdialog.setWindowModality(Qt.WindowModal)
            self.saveStaplesDialog = fdialog
            self.saveStaplesDialog.filesSelected.connect(
                self.exportStaplesCallback)
            fdialog.open()
Пример #7
0
 def save_setup(self):
     try:
         with open(self.CONFIG_FNAME, 'w') as f:
             json.dump(self.__setup, f)
     except Exception as err:
         QMessageBox.critical(self, QApplication.applicationName(),
                              str(err))
Пример #8
0
    def __setupUi(self):
        layout = QVBoxLayout()
        label = QLabel(self)

        pixmap, _ = config.splash_screen()

        label.setPixmap(pixmap)

        layout.addWidget(label, Qt.AlignCenter)

        name = QApplication.applicationName()
        version = QApplication.applicationVersion()

        text = ABOUT_TEMPLATE.format(
            name=escape(name),
            version=escape(version),
        )
        # TODO: Also list all known add-on versions??.
        text_label = QLabel(text)
        layout.addWidget(text_label, Qt.AlignCenter)

        buttons = QDialogButtonBox(
            QDialogButtonBox.Close, Qt.Horizontal, self)
        layout.addWidget(buttons)
        buttons.rejected.connect(self.accept)
        layout.setSizeConstraint(QVBoxLayout.SetFixedSize)
        self.setLayout(layout)
Пример #9
0
 def show_page1(self, first=False):
     if first is True:
         widget = self.stack.widget(1)
         widget.refreshModel()
     self.setWindowTitle(QApplication.applicationName())
     self.menubar.setVisible(True)
     self.stack.setCurrentIndex(1)
Пример #10
0
    def __init__(self, page, parent=None):
        super(HelpForm, self).__init__(parent)
        self.setAttribute(Qt.WA_DeleteOnClose)
        self.setAttribute(Qt.WA_GroupLeader)

        backAction = QAction(qtawesome.icon("fa.backward"), "&Back", self)
        backAction.setShortcut(QKeySequence.Back)
        homeAction = QAction(qtawesome.icon("fa.home"), "&Home", self)
        homeAction.setShortcut("Home")
        self.pageLabel = QLabel()

        toolBar = QToolBar()
        toolBar.addAction(backAction)
        toolBar.addAction(homeAction)
        toolBar.addWidget(self.pageLabel)
        self.textBrowser = QTextBrowser()

        layout = QVBoxLayout()
        layout.addWidget(toolBar)
        layout.addWidget(self.textBrowser, 1)
        self.setLayout(layout)

        backAction.triggered.connect(self.tbackward)
        homeAction.triggered.connect(self.thome)
        self.textBrowser.sourceChanged.connect(self.updatePageTitle)

        self.textBrowser.setSearchPaths([":/help"])
        self.textBrowser.setSource(QUrl(page))
        self.resize(400, 600)
        self.setWindowTitle("{0} Help".format(QApplication.applicationName()))
Пример #11
0
def main():
    root = os.path.join('temp', 'gui_management')
    if os.path.exists(root):
        shutil.rmtree(root)

    latus.logger.init(root)
    latus.logger.set_console_log_level(logging.INFO)
    latus_key = 'my_secret_latus_key'

    log_folder = os.path.join(root, 'log')
    latus.util.make_dirs(log_folder)
    latus.logger.init(log_folder)
    cloud_folder = os.path.join(root, 'cloud')
    cloud_folders = latus.folders.CloudFolders(cloud_folder)

    preferences = {}
    node_dbs = {}
    app_data_folders = {}
    for node in ['a', 'b', 'c']:
        app_data_folders[node] = os.path.join(root, node, 'appdata')
        preferences[node] = latus.preferences.Preferences(app_data_folders[node], True)
        node_id = latus.util.new_node_id()
        preferences[node].set_node_id(node_id)
        preferences[node].set_cloud_root(cloud_folder)
        latus.util.make_dirs(cloud_folders.nodes)
        node_dbs[node] = latus.nodedb.NodeDB(cloud_folders.nodes, node_id, True)
        node_dbs[node].set_user('user_' + node)  # essentially override defaults
        node_dbs[node].set_computer('computer_' + node)  # essentially override defaults
    preferences['a'].set_crypto_key(latus_key)  # a has the latus key, b and c want it

    app = QApplication(sys.argv)
    dialog = ManagementDialog(app_data_folders['a'])
    dialog.show()
    dialog.exec_()
    print(app.applicationName())
 def __init__(self, page, parent=None):
     super(HelpForm, self).__init__(parent)
     self.setAttribute(Qt.WA_DeleteOnClose)
     self.setWindowModality(Qt.WindowModal)
     # actions
     backAction = QAction(QIcon(":/back.png"), "&Back", self)
     backAction.setShortcut(QKeySequence.Back)
     homeAction = QAction(QIcon(":/home.png"), "&Home", self)
     homeAction.setShortcut("Home")
     self.pageLabel = QLabel()
     #toolbar
     toolBar = QToolBar()
     toolBar.addAction(backAction)
     toolBar.addAction(homeAction)
     toolBar.addWidget(self.pageLabel)
     self.textBrowser = QTextBrowser()
     # layout
     layout = QVBoxLayout()
     layout.addWidget(toolBar)
     layout.addWidget(self.textBrowser, 1)
     self.setLayout(layout)
     # signals and slots
     backAction.triggered.connect(self.textBrowser.backward)
     homeAction.triggered.connect(self.textBrowser.home)
     self.textBrowser.sourceChanged.connect(self.updatePageTitle)
     self.textBrowser.setSearchPaths([":/help"])
     self.textBrowser.setSource(QUrl(page))
     self.resize(400, 600)
     self.setWindowTitle("{0} Help".format(QApplication.applicationName()))
Пример #13
0
def main():
    root = os.path.join('temp', 'gui_management')
    if os.path.exists(root):
        shutil.rmtree(root)

    latus.logger.init(root)
    latus.logger.set_console_log_level(logging.INFO)
    latus_key = 'my_secret_latus_key'

    log_folder = os.path.join(root, 'log')
    latus.util.make_dirs(log_folder)
    latus.logger.init(log_folder)
    cloud_folder = os.path.join(root, 'cloud')
    cloud_folders = latus.folders.CloudFolders(cloud_folder)

    preferences = {}
    node_dbs = {}
    app_data_folders = {}
    for node in ['a', 'b', 'c']:
        app_data_folders[node] = os.path.join(root, node, 'appdata')
        preferences[node] = latus.preferences.Preferences(app_data_folders[node], True)
        node_id = latus.util.new_node_id()
        preferences[node].set_node_id(node_id)
        preferences[node].set_cloud_root(cloud_folder)
        latus.util.make_dirs(cloud_folders.nodes)
        node_dbs[node] = latus.nodedb.NodeDB(cloud_folders.nodes, node_id, True)
        node_dbs[node].set_user('user_' + node)  # essentially override defaults
        node_dbs[node].set_computer('computer_' + node)  # essentially override defaults
    preferences['a'].set_crypto_key(latus_key)  # a has the latus key, b and c want it

    app = QApplication(sys.argv)
    dialog = ManagementDialog(app_data_folders['a'])
    dialog.show()
    dialog.exec_()
    print(app.applicationName())
Пример #14
0
 def on_lstPorts_itemDoubleClicked(self, item):
     port = item.text()
     if device.connect(port) is False:
         QMessageBox.critical(self.parent, QApplication.applicationName(),
                              "Could not connect to {}".format(port))
     else:
         self.parent.show_page1(first=True)
Пример #15
0
 def default_setup(self):
     setup = {
         'setup': {
             'app': {
                 'name': QApplication.applicationName(),
                 'version': QApplication.applicationVersion()
             },
             'result_t_z': {
                 'font': {
                     'name': 'Monospace',
                     'size': 7
                 },
                 'color': '#fff',
                 'background_color': '#300A24'
             },
             'result_wind': {
                 'font': {
                     'name': 'Monospace',
                     'size': 7
                 },
                 'color': '#fff',
                 'background_color': '#300A24'
             },
             'result_spr': {
                 'font': {
                     'name': 'Monospace',
                     'size': 7
                 },
                 'color': '#fff',
                 'background_color': '#300A24'
             }
         }
     }
     return setup
 def __init__(self,  page,  parent=None):
     super(HelpForm, self).__init__(parent)
     self.setAttribute(Qt.WA_DeleteOnClose)
     self.setWindowModality(Qt.WindowModal)
     # actions
     backAction = QAction(QIcon(":/back.png"), "&Back", self)
     backAction.setShortcut(QKeySequence.Back)
     homeAction = QAction(QIcon(":/home.png"), "&Home", self)
     homeAction.setShortcut("Home")
     self.pageLabel = QLabel()
     #toolbar
     toolBar = QToolBar()
     toolBar.addAction(backAction)
     toolBar.addAction(homeAction)
     toolBar.addWidget(self.pageLabel)
     self.textBrowser = QTextBrowser()
     # layout
     layout = QVBoxLayout()
     layout.addWidget(toolBar)
     layout.addWidget(self.textBrowser, 1)
     self.setLayout(layout)
     # signals and slots
     backAction.triggered.connect(self.textBrowser.backward)
     homeAction.triggered.connect(self.textBrowser.home)
     self.textBrowser.sourceChanged.connect(self.updatePageTitle)
     self.textBrowser.setSearchPaths([":/help"])
     self.textBrowser.setSource(QUrl(page))
     self.resize(400, 600)
     self.setWindowTitle("{0} Help".format(
         QApplication.applicationName()))
    def load(self, fileName):  # 입력받은 이미지를 화면에 출력하기 위한 함수
        image = QImage(fileName)
        if image.isNull():  # 파일이 존재하지 않을 경우 경고 표시 후 빈화면 출력
            QMessageBox.information(self, QApplication.applicationName(),
                                    "Cannot load " + fileName)
            self.setPixmap(QPixmap())

        self.imageLabel.setPixmap(QPixmap.fromImage(image))
Пример #18
0
 def on_aboutAction_triggered(self):
     QMessageBox.about(
         self, self.tr('About'),
         self.tr('<h1>%s %s</h1>\n' +
                 '<p>Developed by <a href="%s">%s</a></p>') %
         (QApplication.applicationName(), QApplication.applicationVersion(),
          QApplication.organizationDomain(),
          QApplication.organizationName()))
Пример #19
0
    def __init__(self):
        super(SettingsWindow, self).__init__()
        application_name = QApplication.applicationName()
        self.setWindowTitle('{} Settings'.format(application_name))
        self.setWindowIcon(QIcon(':/kamatis.svg'))

        self.__settings_widget = SettingsWidget(self)
        self.setCentralWidget(self.__settings_widget)
Пример #20
0
    def actionSVGSlot(self):
        """docstring for actionSVGSlot"""
        fname = os.path.basename(str(self.fileName()))
        if fname is None:
            directory = "."
        else:
            directory = QFileInfo(fname).path()

        fdialog = QFileDialog(self.win,
                              "%s - Save As" % QApplication.applicationName(),
                              directory,
                              "%s (*.svg)" % QApplication.applicationName())
        fdialog.setAcceptMode(QFileDialog.AcceptSave)
        fdialog.setWindowFlags(Qt.Sheet)
        fdialog.setWindowModality(Qt.WindowModal)
        self.svgsavedialog = fdialog
        self.svgsavedialog.filesSelected.connect(self.saveSVGDialogCallback)
        fdialog.open()
Пример #21
0
    def load_setup(self):
        try:
            with open(self.CONFIG_FNAME, 'r') as f:
                setup = json.load(f)

            if setup['setup']['app']['name'] != QApplication.applicationName() or \
           setup['setup']['app']['version'] != QApplication.applicationVersion():
                QMessageBox.warning(
                    self, QApplication.applicationName(),
                    'Поточний файл налаштувань створений не для цієї програми або \
засторілий.\nПрийняті нові налаштування за промовчанням.')
                setup = self.default_setup()
        except Exception as err:
            QMessageBox.critical(self, QApplication.applicationName(),
                                 str(err))
            setup = self.default_setup()
        finally:
            self.__setup = setup
Пример #22
0
    def actionSVGSlot(self):
        """docstring for actionSVGSlot"""
        fname = os.path.basename(str(self.fileName()))
        if fname is None:
            directory = "."
        else:
            directory = QFileInfo(fname).path()

        fdialog = QFileDialog(self.win,
                              "%s - Save As" % QApplication.applicationName(),
                              directory,
                              "%s (*.svg)" % QApplication.applicationName())
        fdialog.setAcceptMode(QFileDialog.AcceptSave)
        fdialog.setWindowFlags(Qt.Sheet)
        fdialog.setWindowModality(Qt.WindowModal)
        self.svgsavedialog = fdialog
        self.svgsavedialog.filesSelected.connect(self.saveSVGDialogCallback)
        fdialog.open()
Пример #23
0
 def __init__(self, parent=None):
     super().__init__(parent)
     self.setIcon(QMessageBox.Question)
     self.setWindowTitle(QApplication.applicationName())
     self.setWindowModality(Qt.WindowModal)
     if platformSpecific.showAppIconInDialog():
         iconSize = self.style().pixelMetric(QStyle.PM_MessageBoxIconSize, None, self)
         icon = self.windowIcon()
         size = icon.actualSize(QSize(iconSize, iconSize))
         self.setIconPixmap(icon.pixmap(size))
Пример #24
0
 def __init__(self, parent=None):
     super().__init__(parent)
     self.setIcon(QMessageBox.Question)
     self.setWindowTitle(QApplication.applicationName())
     self.setWindowModality(Qt.WindowModal)
     if platformSpecific.showAppIconInDialog():
         iconSize = self.style().pixelMetric(QStyle.PM_MessageBoxIconSize,
                                             None, self)
         icon = self.windowIcon()
         size = icon.actualSize(QSize(iconSize, iconSize))
         self.setIconPixmap(icon.pixmap(size))
Пример #25
0
    def __populate_layout(self):
        layout = self.layout()

        work_length_spin_box = QSpinBox(self)
        work_length_spin_box.setMinimum(1)
        work_length_spin_box.setSuffix(' mins')
        work_length_spin_box.setToolTip('Length of the work period')
        self.__settings.add_handler('work', work_length_spin_box)
        layout.addRow('&Work:', work_length_spin_box)

        short_break_length_spin_box = QSpinBox(self)
        short_break_length_spin_box.setMinimum(1)
        short_break_length_spin_box.setSuffix(' mins')
        text = 'Length of the short break period'
        short_break_length_spin_box.setToolTip(text)
        self.__settings.add_handler('short_break', short_break_length_spin_box)
        layout.addRow('&Short break:', short_break_length_spin_box)

        long_break_length_spin_box = QSpinBox(self)
        long_break_length_spin_box.setMinimum(1)
        long_break_length_spin_box.setSuffix(' mins')
        text = 'Length of the long break period'
        long_break_length_spin_box.setToolTip(text)
        self.__settings.add_handler('long_break', long_break_length_spin_box)
        layout.addRow('&Long break:', long_break_length_spin_box)

        cycle_length_spin_box = QSpinBox(self)
        cycle_length_spin_box.setMinimum(1)
        cycle_length_spin_box.setSuffix(' periods')
        text = 'How many work + short break periods before taking a long break'
        cycle_length_spin_box.setToolTip(text)
        self.__settings.add_handler('cycle', cycle_length_spin_box)
        layout.addRow('&Cycle length:', cycle_length_spin_box)

        autostart_check_box = QCheckBox(self)
        application_name = QApplication.applicationName()
        text = 'Autostart {} on login'.format(application_name)
        autostart_check_box.setToolTip(text)
        self.__settings.add_handler('autostart', autostart_check_box)
        layout.addRow('&Autostart:', autostart_check_box)

        sound_combo_box = SoundComboBox(self)
        sound_combo_box.currentIndexChanged.connect(self.__on_choose_sound)
        self.__sound_combo_box = sound_combo_box
        layout.addRow('&Play sound:', self.__sound_combo_box)

        self.__test_sound_button = QPushButton('Test sound', self)
        self.__test_sound_button.clicked.connect(self.__on_test_sound_clicked)
        layout.addRow(self.__test_sound_button)

        self.__sound_combo_box.select_default()

        button_box = self.__get_buttons()
        layout.addRow(button_box)
Пример #26
0
def prevent_second_instance(app: QApplication, unique_name: str) -> None:
    # This function is only necessary on Qubes, so we can skip it on other platforms to help devs
    if platform.system() != 'Linux':  # pragma: no cover
        return

    # Null byte triggers abstract namespace
    IDENTIFIER = '\0' + app.applicationName() + unique_name
    ALREADY_BOUND_ERRNO = 98

    app.instance_binding = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
    try:
        app.instance_binding.bind(IDENTIFIER)
    except OSError as e:
        if e.errno == ALREADY_BOUND_ERRNO:
            err_dialog = QMessageBox()
            err_dialog.setText(app.applicationName() + ' is already running.')
            err_dialog.exec()
            sys.exit()
        else:
            raise
Пример #27
0
def __messageBox(parent,
                 title,
                 text,
                 icon,
                 buttons=QMessageBox.Ok,
                 defaultButton=QMessageBox.NoButton,
                 textFormat=Qt.AutoText):
    """
    Private module function to show a modal message box.
    
    @param parent parent widget of the message box (QWidget)
    @param title caption of the message box (string)
    @param text text to be shown by the message box (string)
    @param icon type of icon to be shown (QMessageBox.Icon)
    @param buttons flags indicating which buttons to show
        (QMessageBox.StandardButtons)
    @param defaultButton flag indicating the default button
        (QMessageBox.StandardButton)
    @param textFormat format of the text (Qt.TextFormat)
    @return button pressed by the user (QMessageBox.StandardButton)
    """
    messageBox = QMessageBox(parent)
    messageBox.setIcon(icon)
    if parent is not None:
        messageBox.setWindowModality(Qt.WindowModal)
    if title == "":
        messageBox.setWindowTitle("{0}".format(QApplication.applicationName()))
    else:
        messageBox.setWindowTitle("{0} - {1}".format(
            QApplication.applicationName(), title))
    messageBox.setTextFormat(textFormat)
    messageBox.setText(text)
    messageBox.setStandardButtons(buttons)
    messageBox.setDefaultButton(defaultButton)
    messageBox.exec_()
    clickedButton = messageBox.clickedButton()
    if clickedButton is None:
        return QMessageBox.NoButton
    else:
        return messageBox.standardButton(clickedButton)
Пример #28
0
    def query_access(self):
        u'''Запрошує доступ до програми
        '''
        
        deadline_dt = datetime(2018, 5, 31, 23, 59, 59).replace(tzinfo=tzlocal())
        
        ntp_dt = ntptime()
        curr_dt = (ntp_dt.replace(tzinfo=tzlocal()) if ntp_dt else 
                   datetime.now().replace(tzinfo=tzlocal()))
        
        if curr_dt > deadline_dt:
            QMessageBox.critical(None, QApplication.applicationName(),
              'Термін доступності цієї програми вичерпано!\n'
'Зверніться до розробника для отримання нової копії програми!')
            self.exit(1)
            raise SystemExit(1)
        else:
            QMessageBox.warning(None, QApplication.applicationName(),
              'Термін доступності цієї програми закінчується <b>{}</b>.'.format(
                  deadline_dt.strftime('%d.%m.%Y %H:%M:%S')))
            
            return  # Пройшов термін дозволу на перегляд і друк документу.
Пример #29
0
def run():
    app = QApplication(sys.argv)
    app.setOrganizationName("manuskript")
    app.setOrganizationDomain("www.theologeek.ch")
    app.setApplicationName("manuskript")
    app.setApplicationVersion(_version)

    icon = QIcon()
    for i in [16, 31, 64, 128, 256, 512]:
        icon.addFile(appPath("icons/Manuskript/icon-{}px.png".format(i)))
    qApp.setWindowIcon(icon)

    app.setStyle("Fusion")

    # Load style from QSettings
    settings = QSettings(app.organizationName(), app.applicationName())
    if settings.contains("applicationStyle"):
        style = settings.value("applicationStyle")
        app.setStyle(style)

    # Translation process
    locale = QLocale.system().name()

    appTranslator = QTranslator()
    # By default: locale
    translation = appPath(
        os.path.join("i18n", "manuskript_{}.qm".format(locale)))

    # Load translation from settings
    if settings.contains("applicationTranslation"):
        translation = appPath(
            os.path.join("i18n", settings.value("applicationTranslation")))
        print("Found translation in settings:", translation)

    if appTranslator.load(translation):
        app.installTranslator(appTranslator)
        print(app.tr("Loaded translation: {}.").format(translation))

    else:
        print(
            app.tr("Warning: failed to load translator for locale {}...").
            format(locale))

    QIcon.setThemeSearchPaths(QIcon.themeSearchPaths() + [appPath("icons")])
    QIcon.setThemeName("NumixMsk")
    # qApp.setWindowIcon(QIcon.fromTheme("im-aim"))

    # Seperating launch to avoid segfault, so it seem.
    # Cf. http://stackoverflow.com/questions/12433491/is-this-pyqt-4-python-bug-or-wrongly-behaving-code
    launch()
Пример #30
0
def __messageBox(parent, title, text, icon,
                 buttons=QMessageBox.Ok, defaultButton=QMessageBox.NoButton,
                 textFormat=Qt.AutoText):
    """
    Private module function to show a modal message box.
    
    @param parent parent widget of the message box (QWidget)
    @param title caption of the message box (string)
    @param text text to be shown by the message box (string)
    @param icon type of icon to be shown (QMessageBox.Icon)
    @param buttons flags indicating which buttons to show
        (QMessageBox.StandardButtons)
    @param defaultButton flag indicating the default button
        (QMessageBox.StandardButton)
    @param textFormat format of the text (Qt.TextFormat)
    @return button pressed by the user (QMessageBox.StandardButton)
    """
    messageBox = QMessageBox(parent)
    messageBox.setIcon(icon)
    if parent is not None:
        messageBox.setWindowModality(Qt.WindowModal)
    if title == "":
        messageBox.setWindowTitle("{0}".format(
            QApplication.applicationName()))
    else:
        messageBox.setWindowTitle("{0} - {1}".format(
            QApplication.applicationName(), title))
    messageBox.setTextFormat(textFormat)
    messageBox.setText(text)
    messageBox.setStandardButtons(buttons)
    messageBox.setDefaultButton(defaultButton)
    messageBox.exec_()
    clickedButton = messageBox.clickedButton()
    if clickedButton is None:
        return QMessageBox.NoButton
    else:
        return messageBox.standardButton(clickedButton)
Пример #31
0
def startmain():
    """
    Initialise the application and display the main window.
    """
    args = parse_arguments()

    app = QApplication(sys.argv)
    app.cleanup_files = []

    if not args.native_style:
        app.setStyle(QStyleFactory.create('Fusion'))
        app.setPalette(QApplication.style().standardPalette())

    app_icon = QIcon(':/icons/ui/ot_icon.svg')
    print(app_icon.isNull(), app_icon.pixmap(200, 200).isNull())

    app.setApplicationName(APP_NAME)
    app.setApplicationVersion(VERSION_STRING)
    app.setOrganizationName(ORG_NAME)
    app.setWindowIcon(app_icon)

    print('AppName: {0:s}'.format(app.applicationName()))
    print('AppVersion: {0:s}'.format(app.applicationVersion()))
    print('Company Name: {0:s}'.format(app.organizationName()))

    QLocale.setDefault(QLocale(QLocale.English, QLocale.UnitedKingdom))

    # Add passed arguments to app.
    app.args = args
    print('Args:', app.args)

    # Check to see if application already running.
    existing_pid = instance_check(app)
    if existing_pid:
        print(existing_pid)
        if app.args.quit_existing:
            # Command line argument passed to close existing program. Do that, then quit.
            if platform.system() == "Windows":
                subprocess.Popen("taskkill /F /T /PID %i" % existing_pid, shell=True)
            else:
                os.killpg(existing_pid, signal.SIGKILL)
        else:
            message_box_error('Program already running.',
                              'You can only have one copy of the Bing Wallpaper Changer running at once.')
        sys.exit()

    mainwindow = MainWindow()
    # mainwindow.show()
    sys.exit(app.exec_())
Пример #32
0
def main(n):
    app = QApplication(sys.argv)
    setDefaultAppLocale(app)
    app.setApplicationName('KwWorkWindow')
    app.setApplicationVersion('1.0.0')

    if n == 1:
        window = KwWorkWindow()
    elif n == 2:
        window = QWidget()
        layout = QVBoxLayout(window)
        button = QPushButton('Як тебе не любити')
        button.setObjectName('calcButton')
        layout.addWidget(button)

        setup = {
            'setup': {
                'app': {
                    'name': QApplication.applicationName(),
                    'version': QApplication.applicationVersion()
                },
                'KwResultBrowser': {
                    'font': {
                        'name': 'Monospace',
                        'size': 7
                    },
                    'color': '#fff',
                    'background_color': '#300A24'
                }
            }
        }

        browser = KwResultBrowser(setup['setup']['KwResultBrowser'])
        browser.setText('Anton')
        layout.addWidget(browser)
        colorButton = KwColorButton()
        layout.addWidget(colorButton)
        colorChoicer = KwColorChoicer(Qt.green, Qt.magenta)
        layout.addWidget(colorChoicer)
        font_dataChoicer = KwFontDataChoicer()
        font_dataChoicer.fontChanged[str].connect(lambda font: print(font))
        font_dataChoicer.font_sizeChanged[int].connect(lambda s: print(s))
        layout.addWidget(font_dataChoicer)

    with open('ww_style.css', 'r') as f:
        app.setStyleSheet(f.read())

    window.show()
    sys.exit(app.exec())
Пример #33
0
 def __init__(self, parent=None):
     super().__init__(parent)
     # TODO: make sure we need this on Windows
     self.setWindowTitle(QApplication.applicationName())
     self.setText(self.tr("Do you want to save your changes?"))
     self.setInformativeText(self.tr("Your changes will be lost if you don’t save them."))
     self.setWindowModality(Qt.WindowModal)
     self.setStandardButtons(QMessageBox.Save | QMessageBox.Discard | QMessageBox.Cancel)
     self.setDefaultButton(QMessageBox.Save)
     self.setIcon(QMessageBox.Question)
     if platformSpecific.showAppIconInDialog():
         iconSize = self.style().pixelMetric(QStyle.PM_MessageBoxIconSize, None, self)
         icon = self.windowIcon()
         size = icon.actualSize(QSize(iconSize, iconSize))
         self.setIconPixmap(icon.pixmap(size))
Пример #34
0
 def saveFileDialog(self):
     fname = self.fileName()
     if fname is None:
         directory = "."
     else:
         directory = QFileInfo(fname).path()
     if util.isWindows():  # required for native looking file window
         fname = QFileDialog.getSaveFileName(
             self.win, "%s - Save As" % QApplication.applicationName(),
             directory, "%s (*.json)" % QApplication.applicationName())
         if isinstance(fname, (list, tuple)):
             fname = fname[0]
         self.writeDocumentToFile(fname)
     else:  # access through non-blocking callback
         fdialog = QFileDialog(
             self.win, "%s - Save As" % QApplication.applicationName(),
             directory, "%s (*.json)" % QApplication.applicationName())
         fdialog.setAcceptMode(QFileDialog.AcceptSave)
         fdialog.setWindowFlags(Qt.Sheet)
         fdialog.setWindowModality(Qt.WindowModal)
         self.filesavedialog = fdialog
         self.filesavedialog.filesSelected.connect(
             self.saveFileDialogCallback)
         fdialog.open()
Пример #35
0
 def updateToolTip(self):
     db = ReaderDb()
     db.execute("select * from store where iscache=1")
     unread = db.cursor.fetchall()
     db.execute("select * from store where isstore=1")
     store = db.cursor.fetchall()
     db.execute("select * from store where istrash=1")
     trash = db.cursor.fetchall()
     self.setToolTip(
         self.tr('''<span style='font-size:14pt'>{} - {}</span>
     <br><span style='font-size:10pt'>Unread: {}</span>
     <br><span style='font-size:10pt'>Stored: {}</span>
     <br><span style='font-size:10pt'>Deleted: {}</span>''').format(
             QApplication.applicationName(),
             QApplication.applicationVersion(), len(unread), len(store),
             len(trash)))
Пример #36
0
    def __init__(self, parent):
        QDialog.__init__(self, parent)
        self.setupUi(self)
        appname = QApplication.applicationName()
        self.setWindowTitle(self.tr("About {}".format(appname)))
        self.textDisplay.setHtml("""<h1>About {appName}</h1>
        <p><b>Version {version}</b></p>
        <p>{appName} is an editor for genome-scale metabolic models in order to facilitate selection, modification and
        annotation of genome-scale models.<br>
        This program has been developed at the Technical University of Denmark (DTU).</p>

        {appName} is built on top of excellent free software packages:
        <ul>
        <li>Cobrapy for model solving</li>
        <li>Escher for visualization</li>
        <li>Networkx for network layout</li>
        <li>MetaNetX for annotation</li>
        </ul>

        <p>If you need help or want to report a bug, please visit the <a href="{projectPage}">project page</a>.</p>

        <p>If you use {appName} in a scientific publication please cite:<br>
        <b>{citation}</b></p>

        <p>{appName} is distributed under the following license:</b></p>

        <p>The MIT License (MIT)<br>
        Copyright (c) 2016 Technical University of Denmark (DTU)</p>

        <p>Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
        documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
        the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, 
        and to permit persons to whom the Software is furnished to do so, subject to the following conditions:</p>

        <p>The above copyright notice and this permission notice shall be included in all copies or substantial 
        portions of the Software.</p>

        <p>THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT 
        LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO 
        EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN 
        AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE 
        OR OTHER DEALINGS IN THE SOFTWARE.</p>

        """.format(appName=appname,
                   projectPage=__projectpage__,
                   version=__version__,
                   citation=__citation__))
Пример #37
0
def run():
    app = QApplication(sys.argv)
    app.setOrganizationName("manuskript")
    app.setOrganizationDomain("www.theologeek.ch")
    app.setApplicationName("manuskript")
    app.setApplicationVersion(_version)

    icon = QIcon()
    for i in [16, 31, 64, 128, 256, 512]:
        icon.addFile(appPath("icons/Manuskript/icon-{}px.png".format(i)))
    qApp.setWindowIcon(icon)

    app.setStyle("Fusion")

    # Load style from QSettings
    settings = QSettings(app.organizationName(), app.applicationName())
    if settings.contains("applicationStyle"):
        style = settings.value("applicationStyle")
        app.setStyle(style)

    # Translation process
    locale = QLocale.system().name()

    appTranslator = QTranslator()
    # By default: locale
    translation = appPath(os.path.join("i18n", "manuskript_{}.qm".format(locale)))

    # Load translation from settings
    if settings.contains("applicationTranslation"):
        translation = appPath(os.path.join("i18n", settings.value("applicationTranslation")))
        print("Found translation in settings:", translation)

    if appTranslator.load(translation):
        app.installTranslator(appTranslator)
        print(app.tr("Loaded translation: {}.").format(translation))

    else:
        print(app.tr("Warning: failed to load translator for locale {}...").format(locale))

    QIcon.setThemeSearchPaths(QIcon.themeSearchPaths() + [appPath("icons")])
    QIcon.setThemeName("NumixMsk")
    # qApp.setWindowIcon(QIcon.fromTheme("im-aim"))

    # Seperating launch to avoid segfault, so it seem.
    # Cf. http://stackoverflow.com/questions/12433491/is-this-pyqt-4-python-bug-or-wrongly-behaving-code
    launch()
Пример #38
0
    def setupDownloadingUi(self):
        self.resetUi()
        self.dialog.setWindowTitle(
            self.tr("Updating") + " %s…" % QApplication.applicationName())
        self.dialog.setMinimumSize(QSize(rt(500), rt(120)))
        self.dialog.resize(rt(500), rt(120))
        show_widgets = [
            self.ui.main_container, self.ui.label_icon, self.ui.progress_bar,
            self.ui.label_downloading, self.ui.button_cancel_loading,
            self.ui.progress_label
        ]
        for widget in show_widgets:
            widget.show()

        self.ui.button_cancel_loading.setEnabled(True)
        self.ui.button_cancel_loading.setFocus()
        self.ui.button_cancel_loading.clicked.connect(self.dialog.reject)
        self.dialog.adjustSize()
Пример #39
0
 def about(self):
     name = QApplication.applicationName()
     domain = QApplication.organizationDomain()
     text = self.tr(
         "<h3>About {n}</h3>"
         "<p>{n} is a cross-platform, modular typeface design "
         "application.</p><p>{n} is built on top of "
         "<a href='http://ts-defcon.readthedocs.org/en/ufo3/'>defcon</a> "
         "and includes scripting support "
         "with a <a href='http://robofab.com/'>robofab</a>-like API.</p>"
         "<p>Version {} {} – Python {}.").format(
         __version__, gitShortHash, platform.python_version(), n=name)
     if domain:
         text += self.tr("<br>See <a href='http://{d}'>{d}</a> for more "
                         "information.</p>").format(d=domain)
     else:
         text += "</p>"
     QMessageBox.about(self, self.tr("About {}").format(name), text)
Пример #40
0
def tempdir():
    """Return a temporary directory that is erased on app quit."""
    import tempfile
    global _tempdir
    try:
        _tempdir
    except NameError:
        name = QApplication.applicationName().translate({ord('/'): None
                                                         }) or 'qpageview'
        _tempdir = tempfile.mkdtemp(prefix=name + '-')
        import atexit
        import shutil

        @atexit.register
        def remove():
            shutil.rmtree(_tempdir, ignore_errors=True)

    return tempfile.mkdtemp(dir=_tempdir)
Пример #41
0
def main(n):
    app = KwAntTeploMonitorDbl(sys.argv)
    app_exec_name = 'kwCalcGQ'
    app.setApplicationName(app_exec_name)
    app.setApplicationVersion('0.1.0')
    app.setWindowIcon(QIcon(os.path.abspath('class_x24.png')))
    app.setApplicationDisplayName('{} v {}'.format(app_exec_name.lstrip('kw'),
                                  app.applicationVersion()))
    QFontDatabase.addApplicationFont('Hack-Regular.ttf')
    
    if n == 1:
        window = KwMainWindow()
    elif n == 2:
        window = QWidget()
        layout = QVBoxLayout(window)
        button = QPushButton('Як тебе не любити')
        button.setObjectName('calcButton')
        layout.addWidget(button)
        
        setup = {'setup': {'app':
            {'name': QApplication.applicationName(),
             'version': QApplication.applicationVersion()},
            'KwResultBrowser': {'font': {'name': 'Monospace', 'size': 7}, 
                                  'color': '#fff', 'background_color': '#300A24'}
                           }
                 }
        
        browser = KwResultBrowser(setup['setup']['KwResultBrowser'])
        browser.setText('Anton')
        layout.addWidget(browser)
        colorButton = KwColorButton()
        layout.addWidget(colorButton)
        colorChoicer = KwColorChoicer(Qt.green, Qt.magenta)
        layout.addWidget(colorChoicer)
        font_dataChoicer = KwFontDataChoicer()
        font_dataChoicer.fontChanged[str].connect(lambda font: print(font))
        font_dataChoicer.font_sizeChanged[int].connect(lambda s: print(s))
        layout.addWidget(font_dataChoicer)
        
    with open('ww_style.css', 'r') as f:
        app.setStyleSheet(f.read())
        
    window.show()
    sys.exit(app.exec())
Пример #42
0
 def closeEvent(self, event):
     if self.editor.document().isModified():
         name = QApplication.applicationName()
         closeDialog = QMessageBox(
             QMessageBox.Question,
             name,
             "Save your changes?",
             QMessageBox.Save | QMessageBox.Discard | QMessageBox.Cancel,
             self
         )
         closeDialog.setInformativeText(
             "Your changes will be lost if you don’t save them."
         )
         closeDialog.setModal(True)
         ret = closeDialog.exec_()
         if ret == QMessageBox.Save:
             self.save()
             event.accept()
         elif ret == QMessageBox.Discard:
             event.accept()
         else:
             event.ignore()
Пример #43
0
def test_application_name(app: QApplication):
    assert app is not None
    assert app.applicationName() == "Génial"
Пример #44
0
def main(args=None):
    print("starting epyq")

    # TODO: CAMPid 9757656124812312388543272342377
    app = QApplication(sys.argv)
    sys.excepthook = excepthook
    app.setStyleSheet("QMessageBox {{ messagebox-text-interaction-flags: {}; }}".format(Qt.TextBrowserInteraction))
    app.setOrganizationName("EPC Power Corp.")
    app.setApplicationName("EPyQ")

    settings = QSettings(app.organizationName(), app.applicationName())

    if args is None:
        import argparse

        ui_default = "main.ui"

        parser = argparse.ArgumentParser()

        default_interfaces = {"Linux": "socketcan", "Windows": "pcan"}
        parser.add_argument("--interface", default=default_interfaces[platform.system()])

        parser.add_argument("--channel", default=None)
        parser.add_argument("--ui", default=ui_default)
        parser.add_argument("--generate", "-g", action="store_true")
        parser.add_argument("devices", nargs="*")
        args = parser.parse_args()

    if args.channel is None:
        interface = "offline"
        channel = ""
    else:
        interface = args.interface
        channel = args.channel

    # TODO: find the 'proper' way to handle both quoted and non-quoted paths
    for i, arg in enumerate(args.devices):
        if arg[0] == arg[-1] and len(arg) >= 2:
            if arg[0] in ['"', "'"]:
                args.devices[i] = arg[1:-1]

    # TODO: CAMPid 9756652312918432656896822
    if interface != "offline":
        real_bus = can.interface.Bus(bustype=interface, channel=channel)
    else:
        real_bus = None
    bus = epyqlib.busproxy.BusProxy(bus=real_bus)

    if args.generate:
        print("generating")
        start_time = time.monotonic()

        frame_name = "StatusControlVolts2"
        signal_name = "n15V_Supply"
        frame = epyqlib.canneo.Frame(matrix_tx.frameByName(frame_name))
        signal = epyqlib.canneo.Signal(frame.frame.signalByName(signal_name), frame)

        message = can.Message(extended_id=frame.frame._extended, arbitration_id=frame.frame._Id, dlc=frame.frame._Size)

        messages = [
            can.Message(
                extended_id=True, arbitration_id=486517239, dlc=8, data=bytearray([0, 1, 0, 160, 7, 208, 5, 220])
            ),
            can.Message(
                extended_id=True, arbitration_id=486517239, dlc=8, data=bytearray([0, 4, 0, 160, 1, 77, 0, 160])
            ),
            can.Message(extended_id=True, arbitration_id=218082369, dlc=8, data=bytearray([0, 0, 0, 3, 0, 0, 0, 42])),
        ]

        # Copy from PCAN generated and logged messages
        # Bus=2,ID=486517239x,Type=D,DLC=8,DA=0,Data=0 1 0 160 7 208 5 220 ,
        # Bus=2,ID=486517239x,Type=D,DLC=8,DA=0,Data=0 4 0 160 1 77 0 160 ,
        # Bus=2,ID=218082369x,Type=D,DLC=8,DA=0,Data=0 0 0 3 0 0 0 42 ,

        last_send = 0
        while True:
            time.sleep(0.010)
            now = time.monotonic()
            if now - last_send > 0.100:
                last_send = now
                elapsed_time = time.monotonic() - start_time
                value = math.sin(elapsed_time) / 2
                value *= 2
                nominal = -15
                value += nominal
                human_value = value
                value /= float(signal.signal._factor)
                value = round(value)
                print("{:.3f}: {}".format(elapsed_time, value))
                message.data = frame.pack([value, 0, 1, 2])
                bus.send(message)

                bus.send(
                    can.Message(
                        extended_id=True,
                        arbitration_id=0xFF9B41,
                        dlc=8,
                        data=bytearray([0, 0, 0, 0, 0, 0, 0, int(human_value > nominal)]),
                    )
                )

                for m in messages:
                    bus.send(m)
        sys.exit(0)

    devices = [os.path.abspath(f) for f in args.devices]

    window = Window(ui_file=args.ui, devices=devices, bus=bus)

    window.show()
    return app.exec_()
Пример #45
0
def prepare(tests=False):
    app = QApplication(sys.argv)
    app.setOrganizationName("manuskript"+("_tests" if tests else ""))
    app.setOrganizationDomain("www.theologeek.ch")
    app.setApplicationName("manuskript"+("_tests" if tests else ""))
    app.setApplicationVersion(getVersion())

    print("Running manuskript version {}.".format(getVersion()))
    icon = QIcon()
    for i in [16, 32, 64, 128, 256, 512]:
        icon.addFile(appPath("icons/Manuskript/icon-{}px.png".format(i)))
    qApp.setWindowIcon(icon)

    app.setStyle("Fusion")

    # Load style from QSettings
    settings = QSettings(app.organizationName(), app.applicationName())
    if settings.contains("applicationStyle"):
        style = settings.value("applicationStyle")
        app.setStyle(style)

    # Translation process
    locale = QLocale.system().name()

    appTranslator = QTranslator(app)
    # By default: locale

    def extractLocale(filename):
        # len("manuskript_") = 13, len(".qm") = 3
        return filename[11:-3] if len(filename) >= 16 else ""

    def tryLoadTranslation(translation, source):
        if appTranslator.load(appPath(os.path.join("i18n", translation))):
            app.installTranslator(appTranslator)
            print(app.tr("Loaded translation from {}: {}.").format(source, translation))
            return True
        else:
            print(app.tr("Note: No translator found or loaded from {} for locale {}.").
                  format(source, extractLocale(translation)))
            return False

    # Load translation from settings
    translation = ""
    if settings.contains("applicationTranslation"):
        translation = settings.value("applicationTranslation")
        print("Found translation in settings:", translation)

    if (translation != "" and not tryLoadTranslation(translation, "settings")) or translation == "":
        # load from settings failed or not set, fallback
        translation = "manuskript_{}.qm".format(locale)
        tryLoadTranslation(translation, "system locale")

    QIcon.setThemeSearchPaths(QIcon.themeSearchPaths() + [appPath("icons")])
    QIcon.setThemeName("NumixMsk")

    # Font siue
    if settings.contains("appFontSize"):
        f = qApp.font()
        f.setPointSize(settings.value("appFontSize", type=int))
        app.setFont(f)

    # Main window
    from manuskript.mainWindow import MainWindow

    MW = MainWindow()
    # We store the system default cursor flash time to be able to restore it
    # later if necessary
    MW._defaultCursorFlashTime = qApp.cursorFlashTime()

    # Command line project
    if len(sys.argv) > 1 and sys.argv[1][-4:] == ".msk":
        if os.path.exists(sys.argv[1]):
            path = os.path.abspath(sys.argv[1])
            MW._autoLoadProject = path

    return app, MW