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 __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)
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 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")
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 __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"
def remove_group(self, group_name): """ This is a prevent loading old/deleted groups :param group_name: the group name to be removed :return: """ settings = QSettings(self.user_settings_file, QSettings.IniFormat) settings.remove(group_name)
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 __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()
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 __init__(self, args): super().__init__(args) # self.setOrganizationName("philipbel") self.setOrganizationDomain("philipbel.github.io") self.setApplicationName("Subtitles") if sys.platform == 'win32': QSettings.setDefaultFormat(QSettings.IniFormat) self._resourcePaths = self._initResourcePaths()
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 __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 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)
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 __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 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 __init__(self, imgDir, app, start_args): super().__init__() self.app = app # Register the signal handlers signal.signal(signal.SIGTERM, service_shutdown) signal.signal(signal.SIGINT, service_shutdown) # Get version and title self.version = getSPMTVersion() self.title = 'SPMT - Secure PIVX Masternode Tool - v.%s-%s' % ( self.version['number'], self.version['tag']) # Create the userdir if it doesn't exist if not os.path.exists(user_dir): os.makedirs(user_dir) # Open database self.db = Database(self) self.db.open() # Clean v4 migration (read data from old files and delete them) clean_v4_migration(self) # Check for startup args (clear data) if start_args.clearAppData: settings = QSettings('PIVX', 'SecurePivxMasternodeTool') settings.clear() if start_args.clearRpcData: self.db.clearTable('CUSTOM_RPC_SERVERS') if start_args.clearMnData: self.db.clearTable('MASTERNODES') # Clear Rewards and Governance DB (in case of forced shutdown) self.db.clearTable('REWARDS') self.db.clearTable('PROPOSALS') self.db.clearTable('MY_VOTES') # Read Masternode List masternode_list = self.db.getMasternodeList() # Read cached app data self.cache = readCacheSettings() # Initialize user interface self.initUI(masternode_list, imgDir)
def __init__(self, game_dic={}, settings=QSettings()): self.context = zmq.Context() self.game_dic = game_dic # self.ip = "192.168.1.98" if settings.contains("ip_client"): self.ip = settings.value("ip_client") else: self.ip = "localhost" self.port = 5555 self.connect_socket()
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()
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 __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_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 _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)
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)
def __init__(self, context, settings = QSettings()): # self.context = zmq.Context() QtCore.QObject.__init__(self) self.subport = 5556 # self.ip = "192.168.1.98" if settings.contains("ip_client"): self.ip = settings.value("ip_client") else: self.ip = "localhost" self.sub_socket = context.socket(zmq.SUB) self.sub_socket.connect("tcp://" + self.ip + ':' + str(self.subport)) topicfilter = "message" self.sub_socket.setsockopt_string(zmq.SUBSCRIBE, topicfilter) self.running = True
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 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
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 createSettings(cls, fileName): cls.s_settings = QSettings(fileName, QSettings.IniFormat)
#!/usr/bin/python # -*- coding: utf-8 -*- import os from PyQt5.Qt import QSettings __author__ = 'xiwei' HOME = os.getcwd() RESOURCE = os.path.join(HOME, 'resource') ICON = os.path.join(RESOURCE, 'images', 'icon.png') UI = os.path.join(RESOURCE, 'ui', 'main.ui') UI_LOGIN = os.path.join(RESOURCE, 'ui', 'login.ui') STYLE = os.path.join(RESOURCE, 'ui', 'style.css') CLIENT_ID = QSettings().value('client_id')
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()
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 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
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 __init__(self): super(DataJar, self).__init__() self.settings = QSettings(assets.fs.dataPath() + '/data.ini', QSettings.IniFormat) self.load()
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
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())
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
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 )
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
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
help=_('Show the average rating per item indication in the tag browser')) c.add_opt('disable_animations', default=False, help=_('Disable UI animations')) # This option is no longer used. It remains for compatibility with upgrades # so the value can be migrated c.add_opt('tag_browser_hidden_categories', default=set(), help=_('tag browser categories not to display')) c.add_opt return ConfigProxy(c) config = _config() # }}} QSettings.setPath(QSettings.IniFormat, QSettings.UserScope, config_dir) QSettings.setPath(QSettings.IniFormat, QSettings.SystemScope, config_dir) QSettings.setDefaultFormat(QSettings.IniFormat) def available_heights(): desktop = QCoreApplication.instance().desktop() return map(lambda x: x.height(), map(desktop.availableGeometry, range(desktop.screenCount()))) def available_height(): desktop = QCoreApplication.instance().desktop() return desktop.availableGeometry().height() def max_available_height(): return max(available_heights()) def min_available_height():
def __init__(self, filename): self.settings = QSettings(filename,QSettings.IniFormat)
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"))
def __init__(self, organization, product): self.config = QSettings(organization, product)
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 __init__(self, iface, mainWindow=None): """Constructor. :param iface: An interface instance that will be passed to this class which provides the hook by which you can manipulate the QGIS application at run time. :type iface: QgsInterface """ # store references to important stuff from QGIS self.iface = iface self.canvas = iface.mapCanvas() self._project = QgsProject.instance() self._observingLayer = None self._uiHook = mainWindow if isinstance(mainWindow, QMainWindow) else iface # region: LOCALE - UNUSED # initialize plugin directory self.plugin_dir = os.path.dirname(__file__) # #initialize locale localeString = QSettings().value('locale/userLocale') if (localeString): locale = localeString[0:2] else: locale = QLocale().language() locale_path = os.path.join(self.plugin_dir, 'i18n', 'coordinator_{}.qm'.format(locale)) if os.path.exists(locale_path): self.translator = QTranslator() self.translator.load(locale_path) QCoreApplication.installTranslator(self.translator) # endregion # plugin housekeeping: self.openPanelAction = None self.pluginIsActive = False self.dockwidget = None # Init CRS Transformation: self._inputCrs = None self._outputCrs = None # self._transform : input -> output transformation # self._canvasTransform: input -> canvas transformation self.__initTransformers() # initialize canvas marker icon: self.marker = QgsVertexMarker(self.canvas) self.marker.hide() self.marker.setColor(QColor(255, 0, 0)) self.marker.setIconSize(14) self.marker.setIconType( QgsVertexMarker.ICON_CIRCLE ) # See the enum IconType from http://www.qgis.org/api/classQgsVertexMarker.html self.marker.setPenWidth(3) # init point picker: self.mapTool = QgsMapToolEmitPoint(self.canvas)
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)