Example #1
0
class DataJar(QNetworkCookieJar):
	def __init__(self):
		super(DataJar, self).__init__()
		self.settings = QSettings(assets.fs.dataPath() + '/data.ini', QSettings.IniFormat)
		self.load()

	def load(self):
		strCookies = self.settings.value('cookies')
		if strCookies:
			self.setAllCookies(QNetworkCookie.parseCookies(strCookies))

	def save(self):
		cookies = self.allCookies()
		strCookies = ''
		for cookie in cookies:
			strCookies += cookie.toRawForm() + '\n'
		self.settings.setValue('cookies', strCookies)

	def set(self, name, value):
		self.settings.setValue('Data/' + name, value)

	def get(self, name):
		return self.settings.value('Data/' + name)

	def remove(self, name = None):
		if name is None:
			self.settings.remove('Data')
		else:
			self.settings.remove('Data/' + name)
Example #2
0
class DataJar(QNetworkCookieJar):
    def __init__(self):
        super(DataJar, self).__init__()
        self.settings = QSettings(assets.fs.dataPath() + '/data.ini',
                                  QSettings.IniFormat)
        self.load()

    def load(self):
        strCookies = self.settings.value('cookies')
        if strCookies:
            self.setAllCookies(QNetworkCookie.parseCookies(strCookies))

    def save(self):
        cookies = self.allCookies()
        strCookies = ''
        for cookie in cookies:
            strCookies += cookie.toRawForm() + '\n'
        self.settings.setValue('cookies', strCookies)

    def set(self, name, value):
        self.settings.setValue('Data/' + name, value)

    def get(self, name):
        return self.settings.value('Data/' + name)

    def remove(self, name=None):
        if name is None:
            self.settings.remove('Data')
        else:
            self.settings.remove('Data/' + name)
Example #3
0
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setupUi(self)

        settings = QSettings()
        if settings.value(
                "Geometry"):  # Sind Vorgaben in der Registry vorhanden?
            self.restoreGeometry(
                settings.value("Geometry")
            )  # Dann Größe und Position des Fensters wiederherstellen

#         self.watchedDir = os.getcwd()

        self.renameButton.clicked.connect(self.renameSelectedFile)

        self.dateEdit.setText(date.today().isoformat())
        self.dateEdit.textChanged.connect(self.updatePreview)

        self.descriptionSuggestions.hide()

        self.descriptionEdit.textEdited.connect(self.updatePreview)
        self.descriptionEdit.textEdited.connect(self.runCompletion)

        self.sectionBox.currentIndexChanged.connect(self.updatePreview)

        self.lastModifiedComponent = "Y"
Example #4
0
class DesktopFile(object):
    def __init__(self, fileName=None):
        self._settings = None  # QSharedPointer<QSettings>

        if fileName is not None:
            self._settings = QSettings(fileName, QSettings.IniFormat)
            self._settings.setIniCodec('UTF-8')
            self._settings.beginGroup('Desktop Entry')

    def fileName(self):
        if self._settings:
            return self._settings.fileName()
        else:
            return ''

    def name(self):
        self.value('Name', True)

    def comment(self):
        return self.value('Comment', True)

    def type(self):
        return self.value('Type')

    def icon(self):
        return self.value('Icon')

    def value(self, key, localized=False):
        if not self._settings:
            return None
        if localized:
            locale = QLocale.system()
            localeKey = '%s[%s]' % (key, locale.name())
            if self._settings.contains(localeKey):
                return self._settings.value(localeKey)
            localeKey = '%s[%s]' % (key, locale.bcp47Name())
            if self._settings.contains(localeKey):
                return self._settings.value(localeKey)
            idx = locale.name().index('_')
            if idx > 0:
                localeKey = '%s[%s]' % (key, locale.name()[:idx])
                if self._settings.contains(localeKey):
                    return self._settings.value(localeKey)
        return self._settings.value(key)

    def tryExec(self):
        if not self._settings:
            return False

        exec_ = self._settings.value('TryExec')
        if not exec_:
            return True
        if QStandardPaths.findExecutable(exec_):
            return True
        return False
Example #5
0
    def __init__(self, icon, parent=None):
        QtWidgets.QSystemTrayIcon.__init__(self, icon, parent)

        settings = QSettings()

        menu = QtWidgets.QMenu(parent)
        exitAction = menu.addAction("Exit")
        selDirAction = menu.addAction("Select watched dir")
        renameAllAction = menu.addAction("Rename all Files")
        self.setContextMenu(menu)

        self.activated.connect(self.callRenameDialog)
        exitAction.triggered.connect(self.stopbuttonpressed)
        selDirAction.triggered.connect(self.showDirSelector)
        renameAllAction.triggered.connect(self.renameAllFiles)

        self.reactiondialog = RenameDialog()
        defaultWatchedDir = os.path.normcase(os.getcwd(
        ))  # Beim ersten Start: Überwachtes Verzeichnis = Arbeitsverzeichnis
        self.watchedDir = settings.value(
            "WatchedDirectory", defaultWatchedDir
        )  # Zuletzt verwendetes Verzeichnis wiederverwenden
        self.reactiondialog.watchedDir = self.watchedDir
        print("Watched directories: ", self.watchedDir)

        self.observer = Observer()
        self.handler = WatchdogHandler()
        self.observer.schedule(self.handler, self.watchedDir, False)
        self.observer.start()

        self.reIndexDirectory()

        self.handler.newfile.connect(self.filesChanged)
Example #6
0
 def populate(self):
     """Fill the dialog."""
     
     settings = QSettings(self)
     ppscannos = settings.value('ppscannos', type=str)
     if not ppscannos:
         #ppscannos = os.environ['HOME']
         ppscannos = os.path.expanduser('~')
         ppscannos = ppscannos + '/ppscannos1/ppscannos1.py'
     self.lineEditPPScannos.setText(ppscannos)
     self.ppscannosChanged()
     
     defaultScanno = settings.value('defaultScannoFile', type=str)
     if defaultScanno:
         idx = self.comboScannoFiles.findText(defaultScanno)
         self.comboScannoFiles.setCurrentIndex(idx)
Example #7
0
 def __init__(self, open_file_slot, settings_key, menu):
     self.open_file_slot = open_file_slot
     self.settings_key = settings_key
     self.menu = menu
     settings = QSettings()
     file_list = settings.value(settings_key)
     if file_list is not None:
         for file_name in file_list:
             self.append(RecentFile(file_name, self.open_file_slot))
     self.update()
Example #8
0
class Config:
    def __init__(self, organization, product):
        self.config = QSettings(organization, product)

    def setValue(self, option, value):
        self.config.setValue(option, QVariant(value))
        self.config.sync()

    def getBoolValue(self, option):
        default = self._initValue(option, False)
        return self.config.value(option, QVariant(default)) == "true"

    def getNumValue(self, option):
        default = self._initValue(option, 0)
        return int(self.config.value(option, QVariant(default)))#[0]

    def _initValue(self, option, value):
        if defaults.has_key(option):
            return defaults[option]
        return value
Example #9
0
 def get_user_settings(self, group_name, category):  
     """
     Retrieves user settings for the given group and category.
     group_name -- The group for which to retrieve settings values.
     category -- The category for which to retrieve settings values.
     """
     settings = QSettings(self.user_settings_file, QSettings.IniFormat)
     settings.beginGroup(group_name)        
     savedValue = settings.value(str(category))
     settings.endGroup()
     
     return savedValue
Example #10
0
 def settingsValue(key, default, t=None):
     if t is None:
         t = type(default)
     syslog.syslog(
         syslog.LOG_DEBUG,
         "DEBUG  settingsValue %s, default: %s, type: %s" %
         (key, str(default), t))
     s = QSettings()
     var = s.value(key, default, t)
     if not s.contains(key): s.setValue(key, var)
     syslog.syslog(
         syslog.LOG_DEBUG, "DEBUG  settingsValue %s, value: %s, type: %s" %
         (key, var, str(t)))
     return var
Example #11
0
 def initializeSettings(self):
     """Load persistent config settings."""
     
     settings = QSettings()
     s = settings.value('ppscannos', type=str)
     if not s:
         # try the default
         s = os.path.expanduser('~') + '/ppscannos1/ppscannos1.py'
         #s = os.environ['HOME'] + '/ppscannos1/ppscannos1.py'
     self.setPPScannos(s)
     
     s = settings.value('defaultScannoFile', type=str)
     if (not s) and self.ppscannos:
         # try the default
         lst = getRCFilesForDir(os.path.dirname(self.ppscannos))
         if len(lst):
             # prefer 'regex.rc'; otherwise use the first one
             s = lst[0]
             for f in lst:
                 if f == 'regex.rc':
                     s = f
                     break
     self.setDefaultScannoFile(s)
Example #12
0
 def __init__(self,
              open_file_slot,
              settings_key,
              menu,
              app_name,
              org_name='Brunsgen International'):
     super().__init__()
     self.org_name = org_name
     self.app_name = app_name
     self.open_file_slot = open_file_slot
     self.settings_key = settings_key
     self.menu = menu
     settings = QSettings(self.org_name, self.app_name)
     file_list = settings.value(settings_key)
     if file_list is not None:
         for file_name in file_list:
             if len(file_name) < 1:
                 continue
             self.append(RecentFile(file_name, self.open_file_slot))
     self.update()
Example #13
0
    def _readDir(self, dir_, parent):
        '''
        @param: dir_ QDir
        @param: parent BookmarkItem
        '''
        for file_ in dir_.entryInfoList(QDir.Dirs | QDir.Files
                                        | QDir.NoDotAndDotDot):
            # file_ QFileInfo
            if file_.isDir():
                folder = BookmarkItem(BookmarkItem.Folder, parent)
                folder.setTitle(file_.baseName())

                folderDir = QDir(dir_)
                folderDir.cd(file_.baseName())
                self._readDir(folderDir, folder)
            elif file_.isFile():
                urlFile = QSettings(file_.absoluteFilePath(),
                                    QSettings.IniFormat)
                url = urlFile.value('InternetShortcut/URL', type=QUrl)

                item = BookmarkItem(BookmarkItem.Url, parent)
                item.setTitle(file_.baseName())
                item.setUrl(url)
