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)
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)
def showDirSelector(self): print("selektor gewählt") fname = QtWidgets.QFileDialog.getExistingDirectory( None, "Überwachtes Verzeichnis wählen", self.watchedDir) # Zeigt den Dialog fname = os.path.normcase(fname) if ( fname != self.watchedDir and fname ): # Prüfung ob Verzeichnis gewählt wurde und ob es sich vom vorherigen unterscheidet self.observer.unschedule_all() # Watchdog anhalten print("Watchdog gestoppt") self.observer.schedule(self.handler, fname, False) # Watchdog neu starten self.watchedDir = fname self.reactiondialog.watchedDir = self.watchedDir settings = QSettings() settings.setValue( "WatchedDirectory", self.watchedDir) # neuen Verzeichnispfad speichern print("Überwache jetzt:", fname) self.reIndexDirectory( ) # Verzeichnis neu einlesen und Dateien indizieren else: print("Verzeichnis nicht geändert")
def configure(self): """Configure application settings by way of a dialog.""" dlg = ConfigDialog() if dlg.exec(): self.setPPScannos(dlg.lineEditPPScannos.text()) self.setDefaultScannoFile(dlg.comboScannoFiles.currentText()) settings = QSettings(QApplication.organizationName(), QApplication.applicationName()) settings.setValue('ppscannos', self.ppscannos) settings.setValue('defaultScannoFile', self.defaultScannoFile)
def set_user_settings(self, group_name, category, value): """ Saves user settings for a given group and category. group_name -- The group in which to save the settings value. category -- The category in which to save the settings value. value -- The value to save. """ settings = QSettings(self.user_settings_file, QSettings.IniFormat) settings.beginGroup(group_name) settings.setValue(str(category), value) settings.endGroup()
def setConfig(self, info): self._serialConfig.port = info.port self._serialConfig.baudRate = info.baudRate self._serialConfig.dataBits = info.dataBits self._serialConfig.parity = info.parity self._serialConfig.stopBits = info.stopBits # settings = QSettings(self) settings.beginGroup("Settings/" + self.objectName() + "/SerialPort") settings.setValue("port", self._serialConfig.port) settings.setValue("info", self.__str__()) settings.endGroup()
def add_file(self, file_name): item = RecentFile(file_name, self.open_file_slot) if (len(self) > 0) and (self[0] == item): return # No action; it's already there if item in self: self.remove(item) # it might be later in the list self.insert(0, item) # make it the first in this list if len(self) > 10: self[:] = self[:10] # List changed, so save it to the registry settings = QSettings() file_list = [x.file_name for x in self] settings.setValue(self.settings_key, file_list) self.update()
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
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
def save_setting(self, name, value): self._logger.info("Save setting %s -> %s", name, str(value)) settings = QSettings(self._settings_file, QSettings.NativeFormat) settings.setValue(name, value)
def setSettingsValue(key, val): syslog.syslog( syslog.LOG_DEBUG, "DEBUG setSettingsValue %s, value: %s" % (key, str(val))) s = QSettings() s.setValue(key, val)
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
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
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()
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()) # self.setBaseSize(self.screen().size())
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)
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())
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_()
class EKWindow(QDialog, dialog_ui.Ui_Dialog): def __init__(self, app): QDialog.__init__(self) self.app = app self.app_path = os.getenv("APPDATA") + "\\" + qApp.applicationName() self.registrySettings = QSettings("HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run", QSettings.NativeFormat) self.table_path = self.app_path + "\\tables" self.engine = Engine() self.minimize_action = QAction("Minimize", self) self.maximize_action = QAction("Maximize", self) self.settings_action = QAction("Settings", self) self.about_action = QAction("About", self) self.quit_action = QAction("Quit", self) self.tray_icon_menu = QMenu(self) self.tray_icon = QSystemTrayIcon(self) self.setupUi(self) self.icon = QIcon(QPixmap(":icon/off_logo")) self.construct_tray_icon() self.signal_connectors() self.database = DatabaseManager() self.shortcut_key = self.database.get_shortcut_key() self.populate_modifier_cbox() if self.database.get_current_state() == "True": self.engine.conv_state = False else: self.engine.conv_state = True self.icon_activated(QSystemTrayIcon.Trigger) self.file_path_tview.setEnabled(False) self.check_app_path() self.update_table(True) self.init_combobox() if self.registrySettings.contains(qApp.applicationName()): self.start_windows_check.setChecked(True) else: self.start_windows_check.setChecked(False) def check_app_path(self): if not os.path.exists(self.app_path): os.makedirs(self.app_path) if not os.path.exists(self.table_path): os.makedirs(self.table_path) return def construct_tray_icon(self): self.tray_icon.setIcon(self.icon) self.tray_icon_menu.addAction(self.settings_action) self.tray_icon_menu.addSeparator() self.tray_icon_menu.addAction(self.about_action) self.tray_icon_menu.addSeparator() self.tray_icon_menu.addAction(self.quit_action) self.tray_icon.setContextMenu(self.tray_icon_menu) self.tray_icon.show() def signal_connectors(self): self.tray_icon.activated.connect(self.icon_activated) self.settings_action.triggered.connect(self.show_setting) self.about_action.triggered.connect(self.show_about) self.quit_action.triggered.connect(self.quit) self.add_new_button.clicked.connect(self.change_dialog_index) self.back_button.clicked.connect(self.change_dialog_index) self.modifier_cbox.currentIndexChanged.connect(self.populate_shortcut_key) self.shortcut_key_cbox.currentIndexChanged.connect(self.save_shortcut_key) self.browse_button.clicked.connect(self.open_file_dialog) self.add_button.clicked.connect(self.save_file) self.clear_button.clicked.connect(self.reset_form) self.remove_button.clicked.connect(self.remove_keyboard) self.keyboard_cbox.currentIndexChanged.connect(self.save_current_keyboard) self.start_windows_check.stateChanged.connect(self.change_start_windows) def reset_form(self): self.clear_file_error() self.file_path_tview.setText("") def open_file_dialog(self): file_dialog = QFileDialog() self.file_path_tview.setText(QFileDialog.getOpenFileName(file_dialog, str("Choose a SCIM Table"), "", str("Scim Tables (*.in *.txt)"))[0]) def validate(self): try: with open(str(self.file_path_tview.text()), encoding="utf-8") as search: for line in search: line = line.rstrip() # remove '\n' at end of line if "SCIM_Generic_Table_Phrase_Library_TEXT" in line: return True self.show_file_error("Invalid SCIM Table file") return False except: self.show_file_error("Some error occurred") return False def save_file(self): if self.validate(): self.clear_file_error() filepath = str(self.file_path_tview.text()) fileinfo = QFileInfo(filepath) filename = str(int(time.time())) + "_" + fileinfo.fileName() keyboard_name = "Unknown" with open(filepath, encoding="utf-8") as search: for line in search: line = line.rstrip() # remove '\n' at end of line if "NAME" in line: name_line = line name_list = name_line.split('=', 1) if len(name_list) > 0: keyboard_name = name_list[1] if keyboard_name == "Unknown": self.show_file_error("SCIM table name header not found") elif DatabaseManager.check_keyboard_exist(keyboard_name): self.show_file_error("Keyboard already exists") else: shutil.copyfile(filepath, self.table_path + "\\" + filename) DatabaseManager.add_keyboard(keyboard_name, self.table_path + "\\" + filename) self.file_path_tview.setText("") self.update_table() def show_file_error(self, message): self.error_msg.setText(message) def clear_file_error(self): self.error_msg.setText("") def show_about(self): pass def quit(self): self.engine.un_hook() self.app.exit(0) def show_setting(self): self.stacked_widget.setCurrentIndex(0) self.showNormal() def change_dialog_index(self): current_index = self.stacked_widget.currentIndex() if current_index == 0: self.reset_form() self.init_table() self.stacked_widget.setCurrentIndex(1) else: self.init_combobox() self.stacked_widget.setCurrentIndex(0) def populate_modifier_cbox(self): self.modifier_cbox.blockSignals(True) modifiers = DatabaseManager.get_keys() for modifier in modifiers: self.modifier_cbox.addItem(modifier.name, modifier.id) if modifier.id == self.shortcut_key.parent.id: self.modifier_cbox.setCurrentText(modifier.name) self.populate_shortcut_key() self.modifier_cbox.blockSignals(False) def populate_shortcut_key(self): self.shortcut_key_cbox.blockSignals(True) self.shortcut_key_cbox.clear() keys = DatabaseManager.get_keys(self.modifier_cbox.currentData()) for key in keys: self.shortcut_key_cbox.addItem(key.name, key.id) if key.id == self.shortcut_key.id: self.shortcut_key_cbox.setCurrentText(key.name) self.shortcut_key_cbox.blockSignals(False) self.save_shortcut_key() def save_shortcut_key(self): DatabaseManager.set_shortcut_key(self.shortcut_key_cbox.currentData()) self.shortcut_key = DatabaseManager.get_shortcut_key() self.register_shortcut_listener() def register_shortcut_listener(self): self.engine.event_queue.remove_all() if self.shortcut_key.parent.name == "NONE": self.engine.event_queue.register_event( [ [self.shortcut_key.name], self.icon_activated, QSystemTrayIcon.Trigger ] ) elif self.shortcut_key.parent.name == "CTRL": self.engine.event_queue.register_event( [ ['Lcontrol', self.shortcut_key.name], self.icon_activated, QSystemTrayIcon.Trigger ] ) self.engine.event_queue.register_event( [ ['Rcontrol', self.shortcut_key.name], self.icon_activated, QSystemTrayIcon.Trigger ] ) elif self.shortcut_key.parent.name == "ALT": self.engine.event_queue.register_event( [ ['LMenu', self.shortcut_key.name], self.icon_activated, QSystemTrayIcon.Trigger ] ) self.engine.event_queue.register_event( [ ['RMenu', self.shortcut_key.name], self.icon_activated, QSystemTrayIcon.Trigger ] ) return True def change_status(self): self.engine.conv_state = not self.engine.conv_state DatabaseManager.set_current_state(self.engine.conv_state) if self.engine.conv_state: self.show_on_status() self.load_keyboard() else: self.show_off_status() def icon_activated(self, reason): if reason == QSystemTrayIcon.DoubleClick: pass elif reason == QSystemTrayIcon.Trigger: self.change_status() elif reason == QSystemTrayIcon.MiddleClick: pass else: pass def show_on_status(self): self.icon = QIcon(QPixmap(":icon/on_logo")) self.change_icons() def show_off_status(self): self.icon = QIcon(QPixmap(":icon/off_logo")) self.change_icons() def change_icons(self): self.tray_icon.setIcon(self.icon) self.setWindowIcon(self.icon) # TODO : Need to implement this method with current keyboard name self.tray_icon.setToolTip("Keyboard Name") self.show_tray_message() def show_tray_message(self): if self.engine.conv_state: message = "Ekalappai is Switched ON" else: message = "Ekalappai is Switched OFF" self.tray_icon.showMessage( qApp.applicationName() + " " + qApp.applicationVersion(), message, QSystemTrayIcon.MessageIcon(0), 100 ) def update_table(self, init=False): if init: self.init_table() records = DatabaseManager.get_all_keyboards() self.keyboard_table.setRowCount(records[0]) for idx, record in enumerate(records[1]): self.keyboard_table.setItem(idx, 1, QTableWidgetItem(record.language_name)) self.keyboard_table.setItem(idx, 2, QTableWidgetItem(str(record.id))) chk_box = QTableWidgetItem() chk_box.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled) chk_box.setCheckState(Qt.Unchecked) self.keyboard_table.setItem(idx, 0, chk_box) self.keyboard_table.resizeRowsToContents() return """ Initialize the grid with the default options """ def init_table(self): self.keyboard_table.setColumnCount(3) self.keyboard_table.setHorizontalHeaderLabels(["", "Name", "Id"]) self.keyboard_table.setColumnHidden(2, True) self.keyboard_table.setColumnWidth(0, 30) self.keyboard_table.horizontalHeader().setStretchLastSection(True) self.keyboard_table.setEditTriggers(QAbstractItemView.NoEditTriggers) self.keyboard_table.setSelectionBehavior(QTableView.SelectRows) self.keyboard_table.setSelectionMode(QAbstractItemView.SingleSelection) def remove_keyboard(self): for row in range(0, self.keyboard_table.rowCount()): if self.keyboard_table.item(row, 0).checkState() == Qt.Checked and \ DatabaseManager.get_current_keyboard() != self.keyboard_table.item(row, 2).text(): DatabaseManager.remove_keyboard(int(self.keyboard_table.item(row, 2).text())) self.update_table() def init_combobox(self): self.keyboard_cbox.blockSignals(True) self.keyboard_cbox.clear() current_keyboard = DatabaseManager.get_current_keyboard() index = 0 for keyboard in DatabaseManager.get_all_keyboards()[1]: self.keyboard_cbox.addItem(keyboard.language_name, keyboard.id) if int(current_keyboard) == keyboard.id: self.keyboard_cbox.setCurrentText(keyboard.language_name) self.keyboard_cbox.setCurrentIndex(index) index += 1 self.keyboard_cbox.blockSignals(False) def save_current_keyboard(self): DatabaseManager.set_current_keyboard(self.keyboard_cbox.currentData()) self.engine.conv_state = True DatabaseManager.set_current_state(self.engine.conv_state) self.show_on_status() self.load_keyboard() def load_keyboard(self): try: self.engine.file_name = DatabaseManager.get_keyboard_path(DatabaseManager.get_current_keyboard()) self.engine.initialize() except Exception as error: # TODO: Need to throw an error print('Error in loading keyboard') print(error) pass def change_start_windows(self): if self.start_windows_check.isChecked(): self.registrySettings.setValue(qApp.applicationName(), qApp.applicationFilePath()) else: self.registrySettings.remove(qApp.applicationName())
class EKWindow(QDialog, dialog_ui.Ui_Dialog): def __init__(self): QDialog.__init__(self) self.app_path = os.getenv("APPDATA") + "\\" + qApp.applicationName() self.registrySettings = QSettings("HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run", QSettings.NativeFormat) self.table_path = self.app_path + "\\tables" self.engine = Engine() self.minimize_action = QAction("Minimize", self) self.maximize_action = QAction("Maximize", self) self.settings_action = QAction("Settings", self) self.about_action = QAction("About", self) self.quit_action = QAction("Quit", self) self.tray_icon_menu = QMenu(self) self.tray_icon = QSystemTrayIcon(self) self.setupUi(self) self.icon = QIcon(QPixmap(":icon/off_logo")) self.construct_tray_icon() self.signal_connectors() self.database = DatabaseManager() self.shortcut_key = self.database.get_shortcut_key() self.populate_modifier_cbox() if self.database.get_current_state() == "True": self.engine.conv_state = False else: self.engine.conv_state = True self.icon_activated(QSystemTrayIcon.Trigger) self.file_path_tview.setEnabled(False) self.check_app_path() self.update_table(True) self.init_combobox() if self.registrySettings.contains(qApp.applicationName()): self.start_windows_check.setChecked(True) else: self.start_windows_check.setChecked(False) def check_app_path(self): if not os.path.exists(self.app_path): os.makedirs(self.app_path) if not os.path.exists(self.table_path): os.makedirs(self.table_path) return def construct_tray_icon(self): self.tray_icon.setIcon(self.icon) self.tray_icon_menu.addAction(self.settings_action) self.tray_icon_menu.addSeparator() self.tray_icon_menu.addAction(self.about_action) self.tray_icon_menu.addSeparator() self.tray_icon_menu.addAction(self.quit_action) self.tray_icon.setContextMenu(self.tray_icon_menu) self.tray_icon.show() def signal_connectors(self): self.tray_icon.activated.connect(self.icon_activated) self.settings_action.triggered.connect(self.show_setting) self.about_action.triggered.connect(self.show_about) self.quit_action.triggered.connect(self.quit) self.add_new_button.clicked.connect(self.change_dialog_index) self.back_button.clicked.connect(self.change_dialog_index) self.modifier_cbox.currentIndexChanged.connect(self.populate_shortcut_key) self.shortcut_key_cbox.currentIndexChanged.connect(self.save_shortcut_key) self.browse_button.clicked.connect(self.open_file_dialog) self.add_button.clicked.connect(self.save_file) self.clear_button.clicked.connect(self.reset_form) self.remove_button.clicked.connect(self.remove_keyboard) self.keyboard_cbox.currentIndexChanged.connect(self.save_current_keyboard) self.start_windows_check.stateChanged.connect(self.change_start_windows) def reset_form(self): self.clear_file_error() self.file_path_tview.setText("") def open_file_dialog(self): file_dialog = QFileDialog() self.file_path_tview.setText(QFileDialog.getOpenFileName(file_dialog, str("Choose a SCIM Table"), "", str("Scim Tables (*.in *.txt)"))[0]) def validate(self): try: with open(str(self.file_path_tview.text()), encoding="utf-8") as search: for line in search: line = line.rstrip() # remove '\n' at end of line if "SCIM_Generic_Table_Phrase_Library_TEXT" in line: return True self.show_file_error("Invalid SCIM Table file") return False except: self.show_file_error("Some error occurred") return False def save_file(self): if self.validate(): self.clear_file_error() filepath = str(self.file_path_tview.text()) fileinfo = QFileInfo(filepath) filename = str(int(time.time())) + "_" + fileinfo.fileName() keyboard_name = "Unknown" with open(filepath, encoding="utf-8") as search: for line in search: line = line.rstrip() # remove '\n' at end of line if "NAME" in line: name_line = line name_list = name_line.split('=', 1) if len(name_list) > 0: keyboard_name = name_list[1] if keyboard_name == "Unknown": self.show_file_error("SCIM table name header not found") elif DatabaseManager.check_keyboard_exist(keyboard_name): self.show_file_error("Keyboard already exists") else: shutil.copyfile(filepath, self.table_path + "\\" + filename) DatabaseManager.add_keyboard(keyboard_name, filename) self.file_path_tview.setText("") self.update_table() def show_file_error(self, message): self.error_msg.setText(message) def clear_file_error(self): self.error_msg.setText("") def show_about(self): pass def quit(self): self.engine.un_hook() win32api.PostThreadMessage(win32api.GetCurrentThreadId(), win32con.WM_QUIT, 0, 0) self.exit(0) def show_setting(self): self.stacked_widget.setCurrentIndex(0) self.showNormal() def change_dialog_index(self): current_index = self.stacked_widget.currentIndex() if current_index == 0: self.reset_form() self.init_table() self.stacked_widget.setCurrentIndex(1) else: self.init_combobox() self.stacked_widget.setCurrentIndex(0) def populate_modifier_cbox(self): self.modifier_cbox.blockSignals(True) modifiers = DatabaseManager.get_keys() for modifier in modifiers: self.modifier_cbox.addItem(modifier.name, modifier.id) if modifier.id == self.shortcut_key.parent.id: self.modifier_cbox.setCurrentText(modifier.name) self.populate_shortcut_key() self.modifier_cbox.blockSignals(False) def populate_shortcut_key(self): self.shortcut_key_cbox.blockSignals(True) self.shortcut_key_cbox.clear() keys = DatabaseManager.get_keys(self.modifier_cbox.currentData()) for key in keys: self.shortcut_key_cbox.addItem(key.name, key.id) if key.id == self.shortcut_key.id: self.shortcut_key_cbox.setCurrentText(key.name) self.shortcut_key_cbox.blockSignals(False) self.save_shortcut_key() def save_shortcut_key(self): DatabaseManager.set_shortcut_key(self.shortcut_key_cbox.currentData()) self.shortcut_key = DatabaseManager.get_shortcut_key() self.register_shortcut_listener() def register_shortcut_listener(self): self.engine.event_queue.remove_all() if self.shortcut_key.parent.name == "NONE": self.engine.event_queue.register_event( [ [self.shortcut_key.name], self.icon_activated, QSystemTrayIcon.Trigger ] ) elif self.shortcut_key.parent.name == "CTRL": self.engine.event_queue.register_event( [ ['Lcontrol', self.shortcut_key.name], self.icon_activated, QSystemTrayIcon.Trigger ] ) self.engine.event_queue.register_event( [ ['Rcontrol', self.shortcut_key.name], self.icon_activated, QSystemTrayIcon.Trigger ] ) elif self.shortcut_key.parent.name == "ALT": self.engine.event_queue.register_event( [ ['LMenu', self.shortcut_key.name], self.icon_activated, QSystemTrayIcon.Trigger ] ) self.engine.event_queue.register_event( [ ['RMenu', self.shortcut_key.name], self.icon_activated, QSystemTrayIcon.Trigger ] ) return True def change_status(self): self.engine.conv_state = not self.engine.conv_state DatabaseManager.set_current_state(self.engine.conv_state) if self.engine.conv_state: self.show_on_status() self.load_keyboard() else: self.show_off_status() def icon_activated(self, reason): if reason == QSystemTrayIcon.DoubleClick: pass elif reason == QSystemTrayIcon.Trigger: self.change_status() elif reason == QSystemTrayIcon.MiddleClick: pass else: pass def show_on_status(self): self.icon = QIcon(QPixmap(":icon/on_logo")) self.change_icons() def show_off_status(self): self.icon = QIcon(QPixmap(":icon/off_logo")) self.change_icons() def change_icons(self): self.tray_icon.setIcon(self.icon) self.setWindowIcon(self.icon) # TODO : Need to implement this method with current keyboard name self.tray_icon.setToolTip("Keyboard Name") self.show_tray_message() def show_tray_message(self): if self.engine.conv_state: message = "Ekalappai is Switched ON" else: message = "Ekalappai is Switched OFF" self.tray_icon.showMessage( qApp.applicationName() + " " + qApp.applicationVersion(), message, QSystemTrayIcon.MessageIcon(0), 100 ) def update_table(self, init=False): if init: self.init_table() records = DatabaseManager.get_all_keyboards() self.keyboard_table.setRowCount(records[0]) for idx, record in enumerate(records[1]): self.keyboard_table.setItem(idx, 1, QTableWidgetItem(record.language_name)) self.keyboard_table.setItem(idx, 2, QTableWidgetItem(str(record.id))) chk_box = QTableWidgetItem() chk_box.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled) chk_box.setCheckState(Qt.Unchecked) self.keyboard_table.setItem(idx, 0, chk_box) self.keyboard_table.resizeRowsToContents() return """ Initialize the grid with the default options """ def init_table(self): self.keyboard_table.setColumnCount(3) self.keyboard_table.setHorizontalHeaderLabels(["", "Name", "Id"]) self.keyboard_table.setColumnHidden(2, True) self.keyboard_table.setColumnWidth(0, 30) self.keyboard_table.horizontalHeader().setStretchLastSection(True) self.keyboard_table.setEditTriggers(QAbstractItemView.NoEditTriggers) self.keyboard_table.setSelectionBehavior(QTableView.SelectRows) self.keyboard_table.setSelectionMode(QAbstractItemView.SingleSelection) def remove_keyboard(self): for row in range(0, self.keyboard_table.rowCount()): if self.keyboard_table.item(row, 0).checkState() == Qt.Checked and \ DatabaseManager.get_current_keyboard() != self.keyboard_table.item(row, 2).text(): DatabaseManager.remove_keyboard(int(self.keyboard_table.item(row, 2).text())) self.update_table() def init_combobox(self): self.keyboard_cbox.blockSignals(True) self.keyboard_cbox.clear() current_keyboard = DatabaseManager.get_current_keyboard() index = 0 for keyboard in DatabaseManager.get_all_keyboards()[1]: self.keyboard_cbox.addItem(keyboard.language_name, keyboard.id) if int(current_keyboard) == keyboard.id: self.keyboard_cbox.setCurrentText(keyboard.language_name) self.keyboard_cbox.setCurrentIndex(index) index += 1 self.keyboard_cbox.blockSignals(False) def save_current_keyboard(self): DatabaseManager.set_current_keyboard(self.keyboard_cbox.currentData()) self.engine.conv_state = True DatabaseManager.set_current_state(self.engine.conv_state) self.show_on_status() self.load_keyboard() def load_keyboard(self): self.engine.file_name = self.table_path +\ "\\" + \ DatabaseManager.get_keyboard_path(DatabaseManager.get_current_keyboard()) self.engine.initialize() print(DatabaseManager.get_keyboard_path(DatabaseManager.get_current_keyboard())) def change_start_windows(self): if self.start_windows_check.isChecked(): self.registrySettings.setValue(qApp.applicationName(), qApp.applicationFilePath()) else: self.registrySettings.remove(qApp.applicationName())
def closeEvent(self, *args, **kwargs): settings = QSettings() settings.setValue("Geometry", QtCore.QVariant(self.saveGeometry())) print("geschlossen") return QtWidgets.QMainWindow.closeEvent(self, *args, **kwargs)
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