def test_updateKey(self): t = PickleSettings() t.storeSettings() t.initializeSettings() settings = QSettings('zero_substance', 'structjour') apiset = QSettings('zero_substance/stockapi', 'structjour') settings.setValue('journal', self.p) mk = util.ManageKeys(create=True) mk.updateKey('bc', 'Its the end of the world') mk.updateKey('av', 'as we know it') bck = mk.getKey('bc') avk = mk.getKey('av') self.assertTrue(bck == 'Its the end of the world') self.assertTrue(avk == 'as we know it') l = apiset.value('dbsqlite') t.restoreSettings() print(apiset.allKeys()) print(settings.allKeys()) os.remove(l) # self.assertTrue(os) mk = util.ManageKeys() print(mk.getKey('bc'))
def localstuff(): settings = QSettings('zero_substance', 'structjour') apiset = QSettings('zero_substance/stockapi', 'structjour') setkeys = settings.allKeys() apikeys = apiset.allKeys() setval = list() apival = list() for k in setkeys: setval.append(settings.value(k)) for k in apikeys: apival.append(apiset.value(k)) print()
def readThemeIndex(self, themeName): dirList = [] parents = [] themeIndex = QFile() # Read theme index files for i in range(len(self.iconDirs)): themeIndex.setFileName( path.join(unicode(self.iconDirs[i]), unicode(themeName), "index.theme")) if themeIndex.exists(): indexReader = QSettings(themeIndex.fileName(), QSettings.IniFormat) for key in indexReader.allKeys(): if str(key).endswith("/Size"): size = str(indexReader.value(key)) dirList.append((size, unicode(key[:-5]))) parents = indexReader.value('Icon Theme/Inherits') dump = parents parents = list() parents.append(dump) break return QIconTheme(dirList, parents)
class OpenDropQt(QMainWindow): company_str = "CCLC" project_str = "opendrop-qt" def __init__(self, parent=None): super().__init__() if parent: self.setParent(parent) self.resize(300, 500) self.main_layout = QGridLayout() self.setLayout(self.main_layout) self.settings = QSettings(self.company_str, self.project_str) if 'init_completed' not in self.settings.allKeys(): self.setup_initial() self.sb_owl = None self.sb_opendrop = None def setup_initial(self): print('We are here!') setup_container = QWidget() setup_container.setLayout(QVBoxLayout()) initial_setup_label = QLabel( self.tr('Welcome to the initial setup of OpenDropQt!')) setup_container.layout().addWidget(initial_setup_label) self.main_layout.addWidget(setup_container) def start_owl(self): self.sb_owl = sb.Popen(["pkexec"])
def _load_settings(self): # try: # with open(self.settings_path, 'r') as f: # settings = json.load(f) settings = QSettings("Maccesch", "SongScreen") if settings.contains('lyrics_screen'): self.display_lyrics_on_screen(settings.value('lyrics_screen')) if settings.contains('control_window_position'): self.move(settings.value('control_window_position')) for key in settings.allKeys(): self.settings[key] = settings.value(key) # self.settings.update(settings) self.songtext_widget.set_font_size(self.settings['font_size']) self.songtext_widget.set_line_increment(self.settings['line_increment']) # except (FileNotFoundError, ValueError): # pass if not os.path.exists(self.lyrics_language_path) or not self.settings['lyrics_language']: languages = list( filter(lambda p: os.path.isdir(os.path.join(self.lyrics_path, p)) and p != "timings", os.listdir(self.lyrics_path)) ) self.settings['lyrics_language'] = languages[0] if languages else ""
def readThemeIndex(self, themeName): dirList = [] parents = [] themeIndex = QFile() # Read theme index files for i in range(len(self.iconDirs)): themeIndex.setFileName(path.join(unicode(self.iconDirs[i]), unicode(themeName), "index.theme")) if themeIndex.exists(): indexReader = QSettings(themeIndex.fileName(), QSettings.IniFormat) for key in indexReader.allKeys(): if str(key).endswith("/Size"): size = str(indexReader.value(key)) dirList.append((size, unicode(key[:-5]))) parents = indexReader.value('Icon Theme/Inherits') dump=parents parents = list() parents.append(dump) break return QIconTheme(dirList, parents)
def read_app_settings(self): """Read the app settings.""" settings = QSettings(QDir.homePath() + '/.videomorph/config.ini', QSettings.IniFormat) pos = settings.value("pos", QPoint(600, 200), type=QPoint) size = settings.value("size", QSize(1096, 510), type=QSize) self.resize(size) self.move(pos) if 'profile' and 'preset' in settings.allKeys(): prof = settings.value('profile') pres = settings.value('preset') self.cb_profiles.setCurrentIndex(int(prof)) self.cb_presets.setCurrentIndex(int(pres)) if 'output_dir' in settings.allKeys(): self.le_output.setText(str(settings.value('output_dir'))) if 'conversion_lib' in settings.allKeys(): self.conversion_lib = settings.value('conversion_lib')
class SettingsINI(object): """ settings INI file implemented for Wifi-Pumpkin""" _instance = None def __init__(self, filename): if path.isfile(filename): self.psettings = QSettings(filename, QSettings.IniFormat) @staticmethod def getInstance(): if SettingsINI._instance is None: SettingsINI._instance = SettingsINI(C.CONFIG_INI) return SettingsINI._instance def get(self, name_group, key, format=str): """ Get the value for setting key """ self.psettings.beginGroup(name_group) value = self.psettings.value(key, type=format) self.closeGroup() return value def set(self, name_group, key, value): """ Sets the value of setting key to value """ self.psettings.beginGroup(name_group) self.psettings.setValue(key, value) self.closeGroup() def set_one(self, name_group, key, value): """ Sets the value of setting key to value """ self.set(name_group, key, value) for item in self.get_all_childname(name_group): if item != key: self.set(name_group, item, False) def get_by_index_key(self, index, key=str): """ get specific key value by index type(list) """ return str(self.get(key, self.get_all_childname(key)[index])) def get_all_childname(self, key): """ get list all childskeys on file config.ini """ return [x.split("/")[1] for x in self.get_all_keys() if x.split("/")[0] == key] def get_name_activated_plugin(self, key): """ get status by plugin name """ plugins = self.get_all_childname(key) for plugin in plugins: if self.get(key, plugin, format=bool): return plugin return None def get_all_keys(self): """ get all keys on settings""" return self.psettings.allKeys() def closeGroup(self): """ close group settings""" self.psettings.endGroup()
class SettingsUI(QDialog, Ui_Dialog): settings_dict = pyqtSignal(dict) def __init__(self): super().__init__() self.setupUi(self) self.settings = QSettings('settings.ini', QSettings.IniFormat) self.toolButton.clicked.connect(lambda:self.lineEdit_watcher_folder.setText(QFileDialog.getExistingDirectory())) def isFirstRun(self): return self.settings.value('first_run', False) def getAPIKey(self): return self.settings.value('api_key') def getFolder(self): return self.settings.value('folder') # def getWhitelistExtensions(self): # return self.settings.value('files_extension') def getMailServer(self): return self.settings.value('mail_server') def getMailError(self): return self.settings.value('mail_error') def accept(self): if not self.lineEdit_API.text(): QMessageBox.critical(self, 'Ошибка', 'Укажите API ключ для доступа к Yandex API') elif not self.lineEdit_watcher_folder.text() or not os.path.isdir(self.lineEdit_watcher_folder.text()): QMessageBox.critical(self, 'Ошибка', 'Укажите папку с файлами для загрузки') elif not self.lineEdit_mail_server.text(): QMessageBox.critical(self, 'Ошибка', 'Укажите адрес сервера') else: self.settings.setValue('first_run', False) self.settings.setValue('api_key', self.lineEdit_API.text()) self.settings.setValue('folder', self.lineEdit_watcher_folder.text()) self.settings.setValue('mail_error', self.lineEdit_mail_error.text()) self.settings.setValue('mail_server', self.lineEdit_mail_server.text()) self.update_settings() super().accept() def update_settings(self): settings = {} for key in self.settings.allKeys(): settings[key] = self.settings.value(key) self.settings_dict.emit(settings) def exec(self): self.lineEdit_API.setText(self.getAPIKey()) self.lineEdit_watcher_folder.setText(self.getFolder()) self.lineEdit_mail_error.setText(self.getMailError()) self.lineEdit_mail_server.setText(self.getMailServer()) super().exec()
def get_postgres_connections(): s = QSettings() s.beginGroup("PostgreSQL/connections") d = set([key.split('/')[0] for key in s.allKeys()]) d.remove('selected') s.endGroup() return list(d)
def get_existing_database_connections() -> {str}: """ :return: set of connections names """ s = QSettings() s.beginGroup(PG_CONNECTIONS) keys = s.allKeys() s.endGroup() connections = {key.split('/')[0] for key in keys if '/' in key} LOGGER.debug(f"Connections: {connections}") return connections
def main(): """The main routine.""" environ["LIBOVERLAY_SCROLLBAR"] = "0" parser = argparse.ArgumentParser( prog=__title__, description=__title__ + ' is a 2d RPG game maker.', epilog=__copyright__ + ", " + __license__ +".") parser.add_argument('-v', '--version', action='store_true', default=False, help='get software version.') parser.add_argument('-c', '--clean', action='store_true', default=False, help='cleans software settings.') parser.add_argument('-p', '--palette', action='store_true', default=False, help='loads exclusively the palette editor.') parser.add_argument('mapfile', nargs='?', default='check_no_map', help='a single .map.json file') args = parser.parse_args() if args.clean == True: settings = QSettings("FGMK", "fgmkEditor") for key in settings.allKeys(): settings.remove(key) #guarantee to eliminate all settings.sync() #writes to disk exit() if args.palette == True: a = QApplication([]) m = palette_editor.main() a.processEvents() m.show() m.raise_() exit(a.exec_()) if args.version == True: print(__title__ + " v " + __version__ ) exit() a = QApplication([]) start = time() splash_pix = Editor.Icon() splash = QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint) splash.setMask(splash_pix.mask()) splash.show() while time() - start < 1: sleep(0.001) a.processEvents() mw_arg=[] if 'mapfile' in args: mw_arg = [args.mapfile] mw = Editor.MainWindow(mw_arg) a.processEvents() mw.show() splash.finish(mw) mw.raise_() mw.afterInit() exit(a.exec_())
def test_setDB(self): ''' Test the method ManageKeys.setDB. The location depends on having the journal location set. This method is called by init y default. ''' t = PickleSettings() t.storeSettings() t.initializeSettings() settings = QSettings('zero_substance', 'structjour') apiset = QSettings('zero_substance/stockapi', 'structjour') settings.setValue('journal', self.p) mk = util.ManageKeys(create=True) l = apiset.value('dbsqlite') self.assertTrue(os.path.exists(l)) os.remove(l) t.initializeSettings() settings.setValue('journal', self.p) mk = util.ManageKeys(create=True) ll = apiset.value('dbsqlite') self.assertTrue(l == ll) os.remove(ll) # self.assertEqual(l, ll) t.initializeSettings() # settings.setValue('journal', self.p) mk = util.ManageKeys(create=True) lll = apiset.value('dbsqlite') self.assertFalse(lll) t.restoreSettings() print(apiset.allKeys()) print(settings.allKeys()) # self.assertTrue(os) print()
def __init__(self): QMainWindow.__init__(self) self.main_ui = Ui_MainWindow() self.main_ui.setupUi(self) # 初始化数据 settings = QSettings("ZhongLiuYiYuanConfig.ini", QSettings.IniFormat) for i in settings.allKeys(): print(i) self.checkItemPriceDict = { '检查项目A': 101, '检查项目B': 200, '检查项目C': 300, '检查项目D': 200, '检查项目E': 300, '检查项目F': 50234, '检查项目G': 120 } self.checkItemList = [ '检查项目A', '检查项目B', '检查项目C', '检查项目D', '检查项目E', '检查项目F', '检查项目G' ] self.companyList = [ '公司VVVh', '公司12', '公司A432', '公司Afasd', '公司fas', '公司234fw', '公司bfg' ] self.companyPriceDict = dict() self.patientsList = [] self.main_ui.choose_company_button.clicked.connect( self.openCompanyWindow) self.main_ui.choose_items_button.clicked.connect( self.opencheckItemWindow) self.main_ui.add_one_unit_button.clicked.connect(self.add_one_unit) self.main_ui.delete_one_unit_button.clicked.connect( self.delete_one_unit) self.main_ui.save_to_file_button.clicked.connect(self.save_to_file) self.main_ui.com_add_pushButton.clicked.connect(self.add_com_to_list) self.main_ui.com_del_pushButton.clicked.connect(self.del_com_to_list) self.main_ui.item_price_add_pushButton.clicked.connect( self.add_item_price_to_list) self.main_ui.item_price_del_pushButton.clicked.connect( self.del_item_price_to_list) self.main_ui.save_to_ini_button.clicked.connect(self.save_to_ini_file) #初始化页面 for i in self.companyList: self.main_ui.page2_com_listWidget.addItem(i) for j in self.checkItemPriceDict: self.main_ui.page2_item_price_listWidget.addItem( j + ':' + str(self.checkItemPriceDict[j]))
def moveSettingsToNewRoot(): """Move all settings to one application file.""" movelist = [[appinfo.name, appinfo.url, False], "metainfo", "snippets", "sessions", "sessiondata"] for moveitem in movelist: if isinstance(moveitem, string_types): moveitem = [moveitem, appinfo.name, True] o = QSettings(moveitem[1], moveitem[0]) o.setFallbacksEnabled(False) keys = o.allKeys() if len(keys) > 0: s = QSettings() if moveitem[2]: s.beginGroup(moveitem[0]) for k in keys: s.setValue(k, o.value(k)) o.clear()
def test_ibSettings(self): t = PickleSettings() t.storeSettings() t.initializeSettings() apiset = QSettings('zero_substance/stockapi', 'structjour') apiset.setValue('ibRealCb', True) apiset.setValue('ibPaperCb', False) ibs = util.IbSettings() defport = 7496 defid = 7878 defhost = '127.0.0.1' p = ibs.getIbSettings() self.assertEqual(defhost, p['host']) self.assertEqual(defid, p['id']) self.assertEqual(defport, p['port']) t.restoreSettings() print(apiset.allKeys())
def get_db_credentials(self, db_name): db_credentials = {} qs = QSettings() k_list = [ k for k in sorted(qs.allKeys()) if k[:10] == "PostgreSQL" and k.split("/")[2] == db_name ] for k in k_list: if k.split("/")[-1] == "database": db_credentials["dbname"] = qs.value(k) elif k.split("/")[-1] == "host": db_credentials["host"] = qs.value(k) elif k.split("/")[-1] == "port": db_credentials["port"] = qs.value(k) elif k.split("/")[-1] == "username": db_credentials["user"] = qs.value(k) elif k.split("/")[-1] == "password": db_credentials["password"] = qs.value(k) return db_credentials
def settings(self): settings = QSettings(QSettings.IniFormat, QSettings.UserScope, self.name, "settings") # Set default values if the config file is empty or was not created. if not settings.allKeys(): logger.debug("Loading default settings.") settings.beginGroup("Quanty") settings.setValue("Path", self.findQuanty()) settings.setValue("Verbosity", "0x0000") settings.setValue("DenseBorder", "2000") settings.setValue("ShiftSpectra", True) settings.setValue("RemoveFiles", True) settings.endGroup() settings.setValue("CheckForUpdates", True) settings.setValue("CurrentPath", os.path.expanduser("~")) settings.setValue("Version", version) settings.sync() return settings
class ddeconfig(object): ''' 获得桌面图标排序,数量少于一列 ''' def __init__(self): self.defaultpath = os.path.expanduser("~/.config/deepin/dde-desktop.conf") self.desktop_icon = configparser.ConfigParser() self.section = "DesktopItems" self.qsetting_conf = QSettings(self.defaultpath, QSettings.IniFormat) def getDesktopIconlist(self): self.desktop_icon.read(self.defaultpath) list = self.desktop_icon.items(self.section) dict = {} for i in list: name = i[0].split('\\')[-1] y = i[1].split()[-1].replace(')', ' ').split()[0] dict[int(y)] = name dictsort = sorted(dict.iteritems(), key= lambda d:d[0]) rl = [] for k, v in dictsort: rl.append(v) return rl def getDesktopIconlist2(self): self.qsetting_conf = QSettings(self.defaultpath, QSettings.IniFormat) dict = {} for i in self.qsetting_conf.allKeys(): y = self.qsetting_conf.value(i).y() name = i.split('/')[-1] dict[int(y)] = name dictsort = sorted(dict.iteritems(), key = lambda d:d[0]) rl = [] for k, v in dictsort: rl.append(v) return rl
def clicked_set(self): ''' Retrieves all input fields and saves to QSettings ''' settings = QSettings() for key, edit in self.key_to_edit.items(): # setting key has no edit if not edit: continue if key == 'time_unit': value = edit.text() # the only string parameter settings.setValue(key, value) continue if key == 'nT': value = int(edit.text()) # the only integer parameter settings.setValue(key, value) continue value = util.retrieve_double_edit(edit) # None is also fine! settings.setValue(key, value) # the output settings are strings if self.fmt_dropdown.currentText() == 'Decimal': settings.setValue('float_format', '%.3f') elif self.fmt_dropdown.currentText() == 'Scientific': settings.setValue('float_format', '%e') # we can take the items directly settings.setValue('graphics_format', self.graphics_dropdown.currentText()) if self.debug: for key in settings.allKeys(): print(f'Set: {key} -> {settings.value(key)}')
def add_sqlite_connection(self): """add a QGIS-connection to the SpatiaLite loaded by the 3Di plugin""" layer = QgsProject.instance().mapLayersByName("v2_global_settings")[0] source = Path( layer.dataProvider().dataSourceUri().split(" ")[0].split("=")[1][1:-1] ) settings = QSettings() # remove old connection for key in settings.allKeys(): if "SpatiaLite/connections/3Di plugin" in key: settings.remove(key) settings.setValue( "SpatiaLite/connections/%s/sqlitepath" % ( "3Di plugin: {}, {}".format( source.name, datetime.now().strftime("%Y-%m-%d %H:%M") ) ), str(source), ) self.iface.reloadConnections()
def readThemeIndex(self, themeName): dirList = [] parents = [] themeIndex = QFile() # Read theme index files for i in range(len(self.iconDirs)): themeIndex.setFileName(path.join(unicode(self.iconDirs[i]), unicode(themeName), "index.theme")) if themeIndex.exists(): indexReader = QSettings(themeIndex.fileName(), QSettings.IniFormat) for key in indexReader.allKeys(): if key.endswith("/Size"): size = indexReader.value(key) dirList.append((size[0], unicode(key.left(key.size() - 5)))) parents = indexReader.value('Icon Theme/Inherits') parents = parents.toStringList() break return QIconTheme(dirList, parents)
def readThemeIndex(self, themeName): dirList = [] parents = [] themeIndex = QFile() # Read theme index files for i in range(len(self.iconDirs)): themeIndex.setFileName( path.join(unicode(self.iconDirs[i]), unicode(themeName), "index.theme")) if themeIndex.exists(): indexReader = QSettings(themeIndex.fileName(), QSettings.IniFormat) for key in indexReader.allKeys(): if key.endswith("/Size"): size = indexReader.value(key) dirList.append( (size[0], unicode(key.left(key.size() - 5)))) parents = indexReader.value('Icon Theme/Inherits') parents = parents.toStringList() break return QIconTheme(dirList, parents)
def getEditor(): editor = QsciScintilla() lexer = QsciLexerYAML() editor.setLexer(lexer) font = getFont() # lexer.setDefaultFont(font) lexer.setFont(font) settings = QSettings() lexer.readSettings(settings) print(settings.allKeys()) lexer.setDefaultPaper(QColor('#252721')) for i in range(10): lexer.setPaper(QColor('#252721'), i) lexer.setColor(QColor('#f8f8f2'), i) print(lexer.color(i).name()) lexer.setColor(QColor('#e6db74'), 0) # foreground (yellow) lexer.setColor(QColor('#75715e'), 1) # comment (gray) lexer.setColor(QColor('#f92672'), 2) # identifier (red) lexer.setColor(QColor('#ae81ff'), 3) # keyword (purple) lexer.setColor(QColor('#ae81ff'), 4) # number (purple) lexer.setColor(QColor('#ae81ff'), 5) # reference (purple) lexer.setColor(QColor('#ae81ff'), 6) # documentdelimiter (purple) lexer.setColor(QColor('#ae81ff'), 7) # text block marker (purple) lexer.setColor(QColor('#f92672'), 8) # syntax error marker (red) lexer.setColor(QColor('#f92672'), 9) # operator (red) # editor.setFont(font) # editor.setMarginsFont(font) editor.setCaretForegroundColor(QColor('#f8f8f0')) editor.setMarginWidth(0, getMarginWidth(font)) editor.setMarginWidth(1, 0) editor.setMarginLineNumbers(0, True) editor.setMarginsBackgroundColor(QColor('#252721')) editor.setMarginsForegroundColor(QColor('#f8f8f2')) editor.setExtraAscent(3) editor.setTabWidth(4) editor.setMinimumSize(600, 450) return editor
class Dialog(QFileDialog): def __init__(self, title="open file", filetype="", mode="file", settings_name="__"): super().__init__() self.settings_name = settings_name self.load_seetings() self.filter = filetype self.mode = mode self.title = title def openFile(self): if self.mode == "file": file = self.getOpenFileName(caption=self.title, filter=self.filter)[0] elif self.mode == "dir": file = self.getExistingDirectory(caption=self.title) else: return self.update_settings(file) return file def load_seetings(self): self.settings = QSettings("deformation_cytometer", self.settings_name) if "location" in self.settings.allKeys(): self.location = self.settings.value("location") self.setDirectory(self.location) def update_settings(self, file): try: self.settings.setValue("location", os.path.split(file)[0]) except Exception as e: print(e)
class UserSettings(QObject): """ The root of all user settings. """ @inject def __init__(self, configuration: Configuration): super().__init__() QSettings.setDefaultFormat(QSettings.IniFormat) QSettings.setPath(QSettings.IniFormat, QSettings.UserScope, configuration.user_settings_directory) # We fake the application and organisation name to try and use a "nicer" directory for settings. # However, an organisation name is required to ensure this works properly on all systems. # See issues like this: https://www.qtcentre.org/threads/35300-QSplitter-restoreState()-not-working self.__store = QSettings(QSettings.IniFormat, QSettings.UserScope, "nasm", "settings", self) def save(self, key: Union[Key, str], value: any): """ Save a value in the user's settings. """ self.__store.setValue(UserSettings.__key_value(key), value) def save_as_json(self, key: Union[Key, str], value: any): """ Saves the given object in json. Useful for simple types when not natively supported. """ self.__store.setValue(UserSettings.__key_value(key), json.dumps(value)) def save_as_binary(self, key: Union[Key, str], value: any): """ Saves the given object in binary. Useful when other formats are not possible. """ self.__store.setValue(UserSettings.__key_value(key), pickle.dumps(value)) def get(self, key: Union[Key, str], default: any = None) -> any: """ Get a value from the user's settings. Returns the given default if not found, or None otherwise. """ return self.__store.value(UserSettings.__key_value(key), default) def get_from_json(self, key: Union[Key, str], default: any = None): """ Get a value from stored JSON. """ value = self.__store.value(UserSettings.__key_value(key), NOT_FOUND_VALUE) if value == NOT_FOUND_VALUE: return default else: return json.loads(value) def get_from_binary(self, key: Union[Key, str], default: any = None): """ Get a value from stored binary.""" value = self.__store.value(UserSettings.__key_value(key), NOT_FOUND_VALUE) if value == NOT_FOUND_VALUE: return default else: return pickle.loads(value) def save_widget(self, widget: QWidget, group: Union[Key, str]): """ Save a widget's state to the user's settings. """ save_widget(self.__store, widget, UserSettings.__key_value(group)) def restore_widget(self, widget: QWidget, group: Union[Key, str]): """ Restore a widget's state from a user's settings. """ restore_widget(self.__store, widget, UserSettings.__key_value(group)) def file_path(self) -> str: """ Get the file path for the user settings. """ return self.__store.fileName() @staticmethod def __key_value(key: Union[Key, str]): return key if isinstance(key, str) else key.value def clear(self): """ Remove all keys from settings. This is a simple way to ensure the settings file does not grow due to dynamic keys. """ for key in list(self.__store.allKeys()): self.__store.remove(key) def sync(self): """ Ensure the settings file is updated. """ self.__store.sync()
class PickleSettings: '''A utility to store and restore settings for use in testing. Be careful not to lose data.''' def __init__(self): ddiirr = os.path.dirname(__file__) os.chdir(os.path.realpath(ddiirr)) self.settings = QSettings('zero_substance', 'structjour') self.apisettings = QSettings('zero_substance/stockapi', 'structjour') self.chartsettings = QSettings('zero_substance/chart', 'structjour') self.setkeys = [] self.setvals = [] self.apisetkeys = [] self.apisetvals = [] self.name = os.path.join(ddiirr, 'pickleset.zst') # print(self.name) def setUp(self): ddiirr = os.path.dirname(__file__) os.chdir(os.path.realpath(ddiirr + '/../')) def tearDown(self): self.setUp() def initializeSettings(self): self.settings.clear() self.apisettings.clear() self.chartsettings.clear() def removePickle(self): if os.path.exists(self.name): os.remove(self.name) def initializeVars(self): self.setkeys = [] self.setvals = [] self.apisetkeys = [] self.apisetvals = [] self.chartkeys = [] self.chartvals = [] def storeSettings(self, replacePickle=False): if os.path.exists(self.name): if not replacePickle: return self.initializeVars() self.setkeys = self.settings.allKeys() for k in self.setkeys: self.setvals.append(self.settings.value(k)) self.apisetkeys = self.apisettings.allKeys() for k in self.apisetkeys: self.apisetvals.append(self.apisettings.value(k)) self.chartkeys = self.chartsettings.allKeys() for k in self.chartkeys: self.chartvals.append(self.chartsettings.value(k)) setsnkeys = [ self.setkeys, self.setvals, self.apisetkeys, self.apisetvals, self.chartkeys, self.chartvals ] with open(self.name, "wb") as f: '''Cannot pickle qsettings objects- so we pickle a list''' pickle.dump((setsnkeys), f) def restoreSettings(self): if os.path.exists(self.name): with open(self.name, "rb") as f: setsnkeys = pickle.load(f) for k, v in zip(setsnkeys[0], setsnkeys[1]): self.settings.setValue(k, v) for k2, v2 in zip(setsnkeys[2], setsnkeys[3]): self.apisettings.setValue(k2, v2) for k2, v2 in zip(setsnkeys[4], setsnkeys[5]): self.chartsettings.setValue(k2, v2) os.remove(self.name) else: print(f'No pickle found at {self.name}')
class Ui(QtWidgets.QMainWindow): def __init__(self): super(Ui, self).__init__() uic.loadUi('design/main.ui', self) met = QtGui.QFontMetrics(QtGui.QFont()) self.settings = QSettings('dataConfig', 'Tandots') print() #custom function import here self.GetConfig = DataFunctions.GetConfig(self.settings) #self.settings.clear() #Take all elements self.comboBoxServer = self.findChild(QtWidgets.QComboBox,"comboBoxServer") #box on now server self.pathMinecraft = self.findChild(QtWidgets.QLineEdit,"pathMinecraft") #path to mods self.pushButtonTakePath = self.findChild(QtWidgets.QPushButton,"pushButtonTakePath") #take path button self.pushButtonDownload = self.findChild(QtWidgets.QPushButton,"pushButtonDownload") #download button self.progressBar = self.findChild(QtWidgets.QProgressBar,"progressBar") #download_mod progressBar self.labelCountMods = self.findChild(QtWidgets.QLabel,"labelCountMods") #status / mods count label self.labelPathInfo = self.findChild(QtWidgets.QLabel,"labelPathInfo") #status path self.comboBoxServer.currentTextChanged.connect(self.takeServer) self.pathMinecraft.editingFinished.connect(self.saveNowPath) self.pushButtonTakePath.pressed.connect(self.takePath) self.pushButtonDownload.pressed.connect(self.downloadAll) for item in self.settings.allKeys(): self.comboBoxServer.addItem(item.upper()) #init event functionality self.nowServer = self.settings.value(self.comboBoxServer.currentText().lower()) self.check_path() self.path = None self.show() def check_path(self): path = self.pathMinecraft.text() if os.path.exists(path) and "minecraft" in path: if os.path.exists(path+"/mods"): self.saveNowPath() self.path = path self.labelPathInfo.setText("Path is OK!") else: self.labelPathInfo.setText("Not path mods!") self.path = None buttonReply = QMessageBox.question(self, 'Не нашли папку Mods...', "Не найдена папка mods, создать? По адресу:\n{}".format(path), QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if buttonReply == QMessageBox.Yes: self.labelPathInfo.setText("Path is OK!") self.saveNowPath() self.path = path os.mkdir(path+"/mods") else: self.labelPathInfo.setText("Not path mods!") self.path = None else: self.labelPathInfo.setText("Not correct path!") self.path = None def takeServer(self, text): self.nowServer = self.settings.value(text.lower()) if self.nowServer["path"]: self.pathMinecraft.setText(self.nowServer["path"]) else: self.pathMinecraft.clear() def saveNowPath(self): print(self.nowServer,self.pathMinecraft.text()) self.nowServer["path"] = self.pathMinecraft.text() self.settings.setValue(self.nowServer["name"],self.nowServer) def takePath(self): if os.path.exists(self.pathMinecraft.text()): temp_dir = QtWidgets.QFileDialog.getExistingDirectory(self, 'Open mods directory',self.pathMinecraft.text()) print("path", temp_dir) if len(temp_dir) > 2: self.pathMinecraft.setText(temp_dir) else: pass else: temp_dir = QtWidgets.QFileDialog.getExistingDirectory(self, 'Open mods directory', str(Path.home())) print("path",temp_dir) if len(temp_dir)>2: self.pathMinecraft.setText(temp_dir) else: pass self.nowServer["path"] = self.pathMinecraft.text() self.settings.setValue(self.nowServer["name"], self.nowServer) self.check_path() def findByName(self,name, ListMods): #Костыль лять for mod in ListMods: if mod["filename"] == name: return mod else: return None def downloadAll(self): listModsToDownload = [] path = self.nowServer["path"] self.labelCountMods.setText("Скачивание конфигов") print(self.nowServer["git"],path) self.GetConfig.CloneGit(self.nowServer["git"],path+"/ZipClone.zip",self.progressBar) self.labelCountMods.setText("Скачивание модов") if self.nowServer["modList"]: OldServerMods = self.nowServer["modList"] else: OldServerMods = None NewServerMods = self.GetConfig.ListMods(path) if not(OldServerMods): self.nowServer["modList"] = NewServerMods self.DownloadWorkerMain(path, listModsToDownload) self.settings.setValue(self.nowServer["name"], self.nowServer) return for NewMod in NewServerMods: oldMod = self.findByName(NewMod["filename"],OldServerMods) if oldMod and oldMod.get("fileId"): if oldMod["fileId"] != NewMod["fileId"]: os.remove(path + "/mods/" + oldMod["filename"]) listModsToDownload.append(NewMod) else: print(oldMod) if oldMod["md5hash"] != NewMod["md5hash"]: os.remove(path + "/mods/" + oldMod["filename"]) listModsToDownload.append(NewMod) for OldMod in OldServerMods: NewMod = self.findByName(OldMod["filename"],NewServerMods) if not(NewMod): try: os.remove(path + "/mods/" + oldMod["filename"]) except: pass continue modfile = Path(path + "/mods/" + NewMod["filename"]) if not(modfile.exists()): listModsToDownload.append(NewMod) self.DownloadWorkerMain(path,listModsToDownload) self.nowServer["modList"] = NewServerMods self.settings.setValue(self.nowServer["name"], self.nowServer) def DownloadWorkerMain(self,path,listMods): self.labelCountMods.setText(f"Скачиваем моды: 0/{len(listMods)}") for i, mod in enumerate(listMods): print("downloadWorker", mod) self.labelCountMods.setText(f"Скачиваем моды: {i+1}/{len(listMods)}") self.GetConfig.DownloadMods(self.progressBar, path, mod) else: # QMessageBox.question(self, "Статус", "Все установленно!", QMessageBox.Ok) self.labelCountMods.setText("Устоновка завершена!")
class MainWindow(Ui_MainWindow, QMainWindow): def __init__(self): QMainWindow.__init__(self) Ui_MainWindow.setupUi(self, self) self.playlistDrop.dragEnterEvent = self.playlistDragEnterEvent self.playlistDrop.dropEvent = self.playlistDropEvent self.playlistModel = PlaylistModel() self.playlistTable.setModel(self.playlistModel) self.playlistTable.customContextMenuRequested.connect(self.playlistContextMenu) self.playlistTable.doubleClicked.connect(self.onPlaylistDoubleClick) self.playback = PlaybackWidget(self) self.playbackLayout.addWidget(self.playback) self.playback.playButton.clicked.connect(self.onPlaySelected) self.playback.nextButton.clicked.connect(self.onNextClicked) self.playback.prevButton.clicked.connect(self.onPrevClicked) self.libraryDock.setTitleBarWidget(QWidget()) self.playlistsDock.setTitleBarWidget(QWidget()) self.toggleLibraryButton.clicked.connect(self.onToggleLibrary) self.togglePlaylistsButton.clicked.connect(self.onTogglePlaylists) self.library = LibraryWidget(self) self.libraryDock.setWidget(self.library) self.libraryDock.hide() self.library.itemsActivated.connect(self.onLibraryItemActivated) self.playlists = PlaylistsWidget(self) self.playlistsDock.setWidget(self.playlists) self.playlistsDock.hide() self.playlists.loadPlaylist.connect(self.onPlaylistLoad) self.dockState = 0 self.settings = QSettings('txplaya', 'txplaya') if u'geometry/main' in self.settings.allKeys(): self.setGeometry(self.settings.value(u'geometry/main')) for col in range(self.playlistModel.columnCount()): width = self.settings.value(u'geometry/playlist/col/%d' % col) self.playlistTable.setColumnWidth(col, int(width)) dockState = int(self.settings.value(u'geometry/dock/state')) self.dockShow(dockState) self.systemTray = QSystemTrayIcon(self.windowIcon()) self.systemTray.setToolTip('Playa') self.systemTray.show() self.systemTray.activated.connect(self.systemTrayToggle) systemTrayMenu = QMenu() systemTrayMenu.addAction(self.restore) systemTrayMenu.addAction(self.quit) self.systemTray.setContextMenu(systemTrayMenu) self.restore.triggered.connect(self.restoreWindow) self.quit.triggered.connect(self.quitEvent) self.quitButton.clicked.connect(self.quitEvent) self.quitFlag = False # keyboard shortcuts focusLibraryShortcut = QShortcut(QKeySequence('Ctrl+F'), self) focusLibraryShortcut.activated.connect(self.onFocusLibrary) deleteTrackShortcut = QShortcut(QKeySequence('Del'), self.playlistTable) deleteTrackShortcut.setContext(Qt.WidgetShortcut) deleteTrackShortcut.activated.connect(self.onDeleteTrack) togglePlaybackShortcut = QShortcut(QKeySequence('Space'), self) togglePlaybackShortcut.activated.connect(self.onTogglePlayback) startShortcut = QShortcut(QKeySequence(Qt.Key_Return), self.playlistTable) startShortcut.setContext(Qt.WidgetShortcut) startShortcut.activated.connect(self.onPlaySelected) undoShortcut = QShortcut(QKeySequence('Ctrl+Z'), self) undoShortcut.activated.connect(self.onPlaylistUndo) redoShortcut = QShortcut(QKeySequence('Ctrl+Shift+Z'), self) redoShortcut.activated.connect(self.onPlaylistRedo) saveShortcut = QShortcut(QKeySequence('Ctrl+S'), self) saveShortcut.activated.connect(self.onPlaylistSave) self.infoStreamStart() QTimer.singleShot(200, self.fetchLibrary) def infoStreamStart(self): self.infoStream = QInfoStream() self.infoStream.trackStarted.connect(self.playback.trackStarted) self.infoStream.trackStarted.connect(self.playlistModel.trackActivated) self.infoStream.playbackFinished.connect(self.playback.finished) self.infoStream.playbackFinished.connect(self.playlistModel.trackActivated) self.infoStream.playbackPaused.connect(self.playback.paused) self.infoStream.playlistChanged.connect(self.onPlaylistChanged) self.infoStream.disconnected.connect(self.reconnectDialog) self.infoStream.timerUpdated.connect(self.playback.timerUpdated) self.infoStream.playlistRegistryUpdated.connect(self.playlistRegistryUpdated) def fetchLibrary(self): from txplayagui.client import getLibrary onHttpResponse(getLibrary(), self.onLibraryLoaded) def playlistDragEnterEvent(self, event): self._playlistDragDropHandle(event, isDropped=False) def playlistDropEvent(self, event): self._playlistDragDropHandle(event, isDropped=True) def _playlistDragDropHandle(self, event, isDropped): from txplayagui.client import moveTrack, libraryInsert mimeData = event.mimeData() # get row rowPosition = event.pos().y() - self.playlistTable.rowHeight(0) rowTarget = self.playlistTable.rowAt(rowPosition) if rowTarget == -1: # new row rowTarget = self.playlistModel.rowCount() if mimeData.hasUrls(): urls = mimeData.urls() if len(urls) > 0: url = urls[0] if url.isLocalFile(): if not isDropped: event.acceptProposedAction() return # file dropped filepath = url.toLocalFile() from txplayagui.client import insert _ = insert(filepath, rowTarget) return # no urls or not local file if not mimeData.hasText(): return try: data = unwrapMime(mimeData) except ValueError: # invalid data passed return # check for proper flag source = data.get('source') if source not in ('playlist', 'library'): return if not isDropped: # drag entered event.acceptProposedAction() return if source == 'playlist': rowSource = data['row'] moveTrack(rowSource, rowTarget) elif source == 'library': hashes = [item['hash'] for item in data['items']] libraryInsert(hashes, position=rowTarget) def onLibraryLoaded(self, response): try: data = json.loads(response.data) self.library.rescanFinished(data['library']) if 'msg' in data: print data['msg'] except Exception, err: print 'Library load error:', repr(err)
class ini_setting: """ class for managing .ini file and project defaults """ release_mode = False def __init__(self, file_name, model): """ constructor: read setting values into a QSetting object Args: file_name: ini file name """ self.file_name = file_name self.model = model self.error_msg = "" self.groups_with_values = {} # all values read self.groups = {} # group names and key names self.config = None try: self.config = QSettings(QSettings.IniFormat, QSettings.UserScope, "EPA", self.model, None) if (not os.path.isfile(self.file_name) and file_name): from shutil import copyfile copyfile(self.config.fileName(), file_name) # self.create_ini_file(file_name) else: self.file_name = self.config.fileName() self.build_setting_map() print("Read project settings from " + self.file_name) except Exception as exINI: self.config = None self.error_msg = "Reading Error" + ":\n" + str(exINI) def create_ini_file(self, file_name): """ Specify .ini file path after instantiation if setting is not yet instantiated: a new setting is instantiated if the new setting has no key: a new ini file is created Args: file_name: the full path to an ini file Returns: True if successful; False if failed """ if os.path.isfile(self.file_name): return False if self.config is None: try: self.config = QSettings(file_name, QSettings.IniFormat) if len(self.config.allKeys()) == 0: # this is a brand new ini file self.config.setValue("Model/Name", self.model) self.config.sync() print("created ini file: " + file_name) else: print("Read settings from ini file: " + file_name) self.file_name = file_name return True except Exception as exINI: self.config = None self.error_msg = "Reading Error" + ":\n" + str(exINI) return False def get_setting_value(self, group, key): """ Get the value of a ini setting, assuming all settings are grouped Args: group: the string name of a group or section key: the string name of a key Returns: a list of two elements, first being the value, second being the value type """ rval = [None, None] if len(self.groups) == 0: return rval if not group in self.groups: return rval self.config.beginGroup(group) qvar = self.config.value(key) if qvar is None: self.config.endGroup() return rval str_val = str(qvar) if len(str_val) > 0: tval, tval_is_good = ParseData.intTryParse(str_val) if tval_is_good: rval[0] = tval rval[1] = "integer" self.config.endGroup() return rval tval, tval_is_good = ParseData.floatTryParse(str_val) if tval_is_good: rval[0] = tval rval[1] = "float" self.config.endGroup() return rval rval[0] = str_val rval[1] = "string" self.config.endGroup() return rval elif str_val == "": rval[0] = "" rval[1] = "string" else: str_list = qvar.toStringList().join(",") if len(str_list) > 0: rval[0] = str_list.strip(",").split(",") rval[1] = "stringlist" self.config.endGroup() return rval self.config.endGroup() return rval def build_setting_map(self): """ Build a setting group-key-value mapping dictionary as below: self.groups_with_values [group_name] -> [key_name] -> [value, value_type] Also create group dictionary keyed on group name, pointing to its list of keys so we can get setting values on a as needed basis self.groups [group_name] -> [key names] """ self.groups.clear() self.groups_with_values.clear() for group in self.config.childGroups(): self.config.beginGroup(group) self.groups_with_values[group] = {} self.groups[group] = [] for key in self.config.childKeys(): self.groups[group].append(key) val, vtype = self.get_setting_value(group, key) self.groups_with_values[group][key] = val # print group + "::" + key + "::" + self.config.value(key).toString() self.config.endGroup() def read_ini_file_cp(self): self.config.read(self.file_name) for section in self.config.sections(): dict1 = self.config_section_map(section) pass pass def config_section_map(self, section): dict1 = {} for option in self.config.options(section): try: dict1[option] = self.config.get(section, option) if dict1[option] == -1: print ("skip: %s" % option) pass except: print ("exception on %s!" % option) dict1[option] = None return dict1
class GCodeGenerator(QMainWindow): def __init__(self): super(GCodeGenerator, self).__init__() self.settings = QSettings("GCodeGenerator", "GcodeConfig") self.settings.setDefaultFormat(QSettings.IniFormat) self.materialFile = "millingparameters.json" self.load_ui() self.init_Material() if len(self.settings.allKeys()) > 0: self.init_settings() self.toolBoxObj = None self.gcValues = { 'mm': 'G21', 'inch': 'G20', 'trcr': 'G42', #Tool Radius Compensation Right 'trcl': 'G41', #Tool Radius Compensation Left 'trc': 'G40', #Tool Radius Compensation on (disables G41/G42) } self.window.toolBox.setCurrentIndex(0) self.window.toolBox.currentChanged.connect(self.onTabBarClicked) tbIdx = self.window.toolBox.currentIndex() self.window.toolBox.currentChanged.emit(tbIdx) self.gcodeWidget = GcodeWindow(self) self.commonGcode = CommonGcode(self) self.window.pb_gCode.clicked.connect(self.onGCodeClicked) self.window.toolBox_Pocket.currentChanged.connect( self.onPocketToolChanged) self.window.toolBox_Pocket.currentChanged.emit(0) def load_ui(self): #loader = QUiLoader() path = os.path.join(os.path.dirname(__file__), "form.ui") ui_file = QFile(path) ui_file.open(QFile.ReadOnly) #self.window = loader.load(ui_file, self) self.window = uic.loadUi(ui_file) ui_file.close() self.window.actionGCode_Pre_Post.triggered.connect( self.onActionGCode_Pre_Post) self.window.actionMaterial.triggered.connect(self.onActionMaterial) self.window.actionMachine_Params.triggered.connect( self.onActionMachineParams) def write_settings(self): boolean = {True: 1, False: 0} self.settings.setValue("Preamble", self.window.preamble.text()) self.settings.setValue("PostGcode", self.window.postGcode.text()) self.settings.setValue("Material", self.window.cbMaterial.currentIndex()) self.settings.setValue("Materials", self.window.cbMaterials.currentIndex()) self.settings.setValue("ToolId", self.window.toolId.text()) self.settings.setValue("SpindleSpeed", self.window.spindleSpeed.text()) self.settings.setValue("Direction_CCW", boolean[self.window.dirCCW.isChecked()]) self.settings.setValue("Direction_CW", boolean[self.window.dirCW.isChecked()]) self.settings.setValue("Unit_mm", boolean[self.window.unitMm.isChecked()]) self.settings.setValue("Unit_inch", boolean[self.window.unitInch.isChecked()]) self.settings.setValue( "ViewGcode", boolean[self.window.actionGCode_Pre_Post.isChecked()]) self.settings.setValue("ViewMaterial", boolean[self.window.actionMaterial.isChecked()]) self.settings.setValue( "ViewParams", boolean[self.window.actionMachine_Params.isChecked()]) self.settings.setValue("Speed_XY", self.window.speedXY.text()) self.settings.setValue("Speed_Z", self.window.speedZ.text()) self.settings.setValue("ToolDiameter", self.window.toolDiameter.text()) self.settings.setValue("StartZ", self.window.startZ.text()) self.settings.setValue("SafeZ", self.window.zSafe.text()) self.settings.setValue("Speed_G2G3", self.window.speedG2G3.text()) self.settings.setValue("Speed_Zg1", self.window.speedZg1.text()) self.settings.setValue("Center_X", self.window.centerX.text()) self.settings.setValue("Center_Y", self.window.centerY.text()) self.settings.setValue("DepthTotal", self.window.depthTotal.text()) self.settings.setValue("DepthStep", self.window.depthStep.text()) def init_settings(self): #print(self.settings.fileName()) #print(len(self.settings.allKeys())) self.window.actionGCode_Pre_Post.setChecked( bool(int(self.settings.value("ViewGcode")))) self.window.actionGCode_Pre_Post.triggered.emit() self.window.actionMaterial.setChecked( bool(int(self.settings.value("ViewMaterial")))) self.window.actionMaterial.triggered.emit() self.window.actionMachine_Params.setChecked( bool(int(self.settings.value("ViewParams")))) self.window.actionMachine_Params.triggered.emit() self.window.preamble.setText(self.settings.value("Preamble")) self.window.postGcode.setText(self.settings.value("PostGcode")) self.window.cbMaterial.setCurrentIndex( int(self.settings.value("Material"))) self.window.cbMaterials.setCurrentIndex( int(self.settings.value("Materials"))) self.window.toolId.setText(self.settings.value("ToolId")) self.window.spindleSpeed.setText(self.settings.value("SpindleSpeed")) self.window.dirCCW.setChecked( bool(int(self.settings.value("Direction_CCW")))) self.window.dirCW.setChecked( bool(int(self.settings.value("Direction_CW")))) self.window.unitMm.setChecked(bool(int( self.settings.value("Unit_mm")))) self.window.unitInch.setChecked( bool(int(self.settings.value("Unit_inch")))) self.window.speedXY.setText(self.settings.value("Speed_XY")) self.window.speedZ.setText(self.settings.value("Speed_Z")) self.window.toolDiameter.setText(self.settings.value("ToolDiameter")) self.window.startZ.setText(self.settings.value("StartZ")) self.window.zSafe.setText(self.settings.value("SafeZ")) self.window.speedG2G3.setText(self.settings.value("Speed_G2G3")) self.window.speedZg1.setText(self.settings.value("Speed_Zg1")) self.window.centerX.setText(self.settings.value("Center_X")) self.window.centerY.setText(self.settings.value("Center_Y")) self.window.depthTotal.setText(self.settings.value("DepthTotal")) self.window.depthStep.setText(self.settings.value("DepthStep")) def init_Material(self): with open(self.materialFile, "r") as read_file: self.dicMaterials = json.load(read_file) for (cat, v) in self.dicMaterials.items(): self.window.cbMaterial.addItem(cat) self.window.cbMaterial.currentIndexChanged.connect( self.onMaterialChanged) self.window.cbMaterials.currentIndexChanged.connect( self.onMaterialsChanged) matIdx = self.window.cbMaterial.currentIndex() self.window.cbMaterial.currentIndexChanged.emit(matIdx) def onActionGCode_Pre_Post(self): if self.window.actionGCode_Pre_Post.isChecked(): self.window.frame_Gcode.show() else: self.window.frame_Gcode.hide() def onActionMaterial(self): if self.window.actionMaterial.isChecked(): self.window.frame_Material.show() else: self.window.frame_Material.hide() def onActionMachineParams(self): if self.window.actionMachine_Params.isChecked(): self.window.groupBoxDirection.show() else: self.window.groupBoxDirection.hide() #Slot int def onTabBarClicked(self, idx): self.toolBox = None if idx == 0: from ContourArc import ContourArc contourArc = ContourArc(self) self.toolBoxObj = contourArc elif idx == 1: from ContourRoundRect import ContourRoundRectangle contourRRect = ContourRoundRectangle(self) self.toolBoxObj = contourRRect def onPocketToolChanged(self, idx): if idx == 0: from PocketCircle import PocketCircle pocketCircle = PocketCircle(self) self.toolBoxObj = pocketCircle def onMaterialChanged(self, idx): material = self.window.cbMaterial.currentText() #print(material) with open(self.materialFile, "r") as read_file: self.dicMaterials = json.load(read_file) self.window.cbMaterials.clear() for item in self.dicMaterials[material]: self.window.cbMaterials.addItem(item["Material"]) #print(item["Material"]) def onMaterialsChanged(self, idx): material = self.window.cbMaterial.currentText() materials = self.window.cbMaterials.currentText() #print(material, " ",materials) for item in self.dicMaterials[material]: if item["Material"] == materials: self.window.toolId.setText(str(item["ToolID"])) self.window.spindleSpeed.setText(str(item["Spindel-RPM"])) def onGCodeClicked(self): self.gcodeWidget.dialog.gcodeText.clear() self.gcodeWidget.dialog.gcodeText.appendPlainText( self.commonGcode.getGCode(self)) self.gcodeWidget.show()
class Backup: ''' A utility to store and restore settings for use in testing. Be careful not to lose data. ''' setname = 'settings.zst' def __init__(self, backuploc=None, theDate=None): ''' Store the directory settings in self. The initial strings for the DB are in settings. If initialize is called, they are gone. Likeise, restoration will depend on reinitializing settings ''' self.settings = QSettings('zero_substance', 'structjour') self.apisettings = QSettings('zero_substance/stockapi', 'structjour') self.chartsettings = QSettings('zero_substance/chart', 'structjour') if backuploc is None: if not os.path.exists(self.settings.value('journal')): msg = f"Journal location {self.settings.value('journal')} does not exist" logging.error(msg) raise ValueError(msg) self.rootdir = os.path.normpath( os.path.join(self.settings.value('journal'), 'backup')) else: self.rootdir = backuploc d = pd.Timestamp( theDate) if theDate is not None else pd.Timestamp.now() self.bdir = os.path.join(self.rootdir, d.strftime("backup_%Y%m%d_%H.%M.%S")) self.bu_settings = os.path.join(self.bdir, self.setname) self.dbtrade = self.settings.value('tradeDb') self.dbstructjour = self.settings.value('structjourDb') self.setkeys = [] self.setvals = [] self.apisetkeys = [] self.apisetvals = [] # print(self.bu_settings) def initializeSettings(self): ''' Remove all settings except zero_substance/structjour/journal ''' for key in self.settings.allKeys(): if key != 'journal': self.settings.remove(key) self.apisettings.clear() self.chartsettings.clear() self.settings.sync() self.apisettings.sync() self.chartsettings.sync() def createDir(self): try: if not os.path.exists(self.rootdir): os.mkdir(self.rootdir) if not os.path.exists(self.bdir): os.mkdir(self.bdir) except Exception as ex: logging.error(ex) logging.error('Failed to create backup directory. ' + str(ex)) raise ValueError(ex) pass def removePickle(self): if os.path.exists(self.bu_settings): os.remove(self.bu_settings) def initializeVars(self): self.setkeys = [] self.setvals = [] self.apisetkeys = [] self.apisetvals = [] self.chartkeys = [] self.chartvals = [] def backupDatabase(self, theDir=None): ''' Helper method for backup. If either db file is not found, change the backup dir name to include 'FAILED'. That will prevent a bad restore and retain files and settings in the directory ''' self.bdir = self.bdir if theDir is None else theDir if not os.path.exists(self.bdir): raise ValueError(f'Backup directory {self.bdir} does not exist') dbtrade2 = os.path.split(self.dbtrade)[1] dbstructjour2 = os.path.split(self.dbstructjour)[1] dbtrade2 = os.path.normpath(os.path.join(self.bdir, dbtrade2)) dbstructjour2 = os.path.normpath(os.path.join(self.bdir, dbstructjour2)) try: copyfile(self.dbtrade, dbtrade2) except FileNotFoundError: logging.error( f'Trade database does not exist at {self.dbtrade} and cannot be copied' ) changebdir = self.bdir[0:-17] + "FAILED_" + self.bdir[-17:] os.rename(self.bdir, changebdir) self.bdir = changebdir dbstructjour2 = os.path.normpath( os.path.join(self.bdir, os.path.split(dbstructjour2)[1])) else: logging.info(f'Trade database has been backed up to {dbtrade2}') if dbtrade2 != dbstructjour2: logging.info(f'Trade database has been backed up to {dbtrade2}') try: copyfile(self.dbstructjour, dbstructjour2) except FileNotFoundError: logging.error( f'Structjour database does not exist at {self.dbstructjour} and cannot be copied' ) if self.bdir.find('FAILED_') == -1: changedir = self.bdir[0:-17] + "FAILED_" + self.bdir[-17:] os.rename(self.bdir, changedir) else: logging.info( f'Structjour database has been backed up to {dbstructjour2}' ) def restoreDatabase(self, theDir=None): self.bdir = self.bdir if theDir is None else theDir if not os.path.exists(self.bdir): raise ValueError(f'Backup directory {self.bdir} does not exist.') dbtrade = self.settings.value('tradeDb') dbstructjour = self.settings.value('structjourDb') dbt = os.path.join(self.bdir, os.path.split(dbtrade)[1]) dbs = os.path.join(self.bdir, os.path.split(dbstructjour)[1]) if os.path.exists(dbt): copyfile(dbt, dbtrade) logging.info(f'Db restored {dbt}') else: logging.error(f'Backup file {dbt} does not exist.') if dbs != dbt: if os.path.exists(dbs): copyfile(dbs, dbstructjour) logging.info(f'Db restored {dbs}') else: logging.error(f'Backup file {dbt} does not exist.') def storeSettings(self, replacePickle=False): self.createDir() if os.path.exists(self.bu_settings): if not replacePickle: return self.initializeVars() self.setkeys = self.settings.allKeys() for k in self.setkeys: self.setvals.append(self.settings.value(k)) self.apisetkeys = self.apisettings.allKeys() for k in self.apisetkeys: self.apisetvals.append(self.apisettings.value(k)) self.chartkeys = self.chartsettings.allKeys() for k in self.chartkeys: self.chartvals.append(self.chartsettings.value(k)) setsnkeys = [ self.setkeys, self.setvals, self.apisetkeys, self.apisetvals, self.chartkeys, self.chartvals ] with open(self.bu_settings, "wb") as f: '''Cannot pickle qsettings objects- so we pickle a list''' pickle.dump((setsnkeys), f) logging.info( f'Settings have been backed up to file {self.bu_settings}') def restoreSettings(self, theDir=None): theDir = self.mostRecent() if theDir is None else theDir bu_settings = os.path.join(theDir, self.setname) if os.path.exists(bu_settings): with open(bu_settings, "rb") as f: setsnkeys = pickle.load(f) for k, v in zip(setsnkeys[0], setsnkeys[1]): self.settings.setValue(k, v) for k2, v2 in zip(setsnkeys[2], setsnkeys[3]): self.apisettings.setValue(k2, v2) for k2, v2 in zip(setsnkeys[4], setsnkeys[5]): self.chartsettings.setValue(k2, v2) logging.info(f'Settings backed up to file {bu_settings}') else: logging.error(f'No settings backup found at {bu_settings}') def backup(self): self.storeSettings() self.backupDatabase() def restore(self, theDir=None): self.bdir = self.mostRecent() if theDir is None else theDir self.bdir = os.path.normpath(self.bdir) if not os.path.exists(self.bdir): raise ValueError(f'Backup directory {self.bdir} does not exist') self.restoreSettings(self.bdir) self.restoreDatabase(self.bdir) def mostRecent(self): thedirs = os.listdir(self.rootdir) maxdate = '' maxdir = None for thedir in thedirs: if thedir.startswith('backup_2'): d = thedir[7:].replace('.', ':') if d > maxdate: maxdir = thedir return os.path.join(self.rootdir, maxdir) if maxdir is not None else '' def _clearJournalDir(self): '''For Testing ONLY. TODO implement a seperate backup/restore for this one string''' # jdir = self.settings('journal') self.settings.remove('journal') def _restoreJournalDir(self): '''For Testing''' pass
class Addon(clickpoints.Addon): signal_update_plot = QtCore.Signal() signal_plot_finished = QtCore.Signal() net1_db_name = "segmentation 1" net1_db_color = "#0a2eff" # TODO maye choose better colors net2_db_name = "segmentation 2" net2_db_color = "#Fa2eff" overlap_mask = "overlapp" overlap_mask_color = "#fff014" def __init__(self, *args, **kwargs): clickpoints.Addon.__init__(self, *args, **kwargs) # database setup ''' if not all(["ROI" in m.name for m in self.db.getMaskTypes()]): choice = QtWidgets.QMessageBox.question(self, 'continue', "All exisiting masks will be deleted", QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No) if choice == QtWidgets.QMessageBox.No: return else: setup_masks(self.db) self.cp.reloadMaskTypes() self.cp.reloadMaskTypes() ''' self.exp_db = None self.exp_db_mask = None self.export_db_path = "/home/user/Desktop/2020_Deformation_Cytometer/network_problems/network_problems.cdb" self.export_db_path_mask = "/home/user/Desktop/2020_Deformation_Cytometer/network_problems_illustration2/network_problems_mask.cdb" #self.setup_additonal_databases_wrapper(db_name=self.export_db_path, db_name_illustration=self.export_db_path_mask) self.current_positions = [] self.curr_pos_index = 0 self.set_probability_map = True # QThread Worker, that is not running yet self.thread = Worker(self, run_function=None) self.thread.started.connect(self.switch_predict_all_text) self.thread.finished.connect(self.switch_predict_all_text) self.stop = False # TODO load this from config // at least try to self.magnification = 40 self.coupler = 0.5 self.pixel_size_camera = 6.9 self.pixel_size = self.pixel_size_camera/(self.magnification * self.coupler) self.pixel_size *= 1e-6 #conversion to meter self.r_min = 2 # in µm self.edge_dist = 15 # in µm self.channel_width = 0 self.solidity_threshold = 0.96 self.irregularity_threshold = 1.06 self.note_filtered = True # write irregularity and solidtiy down for cells that would have been filtered out by these thresholds self.db.deleteMaskTypes() self.mt1 = self.db.setMaskType(name=self.net1_db_name, color=self.net1_db_color, index=1) self.mt2 = self.db.setMaskType(name=self.net2_db_name, color=self.net2_db_color, index=2) self.mt_ov = self.db.setMaskType(name=self.overlap_mask, color=self.overlap_mask_color, index=3) self.elt1 = self.db.setMarkerType(name=self.net1_db_name, color=self.net1_db_color, mode=clickpoints.DataFile.TYPE_Ellipse) self.elt2 = self.db.setMarkerType(name=self.net2_db_name, color=self.net2_db_color, mode=clickpoints.DataFile.TYPE_Ellipse) self.cp.reloadMaskTypes() self.cp.reloadTypes() self.cp.save() self.folder = os.getcwd() self.file1 = "" self.file2 = "" self.settings = QSettings("clickpoints_segmentation_evaluation", "clickpoints_segmentation_evaluation") if "file1" in self.settings.allKeys(): self.file1 = self.settings.value("file1") if "file2" in self.settings.allKeys(): self.file2 = self.settings.value("file2") self.Segmentation1 = None self.Segmentation2 = None """ GUI Widgets""" self.setWindowTitle("DeformationCytometer - ClickPoints") # layouts self.layout = QtWidgets.QVBoxLayout(self) self.setMinimumWidth(400) self.setMinimumHeight(200) self.layout.setSpacing(20) self.layout.setContentsMargins(10, 20, 10, 20) self.layout_find_files1 = SetFile(self.file1) self.layout_find_files1.fileSeleted.connect(partial(self.files_selected, obj=[1])) self.layout_find_files1.line_edit_folder.textEdited.connect(partial(self.files_selected, obj=[1], from_field=True)) self.layout_find_files2 = SetFile(self.file2) self.layout_find_files2.fileSeleted.connect(partial(self.files_selected, obj=[2])) self.layout_find_files2.line_edit_folder.textEdited.connect(partial(self.files_selected, obj=[2], from_field=True)) self.layout_evaluate = QtWidgets.QHBoxLayout() # trying to load the Segmentation functions right now self.files_selected(obj=[1,2]) # path to export db self.layout_export_1 = QtWidgets.QHBoxLayout() self.line_edit_export = QtWidgets.QLineEdit(self.export_db_path) # note: editing finshed is emit when you pressed enter self.line_edit_export.editingFinished.connect(partial(self.setup_additonal_databases_wrapper, db_name="auto")) self.layout_export_1.addWidget(self.line_edit_export, stretch=4) self.export_button = QtWidgets.QPushButton("export") self.export_button.clicked.connect(partial(self.export, filename=self.export_db_path, illustration=False)) self.layout_export_1.addWidget(self.export_button, stretch=2) ''' # the selected files self.scroll = QtWidgets.QScrollArea() self.add_file() ''' # accept and decline buttons plus counters self.accept_layout = QtWidgets.QVBoxLayout() self.accept_button = QtWidgets.QPushButton("error network 1") self.accept_counter = QtWidgets.QLabel(str(0)) self.accept_button.clicked.connect(partial(self.decide_network, self.accept_counter, "error network 1")) self.accept_layout.addWidget(self.accept_button,stretch=1) self.accept_layout.addWidget(self.accept_counter,stretch=1) self.accept_layout.addStretch(stretch=3) self.layout_evaluate.addLayout(self.accept_layout) self.reject_layout = QtWidgets.QVBoxLayout() self.reject_button = QtWidgets.QPushButton("error network 2") self.reject_counter = QtWidgets.QLabel(str(0)) self.reject_button.clicked.connect(partial(self.decide_network,self.reject_counter, "error network 2")) self.reject_layout.addWidget(self.reject_button,stretch=1) self.reject_layout.addWidget(self.reject_counter,stretch=1) self.reject_layout.addStretch(stretch=3) self.layout_evaluate.addLayout(self.reject_layout) self.next_layout = QtWidgets.QVBoxLayout() self.next_button = QtWidgets.QPushButton("next") self.next_button.clicked.connect(self.next_position) self.next_layout.addWidget(self.next_button) self.next_layout.addStretch() self.layout_evaluate.addLayout(self.next_layout) #self.skip_layout = QtWidgets.QVBoxLayout() #self.skip_button = QtWidgets.QPushButton("skip") #self.skip_button.clicked.connect(partial(self.decide_network, None, None)) #self.skip_layout.addWidget(self.skip_button) #self.skip_layout.addStretch() #self.layout_evaluate.addLayout(self.skip_layout) self.export_layout = QtWidgets.QVBoxLayout() self.export_mask_button = QtWidgets.QPushButton("export illustration") self.export_mask_button.clicked.connect(partial(self.export, filename=self.export_db_path_mask, illustration=True)) self.all_frames_button = QtWidgets.QPushButton("predict all frames") self.all_frames_button.clicked.connect(partial(self.start_thread, self.predict_all)) self.export_layout.addWidget(self.export_mask_button) self.export_layout.addWidget(self.all_frames_button) self.layout_evaluate.addLayout(self.export_layout) self.layout.addLayout(self.layout_find_files1) self.layout.addLayout(self.layout_find_files2) self.layout.addLayout(self.layout_export_1) self.layout.addLayout(self.layout_evaluate) #self.layout.addLayout(self.layout_layers) self.show() #TODO do I really need this?? def setup_additonal_databases_wrapper(self, db_name=None, db_name_illustration=None): if db_name == "auto": db_name = self.line_edit_export.text() if not db_name is None: if db_name.endswith(".cdb"): print("writing to " + db_name) if self.exp_db is not None: self.exp_db.db.close() self.notes_txt.close() self.exp_db, self.notes_txt = set_up_additional_databases(self, db_name) else: print("invalid path: " + db_name) if not db_name_illustration is None: print("writing to " + db_name_illustration) if self.exp_db_mask is not None: self.exp_db_mask.db.close() self.notes_txt_mask.close() self.exp_db_mask, self.notes_txt_mask = set_up_additional_databases(self, db_name_illustration, illustration=True) def files_selected(self, obj=[0], from_field=False): if from_field: self.file1 = self.layout_find_files1.line_edit_folder.text() self.file2 = self.layout_find_files2.line_edit_folder.text() else: self.file1 = self.layout_find_files1.files self.file2 = self.layout_find_files2.files try: frame = self.cp.getCurrentFrame() except AttributeError: frame = 0 img_shape = self.db.getImage(frame=frame).getShape() if 1 in obj and not self.file1 in [""," "]: self.file1 = self.layout_find_files1.files self.settings.setValue("file1", self.file1) if self.file1.endswith(".cdb"): self.Seg1 = FromOtherDB(db_path=self.file1) else: self.Segmentation1 = self.import_seg_function(self.file1) if not self.Segmentation1 is None: try: self.Seg1 = self.Segmentation1( img_shape=img_shape, pixel_size=self.pixel_size, r_min=self.r_min, frame_data=None, edge_dist=self.edge_dist, channel_width=self.channel_width) print("succesfully loaded %s"%self.file1) except OSError as e: print(e) if 2 in obj and not self.file2 in [""," "]: self.file2 = self.layout_find_files2.files self.settings.setValue("file2", self.file2) if self.file2.endswith(".cdb"): self.Seg2 = FromOtherDB(db_path=self.file2) else: self.Segmentation2 = self.import_seg_function(self.file2) if not self.Segmentation2 is None: try: self.Seg2 = self.Segmentation2( img_shape=img_shape, pixel_size=self.pixel_size, r_min=self.r_min, frame_data=None, edge_dist=self.edge_dist, channel_width=self.channel_width) print("succesfully loaded %s"%self.file2) except OSError as e: print(e) if 1 in obj and self.file1 in [""," "]: self.Seg1 = None if 2 in obj and self.file2 in [""," "]: self.Seg2 = None self.settings.sync() def decide_network(self, counter, text): if len(self.current_positions) > 0 and not counter is None: ellipse = self.find_closest_ellipse(self.current_positions[self.curr_pos_index]) ellipse.text = text ellipse.save() self.cp.reloadMarker(self.cp.getCurrentFrame()) counter.setText(str(int(counter.text()) + 1)) #self.next_position() else: #self.next_position() pass def find_closest_ellipse(self, pos): frame = self.cp.getCurrentFrame() all_ellipses = self.db.getEllipses(frame=frame) dists = [np.sqrt((pos[0] - e.y) ** 2 + (pos[1] - e.x) ** 2) for e in all_ellipses] min_ellipse = all_ellipses[np.argmin(dists)] return min_ellipse def next_frame(self): self.predict(frame=self.cp.getCurrentFrame() + 1) self.cp.jumpFramesWait(1) print(self.cp.getCurrentFrame()) self.curr_pos_index = 0 def next_position(self): if len(self.current_positions) <= self.curr_pos_index + 1: self.next_frame() while len(self.current_positions) == 0: self.next_frame() self.cp.centerOn(self.current_positions[self.curr_pos_index][1], self.current_positions[self.curr_pos_index][0]) else: self.curr_pos_index +=1 self.cp.centerOn(self.current_positions[self.curr_pos_index][1], self.current_positions[self.curr_pos_index][0]) def previous_position(self): if self.curr_pos_index > 0: self.curr_pos_index -=1 self.cp.centerOn(self.current_positions[self.curr_pos_index][1], self.current_positions[self.curr_pos_index][0]) def predict_all(self): self.stop = False curr_frame = self.cp.getCurrentFrame() total_frames =self.db.getImageCount() for f in tqdm(range(curr_frame, total_frames,1)): if self.stop: break self.predict(f) def export(self, filename="", illustration=False): if not os.path.exists(filename): set_up_additional_databases(self, filename, illustration=illustration) folder = os.path.split(filename)[0] frame = self.cp.getCurrentFrame() db_im = self.db.getImage(frame=frame) name = "frame" + str(frame) + "_" + os.path.split(db_im.filename)[1] data = db_im.data im = Image.fromarray(data) im.save(os.path.join(folder, name)) if illustration: self.notes_txt_mask.write(filename + "\t" + name + "\n") self.save_to_other_db(self.exp_db_mask, frame, name, save_mask=illustration) else: self.notes_txt.write(filename + "\t" + name + "\n") self.save_to_other_db(self.exp_db, frame, name) def save_to_other_db(self, db, frame, fname, save_mask=0): try: s_id = db.getImageCount() except TypeError: s_id = 0 try: im = db.setImage(sort_index=s_id, filename=fname,path=1) if save_mask: try: mask_data = self.db.getMask(frame=frame).data db.setMask(frame=s_id, data=mask_data) except AttributeError: pass for ellipse in self.db.getEllipses(frame=frame): db.setEllipse(type=ellipse.type.name, image=im, x=ellipse.x, y=ellipse.y, width=ellipse.width, height=ellipse.height, angle=ellipse.angle) except Exception as e: print(e) def keyPressEvent(self, event): # error network 1 if event.key() == QtCore.Qt.Key_1: self.decide_network(self.accept_counter, "error network 1") # error network 1 if event.key() == QtCore.Qt.Key_2: self.decide_network(self.reject_counter, "error network 2") # go to next position: if event.key() == QtCore.Qt.Key_3: self.next_position() # go to previous position: if event.key() == QtCore.Qt.Key_4: self.next_position() # export to improve network if event.key() == QtCore.Qt.Key_E: self.export(filename=self.export_db_path, illustration=False) # export to illustrate errors if event.key() == QtCore.Qt.Key_U: self.export(filename=self.export_db_path_mask, illustration=True) def import_seg_function(self,path): try: imp = importlib.util.spec_from_file_location("module.name", path) module = importlib.util.module_from_spec(imp) imp.loader.exec_module(module) return module.Segmentation except Exception as e: print("import failed") print(e) return None def predict(self, frame): prob_map1 = None prob_map2 = None pred_mask1 = None pred_mask2 = None ellipses1 = [] ellipses2 = [] # loading the image db_im = self.db.getImage(frame=frame) self.db.deleteEllipses(frame=frame,type="segmentation 1") self.db.deleteEllipses(frame=frame,type="segmentation 2") image = db_im.data # making the predicition if self.Seg1 is None: res1 = None elif isinstance(self.Seg1, FromOtherDB): res1 = self.Seg1.getMaskEllipse(frame) else: res1 = self.Seg1.segmentation(image) if self.Seg2 is None: res2 = None elif isinstance(self.Seg2, FromOtherDB): res2 = self.Seg2.getMaskEllipse(frame) else: res2 = self.Seg2.segmentation(image) if not res1 is None: if len(res1) == 2: pred_mask1, ellipses1 = res1 else: pred_mask1, ellipses1, prob_map1 = res1 else: pred_mask1 = np.zeros(image.shape) if not res2 is None: if len(res2) == 2: pred_mask2, ellipses2 = res2 else: pred_mask2, ellipses2, prob_map2 = res2 else: pred_mask2 = np.zeros(image.shape) if self.set_probability_map: self.add_prob_map(prob_map1, frame, layer="segmentation 1") self.add_prob_map(prob_map2, frame, layer="segmentation 2") # writing prediction to database mask_data = pred_mask2.astype(np.uint8) * 2 mask_data += pred_mask1.astype(np.uint8) self.find_unique_objects( mask_data) self.db.setMask(frame=frame, data=mask_data) for el in ellipses1: self.set_ellipse(db_im, self.net1_db_name, el) for el in ellipses2: self.set_ellipse(db_im, self.net2_db_name, el) self.cp.reloadMarker(frame=frame) self.cp.reloadMask() def add_prob_map(self, prob_map, frame, layer=""): if not prob_map is None: folder = os.path.split(self.db._database_filename)[0] seg_id = int(layer[-1]) filename = os.path.join(folder, "%dprob_map%d.tiff"%(frame,seg_id)) Image.fromarray((prob_map * 255).astype(np.uint8)).save(filename) layers = [l.name for l in self.db.getLayers()] paths = [p.path for p in self.db.getPaths()] if folder not in paths: self.db.setPath(folder) path_obj = self.db.getPaths(path_string=folder)[0] if not layer in layers: new_layer = self.db.setLayer(layer, base_layer=layers[0]) try: self.db.setImage(filename=filename, sort_index=frame, layer=layer, path=path_obj) except IntegrityError: return def find_unique_objects(self, mask_pred): labeled = label(mask_pred > 0) # this merges overlapping areas and stuff self.current_positions = [r.centroid for r in regionprops(labeled) if r.area > 100] def set_ellipse(self, im, mtype, ellipse): pix_size = self.pixel_size*1e6 text = "irregularity: %s\nsolidity: %s"%(str(np.round(ellipse["irregularity"], 2)), str(np.round(ellipse["solidity"], 2))) filtered = ~((ellipse["solidity"] > 0.96) & (ellipse["irregularity"] < 1.06)) strain = (ellipse["long_axis"] - ellipse["short_axis"]) / np.sqrt(ellipse["long_axis"] * ellipse["short_axis"]) if filtered and self.note_filtered: el = self.db.setEllipse(image=im, type=mtype, x=ellipse["x_pos"], y=ellipse["y_pos"], width=0, height=0, angle=0, text=text) elif not filtered: text = "strain: %s\n"%np.round(strain,2) + text el = self.db.setEllipse(image=im, type=mtype, x=ellipse["x_pos"], y=ellipse["y_pos"], width=ellipse["long_axis"]/pix_size, height=ellipse["short_axis"]/pix_size, angle=ellipse["angle"], text=text) else: return #self.cp.centerOn(self.data.x[nearest_point], self.data.y[nearest_point]) # run in a separate thread to keep clickpoints gui responsive // now using QThread and stuff def switch_predict_all_text(self): if self.thread.isRunning(): self.all_frames_button.setText("stop") self.all_frames_button.clicked.connect(self.stop_thread) else: self.all_frames_button.setText("predict all frames") self.all_frames_button.clicked.connect(partial(self.start_thread, run_function=self.predict_all)) def stop_thread(self): self.stop = True self.thread.quit() def start_thread(self, run_function=None): self.thread.run_function = run_function self.thread.start() # starting thread
def main(): """" fgmk main routine When you use `python -m fgmk`, the main routine is called. If you use `pip install fgmk`, typing fgmk will also call this routine. The objective of this function is to: 1. load the Editor when called without args 2. if the arg is a map, and no additional args, load the Editor and open the map 3. seeing the current version by using `--version`, and not opening the Editor 4. being able to clean the settings in case a invalid setting is loaded somehow Additionally, I plan to enable expanding to being able to manipulate some files and also opening directly a sub editor - like the palette editor. """ environ["LIBOVERLAY_SCROLLBAR"] = "0" parser = argparse.ArgumentParser( prog=__title__, description=__title__ + ' is a 2d RPG game maker.', epilog=__copyright__ + ", " + __license__ + ".") parser.add_argument('-v', '--version', action='store_true', default=False, help='get software version.') parser.add_argument('-c', '--clean', action='store_true', default=False, help='cleans software settings.') parser.add_argument('-p', '--palette', action='store_true', default=False, help='loads exclusively the palette editor.') parser.add_argument('mapfile', nargs='?', default='check_no_map', help='a single .map.json file') args = parser.parse_args() if args.clean == True: settings = QSettings("FGMK", "fgmkEditor") for key in settings.allKeys(): settings.remove(key) #guarantee to eliminate all settings.sync() #writes to disk exit() if args.palette == True: a = QApplication([]) mw_arg = [] if 'mapfile' in args: mw_arg = [args.mapfile] m = palette_editor.main(palettefiles=mw_arg) a.processEvents() m.show() m.raise_() exit(a.exec_()) if args.version == True: print(__title__ + " v " + __version__) exit() a = QApplication([]) start = time() splash_pix = Editor.Icon() splash = QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint) splash.setMask(splash_pix.mask()) splash.show() while time() - start < 1: sleep(0.001) a.processEvents() mw_arg = [] if 'mapfile' in args: mw_arg = [args.mapfile] mw = Editor.MainWindow(mw_arg) a.processEvents() mw.show() splash.finish(mw) mw.raise_() mw.afterInit() exit(a.exec_())
class GreaseMonkeyJsObject(QObject): """ Class implementing the Python side for GreaseMonkey scripts. """ def __init__(self, parent=None): """ Constructor @param parent reference to the parent object @type QObject """ super(GreaseMonkeyJsObject, self).__init__(parent) self.__settings = None def setSettingsFile(self, name): """ Public method to set the settings file for the GreaseMonkey parameters. @param name name of the settings file @type str """ if self.__settings is not None: self.__settings.sync() self.__settings = None self.__settings = QSettings(name, QSettings.IniFormat) @pyqtSlot(str, str, str) def getValue(self, nspace, name, dValue): """ Public slot to get the value for the named variable for the identified script. @param nspace unique script id @type str @param name name of the variable @type str @param dValue default value @type str @return value for the named variable @rtype str """ vName = "GreaseMonkey-{0}/{1}".format(nspace, name) sValue = self.__settings.value(vName, dValue) if not sValue: return dValue return sValue @pyqtSlot(str, str, str) def setValue(self, nspace, name, value): """ Public slot to set the value for the named variable for the identified script. @param nspace unique script id @type str @param name name of the variable @type str @param value value to be set @type str @return flag indicating success @rtype bool """ vName = "GreaseMonkey-{0}/{1}".format(nspace, name) self.__settings.setValue(vName, value) self.__settings.sync() return True @pyqtSlot(str, str) def deleteValue(self, nspace, name): """ Public slot to set delete the named variable for the identified script. @param nspace unique script id @type str @param name name of the variable @type str @return flag indicating success @rtype bool """ vName = "GreaseMonkey-{0}/{1}".format(nspace, name) self.__settings.remove(vName) self.__settings.sync() return True @pyqtSlot(str) def listValues(self, nspace): """ Public slot to list the stored variables for the identified script. @param nspace unique script id @type str @return list of stored variables @rtype list of str """ nspaceName = "GreaseMonkey-{0}".format(nspace) self.__settings.beginGroup(nspaceName) keys = self.__settings.allKeys() self.__settings.endGroup() return keys @pyqtSlot(str) def setClipboard(self, text): """ Public slot to set some clipboard text. @param text text to be copied to the clipboard @type str """ QGuiApplication.clipboard().setText(text)
def __init__(self, gtomain, parent=None): super(GtoQgisSettingsDialog, self).__init__(parent) # gto self.gtomain = gtomain self.info = self.gtomain.info self.helper = self.gtomain.helper self.debug = self.gtomain.debug self.iface = self.gtomain.iface try: # references self.undoList = [] self.setWindowTitle('QGIS settings') self.setSizeGripEnabled(True) self.model = QStandardItemModel(self) self.model.setColumnCount(2) self.model.setHeaderData(0, Qt.Horizontal, "key") self.model.setHeaderData(1, Qt.Horizontal, "value") s = QSettings() for key in s.allKeys(): val = s.value(key) items = [] itKey = QStandardItem(key) itKey.setEditable(False) items.append(itKey) try: items.append(QStandardItem(val)) self.model.appendRow(items) except Exception as e: pass # if self.debug: self.info.err(e) self._proxy = MyFilter(self) self._proxy.setSourceModel(self.model) self.model.itemChanged.connect(self.dataChanged) # QstandardItem # create gui self.tableview = QTableView() self.tableview.horizontalHeader().setSectionResizeMode( QHeaderView.Stretch) self.tableview.horizontalHeader().setSectionsMovable(False) self.tableview.setSelectionBehavior( QAbstractItemView.SelectRows) # SelectItems self.tableview.setSelectionMode(QAbstractItemView.SingleSelection) self.tableview.setModel(self._proxy) self.search = QLineEdit() self.search.textChanged.connect(self.on_text_changed) self.btnDelete = QPushButton('Delete') self.btnDelete.clicked.connect(self.delete) self.btnAddRandowKey = QPushButton('add key') self.btnAddRandowKey.clicked.connect(self.addRandomKey) self.btnAddRandowKey.setHidden(not self.debug) # self.btnDelete.setEnabled(self.debug) self.btnUndo = QPushButton("Undo") self.btnUndo.setEnabled(False) self.btnUndo.clicked.connect(self.undo) self.btnCopy = QPushButton('Copy') self.btnCopy.clicked.connect(self.copy) self.chkPureJson = QCheckBox('Pure json') # layout search laySearch = QHBoxLayout() laySearch.addWidget(QLabel('Suche:')) laySearch.addWidget(self.search) # layout buttons layBtns = QHBoxLayout() layBtns.addWidget(self.btnAddRandowKey) layBtns.addWidget(self.btnDelete) layBtns.addWidget(self.btnUndo) hspacer = QSpacerItem(0, 0, QSizePolicy.Expanding, QSizePolicy.Minimum) layBtns.addItem(hspacer) layBtns.addWidget(self.btnCopy) layBtns.addWidget(self.chkPureJson) # layout dialog self.layout = QVBoxLayout(self.iface.mainWindow()) self.layout.addLayout(laySearch) self.layout.addWidget(self.tableview) self.layout.addLayout(layBtns) self.setLayout(self.layout) self.resize(640, 480) self.tableview.sortByColumn(0, Qt.AscendingOrder) self.tableview.setSortingEnabled(True) self.tableview.selectRow(0) except Exception as e: self.info.err(e)
class Datachecker: """QGIS Plugin Implementation.""" def __init__(self, iface): """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 """ # Save reference to the QGIS interface self.iface = iface # initialize plugin directory self.plugin_dir = os.path.dirname(__file__) # initialize locale locale = QSettings().value("locale/userLocale")[0:2] locale_path = os.path.join(self.plugin_dir, "i18n", "datachecker_{}.qm".format(locale)) # print(locale_path) if os.path.exists(locale_path): self.translator = QTranslator() self.translator.load(locale_path) if qVersion() > "4.3.3": QCoreApplication.installTranslator(self.translator) # Declare instance attributes self.actions = [] self.menu = self.tr(u"&Riooldatachecker") # TODO: We are going to let the user set this up in a future iteration self.toolbar = self.iface.addToolBar(u"Datachecker") self.toolbar.setObjectName(u"Datachecker") # print "** INITIALIZING Datachecker" self.pluginIsActive = False self.dockwidget = None # noinspection PyMethodMayBeStatic def tr(self, message): """Get the translation for a string using Qt translation API. We implement this ourselves since we do not inherit QObject. :param message: String for translation. :type message: str, QString :returns: Translated version of message. :rtype: QString """ # noinspection PyTypeChecker,PyArgumentList,PyCallByClass return QCoreApplication.translate("Datachecker", message) def add_action( self, icon_path, text, callback, enabled_flag=True, add_to_menu=True, add_to_toolbar=True, status_tip=None, whats_this=None, parent=None, ): """Add a toolbar icon to the toolbar. :param icon_path: Path to the icon for this action. Can be a resource path (e.g. ':/plugins/foo/bar.png') or a normal file system path. :type icon_path: str :param text: Text that should be shown in menu items for this action. :type text: str :param callback: Function to be called when the action is triggered. :type callback: function :param enabled_flag: A flag indicating if the action should be enabled by default. Defaults to True. :type enabled_flag: bool :param add_to_menu: Flag indicating whether the action should also be added to the menu. Defaults to True. :type add_to_menu: bool :param add_to_toolbar: Flag indicating whether the action should also be added to the toolbar. Defaults to True. :type add_to_toolbar: bool :param status_tip: Optional text to show in a popup when mouse pointer hovers over the action. :type status_tip: str :param parent: Parent widget for the new action. Defaults None. :type parent: QWidget :param whats_this: Optional text to show in the status bar when the mouse pointer hovers over the action. :returns: The action that was created. Note that the action is also added to self.actions list. :rtype: QAction """ icon = QIcon(icon_path) action = QAction(icon, text, parent) action.triggered.connect(callback) action.setEnabled(enabled_flag) if status_tip is not None: action.setStatusTip(status_tip) if whats_this is not None: action.setWhatsThis(whats_this) if add_to_toolbar: self.toolbar.addAction(action) if add_to_menu: self.iface.addPluginToMenu(self.menu, action) self.actions.append(action) return action def initGui(self): """Create the menu entries and toolbar icons inside the QGIS GUI.""" icon_path = ":/plugins/Datachecker/icon.png" self.add_action( icon_path, text=self.tr(u"Riooldatachecker"), callback=self.run, parent=self.iface.mainWindow(), ) # -------------------------------------------------------------------------- def onClosePlugin(self): """Cleanup necessary items here when plugin dockwidget is closed""" # print "** CLOSING Datachecker" # disconnects self.dockwidget.closingPlugin.disconnect(self.onClosePlugin) # remove this statement if dockwidget is to remain # for reuse if plugin is reopened # Commented next statement since it causes QGIS crashe # when closing the docked window: # self.dockwidget = None self.pluginIsActive = False def unload(self): """Removes the plugin menu item and icon from QGIS GUI.""" # print "** UNLOAD Datachecker" for action in self.actions: self.iface.removePluginMenu(self.tr(u"&Riooldatachecker"), action) self.iface.removeToolBarIcon(action) # remove the toolbar del self.toolbar # -------------------------------------------------------------------------- def pb_select_dc_folder(self): foldername = QFileDialog.getExistingDirectory() if foldername: self.dockwidget.folderNaam.setText(foldername) self.dockwidget.folderNaam.setToolTip(foldername) self.fill_checks_list() def fill_checks_list(self): self.dockwidget.listChecks.clear() foldername = self.dockwidget.folderNaam.text() geopackageList = [] for file in os.listdir(foldername): if file.endswith(".gpkg"): geopackageList.append(file) self.dockwidget.listChecks.addItems(geopackageList) def getConnectionDetails(self, value): type = value.split()[0] value = value.split()[1] if type == "Postgresql:": password = self.s_postgresql.value(value + "/password") username = self.s_postgresql.value(value + "/username") port = self.s_postgresql.value(value + "/port") host = self.s_postgresql.value(value + "/host") self.threedi_db_settings = { "threedi_dbname": value, "threedi_host": host, "threedi_user": username, "threedi_password": password, "threedi_port": port, "type": "Postgresql", } def get_databases(self): databases = [] self.s_postgresql = QSettings() self.s_postgresql.beginGroup("PostgreSQL/connections") all_pgsql_dbkeys = self.s_postgresql.allKeys() for key in all_pgsql_dbkeys: if not key.startswith('selected'): databases.append("Postgresql: " + key.split("/")[0]) databases = list(dict.fromkeys(databases)) return databases def laad_gpkg(self): fileName = self.dockwidget.listChecks.selectedItems() # dictionary with layer_names of gpkg and potential group name in QGIS group_mapping = { "chk.leiding": "leidingen", "chk.put": "putten", "chk.profiel": "profielen", 'chk.kunstwerken': 'kunstwerken', 'model.': 'brongegevens', } if len(fileName) > 0: root = QgsProject.instance().layerTreeRoot() for gpkg in fileName: foldername = self.dockwidget.folderNaam.text() file = os.path.join(foldername, gpkg.text()) conn = ogr.Open(file) for key, value in group_mapping.items(): group = root.addGroup(value) for layer in conn: if layer.GetName().split('_')[ 0] == key or layer.GetName().startswith(key): if layer.GetFeatureCount() > 0: combined = file + "|layername={}".format( layer.GetName()) vlayer = QgsVectorLayer( combined, layer.GetName(), "ogr") QgsProject.instance().addMapLayer( vlayer, False) group.addLayer(vlayer) root = QgsProject.instance().layerTreeRoot() for child in root.children(): if child.name() in group_mapping.values(): for child2 in child.children(): if isinstance(child2, QgsLayerTreeLayer): child2.setCustomProperty("showFeatureCount", True) self.laad_qml_styling('beheerder-std') self.dockwidget.stylingbox.setCurrentIndex(2) def pb_select_exp_folder(self): foldername = QFileDialog.getExistingDirectory() if foldername: self.dockwidget.folderNaam_export.setText(foldername) self.dockwidget.folderNaam_export.setToolTip(foldername) self.fill_export_list() def fill_export_list(self): self.dockwidget.listExport.clear() foldername = self.dockwidget.folderNaam_export.text() exportList = [] for file in os.listdir(foldername): if file.endswith(".shp"): exportList.append(file) self.dockwidget.listExport.addItems(exportList) def save_qml_styling(self): #,style_dir): scriptLocatie = os.path.dirname(os.path.realpath(__file__)) stijlgroep = self.dockwidget.stylingbox.currentText( ) # 'Beheerder-std' style_dir = os.path.join(scriptLocatie, 'styling', stijlgroep) # style_dir=r'C:\Users\onnoc\AppData\Roaming\QGIS\QGIS3\profiles\default\python\plugins\OASDGLDatachecker\styling\Stylingbeheerder' for layer in QgsProject.instance().mapLayers().values(): file = os.path.join(style_dir, layer.name() + ".qml") if os.path.exists(file): os.remove(file) # layer.exportNamedStyle(file, "test") layer.saveNamedStyle(file) # print(result) def laad_qml_styling(self, stylingnaam): if not stylingnaam: folder = "styling\\" + self.dockwidget.stylingbox.currentText() else: folder = "styling\\" + stylingnaam # print(folder) for layer in QgsProject.instance().mapLayers().values(): scriptLocatie = os.path.dirname(os.path.realpath(__file__)) qmlpad = os.path.join(scriptLocatie, folder, layer.name()) + ".qml" layer.loadNamedStyle(qmlpad) layer.triggerRepaint() # print(layer.name()) print(qmlpad) self.configure_dropdown() def add_qml_styling(self): qid = QInputDialog() title = "Nieuwe Stijling groep" label = "Naam stijling groep: " mode = QLineEdit.Normal default = "<your name here>" text, ok = QInputDialog.getText(qid, title, label, mode, default) if ok and text and not text == default: scriptLocatie = os.path.dirname(os.path.realpath(__file__)) folder = os.path.join(scriptLocatie, 'styling', text) print(folder) if not os.path.exists(folder): os.makedirs(folder, exist_ok=True) stylingfolders = self.get_stylingfolders() self.dockwidget.stylingbox.clear() self.dockwidget.stylingbox.addItems(stylingfolders) self.dockwidget.stylingbox.setCurrentText(text) def remove_qml_styling(self): stylinggroup = self.dockwidget.stylingbox.currentText() msgbox = QMessageBox( ) # https://www.riverbankcomputing.com/static/Docs/PyQt4/qmessagebox.html#details msgbox.setText("De stijlgroep: '" + stylinggroup + "' wordt verwijderd als je doorgaat.") msgbox.setInformativeText("Wil je doorgaan?") msgbox.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel) ret = msgbox.exec_() if not stylinggroup in ['Beheerder-std', 'Modelleur-std']: if ret == QMessageBox.Ok: scriptLocatie = os.path.dirname(os.path.realpath(__file__)) folder = os.path.join(scriptLocatie, 'styling', stylinggroup) print(folder) # subfolders = [ f.name for f in os.scandir(folder) if f.is_dir() ] files = glob.glob(os.path.join(folder, '*')) for file in files: os.remove(file) os.rmdir(folder) self.dockwidget.stylingbox.clear() stylingfolders = self.get_stylingfolders() self.dockwidget.stylingbox.addItems(stylingfolders) def update_status(self, waarde): # waarde='verwerkt' lyr = iface.activeLayer() lyr.startEditing() features = lyr.selectedFeatures() lyr.updateFields() idx = lyr.fields().indexFromName("status") for f in features: print(f) lyr.changeAttributeValue(f.id(), idx, waarde) lyr.commitChanges() # self.filter_status() def filter_status(self, waarde, filter): # filter = true statement = "status is null or status IN ()" basis = "status is null or status IN (" oldstatement = "" try: oldstatement = iface.activeLayer().subsetString() if filter: if not basis in oldstatement: statement = basis + "'" + waarde + "')" elif oldstatement.find(waarde) == -1: statement = oldstatement.replace(basis, "") statement = statement.replace(")", "") if len(statement) == 0: statement = basis + "'" + waarde + "')" elif len(statement) > 2: statement = basis + statement + ",'" + waarde + "')" else: statement = oldstatement else: if not basis in oldstatement: statement = "status is null or status IN ('gecontroleerd', 'verwerkt')" if waarde == 'gecontroleerd': statement = statement.replace("'" + waarde + "', ", "") else: statement = statement.replace(", '" + waarde + "'", "") elif oldstatement.find(waarde) == -1: statement = oldstatement else: statement = oldstatement.replace(basis, "") statement = statement.replace(")", "") statement = statement.replace("'" + waarde + "'", "") if len(statement) == 0: statement = basis + ")" elif len(statement) > 2: statement = statement.replace(",,", ",") statement = statement.strip(",") statement = basis + statement + ")" except: # statement = "status is null or status IN (gecontroleerd, verwerkt)" pass if not statement in [oldstatement, ""]: for layer in QgsProject.instance().mapLayers().values(): if layer.name().startswith("chk."): layer.setSubsetString(statement) def configure_dropdown(self): for layer in QgsProject.instance().mapLayers().values(): idx = layer.fields().indexFromName("status") editor_widget_setup = QgsEditorWidgetSetup( "ValueMap", { "map": { u"gecontroleerd": u"gecontroleerd", u"verwerkt": u"verwerkt" } }, ) layer.setEditorWidgetSetup(idx, editor_widget_setup) QSettings().setValue("/Map/identifyAutoFeatureForm", "true") def get_stylingfolders(self): scriptLocatie = os.path.dirname(os.path.realpath(__file__)) folder = os.path.join(scriptLocatie, 'styling') # folder = r'C:\Users\onnoc\AppData\Roaming\QGIS\QGIS3\profiles\default\python\plugins\OASDGLDatachecker\styling' subfolders = [f.name for f in os.scandir(folder) if f.is_dir()] return subfolders def save_folderchecks(self): folderchecks = os.path.realpath(self.dockwidget.folderNaam.text()) self.save_qsetting("paths", "folderchecks", folderchecks) def save_folderbeheerexport(self): folderchecks = os.path.realpath( self.dockwidget.folderNaam_export.text()) self.save_qsetting("paths", "folderbeheerexport", folderchecks) def save_leidingfile(self): leidingfile = os.path.realpath(self.dockwidget.leidingFile.filePath()) self.save_qsetting("paths", "leidingfile", leidingfile) def save_putfile(self): # putfile = os.path.dirname(os.path.realpath(self.dockwidget.putFile.filePath())) putfile = os.path.realpath(self.dockwidget.putFile.filePath()) self.save_qsetting('paths', 'putfile', putfile) def save_DEMfile(self): DEMfile = os.path.realpath(self.dockwidget.dem.filePath()) self.save_qsetting('paths', 'DEMfile', DEMfile) def create_db_from_qgis(self): settings = SettingsObjectPlugin() settings.createdb = True settings.database = self.dockwidget.dbName.text() settings.host = self.dockwidget.dbHost.text() settings.port = self.dockwidget.dbPort.text() settings.username = self.dockwidget.dbUsername.text() settings.password = self.dockwidget.dbPassword.text() # settings.s = self.dockwidget.? run_scripts(settings) qgs_settings = QSettings() qgs_settings.setValue( 'PostgreSQL/connections/' + settings.database + '/host', settings.host) qgs_settings.setValue( 'PostgreSQL/connections/' + settings.database + '/port', settings.port) qgs_settings.setValue( 'PostgreSQL/connections/' + settings.database + '/username', settings.username) qgs_settings.setValue( 'PostgreSQL/connections/' + settings.database + '/password', settings.password) qgs_settings.setValue( 'PostgreSQL/connections/' + settings.database + '/database', settings.database) qgs_settings.setValue( 'PostgreSQL/connections/' + settings.database + '/saveUsername', True) qgs_settings.setValue( 'PostgreSQL/connections/' + settings.database + '/savePassword', True) databases = self.get_databases() self.dockwidget.bestaandeDatabases.clear() self.dockwidget.bestaandeDatabases.addItems(databases) def get_settings(self): #vul_settings settings = SettingsObjectPlugin() # settings.s='localhost' #self.threedi_db_settings["threedi_host"] self.getConnectionDetails settings.host = self.threedi_db_settings['threedi_host'] settings.database = self.threedi_db_settings['threedi_dbname'] settings.port = self.threedi_db_settings['threedi_port'] settings.username = self.threedi_db_settings['threedi_user'] settings.password = self.threedi_db_settings['threedi_password'] settings.emptydb = True settings.import_type = self.get_qsetting("Instellingen", "ImportSoftware") #"gbi" if not settings.import_type or settings.import_type == "": settings.import_type = "gbi" settings.export = True settings.gpkg_output_layer = self.dockwidget.outputFileName.text() settings.checks = True # settings.checks = False settings.max_connections = 8 putfile = self.get_qsetting("paths", "putfile") settings.manhole_layer = putfile leidingfile = self.get_qsetting("paths", "leidingfile") settings.pipe_layer = leidingfile settings.dem = os.path.realpath(self.dockwidget.dem.filePath()) #'C:\\Users\onnoc\AppData\Roaming\QGIS\QGIS3\profiles\default\python\plugins\OASDGLDatachecker\tool_quality_checks\test\data\schiedam-test\dem_schiedam_test.tif') self.instellingen_ophalen(settings) print(settings.__dict__) # run_scripts(settings) # settings.dropdb = False # settings.createdb = False return settings def completed(self, result): #,exception, result=None): """This is called when doSomething is finished. Exception is not None if doSomething raises an exception. result is the return value of doSomething.""" print(result) if result: self.initialize_paths() print('succesfully ran') if exception is None: if result is None: QgsMessageLog.logMessage( 'Completed with no exception and no result '\ '(probably manually canceled by the user)', MESSAGE_CATEGORY, Qgis.Warning) else: QMessageBox.information( None, "Checks outcome", "Your checks have ran succesfully", ) else: QgsMessageLog.logMessage("Exception: {}".format(exception), MESSAGE_CATEGORY, Qgis.Critical) return def slider_function(self, value): layer = self.iface.mapCanvas().currentLayer() #print(layer.renderer().type()) #for field in layer.renderer().symbol().symbolLayer(0): #print(field.name(), field.typeName()) #layer.renderer().symbol().symbolLayer(0).setSize(value) #layer=iface.mapCanvas().currentLayer() #QgsMessageLog.logMessage('stylings opgeslagen', 'datachecker') renderer = layer.renderer() if hasattr(renderer, 'symbol') == False: if hasattr(renderer, 'Rule') == True: root_rule = renderer.rootRule() for rule in root_rule.children(): rule.symbol().setSize(value) elif layer.renderer().symbol().type() == 1: # Lijnen layer.renderer().symbol().symbolLayer(0).setWidth(value) print(layer.renderer().symbol().symbolLayer(0).width()) elif layer.renderer().symbol().type() == 0: # symbolen # newsize = layer.renderer().symbol().symbolLayer(0).size()*5/value layer.renderer().symbol().symbolLayer(0).setSize(value) print(layer.renderer().symbol().symbolLayer(0).size()) layer.triggerRepaint() iface.layerTreeView().refreshLayerSymbology(layer.id()) print(layer.name()) #print(value) def switch_layerIsolate(self, value): if value: iface.currentLayerChanged.connect( lambda _: self.switch_visibility()) # iface.layerTreeView().selectionChanged.connect(self.switch_visibility) # QObject.connect(self.iface,SIGNAL("currentLayerChanged(QgsMapLayer *)") ,self.switch_visibility) # QObject.connect(self.iface.mapCanvas(),SIGNAL("selectionChanged(QgsMapLayer)"), self.switch_visibility) else: # iface.currentLayerChanged.disconnect(lambda _: self.switch_visibility) iface.layerTreeView().currentLayerChanged.disconnect( ) #lambda _: self.switch_visibility) # QObject.disconnect(self.iface,SIGNAL("currentLayerChanged(QgsMapLayer *)") ,self.switch_visibility) # QObject.disconnect(self.iface.mapCanvas(),SIGNAL("selectionChanged(QgsMapLayer)"), self.switch_visibility) def switch_visibility(self): check = self.dockwidget.layerIsolate.checkState() if check: root = QgsProject.instance().layerTreeRoot() allLayers = root.layerOrder() for layer in allLayers: if layer in iface.layerTreeView().selectedLayers(): root.findLayer(layer.id()).setItemVisibilityChecked(True) else: root.findLayer(layer.id()).setItemVisibilityChecked(False) def instellingen_opslaan(self): for veld in velden: box = getattr(self.dockwidget, veld) waarde = box.value() # print(veld, waarde) self.save_qsetting("Instellingen", veld, waarde) def instellingenDefault_opslaan(self): for veld in velden: box = getattr(self.dockwidget, veld) waarde = box.value() # print(veld, waarde) self.save_qsetting("InstellingenDefault", veld, waarde) def instellingen_ophalen(self, settings): s = QSettings() group = "Instellingen" for veld in velden: value = s.value("OASDGLDatachecker/" + group + "/" + veld) setattr(settings, veld, value) # print(value) def instellingen_laden(self, default=False, initializePlugin=False): # default = True # initializePlugin = False if default: group = "InstellingenDefault" else: group = "Instellingen" for veld in velden: try: s = QSettings() value = s.value("OASDGLDatachecker/" + group + "/" + veld) box = getattr(self.dockwidget, veld) value2 = float(value) # print(value2) if value: box.valueChanged.disconnect(self.instellingen_opslaan) box.setValue(value2) #float(value) # box.valueChanged.connect(self.instellingen_opslaan) except: if initializePlugin: self.instellingenDefault_opslaan() else: pass def importSoftware_opslaan(self, waarde): s = QSettings() self.save_qsetting("Instellingen", "ImportSoftware", waarde) def save_qsetting(self, group, key, value): # file waar het opgeslagen wordt: C:\Users\onnoc\AppData\Roaming\QGIS\QGIS3\profiles\default\QGIS\QGIS3.INI s = QSettings() s.setValue("OASDGLDatachecker/" + group + "/" + key, value) test = s.value("OASDGLDatachecker/" + group + "/" + key) def get_qsetting(self, group, key): s = QSettings() try: value = s.value('OASDGLDatachecker/' + group + '/' + key) return (value) except: pass def delete_qsetting(self): QSettings().remove('UI/recentProjects') # als voorbeeld def select_output_file(self): file_name = QFileDialog.getSaveFileName(filter="*.gpkg") if str(file_name[0]): self.dockwidget.outputFileName.setText(str(file_name[0])) file_name = os.path.realpath(str(file_name[0])) self.save_qsetting('paths', 'outputfile', file_name) def draai_de_checks(self): settings = self.get_settings() task1 = QgsTask.fromFunction('Draai checks', run_scripts_task, on_finished=self.completed, settings=settings) QgsApplication.taskManager().addTask(task1) #run_scripts(settings) self.initialize_paths() def initialize_paths(self): foldernaam = self.get_qsetting("paths", "folderchecks") if foldernaam: foldernaam = Path(foldernaam) self.dockwidget.folderNaam.setText(str(foldernaam)) self.dockwidget.folderNaam.setToolTip(str(foldernaam)) self.fill_checks_list() foldernaam_export = self.get_qsetting("paths", "folderbeheerexport") if foldernaam_export: foldernaam_export = Path(foldernaam_export) self.dockwidget.folderNaam_export.setText(str(foldernaam_export)) self.dockwidget.folderNaam_export.setToolTip( str(foldernaam_export)) self.fill_export_list() DEMfile = self.get_qsetting('paths', 'DEMfile') if DEMfile: print(DEMfile) self.dockwidget.dem.setFilePath(os.path.join(str(DEMfile))) putfile = self.get_qsetting('paths', 'putfile') if putfile: self.dockwidget.putFile.setFilePath(os.path.join(str(putfile))) leidingfile = self.get_qsetting('paths', 'leidingfile') if leidingfile: self.dockwidget.leidingFile.setFilePath( os.path.join(str(leidingfile))) importSoftware = self.get_qsetting("Instellingen", "ImportSoftware") if importSoftware: self.dockwidget.boxSoftware.setCurrentText(importSoftware) self.instellingen_laden(initializePlugin=True) def run(self): """Run method that loads and starts the plugin""" if not self.pluginIsActive: self.pluginIsActive = True # print "** STARTING Datachecker" # dockwidget may not exist if: # first run of plugin # removed on close (see self.onClosePlugin method) if self.dockwidget == None: # Create the dockwidget (after translation) and keep reference self.dockwidget = DatacheckerDockWidget() databases = self.get_databases() self.dockwidget.bestaandeDatabases.addItems(databases) stylingfolders = self.get_stylingfolders() self.dockwidget.stylingbox.clear() self.dockwidget.stylingbox.addItems(stylingfolders) self.dockwidget.bestaandeDatabases.currentTextChanged.connect( self.getConnectionDetails) self.dockwidget.ObjectSlider.valueChanged.connect( self.slider_function) self.dockwidget.applyStylingButton.clicked.connect( self.laad_qml_styling) self.dockwidget.selectFolderButton.clicked.connect( self.pb_select_dc_folder) self.dockwidget.reloadResult.clicked.connect(self.fill_checks_list) self.dockwidget.outputFileButton.clicked.connect( self.select_output_file) self.dockwidget.folderNaam.textChanged.connect( self.save_folderchecks) self.dockwidget.folderNaam_export.textChanged.connect( self.save_folderbeheerexport) # self.dockwidget.folderNaam.editingFinished.connect(self.fill_checks_list) self.dockwidget.InladenGpkgButton.clicked.connect(self.laad_gpkg) self.dockwidget.savelayer.clicked.connect(self.save_qml_styling) self.dockwidget.addStyling.clicked.connect(self.add_qml_styling) self.dockwidget.removeStyling.clicked.connect( self.remove_qml_styling) self.dockwidget.selectFolderButton_export.clicked.connect( self.pb_select_exp_folder) self.dockwidget.createdbButton.clicked.connect( self.create_db_from_qgis) ##self.dockwidget.linePutten.dropevent.connect(over self.dockwidget.pgecontroleerd.clicked.connect( lambda: self.update_status(waarde='gecontroleerd')) self.dockwidget.pverwerkt.clicked.connect( lambda: self.update_status(waarde='verwerkt')) self.dockwidget.pleeg.clicked.connect( lambda: self.update_status(waarde=None)) self.dockwidget.cbgecontroleerd.stateChanged.connect( lambda: self.filter_status(waarde='gecontroleerd', filter=self.dockwidget. cbgecontroleerd.isChecked())) self.dockwidget.cbverwerkt.stateChanged.connect( lambda: self.filter_status(waarde='verwerkt', filter=self.dockwidget.cbverwerkt. isChecked())) iface.currentLayerChanged.connect( lambda _: self.switch_visibility()) # self.dockwidget.layerIsolate.stateChanged.connect(self.switch_layerIsolate) self.dockwidget.leidingFile.fileChanged.connect( self.save_leidingfile) self.dockwidget.putFile.fileChanged.connect(self.save_putfile) self.dockwidget.dem.fileChanged.connect(self.save_DEMfile) self.dockwidget.DatachecksButton.clicked.connect( self.draai_de_checks) try: self.dockwidget.boxSoftware.currentTextChanged.disconnect( self.importSoftware_opslaan) except: pass self.dockwidget.boxSoftware.clear() self.dockwidget.boxSoftware.addItems(["gbi", "gisib"]) self.dockwidget.boxSoftware.currentTextChanged.connect( self.importSoftware_opslaan) self.dockwidget.instellingenopslaan.clicked.connect( self.instellingenDefault_opslaan) for veld in velden: box = getattr(self.dockwidget, veld) box.valueChanged.connect(self.instellingen_opslaan) # waarde = box.valueChanged.connect(self.instellingen_opslaan) self.dockwidget.defaultInstellingen.clicked.connect( lambda: self.instellingen_laden(default=True)) # connect to provide cleanup on closing of dockwidget self.dockwidget.closingPlugin.connect(self.onClosePlugin) # show the dockwidget # TODO: fix to allow choice of dock location self.iface.addDockWidget(Qt.RightDockWidgetArea, self.dockwidget) self.dockwidget.show() self.initialize_paths()