Example #14
0
 def load_setting(self, name):
     settings = QSettings(self._settings_file, QSettings.NativeFormat)
     value = settings.value(name, "")
     self._logger.info("Load setting %s -> %s", name, str(value))
     return value
Example #15
0
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QGridLayout, QFormLayout, QLabel, QLineEdit, QHBoxLayout, QVBoxLayout
from PyQt5.QtGui import *
from PyQt5.Qt import *
from PyQt5.Qt import QSettings
from PyQt5.QtCore import QObject,pyqtSignal
from PyQt5.QtCore import QThread
import game as gm
import client
import json

# non blocking subcriber
# https://stackoverflow.com/questions/26012132/zero-mq-socket-recv-call-is-blocking


settings = QSettings("artifice.ini", QSettings.IniFormat)
if not settings.value("ip_client"):
    settings.setValue("ip_client", "127.0.0.1")

class Artifice(QMainWindow):

    def __init__(self):
        QMainWindow.__init__(self)
        self.content = Fenetre()
        self.setCentralWidget(self.content)
        # self.setStyleSheet("QPushButton {border: none; text-decoration: none;} "
        #                    "QPushButton:hover {border: none; text-decoration: underline; image: url(images/b1.png);}")
        # self.setStyleSheet("QPushButton {border: 1px solid red;}")
        # self.setStyleSheet("QCarte:pressed {border: 1px solid red;}")
        # self.setStyleSheet("QPushButton:checked {border-style: outset; border-width: 10px;}")
        # self.setStyleSheet("QCarte:clicked {border-style: outset; border-width: 10px;}")
        # self.setFixedSize(self.screen().size())
Example #16
0
class EKWindow(QDialog):
    """
        Class which is responisble for running this entire application
    """

    def __init__(self):
        """
            Constructor for this class
        """
        super(EKWindow, self).__init__()
        self.engine = Engine("tables/Tamil-bamini.txt.in")

        # Settings file initialization
        self.settingsFilePath = os.getenv("APPDATA") + "\\" + qApp.applicationName() + "\eksettings.ini"
        self.init_settings()    # Function to check whether the settings file is or not.
        self.iniSettings = QSettings(self.settingsFilePath, QSettings.IniFormat)

        # Variable Initialization
        self.registrySettings = QSettings("HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run", QSettings.NativeFormat)
        self.shortcutModifierKey = self.iniSettings.value("shortcut_modifier")
        self.shortcutKey = self.iniSettings.value("shortcut")
        self.selectedKeyboard = self.iniSettings.value("selected_keyboard")
        self.keyboardStatus = False
        self.fileName = ""

        # Ui variable Initialization
        self.iconGroupBox = QGroupBox("Keyboards")
        self.iconLabel = QLabel("Keyboard:")
        self.iconComboBox = QComboBox(self)
        self.shortcutGroupBox = QGroupBox("Shortcut Setting")
        self.shortcutComboBox1 = QComboBox(self)
        self.shortcutComboBox2 = QComboBox(self)
        self.otherSettingsGroupBox = QGroupBox("Other Settings")
        self.checkboxStartWithWindows = QCheckBox()
        self.minimizeAction = QAction("Minimize", self)
        self.maximizeAction = QAction("Maximize", self)
        self.settingsAction = QAction("Settings", self)
        self.aboutAction = QAction("About", self)
        self.quitAction = QAction("Quit", self)
        self.trayIconMenu = QMenu(self)
        self.trayIcon = QSystemTrayIcon(self)
        self.mainLayout = QVBoxLayout()
        self.mainLayout.addWidget(self.iconGroupBox)
        self.mainLayout.addWidget(self.shortcutGroupBox)
        self.mainLayout.addWidget(self.otherSettingsGroupBox)
        self.setLayout(self.mainLayout)

        # UI constructor and connectors
        self.create_settings_group_boxes()
        self.create_actions()
        self.create_tray_icon()

        # Signal connectors
        self.iconComboBox.currentIndexChanged.connect(self.change_keyboard)
        self.shortcutComboBox1.currentIndexChanged.connect(self.set_shortcut_modifier)
        self.shortcutComboBox2.currentIndexChanged.connect(self.set_shortcut_key)
        self.trayIcon.activated.connect(self.icon_activated)
        self.checkboxStartWithWindows.stateChanged.connect(self.checkbox_start_with_windows_ticked)

        if self.keyboardStatus:
            self.iconComboBox.setCurrentIndex(self.selectedKeyBoard)
        else:
            self.change_keyboard(0)
            self.iconComboBox.setCurrentIndex(0)

        self.trayIcon.show()
        self.set_shortcut_key()
        self.setWindowTitle(qApp.applicationName() + " " + qApp.applicationVersion())

    def init_settings(self):
        """
            Function to check whether the settings file is there or not. If there is no file, then it will create with
            default settings.
        """
        if not os.path.exists(self.settingsFilePath):
            settings_dir = os.getenv("APPDATA") + "\\" + qApp.applicationName()
            if not os.path.exists(settings_dir):
                os.makedirs(settings_dir)
            setting_path = ""
            if getattr(sys, 'frozen', False):
                setting_path = os.path.dirname(sys.executable)
            elif __file__:
                setting_path = os.path.dirname(__file__)
            shutil.copyfile(os.path.join(setting_path, "resources\eksettings.ini"), self.settingsFilePath)
        return

    def create_settings_group_boxes(self):
        """
            UI generator function.
        """
        self.iconComboBox.addItem("No Keyboard")
        self.iconComboBox.addItem("Tamil99")
        self.iconComboBox.addItem("Phonetic")
        self.iconComboBox.addItem("Typewriter")
        self.iconComboBox.addItem("Bamini")
        self.iconComboBox.addItem("Inscript")
        icon_layout = QHBoxLayout(self)
        icon_layout.addWidget(self.iconLabel)
        icon_layout.addWidget(self.iconComboBox)
        icon_layout.addStretch()
        self.iconGroupBox.setLayout(icon_layout)

        shortcut_label_1 = QLabel("Modifier Key:")
        shortcut_label_2 = QLabel("Shortcut Key:")

        self.shortcutComboBox1.addItem("NONE")
        self.shortcutComboBox1.addItem("CTRL")
        self.shortcutComboBox1.addItem("ALT")

        modifier_index = self.shortcutComboBox1.findText(self.shortcutModifierKey)
        self.shortcutComboBox1.setCurrentIndex(modifier_index)

        self.shortcutComboBox2.setMinimumContentsLength(3)

        if modifier_index == 0:
            self.shortcutComboBox2.addItem("F1")
            self.shortcutComboBox2.addItem("ESC")
            self.shortcutComboBox2.addItem("F2")
            self.shortcutComboBox2.addItem("F3")
            self.shortcutComboBox2.addItem("F4")
            self.shortcutComboBox2.addItem("F5")
            self.shortcutComboBox2.addItem("F6")
            self.shortcutComboBox2.addItem("F7")
            self.shortcutComboBox2.addItem("F8")
            self.shortcutComboBox2.addItem("F9")
            self.shortcutComboBox2.addItem("F10")
        else:
            self.shortcutComboBox2.addItem("1")
            self.shortcutComboBox2.addItem("2")
            self.shortcutComboBox2.addItem("3")
            self.shortcutComboBox2.addItem("4")
            self.shortcutComboBox2.addItem("5")
            self.shortcutComboBox2.addItem("6")
            self.shortcutComboBox2.addItem("7")
            self.shortcutComboBox2.addItem("8")
            self.shortcutComboBox2.addItem("9")
            self.shortcutComboBox2.addItem("0")

        key_index = self.shortcutComboBox2.findText(self.shortcutKey)
        self.shortcutComboBox2.setCurrentIndex(key_index)

        shortcut_layout = QHBoxLayout(self)
        shortcut_layout.addWidget(shortcut_label_1)
        shortcut_layout.addWidget(self.shortcutComboBox1)
        shortcut_layout.addWidget(shortcut_label_2)
        shortcut_layout.addWidget(self.shortcutComboBox2)
        shortcut_layout.addStretch()
        self.shortcutGroupBox.setLayout(shortcut_layout)

        checkbox_start_with_windows_label = QLabel("Start eKalappai whenever windows starts")

        # if registry entry for auto start with windows for the current user exists, then check the checkbox
        if self.registrySettings.contains(qApp.applicationName()):
            self.checkboxStartWithWindows.setChecked(True)
        else:
            self.checkboxStartWithWindows.setChecked(False)

        other_settings_layout = QHBoxLayout(self)
        other_settings_layout.addWidget(checkbox_start_with_windows_label)
        other_settings_layout.addWidget(self.checkboxStartWithWindows)
        other_settings_layout.addStretch()
        self.otherSettingsGroupBox.setLayout(other_settings_layout)

    def set_shortcut_key(self):
        """
            Function to change the shortcut key when its changed.
        """
        self.shortcutKey = self.shortcutComboBox2.currentText()
        self.iniSettings.setValue("shortcut", self.shortcutKey)
        self.register_shortcut_listener()
        if self.shortcutKey == "ESC":
            self.shortcutKeyHex = 0x1B
        elif self.shortcutKey == "F1":
            self.shortcutKeyHex = 0x70
        elif self.shortcutKey == "F2":
            self.shortcutKeyHex = 0x71
        elif self.shortcutKey == "F3":
            self.shortcutKeyHex = 0x72
        elif self.shortcutKey == "F4":
            self.shortcutKeyHex = 0x73
        elif self.shortcutKey == "F5":
            self.shortcutKeyHex = 0x74
        elif self.shortcutKey == "F6":
            self.shortcutKeyHex = 0x75
        elif self.shortcutKey == "F7":
            self.shortcutKeyHex = 0x76
        elif self.shortcutKey == "F8":
            self.shortcutKeyHex = 0x77
        elif self.shortcutKey == "F9":
            self.shortcutKeyHex = 0x78
        elif self.shortcutKey == "F10":
            self.shortcutKeyHex = 0x79
        elif self.shortcutKey == "1":
            self.shortcutKeyHex = 0x31
        elif self.shortcutKey == "2":
            self.shortcutKeyHex = 0x32
        elif self.shortcutKey == "3":
            self.shortcutKeyHex = 0x33
        elif self.shortcutKey == "4":
            self.shortcutKeyHex = 0x34
        elif self.shortcutKey == "5":
            self.shortcutKeyHex = 0x35
        elif self.shortcutKey == "6":
            self.shortcutKeyHex = 0x36
        elif self.shortcutKey == "7":
            self.shortcutKeyHex = 0x37
        elif self.shortcutKey == "8":
            self.shortcutKeyHex = 0x38
        elif self.shortcutKey == "9":
            self.shortcutKeyHex = 0x39
        elif self.shortcutKey == "0":
            self.shortcutKeyHex = 0x30

    def create_actions(self):
        """
            Slot connectors for all right clicking and other actions.
        """
        self.minimizeAction.triggered.connect(self.hide)
        self.maximizeAction.triggered.connect(self.showMaximized)
        self.settingsAction.triggered.connect(self.showNormal)
        self.aboutAction.triggered.connect(self.show_about)
        self.quitAction.triggered.connect(self.quit)

    def quit(self):
        self.engine.un_hook()
        exit(0)

    def create_tray_icon(self):
        """
            Tray icon creator and corresponding connectors
        """
        self.trayIconMenu.addAction(self.settingsAction)
        self.trayIconMenu.addSeparator()
        self.trayIconMenu.addAction(self.aboutAction)
        self.trayIconMenu.addSeparator()
        self.trayIconMenu.addAction(self.quitAction)
        self.trayIcon.setContextMenu(self.trayIconMenu)

    def setVisible(self, visible):
        self.settingsAction.setEnabled(self.isMaximized() or not visible)
        super(EKWindow, self).setVisible(visible)

    def closeEvent(self, event):
        if self.trayIcon.isVisible():
            self.hide()
            event.ignore()

    def load_keyboard(self):
        """
            Mapping file loading function
        """
        if self.selectedKeyboard == 1:
            self.fileName = "tables/Tamil-tamil99.txt.in"
        elif self.selectedKeyboard == 2:
            self.fileName = "tables/Tamil-phonetic.txt.in"
        elif self.selectedKeyboard == 3:
            self.fileName = "tables/Tamil-typewriter.txt.in"
        elif self.selectedKeyboard == 4:
            self.fileName = "tables/Tamil-bamini.txt.in"
        elif self.selectedKeyboard == 5:
            self.fileName = "tables/Tamil-inscript.txt.in"
        else:
            pass

    def getPath(self, index):
            if index == 1:
                self.path = "tables/Tamil-tamil99.txt.in"
            elif index == 2:
                self.path = "tables/Tamil-phonetic.txt.in"
            elif index == 3:
                self.path = "tables/Tamil-typewriter.txt.in"
            elif index == 4:
                self.path = "tables/Tamil-bamini.txt.in"
            elif index == 5:
                self.path = "tables/Tamil-inscript.txt.in"
            else:
                pass

    def change_keyboard(self, index):
        """
            Function to change the keyboard based on the index which was sent as a param
        """
        if int(index) != 0:
            self.iniSettings.setValue("selected_keyboard", index)
            self.selectedKeyboard = index
        self.iconComboBox.setCurrentIndex(int(index))
        icon = self.iconComboBox.itemIcon(int(index))
        self.trayIcon.setIcon(icon)
        self.setWindowIcon(icon)
        self.trayIcon.setToolTip(self.iconComboBox.itemText(int(index)))
        self.show_tray_message(index)
        self.load_keyboard()
        if int(index) != 0:
            self.getPath(int(index))
            self.engine.file_name = self.path
            self.engine.initialize()
            self.engine.conv_state = True
        else:
            try:
                self.engine.conv_state = False
            except:
                pass

    def icon_activated(self, reason):
        """
            Function to toggle the state when the icon is clicked or shortcut key is pressed
        """
        if reason == QSystemTrayIcon.DoubleClick:
            pass
        elif reason == QSystemTrayIcon.Trigger:
            if self.keyboardStatus:
                self.keyboardStatus = False
            else:
                self.keyboardStatus = True
            if self.keyboardStatus:
                self.change_keyboard(self.selectedKeyboard)
            else:
                self.change_keyboard(0)
        elif reason == QSystemTrayIcon.MiddleClick:
            pass
        else:
            pass

    def show_tray_message(self, index):
        """
            Tray message generator when there is change in keyboard state
        """
        icon = QSystemTrayIcon.MessageIcon(0)
        message = self.iconComboBox.itemText(int(index)) + " set"
        self.trayIcon.showMessage(qApp.applicationName() + " " + qApp.applicationVersion(), message, icon, 100)

    def checkbox_start_with_windows_ticked(self):
        """
            Function to add or disable registry entry to auto start ekalappai with windows for the current users
        """
        if self.checkboxStartWithWindows.isChecked():
            self.registrySettings.setValue(qApp.applicationName(), qApp.applicationFilePath())
        else:
            self.registrySettings.remove(qApp.applicationName())

    def show_about(self):
        pass

    def set_shortcut_modifier(self, index):
        """
            Function to set the shortcut modifier when its changed.
        """
        self.iniSettings.setValue("shortcut_modifier", self.shortcutComboBox1.currentText())
        self.shortcutModifierKey = self.iniSettings.value("shortcut_modifier")
        # if none is selected, the allowed single key shortcuts should change
        if index == 0:
            self.shortcutComboBox2.clear()
            self.shortcutComboBox2.addItem("ESC")
            self.shortcutComboBox2.addItem("F1")
            self.shortcutComboBox2.addItem("F2")
            self.shortcutComboBox2.addItem("F3")
            self.shortcutComboBox2.addItem("F4")
            self.shortcutComboBox2.addItem("F5")
            self.shortcutComboBox2.addItem("F6")
            self.shortcutComboBox2.addItem("F7")
            self.shortcutComboBox2.addItem("F8")
            self.shortcutComboBox2.addItem("F9")
            self.shortcutComboBox2.addItem("F10")
        else:
            self.shortcutComboBox2.clear()
            self.shortcutComboBox2.addItem("1")
            self.shortcutComboBox2.addItem("2")
            self.shortcutComboBox2.addItem("3")
            self.shortcutComboBox2.addItem("4")
            self.shortcutComboBox2.addItem("5")
            self.shortcutComboBox2.addItem("6")
            self.shortcutComboBox2.addItem("7")
            self.shortcutComboBox2.addItem("8")
            self.shortcutComboBox2.addItem("9")
            self.shortcutComboBox2.addItem("0")
        self.register_shortcut_listener()

    def register_shortcut_listener(self):
        self.engine.event_queue.remove_all()
        if self.iniSettings.value("shortcut_modifier") == "NONE":
            self.engine.event_queue.register_event([[self.shortcutKey], self.icon_activated, QSystemTrayIcon.Trigger])
        elif self.iniSettings.value("shortcut_modifier") == "CTRL":
            self.engine.event_queue.register_event([['Lcontrol', self.shortcutKey], self.icon_activated, QSystemTrayIcon.Trigger])
            self.engine.event_queue.register_event([['Rcontrol', self.shortcutKey], self.icon_activated, QSystemTrayIcon.Trigger])
        elif self.iniSettings.value("shortcut_modifier") == "ALT":
            self.engine.event_queue.register_event([['LMenu', self.shortcutKey], self.icon_activated, QSystemTrayIcon.Trigger])
            self.engine.event_queue.register_event([['RMenu', self.shortcutKey], self.icon_activated, QSystemTrayIcon.Trigger])
        return True
Example #17
0
class MainWindow(QMainWindow):
    def __init__(self):
        self.settings = QSettings("yayachiken", "PyMorsetrainer")
        if not self.settings.allKeys():
            print("Initializing application settings...")
            self.settings.setValue("currentLesson", "1")
            self.settings.setValue("wpm", "20")
            self.settings.setValue("effectiveWpm", "15")
            self.settings.setValue("frequency", "800")
            self.settings.setValue("duration", "1")
        
        self.requireNewExercise = False
        self.mp = None
        self.lessonButtons = []
        self.debug = False

        super().__init__()
        self.initUI()
        self.generateExercise()
        
    def initUI(self):
        self.centralWidget = QWidget()
        self.setCentralWidget(self.centralWidget)

        self.receivedTextEdit = QTextEdit()
        self.receivedTextEdit.setAcceptRichText(False)
        monospaceFont = QFont("Monospace")
        monospaceFont.setStyleHint(QFont.Monospace)
        self.receivedTextEdit.setFont(monospaceFont)
        
        playExerciseButton = QPushButton("Play exercise text")
        playExerciseButton.clicked.connect(self.playExercise)
        
        stopButton = QPushButton("Stop playing")
        stopButton.clicked.connect(self.stopPlaying)
        
        validateButton = QPushButton("Check input / Generate next exercise")
        validateButton.clicked.connect(self.checkInput)
        
        self.wpmLineEdit = QLineEdit(self.settings.value("wpm"))
        self.wpmLineEdit.textChanged.connect(functools.partial(self.saveChangedText, self.wpmLineEdit, "wpm"))
        wpmLabel = QLabel("WPM")
        
        self.ewpmLineEdit = QLineEdit(self.settings.value("effectiveWpm"))
        self.ewpmLineEdit.textChanged.connect(functools.partial(self.saveChangedText, self.ewpmLineEdit, "effectiveWpm"))
        ewpmLabel = QLabel("effective WPM")
        
        self.freqLineEdit = QLineEdit(self.settings.value("frequency"))
        self.freqLineEdit.textChanged.connect(functools.partial(self.saveChangedText, self.freqLineEdit, "frequency"))
        freqLabel = QLabel("Frequency (Hz)")
        
        self.durationLineEdit = QLineEdit(self.settings.value("duration"))
        self.durationLineEdit.textChanged.connect(functools.partial(self.saveChangedText, self.durationLineEdit, "duration"))
        durationLabel = QLabel("Duration (min)")
        
        self.lessonGrid = QGridLayout()
        
        lessonCombo = QComboBox()
        lessonCombo.setStyleSheet("combobox-popup: 0;")
        lessonCombo.addItem("1 - K M")
        for lesson in range(2, len(KOCH_LETTERS)):
            lessonCombo.addItem(str(lesson) + " - " + KOCH_LETTERS[lesson])
        lessonCombo.setCurrentIndex(int(self.settings.value("currentLesson"))-1)
        lessonCombo.currentIndexChanged.connect(self.newLessonSelected)
        
        lessonIdLabel = QLabel("Lesson:")
        
        lessonBox = QHBoxLayout()
        lessonBox.addWidget(lessonIdLabel)
        lessonBox.addWidget(lessonCombo)
        lessonBox.addStretch(-1)

        self.createLessonLetterButtons(self.lessonGrid)
        
        mainLayout = QVBoxLayout()

        inputAndParameters = QHBoxLayout()
        parameterField = QVBoxLayout()
        inputAndParameters.addWidget(self.receivedTextEdit, stretch=1)
        self.receivedTextEdit.setSizePolicy(QSizePolicy(QSizePolicy.Expanding, QSizePolicy.MinimumExpanding))
        inputAndParameters.addLayout(parameterField, stretch=0)

        parameterField.addWidget(playExerciseButton)
        parameterField.addWidget(stopButton)
        parameterField.addWidget(validateButton)

        parameterGrid = QGridLayout()
        parameterGrid.addWidget(self.wpmLineEdit, 0, 0)
        parameterGrid.addWidget(wpmLabel, 0, 1)
        parameterGrid.addWidget(self.ewpmLineEdit, 1, 0)
        parameterGrid.addWidget(ewpmLabel, 1, 1)
        parameterGrid.addWidget(self.freqLineEdit, 2, 0)
        parameterGrid.addWidget(freqLabel, 2, 1)
        parameterGrid.addWidget(self.durationLineEdit, 3, 0)
        parameterGrid.addWidget(durationLabel, 3, 1)
        parameterField.addLayout(parameterGrid)
        parameterField.insertSpacing(-1, 15)
        parameterField.addLayout(lessonBox)
        parameterField.insertStretch(-1)

        mainLayout.addLayout(inputAndParameters)
        mainLayout.addLayout(self.lessonGrid)
        
        self.centralWidget.setLayout(mainLayout)
        
        self.setWindowTitle('PyMorsetrainer')
        self.show()
        
    def closeEvent(self, event):
        self.stopPlaying()

    def createLessonLetterButtons(self, parentGrid):
        newButtonCount = int(self.settings.value("currentLesson")) + 1
        oldButtonCount = len(self.lessonButtons)

        if oldButtonCount > newButtonCount:
            for button in self.lessonButtons[newButtonCount:]:
                parentGrid.removeWidget(button)
                button.deleteLater()
            self.lessonButtons = self.lessonButtons[:newButtonCount]
        else:
            for idx, letter in enumerate(KOCH_LETTERS[oldButtonCount:newButtonCount]):
                idx = idx + oldButtonCount
                button = QToolButton()
                button.setText(letter)
                button.clicked.connect(functools.partial(self.playMorse, letter))
                buttonPolicy = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed, QSizePolicy.PushButton)
                buttonPolicy.setHorizontalStretch(0)
                button.setSizePolicy(buttonPolicy)
                button.setMinimumWidth(5)
                parentGrid.addWidget(button, 1 + int(idx / 12), int(idx % 12))
                self.lessonButtons.append(button)
        
    def playMorse(self, text):
        if self.mp is not None:
            self.mp.shutdown()
        wpm = int(self.settings.value("wpm"))
        effectiveWpm = int(self.settings.value("effectiveWpm"))
        frequency = int(self.settings.value("frequency"))
        self.mp = MorsePlayer(text, wpm, effectiveWpm, frequency)
        self.mp.start()

    def playExercise(self):
        if self.requireNewExercise == True:
            self.generateExercise()
        self.playMorse(self.morse_solution)
    
    def stopPlaying(self):
        if self.mp is not None:
            self.mp.shutdown()
    
    def newLessonSelected(self, comboId):
        newLesson = comboId + 1
        self.settings.setValue("currentLesson", newLesson)
        self.createLessonLetterButtons(self.lessonGrid)
        self.requireNewExercise = True
        
    def generateExercise(self):
        lesson = int(self.settings.value("currentLesson"))
        letters = KOCH_LETTERS[:lesson+1]
        wpm = int(self.wpmLineEdit.text())
        effectiveWpm = int(self.ewpmLineEdit.text())
        frequency = int(self.freqLineEdit.text())
        duration = int(self.durationLineEdit.text())
        
        mc = MorseCode("")
        
        while mc.tally_length_in_seconds(wpm, effectiveWpm) < duration * 60:
            new_word = ""
            for _ in range(0, 5):
                new_word += (random.choice(letters))
            mc.set_morse_text(mc.get_morse_text() + " " + new_word)
        self.requireNewExercise = False
        self.morse_solution = mc.get_morse_text()
        if self.debug:
            print(self.morse_solution)
        
    def checkInput(self):
        self.evalWindow = EvaluationWindow(self.receivedTextEdit.toPlainText().upper(), self.morse_solution)
        self.evalWindow.setModal(True)
        self.evalWindow.show()
        self.requireNewExercise = True
        self.receivedTextEdit.clear()

    def saveChangedText(self, inputField, settingName):
        self.settings.setValue(settingName, inputField.text())

    def enableDebugMode():
        self.debug = True
Example #18
0
class DataSet(QObject):

    training_limit = 100
    testing_limit = 200
    all_images = []
    training_images = []
    testing_images = []
    all_testing_images = []
    training_labels = []
    training_cls = []

    total_iterations = 0
    index_in_epoch = 0
    epochs_completed = 0
    one_hot_size = 0
    current_testing_max = 0

    img_shape = ()
    base_dir = os.path.dirname(os.path.realpath(__file__)) + "/../"

    test_set_changed = pyqtSignal(int)

    def __init__(self, img_size):
        super().__init__()
        self.settings = QSettings("Theo Styles",
                                  "Convolutional Neural Network")
        self.img_shape = (img_size, img_size)
        self.training_labels = np.array([])
        self.training_images = np.array([])
        self.labels = []

    def get_label_index(self, name):
        self.labels.append(name)
        self.labels = sorted(set(self.labels),
                             key=lambda x: self.labels.index(x))
        for i, label in enumerate(self.labels):
            if str(label) == str(name):
                return i

    def add_sets_to_training_data(self, numberOfSets, itemNames, images):
        if len(images) == 0 or len(itemNames) == 0: return

        self.training_images = []
        self.training_labels = []

        self.one_hot_size = numberOfSets

        for i, image in enumerate(images):
            one_hot = [0 for x in range(self.one_hot_size)]
            index = self.get_label_index(itemNames[i])
            one_hot[index] = 1
            self.training_images.append(image)
            self.training_labels.append(one_hot)

        self.training_labels = np.array(self.training_labels)
        self.training_images = np.array(self.training_images)
        self.training_cls = np.argmax(self.training_labels, axis=1)
        self.index_in_epoch = 0
        self.total_iterations = 0
        self.epochs_completed = 0
        self.training_limit = len(self.training_images)

    def set_testing_data(self, images):
        self.all_testing_images = images
        self.new_testing_data()

    def add_to_testing_data(self, image):
        self.all_testing_images.append(image)
        self.test_set_changed.emit(len(self.all_testing_images))

    def new_testing_data(self):
        self.testing_images = []
        self.current_testing_max = min(
            len(self.all_testing_images),
            self.settings.value("testing_amount", self.testing_limit))

        for x in self.all_testing_images[0:self.current_testing_max]:
            self.testing_images.append(x)

        self.all_testing_images = self.all_testing_images[self.
                                                          current_testing_max:]

        self.test_set_changed.emit(len(self.all_testing_images))

        self.testing_images = np.array(self.testing_images)
        np.random.shuffle(self.testing_images)

    def next_batch(self, batch_size):
        batch_size = min(batch_size, self.training_limit)
        start = self.index_in_epoch
        self.index_in_epoch += batch_size
        if self.index_in_epoch > self.training_limit:
            # Finished epoch
            self.epochs_completed += 1
            # Shuffle the data
            perm = np.arange(self.training_limit)
            np.random.shuffle(perm)
            self.training_images = self.training_images[perm]
            self.training_labels = self.training_labels[perm]
            # Start next epoch
            start = 0
            self.index_in_epoch = batch_size
            assert batch_size <= self.training_limit
        end = self.index_in_epoch
        return self.training_images[start:end], self.training_labels[start:end]
Example #19
0
class MainWindow(QMainWindow):
    def __init__(self):
        self.settings = QSettings("yayachiken", "PyMorsetrainer")
        if self.settings.value("currentLesson") is not None:
            self.lesson = int(self.settings.value("currentLesson"))
        else:
            self.lesson = 1
            self.settings.setValue("currentLesson", 1)
        
        self.requireNewExercise = False
        self.mp = None
        self.thread = None

        super().__init__()
        self.initUI()
        self.generateExercise()
        
    def initUI(self):
        self.centralWidget = QWidget()
        self.setCentralWidget(self.centralWidget)

        self.receivedTextEdit = QTextEdit()
        self.receivedTextEdit.setAcceptRichText(False)
        monospaceFont = QFont("Monospace")
        monospaceFont.setStyleHint(QFont.Monospace)
        self.receivedTextEdit.setFont(monospaceFont)
        
        playExerciseButton = QPushButton("Play exercise text")
        playExerciseButton.clicked.connect(self.playExercise)
        
        stopButton = QPushButton("Stop playing")
        stopButton.clicked.connect(self.stopPlaying)
        
        validateButton = QPushButton("Check input / Generate next exercise")
        validateButton.clicked.connect(self.checkInput)
        
        self.wpmLineEdit = QLineEdit("20")
        wpmLabel = QLabel("WPM")
        
        self.ewpmLineEdit = QLineEdit("15")
        ewpmLabel = QLabel("effective WPM")
        
        self.freqLineEdit = QLineEdit("800")
        freqLabel = QLabel("Frequency (Hz)")
        
        self.durationLineEdit = QLineEdit("1")
        durationLabel = QLabel("Duration (min)")
        
        lessonBox = QHBoxLayout()
        lessonBox.setAlignment(Qt.AlignLeft)
        
        lessonCombo = QComboBox()
        lessonCombo.setMaximumWidth(75)
        lessonCombo.addItem("1 - K M")
        for lesson in range(2, len(KOCH_LETTERS)):
            lessonCombo.addItem(str(lesson) + " - " + KOCH_LETTERS[lesson])
        lessonCombo.setCurrentIndex(self.lesson-1)
        lessonCombo.currentIndexChanged.connect(self.newLessonSelected)
        
        lessonIdLabel = QLabel("Lesson:")
        lessonIdLabel.setMaximumWidth(50)
        
        self.lessonLabel = QLabel(' '.join(KOCH_LETTERS[:self.lesson+1]))
        lessonBox.addWidget(lessonIdLabel)
        lessonBox.addWidget(lessonCombo)
        lessonBox.addWidget(self.lessonLabel)
        
        grid = QGridLayout()
        grid.setSpacing(10)
        grid.addWidget(self.receivedTextEdit, 1, 1, 7, 1)
        grid.addWidget(playExerciseButton, 1, 2, 1, 2)
        grid.addWidget(stopButton, 2, 2, 1, 2)
        grid.addWidget(validateButton, 3, 2, 1, 2)
        grid.addWidget(self.wpmLineEdit, 4, 2)
        grid.addWidget(wpmLabel, 4, 3)
        grid.addWidget(self.ewpmLineEdit, 5, 2)
        grid.addWidget(ewpmLabel, 5, 3)
        grid.addWidget(self.freqLineEdit, 6, 2)
        grid.addWidget(freqLabel, 6, 3)
        grid.addWidget(self.durationLineEdit, 7, 2)
        grid.addWidget(durationLabel, 7, 3)
        grid.addLayout(lessonBox, 8, 1, 1, 3)
        
        self.centralWidget.setLayout(grid)
        
        self.setWindowTitle('PyMorsetrainer')
        self.show()
        
    def closeEvent(self, event):
        self.stopPlaying()
        
        
    def playExercise(self):
        if self.requireNewExercise == True:
            self.generateExercise()
        wpm = int(self.wpmLineEdit.text())
        effectiveWpm = int(self.ewpmLineEdit.text())
        frequency = int(self.freqLineEdit.text())
        self.mp = MorsePlayer(self.morse_solution, wpm, effectiveWpm, frequency)
        self.mp.start()
    
    def stopPlaying(self):
        if self.mp is not None:
            self.mp.shutdown()
    
    def newLessonSelected(self, comboId):
        self.lesson = comboId+1
        self.settings.setValue("currentLesson", self.lesson)
        self.lessonLabel.setText(' '.join(KOCH_LETTERS[:self.lesson+1]))
        self.requireNewExercise = True
        
    def generateExercise(self):
        letters = KOCH_LETTERS[:self.lesson+1]
        wpm = int(self.wpmLineEdit.text())
        effectiveWpm = int(self.ewpmLineEdit.text())
        frequency = int(self.freqLineEdit.text())
        duration = int(self.durationLineEdit.text())
        
        mc = MorseCode("")
        
        while mc.tally_length_in_seconds(wpm, effectiveWpm) < duration * 60:
            new_word = ""
            for _ in range(0, 5):
                new_word += (random.choice(letters))
            mc.set_morse_text(mc.get_morse_text() + " " + new_word)
        self.requireNewExercise = False
        self.morse_solution = mc.get_morse_text()
        print(self.morse_solution)
        
    def checkInput(self):
        self.evalWindow = EvaluationWindow(self.receivedTextEdit.toPlainText().upper(), self.morse_solution)
        self.evalWindow.setModal(True)
        self.evalWindow.show()
        self.requireNewExercise = True
        self.receivedTextEdit.clear()
 def startingProfile(cls):
     '''
     @brief: Name of starting profile
     '''
     settings = QSettings(pathjoin(DataPaths.path(DataPaths.Profiles), 'profiles.ini'), QSettings.IniFormat)
     return settings.value('Profiles/startProfile', 'default')
Example #21
0
class MainWindow(QMainWindow):
    def __init__(self):
        self.settings = QSettings("yayachiken", "PyMorsetrainer")
        if not self.settings.allKeys():
            print("Initializing application settings...")
            self.settings.setValue("currentLesson", "1")
            self.settings.setValue("wpm", "20")
            self.settings.setValue("effectiveWpm", "15")
            self.settings.setValue("frequency", "800")
            self.settings.setValue("duration", "1")

        self.requireNewExercise = False
        self.mp = None
        self.lessonButtons = []
        self.debug = False

        super().__init__()
        self.initUI()
        self.generateExercise()

    def initUI(self):
        self.centralWidget = QWidget()
        self.setCentralWidget(self.centralWidget)

        self.receivedTextEdit = QTextEdit()
        self.receivedTextEdit.setAcceptRichText(False)
        monospaceFont = QFont("Monospace")
        monospaceFont.setStyleHint(QFont.Monospace)
        self.receivedTextEdit.setFont(monospaceFont)

        playExerciseButton = QPushButton("Play exercise text")
        playExerciseButton.clicked.connect(self.playExercise)

        stopButton = QPushButton("Stop playing")
        stopButton.clicked.connect(self.stopPlaying)

        validateButton = QPushButton("Check input / Generate next exercise")
        validateButton.clicked.connect(self.checkInput)

        self.wpmLineEdit = QLineEdit(self.settings.value("wpm"))
        self.wpmLineEdit.textChanged.connect(
            functools.partial(self.saveChangedText, self.wpmLineEdit, "wpm"))
        wpmLabel = QLabel("WPM")

        self.ewpmLineEdit = QLineEdit(self.settings.value("effectiveWpm"))
        self.ewpmLineEdit.textChanged.connect(
            functools.partial(self.saveChangedText, self.ewpmLineEdit,
                              "effectiveWpm"))
        ewpmLabel = QLabel("effective WPM")

        self.freqLineEdit = QLineEdit(self.settings.value("frequency"))
        self.freqLineEdit.textChanged.connect(
            functools.partial(self.saveChangedText, self.freqLineEdit,
                              "frequency"))
        freqLabel = QLabel("Frequency (Hz)")

        self.durationLineEdit = QLineEdit(self.settings.value("duration"))
        self.durationLineEdit.textChanged.connect(
            functools.partial(self.saveChangedText, self.durationLineEdit,
                              "duration"))
        durationLabel = QLabel("Duration (min)")

        self.lessonGrid = QGridLayout()

        lessonCombo = QComboBox()
        lessonCombo.setStyleSheet("combobox-popup: 0;")
        lessonCombo.addItem("1 - K M")
        for lesson in range(2, len(KOCH_LETTERS)):
            lessonCombo.addItem(str(lesson) + " - " + KOCH_LETTERS[lesson])
        lessonCombo.setCurrentIndex(
            int(self.settings.value("currentLesson")) - 1)
        lessonCombo.currentIndexChanged.connect(self.newLessonSelected)

        lessonIdLabel = QLabel("Lesson:")

        lessonBox = QHBoxLayout()
        lessonBox.addWidget(lessonIdLabel)
        lessonBox.addWidget(lessonCombo)
        lessonBox.addStretch(-1)

        self.createLessonLetterButtons(self.lessonGrid)

        mainLayout = QVBoxLayout()

        inputAndParameters = QHBoxLayout()
        parameterField = QVBoxLayout()
        inputAndParameters.addWidget(self.receivedTextEdit, stretch=1)
        self.receivedTextEdit.setSizePolicy(
            QSizePolicy(QSizePolicy.Expanding, QSizePolicy.MinimumExpanding))
        inputAndParameters.addLayout(parameterField, stretch=0)

        parameterField.addWidget(playExerciseButton)
        parameterField.addWidget(stopButton)
        parameterField.addWidget(validateButton)

        parameterGrid = QGridLayout()
        parameterGrid.addWidget(self.wpmLineEdit, 0, 0)
        parameterGrid.addWidget(wpmLabel, 0, 1)
        parameterGrid.addWidget(self.ewpmLineEdit, 1, 0)
        parameterGrid.addWidget(ewpmLabel, 1, 1)
        parameterGrid.addWidget(self.freqLineEdit, 2, 0)
        parameterGrid.addWidget(freqLabel, 2, 1)
        parameterGrid.addWidget(self.durationLineEdit, 3, 0)
        parameterGrid.addWidget(durationLabel, 3, 1)
        parameterField.addLayout(parameterGrid)
        parameterField.insertSpacing(-1, 15)
        parameterField.addLayout(lessonBox)
        parameterField.insertStretch(-1)

        mainLayout.addLayout(inputAndParameters)
        mainLayout.addLayout(self.lessonGrid)

        self.centralWidget.setLayout(mainLayout)

        self.setWindowTitle('PyMorsetrainer')
        self.show()

    def closeEvent(self, event):
        self.stopPlaying()

    def createLessonLetterButtons(self, parentGrid):
        newButtonCount = int(self.settings.value("currentLesson")) + 1
        oldButtonCount = len(self.lessonButtons)

        if oldButtonCount > newButtonCount:
            for button in self.lessonButtons[newButtonCount:]:
                parentGrid.removeWidget(button)
                button.deleteLater()
            self.lessonButtons = self.lessonButtons[:newButtonCount]
        else:
            for idx, letter in enumerate(
                    KOCH_LETTERS[oldButtonCount:newButtonCount]):
                idx = idx + oldButtonCount
                button = QToolButton()
                button.setText(letter)
                button.clicked.connect(
                    functools.partial(self.playMorse, letter))
                buttonPolicy = QSizePolicy(QSizePolicy.Minimum,
                                           QSizePolicy.Fixed,
                                           QSizePolicy.PushButton)
                buttonPolicy.setHorizontalStretch(0)
                button.setSizePolicy(buttonPolicy)
                button.setMinimumWidth(5)
                parentGrid.addWidget(button, 1 + int(idx / 12), int(idx % 12))
                self.lessonButtons.append(button)

    def playMorse(self, text):
        if self.mp is not None:
            self.mp.shutdown()
        wpm = int(self.settings.value("wpm"))
        effectiveWpm = int(self.settings.value("effectiveWpm"))
        frequency = int(self.settings.value("frequency"))
        self.mp = MorsePlayer(text, wpm, effectiveWpm, frequency)
        self.mp.start()

    def playExercise(self):
        if self.requireNewExercise == True:
            self.generateExercise()
        self.playMorse(self.morse_solution)

    def stopPlaying(self):
        if self.mp is not None:
            self.mp.shutdown()

    def newLessonSelected(self, comboId):
        newLesson = comboId + 1
        self.settings.setValue("currentLesson", newLesson)
        self.createLessonLetterButtons(self.lessonGrid)
        self.requireNewExercise = True

    def generateExercise(self):
        lesson = int(self.settings.value("currentLesson"))
        letters = KOCH_LETTERS[:lesson + 1]
        wpm = int(self.wpmLineEdit.text())
        effectiveWpm = int(self.ewpmLineEdit.text())
        frequency = int(self.freqLineEdit.text())
        duration = int(self.durationLineEdit.text())

        mc = MorseCode("")

        while mc.tally_length_in_seconds(wpm, effectiveWpm) < duration * 60:
            new_word = ""
            for _ in range(0, 5):
                new_word += (random.choice(letters))
            mc.set_morse_text(mc.get_morse_text() + " " + new_word)
        self.requireNewExercise = False
        self.morse_solution = mc.get_morse_text()
        if self.debug:
            print(self.morse_solution)

    def checkInput(self):
        self.evalWindow = EvaluationWindow(
            self.receivedTextEdit.toPlainText().upper(), self.morse_solution)
        self.evalWindow.setModal(True)
        self.evalWindow.show()
        self.requireNewExercise = True
        self.receivedTextEdit.clear()

    def saveChangedText(self, inputField, settingName):
        self.settings.setValue(settingName, inputField.text())

    def enableDebugMode():
        self.debug = True
Example #22
0
class LayerManager( QtCore.QObject ):

    # signals declaration
    update_available_layers = QtCore.pyqtSignal( list, list )
    update_instantiated_layers = QtCore.pyqtSignal( list )

    def __init__( self, scene,model, parent=None ):
        ''' initialisation of the laye manager '''
        super( LayerManager, self ).__init__( parent )
        self.scene = scene
        self.model = model
        self.settings = QSettings("config.ini",QSettings.IniFormat)
        self.projection = None
        self.scene_bounding_box = None
        self.instantiated_layers = []
        self.instantiable_layers = []
        self.available_layers = []
        self.initLayers()
        

    def initLayers( self ):
        ''' list all instantiable layers '''
        layers_list = self.settings.value("map/available_layers",[])

        for layer in layers_list:
            module_name, module_class = layer.split( '.' )
            print ('module_name',module_name,module_class)
            module = importlib.import_module( "python_modules.view.view_map."+module_name )
            print('module',module)
            self.instantiable_layers.append( getattr( module, module_class ) )

    def getProjection( self ):
        ''' return projection '''
        return self.projection

    def update( self, scene_bounding_box ):
        ''' update instantiated layers '''
        for layer in self.instantiated_layers:
            layer.update( scene_bounding_box )
        self.scene_bounding_box = scene_bounding_box
    def addLayer( self, layer_name ):
        ''' create layer '''
        # instantiation
        global instantiates
        instantiates += 1
        for layer in self.instantiable_layers:
            print ('add layer names :',layer.name( layer ))
            if layer.name( layer ) == layer_name:
                print (type(self.parent()))
                self.instantiated_layers.append( layer( self.scene, instantiates, self.model, self.parent().getSceneCoord(), self ) )
                self.update_instantiated_layers.emit( self.instantiated_layers )

        # update projection
        if self.projection == None:
            self.projection = self.instantiated_layers[0].getProjection()
            print ('recuperation de la projection du premier layer cree',self.projection)

        self.updateAvailableLayers()

    def removeLayer( self, layer_name ):
        ''' delete layer '''
        global instantiates
        instantiates -= 1

        # get z value
        for instantiated_layer in self.instantiated_layers:
            if instantiated_layer.__class__.name( instantiated_layer.__class__ ) == layer_name:
                z_value = instantiated_layer.getZValue()
                break

        # update others z value
        for instantiated_layer in self.instantiated_layers:
            if instantiated_layer.__class__.name( instantiated_layer.__class__ ) == layer_name:
                layer_to_remove = instantiated_layer
            elif instantiated_layer.getZValue() > z_value:
                instantiated_layer.decreaseZValue()

        # destruction
        self.instantiated_layers.remove( layer_to_remove )
        layer_to_remove.clearItems()
        self.update_instantiated_layers.emit( self.instantiated_layers )

        # update projection or opacity
        if self.instantiated_layers == []:
            self.projection = None
            self.updateAvailableLayers()

    def updateAvailableLayers( self ):
        ''' update available layers list '''

        self.available_layers = []
        # if projection is null, only layers with specific projection can be instantiate
        if self.projection == None:
            for layer in self.instantiable_layers:
                if layer.projection( layer ) != None:
                    self.available_layers.append( layer.name( layer ) )
        # if a projection is already activated, layers without projection are added and layers with other projection become unavailable
        else:
            for layer in self.instantiable_layers:
                if layer.projection( layer ) == self.projection or layer.projection( layer ) == None:
                        self.available_layers.append( layer.name( layer ) )
        self.update_available_layers.emit( self.available_layers, self.instantiable_layers )

    def updateRotation( self, value ):
        for instantiated_layer in self.instantiated_layers:
            instantiated_layer.updateRotation( value )

    def releaseEvent( self, pos, scene_pos ):
        for instantiated_layer in self.instantiated_layers:
            if instantiated_layer.__class__.name( instantiated_layer.__class__ ) == 'Draw':
                instantiated_layer.releaseEvent( pos, scene_pos )
Example #23
0
class MyNetworkCookieJar(QNetworkCookieJar):
	def __init__(self, parent=None):
		QNetworkCookieJar.__init__(self, parent)
		self.storage = QSettings(QSettings.IniFormat, QSettings.UserScope, "fbreader", "plugin")
		self.loadCookies()

	def setCookiesFromUrl(self, cookieList, url):
		res = QNetworkCookieJar.setCookiesFromUrl(self, cookieList, url)
		self.saveCookies()
		return res

	def saveCookies(self):
		cookies = QByteArray()
		for cookie in self.allCookies():
			if not cookie.isSessionCookie():
				cookies.append(cookie.toRawForm())
				cookies.append("\n")
		self.storage.setValue("cookies", cookies)

	def loadCookies(self):
		tmp = self.storage.value("cookies")
		if not tmp:
			return
		cookieList = QNetworkCookie.parseCookies(tmp)
		self.setAllCookies(cookieList)

	def py_cookies_internal(self):
		for c in self.allCookies():
			name, value = map(bytes, (c.name(), c.value()))
			domain = bytes(c.domain())
			initial_dot = domain_specified = domain.startswith(b'.')
			secure = bool(c.isSecure())
			path = unicode(c.path()).strip().encode('utf-8')
			expires = c.expirationDate()
			is_session_cookie = False
			if expires.isValid():
				expires = expires.toTime_t()
			else:
				expires = None
				is_session_cookie = True
			path_specified = True
			if not path:
				path = b'/'
				path_specified = False
			c = Cookie(0,  # version
					name, value,
					None,  # port
					False,  # port specified
					domain, domain_specified, initial_dot, path,
					path_specified,
					secure, expires, is_session_cookie,
					None,  # Comment
					None,  # Comment URL
					{}  # rest
			)
			yield c
	@property
	def py_cookies(self):
		'''
		Return all the cookies set currently as :class:`Cookie` objects.
		Returns expired cookies as well.
		'''
		return list(self.py_cookies_internal())
Example #24
0
 class __Config:
     def __init__(self, filename):
         self.settings = QSettings(filename,QSettings.IniFormat)
     def __str__(self):
         return repr(self) + self.val
     def basepath (self):
         return self.settings.value("global/resources_path")
     def path_to_pic(self):
         return os.path.join(self.settings.value("global/resources_path"),self.settings.value("global/resources_pic"))
     def path_to_qss(self):
         return os.path.join(self.settings.value("global/resources_path"),self.settings.value("global/resources_qss"))
     def path_to_book(self):
         return os.path.join(self.settings.value("global/resources_path"),self.settings.value("global/resources_book"))
     def path_to_texture(self):
         return os.path.join(self.settings.value("global/resources_path"),self.settings.value("global/resources_texture"))
     def path_to_icons(self):
         return os.path.join(self.settings.value("global/resources_path"),self.settings.value("global/resources_icons"))
     def path_to_sqlite(self):
         return os.path.join(self.settings.value("global/resources_path"),self.settings.value("global/resources_sqlite"))
     def model_database (self):
         return os.path.join(self.path_to_sqlite(),self.settings.value("global/default_database"))
     def current_database (self):
         return os.path.join(self.path_to_sqlite(),self.settings.value("global/current_database"))        
Example #25
0
class PreferencesDialog(QDialog):
    def __init__(self, parent):
        """
        Constructor of the PreferencesDialog.
        :param parent: A QWidget type (most likely the MainWindow) which is the parent widget of the dialog. 
        """
        super().__init__(parent)
        self.ui = Ui_PreferencesDialog()
        self.ui.setupUi(self)
        self._set_validators()

        self.settings = QSettings()

        # connect signals and slots
        self.ui.defaultValuesButton.clicked.connect(self._use_default_values)
        self.ui.buttonBox.accepted.connect(self._save_inputs)
        self.ui.outputFolderBrowseButton.clicked.connect(
            self._browse_output_folder)
        self.ui.vggBrowseButton.clicked.connect(self._browse_vgg)

        # disable "Use deepflow" checkbox under Microsoft Windows.
        self.ui.deepFlowCheckBox.setDisabled(get_os_type() == OS.WIN)

    def _set_validators(self):
        """
        This methods sets validation rules for the input fields. It should be called only once when the 
        PreferencesDialog is instantiated.
        :return: Has no return values.
        """
        self.ui.contentWeightInput.setValidator(QDoubleValidator(self))
        self.ui.styleWeightInput.setValidator(QDoubleValidator(self))
        self.ui.tvWeightInput.setValidator(QDoubleValidator(self))
        self.ui.temporalWeightInput.setValidator(QDoubleValidator(self))
        self.ui.learningRateInput.setValidator(QDoubleValidator(self))
        self.ui.iterationsInput.setValidator(QIntValidator(0, 5000, self))

    def show(self):
        """
        By calling this method the dialog gets visible. Also, the input widgets are set to their corresponding states.
        :return:
        """
        self._init_inputs()
        super().show()

    @pyqtSlot()
    def _init_inputs(self):
        """
        This method is called when the dialog is shown. It sets the initial values of the input fields and other
        widgets.
        :return: Has no return values. 
        """
        self.ui.contentWeightInput.setText(
            str(self.settings.value(CONTENT_WEIGHT_ID, str(CONTENT_WEIGHT))))
        self.ui.styleWeightInput.setText(
            str(self.settings.value(STYLE_WEIGHT_ID, str(STYLE_WEIGHT))))
        self.ui.tvWeightInput.setText(
            str(self.settings.value(TV_WEIGHT_ID, str(TV_WEIGHT))))
        self.ui.temporalWeightInput.setText(
            str(self.settings.value(TEMPORAL_WEIGHT_ID, str(TEMPORAL_WEIGHT))))
        self.ui.learningRateInput.setText(
            str(self.settings.value(LEARNING_RATE_ID, str(LEARNING_RATE))))
        self.ui.iterationsInput.setText(
            str(self.settings.value(ITERATIONS_ID, str(ITERATIONS))))
        self.ui.outputFolderInput.setText(
            str(self.settings.value(OUTPUT_LOCATION_ID, OUTPUT_LOCATION)))
        self.ui.vggInput.setText(
            str(self.settings.value(VGG_LOCATION_ID, VGG_LOCATION)))
        self.ui.deepFlowCheckBox.setChecked(
            str_to_bool(self.settings.value(USE_DEEPFLOW_ID, USE_DEEPFLOW)))

    @pyqtSlot()
    def _use_default_values(self):
        """
        This method sets the default values for the widgets.
        :return: Has no return values.
        """
        self.ui.contentWeightInput.setText(str(CONTENT_WEIGHT))
        self.ui.styleWeightInput.setText(str(STYLE_WEIGHT))
        self.ui.tvWeightInput.setText(str(TV_WEIGHT))
        self.ui.temporalWeightInput.setText(str(TEMPORAL_WEIGHT))
        self.ui.learningRateInput.setText(str(LEARNING_RATE))
        self.ui.iterationsInput.setText(str(ITERATIONS))
        self.ui.outputFolderInput.setText(OUTPUT_LOCATION)
        self.ui.vggInput.setText(VGG_LOCATION)
        self.ui.deepFlowCheckBox.setChecked(USE_DEEPFLOW)

    @pyqtSlot()
    def _save_inputs(self):
        """
        Saves the input values from the widget by using QSettings.
        :return: Has no return values.
        """
        content_weight = float(self.ui.contentWeightInput.text())
        style_weight = float(self.ui.styleWeightInput.text())
        tv_weight = float(self.ui.tvWeightInput.text())
        temporal_weight = float(self.ui.temporalWeightInput.text())
        learning_rate = float(self.ui.learningRateInput.text())
        iterations = float(self.ui.iterationsInput.text())
        output_location = self.ui.outputFolderInput.text()
        vgg_location = self.ui.vggInput.text()
        use_deepflow = self.ui.deepFlowCheckBox.isChecked()
        if not os.path.isdir(output_location):
            self.show_error_dialog(
                "Output folder {} does not exist!".format(output_location))
        elif not os.path.isfile(vgg_location):
            self.show_error_dialog(
                "VGG input {} does not exist!".format(vgg_location))
        else:
            self.settings.setValue(CONTENT_WEIGHT_ID, content_weight)
            self.settings.setValue(STYLE_WEIGHT_ID, style_weight)
            self.settings.setValue(TV_WEIGHT_ID, tv_weight)
            self.settings.setValue(TEMPORAL_WEIGHT_ID, temporal_weight)
            self.settings.setValue(LEARNING_RATE_ID, learning_rate)
            self.settings.setValue(ITERATIONS_ID, iterations)
            self.settings.setValue(OUTPUT_LOCATION_ID, output_location)
            self.settings.setValue(VGG_LOCATION_ID, vgg_location)
            self.settings.setValue(USE_DEEPFLOW_ID, boo_to_str(use_deepflow))

    @pyqtSlot()
    def _browse_output_folder(self):
        """
        A slot method for the "Browse" button used for browsing the output folder location.
        :return: Has no return values.
        """
        file_dialog = QFileDialog(self)
        file_dialog.setFileMode(QFileDialog.Directory)
        file_dialog.setOption(QFileDialog.ShowDirsOnly)
        if file_dialog.exec_():
            if len(file_dialog.selectedFiles()) > 0:
                selected_folder = file_dialog.selectedFiles()[0]
                self.ui.outputFolderInput.setText(selected_folder)

    @pyqtSlot()
    def _browse_vgg(self):
        """
        A slot method for the "Browse" button used for browsing the VGG(.mat) file  location.
        :return: Has no return values.
        """
        file_dialog = QFileDialog(self)
        file_dialog.setNameFilter("VGG (*.mat)")
        if file_dialog.exec_():
            if len(file_dialog.selectedFiles()) > 0:
                selected_folder = file_dialog.selectedFiles()[0]
                self.ui.outputFolderInput.setText(selected_folder)

    @pyqtSlot(str)
    def show_error_dialog(self, message):
        """
        Shows an error dialog to the user with the input message.
        :param message: A string holding the error message.
        :return: Has no return value.
        """
        error_message = QMessageBox(self)
        error_message.setWindowTitle("Error!")
        error_message.setText(message)
        error_message.setIcon(QMessageBox.Critical)
        error_message.exec_()
Example #26
0
    def __init__(self, parent=None):
        super(SerialPortProxy, self).__init__(parent)
        self.setObjectName("SerialPortProxy")

        #
        self._currIndex = 0
        self._currFrameId = 0
        self._frameSize = 0
        self._streamBuff = []
        self._newBuff = [0] * 4096
        self._pkgBuff = [0] * 100
        self._serialRecv = SerialRecv()

        self._serialConfig = SerialPortConfig()
        self._serialPort = QSerialPort(self)

        #
        self._serialPort.error.connect(self.onSerialPortError)
        self._serialPort.readyRead.connect(self.readData)

        #
        self._serialSimulate = None  # SerialSimulate(self)

        # read configuration
        settings = QSettings(self)
        # group - serialport properties
        settings.beginGroup("Settings/" + self.objectName() + "/SerialPort")
        self._serialConfig.port = settings.value("port", "COM1")
        infolist = settings.value("info", "115200-8-N-1").split("-")
        self._serialConfig.baudRate = int(infolist[0])
        dataBits = int(infolist[1])
        self._serialConfig.dataBits = (
            QSerialPort.Data5
            if dataBits == 5
            else QSerialPort.Data6
            if dataBits == 6
            else QSerialPort.Data7
            if dataBits == 7
            else QSerialPort.Data8
            if dataBits == 8
            else QSerialPort.Data8
        )
        parity = infolist[2][0].upper()
        self._serialConfig.parity = (
            QSerialPort.NoParity
            if parity == "N"
            else QSerialPort.EvenParity
            if parity == "E"
            else QSerialPort.OddParity
            if parity == "O"
            else QSerialPort.SpaceParity
            if parity == "S"
            else QSerialPort.MarkParity
            if parity == "M"
            else QSerialPort.NoParity
        )
        stopBits = int(float(infolist[3]) * 10)
        self._serialConfig.stopBits = (
            QSerialPort.OneStop
            if stopBits == 10
            else QSerialPort.OneAndHalfStop
            if stopBits == 15
            else QSerialPort.TwoStop
            if stopBits == 20
            else QSerialPort.OneStop
        )
        settings.endGroup()
Example #27
0
class QuiController(object):
    def __init__(self):
        pass

    def window_init(self):
        self.speech = Speech()
        self.document_editor = QuiTextEditor(self)
        self.document = self.document_editor.document()

        self.settings = QSettings("MyCompany", "MyApp")

        self.main_window = QuiMain(self)
        self._end_called = False

    def start(self):
        app = QApplication(sys.argv)
        app.setApplicationName('QuickText')

        self.window_init()

        if self.settings.value("myWidget/geometry") and self.settings.value("myWidget/windowState"):
            self.main_window.restoreGeometry(self.settings.value("myWidget/geometry"))
            self.main_window.restoreState(self.settings.value("myWidget/windowState"))
        self.main_window.show()

        try:
            ret = app.exec_()
        finally:
            self.end(ret)

    def end(self, ret=0):
        if self._end_called:
            return
        self._end_called = True

        self.settings.setValue("myWidget/geometry", self.main_window.saveGeometry())
        self.settings.setValue("myWidget/windowState", self.main_window.saveState())

        sys.exit(ret)

    def save(self):
        path, t = QFileDialog.getSaveFileName()
        cur = self.document.begin()
        last = self.document.end()
        with open(path, 'w') as f:
            while cur != last:
                f.write(cur.text()+'\n\n')
                cur = cur.next()

    def load(self):
        path, t = QFileDialog.getOpenFileName()
        markdown = Markdown()
        markdown.serializer = self._loader
        markdown.convertFile(path)

    def _loader(self, element):
        root = ElementTree(element).getroot()
        self.document.clear()
        cur = self.document_editor.textCursor()
        for child in root.getchildren():
            form = getattr(self.document_editor, 'format_{}'.format(child.tag), None)

            cur.insertText(child.text+'\n', form)

        return to_html_string(element)
Example #28
0
    def __init__(self, argv):  # noqa 901
        super(MainApplication, self).__init__(argv)
        self._isPrivate = False
        self._isPortable = True
        self._isClosing = False
        self._isStartingAfterCrash = False

        self._history = None  # History
        self._bookmarks = None  # Bookmarks
        self._autoFill = None  # AutoFill
        self._cookieJar = None  # CookieJar
        self._plugins = None  # PluginProxy
        self._browsingLibrary = None  # BrowsingLibrary

        self._networkManager = None
        self._restoreManager = None
        self._sessionManager = None
        self._downloadManager = None
        self._userAgentManager = None
        self._searchEnginesManager = None
        self._closedWindowsManager = None
        self._protocolHandlerManager = None
        self._html5PermissionsManager = None
        self._desktopNotifications = None  # DesktopNotificationsFactory
        self._webProfile = None  # QWebEngineProfile

        self._autoSaver = None
        self._proxyStyle = None
        self._wmClass = QByteArray()

        self._windows = []
        self._lastActiveWindow = None
        self._postLaunchActions = []

        self.setAttribute(Qt.AA_UseHighDpiPixmaps)
        self.setAttribute(Qt.AA_DontCreateNativeWidgetSiblings)

        self.setApplicationName('demo')
        self.setOrganizationDomain('org.autowin')
        self.setWindowIcon(QIcon.fromTheme('demo', QIcon(':/icons/demo.svg')))
        self.setDesktopFileName('orig.autowin.demo')

        self.setApplicationVersion('1.0')

        # Set fallback icon theme (eg. on Windows/Mac)
        if QIcon.fromTheme('view-refresh').isNull():
            QIcon.setThemeName('breeze-fallback')

        # QSQLITE database plugin is required
        if not QSqlDatabase.isDriverAvailable('QSQLITE'):
            QMessageBox.Critical(
                None, 'Error', 'Qt SQLite database plugin is not available.'
                ' Please install it and restart the application.')
            self._isClosing = True
            return
        if const.OS_WIN:
            # Set default app font (needed for N'ko)
            fontId = QFontDatabase.addApplicationFont('font.ttf')
            if fontId != -1:
                families = QFontDatabase.applicationFontFamilies(fontId)
                if not families.empty():
                    self.setFont(QFont(families.at(0)))

        startUrl = QUrl()
        startProfile = ''
        messages = []

        noAddons = False
        newInstance = False

        if len(argv) > 1:
            cmd = CommandLineOptions()
            for pair in cmd.getActions():
                action = pair.action
                text = pair.text
                if action == const.CL_StartWithoutAddons:
                    noAddons = True
                elif action == const.CL_StartWithProfile:
                    startProfile = text
                elif action == const.CL_StartPortable:
                    self._isPortable = True
                elif action == const.CL_NewTab:
                    messages.append("ACTION:NewTab")
                    self._postLaunchActions.append(self.OpenNewTab)
                elif action == const.CL_NewWindow:
                    messages.append("ACTION:NewWindow")
                elif action == const.CL_ToggleFullScreen:
                    messages.append("ACTION:ToggleFullScreen")
                    self._postLaunchActions.append(self.ToggleFullScreen)
                elif action == const.CL_ShowDownloadManager:
                    messages.append("ACTION:ShowDownloadManager")
                    self._postLaunchActions.append(self.OpenDownloadManager)
                elif action == const.CL_StartPrivateBrowsing:
                    self._isPrivate = True
                elif action == const.CL_StartNewInstance:
                    newInstance = True
                elif action == const.CL_OpenUrlInCurrentTab:
                    startUrl = QUrl.fromUserInput(text)
                    messages.append("ACTION:OpenUrlInCurrentTab" + text)
                elif action == const.CL_OpenUrlInNewWindow:
                    startUrl = QUrl.fromUserInput(text)
                    messages.append("ACTION:OpenUrlInNewWindow" + text)
                elif action == const.CL_OpenUrl:
                    startUrl = QUrl.fromUserInput(text)
                    messages.append("URL:" + text)
                elif action == const.CL_ExitAction:
                    self._isClosing = True
                    return
                elif action == const.CL_WMClass:
                    self._wmClass = text

        if not self.isPortable():
            appConf = QSettings(
                pathjoin(self.applicationDirPath(), '%s.conf' % const.APPNAME),
                QSettings.IniFormat)
            appConf.value('Config/Portable')

        if self.isPortable():
            print('%s: Running in Portable Mode.' % const.APPNAME)
            DataPaths.setPortableVersion()

        # Don't start single application in private browsing
        if not self.isPrivate():
            appId = 'org.autowin.mc'

            if self.isPortable():
                appId += '.Portable'

            if self.isTestModeEnabled():
                appId += '.TestMode'

            if newInstance:
                if not startProfile or startProfile == 'default':
                    print(
                        'New instance cannot be started with default profile!')
                else:
                    # Generate unique appId so it is possible to start more
                    # separate instances of the same profile. It is dangerous to
                    # run more instance of the same profile, but if the user
                    # wants it, we should allow it.
                    appId += '.' + str(QDateTime.currentMSecsSinceEpoch())

            self.setAppId(appId)

        # If there is nothing to tell other instance, we need to at least weak it
        if not messages:
            messages.append(' ')

        if self.isRunning():
            self._isClosing = True
            for message in messages:
                self.sendMessage(message)
            return

        if const.OS_MACOS:
            self.setQuitOnLastWindowClosed(False)
            # TODO:
            # disable tabbing issue #2261
            # extern void disableWindowTabbing();
            # self.disableWindowTabbing()
        else:
            self.setQuitOnLastWindowClosed(True)

        QSettings.setDefaultFormat(QSettings.IniFormat)
        QDesktopServices.setUrlHandler('http', self.addNewTab)
        QDesktopServices.setUrlHandler('https', self.addNewTab)
        QDesktopServices.setUrlHandler('ftp', self.addNewTab)

        profileManager = ProfileManager()
        profileManager.initConfigDir()
        profileManager.initCurrentProfile(startProfile)

        Settings.createSettings(
            pathjoin(DataPaths.currentProfilePath(), 'settings.ini'))

        NetworkManager.registerSchemes()

        if self.isPrivate():
            self._webProfile = QWebEngineProfile()
        else:
            self._webProfile = QWebEngineProfile.defaultProfile()
        self._webProfile.downloadRequested.connect(self.downloadRequested)

        self._networkManager = NetworkManager(self)

        self.setupUserScripts()

        if not self.isPrivate() and not self.isTestModeEnabled():
            self._sessionManager = SessionManager(self)
            self._autoSaver = AutoSaver(self)
            self._autoSaver.save.connect(
                self._sessionManager.autoSaveLastSession)

            settings = Settings()
            settings.beginGroup('SessionRestore')
            wasRunning = settings.value('isRunning', False)
            wasRestoring = settings.value('isRestoring', False)
            settings.setValue('isRunning', True)
            settings.setValue('isRestoring', wasRunning)
            settings.endGroup()
            settings.sync()

            self._isStartingAfterCrash = bool(wasRunning and wasRestoring)

            if wasRunning:
                QTimer.singleShot(
                    60 * 1000, lambda: Settings().setValue(
                        'SessionRestore/isRestoring', False))

            # we have to ask about startup session before creating main window
            if self._isStartingAfterCrash and self.afterLaunch(
            ) == self.SelectSession:
                self._restoreManager = RestoreManager(
                    self.sessionManager().askSessionFromUser())

        self.loadSettings()

        self._plugins = PluginProxy(self)
        self._autoFill = AutoFill(self)
        self.app.protocolHandlerManager()

        if not noAddons:
            self._plugins.loadPlugins()

        window = self.createWindow(const.BW_FirstAppWindow, startUrl)
        window.startingCompleted.connect(self.restoreOverrideCursor)

        self.focusChanged.connect(self.onFocusChanged)

        if not self.isPrivate() and not self.isTestModeEnabled():
            # check updates
            settings = Settings()
            checkUpdates = settings.value('Web-Browser-Settings/CheckUpdates',
                                          True)

            if checkUpdates:
                Updater(window)

            self.sessionManager().backupSavedSessions()

            if self._isStartingAfterCrash or self.afterLaunch(
            ) == self.RestoreSession:
                self._restoreManager = RestoreManager(
                    self.sessionManager().lastActiveSessionPath())
                if not self._restoreManager.isValid():
                    self.destroyRestoreManager()

            if not self._isStartingAfterCrash and self._restoreManager:
                self.restoreSession(window, self._restoreManager.restoreData())

        QSettings.setPath(QSettings.IniFormat, QSettings.UserScope,
                          DataPaths.currentProfilePath())

        self.messageReceived.connect(self.messageReceivedCb)
        self.aboutToQuit.connect(self.saveSettings)

        QTimer.singleShot(0, self.postLaunch)