class CPTranslator: def __init__(self, qmPath, language = 'de_DE'): self.l18Path = os.path.abspath(qmPath) self.language = language self.translator = QTranslator() self.loadDictionary() def getTranslator(self): return self.translator def loadDictionary(self): self.translator.load('%s.po' % (self.language,), self.l18Path) def changeLanguage(self, language): self.language = language self.loadDictionary() def pyTranslate(self, context, sourceText, disambiguation = None, params = None): txt = QApplication.translate(context, sourceText, disambiguation) if params is not None: return txt.format(params) else: return txt
def main(): app = QApplication([i.encode('utf-8') for i in sys.argv]) app.setOrganizationName(ffmc.__name__) app.setOrganizationDomain(ffmc.__url__) app.setApplicationName('FF Multi Converter') app.setWindowIcon(QIcon(':/ffmulticonverter.png')) locale = QLocale.system().name() qtTranslator = QTranslator() if qtTranslator.load('qt_' + locale, ':/'): app.installTranslator(qtTranslator) appTranslator = QTranslator() if appTranslator.load('ffmulticonverter_' + locale, ':/'): app.installTranslator(appTranslator) if not os.path.exists(config.log_dir): os.makedirs(config.log_dir) logging.basicConfig( filename=config.log_file, level=logging.DEBUG, format=config.log_format, datefmt=config.log_dateformat ) converter = MainWindow() converter.show() app.exec_()
def main(): # DBUS MainLoop if not dbus.get_default_main_loop(): from dbus.mainloop.pyqt5 import DBusQtMainLoop DBusQtMainLoop(set_as_default = True) # Application Stuff from libhistorymanager.window import MainManager app = QApplication(sys.argv) app.setOrganizationName("history-manager") app.setApplicationName("history-manager") app.setApplicationVersion("0.2.8b") locale = QLocale.system().name() translator = QTranslator(app) translator.load(join("/usr/share/history-manager", "languages/{}.qm".format(locale))) app.installTranslator(translator) # Create Main Widget and make some settings mainWindow = MainManager(None, app= app) mainWindow.resize(640, 480) mainWindow.setWindowIcon(QIcon.fromTheme("view-history")) mainWindow.show() # Create connection for lastWindowClosed signal to quit app app.lastWindowClosed.connect(app.quit) # Run the applications app.exec_()
def run(image_path = None): # Global exceptions sys.excepthook = excepthook app = QApplication(sys.argv) # Splash screen splash_pix = QPixmap('resources/splash.jpg') splash = QSplashScreen(splash_pix) splash.setMask(splash_pix.mask()) splash.show() app.processEvents() # Load translation locale_code = SettingsModel().get('Language', 'code') if locale_code != "en_US": # Standard language # Standard translator for the generated GUI translator = QTranslator() translator.load('localization/' + locale_code + '.qm') app.installTranslator(translator) # Translator for various GUI elements translator_2 = QTranslator() translator_2.load('localization/' + locale_code + '_2.qm') app.installTranslator(translator_2) # Start m = Hitagi(image_path) # Pass image path splash.finish(m) sys.exit(app.exec())
def main(): app = QApplication(sys.argv) locale = QLocale.system().name() conf = prepare.Config() local_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), 'data', 'locale')) translator = QTranslator() if not os.path.isfile(conf.config_file): if locale in prepare.LANGUISH.keys(): conf.write_config('squares', 'gray', 30, 30, prepare.LANGUISH[locale]['Lang'], __version__) translator.load(os.path.join(local_dir, 'pybigpixel_' + locale + '.qm')) app.installTranslator(translator) else: conf.write_config('squares', 'gray', 30, 30, 'English', __version__) else: key = [key for key in prepare.LANGUISH.keys() if prepare.LANGUISH[key]['Lang'] == conf.get_languish()] if key[0] != 'default': translator.load(os.path.join(local_dir, 'pybigpixel_' + key[0] + '.qm')) app.installTranslator(translator) window = Window(conf) window.show() sys.exit(app.exec_())
def main(): global app # register representation factories baseRepresentationFactories.registerAllFactories() representationFactories.registerAllFactories() # initialize the app app = Application(sys.argv) app.setOrganizationName("TruFont") app.setOrganizationDomain("trufont.github.io") app.setApplicationName("TruFont") app.setApplicationVersion(__version__) app.setWindowIcon(QIcon(":app.png")) app.setAttribute(Qt.AA_UseHighDpiPixmaps, True) # Install stream redirection app.outputWindow = OutputWindow() # Exception handling sys.excepthook = exceptionCallback # Qt's translation for itself. May not be installed. qtTranslator = QTranslator() qtTranslator.load("qt_" + QLocale.system().name(), QLibraryInfo.location(QLibraryInfo.TranslationsPath)) app.installTranslator(qtTranslator) appTranslator = QTranslator() appTranslator.load("trufont_" + QLocale.system().name(), os.path.dirname(os.path.realpath(__file__)) + "/resources") app.installTranslator(appTranslator) # parse options and open fonts parser = QCommandLineParser() parser.setApplicationDescription(QApplication.translate( "Command-line parser", "The TruFont font editor.")) parser.addHelpOption() parser.addVersionOption() parser.addPositionalArgument(QApplication.translate( "Command-line parser", "files"), QApplication.translate( "Command-line parser", "The UFO files to open.")) parser.process(app) args = parser.positionalArguments() if not args: fontPath = None # maybe load recent file settings = QSettings() loadRecentFile = settings.value("misc/loadRecentFile", False, bool) if loadRecentFile: recentFiles = settings.value("core/recentFiles", [], type=str) if len(recentFiles) and os.path.exists(recentFiles[0]): fontPath = recentFiles[0] app.openFile(fontPath) # otherwise, create a new file if fontPath is None: app.newFile() else: for fontPath in args: app.openFile(fontPath) sys.exit(app.exec_())
def install_qt_trans(): # So, we install the gettext locale, great, but we also should try to install qt_*.qm if # available so that strings that are inside Qt itself over which I have no control are in the # right language. from PyQt5.QtCore import QCoreApplication, QTranslator, QLocale, QLibraryInfo lang = str(QLocale.system().name())[:2] qmname = 'qt_%s' % lang qtr = QTranslator(QCoreApplication.instance()) qtr.load(qmname, QLibraryInfo.location(QLibraryInfo.TranslationsPath)) QCoreApplication.installTranslator(qtr)
def start_gui(): from .frontends import MainWindow app = QApplication(sys.argv) trans = QTranslator() trans.load(config['lang'], Constant.locale_dir) app.installTranslator(trans) window = MainWindow() window.show() sys.exit(app.exec_())
def main(): if markups.__version_tuple__ < (2, ): sys.exit('Error: ReText needs PyMarkups 2.0 or newer to run.') # If we're running on Windows without a console, then discard stdout # and save stderr to a file to facilitate debugging in case of crashes. if sys.executable.endswith('pythonw.exe'): sys.stdout = open(devnull, 'w') sys.stderr = open('stderr.log', 'w') app = QApplication(sys.argv) app.setOrganizationName("ReText project") app.setApplicationName("ReText") app.setApplicationDisplayName("ReText") app.setApplicationVersion(app_version) app.setOrganizationDomain('mitya57.me') if hasattr(app, 'setDesktopFileName'): # available since Qt 5.7 app.setDesktopFileName('me.mitya57.ReText.desktop') QNetworkProxyFactory.setUseSystemConfiguration(True) RtTranslator = QTranslator() for path in datadirs: if RtTranslator.load('retext_' + globalSettings.uiLanguage, join(path, 'locale')): break QtTranslator = QTranslator() QtTranslator.load("qt_" + globalSettings.uiLanguage, QLibraryInfo.location(QLibraryInfo.TranslationsPath)) app.installTranslator(RtTranslator) app.installTranslator(QtTranslator) print('Using configuration file:', settings.fileName()) if globalSettings.appStyleSheet: sheetfile = QFile(globalSettings.appStyleSheet) sheetfile.open(QIODevice.ReadOnly) app.setStyleSheet(QTextStream(sheetfile).readAll()) sheetfile.close() window = ReTextWindow() window.show() # ReText can change directory when loading files, so we # need to have a list of canonical names before loading fileNames = list(map(canonicalize, sys.argv[1:])) previewMode = False for fileName in fileNames: if QFile.exists(fileName): window.openFileWrapper(fileName) if previewMode: window.actionPreview.setChecked(True) window.preview(True) elif fileName == '--preview': previewMode = True inputData = '' if (sys.stdin is None or sys.stdin.isatty()) else sys.stdin.read() if inputData or not window.tabWidget.count(): window.createNew(inputData) signal.signal(signal.SIGINT, lambda sig, frame: window.close()) sys.exit(app.exec())
class Application(object): def __init__(self, config, use_qt_notifications): # This is done dynamically so localization # support can be configure beforehand. from plover.gui_qt.main_window import MainWindow self._app = None self._win = None self._engine = None self._translator = None QCoreApplication.setApplicationName(__software_name__.capitalize()) QCoreApplication.setApplicationVersion(__version__) QCoreApplication.setOrganizationName('Open Steno Project') QCoreApplication.setOrganizationDomain('openstenoproject.org') self._app = QApplication([]) self._app.setAttribute(Qt.AA_UseHighDpiPixmaps) # Enable localization of standard Qt controls. self._translator = QTranslator() translations_dir = QLibraryInfo.location(QLibraryInfo.TranslationsPath) self._translator.load('qtbase_' + get_language(), translations_dir) self._app.installTranslator(self._translator) QApplication.setQuitOnLastWindowClosed(False) signal.signal(signal.SIGINT, lambda signum, stack: QCoreApplication.quit()) # Make sure the Python interpreter runs at least every second, # so signals have a chance to be processed. self._timer = QTimer() self._timer.timeout.connect(lambda: None) self._timer.start(1000) self._engine = Engine(config, KeyboardEmulation()) self._win = MainWindow(self._engine, use_qt_notifications) self._app.aboutToQuit.connect(self._win.on_quit) def __del__(self): del self._win del self._app del self._engine del self._translator def run(self): self._app.exec_() self._engine.quit() self._engine.wait()
def main(): logging.basicConfig(level=logging.WARN, format="%(asctime)s %(levelname)s %(message)s") app = QApplication(sys.argv) translator = QTranslator(app) path = os.path.dirname(rect.__file__) if QLocale.system().language() == QLocale.Japanese: translator.load(path+"/i18n/trainscanner_ja") app.installTranslator(translator) se = SettingsGUI() se.show() se.raise_() sys.exit(app.exec_())
def main(): #pyqt_set_trace() app = QApplication(sys.argv) translator = QTranslator(app) rpath = getattr(sys, '_MEIPASS', os.getcwd()) loc = SystemLanguage() if loc[:2] == "ja": translator.load(rpath+"/i18n/trainscanner_ja") app.installTranslator(translator) se = SettingsGUI() se.show() se.raise_() sys.exit(app.exec_())
def test_qgis_translations(self): """Test that translations work.""" parent_path = os.path.join(__file__, os.path.pardir, os.path.pardir) dir_path = os.path.abspath(parent_path) file_path = os.path.join( dir_path, 'i18n', 'af.qm') translator = QTranslator() translator.load(file_path) QCoreApplication.installTranslator(translator) expected_message = 'Goeie more' real_message = QCoreApplication.translate("@default", 'Good morning') self.assertEqual(real_message, expected_message)
def main(): app = QApplication(sys.argv) app.setApplicationName("Kaptan") app.setOrganizationName("Kaptan") app.setApplicationVersion("5.0 Beta3") #app.setStyleSheet(open(join(dirPath, "data/libkaptan.qss").read()) locale = QLocale.system().name() translator = QTranslator(app) translator.load("/usr/share/kaptan/languages/kaptan_{}.qm".format(locale)) app.installTranslator(translator) kaptan = Kaptan() kaptan.show() app.exec_()
def main(): dirPath = dirname(__file__) app = QApplication(sys.argv) #app.setStyleSheet(open(join(dirPath, "data/kaptan.qss").read()) locale = QLocale.system().name() translator = QTranslator(app) translator.load(join(dirPath, "languages/{}.qm".format(locale))) app.installTranslator(translator) kaptan = Kaptan() kaptan.show() app.exec_()
def main(): if settings.get('log:errors'): log_filename = settings.get('log:filename') if log_filename: try: log_file = open(log_filename,"w") print ('Redirecting stderr/stdout... to %s' % log_filename) sys.stderr = log_file sys.stdout = log_file except IOError: print("Lector could not open log file '%s'!\n" % log_filename \ + " Redirecting will not work.") else: print("Log file is not set. Please set it in settings.") app = QApplication(sys.argv) opts = [str(arg) for arg in app.arguments()[1:]] if '--no-scanner' in opts: scanner = False else: scanner = True qsrand(QTime(0, 0, 0).secsTo(QTime.currentTime())) locale = settings.get('ui:lang') if not locale: locale = QLocale.system().name() qtTranslator = QTranslator() if qtTranslator.load(":/translations/ts/lector_" + locale, 'ts'): app.installTranslator(qtTranslator) window = Window(scanner) window.show() app.exec_()
def main(): sys.setrecursionlimit(60) # to find infinite signal loops? app = QApplication(sys.argv) QCoreApplication.setOrganizationName("testPrintFramework") QCoreApplication.setOrganizationDomain("testPrintFramework.com") QCoreApplication.setApplicationName("testPrintFramework") # To test translations, in shell >export LANG=es or >export LANG=cn translator = QTranslator() result = translator.load("/home/bootch/Downloads/SubprojectsPensool/qtPrintFramework/resources/translations/qtPrintFramework_es.qm") if not result: print("Not load translation") # Not a failure nor exception: program continues in default (usually English) if not app.installTranslator(translator): print("Not install translator.") if config.useQML: from qtEmbeddedQmlFramework.resourceManager import resourceMgr resourceMgr.setResourceRoot(__file__, 'qtPrintFramework') mainWindow = MainWindow() mainWindow.show() sys.exit(app.exec_())
def __init__(self): from codec import Codec from window import Window from system import System from datajar import DataJar from filesystem import FileSystem try: manifest = json.load(codecs.open('manifest.json', 'r', 'utf-8')) except: manifest = {} for key in assets.manifest: if key in manifest: assets.manifest[key] = manifest[key] self.app = QApplication(sys.argv) self.app.setApplicationName(assets.manifest['name']) self.app.setApplicationVersion(assets.manifest['version']) assets.sys = System() assets.codec = Codec() assets.fs = FileSystem() assets.dataJar = DataJar() translator = QTranslator() if translator.load("zh_CN.qm"): self.app.installTranslator(translator) self.window = Window(None, assets.manifest['path'] + 'index.html') sys.exit(self.app.exec_())
def _ensureQApplication(): if not QApplication.instance(): app = QApplication(["ubuntu-release-upgrader"]) # Try to load default Qt translations so we don't have to worry about # QStandardButton translations. # FIXME: make sure we dep on l10n translator = QTranslator(app) if type(PYQT_VERSION) == int: translator.load(QLocale.system(), 'qt', '_', '/usr/share/qt5/translations') else: translator.load(QLocale.system(), 'qt', '_', '/usr/share/qt4/translations') app.installTranslator(translator) return app return QApplication.instance()
def loadQtTranslation(self, file, language = "default"): #TODO Add support for specifying a language from preferences path = None if language == "default": # If we have a language set in the environment, try and use that. lang = os.getenv("LANGUAGE") if lang: try: path = Resources.getPath(Resources.i18nLocation, lang, "LC_MESSAGES", file + ".qm") except FileNotFoundError: path = None # If looking up the language from the enviroment fails, try and use Qt's system locale instead. if not path: locale = QLocale.system() # First, try and find a directory for any of the provided languages for lang in locale.uiLanguages(): try: path = Resources.getPath(Resources.i18nLocation, lang, "LC_MESSAGES", file + ".qm") language = lang except FileNotFoundError: pass else: break # If that fails, see if we can extract a language "class" from the # preferred language. This will turn "en-GB" into "en" for example. if not path: lang = locale.uiLanguages()[0] lang = lang[0:lang.find("-")] try: path = Resources.getPath(Resources.i18nLocation, lang, "LC_MESSAGES", file + ".qm") language = lang except FileNotFoundError: pass else: path = Resources.getPath(Resources.i18nLocation, language, "LC_MESSAGES", file + ".qm") # If all else fails, fall back to english. if not path: Logger.log("w", "Could not find any translations matching {0} for file {1}, falling back to english".format(language, file)) try: path = Resources.getPath(Resources.i18nLocation, "en", "LC_MESSAGES", file + ".qm") except FileNotFoundError: Logger.log("w", "Could not find English translations for file {0}. Switching to developer english.".format(file)) return translator = QTranslator() if not translator.load(path): Logger.log("e", "Unable to load translations %s", file) return # Store a reference to the translator. # This prevents the translator from being destroyed before Qt has a chance to use it. self._translators[file] = translator # Finally, install the translator so Qt can use it. self.installTranslator(translator)
def main(): app = QApplication(sys.argv) app.setOrganizationName("ReText project") app.setApplicationName("ReText") app.setApplicationDisplayName("ReText") app.setApplicationVersion(app_version) app.setOrganizationDomain('mitya57.me') if hasattr(app, 'setDesktopFileName'): # available since Qt 5.7 app.setDesktopFileName('me.mitya57.ReText.desktop') QNetworkProxyFactory.setUseSystemConfiguration(True) RtTranslator = QTranslator() for path in datadirs: if RtTranslator.load('retext_' + globalSettings.uiLanguage, join(path, 'locale')): break QtTranslator = QTranslator() QtTranslator.load("qt_" + globalSettings.uiLanguage, QLibraryInfo.location(QLibraryInfo.TranslationsPath)) app.installTranslator(RtTranslator) app.installTranslator(QtTranslator) if globalSettings.appStyleSheet: sheetfile = QFile(globalSettings.appStyleSheet) sheetfile.open(QIODevice.ReadOnly) app.setStyleSheet(QTextStream(sheetfile).readAll()) sheetfile.close() window = ReTextWindow() window.show() # ReText can change directory when loading files, so we # need to have a list of canonical names before loading fileNames = list(map(canonicalize, sys.argv[1:])) previewMode = False for fileName in fileNames: if QFile.exists(fileName): window.openFileWrapper(fileName) if previewMode: window.actionPreview.trigger() elif fileName == '--preview': previewMode = True if sys.stdin: inputData = '' if sys.stdin.isatty() else sys.stdin.read() if inputData or not window.tabWidget.count(): window.createNew(inputData) signal.signal(signal.SIGINT, lambda sig, frame: window.close()) sys.exit(app.exec())
class pointSamplingTool(object): def __init__(self, iface): self.iface = iface if QSettings().value('locale/overrideFlag'): locale = QSettings().value('locale/userLocale') else: locale = QLocale.system().name() locale_path = os.path.join( os.path.dirname(__file__), 'i18n', 'pointSamplingTool_{}.qm'.format(locale[0:2])) if os.path.exists(locale_path): self.translator = QTranslator() self.translator.load(locale_path) QCoreApplication.installTranslator(self.translator) def initGui(self): # create action self.action = QAction(QIcon(":/plugins/pointSamplingTool/pointSamplingToolIcon.png"), QCoreApplication.translate('Point Sampling Tool', 'Point Sampling Tool'), self.iface.mainWindow()) self.action.setWhatsThis(QCoreApplication.translate('Point Sampling Tool', 'Collects polygon attributes and raster values from multiple layers at specified sampling points')) self.action.triggered.connect(self.run) # add toolbar button and menu item self.iface.addToolBarIcon(self.action) self.iface.addPluginToMenu(QCoreApplication.translate('Point Sampling Tool', "&Analyses"), self.action) def unload(self): # remove the plugin menu item and icon self.iface.removePluginMenu(QCoreApplication.translate('Point Sampling Tool', "&Analyses"), self.action) self.iface.removeToolBarIcon(self.action) def run(self): # create and show a configuration dialog or something similar dialoga = doPointSamplingTool.Dialog(self.iface) dialoga.exec_()
def main(argv=None): if not argv: argv = sys.argv app = QApplication(argv) translator = QTranslator() translator.load("qt_" + QLocale.system().name(), os.path.join( getResourcesPath(), "translations")) app.installTranslator(translator) myTranslator = QTranslator() myTranslator.load("Tiles_" + QLocale.system().name(), os.path.join( getResourcesPath(), "translations")) app.installTranslator(myTranslator) window = MainWindow() window.show() return app.exec_()
def gui(): app = QApplication(sys.argv) translator = QTranslator() if translator.load('wise_'+ QLocale.system().name()+'.qm',":/translations/"): app.installTranslator(translator) translator_qt = QTranslator() if translator_qt.load('qt_'+ QLocale.system().name()+'.qm',":/translations/"): print('i found qt') app.installTranslator(translator_qt) timer = Timer() def beep(): print('\a') timer.timeout.connect(beep) timer.show() sys.exit(app.exec_())
def switch_language(self): translator = QTranslator(self.qapp) logging.debug("Loading translations") locale = self.preferences["lang"] QLocale.setDefault(QLocale(locale)) if translator.load(":/i18n/{0}".format(locale)): if QCoreApplication.installTranslator(translator): logging.debug("Loaded i18n/{0}".format(locale)) else: logging.debug("Couldn't load translation")
def main(): app = QApplication(sys.argv) translator = QTranslator() if translator.load('editor_'+ QLocale.system().name()+'.qm',":/translations/"): app.installTranslator(translator) translator_qt = QTranslator() if translator_qt.load('qt_'+ QLocale.system().name()+'.qm',":/translations/"): # print('i found qt') app.installTranslator(translator_qt) mainwindow = Editor() mainwindow.setWindowTitle('simple text editor') mainwindow.setWindowIcon(QIcon(':/icons/editor.ico')) mainwindow.show() sys.exit(app.exec_())
def checkBoxToggled(self): checkBox = self.sender() window = self.mainWindowForCheckBoxMap.get(checkBox) if not window: translator = QTranslator() translator.load(self.qmFileForCheckBoxMap[checkBox]) QApplication.installTranslator(translator) # Because we will be installing an event filter for the main window # it is important that this instance isn't garbage collected before # the main window when the program terminates. We ensure this by # making the main window a child of this one. window = MainWindow(self) window.setPalette(QPalette(self.colorForLanguage(checkBox.text()))) window.installEventFilter(self) self.mainWindowForCheckBoxMap[checkBox] = window window.setVisible(checkBox.isChecked())
def __init__(self, app_dir): app_dir = os.path.realpath(app_dir) manifest_path = os.path.join(app_dir, "manifest.json") try: manifest = json.load(codecs.open(manifest_path, 'r', 'utf-8')) except: manifest = {} for key in manifest: assets.manifest[key] = manifest[key] app = QApplication(sys.argv) app.setApplicationName(assets.manifest['name']) app.setApplicationVersion(assets.manifest['version']) assets.sys = System() assets.codec = Codec() assets.fs = FileSystem() assets.dataJar = DataJar() translator = QTranslator() translateLocaleName = "qt_" + QLocale.system().name() translator.load(translateLocaleName, QLibraryInfo.location(QLibraryInfo.TranslationsPath)) app.installTranslator(translator) if assets.manifest.get("plugins"): plugindir = os.path.join(app_dir, assets.manifest["plugins"]) plugin_manager = PluginsManager(plugindir) plugin_manager.load(assets) assets.manifest['icon'] = os.path.join(app_dir, assets.manifest["icon"]) assets.manifest['app_dir'] = app_dir if "--debug" in sys.argv: assets.manifest['debug'] = True index_path = os.path.join(app_dir, assets.manifest['path'] + 'index.html') self.window = Window(None, index_path) sys.exit(app.exec_())
class OfflineMapMatching: '''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', 'OfflineMapMatching_{}.qm'.format(locale)) if os.path.exists(locale_path): self.translator = QTranslator() self.translator.load(locale_path) if qVersion() > '4.3.3': QCoreApplication.installTranslator(self.translator) # Create the dialog (after translation) and keep reference self.dlg = OfflineMapMatchingDialog() # Declare instance attributes self.actions = [] self.menu = self.tr(u'&Offline-MapMatching') # TODO: We are going to let the user set this up in a future iteration self.toolbar = self.iface.addToolBar(u'OfflineMapMatching') self.toolbar.setObjectName(u'OfflineMapMatching') #add help-document to the GUI dir = os.path.dirname(__file__) file = os.path.abspath(os.path.join(dir, 'help_docs', 'help.html')) if os.path.exists(file): with open(file) as helpf: help = helpf.read() self.dlg.textBrowser_help.insertHtml(help) self.dlg.textBrowser_help.moveCursor(QTextCursor.Start) #declare additional instance vars self.map_matcher = MapMatcher() self.provider = OfflineMapMatchingProvider() #connect slots and signals self.dlg.comboBox_trajectory.currentIndexChanged.connect( self.startPopulateFieldsComboBox) self.dlg.pushButton_start.clicked.connect(self.startMapMatching) #set a default crs to avoid problems in QGIS 3.4 self.dlg.mQgsProjectionSelectionWidget.setCrs( QgsCoordinateReferenceSystem('EPSG:4326')) # 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('OfflineMapMatching', message) def add_action(self, icon_path, text, callback=None, enabled_flag=True, add_to_menu=True, add_to_toolbar=True, status_tip=None, whats_this=None, parent=None, action=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) if action is None: 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.addPluginToVectorMenu(self.menu, action) # self.iface.vectorMenu().addAction(action) self.actions.append(action) return action def initGui(self): '''Create the menu entries, toolbar icons inside the QGIS GUI and add a new processing provider.''' icon_path = ':/plugins/offline_map_matching/icons/icon.png' #set up entry for the main gui self.add_action(icon_path, text=self.tr(u'Match Trajectory'), callback=self.run, parent=self.iface.mainWindow()) #init the preprocessing group with their entries menu = QMenu() #add icons icon_clip = QIcon( ':/plugins/offline_map_matching/icons/clipping_icon.png') icon_density = QIcon( ':/plugins/offline_map_matching/icons/reduce_density_icon.png') icon_pp = QIcon( ':/plugins/offline_map_matching/icons/preprocessing_icon.png') #add actions action_clip = menu.addAction(icon_clip, 'Clip Network', self.clipNetwork) action_clip.setObjectName('clip_network') action_reduce = menu.addAction(icon_density, 'Reduce Trajectory Density', self.reduceDensity) action_reduce.setObjectName('reduce_density') #add main entry preprocessing_action = QAction(icon_pp, 'Preprocessing', self.iface.mainWindow()) preprocessing_action.setMenu(menu) self.add_action('', text=self.tr(u'Preprocessing'), action=preprocessing_action, parent=self.iface.mainWindow(), add_to_toolbar=False) # preprocessing_action.setMenu(menu) # self.actions.append(preprocessing_action) # self.iface.addPluginToVectorMenu(self.menu, preprocessing_action) #add the processing provider QgsApplication.processingRegistry().addProvider(self.provider) def clipNetwork(self): processing.execAlgorithmDialog('omm:clip_network', {}) def reduceDensity(self): processing.execAlgorithmDialog('omm:reduce_trajectory_density', {}) def unload(self): '''Removes the plugin menu item and icon from QGIS GUI. Remove the processing provider.''' for action in self.actions: self.iface.removePluginVectorMenu(self.tr(u'&Offline-MapMatching'), action) #self.iface.vectorMenu().removeAction(action) self.iface.removeToolBarIcon(action) # remove the toolbar del self.toolbar #remove the processing provider QgsApplication.processingRegistry().removeProvider(self.provider) def run(self): '''Run method that performs all the real work''' #populate the comboboxes with the available layers self.populateComboBox('network') self.populateComboBox('trajectory') self.populateComboBox('fields') #clear all other gui elements self.dlg.progressBar.setValue(0) self.dlg.doubleSpinBox_sigma.setValue(50.0) self.dlg.doubleSpinBox_my.setValue(0.0) self.dlg.doubleSpinBox_beta.setValue(30.0) self.dlg.doubleSpinBox_max.setValue(0.0) self.dlg.label_info.setText('') #self.dlg.lineEdit_crs.setText('') # show the dialog self.dlg.show() # Run the dialog event loop #result = self.dlg.exec_() # See if OK was pressed #if result: # Do something useful here - delete the line containing pass and # substitute with your code. #pass def populateComboBox(self, type): '''Populate the given combobox.''' if type == 'network': self.map_matcher.fillLayerComboBox(self.iface, self.dlg.comboBox_network, 'LINESTRING') elif type == 'trajectory': self.map_matcher.fillLayerComboBox(self.iface, self.dlg.comboBox_trajectory, 'POINT') elif type == 'fields': self.map_matcher.fillAttributeComboBox( self.dlg.comboBox_trajectoryID, self.dlg.comboBox_trajectory.currentText()) def startPopulateFieldsComboBox(self): self.populateComboBox('fields') def startMapMatching(self): self.dlg.groupBox_data.setEnabled(False) self.dlg.groupBox_settings.setEnabled(False) self.dlg.pushButton_start.setEnabled(False) try: start_time = time.time() result = self.map_matcher.startViterbiMatchingGui( self.dlg.progressBar, self.dlg.comboBox_trajectory.currentText(), self.dlg.comboBox_network.currentText(), self.dlg.comboBox_trajectoryID.currentText(), self.dlg.doubleSpinBox_sigma.value(), self.dlg.doubleSpinBox_my.value(), self.dlg.doubleSpinBox_beta.value(), self.dlg.doubleSpinBox_max.value(), self.dlg.label_info, self.dlg.mQgsProjectionSelectionWidget.crs().authid()) if result == 0: self.iface.messageBar().pushMessage( 'map matching finished ^o^ - time: ' + str(round(time.time() - start_time, 2)) + ' sec', level=Qgis.Success, duration=60) elif result == -1: self.iface.messageBar().pushMessage( 'Error during calculation of candidates. Check the QGIS-log for further information.', level=Qgis.Warning, duration=60) elif result == -2: self.iface.messageBar().pushMessage( 'Error during calculation of starting probabilities. Check the QGIS-log for further information.', level=Qgis.Warning, duration=60) elif result == -3: self.iface.messageBar().pushMessage( 'Error during calculation of transition probabilities. Check the QGIS-log for further information.', level=Qgis.Warning, duration=60) elif result == -4: self.iface.messageBar().pushMessage( 'Error during calculation of backtracking. Check the QGIS-log for further information.', level=Qgis.Warning, duration=60) elif result == -5: self.iface.messageBar().pushMessage( 'Error during calculating the most likely path. Check the QGIS-log for further information.', level=Qgis.Warning, duration=60) elif result == -6: self.iface.messageBar().pushMessage( 'Error during calculating the path on network. Check the QGIS-log for further information.', level=Qgis.Warning, duration=60) except: QgsMessageLog.logMessage(traceback.format_exc(), level=Qgis.Critical) self.iface.messageBar().pushMessage( 'An error occured. Please look into the log and/or Python console for further information.', level=Qgis.Critical, duration=60) self.dlg.groupBox_data.setEnabled(True) self.dlg.groupBox_settings.setEnabled(True) self.dlg.pushButton_start.setEnabled(True)
class CKANBrowser: """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 """ QgsMessageLog.logMessage('__init__', 'CKAN-Browser', Qgis.Info) QSettings().setValue("ckan_browser/isopen", False) self.iface = iface # initialize plugin directory self.plugin_dir = os.path.dirname(__file__) QgsMessageLog.logMessage( u'plugin directory: {}'.format(self.plugin_dir), 'CKAN-Browser', Qgis.Info) # initialize locale locale = QSettings().value('locale/userLocale')[0:2] QgsMessageLog.logMessage(u'locale: {}'.format(locale), 'CKAN-Browser', Qgis.Info) locale_path = os.path.join(self.plugin_dir, 'i18n', 'CKANBrowser_{}.qm'.format(locale)) QgsMessageLog.logMessage(u'locale_path: {}'.format(locale_path), 'CKAN-Browser', Qgis.Info) locale_path_en = os.path.join(self.plugin_dir, 'i18n', 'CKANBrowser_en.qm') # if we don't have translation for current locale, completely switch to English if not os.path.exists(locale_path): locale = 'en' locale_path = locale_path_en # if locale is not 'en' then additionally load 'en' as fallback for untranslated elements. # !!! this has to be done before(!) adding the actual locale: # https://doc.qt.io/qt-5/qcoreapplication.html#installTranslator # "Translations are searched for in the reverse order in which they were installed, so the most recently # installed translation file is searched first and the first translation file installed is searched last." if locale != 'en': QgsMessageLog.logMessage( u'loading "en" fallback: {}'.format(locale_path_en), 'CKAN-Browser', Qgis.Info) self.translator_en = QTranslator() self.translator_en.load(locale_path_en) if not QCoreApplication.installTranslator(self.translator_en): QgsMessageLog.logMessage( u'could not install translator: {}'.format(locale_path_en), 'CKAN-Browser', Qgis.Critical) else: QgsMessageLog.logMessage(u'locale "en" installed', 'CKAN-Browser', Qgis.Info) if os.path.exists(locale_path): self.translator = QTranslator() # load translations according to locale self.translator.load(locale_path) if not QCoreApplication.installTranslator(self.translator): QgsMessageLog.logMessage( u'could not install translator: {}'.format(locale_path), 'CKAN-Browser', Qgis.Critical) else: QgsMessageLog.logMessage( u'locale "{}" installed'.format(locale), 'CKAN-Browser', Qgis.Info) self.settings = Settings() self.settings.load() self.util = Util(self.settings, self.iface.mainWindow()) # TODO ping API # Create the dialog (after translation) and keep reference # self.dlg = CKANBrowserDialog(self.settings, self.iface, self.iface.mainWindow()) # Declare instance attributes self.actions = [] self.menu = self.util.tr(u'&Open Data (CKAN) Browser') # TODO: We are going to let the user set this up in a future iteration self.toolbar = self.iface.addToolBar(u'Open Data (CKAN) Browser') self.toolbar.setObjectName(u'Open Data (CKAN) Browser') 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 InaSAFE 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 = os.path.join(os.path.dirname(__file__), 'icon.png') self.add_action(icon_path, text=self.util.tr(u'Open Data (CKAN) Browser'), callback=self.run, parent=self.iface.mainWindow()) icon_settings = os.path.join(os.path.dirname(__file__), 'icon-settings.png') self.add_action(icon_settings, text=self.util.tr(u'ckan_browser_settings'), callback=self.open_settings, parent=self.iface.mainWindow()) def unload(self): """Removes the plugin menu item and icon from QGIS GUI.""" for action in self.actions: self.iface.removePluginMenu( self.util.tr(u'&Open Data (CKAN) Browser'), action) self.iface.removeToolBarIcon(action) def run(self): """Run method that performs all the real work""" is_open = QSettings().value("ckan_browser/isopen", False) #Python treats almost everything as True```` #is_open = bool(is_open) self.util.msg_log_debug(u'isopen: {0}'.format(is_open)) #!!!string comparison - Windows and Linux treat it as string, Mac as bool # so we convert string to bool if isinstance(is_open, str): is_open = self.util.str2bool(is_open) if is_open: self.util.msg_log_debug(u'Dialog already opened') return # auf URL testen dir_check = self.util.check_dir(self.settings.cache_dir) api_url_check = self.util.check_api_url(self.settings.ckan_url) if dir_check is False or api_url_check is False: dlg = CKANBrowserDialogSettings(self.settings, self.iface, self.iface.mainWindow()) dlg.show() result = dlg.exec_() if result != 1: return # self.util.msg_log('cache_dir: {0}'.format(self.settings.cache_dir)) try: QSettings().setValue("ckan_browser/isopen", True) self.dlg = CKANBrowserDialog(self.settings, self.iface, self.iface.mainWindow()) # show the dialog self.dlg.show() #self.dlg.open() # Run the dialog event loop result = self.dlg.exec_() # See if OK was pressed if result: # Do something useful here - delete the line containing pass and # substitute with your code. pass finally: QSettings().setValue("ckan_browser/isopen", False) def open_settings(self): dlg = CKANBrowserDialogSettings(self.settings, self.iface, self.iface.mainWindow()) dlg.show() dlg.exec_()
class YKRTool: """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', 'YKRTool_{}.qm'.format(locale)) 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'&Ilmastovaikutusten arviointityökalu') self.conn = None self.connParams = None self.tableNames = {} # Check if plugin was started the first time in current QGIS session # Must be set in initGui() to survive plugin reloads self.first_start = None self.mainDialog = uic.loadUi( os.path.join(self.plugin_dir, 'ykr_tool_main.ui')) self.settingsDialog = uic.loadUi( os.path.join(self.plugin_dir, 'ykr_tool_db_settings.ui')) # 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('YKRTool', 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: # Adds plugin icon to Plugins toolbar self.iface.addToolBarIcon(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/ykr_tool/icon.png' self.add_action(icon_path, text=self.tr(u'Ilmastovaikutusten arviointityökalu'), callback=self.run, parent=self.iface.mainWindow()) # will be set False in run() self.first_start = True def unload(self): """Removes the plugin menu item and icon from QGIS GUI.""" for action in self.actions: self.iface.removePluginMenu( self.tr(u'&Ilmastovaikutusten arviointityökalu'), action) self.iface.removeToolBarIcon(action) def run(self): """Run method that performs all the real work""" # Create the dialog with elements (after translation) and keep reference # Only create GUI ONCE in callback, so that it will only load when the plugin is started if self.first_start: self.first_start = False self.setupMainDialog() self.mainDialog.show() # Run the dialog event loop result = self.mainDialog.exec_() # See if OK was pressed if result: if not self.connParams: configFilePath = QSettings().value("/YKRTool/configFilePath",\ "", type=str) self.connParams = self.parseConfigFile(configFilePath) self.createDbConnection(self.connParams) self.sessionParams = self.generateSessionParameters() self.readProcessingInput() if not self.uploadData(): return self.runCalculations() self.cleanUp() def setupMainDialog(self): '''Sets up the main dialog''' self.mainDialog.geomArea.addItem("Tampere") self.mainDialog.adminArea.addItem("Pirkanmaa") self.mainDialog.pitkoScenario.addItems( ["wem", "eu80", "kasvu", "muutos", "saasto", "static"]) self.mainDialog.emissionsAllocation.addItems(["hjm", "em"]) self.mainDialog.elecEmissionType.addItems(["hankinta", "tuotanto"]) self.mainDialog.settingsButton.clicked.connect( self.displaySettingsDialog) self.mainDialog.ykrPopLayerList.hide() self.mainDialog.ykrJobsLayerList.hide() self.mainDialog.ykrBuildingsLayerList.hide() self.mainDialog.futureAreasLayerList.hide() self.mainDialog.futureNetworkLayerList.hide() self.mainDialog.futureStopsLayerList.hide() self.mainDialog.ykrPopLoadLayer.clicked.connect(self.handleLayerToggle) self.mainDialog.ykrJobsLoadLayer.clicked.connect( self.handleLayerToggle) self.mainDialog.ykrBuildingsLoadLayer.clicked.connect( self.handleLayerToggle) self.mainDialog.futureAreasLoadLayer.clicked.connect( self.handleLayerToggle) self.mainDialog.futureNetworkLoadLayer.clicked.connect( self.handleLayerToggle) self.mainDialog.futureStopsLoadLayer.clicked.connect( self.handleLayerToggle) self.mainDialog.calculateFuture.clicked.connect(self.handleLayerToggle) # Future calculations currently not supported self.mainDialog.calculateFuture.setEnabled(False) self.mainDialog.futureBox.setEnabled(False) def displaySettingsDialog(self): '''Sets up and displays the settings dialog''' self.settingsDialog.show() self.settingsDialog.configFileInput.setStorageMode( QgsFileWidget.GetFile) self.settingsDialog.configFileInput.setFilePath(QSettings().value\ ("/YKRTool/configFilePath", "", type=str)) self.settingsDialog.loadFileButton.clicked.connect( self.setConnectionParamsFromFile) result = self.settingsDialog.exec_() if result: self.connParams = self.readConnectionParamsFromInput() def setConnectionParamsFromFile(self): '''Reads connection parameters from file and sets them to the input fields''' filePath = self.settingsDialog.configFileInput.filePath() QSettings().setValue("/YKRTool/configFilePath", filePath) try: dbParams = self.parseConfigFile(filePath) except Exception as e: self.iface.messageBar().pushMessage('Virhe luettaessa tiedostoa',\ str(e), Qgis.Warning, duration=10) self.setConnectionParamsFromInput(dbParams) def parseConfigFile(self, filePath): '''Reads configuration file and returns parameters as a dict''' # Setup an empty dict with correct keys to avoid keyerrors dbParams = { 'host': '', 'port': '', 'database': '', 'user': '', 'password': '' } if not os.path.exists(filePath): self.iface.messageBar().pushMessage('Virhe', 'Tiedostoa ei voitu lukea',\ Qgis.Warning) return dbParams parser = ConfigParser() parser.read(filePath) if parser.has_section('postgresql'): params = parser.items('postgresql') for param in params: dbParams[param[0]] = param[1] else: self.iface.messageBar().pushMessage( 'Virhe', 'Tiedosto ei sisällä\ tietokannan yhteystietoja', Qgis.Warning) return dbParams def setConnectionParamsFromInput(self, params): '''Sets connection parameters to input fields''' self.settingsDialog.dbHost.setValue(params['host']) self.settingsDialog.dbPort.setValue(params['port']) self.settingsDialog.dbName.setValue(params['database']) self.settingsDialog.dbUser.setValue(params['user']) self.settingsDialog.dbPass.setText(params['password']) def readConnectionParamsFromInput(self): '''Reads connection parameters from user input and returns a dictionary''' params = {} params['host'] = self.settingsDialog.dbHost.value() params['port'] = self.settingsDialog.dbPort.value() params['database'] = self.settingsDialog.dbName.value() params['user'] = self.settingsDialog.dbUser.value() params['password'] = self.settingsDialog.dbPass.text() return params def handleLayerToggle(self): '''Toggle UI components visibility based on selection''' if self.mainDialog.ykrPopLoadLayer.isChecked(): self.mainDialog.ykrPopLayerList.show() self.mainDialog.ykrPopFile.hide() else: self.mainDialog.ykrPopLayerList.hide() self.mainDialog.ykrPopFile.show() if self.mainDialog.ykrJobsLoadLayer.isChecked(): self.mainDialog.ykrJobsLayerList.show() self.mainDialog.ykrJobsFile.hide() else: self.mainDialog.ykrJobsLayerList.hide() self.mainDialog.ykrJobsFile.show() if self.mainDialog.ykrBuildingsLoadLayer.isChecked(): self.mainDialog.ykrBuildingsLayerList.show() self.mainDialog.ykrBuildingsFile.hide() else: self.mainDialog.ykrBuildingsLayerList.hide() self.mainDialog.ykrBuildingsFile.show() if self.mainDialog.futureAreasLoadLayer.isChecked(): self.mainDialog.futureAreasLayerList.show() self.mainDialog.futureAreasFile.hide() else: self.mainDialog.futureAreasLayerList.hide() self.mainDialog.futureAreasFile.show() if self.mainDialog.futureNetworkLoadLayer.isChecked(): self.mainDialog.futureNetworkLayerList.show() self.mainDialog.futureNetworkFile.hide() else: self.mainDialog.futureNetworkLayerList.hide() self.mainDialog.futureNetworkFile.show() if self.mainDialog.futureStopsLoadLayer.isChecked(): self.mainDialog.futureStopsLayerList.show() self.mainDialog.futureStopsFile.hide() else: self.mainDialog.futureStopsLayerList.hide() self.mainDialog.futureStopsFile.show() if self.mainDialog.calculateFuture.isChecked(): self.mainDialog.futureBox.setEnabled(True) else: self.mainDialog.futureBox.setEnabled(False) def createDbConnection(self, connParams): '''Creates a database connection and cursor based on connection params''' QgsMessageLog.logMessage(str(self.connParams), "YKRTool", Qgis.Info) if '' in list(connParams.values()): self.iface.messageBar().pushMessage('Virhe yhdistäessä tietokantaan',\ 'Täytä puuttuvat yhteystiedot', Qgis.Critical) return False try: self.conn = psycopg2.connect(host=connParams['host'],\ port=connParams['port'], database=connParams['database'],\ user=connParams['user'], password=connParams['password'],\ connect_timeout=3) self.cur = self.conn.cursor() except Exception as e: self.iface.messageBar().pushMessage('Virhe yhdistäessä tietokantaan',\ str(e), Qgis.Critical, duration=10) return False def generateSessionParameters(self): '''Get necessary values for processing session''' sessionParams = {} usr = getpass.getuser() sessionParams["user"] = usr.replace(" ", "_") now = datetime.datetime.now() sessionParams["startTime"] = now.strftime("%Y%m%d_%H%M%S") sessionParams["baseYear"] = now.year sessionParams["uuid"] = str(uuid.uuid4()) return sessionParams def readProcessingInput(self): '''Read user input from main dialog''' if self.mainDialog.ykrPopLoadLayer.isChecked(): self.ykrPopLayer = self.mainDialog.ykrPopLayerList.currentLayer() else: self.ykrPopLayer = QgsVectorLayer(self.mainDialog.\ ykrPopFile.filePath(), "ykr_vaesto_2017", "ogr") if self.mainDialog.ykrBuildingsLoadLayer.isChecked(): self.ykrBuildingsLayer = self.mainDialog.ykrBuildingsLayerList.currentLayer( ) else: self.ykrBuildingsLayer = QgsVectorLayer(self.mainDialog.\ ykrBuildingsFile.filePath(), "pir_rakennukset_2017_piste", "ogr") if self.mainDialog.ykrJobsLoadLayer.isChecked(): self.ykrJobsLayer = self.mainDialog.ykrJobsLayerList.currentLayer() else: self.ykrJobsLayer = QgsVectorLayer(self.mainDialog.\ ykrJobsFile.filePath(), "ykr_tyopaikat_2015", "ogr") def uploadData(self): '''Check if layers are valid and write to database''' if not self.checkLayerValidity(): return False params = { 'INPUT': '', 'SHAPE_ENCODING': '', 'GTYPE': 5, # 3 for point, 5 for polygon 'A_SRS': QgsCoordinateReferenceSystem('EPSG:3067'), 'T_SRS': None, 'S_SRS': None, 'HOST': self.connParams['host'], 'PORT': self.connParams['port'], 'USER': self.connParams['user'], 'DBNAME': self.connParams['database'], 'PASSWORD': self.connParams['password'], 'SCHEMA': 'user_input', 'TABLE': '', 'PK': 'fid', 'PRIMARY_KEY': None, 'GEOCOLUMN': 'geom', 'DIM': 0, 'FIELDS': [], 'LAUNDER': False, 'INDEX': False, 'SKIPFAILURES': False, 'PROMOTETOMULTI': False, 'PRECISION': True } for layer in [ self.ykrBuildingsLayer, self.ykrJobsLayer, self.ykrPopLayer ]: params['INPUT'] = layer tableName = self.sessionParams['uuid'] + '_' + layer.name() tableName = tableName.replace('-', '_') params[ 'TABLE'] = tableName[: 49] # Truncate tablename to avoid hitting postgres 63char cap if layer.geometryType() == 0: # point params['GTYPE'] = 3 elif layer.geometryType() == 2: # polygon params['GTYPE'] = 5 processing.run("gdal:importvectorintopostgisdatabasenewconnection", params) self.tableNames[layer] = params['TABLE'] return True def checkLayerValidity(self): '''Checks that the layers are valid and raises an exception if necessary''' try: if not self.ykrPopLayer.isValid(): raise Exception( "Virhe ladattaessa nykytilanteen YKR-väestötasoa") if not self.ykrBuildingsLayer.isValid(): raise Exception( "Virhe ladattaessa nykytilanteen YKR-rakennustasoa") if not self.ykrJobsLayer.isValid(): print(abcdeft) raise Exception( "Virhe ladattaessa nykytilanteen YKR-työpaikkatasoa") if self.mainDialog.calculateFuture.isChecked(): if not self.futureAreasLayer.isValid(): raise Exception( "Virhe ladattaessa tulevaisuuden aluevaraustietoja") if self.futureNetworkLayer: if not self.futureNetworkLayer.isValid(): raise Exception( "Virhe ladattaessa keskusverkkotietoja") if self.futureStopsLayer: if not self.futureStopsLayer.isValid(): raise Exception( "Virhe ladattaessa joukkoliikennepysäkkitietoja") return True except Exception as e: self.iface.messageBar().pushMessage('Virhe ladattaessa tasoja', str(e), Qgis.Critical) return False def runCalculations(self): '''Call necessary processing functions in database''' vals = { 'uuid': self.sessionParams['uuid'], 'popLayer': self.tableNames[self.ykrPopLayer], 'jobLayer': self.tableNames[self.ykrJobsLayer] } query = '''CREATE TABLE user_input."ykr_{uuid}" AS SELECT * FROM il_preprocess('user_input.tutkimusalue_uuid','{popLayer}','{jobLayer}')'''.format( **vals) self.cur.execute(query) query = 'ALTER TABLE user_input."ykr_{uuid}" ADD PRIMARY KEY (xyind)'.format( **vals) self.cur.execute(query) query = 'CREATE INDEX "ykr_{uuid}_gidx" ON user_input."ykr_{uuid}" USING GIST(geom)'.format( **vals) self.cur.execute(query) def cleanUp(self): '''Delete temporary data and close db connection''' for table in list(self.tableNames.values()): self.cur.execute('DROP TABLE user_input."' + table + '"') self.conn.commit() self.conn.close() self.iface.messageBar().pushMessage('Valmis', 'Laskentasessio ' +\ str(self.sessionParams['uuid']) + ' on valmis', Qgis.Success)
class Master: """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', 'Master_{}.qm'.format(locale)) if os.path.exists(locale_path): self.translator = QTranslator() self.translator.load(locale_path) if qVersion() > '4.3.3': QCoreApplication.installTranslator(self.translator) # Create the dialog (after translation) and keep reference self.dlg = MasterDialog(parent=iface.mainWindow()) self.banderaInicial = True var = QSettings() if var.value('logeado') == 'True': # Declare instance attributes self.actions = [] self.menu = self.tr(u'&Master') # TODO: We are going to let the user set this up in a future iteration self.toolbar = self.iface.addToolBar(u'Master') self.toolbar.setObjectName(u'Master') self.CFG = Configuracion.Configuracion() self.UTI = utilidades.Utilidad() self.UTI.CFG = self.CFG self.headers = {'Content-Type': 'application/json'} # consulta informacion del usuario logueado usuario = self.UTI.decodeRot13(QSettings().value('usuario')) #print(usuario) var = QSettings() token = var.value('token') # se decodifica el token (JWT) decode = jwt.decode(token, verify=False) #print(decode) resultado = self.consumeWSGeneral( url_cons=self.CFG.url_MA_getInfoUser + str(decode['user_name'])) #print(resultado) if not resultado: return self.dlg.btnAsigTareas.hide() #self.dlg.btnUpload.hide() var.setValue("datoUsuario", resultado) # obtiene todos los permisos del usuario # ----- P E N D I E N T E ---- #self.dlg.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint) #self.CFG = Configuracion # Consulta de cartografia self.ACA = ActualizacionCatastralV3.ActualizacionCatastralV3(iface) self.UTI.ACA = self.ACA #Subir shapes self.SHP = subir_shape.SubirShape(iface) # Division y fusion self.DFS = DivisionFusion.DivisionFusion(iface, self.ACA) # Dibujo self.DBJ = DibujoV3.DibujoV3(iface) # Eliminacion de geometrias self.ELM = EliminacionV3.EliminacionV3(iface) # Verificacion de Topologias self.TPG = TopologiaV3.TopologiaV3(iface, self.ACA, self.CFG, self.UTI) # Integracion (Carga masiva) self.CMS = Integracion.Integracion(iface) # Asignaciones de campo, revision y padron self.ASCM = AsignacionCampo.AsignacionCampo(iface, self.UTI) self.ASRV = AsignacionRevision.AsignacionRevision(iface, self.UTI) self.ASPA = AsignacionPadron.AsignacionPadron(iface, self.UTI) # Intermediarios de asignaciones para Padron y gabinete self.INTEPAD = IntermedioCedulaRevision.IntermedioCedulaRevision( iface, self, 'PAD') self.INTEREV = IntermedioCedulaRevision.IntermedioCedulaRevision( iface, self, 'REV') #------------ DESACTIVAMOS LAS OPERACIONES Y MANDAMOS A VERIFICAR SUS ROLES self.comproveRoles() self.asignActionsByRoles(iface) # ------------ EVENTO DE BOTONES ------------- self.dlg.btnAsigTareas.clicked.connect(self.irAAsignaTareas) self.dlg.btnConsulta.clicked.connect(self.irAConsulta) self.dlg.btnDibujo.clicked.connect(self.irADibujo) self.dlg.btnEliminar.clicked.connect(self.irAEliminar) self.dlg.btnTopologia.clicked.connect(self.irATopologia) self.dlg.btnFusDiv.clicked.connect(self.irAFusionDivision) self.dlg.btnCargaMasiva.clicked.connect(self.irACargaMasiva) self.dlg.btnAsigCampo.clicked.connect(self.irAAsignacionCampo) self.dlg.btnAsigRev.clicked.connect(self.irAAsignacionRevision) self.dlg.btnAsigPad.clicked.connect(self.irAAsignacionPadron) self.dlg.btnUpload.clicked.connect(self.irASubirShape) self.dlg.btnInterPad.clicked.connect(self.irAIntermediarioPad) self.dlg.btnInterRev.clicked.connect(self.irAIntermediarioRev) self.dlg.btnAdminUsers.clicked.connect(self.irAAdminUsuarios) #self.dlg.btnAsigCampo.setEnabled(False) #self.dlg.btnAsigRev.setEnabled(False) #---------METODO QUE DESABILITA TODAS LAS ACCIONES DE LOS BOTONES def comproveRoles(self): # ------------ PRUEBA PARA DESHABILITAR LOS BOTONES ------- self.dlg.btnAsigTareas.setEnabled(False) self.dlg.btnConsulta.setEnabled(False) self.dlg.btnDibujo.setEnabled(False) self.dlg.btnEliminar.setEnabled(False) self.dlg.btnTopologia.setEnabled(False) self.dlg.btnFusDiv.setEnabled(False) self.dlg.btnCargaMasiva.setEnabled(False) self.dlg.btnAsigCampo.setEnabled(False) self.dlg.btnAsigRev.setEnabled(False) self.dlg.btnAsigPad.setEnabled(False) self.dlg.btnInterPad.setEnabled(False) self.dlg.btnInterRev.setEnabled(False) self.dlg.btnAdminUsers.setEnabled(False) #--------MEOTOD QUE COMPRUEBA LAS VERIIFCACIONES DE LOS BOTONES def asignActionsByRoles(self, iface): var = QSettings() if var.value('logeado') == 'True': response = self.consumeWSGeneral(self.CFG.url_permisos) for rol in response["roles"]: if rol == 'ASIGNACION_TAREAS': self.dlg.btnAsigTareas.setEnabled(True) if rol == 'CONSULTA': self.dlg.btnConsulta.setEnabled(True) if rol == 'DIBUJO': self.dlg.btnDibujo.setEnabled(True) if rol == 'ELIMINAR': self.dlg.btnEliminar.setEnabled(True) if rol == 'TOPOLOGIA': self.dlg.btnTopologia.setEnabled(True) if rol == 'FUSION_SUBDIVISION': self.dlg.btnFusDiv.setEnabled(True) if rol == 'CARGA_MASIVA': self.dlg.btnCargaMasiva.setEnabled(True) if rol == 'ASIGNACION_CAMPO': self.dlg.btnAsigCampo.setEnabled(True) if rol == 'ASIGNACION_REVISION': self.dlg.btnAsigRev.setEnabled(True) if rol == 'ASIGNACION_PADRON': self.dlg.btnAsigPad.setEnabled(True) if rol == 'INTERMEDIO_REVISION': self.dlg.btnInterRev.setEnabled(True) if rol == 'INTERMEDIO_PADRON': self.dlg.btnInterPad.setEnabled(True) if rol == 'ADMIN_USERS': self.dlg.btnAdminUsers.setEnabled(True) else: self.comproveRoles() #------------------ no se hace nada con este metodo ----------------------------------- def borrar(self): # valida si ya se ha agregado el grupo root = QgsProject.instance().layerTreeRoot() group = root.findGroup('consulta') if group is None: root = QgsProject.instance().layerTreeRoot() root.addGroup('consulta') root.addGroup('referencia') # nuevaCapa = QgsVectorLayer(QSettings().value('sAreasInscritas'), 'areas_inscritas', 'memory') listNC = [] listNC.append( QgsVectorLayer(QSettings().value('sAreasInscritas'), 'areas_inscritas', 'memory')) listNC.append( QgsVectorLayer(QSettings().value('sCvesVert'), 'cves_verticales', 'memory')) listNC.append( QgsVectorLayer(QSettings().value('sVert'), 'verticales', 'memory')) listNC.append( QgsVectorLayer(QSettings().value('sHoriNum'), 'horizontales.num', 'memory')) listNC.append( QgsVectorLayer(QSettings().value('sHoriGeom'), 'horizontales.geom', 'memory')) listNC.append( QgsVectorLayer(QSettings().value('sConst'), 'construcciones', 'memory')) listNC.append( QgsVectorLayer(QSettings().value('sPredNum'), 'predios.num', 'memory')) listNC.append( QgsVectorLayer(QSettings().value('sPredGeom'), 'predios.geom', 'memory')) listNC.append( QgsVectorLayer(QSettings().value('sManzana'), 'manzana', 'memory')) root = QgsProject.instance().layerTreeRoot() group = root.findGroup('consulta') for l in listNC: self.UTI.formatoCapa(l.name(), l) QgsProject.instance().addMapLayers([l], False) capaArbol = QgsLayerTreeLayer(l) group.insertChildNode(0, capaArbol) # 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('Master', 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/Master/icon.png' var = QSettings() if var.value('logeado') == 'True': self.add_action(icon_path, text=self.tr(u'Master'), callback=self.run, parent=self.iface.mainWindow()) #----------------------------------------------------- def unload(self): """Removes the plugin menu item and icon from QGIS GUI.""" for action in self.actions: self.iface.removePluginMenu(self.tr(u'&Master'), action) self.iface.removeToolBarIcon(action) # remove the toolbar del self.toolbar #----------------------------------------------------- def run(self): """Run method that performs all the real work""" #self.irAConsulta() #self.ACA.UTI = self.UTI #self.ACA.pintarCapas() #self.irAFusionDivision() ''' if self.banderaInicial: capaManzana = QgsProject.instance().mapLayer(self.ACA.obtenerIdCapa('manzana')) capaPredsG = QgsProject.instance().mapLayer(self.ACA.obtenerIdCapa('predios.geom')) capaPredN = QgsProject.instance().mapLayer(self.ACA.obtenerIdCapa('predios.num')) capaConst = QgsProject.instance().mapLayer(self.ACA.obtenerIdCapa('construcciones')) capaHoriG = QgsProject.instance().mapLayer(self.ACA.obtenerIdCapa('horizontales.geom')) capaHoriN = QgsProject.instance().mapLayer(self.ACA.obtenerIdCapa('horizontales.num')) capaVert = QgsProject.instance().mapLayer(self.ACA.obtenerIdCapa('verticales')) capaCvert = QgsProject.instance().mapLayer(self.ACA.obtenerIdCapa('cves_verticales')) self.banderaInicial = False '' ' capaManzana.selectionChanged.connect(self.ELM.cargarEliminar) capaPredsG.selectionChanged.connect(self.ELM.cargarEliminar) capaPredN.selectionChanged.connect(self.ELM.cargarEliminar) capaConst.selectionChanged.connect(self.ELM.cargarEliminar) capaHoriG.selectionChanged.connect(self.ELM.cargarEliminar) capaHoriN.selectionChanged.connect(self.ELM.cargarEliminar) capaVert.selectionChanged.connect(self.ELM.cargarEliminar) capaCvert.selectionChanged.connect(self.ELM.cargarEliminar) ''' # show the dialog #self.irAConsulta() #self.ACA.pintarCapas() self.dlg.show() # Run the dialog event loop result = self.dlg.exec_() # See if OK was pressed #self.irAConsulta() if result: # Do something useful here - delete the line containing pass and # substitute with your code. pass #----------------------------------------------------------------------- def irAAsignaTareas(self): # Asignacion de tareas self.AST = AsignaTareas.AsignaTareas(iface) self.AST.CFG = self.CFG self.AST.UTI = self.UTI self.AST.run() #----------------------------------------------------------------------- def irAConsulta(self): self.ACA.CFG = self.CFG self.ACA.UTI = self.UTI self.ACA.DFS = self.DFS self.ACA.DBJ = self.ACA self.ACA.ELM = self.ELM self.ACA.DFS = self.DFS self.ACA.TPG = self.TPG self.ACA.CMS = self.CMS self.ACA.run() #-------------------------------------------------------------------------- def irADibujo(self): self.DBJ.CFG = self.CFG self.DBJ.UTI = self.UTI self.DBJ.DFS = self.DFS self.DBJ.ACA = self.ACA self.DBJ.ELM = self.ELM self.DBJ.DFS = self.DFS self.DBJ.TPG = self.TPG self.DBJ.run() #------------------------------------------------------------------------ def irAEliminar(self): self.ELM.CFG = self.CFG self.ELM.UTI = self.UTI self.ELM.DFS = self.DFS self.ELM.DBJ = self.DBJ self.ELM.ACA = self.ACA self.ELM.DFS = self.DFS self.ELM.TPG = self.TPG self.ELM.run() #----------------------------------------------------------------------------- def irATopologia(self): #self.TPG.CFG = self.CFG #self.TPG.UTI = self.UTI self.TPG.DFS = self.DFS self.TPG.DBJ = self.DBJ self.TPG.ELM = self.ELM self.TPG.DFS = self.DFS self.TPG.CMS = self.CMS self.TPG.run() #-------------------------------------------------------------------------- def irAFusionDivision(self): self.DFS.CFG = self.CFG self.DFS.UTI = self.UTI self.DFS.DFS = self.DFS self.DFS.DBJ = self.DBJ self.DFS.ELM = self.ELM self.DFS.ACA = self.ACA self.DFS.TPG = self.TPG self.DFS.run() ############################################################################## def irACargaMasiva(self): self.CMS.UTI = self.UTI self.CMS.ACA = self.ACA self.CMS.run() ############################################################################## def irASubirShape(self): self.SHP.UTI = self.UTI self.SHP.ACA = self.ACA self.SHP.CFG = self.CFG self.SHP.run() ############################################################################### def irAAsignacionCampo(self): self.ASCM.CFG = self.CFG self.ASCM.ACA = self.ACA self.ASCM.run() #################################################################################### def irAAsignacionRevision(self): self.ASRV.CFG = self.CFG self.ASRV.ACA = self.ACA self.ASRV.run() #################################################################################### def irAAsignacionPadron(self): self.ASPA.CFG = self.CFG self.ASPA.ACA = self.ACA self.ASPA.run() #################################################################################### def irAIntermediarioPad(self): self.INTEPAD.CFG = self.CFG self.INTEPAD.ACA = self.ACA self.INTEPAD.UTI = self.UTI self.INTEPAD.run() #################################################################################### def irAIntermediarioRev(self): self.INTEREV.CFG = self.CFG self.INTEREV.ACA = self.ACA self.INTEREV.UTI = self.UTI self.INTEREV.run() #################################################################################### def irAAdminUsuarios(self): #Administracion de usuarios self.ADU = AdminUsers.AdminUsers(iface) self.ADU.CFG = self.CFG self.ADU.UTI = self.UTI self.ADU.run() # --- S E R V I C I O S W E B --- # - consume ws def consumeWSGeneral(self, url_cons=""): url = url_cons data = "" try: self.headers['Authorization'] = self.UTI.obtenerToken() #jwt.decode(self.UTI.obtenerToken(), "JWT", algorithms=['RS256']) #print(self.UTI.obtenerToken().encode().decode("RS256")) #var = QSettings() #token = var.value('token') # se decodifica el token (JWT) #decode = jwt.decode(token, verify=False) #print(decode) response = requests.get(url, headers=self.headers) except requests.exceptions.RequestException as e: self.UTI.mostrarAlerta( "Error de servidor, 'consumeWSGeneral(Master)' '" + str(e) + "'", QMessageBox().Critical, "Error de servidor") return if response.status_code == 200: data = response.content elif response.status_code == 403: self.UTI.mostrarAlerta('Sin Permisos para ejecutar la accion', QMessageBox().Critical, "Sistema Cartográfico") return None else: self.UTI.mostrarAlerta( 'Error en peticion "consumeWSGeneral(Master)":\n' + response.text, QMessageBox().Critical, "Error de servidor") return #print(json.loads(data.decode("utf-8"))) return json.loads(data.decode("utf-8"))
class TopoUSM2: def __init__(self, iface): # 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', 'TopoUSM2_{}.qm'.format(locale)) if os.path.exists(locale_path): self.translator = QTranslator() self.translator.load(locale_path) if qVersion() > '4.3.3': QCoreApplication.installTranslator(self.translator) # Create the dialog (after translation) and keep reference self.dlg = TopoUSM2Dialog() # Declare instance attributes self.actions = [] self.menu = self.tr(u'&TopoUSM2') # TODO: We are going to let the user set this up in a future iteration self.toolbar = self.iface.addToolBar(u'TopoUSM2') self.toolbar.setObjectName(u'TopoUSM2') ################################################################ ## Custom UIs ## ################################################################ self.usmlayers = [] ## Raster only in the Combo Manager for specifying input layer self.dlg.mMapLayerComboBox.setFilters( QgsMapLayerProxyModel.RasterLayer) ## Push run to trigger self.processing self.dlg.pushButton.clicked.connect(self.processing) ## Tab-changed action self.dlg.tabWidget.currentChanged.connect(self.tabChanged) ## Tables self.model = QStandardItemModel() self.dlg.tableView.setModel(self.model) ## Textedit cursor self.cursor = self.dlg.textEdit.textCursor() ## Sliders self.dlg.horizontalSlider.valueChanged.connect(self.slider1Changed) self.dlg.horizontalSlider_2.valueChanged.connect(self.slider2Changed) ## Push to apply styles self.dlg.pushButton_2.clicked.connect(self.doApply_styles_USMs) # 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('TopoUSM2', 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/topousm2/icon.png' self.add_action(icon_path, text=self.tr(u'Create TopoUSM layer'), callback=self.run, parent=self.iface.mainWindow()) def unload(self): """Removes the plugin menu item and icon from QGIS GUI.""" for action in self.actions: self.iface.removePluginMenu(self.tr(u'&TopoUSM2'), action) self.iface.removeToolBarIcon(action) # remove the toolbar del self.toolbar def run(self): """Run method that performs all the real work""" # show the dialog self.dlg.show() # Run the dialog event loop result = self.dlg.exec_() # See if OK was pressed if result: pass ### Custom event functions @@@@ def slider1Changed(self): val1 = self.dlg.horizontalSlider.value() self.dlg.label_11.setText('%.2f' % (float(val1) * 0.1)) self.doTableRefresh() def slider2Changed(self): val2 = self.dlg.horizontalSlider_2.value() self.dlg.label_13.setText('%.2f' % (10**(float(val2) / 10))) self.doTableRefresh() def usm_cap(self, r): val1, val2 = self.dlg.horizontalSlider.value( ), self.dlg.horizontalSlider_2.value() a = float(val1) * 0.1 b = 10**(float(val2) / 10) return (r**a) * b def tabChanged(self, i): if i == 1: self.doTableRefresh() def doTableRefresh(self): ## Find usmfiles if self.usmlayers: usmfiles = [ usmlayer.dataProvider().dataSourceUri() for usmlayer in self.usmlayers ] else: usmfiles = self.find_usmfiles() ## Make it a table radius, self.amps = [], [] radius = [self.fname2usmradius(usmfile) for usmfile in usmfiles] amps = [('%.2f' % self.usm_cap(r)) for r in radius] fnames = [os.path.basename(usmfile) for usmfile in usmfiles] DB = c_[radius, amps, fnames, usmfiles] DB = sorted(DB, key=lambda r: r[0]) self.model.clear() self.model.setHorizontalHeaderLabels(['radius', 'cap', 'Name', 'Path']) for item in DB: self.model.appendRow([QStandardItem(vals) for vals in item]) def __log__(self, text, end='\n'): self.dlg.textEdit.append(text + end) self.cursor.movePosition(QTextCursor.End) self.dlg.textEdit.setTextCursor(self.cursor) def fname2usmradius(self, fname): return int(fname[fname.rindex('_') + 8:fname.rindex('.')]) def find_usmfiles(self, fname='auto'): if fname == 'auto': srclayer = self.dlg.mMapLayerComboBox.currentLayer() if not srclayer: return fname = srclayer.dataProvider().dataSourceUri() fbody = fname[:fname.rindex('.')] ## Get filename without extention usmfiles = glob.glob(fbody + '_TopoUSM*.tif') usmfiles = [ usmfile for usmfile in usmfiles if ('Composite' not in usmfile) and ('Blurred' not in usmfile) ] return usmfiles def doApply_styles_USMs(self): if not self.usmlayers: usmfiles = self.find_usmfiles() for usmfile in usmfiles: self.usmlayers.append(self.iface.addRasterLayer(usmfile)) for usmlayer in self.usmlayers: self.apply_styles(usmlayer) def apply_styles(self, layer, cap=None): if not layer: return fname = os.path.basename(layer.dataProvider().dataSourceUri()) if cap == None: if ('Composite' not in fname) and ('Blurred' not in fname): radius = self.fname2usmradius(fname) cap = self.usm_cap(radius) ## Pesudocolor method <- It works except legend ## #shader, colorramp = QgsRasterShader(), QgsColorRampShader() #colorramp.setClassificationMode(1) #colorramp.setColorRampType(QgsColorRampShader.Interpolated) #colorramp.setColorRampItemList([ \ # QgsColorRampShader.ColorRampItem(-100, QColor(0,0,0)), \ # QgsColorRampShader.ColorRampItem(100, QColor(255,255,255))]) #shader.setRasterShaderFunction(colorramp) #render = QgsSingleBandPseudoColorRenderer(usmlayer.dataProvider(), usmlayer.type(), shader) #usmlayer.setRenderer(render) #usmlayer.renderer().setClassificationMin(-100) #usmlayer.renderer().setClassificationMin(100) ## Grayscale method ## render = QgsSingleBandGrayRenderer(layer.dataProvider(), layer.type()) ## Create a custom QGIS style file (QML) path_defaultQML = os.path.join( os.path.dirname(os.path.realpath(__file__)), 'USM_styletemplate.qml') path_tmpQML = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'tmp.qml') tree = ET.parse(path_defaultQML) root = tree.getroot() minval = root.find( './pipe/rasterrenderer/contrastEnhancement/minValue') maxval = root.find( './pipe/rasterrenderer/contrastEnhancement/maxValue') minval.text, maxval.text = str(-1 * cap), str(cap) tree.write(path_tmpQML) ## Another failed atteampt to set minmax #fp = QFile(path_tmpQML); fp.open(QIODevice.ReadOnly) #doc = QDomDocument(); doc.setContent(fp); fp.close() #elem = doc.documentElement() #QDOMElement #contrast = QgsContrastEnhancement() #contrast.readXml(elem) #contrast.setContrastEnhancementAlgorithm(QgsContrastEnhancement.StretchToMinimumMaximum, False) #contrast.setMaximumValue(100, False); contrast.setMinimumValue(-100, True) # <- Completely broken #render.setContrastEnhancement(contrast) #render.setGradient(QgsSingleBandGrayRenderer.BlackToWhite) #usmlayer.setRenderer(render) ## Another failed attempt to set minmax ## #bounds = QgsRasterMinMaxOrigin() #bounds.setExtent(QgsRasterMinMaxOrigin.WholeRaster) #bounds.setLimits(QgsRasterMinMaxOrigin.StdDev) #bounds.setStatAccuracy(QgsRasterMinMaxOrigin.Estimated) #usmlayer.renderer().setMinMaxOrigin(bounds) ## Then import it to the layer layer.setBlendMode(QPainter.CompositionMode_Overlay) layer.loadNamedStyle(path_tmpQML) layer.setCrs(self.dlg.mMapLayerComboBox.currentLayer().crs()) layer.emitStyleChanged() # <- Broken? layer.triggerRepaint() def processing(self): ################################################################ ## Custom Ops ## ################################################################ srclayer = self.dlg.mMapLayerComboBox.currentLayer() if not srclayer: return srcfname = srclayer.dataProvider().dataSourceUri() if not os.path.exists(srcfname): return fbody = srcfname[:srcfname.rindex( '.')] ## Get filename without extention ## Disable interface during the processing self.dlg.pushButton.setEnabled(False) self.dlg.tabWidget.setEnabled(False) self.dlg.textEdit.clear() ## Setup handling of NaNs nodata = [] for val in self.dlg.lineEdit_3.text().split(','): if val == '$floatmin': nodata.append(sys.float_info.min) elif val == '$floatmax': nodata.append(sys.float_info.max) elif val == '$intmax': nodata.append(sys.maxsize) elif val == '$intmin': nodata.append(-sys.maxsize - 1) else: nodata.append(float(nodata)) bounds = [float(i) for i in self.dlg.lineEdit_2.text().split(',')] replacenan = nan if self.dlg.lineEdit_4.text() == 'NaN' else float( self.dlg.lineEdit_4.text()) ## Read source grid G = Grid(self.dlg, srcfname, nodata) self.__log__(G.fname) G.Z[G.Z < bounds[0]] = nan G.Z[G.Z > bounds[1]] = nan G.Z[isnan(G.Z)] = replacenan original_stdev = nanstd(G.Z) if self.dlg.tabWidget.currentIndex() == 0: ## TopoUSM processing ## radius = map(int, self.dlg.lineEdit.text().split(',')) iterations = int(self.dlg.mQgsSpinBox.value()) Z0 = G.Z.copy() ##Backup original array so that no need to reopen usmfiles = [] for r in radius: G.Z = Z0.copy() G.TopoUSM2(r, iterations) if self.dlg.checkBox_4.isChecked(): G.log10( amp=1 ) ## Apply logarithmic dynamic range compression if specified ## Save TopoUSM rasters fname = (fbody + '_TopoUSM%d.tif' % r) usmfiles.append(fname) if self.dlg.checkBox_2.isChecked(): G.save_asint16(fname, nodata=nan) else: G.save(fname, nodata=nan) if self.dlg.checkBox_3.isChecked(): ## Save blurred rasters if specified fname = (fbody + '_Blurred%d.tif' % r) usmfiles.append(fname) G.Z = G.Z_blurred G.save(fname, nodata=nan) self.__log__('T + %d seconds.' % (time() - G.timestart)) QMessageBox.information(self.dlg, "Done!", "Done!") G = None self.__log__('Following files were generated:\n' + '\n'.join(usmfiles)) self.__log__( 'Tips: After the completion, you may set optimal value ranges (e.g. -100,100) for each TopoUSM layers and then change the color blending mode to overlay or hardlight. Currently, automatically estimated values are set. Following layering is the quickest choice: Color gradation (Normal) > TopoUSM layers (hardlight) > hillshade, slope, or contours (multiply)' ) ## Open files after completion ## if self.dlg.checkBox.isChecked(): for usmfile in usmfiles: self.usmlayers.append(self.iface.addRasterLayer(usmfile)) elif self.dlg.tabWidget.currentIndex() == 1: ## TopoUSM stacking ## if self.usmlayers: usmfiles = [ usmlayer.dataProvider().dataSourceUri() for usmlayer in self.usmlayers ] else: usmfiles = self.find_usmfiles() outfile = srcfname[:srcfname.rindex('.' )] + '_TopoUSM-Composite.tif' radius = [self.fname2usmradius(usmfile) for usmfile in usmfiles] caps = [self.usm_cap(r) for r in radius] amps = [max(caps) / cap for cap in caps] G0 = Grid(self.dlg, usmfiles[0], nodata=[]) G0.Z[isnan(G0.Z)] = 0 Z = array(G0.Z.copy(), dtype=float) * amps[0] / len(amps) for i in arange(1, len(usmfiles)): self.__log__('[Stack] %s amp=%.2f' % (usmfiles[i], amps[i])) G1 = Grid(self.dlg, usmfiles[i], nodata=[nan]) G1.Z[isnan(G1.Z)] = 0 Z += G1.Z * amps[i] / len(amps) G0.Z = Z if self.dlg.checkBox_2.isChecked(): G0.save_asint16(outfile, nodata=nan) else: G0.save(outfile, nodata=nan) self.__log__('Composite USM file was successfully baked:\n' + outfile) if self.dlg.checkBox.isChecked(): composite_layer = self.iface.addRasterLayer(outfile) self.apply_styles(composite_layer, cap=max(caps)) G0, G1 = None, None ## Clear memory ##Enalbe interface ater the processing self.dlg.pushButton.setEnabled(True) self.dlg.tabWidget.setEnabled(True)
class CityJsonLoader: """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', 'CityJsonLoader_{}.qm'.format(locale)) if os.path.exists(locale_path): self.translator = QTranslator() self.translator.load(locale_path) if qVersion() > '4.3.3': QCoreApplication.installTranslator(self.translator) # Create the dialog (after translation) and keep reference self.dlg = CityJsonLoaderDialog() # Declare instance attributes self.actions = [] self.menu = self.tr(u'&CityJSON Loader') # TODO: We are going to let the user set this up in a future iteration self.toolbar = self.iface.addToolBar(u'CityJsonLoader') self.toolbar.setObjectName(u'CityJsonLoader') self.dlg.browseButton.clicked.connect(self.select_cityjson_file) def select_cityjson_file(self): filename, _ = QFileDialog.getOpenFileName(self.dlg, "Select CityJSON file", "", "*.json") self.dlg.cityjsonPathLineEdit.setText(filename) try: fstream = open(filename) model = cityjson.CityJSON(fstream) self.dlg.metadataInfoBox.setPlainText(model.get_info()) except: self.dlg.metadataInfoBox.setPlainText("File could not be loaded") # 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('CityJsonLoader', 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.addPluginToVectorMenu(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/cityjson_loader/cityjson_logo.png' self.add_action(icon_path, text=self.tr(u'Load CityJSON...'), callback=self.run, parent=self.iface.mainWindow()) def unload(self): """Removes the plugin menu item and icon from QGIS GUI.""" for action in self.actions: self.iface.removePluginVectorMenu(self.tr(u'&CityJSON Loader'), action) self.iface.removeToolBarIcon(action) # remove the toolbar del self.toolbar def get_attribute_keys(self, objs): atts = [] for key, obj in objs.items(): if "attributes" in obj: for att_key, att_value in obj["attributes"].items(): if not att_key in atts: atts.append(att_key) return atts def read_boundary(self, boundary, points): g = QgsPolygon() i = 0 for ring in boundary: poly = [] for index in ring: poly.append(points[index]) r = QgsLineString(poly) if i == 0: g.setExteriorRing(r) else: g.addInteriorRing(r) i = 1 return g def load_cityjson(self, filepath): file = open(filepath) city_model = cityjson.CityJSON(file) filename_with_ext = os.path.basename(filepath) filename, file_extension = os.path.splitext(filename_with_ext) geom_type = "MultiPolygon" if "crs" in city_model.j["metadata"]: geom_type = "{}?crs=EPSG:{}".format( geom_type, city_model.j["metadata"]["crs"]["epsg"]) multilayer = self.dlg.splitByTypeCheckBox.isChecked() city_objects = city_model.j["CityObjects"] # Setup the layer(s) vls = dict() if multilayer: # Identify object types present in the file types = set() for key, obj in city_objects.items(): types.add(city_objects[key]['type']) for t in types: vl = QgsVectorLayer(geom_type, "{} - {}".format(filename, t), "memory") vls[t] = vl else: vls["all"] = QgsVectorLayer(geom_type, filename, "memory") # Identify attributes present in the file att_keys = self.get_attribute_keys(city_objects) fields = [ QgsField("uid", QVariant.String), QgsField("type", QVariant.String) ] for att in att_keys: fields.append(QgsField("attribute.{}".format(att), QVariant.String)) # Setup attributes on the datasource(s) for vl_key, vl in vls.items(): pr = vl.dataProvider() pr.addAttributes(fields) vl.updateFields() # Prepare transformation parameters scale = (1, 1, 1) translate = (0, 0, 0) if "transform" in city_model.j: scale = city_model.j["transform"]["scale"] translate = city_model.j["transform"]["translate"] # Load the vertices list verts = city_model.j["vertices"] points = [] for v in verts: points.append( QgsPoint(v[0] * scale[0] + translate[0], v[1] * scale[1] + translate[1], v[2] * scale[2] + translate[2])) # A simple count of the skipped geometries skipped_geometries = 0 # Iterate through the city objects for key, obj in city_objects.items(): if multilayer: pr = vls[obj["type"]].dataProvider() else: pr = vls["all"].dataProvider() fet = QgsFeature(pr.fields()) fet["uid"] = key fet["type"] = obj["type"] # Load the attributes if "attributes" in obj: for att_key, att_value in obj["attributes"].items(): fet["attribute.{}".format(att_key)] = att_value # Load the geometries (only surfaces and solids, for now) geoms = QgsMultiPolygon() for geom in obj["geometry"]: if "Surface" in geom["type"]: for boundary in geom["boundaries"]: g = self.read_boundary(boundary, points) geoms.addGeometry(g) continue if geom["type"] == "Solid": for boundary in geom["boundaries"]: for solid in boundary: g = self.read_boundary(solid, points) geoms.addGeometry(g) continue skipped_geometries += 1 fet.setGeometry(QgsGeometry(geoms)) # Add feature to the provider pr.addFeature(fet) # Add the layer(s) to the project for vl_key, vl in vls.items(): QgsProject.instance().addMapLayer(vl) if with_3d: # Add the 3D symbol to the renderer material = QgsPhongMaterialSettings() material.setDiffuse(vl.renderer().symbol().color()) symbol = QgsPolygon3DSymbol() symbol.setMaterial(material) renderer = QgsVectorLayer3DRenderer() renderer.setLayer(vl) renderer.setSymbol(symbol) vl.setRenderer3D(renderer) # Show a message with the outcome of the loading process msg = QMessageBox() if skipped_geometries > 0: msg.setIcon(QMessageBox.Warning) msg.setText("CityJSON loaded with issues.") msg.setInformativeText("Some geometries were skipped.") msg.setDetailedText( "{} geometries were not surfaces or solids, so could not be loaded." .format(skipped_geometries)) else: msg.setIcon(QMessageBox.Information) msg.setText("CityJSON loaded successfully.") msg.setWindowTitle("CityJSON loading finished") msg.setStandardButtons(QMessageBox.Ok) msg.exec_() def run(self): """Run method that performs all the real work""" # show the dialog self.dlg.show() # Run the dialog event loop result = self.dlg.exec_() # See if OK was pressed if result: filepath = self.dlg.cityjsonPathLineEdit.text() self.load_cityjson(filepath)
class PreferencesWindow(Setting_Ui): def __init__(self, parent, persepolis_setting): super().__init__(persepolis_setting) self.persepolis_setting = persepolis_setting self.parent = parent self.grandparent = parent.persepolis_main self.persepolis_setting.beginGroup('settings') # initialization self.tries_spinBox.setValue( int(self.persepolis_setting.value('max-tries'))) self.wait_spinBox.setValue( int(self.persepolis_setting.value('retry-wait'))) self.time_out_spinBox.setValue( int(self.persepolis_setting.value('timeout'))) self.connections_spinBox.setValue( int(self.persepolis_setting.value('connections'))) self.rpc_port_spinbox.setValue( int(self.persepolis_setting.value('rpc-port'))) # add support for other languages locale = str(self.persepolis_setting.value('settings/locale')) QLocale.setDefault(QLocale(locale)) self.translator = QTranslator() if self.translator.load(':/translations/locales/ui_' + locale, 'ts'): QCoreApplication.installTranslator(self.translator) # wait_queue wait_queue_list = self.persepolis_setting.value('wait-queue') q_time = QTime(int(wait_queue_list[0]), int(wait_queue_list[1])) self.wait_queue_time.setTime(q_time) # change aria2 path self.aria2_path_pushButton.clicked.connect(self.changeAria2Path) self.aria2_path_checkBox.toggled.connect(self.ariaCheckBoxToggled) aria2_path = self.persepolis_setting.value('settings/aria2_path') self.aria2_path_lineEdit.setEnabled(False) if aria2_path != None: self.aria2_path_checkBox.setChecked(True) self.aria2_path_lineEdit.setText(str(aria2_path)) self.ariaCheckBoxToggled('aria2') if os_type == 'Linux' or os_type == 'FreeBSD' or os_type == 'OpenBSD': for widget in self.aria2_path_checkBox, self.aria2_path_lineEdit, self.aria2_path_pushButton: widget.hide() # save_as_tab self.download_folder_lineEdit.setText( str(self.persepolis_setting.value('download_path'))) self.temp_download_lineEdit.setText( str(self.persepolis_setting.value('download_path_temp'))) # subfolder if str(self.persepolis_setting.value('subfolder')) == 'yes': self.subfolder_checkBox.setChecked(True) else: self.subfolder_checkBox.setChecked(False) # notifications_tab self.volume_label.setText( 'Volume : ' + str(self.persepolis_setting.value('sound-volume'))) self.volume_dial.setValue( int(self.persepolis_setting.value('sound-volume'))) # set style # if style_comboBox is changed, self.styleComboBoxChanged is called. self.style_comboBox.currentIndexChanged.connect( self.styleComboBoxChanged) # find available styles(It's depends on operating system and desktop environments). available_styles = QStyleFactory.keys() for style in available_styles: self.style_comboBox.addItem(style) # System >> for system default style # when user select System for style section, the default system style is using. self.style_comboBox.addItem('System') current_style_index = self.style_comboBox.findText( str(self.persepolis_setting.value('style'))) if current_style_index != -1: self.style_comboBox.setCurrentIndex(current_style_index) # available language available_language = ['en_US', 'fa_IR', 'zh_CN', 'fr_FR'] for lang in available_language: self.lang_comboBox.addItem(str(QLocale(lang).nativeLanguageName()), lang) current_locale = self.lang_comboBox.findData( str(self.persepolis_setting.value('locale'))) self.lang_comboBox.setCurrentIndex(current_locale) # set color_scheme color_scheme = [ 'System', 'Persepolis Light Blue', 'Persepolis Dark Blue', 'Persepolis ArcDark Blue', 'Persepolis ArcDark Red', 'Persepolis Old Dark Red', 'Persepolis Old Light Red', 'Persepolis Old Dark Blue', 'Persepolis Old light Blue' ] self.color_comboBox.addItems(color_scheme) current_color_index = self.color_comboBox.findText( str(self.persepolis_setting.value('color-scheme'))) self.color_comboBox.setCurrentIndex(current_color_index) self.current_icon = self.persepolis_setting.value('icons') # icon size size = ['128', '64', '48', '32', '24', '16'] self.icons_size_comboBox.addItems(size) current_icons_size_index = self.icons_size_comboBox.findText( str(self.persepolis_setting.value('toolbar_icon_size'))) self.icons_size_comboBox.setCurrentIndex(current_icons_size_index) # call iconSizeComboBoxCanged if index is changed self.icons_size_comboBox.currentIndexChanged.connect( self.iconSizeComboBoxCanged) self.iconSizeComboBoxCanged(1) # set notification notifications = ['Native notification', 'QT notification'] self.notification_comboBox.addItems(notifications) current_notification_index = self.notification_comboBox.findText( str(self.persepolis_setting.value('notification'))) self.notification_comboBox.setCurrentIndex(current_notification_index) # set font font_setting = QFont() font_setting.setFamily(str(self.persepolis_setting.value('font'))) self.fontComboBox.setCurrentFont(font_setting) self.font_size_spinBox.setValue( int(self.persepolis_setting.value('font-size'))) # sound frame self.sound_frame.setEnabled(False) self.enable_notifications_checkBox.toggled.connect(self.soundFrame) if str(self.persepolis_setting.value('sound')) == 'yes': self.enable_notifications_checkBox.setChecked(True) else: self.enable_notifications_checkBox.setChecked(False) # connect folder buttons self.download_folder_lineEdit.setEnabled(False) self.download_folder_pushButton.clicked.connect( self.downloadFolderPushButtonClicked) self.temp_download_lineEdit.setEnabled(False) self.temp_download_pushButton.clicked.connect( self.tempDownloadPushButtonClicked) # dial self.volume_dial.setNotchesVisible(True) self.volume_dial.valueChanged.connect(self.dialChanged) # tray icon if str(self.persepolis_setting.value('tray-icon')) == 'yes': self.enable_system_tray_checkBox.setChecked(True) else: self.enable_notifications_checkBox.setChecked(False) # show_menubar if str(self.persepolis_setting.value('show-menubar')) == 'yes': self.show_menubar_checkbox.setChecked(True) else: self.show_menubar_checkbox.setChecked(False) if platform.system() == 'Darwin': self.show_menubar_checkbox.setChecked(True) self.show_menubar_checkbox.hide() # show_sidepanel if str(self.persepolis_setting.value('show-sidepanel')) == 'yes': self.show_sidepanel_checkbox.setChecked(True) else: self.show_sidepanel_checkbox.setChecked(False) # show ProgressWindow if str(self.persepolis_setting.value('show-progress')) == 'yes': self.show_progress_window_checkbox.setChecked(True) else: self.show_progress_window_checkbox.setChecked(False) # after download dialog if str(self.persepolis_setting.value('after-dialog')) == 'yes': self.after_download_checkBox.setChecked(True) else: self.after_download_checkBox.setChecked(False) # run persepolis at startup checkBox if str(self.persepolis_setting.value('startup')) == 'yes': self.startup_checkbox.setChecked(True) else: self.startup_checkbox.setChecked(False) # font_checkBox if str(self.persepolis_setting.value('custom-font')) == 'yes': self.font_checkBox.setChecked(True) else: self.font_checkBox.setChecked(False) self.fontCheckBoxState(self.font_checkBox) # keep_awake_checkBox if str(self.persepolis_setting.value('awake')) == 'yes': self.keep_awake_checkBox.setChecked(True) else: self.keep_awake_checkBox.setChecked(False) # columns_tab if str(self.persepolis_setting.value('column0')) == 'yes': self.column0_checkBox.setChecked(True) else: self.column0_checkBox.setChecked(False) if str(self.persepolis_setting.value('column1')) == 'yes': self.column1_checkBox.setChecked(True) else: self.column1_checkBox.setChecked(False) if str(self.persepolis_setting.value('column2')) == 'yes': self.column2_checkBox.setChecked(True) else: self.column2_checkBox.setChecked(False) if str(self.persepolis_setting.value('column3')) == 'yes': self.column3_checkBox.setChecked(True) else: self.column3_checkBox.setChecked(False) if str(self.persepolis_setting.value('column4')) == 'yes': self.column4_checkBox.setChecked(True) else: self.column4_checkBox.setChecked(False) if str(self.persepolis_setting.value('column5')) == 'yes': self.column5_checkBox.setChecked(True) else: self.column5_checkBox.setChecked(False) if str(self.persepolis_setting.value('column6')) == 'yes': self.column6_checkBox.setChecked(True) else: self.column6_checkBox.setChecked(False) if str(self.persepolis_setting.value('column7')) == 'yes': self.column7_checkBox.setChecked(True) else: self.column7_checkBox.setChecked(False) if str(self.persepolis_setting.value('column10')) == 'yes': self.column10_checkBox.setChecked(True) else: self.column10_checkBox.setChecked(False) if str(self.persepolis_setting.value('column11')) == 'yes': self.column11_checkBox.setChecked(True) else: self.column11_checkBox.setChecked(False) if str(self.persepolis_setting.value('column12')) == 'yes': self.column12_checkBox.setChecked(True) else: self.column12_checkBox.setChecked(False) # video_finder self.enable_video_finder_checkbox.stateChanged.connect( self.videoFinderFram) self.enable_video_finder_checkbox.setChecked( persepolis_setting.value('video_finder/enable', 'yes') == 'yes') self.hide_no_audio_checkbox.setChecked( persepolis_setting.value('video_finder/hide_no_audio') == 'yes') self.hide_no_video_checkbox.setChecked( persepolis_setting.value('video_finder/hide_no_video') == 'yes') try: # Integer casting may raise exception. self.max_links_spinBox.setValue( int(persepolis_setting.value('video_finder/max_links', 3))) except: pass self.videoFinderFram() # ok cancel default button self.cancel_pushButton.clicked.connect(self.close) self.defaults_pushButton.clicked.connect( self.defaultsPushButtonPressed) self.ok_pushButton.clicked.connect(self.okPushButtonPressed) # font_checkBox connect self.font_checkBox.stateChanged.connect(self.fontCheckBoxState) # saving initial value of self.persepolis_setting in self.first_key_value_dict # at the end! in the okPushButtonPressed method, first_key_value_dict will compared with second_key_value_dict. # if any thing changed , then a message box notify user about "some changes take effect after restarting persepolis". self.first_key_value_dict = {} for member in self.persepolis_setting.allKeys(): self.first_key_value_dict[member] = str( self.persepolis_setting.value(member)) self.persepolis_setting.endGroup() # setting window size and position size = self.persepolis_setting.value('PreferencesWindow/size', QSize(578, 565)) position = self.persepolis_setting.value('PreferencesWindow/position', QPoint(300, 300)) self.resize(size) self.move(position) # Papirus icons can be used with small sizes(smaller than 48) def iconSizeComboBoxCanged(self, index): self.icon_comboBox.clear() selected_size = int(self.icons_size_comboBox.currentText()) if selected_size < 48: # add Papirus-light and Papirus-Dark icons to the list icons = [ 'Archdroid-Red', 'Archdroid-Blue', 'Breeze', 'Breeze-Dark', 'Papirus', 'Papirus-Dark', 'Papirus-Light' ] self.icon_comboBox.addItems(icons) current_icons_index = self.icon_comboBox.findText( str(self.persepolis_setting.value('icons', self.current_icon))) else: # eliminate Papirus-light and Papirus-Dark from list icons = [ 'Archdroid-Red', 'Archdroid-Blue', 'Breeze', 'Breeze-Dark', 'Papirus' ] self.icon_comboBox.addItems(icons) # current_icons_index is -1, if findText couldn't find icon index. current_icons_index = self.icon_comboBox.findText( str(self.persepolis_setting.value('icons', self.current_icon))) # set 'Archdroid-Blue' if current_icons_index is -1 if current_icons_index == -1: current_icons_index = 1 self.icon_comboBox.setCurrentIndex(current_icons_index) # active color_comboBox only when user is select "Fusion" style. def styleComboBoxChanged(self, index): selected_style = self.style_comboBox.currentText() if selected_style != 'Fusion': current_color_index = self.color_comboBox.findText('System') self.color_comboBox.setCurrentIndex(current_color_index) # disable color_comboBox self.color_comboBox.setEnabled(False) else: # enable color_comboBox self.color_comboBox.setEnabled(True) def fontCheckBoxState(self, checkBox): # deactive fontComboBox and font_size_spinBox if font_checkBox not checked! if self.font_checkBox.isChecked(): self.fontComboBox.setEnabled(True) self.font_size_spinBox.setEnabled(True) else: self.fontComboBox.setEnabled(False) self.font_size_spinBox.setEnabled(False) def closeEvent(self, event): # saving window size and position self.persepolis_setting.setValue('PreferencesWindow/size', self.size()) self.persepolis_setting.setValue('PreferencesWindow/position', self.pos()) self.persepolis_setting.sync() self.destroy() if self.parent.isVisible() == False: self.parent.minMaxTray(event) self.close() def soundFrame(self, checkBox): if self.enable_notifications_checkBox.isChecked(): self.sound_frame.setEnabled(True) else: self.sound_frame.setEnabled(False) def ariaCheckBoxToggled(self, checkBox): if self.aria2_path_checkBox.isChecked(): self.aria2_path_pushButton.setEnabled(True) else: self.aria2_path_pushButton.setEnabled(False) def changeAria2Path(self, button): cwd = sys.argv[0] cwd = os.path.dirname(cwd) f_path, filters = QFileDialog.getOpenFileName(self, 'Select aria2 path', cwd) # if path is correct: if os.path.isfile(str(f_path)): self.aria2_path_lineEdit.setText(str(f_path)) else: self.aria2_path_checkBox.setChecked(False) def downloadFolderPushButtonClicked(self, button): download_path = str( self.persepolis_setting.value('settings/download_path')) fname = QFileDialog.getExistingDirectory(self, 'Select a directory', download_path) if fname: # Returns pathName with the '/' separators converted to separators that are appropriate for the underlying operating system. # On Windows, toNativeSeparators("c:/winnt/system32") returns # "c:\winnt\system32". fname = QDir.toNativeSeparators(fname) self.download_folder_lineEdit.setText(fname) self.persepolis_setting.setValue('settings/download_path', str(fname)) def tempDownloadPushButtonClicked(self, button): download_path_temp = str( self.persepolis_setting.value('settings/download_path_temp')) fname = QFileDialog.getExistingDirectory(self, 'Open f', download_path_temp) if fname: self.temp_download_lineEdit.setText(fname) self.persepolis_setting.setValue('settings/download_path_temp', str(fname)) def dialChanged(self, dial): self.volume_label.setText('Volume : ' + str(self.volume_dial.value())) def defaultsPushButtonPressed(self, button): self.persepolis_setting.beginGroup('settings') self.setting_dict = returnDefaultSettings() self.tries_spinBox.setValue(int(self.setting_dict['max-tries'])) self.wait_spinBox.setValue(int(self.setting_dict['retry-wait'])) self.time_out_spinBox.setValue(int(self.setting_dict['timeout'])) self.connections_spinBox.setValue(int( self.setting_dict['connections'])) self.rpc_port_spinbox.setValue(int(self.setting_dict['rpc-port'])) self.aria2_path_lineEdit.setText('') self.aria2_path_checkBox.setChecked(False) # wait-queue wait_queue_list = self.setting_dict['wait-queue'] q_time = QTime(wait_queue_list[0], wait_queue_list[1]) self.wait_queue_time.setTime(q_time) # save_as_tab self.download_folder_lineEdit.setText( str(self.setting_dict['download_path'])) self.temp_download_lineEdit.setText( str(self.setting_dict['download_path_temp'])) self.subfolder_checkBox.setChecked(True) # notifications_tab self.volume_label.setText('Volume : ' + str(self.setting_dict['sound-volume'])) self.volume_dial.setValue(int(self.setting_dict['sound-volume'])) # set style current_style_index = self.style_comboBox.findText( str(self.setting_dict['style'])) self.style_comboBox.setCurrentIndex(current_style_index) # set language current_locale = self.lang_comboBox.findData( str(self.setting_dict['locale'])) self.lang_comboBox.setCurrentIndex(current_locale) # set color_scheme current_color_index = self.color_comboBox.findText( str(self.setting_dict['color-scheme'])) self.color_comboBox.setCurrentIndex(current_color_index) # set icons current_icons_index = self.icon_comboBox.findText( str(self.setting_dict['icons'])) self.icon_comboBox.setCurrentIndex(current_icons_index) # set icons size current_icons_size_index = self.icons_size_comboBox.findText( str(self.setting_dict['toolbar_icon_size'])) self.icons_size_comboBox.setCurrentIndex(current_icons_size_index) # set notification current_notification_index = self.notification_comboBox.findText( str(self.setting_dict['notification'])) self.notification_comboBox.setCurrentIndex(current_notification_index) # set font self.font_checkBox.setChecked(False) font_setting = QFont() font_setting.setFamily(str(self.setting_dict['font'])) self.fontComboBox.setCurrentFont(font_setting) self.font_size_spinBox.setValue(int(self.setting_dict['font-size'])) # sound frame self.enable_notifications_checkBox.setChecked(True) # tray icon self.enable_system_tray_checkBox.setChecked(True) # after_download_checkBox self.after_download_checkBox.setChecked(True) # hide menubar for linux if platform.system == 'Darwin': self.show_menubar_checkbox.setChecked(True) else: self.show_menubar_checkbox.setChecked(False) # show side panel self.show_sidepanel_checkbox.setChecked(True) # show progress window self.show_progress_window_checkbox.setChecked(True) # run persepolis at startup checkBox self.startup_checkbox.setChecked(False) # keep_awake_checkBox self.keep_awake_checkBox.setChecked(False) # columns_tab self.column0_checkBox.setChecked(True) self.column1_checkBox.setChecked(True) self.column2_checkBox.setChecked(True) self.column3_checkBox.setChecked(True) self.column4_checkBox.setChecked(True) self.column5_checkBox.setChecked(True) self.column6_checkBox.setChecked(True) self.column7_checkBox.setChecked(True) self.column10_checkBox.setChecked(True) self.column11_checkBox.setChecked(True) self.column12_checkBox.setChecked(True) # video finder self.enable_video_finder_checkbox.setChecked(True) self.hide_no_audio_checkbox.setChecked(True) self.hide_no_video_checkbox.setChecked(True) self.max_links_spinBox.setValue(3) self.persepolis_setting.endGroup() def videoFinderFram(self): self.video_finder_frame.setEnabled( self.enable_video_finder_checkbox.isChecked()) def okPushButtonPressed(self, button): self.persepolis_setting.beginGroup('settings') self.persepolis_setting.setValue('max-tries', self.tries_spinBox.value()) self.persepolis_setting.setValue('retry-wait', self.wait_spinBox.value()) self.persepolis_setting.setValue('timeout', self.time_out_spinBox.value()) self.persepolis_setting.setValue('connections', self.connections_spinBox.value()) self.persepolis_setting.setValue('rpc-port', self.rpc_port_spinbox.value()) self.persepolis_setting.setValue('download_path', self.download_folder_lineEdit.text()) self.persepolis_setting.setValue('download_path_temp', self.temp_download_lineEdit.text()) self.persepolis_setting.setValue('sound-volume', self.volume_dial.value()) self.persepolis_setting.setValue( 'notification', self.notification_comboBox.currentText()) self.persepolis_setting.setValue( 'wait-queue', self.wait_queue_time.text().split(':')) # change aria2_path if self.aria2_path_checkBox.isChecked(): self.persepolis_setting.setValue( 'settings/aria2_path', str(self.aria2_path_lineEdit.text())) # changing icons icons = self.icon_comboBox.currentText() self.persepolis_setting.setValue('icons', icons) if icons != self.current_icon: # it means icons changed for list in [ self.parent.logwindow_list, self.parent.about_window_list, self.parent.addlinkwindows_list, self.parent.propertieswindows_list, self.parent.afterdownload_list, self.parent.text_queue_window_list, self.parent.progress_window_list ]: for window in list: window.changeIcon(icons) self.parent.changeIcon(icons) # icons size icons_size = self.icons_size_comboBox.currentText() self.persepolis_setting.setValue('toolbar_icon_size', icons_size) icons_size = int(icons_size) self.parent.toolBar.setIconSize(QSize(icons_size, icons_size)) self.parent.toolBar2.setIconSize(QSize(icons_size, icons_size)) # style style = str(self.style_comboBox.currentText()) self.persepolis_setting.setValue('style', style) # language locale = str( self.lang_comboBox.itemData(self.lang_comboBox.currentIndex())) self.persepolis_setting.setValue('locale', locale) # color_scheme color_scheme = self.color_comboBox.currentText() self.persepolis_setting.setValue('color-scheme', color_scheme) # font and font size current_font = self.fontComboBox.currentFont() current_font = current_font.key() current_font = current_font.split(',') font = str(current_font[0]) self.persepolis_setting.setValue('font', font) font_size = self.font_size_spinBox.value() self.persepolis_setting.setValue('font-size', font_size) if self.font_checkBox.isChecked(): custom_font = 'yes' else: custom_font = 'no' self.persepolis_setting.setValue('custom-font', custom_font) # if user select qt notification >> enable_system_tray icon if self.persepolis_setting.value('notification') == 'QT notification': self.enable_system_tray_checkBox.setChecked(True) # enable_system_tray_checkBox if self.enable_system_tray_checkBox.isChecked(): self.persepolis_setting.setValue('tray-icon', 'yes') self.parent.system_tray_icon.show() self.parent.minimizeAction.setEnabled(True) self.parent.trayAction.setChecked(True) else: self.persepolis_setting.setValue('tray-icon', 'no') self.parent.system_tray_icon.hide() self.parent.minimizeAction.setEnabled(False) self.parent.trayAction.setChecked(False) # after_download_checkBox if self.after_download_checkBox.isChecked(): self.persepolis_setting.setValue('after-dialog', 'yes') else: self.persepolis_setting.setValue('after-dialog', 'no') # show_menubar_checkbox if self.show_menubar_checkbox.isChecked(): self.persepolis_setting.setValue('show-menubar', 'yes') self.parent.menubar.show() self.parent.toolBar2.hide() self.parent.showMenuBarAction.setChecked(True) else: self.persepolis_setting.setValue('show-menubar', 'no') self.parent.menubar.hide() self.parent.toolBar2.show() self.parent.showMenuBarAction.setChecked(False) # show_sidepanel_checkbox if self.show_sidepanel_checkbox.isChecked(): self.persepolis_setting.setValue('show-sidepanel', 'yes') self.parent.category_tree_qwidget.show() else: self.persepolis_setting.setValue('show-sidepanel', 'no') self.parent.category_tree_qwidget.hide() # show_progress_window_checkbox if self.show_progress_window_checkbox.isChecked(): self.persepolis_setting.setValue('show-progress', 'yes') else: self.persepolis_setting.setValue('show-progress', 'no') if self.startup_checkbox.isChecked(): self.persepolis_setting.setValue('startup', 'yes') if not (startup.checkstartup() ): # checking existance of Persepolis in system's startup startup.addstartup() # adding Persepolis to system's startup else: self.persepolis_setting.setValue('startup', 'no') if startup.checkstartup( ): # checking existance of Persepolis in system's startup startup.removestartup( ) # removing Persepolis from system's startup # keep_awake_checkBox if self.keep_awake_checkBox.isChecked(): self.persepolis_setting.setValue('awake', 'yes') self.parent.keep_awake_checkBox.setChecked(True) else: self.persepolis_setting.setValue('awake', 'no') self.parent.keep_awake_checkBox.setChecked(False) # this section creates temporary download folder and download folder and # download sub folders if they did not existed. download_path_temp = self.persepolis_setting.value( 'download_path_temp') download_path = self.persepolis_setting.value('download_path') folder_list = [download_path_temp, download_path] if self.subfolder_checkBox.isChecked(): self.persepolis_setting.setValue('subfolder', 'yes') for folder in [ 'Audios', 'Videos', 'Others', 'Documents', 'Compressed' ]: folder_list.append(os.path.join(download_path, folder)) else: self.persepolis_setting.setValue('subfolder', 'no') for folder in folder_list: osCommands.makeDirs(folder) if self.enable_notifications_checkBox.isChecked(): self.persepolis_setting.setValue('sound', 'yes') else: self.persepolis_setting.setValue('sound', 'no') # columns_tab if self.column0_checkBox.isChecked(): self.persepolis_setting.setValue('column0', 'yes') self.parent.download_table.setColumnHidden(0, False) if self.parent.download_table.isColumnHidden(0): self.parent.download_table.setColumnWidth(0, 100) else: self.persepolis_setting.setValue('column0', 'no') self.parent.download_table.setColumnHidden(0, True) if self.column1_checkBox.isChecked(): self.persepolis_setting.setValue('column1', 'yes') self.parent.download_table.setColumnHidden(1, False) if self.parent.download_table.isColumnHidden(1): self.parent.download_table.setColumnWidth(1, 100) else: self.persepolis_setting.setValue('column1', 'no') self.parent.download_table.setColumnHidden(1, True) if self.column2_checkBox.isChecked(): self.persepolis_setting.setValue('column2', 'yes') self.parent.download_table.setColumnHidden(2, False) if self.parent.download_table.isColumnHidden(2): self.parent.download_table.setColumnWidth(2, 100) else: self.persepolis_setting.setValue('column2', 'no') self.parent.download_table.setColumnHidden(2, True) if self.column3_checkBox.isChecked(): self.persepolis_setting.setValue('column3', 'yes') self.parent.download_table.setColumnHidden(3, False) if self.parent.download_table.isColumnHidden(3): self.parent.download_table.setColumnWidth(3, 100) else: self.persepolis_setting.setValue('column3', 'no') self.parent.download_table.setColumnHidden(3, True) if self.column4_checkBox.isChecked(): self.persepolis_setting.setValue('column4', 'yes') self.parent.download_table.setColumnHidden(4, False) if self.parent.download_table.isColumnHidden(4): self.parent.download_table.setColumnWidth(4, 100) else: self.persepolis_setting.setValue('column4', 'no') self.parent.download_table.setColumnHidden(4, True) if self.column5_checkBox.isChecked(): self.persepolis_setting.setValue('column5', 'yes') self.parent.download_table.setColumnHidden(5, False) if self.parent.download_table.isColumnHidden(5): self.parent.download_table.setColumnWidth(5, 100) else: self.persepolis_setting.setValue('column5', 'no') self.parent.download_table.setColumnHidden(5, True) if self.column6_checkBox.isChecked(): self.persepolis_setting.setValue('column6', 'yes') self.parent.download_table.setColumnHidden(6, False) if self.parent.download_table.isColumnHidden(6): self.parent.download_table.setColumnWidth(6, 100) else: self.persepolis_setting.setValue('column6', 'no') self.parent.download_table.setColumnHidden(6, True) if self.column7_checkBox.isChecked(): self.persepolis_setting.setValue('column7', 'yes') self.parent.download_table.setColumnHidden(7, False) if self.parent.download_table.isColumnHidden(7): self.parent.download_table.setColumnWidth(7, 100) else: self.persepolis_setting.setValue('column7', 'no') self.parent.download_table.setColumnHidden(7, True) if self.column10_checkBox.isChecked(): self.persepolis_setting.setValue('column10', 'yes') self.parent.download_table.setColumnHidden(10, False) if self.parent.download_table.isColumnHidden(10): self.parent.download_table.setColumnWidth(10, 100) else: self.persepolis_setting.setValue('column10', 'no') self.parent.download_table.setColumnHidden(10, True) if self.column11_checkBox.isChecked(): self.persepolis_setting.setValue('column11', 'yes') self.parent.download_table.setColumnHidden(11, False) if self.parent.download_table.isColumnHidden(11): self.parent.download_table.setColumnWidth(11, 100) else: self.persepolis_setting.setValue('column11', 'no') self.parent.download_table.setColumnHidden(11, True) if self.column12_checkBox.isChecked(): self.persepolis_setting.setValue('column12', 'yes') self.parent.download_table.setColumnHidden(12, False) if self.parent.download_table.isColumnHidden(12): self.parent.download_table.setColumnWidth(12, 100) else: self.persepolis_setting.setValue('column12', 'no') self.parent.download_table.setColumnHidden(12, True) # video_finder if self.enable_video_finder_checkbox.isChecked(): enable = 'yes' else: enable = 'no' if self.hide_no_audio_checkbox.isChecked(): hide_no_audio = 'yes' else: hide_no_audio = 'no' if self.hide_no_video_checkbox.isChecked(): hide_no_video = 'yes' else: hide_no_video = 'no' self.persepolis_setting.setValue('video_finder/enable', enable) self.persepolis_setting.setValue('video_finder/hide_no_audio', hide_no_audio) self.persepolis_setting.setValue('video_finder/hide_no_video', hide_no_video) self.persepolis_setting.setValue('video_finder/max_links', self.max_links_spinBox.value()) # saving value of persepolis_setting in second_key_value_dict. self.second_key_value_dict = {} for member in self.persepolis_setting.allKeys(): self.second_key_value_dict[member] = str( self.persepolis_setting.value(member)) # comparing first_key_value_dict with second_key_value_dict show_message_box = False for key in self.first_key_value_dict.keys(): if self.first_key_value_dict[key] != self.second_key_value_dict[ key]: if key in [ 'locale', 'aria2_path', 'download_path_temp', 'download_path', 'custom-font', 'rpc-port', 'max-tries', 'retry-wait', 'timeout', 'connections', 'style', 'font', 'font-size', 'color-scheme' ]: show_message_box = True # if any thing changed that needs restarting, then notify user about "Some changes take effect after restarting persepolis" if show_message_box: restart_messageBox = QMessageBox() restart_messageBox.setText( QCoreApplication.translate( "setting_src_ui_tr", '<b><center>Restart Persepolis Please!</center></b><br><center>Some changes take effect after restarting Persepolis</center>' )) restart_messageBox.setWindowTitle( QCoreApplication.translate("setting_src_ui_tr", 'Restart Persepolis!')) restart_messageBox.exec_() # applying changes self.persepolis_setting.endGroup() self.persepolis_setting.sync() self.close()
class CoordinateExtractor_dev1: """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 """ self.point_mlyr_name = '' self.line_mlyr_name = '' self.polygon_mlyr_name = '' self.coord_order = None self.latlon_separator = None self.coordinate_format = None # 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', 'CoordinateExtractor_dev1_{}.qm'.format(locale)) if os.path.exists(locale_path): self.translator = QTranslator() self.translator.load(locale_path) if qVersion() > '4.3.3': QCoreApplication.installTranslator(self.translator) # Create the dialog (after translation) and keep reference self.dlg = CoordinateExtractor_dev1Dialog() self.dlg.comboBoxCoordOrder.currentIndexChanged.connect( self.get_sample_coord_pair_format) self.dlg.comboBoxCoordSeparator.currentIndexChanged.connect( self.get_sample_coord_pair_format) self.dlg.comboBoxCoordFormat.currentIndexChanged.connect( self.get_sample_coord_pair_format) # self.dlg.pushButtonExtractCoord.clicked.connect(self.extract_coordinates) # self.dlg.pushButtonGetWKTString.clicked.connect(self.get_wkt) self.dlg.pushButtonCreateFeature.clicked.connect(self.create_feature) # Declare instance attributes self.actions = [] self.menu = self.tr(u'&CoordinateExtractor_dev1') # TODO: We are going to let the user set this up in a future iteration self.toolbar = self.iface.addToolBar(u'CoordinateExtractor_dev1') self.toolbar.setObjectName(u'CoordinateExtractor_dev1') # 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('CoordinateExtractor_dev1', 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/coord_extractor/icon.png' self.add_action(icon_path, text=self.tr(u'CoordinateExtractor_dev1'), callback=self.run, parent=self.iface.mainWindow()) def unload(self): """Removes the plugin menu item and icon from QGIS GUI.""" for action in self.actions: self.iface.removePluginMenu(self.tr(u'&CoordinateExtractor_dev1'), action) self.iface.removeToolBarIcon(action) # remove the toolbar del self.toolbar """ Create memory layers from point, line, polygon """ @staticmethod def create_mlyr(mlyr_name, mlyr_type): """ Create temporary 'memory' layer to store results. :param lyr_name: string, layer name """ if mlyr_type == 'POINT': mlyr = QgsVectorLayer('Point?crs=epsg:4326', mlyr_name, 'memory') elif mlyr_type == 'POLYGON': mlyr = QgsVectorLayer('Polygon?crs=epsg:4326', mlyr_name, 'memory') prov = mlyr.dataProvider() mlyr.startEditing() prov.addAttributes([QgsField("NAME", QVariant.String)]) mlyr.commitChanges() QgsProject.instance().addMapLayer(mlyr) """ Add line, polygon feature to memory layer """ def add_polygon_feature(self, polygon_geom): """ Add feature to layer :param: boundary: list, list of QgsPoint objects """ out_lyr = QgsProject.instance().mapLayersByName( self.polygon_mlyr_name)[0] self.iface.setActiveLayer(out_lyr) out_lyr = self.iface.activeLayer() out_lyr.startEditing() out_prov = out_lyr.dataProvider() feat = QgsFeature() feat.setGeometry(polygon_geom) feat.setAttributes(['']) out_prov.addFeatures([feat]) out_lyr.commitChanges() out_lyr.updateExtents() self.iface.mapCanvas().setExtent(out_lyr.extent()) self.iface.mapCanvas().refresh() def add_polygon_line_feature(self, ftype, fgeom, fname): """ Add feature to layer :param: boundary: list, list of QgsPoint objects """ if ftype == 'POLYGON': out_lyr = QgsProject.instance().mapLayersByName( self.polygon_mlyr_name)[0] self.iface.setActiveLayer(out_lyr) out_lyr = self.iface.activeLayer() out_lyr.startEditing() out_prov = out_lyr.dataProvider() feat = QgsFeature() feat.setGeometry(fgeom) feat.setAttributes([fname]) out_prov.addFeatures([feat]) out_lyr.commitChanges() out_lyr.updateExtents() self.iface.mapCanvas().setExtent(out_lyr.extent()) self.iface.mapCanvas().refresh() """ Sets coordinate pair format """ def set_coord_order(self): if self.dlg.comboBoxCoordOrder.currentIndex() == 0: self.coord_order = None if self.dlg.comboBoxCoordOrder.currentIndex() == 1: self.coord_order = cet.ORDER_LATLON elif self.dlg.comboBoxCoordOrder.currentIndex() == 2: self.coord_order = cet.ORDER_LONLAT def set_latlon_separator(self): if self.dlg.comboBoxCoordSeparator.currentIndex() == 0: self.dlg.lineEditUserSeparator.setEnabled(False) self.latlon_separator = None elif self.dlg.comboBoxCoordSeparator.currentIndex( ) == 1: # Null separator self.dlg.lineEditUserSeparator.setEnabled(False) self.latlon_separator = cet.SEP_NULL elif self.dlg.comboBoxCoordSeparator.currentIndex() == 2: # Space self.dlg.lineEditUserSeparator.setEnabled(False) self.latlon_separator = cet.SEP_SPACE elif self.dlg.comboBoxCoordSeparator.currentIndex() == 3: # Hyphen self.dlg.lineEditUserSeparator.setEnabled(False) self.latlon_separator = cet.SEP_HYPHEN elif self.dlg.comboBoxCoordSeparator.currentIndex() == 4: self.dlg.lineEditUserSeparator.setEnabled(False) self.latlon_separator = cet.SEP_SLASH elif self.dlg.comboBoxCoordSeparator.currentIndex() == 5: self.dlg.lineEditUserSeparator.setEnabled(False) self.latlon_separator = '\\' elif self.dlg.comboBoxCoordSeparator.currentIndex() == 6: self.dlg.lineEditUserSeparator.setEnabled(True) self.latlon_separator = self.dlg.lineEditUserSeparator.text() def set_coordinate_format(self): if self.dlg.comboBoxCoordFormat.currentIndex() == 0: self.coordinate_format = None elif self.dlg.comboBoxCoordFormat.currentIndex() == 1: self.coordinate_format = cet.DMSH_COMP elif self.dlg.comboBoxCoordFormat.currentIndex() == 2: self.coordinate_format = cet.HDMS_COMP elif self.dlg.comboBoxCoordFormat.currentIndex() == 3: self.coordinate_format = cet.DMSH_SEP elif self.dlg.comboBoxCoordFormat.currentIndex() == 4: self.coordinate_format = cet.HDMS_SEP def get_geometry_type(self): if self.dlg.comboBoxFeatureType.currentIndex() == 0: return agt.GEOM_POINT elif self.dlg.comboBoxFeatureType.currentIndex() == 1: return agt.GEOM_LINE elif self.dlg.comboBoxFeatureType.currentIndex() == 2: return agt.GEOM_POLYGON def get_sample_coord_pair_format(self): self.set_coord_order() self.set_latlon_separator() self.set_coordinate_format() if self.coord_order is not None and self.latlon_separator is not None and self.coordinate_format is not None: sample_format = get_sample_coordinates(self.coord_order, self.latlon_separator, self.coordinate_format) self.dlg.labelCoordExample.setText(sample_format) else: self.dlg.labelCoordExample.setText("Choose to see format example") def extract_coordinates(self): self.set_coord_order() self.set_latlon_separator() self.set_coordinate_format() self.dlg.tableWidgetCoordinates.setRowCount(0) raw_text = self.dlg.textEditRawText.toPlainText() coord_regex = cet.CoordRegexBuilder(self.coord_order, self.coordinate_format, self.latlon_separator) extracted_coord = cet.CoordinateExtractor(raw_text, coord_regex) coord_list = extracted_coord.get_coord_pair_list() for coord in coord_list: if self.coord_order == cet.ORDER_LATLON: row_pos = self.dlg.tableWidgetCoordinates.rowCount() self.dlg.tableWidgetCoordinates.insertRow(row_pos) self.dlg.tableWidgetCoordinates.setItem( row_pos, 0, QTableWidgetItem(coord[0])) self.dlg.tableWidgetCoordinates.setItem( row_pos, 1, QTableWidgetItem(coord[2])) elif self.coord_order == cet.ORDER_LONLAT: row_pos = self.dlg.tableWidgetCoordinates.rowCount() self.dlg.tableWidgetCoordinates.insertRow(row_pos) self.dlg.tableWidgetCoordinates.setItem( row_pos, 0, QTableWidgetItem(coord[2])) self.dlg.tableWidgetCoordinates.setItem( row_pos, 1, QTableWidgetItem(coord[0])) def create_feature(self): self.dlg.textEditRawTextWKRTString.clear() self.dlg.tableWidgetCoordinates.setRowCount(0) self.extract_coordinates() feat_name = self.dlg.lineEditFeatureName.text() if self.point_mlyr_name == '': self.point_mlyr_name = 'POINT' if self.line_mlyr_name == '': self.line_mlyr_name == 'LINE' if self.polygon_mlyr_name == '': self.polygon_mlyr_name = 'POLYGON' layers = QgsProject.instance().layerTreeRoot().children() layers_list = [] # List of layers in current (opened) QGIS project for layer in layers: layers_list.append(layer.name()) # A list in which QgsPoints will be stored points = [] # Get number of extracted points points_count = self.dlg.tableWidgetCoordinates.rowCount() for i in range(0, points_count): point_coordinates = agt.CoordinatesPair( self.dlg.tableWidgetCoordinates.item(i, 0).text(), self.dlg.tableWidgetCoordinates.item(i, 1).text()) if point_coordinates.is_valid is True: point = QgsPointXY(point_coordinates.lon_dd, point_coordinates.lat_dd) points.append(point) wkt_str = '' feat = QgsFeature() geom_type = self.get_geometry_type() if geom_type == agt.GEOM_POINT: if self.point_mlyr_name not in layers_list: self.create_mlyr(self.point_mlyr_name, 'POINT') wkt_str = ''.join([point_item.asWkt() for point_item in points]) out_lyr = QgsProject.instance().mapLayersByName( self.point_mlyr_name)[0] self.iface.setActiveLayer(out_lyr) # There might be many points so first started editing of the point layer # add points in the loop to layer and at the and commit changes out_lyr.startEditing() out_prov = out_lyr.dataProvider() point_nr = 0 for point_item in points: point_nr += 1 point_name = '{}-{}'.format(feat_name, point_nr) point_geom = QgsGeometry.fromPointXY(point_item) feat.setGeometry(point_geom) feat.setAttributes([point_name]) out_prov.addFeatures([feat]) out_lyr.commitChanges() out_lyr.updateExtents() self.iface.mapCanvas().setExtent(out_lyr.extent()) self.iface.mapCanvas().refresh() elif geom_type == agt.GEOM_LINE: line_geom = QgsGeometry.fromPolylineXY(points) wkt_str = line_geom.asWkt() elif geom_type == agt.GEOM_POLYGON: if self.polygon_mlyr_name not in layers_list: self.create_mlyr(self.polygon_mlyr_name, 'POLYGON') polygon_geom = QgsGeometry.fromPolygonXY([points]) wkt_str = polygon_geom.asWkt() #self.add_polygon_feature(polygon_geom) self.add_polygon_line_feature('POLYGON', polygon_geom, feat_name) self.dlg.textEditRawTextWKRTString.append(wkt_str) def run(self): """Run method that performs all the real work""" # show the dialog self.dlg.show() # Run the dialog event loop result = self.dlg.exec_() # See if OK was pressed if result: # Do something useful here - delete the line containing pass and # substitute with your code. pass
class Tachy2Gis: """QGIS Plugin Implementation.""" # Custom methods go here: NO_PORT = 'Select tachymeter USB port' def vertexReceived(self, line): newVtx = T2G_Vertex.fromGSI(line) self.mapTool.addVertex(vtx=newVtx) ## Clears the map canvas and in turn the vertexList def clearCanvas(self): self.mapTool.clear() ## Opens the field dialog in preparation of dumping new vertices to the target layer def dump(self): # the input table of the dialog is updated self.fieldDialog.populateFieldTable() result = self.fieldDialog.exec_() if result == QDialog.Accepted: targetLayer = self.fieldDialog.layer self.vertexList.dumpToFile(targetLayer, self.fieldDialog.fieldData) # if the target layer holds point geometries, only the currently selected vertex is dumped and # removed from the list if self.fieldDialog.targetLayerComboBox.currentLayer( ).geometryType() == 0: self.mapTool.deleteVertex() else: # otherwise the list is cleared self.mapTool.clear() targetLayer.dataProvider().forceReload() targetLayer.triggerRepaint() self.vertexList.updateAnchors( self.dlg.sourceLayerComboBox.currentLayer()) else: return ## Restores the map tool to the one that was active before T2G was started # The pan tool is the default tool used by QGIS def restoreTool(self): if self.previousTool is None: self.previousTool = QgsMapToolPan(self.iface.mapCanvas()) self.iface.mapCanvas().setMapTool(self.previousTool) def setActiveLayer(self): if Qt is None: return activeLayer = self.dlg.sourceLayerComboBox.currentLayer() if activeLayer is None: return self.iface.setActiveLayer(activeLayer) self.vertexList.updateAnchors(activeLayer) def targetChanged(self): targetLayer = self.fieldDialog.targetLayerComboBox.currentLayer() self.mapTool.setGeometryType(targetLayer) def toggleEdit(self): iface.actionToggleEditing().trigger() def connectSerial(self): port = self.dlg.portComboBox.currentText() if not port == Tachy2Gis.NO_PORT: self.tachyReader.setPort(port) def setLog(self): logFileName = QFileDialog.getOpenFileName()[0] self.dlg.logFileEdit.setText(logFileName) self.tachyReader.setLogfile(logFileName) def dumpEnabled(self): verticesAvailable = (len(self.vertexList) > 0) # Selecting a target layer while there are no vertices in the vertex list may cause segfaults. To avoid this, # the 'Dump' button is disabled as long there are none: self.dlg.dumpButton.setEnabled(verticesAvailable) def zoom_full_extent(self): canvas = iface.mapCanvas() canvas.zoomToFullExtent() canvas.refresh() # Interface code goes here: def setupControls(self): """This method connects all controls in the UI to their callbacks. It is called in ad_action""" portNames = [Tachy2Gis.NO_PORT] portNames.extend( [port.portName() for port in QSerialPortInfo.availablePorts()]) self.dlg.portComboBox.addItems(portNames) self.dlg.portComboBox.currentIndexChanged.connect(self.connectSerial) self.dlg.logFileButton.clicked.connect(self.setLog) self.dlg.deleteAllButton.clicked.connect(self.clearCanvas) self.dlg.finished.connect(self.mapTool.clear) self.dlg.dumpButton.clicked.connect(self.dump) self.dlg.deleteVertexButton.clicked.connect(self.mapTool.deleteVertex) self.dlg.vertexTableView.setModel(self.vertexList) self.dlg.vertexTableView.horizontalHeader().setSectionResizeMode( 0, QHeaderView.Stretch) self.dlg.vertexTableView.setSelectionModel( QItemSelectionModel(self.vertexList)) self.dlg.vertexTableView.selectionModel().selectionChanged.connect( self.mapTool.selectVertex) self.dlg.finished.connect(self.restoreTool) self.dlg.accepted.connect(self.restoreTool) self.dlg.rejected.connect(self.restoreTool) self.dlg.sourceLayerComboBox.setFilters( QgsMapLayerProxyModel.VectorLayer | QgsMapLayerProxyModel.WritableLayer) self.dlg.sourceLayerComboBox.setLayer(self.iface.activeLayer()) self.dlg.sourceLayerComboBox.layerChanged.connect(self.setActiveLayer) self.dlg.sourceLayerComboBox.layerChanged.connect(self.mapTool.clear) self.fieldDialog.targetLayerComboBox.layerChanged.connect( self.targetChanged) self.vertexList.layoutChanged.connect(self.dumpEnabled) self.fieldDialog.buttonBox.accepted.connect( self.extent_provider.add_feature) self.dlg.zoomResetButton.clicked.connect(self.extent_provider.reset) self.dlg.zoomModeComboBox.addItems([ 'Layer', 'Last feature', 'Last 2 features', 'Last 4 features', 'Last 8 features', ]) self.dlg.zoomModeComboBox.currentIndexChanged.connect( self.extent_provider.set_mode) self.dlg.zoomActiveCheckBox.stateChanged.connect( self.auto_zoomer.set_active) self.extent_provider.ready.connect(self.auto_zoomer.apply) ## 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. def __init__(self, iface): # 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', 'Tachy2Gis_{}.qm'.format(locale)) 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('&Tachy2GIS') self.toolbar = self.iface.addToolBar('Tachy2Gis') self.toolbar.setObjectName('Tachy2Gis') ## From here: Own additions self.vertexList = T2G_VertexList() self.extent_provider = ExtentProvider(self.vertexList, self.iface.mapCanvas()) self.auto_zoomer = AutoZoomer(self.iface.mapCanvas(), self.extent_provider) self.mapTool = T2G_VertexePickerTool(self) self.previousTool = None self.fieldDialog = FieldDialog(self.iface.activeLayer()) self.tachyReader = TachyReader(QSerialPort.Baud9600) self.pollingThread = QThread() self.tachyReader.moveToThread(self.pollingThread) self.pollingThread.start() self.tachyReader.lineReceived.connect(self.vertexReceived) self.tachyReader.beginListening() # 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('Tachy2Gis', 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 """ # Create the dialog (after translation) and keep reference self.dlg = Tachy2GisDialog() self.setupControls() 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.iface.addToolBarIcon(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/Tachy2Gis/icon.png' self.add_action(icon_path, text=self.tr('Tachy2GIS'), callback=self.run, parent=self.iface.mainWindow()) def unload(self): """Removes the plugin menu item and icon from QGIS GUI.""" for action in self.actions: self.iface.removePluginMenu(self.tr('&Tachy2GIS'), action) self.iface.removeToolBarIcon(action) # remove the toolbar del self.toolbar if self.pollingThread.isRunning(): self.tachyReader.shutDown() self.pollingThread.terminate() self.pollingThread.wait() def run(self): """Run method that performs all the real work""" # Store the active map tool and switch to the T2G_VertexPickerTool self.previousTool = self.iface.mapCanvas().mapTool() self.iface.mapCanvas().setMapTool(self.mapTool) self.mapTool.alive = True self.setActiveLayer() self.dlg.show() # Run the dialog event loop result = self.dlg.exec_() # See if OK was pressed if result: # Do something useful here - delete the line containing pass and # substitute with your code. pass
class QCopycanvas: """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', 'QCopycanvas_{}.qm'.format(locale)) 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'&QCopycanvas') # Check if plugin was started the first time in current QGIS session # Must be set in initGui() to survive plugin reloads self.first_start = 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('QCopycanvas', 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, shortcut=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 shortcut is not None: action.setShortcut(QKeySequence(shortcut)) if add_to_toolbar: # Adds plugin icon to Plugins toolbar self.iface.addToolBarIcon(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/QCopycanvas/icon.png' self.add_action( icon_path, text=self.tr(u'Copy map canvas'), shortcut="Ctrl+Space", callback=self.run, parent=self.iface.mainWindow()) # will be set False in run() self.first_start = True def unload(self): """Removes the plugin menu item and icon from QGIS GUI.""" for action in self.actions: self.iface.removePluginMenu( self.tr(u'&QCopycanvas'), action) self.iface.removeToolBarIcon(action) def showMessage(self, title, msg, button): msgBox = QMessageBox() msgBox.setIcon(QMessageBox.Information) msgBox.setWindowTitle(title) msgBox.setText(msg) msgBox.setStandardButtons(QMessageBox.Ok) font = QFont() font.setPointSize(9) msgBox.setFont(font) msgBox.setWindowFlags(Qt.CustomizeWindowHint | Qt.WindowStaysOnTopHint | Qt.WindowCloseButtonHint) buttonY = msgBox.button(QMessageBox.Ok) buttonY.setText(button) buttonY.setFont(font) msgBox.exec_() def run(self): """Run method that performs all the real work""" # Create the dialog with elements (after translation) and keep reference # Only create GUI ONCE in callback, so that it will only load when the plugin is started QApplication.clipboard().setImage(QImage(QWidget.grab(self.iface.mapCanvas()))) self.showMessage(title='QCopycanvas', msg='Copied map canvas successfully.', button='OK')
class GeoDataFarm: """QGIS Plugin Implementation.""" def __init__(self, iface): """Constructor. Parameters ---------- iface: QgsInterface, 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. """ # Save reference to the QGIS interface self.iface = iface # initialize plugin directory self.plugin_dir = os.path.dirname(__file__) translate = TR() self.tr = translate.tr # initialize locale locale = QSettings().value('locale/userLocale')[0:2] locale_path = os.path.join(self.plugin_dir, 'i18n', 'GeoDataFarm_{}.qm'.format(locale)) 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'&GeoFarm') self.toolbar = self.iface.addToolBar(u'GeoDataFarm') self.toolbar.setObjectName(u'GeoDataFarm') self.tsk_mngr = QgsApplication.taskManager() #print "** INITIALIZING GeoDataFarm" self.items_in_table = None self.pluginIsActive = False self.dock_widget = None self.populate = None self.db = None self.IH = None self.df = None self.db = None self.add_field = None self.save_planting = None self.save_fertilizing = None self.save_spraying = None self.save_other = None self.save_harvesting = None self.save_plowing = None self.save_harrowing = None self.save_soil = None self.plan_ahead = None self.report_generator = None # noinspection PyMethodMayBeStatic 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. Parameters ---------- icon_path: str Path to the icon for this action. Can be a resource path (e.g. ':/plugins/foo/bar.png') or a normal file system path. text: str Text that should be shown in menu items for this action. callback: function Function to be called when the action is triggered. enabled_flag: bool A flag indicating if the action should be enabled by default. Defaults to True. add_to_menu: bool Flag indicating whether the action should also be added to the menu. Defaults to True. add_to_toolbar: bool Flag indicating whether the action should also be added to the toolbar. Defaults to True. status_tip: str Optional text to show in a popup when mouse pointer hovers over the action. parent: QWidget Parent widget for the new action. Defaults None. whats_this: str Optional text to show in the status bar when the mouse pointer hovers over the action. Returns ------- QAction The action that was created. Note that the action is also added to self.actions list. """ 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/GeoDataFarm/img/icon.png' self.add_action(icon_path, text=self.tr(u'GeoDataFarm'), callback=self.run, parent=self.iface.mainWindow()) def onClosePlugin(self): """Cleanup necessary items here when plugin dock_widget is closed""" self.dock_widget.closingPlugin.disconnect(self.onClosePlugin) self.pluginIsActive = False def unload(self): """Removes the plugin menu item and icon from QGIS GUI.""" #print "** UNLOAD GeoDataFarm" for action in self.actions: self.iface.removePluginMenu(self.tr(u'&GeoFarm'), action) self.iface.removeToolBarIcon(action) # remove the toolbar del self.toolbar # Functions create specific for GeoDataFarm----------------------------- def add_selected_tables(self): """Adds a layer for each "parameter" of all selected tables""" add_layer_to_canvas = AddLayerToCanvas(self) add_layer_to_canvas.run() def reload_layer(self): """Reloads a layer be create a CreateLayer object and call the function repaint_layer""" create_layer = CreateLayer(self.db, self.dock_widget) create_layer.repaint_layer() def reload_range(self): """Reload the range of the lowest and highest value of the layer""" cb = self.dock_widget.mMapLayerComboBox layer = cb.currentLayer() if layer is not None: try: lv = layer.renderer().ranges()[0].lowerValue() hv = layer.renderer().ranges()[-1].upperValue() nbr_cat = len(layer.renderer().ranges()) self.dock_widget.LEMinColor.setText(str(lv)) self.dock_widget.LEMaxColor.setText(str(hv)) self.dock_widget.LEMaxNbrColor.setText(str(nbr_cat)) except AttributeError: pass def run_analyse(self): """Gathers the parameters and start the analyse dialog""" names = [] harvest_file = False input_file = False self.items_in_table = self.populate.get_items_in_table() self.lw_list = self.populate.get_lw_list() for i, (lw, schema) in enumerate(self.lw_list): for item in self.items_in_table[i][0]: if (item.checkState() == 2 and self.db.check_table_exists( item.text(), schema, False)): if schema == 'harvest': harvest_file = True if schema == 'plant' or schema == 'soil' or schema == 'spray' or schema == 'ferti' or schema == 'weather': input_file = True names.append([schema, item.text()]) if harvest_file and input_file: analyse = Analyze(self, names) if analyse.check_consistency(): analyse.default_layout() analyse.run() else: return else: QMessageBox.information( None, self.tr("Error:"), self. tr('You need to have at least one input (activity or soil) and one harvest data set selected.' )) def _q_replace_db_data(self, tbl=None): """Function that might be removed after the full support for shape files """ schema = self.dock_widget.CBDataType.currentText() tables_in_db = self.db.get_tables_in_db(schema=schema) if tbl is not None: tbl_name = tbl else: tbl_name = str(self.IH.file_name) if isint(tbl_name[0]): tbl_name = '_' + tbl_name if tbl_name in tables_in_db: qm = QMessageBox() ret = qm.question( None, 'Message', self. tr("The name of the data set already exist in your database, would you like to replace it?" ), qm.Yes, qm.No) if ret == qm.No: return False else: self.db.execute_sql("DROP TABLE {schema}.{tbl}".format( schema=schema, tbl=tbl_name)) return True else: return True def tbl_mgmt(self): """Open the table manager widget""" tabel_mgmt = TableManagement(self) tabel_mgmt.run() def multi_edit(self): """Opens the multi edit widget""" me = MultiEdit(self) me.show() def drop_unreal(self): du = DropUnReal(self) du.show() def import_irrigation(self): """Opens the irrigation handler widget""" irr = IrrigationHandler(self) irr.run() def create_guide(self): """Opens the create guide file widget""" guide = CreateGuideFile(self) guide.run() def get_database_connection(self): """Connects to the database and create the db object""" self.db = DB(self.dock_widget, path=self.plugin_dir) connected = self.db.get_conn() if not connected: QMessageBox.information( None, "Information:", self. tr("Welcome to GeoDataFarm, this is a plugin still under development, if you have any suggestions of imporvements or don't understand some parts please do send a e-mail to me at [email protected]" )) return False return True def add_crop(self): """Adds a crop to the database""" crop_name = self.dock_widget.LECropName.text() if len(crop_name) == 0: QMessageBox.information(None, self.tr('Error:'), self.tr('Crop name must be filled in.')) return sql = """Insert into crops (crop_name) VALUES ('{name}')""".format(name=crop_name) r_value = self.db.execute_sql(sql, return_failure=True) if r_value is IntegrityError: QMessageBox.information( None, self.tr('Error:'), self.tr('Crop name already exist, please select a new name')) return _name = QApplication.translate("qadashboard", crop_name, None) item = QListWidgetItem(_name, self.dock_widget.LWCrops) item.setFlags(item.flags() | QtCore.Qt.ItemIsUserCheckable) item.setCheckState(QtCore.Qt.Unchecked) self.populate.reload_crops() def remove_crop_name(self): for i in range(self.dock_widget.LWCrops.count()): item = self.dock_widget.LWCrops.item(i) if item.checkState() == 2: sql = "delete from crops where crop_name = '{n}'".format( n=item.text()) self.db.execute_sql(sql) self.populate.reload_crops() def clicked_create_farm(self): """Connects the docked widget with the CreateFarm script and starts the create_farm widget""" create_farm = CreateFarm(self, True) create_farm.run() def connect_to_farm(self): """Connects the docked widget with the CreateFarm script and starts the connect to farm widget""" create_farm = CreateFarm(self, False) create_farm.run() def fix_rows(self): RowFixer(self) def run_interpolate_harvest(self): cta = ConvertToAreas(self) cta.run() def set_buttons(self): """Since most functions are dependent on that a database connections exist the buttons are set when a connection is set. If new connections are added here do not forget to add them in create_new_farms function that resets the database connection""" if self.populate is None: self.populate = Populate(self) self.dock_widget.PBOpenRD.clicked.connect(self.import_irrigation) self.dock_widget.PBUpdateLists.clicked.connect( self.populate.update_table_list) self.save_planting = SavePlanting(self) self.satellite_data = SatelliteData(self) self.satellite_data.set_widget_connections() self.save_planting.set_widget_connections() self.save_fertilizing = SaveFertilizing(self) self.save_fertilizing.set_widget_connections() self.report_generator = RapportGen(self) self.report_generator.set_widget_connections() self.add_field = AddField(self) self.add_field.set_widget_connections() self.plan_ahead = PlanAhead(self) self.plan_ahead.set_widget_connections() self.save_spraying = SaveSpraying(self) self.save_spraying.set_widget_connections() self.save_other = SaveOther(self) self.save_other.set_widget_connections() self.save_harvesting = SaveHarvesting(self) self.save_harvesting.set_widget_connections() self.save_plowing = SavePlowing(self) self.save_plowing.set_widget_connections() self.save_harrowing = SaveHarrowing(self) self.save_harrowing.set_widget_connections() self.save_soil = SaveSoil(self) self.save_soil.set_widget_connections() self.dock_widget.PBAddCrop.clicked.connect(self.add_crop) self.dock_widget.PBRemoveCrop.clicked.connect( self.remove_crop_name) self.dock_widget.PBMultiEdit.clicked.connect(self.multi_edit) self.dock_widget.PBDropUnReal.clicked.connect(self.drop_unreal) self.dock_widget.PBReloadLayer.clicked.connect(self.reload_layer) self.dock_widget.PBEditTables.clicked.connect(self.tbl_mgmt) self.dock_widget.PBCreateGuide.clicked.connect(self.create_guide) self.dock_widget.PBFixRows.clicked.connect(self.fix_rows) self.dock_widget.PBRunAnalyses.clicked.connect(self.run_analyse) self.dock_widget.PBAdd2Canvas.clicked.connect( self.add_selected_tables) self.dock_widget.PBWebbpage.clicked.connect( lambda: webbrowser.open('http://www.geodatafarm.com/')) self.dock_widget.PBHvInterpolateData.clicked.connect( self.run_interpolate_harvest) def run(self): """Run method that loads and starts the plugin""" icon_path = ':/plugins/GeoDataFarm/img/icon.png' if not self.pluginIsActive: self.pluginIsActive = True #print "** STARTING GeoDataFarm" # dock_widget may not exist if: # first run of plugin # removed on close (see self.onClosePlugin method) if self.dock_widget is None: # Create the dock_widget (after translation) and keep reference self.dock_widget = GeoDataFarmDockWidget() img = QImage(icon_path) pimg = QtGui.QPixmap.fromImage(img).scaled( 91, 91, QtCore.Qt.KeepAspectRatio) self.dock_widget.LIcon.setPixmap(pimg) if self.get_database_connection(): self.set_buttons() self.dock_widget.PBAddNewFarm.clicked.connect( self.clicked_create_farm) self.dock_widget.PBConnect2Farm.clicked.connect( self.connect_to_farm) try: self.reload_range() except: pass self.dock_widget.mMapLayerComboBox.currentIndexChanged.connect( self.reload_range) # show the dock_widget # connect to provide cleanup on closing of dock_widget self.dock_widget.closingPlugin.connect(self.onClosePlugin) #self.iface.addDockWidget(Qt.RightDockWidgetArea, self.dock_widget) self.dock_widget.show()
class DivisionFusion: """QGIS Plugin Implementation.""" def __init__(self, iface, ACA): """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 self.CFG = None self.UTI = None self.DFS = None self.DBJ = None self.ELM = None self.ACA = ACA self.TPG = None # 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', 'DivisionFusion_{}.qm'.format(locale)) if os.path.exists(locale_path): self.translator = QTranslator() self.translator.load(locale_path) if qVersion() > '4.3.3': QCoreApplication.installTranslator(self.translator) # Create the dialog (after translation) and keep reference self.dlg = DivisionFusionDialog(parent=iface.mainWindow(), DIV=self) # Declare instance attributes ''' self.actions = [] self.menu = self.tr(u'&DivisionFusion') # TODO: We are going to let the user set this up in a future iteration self.toolbar = self.iface.addToolBar(u'DivisionFusion') self.toolbar.setObjectName(u'DivisionFusion') ''' self.eventos = EventoDivision(iface.mapCanvas(), self, iface.cadDockWidget()) iface.mapCanvas().setMapTool(self.eventos) self.VentanaAreas = VentanaAreas(self) self.VentanaFusion = VentanaFusionV3(iface, self) self.VentanaClaves = VentanaClavesV3(iface, self) self.rubberMarca = QgsRubberBand(iface.mapCanvas(), QgsWkbTypes.PolygonGeometry) self.rubberMarca.setFillColor(QColor(255, 255, 0, 12)) self.rubberMarca.setStrokeColor(QColor(255, 150, 0, 255)) self.rubberMarca.setWidth(2) self.listaNuevosPredios = [] self.cargoPredio = False self.listaColores = [] self.rubbersAreas = [] self.dlg.btnDibujarCortes.setEnabled(False) self.dlg.btnEditarCortes.setEnabled(False) self.dlg.btnEliminarCortes.setEnabled(False) self.dlg.btnApagarHerramientas.setEnabled(False) self.dlg.btnConfirmarCortes.setEnabled(False) self.dlg.btnDeshacerTodo.setEnabled(False) self.dlg.btnCancelarSub.setEnabled(False) self.dlg.btnDeshacerCortes.setEnabled(False) self.dlg.btnLlamarCalcular.setEnabled(False) self.dlg.btnFusionar.clicked.connect(self.preguntarFusion) self.dlg.btnCargarPredio.clicked.connect(self.pasarAModoDivision) self.dlg.btnConfirmarCortes.clicked.connect(self.confirmarCortes) self.dlg.btnDibujarCortes.clicked.connect(self.encenderModoDividir) self.dlg.btnEliminarCortes.clicked.connect(self.encenderModoEliminar) self.dlg.btnApagarHerramientas.clicked.connect(self.apagarHerramientas) self.dlg.btnDeshacerTodo.clicked.connect(self.rollBack) self.dlg.btnCancelarSub.clicked.connect(self.cancelarSubdivision) self.dlg.btnDeshacerCortes.clicked.connect(self.vaciarLineasCorte) self.dlg.btnLlamarCalcular.clicked.connect(self.irAreas) self.dlg.btnEditarCortes.clicked.connect(self.encenderModoEditar) self.dlg.btnDeshacerTodo.hide() self.enClaves = False self.enSubdivision = False self.enFusion = False self.headers = {'Content-Type': 'application/json'} self.geomsAreas = [] # 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('DivisionFusion', 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/DivisionFusion/icon.png' self.add_action(icon_path, text=self.tr(u'DivisionFusion'), callback=self.run, parent=self.iface.mainWindow()) def unload(self): """Removes the plugin menu item and icon from QGIS GUI.""" for action in self.actions: self.iface.removePluginMenu(self.tr(u'&DivisionFusion'), action) self.iface.removeToolBarIcon(action) # remove the toolbar del self.toolbar def run(self): """Run method that performs all the real work""" # show the dialog for x in iface.mapNavToolToolBar().actions(): if x.objectName() == 'mActionPan': x.trigger() for x in iface.advancedDigitizeToolBar().actions(): if x.objectName() == 'mEnableAction': x.trigger() self.dlg.show() # Run the dialog event loop iface.mapCanvas().setMapTool(self.eventos) result = self.dlg.exec_() # See if OK was pressed self.dlg.btnFusionar.setEnabled(True) self.dlg.comboPredios.setEnabled(True) self.dlg.btnCargarPredio.setEnabled(True) self.dlg.btnDibujarCortes.setEnabled(False) self.dlg.btnEditarCortes.setEnabled(False) self.dlg.btnEliminarCortes.setEnabled(False) self.dlg.btnApagarHerramientas.setEnabled(False) self.dlg.btnConfirmarCortes.setEnabled(False) self.dlg.btnDeshacerTodo.setEnabled(False) # llena los predios en el combo self.dlg.comboPredios.clear() lista = [] capaPredios = QgsProject.instance().mapLayer( self.ACA.obtenerIdCapa('predios.geom')) if capaPredios is None: return # lista de features for predio in capaPredios.getFeatures(): lista.append(str(predio['clave'])) lista.sort() for elemento in lista: self.dlg.comboPredios.addItem(elemento) if result: # Do something useful here - delete the line containing pass and # substitute with your code. pass '''def consumirPredios(self): listaPredio =[] if iface.activeLayer() != None: seleccion = self.iface.activeLayer().selectedFeatures() for i in seleccion: self.id = self.consumeWSGeneral(url_cons = self.CFG.url_AU_getAllfactures + str(i['id']) ) if not self.id: return listaPredio.append(self.id) print(listaPredio)''' #------------------------------------------------------------------------------ #Preguntamos si quiere fusionar def preguntarFusion(self): listaPredio = [] #self.consumirPredios() if iface.activeLayer() != None: seleccion = self.iface.activeLayer().selectedFeatures() #self.VentanaFusion.dlg.close() if self.validarCuentaSeleccion(): #Si la seleccion es valida for i in seleccion: self.id = self.consumeWSGeneral( url_cons=self.CFG.url_AU_getAllfactures + str(i['id'])) if not self.id: return listaPredio.append(self.id) #print(listaPredio) self.enFusion = True #self.VentanaFusion.dlg.show() #self.VentanaFusion.llenarTablaComp(listaPredio[0], listaPredio[1]) self.dlg.btnCargarPredio.setEnabled(False) #else: #self.UTI.mostrarAlerta('La fusion requiere la seleccion de exactamente 2 predios contiguos', QMessageBox().Critical, 'Error de fusion') #------------------------------------------------------------------ #Validamosla seleccion def validarCuentaSeleccion(self): seleccion = self.iface.activeLayer().selectedFeatures() for i in seleccion: if str(i['id']) == '': self.UTI.mostrarAlerta( 'El predio ' + str(i['clave']) + ' no se puede fusionar, guarde los cambios antes de continuar', QMessageBox().Critical, 'Error de fusion') return False if len(seleccion) != 2: #Cuando tenemos seleccionados no 2 elementos self.UTI.mostrarAlerta( 'La fusion requiere la seleccion de exactamente 2 predios contiguos', QMessageBox().Critical, 'Error de fusion') return False else: if not self.validarContiguedad(): self.UTI.mostrarAlerta( 'Los predios seleccionados no son contiguos', QMessageBox().Critical, 'Error de fusion') return False else: return True #----------------------------------------------------------------------------- def validarContiguedad(self): #Aqui checamos si dos predios son contiguos seleccion = self.iface.activeLayer().selectedFeatures() pred1 = seleccion[0].geometry().buffer(0.0000001, 1) pred2 = seleccion[1].geometry().buffer(0.0000001, 1) #Checamos que el area de interseccion sea un valor considerable area = pred1.intersection(pred2).area() return area > 0.0000000001 #----------------------------------------------------------------------------------- def fusionarPredios(self, eleccion): #Aqui fusionamos los predios #OBtener las capas capaManzana = QgsProject.instance().mapLayer( self.ACA.obtenerIdCapa('manzana')) capaPuntos = QgsProject.instance().mapLayer( self.ACA.obtenerIdCapa('predios.num')) capaPredios = QgsProject.instance().mapLayer( self.ACA.obtenerIdCapa('predios.geom')) capaConstru = QgsProject.instance().mapLayer( self.ACA.obtenerIdCapa('construcciones')) capaCondH = QgsProject.instance().mapLayer( self.ACA.obtenerIdCapa('horizontales.geom')) #Puntos y eleccion de victima seleccion = self.iface.activeLayer().selectedFeatures() if seleccion == None: self.pluginFD.UTI.mostrarAlerta( 'Debes seleccionar un predio destino', QMessageBox().Critical, 'Error de seleccion') return listaPuntos = [None, None] #Definimos el predio 'victima if eleccion == 0: victima = 1 else: victima = 0 #eliminamos el predio no elegido self.eliminarNoElegido(seleccion[victima]) #Eliminar punto del predio no elegido for punto in capaPuntos.getFeatures(): if punto.geometry().intersects(seleccion[victima].geometry( )): #Bsucamos el punto del predio victima capaPuntos.startEditing() capaPuntos.dataProvider().deleteFeatures([punto.id()]) capaPuntos.triggerRepaint() capaPuntos.commitChanges() break #Generar geometria del predio fusionado rango = len(seleccion) geomFusion = seleccion[0].geometry() featFusion = QgsFeature() capaPredios.startEditing() #Generar geometria del predio fusionado for i in range(0, rango): self.iface.activeLayer().dataProvider().deleteFeatures( [seleccion[i].id()]) geomFusion = geomFusion.combine(seleccion[i].geometry()) #self.geom listaFinal = [] listaPrimera = [] featFusion.setGeometry(geomFusion) #Renombrar construcciones cuentaConstruccion = 1 capaConstru.startEditing() #--------Renombrar construcciones---- for construccion in capaConstru.getFeatures(): geomConstru = construccion.geometry() if geomConstru.buffer(-0.0000001, 1).intersects( geomFusion ): #Sacamos las construcciones dentro del predio fusionado listaPrimera.append(construccion) else: if self.contarIntegraciones( geomConstru.buffer(-0.0000001, 1), 'predios.geom' ) == 0: #Obtenemos los aleros del predio fusionado if geomConstru.buffer( 0.0000001, 1).intersection(geomFusion).area() > 0.000000001: listaPrimera.append(construccion) for construccion in listaPrimera: geomConstru = construccion.geometry() seIncluye = True for condominio in capaCondH.getFeatures(): geomHori = condominio.geometry() if geomConstru.buffer(-0.0000001, 1).intersects(geomHori): seIncluye = False break if seIncluye: listaFinal.append(construccion) supConst = 0 #Renombramos ls volumenes for construccion in listaFinal: geomConstru = construccion.geometry() construccion['nom_volumen'] = 'V' + str(cuentaConstruccion) niveles = construccion['num_niveles'] if niveles <= 0: niveles = 1 capaConstru.updateFeature(construccion) cuentaConstruccion += 1 supConst += (geomConstru.area() * niveles) capaConstru.commitChanges() #---------------------------------------------- #Estableer atributos del predio fusionado idx1 = capaPredios.fields().lookupField('sup_terr') idx2 = capaPredios.fields().lookupField('sup_contruccion') attr = seleccion[eleccion].attributes() attr[idx1] = geomFusion.area() attr[idx2] = supConst featFusion.setAttributes(attr) capaPredios.updateFeature(featFusion) capaPredios.dataProvider().addFeatures([featFusion]) capaPredios.triggerRepaint() capaPredios.commitChanges() self.UTI.mostrarAlerta('Fusion completada con exito', QMessageBox().Information, 'Fusion de predios') self.enFusion = False self.dlg.close() #----------------------------------------------------------------------------------- #Aqui contmaos cuantas geometrias de una capa toca una geomtrias especifica def contarIntegraciones(self, geometria, nombreCapa): capa = QgsProject.instance().mapLayersByName(nombreCapa)[0] cuenta = 0 for feat in capa.getFeatures(): if geometria.intersects(feat.geometry()): cuenta += 1 return cuenta #--------------------------------------------------------------------------- #Poinemos en lista de eliminados el predio no elegido def eliminarNoElegido(self, feat): campos = {} campos['wkt'] = feat.geometry().asWkt() campos['srid'] = 32614 campos['tabla'] = 'e_predio' atributos = {} capaPredios = QgsProject.instance().mapLayer( self.ACA.obtenerIdCapa('predios.geom')) nombresAtrbutos = capaPredios.fields() nombres = [campo.name() for campo in nombresAtrbutos] for x in range(0, len(nombres)): atributo = feat.attributes()[x] if str(feat.attributes()[x]) == "NULL": atributo = None atributos[str(nombres[x])] = atributo campos['attr'] = atributos campos['nuevo'] = False campos['eliminado'] = True listaTemp = QSettings().value('listaEliminada') listaTemp.append(campos) QSettings().setValue('listaEliminada', listaTemp) #-------------------------------------------------------------------------- #Activamos el modo de division def pasarAModoDivision(self, predio): #clave = self.dlg.comboPredios.currentText() #Obtenemos la clave del predio a editar clave = predio if clave == '': self.UTI.mostrarAlerta( 'Primero debes cargar una manzana de la seccion de consulta', QMessageBox().Critical, 'Error de cargado de predio') return capaPredios = QgsProject.instance().mapLayer( self.ACA.obtenerIdCapa('predios.geom')) #capaPredios.setReadOnly(False) #capaPredios.startEditing() self.predioEnDivision = None for predio in capaPredios.getFeatures( ): #Obtenemos el feature a dividr con base en la clave elegida if predio.attributes()[0] == clave: self.predioEnDivision = predio break if self.predioEnDivision != None: self.atributosAHeredar = self.predioEnDivision.attributes( ) #Obtenemos los atributos a heredar self.atributosAHeredar[1] = None #Ponemos le id como vacio self.rubberMarca.reset( QgsWkbTypes.PolygonGeometry) #Borramos la geometria amarillita self.UTI.mostrarAlerta( "Dibuja las lineas de corte sobre el predio indicado.\nRecuerda que los cortes no pueden estar sobre construcciones o condiminios.\nAsegurate que las lineas atraviesen el predio por completo\nNOTA: Las lineas solo afectaran al predio seleccionado.", QMessageBox().Information, "Subdivision de predios") self.cargoPredio = True self.encenderModoDividir() #Encendemos modo dividir # marca de amarillo el poligono del predio a subdividir self.geomEnDivision = self.predioEnDivision.geometry() self.pintarAreaPredioSubdiv() # zoom al predio a subdividir geometria = self.geomEnDivision bbox = geometria.boundingBox() iface.mapCanvas().setExtent(bbox) iface.mapCanvas().refresh() # comportamiento de botones self.dlg.btnFusionar.setEnabled(False) self.dlg.btnCancelarSub.setEnabled(True) self.dlg.btnCargarPredio.setEnabled(False) self.dlg.comboPredios.setEnabled(False) self.dlg.comboPredios.setEnabled(False) self.dlg.btnConfirmarCortes.setEnabled(True) self.dlg.btnDeshacerTodo.setEnabled(True) self.dlg.btnDeshacerCortes.setEnabled(True) self.dlg.btnLlamarCalcular.setEnabled(True) self.enSubdivision = True else: self.UTI.mostrarAlerta('El predio no fue encontrado', QMessageBox().Critical, 'Error de cargado de predio') #------------------------------------------------------------------------- def cancelarSubdivision(self): mensaje = "El modo de division se apagara, el progreso se perdera\nDeseas continuar?" respuesta = QMessageBox.question(iface.mainWindow(), "Cancelar subdivision", mensaje, QMessageBox.Yes, QMessageBox.No) #Si el usuario acepta.... if respuesta == QMessageBox.Yes: self.vaciarRubbers() self.predioEnDivision = None self.geomEnDivision = None self.modoDividir = False self.modoEliminar = False self.apagarHerramientas() self.dlg.btnCancelarSub.setEnabled(False) self.dlg.btnCargarPredio.setEnabled(True) self.dlg.comboPredios.setEnabled(True) self.dlg.btnFusionar.setEnabled(True) self.dlg.btnConfirmarCortes.setEnabled(False) self.dlg.btnDeshacerCortes.setEnabled(False) self.dlg.btnLlamarCalcular.setEnabled(False) self.dlg.btnApagarHerramientas.setEnabled(False) self.dlg.btnEliminarCortes.setEnabled(False) self.dlg.btnDibujarCortes.setEnabled(False) self.dlg.btnEditarCortes.setEnabled(False) self.dlg.btnDeshacerTodo.setEnabled(False) self.enSubdivision = False #----------------------------------------------------------------------------------- #-------------------------------------------- def confirmarCortes(self): #Aqui cehcamos que los cortes esten en orden print(self.eventos.relaciones) #cuentaCortes = 0 #rango = corte rango = len(self.eventos.relaciones) - 1 #geoTemp = geo geoTemp = QgsGeometry.fromWkt(self.geomEnDivision.asWkt()) print('------------------------------') print(geoTemp) print('------------------------------') cuentaSalida = self.subdividirPredio( geoTemp, True ) - 1 #Aqui enviamos una geomtria temporal, para ven en cuantos cortes quedara print(cuentaSalida) if cuentaSalida >= 2: listaNoTocar = [] capaPredios = QgsProject.instance().mapLayer( self.ACA.obtenerIdCapa('predios.geom')) capaCondH = QgsProject.instance().mapLayersByName( 'horizontales.geom')[0] capaCondV = QgsProject.instance().mapLayersByName('verticales')[0] capaConstru = QgsProject.instance().mapLayer( self.ACA.obtenerIdCapa('construcciones')) #Obtenemos los features que no deben tocarse for feat in capaConstru.getFeatures(): geom = feat.geometry().buffer(-0.0000002, 1) if geom.intersects(self.geomEnDivision): listaNoTocar.append(geom) for feat in capaCondH.getFeatures(): geom = feat.geometry().buffer(-0.0000002, 1) if geom.intersects(self.geomEnDivision): listaNoTocar.append(geom) for feat in capaCondV.getFeatures(): geom = feat.geometry().buffer(-0.0000002, 1) if geom.intersects(self.geomEnDivision): listaNoTocar.append(geom) bandera = True #Aqui checamos que cada linea no toque lo no tocable for i in range(0, rango): for comp in listaNoTocar: geom = self.eventos.relaciones[i].geom if geom != None: if geom.buffer(0.0000001, 1).intersects(comp): bandera = False self.eventos.relaciones[i].rubber.setStrokeColor( QColor(255, 0, 0, 255)) else: self.eventos.relaciones[i].rubber.setStrokeColor( QColor(0, 61, 240, 255)) iface.mapCanvas().refresh() if bandera: #Si todo esta en orden self.eventos.rubberPunto.reset(QgsWkbTypes.PointGeometry) self.apagarHerramientas() #mostramos mensaje de confirmacion mensaje = "La cantidad de predios que quedaran como resultado, es de: " + str( cuentaSalida) + "\nDeseas continua?" respuesta = QMessageBox.question( iface.mainWindow(), "Nota de subdivision de predio", mensaje, QMessageBox.Yes, QMessageBox.No) #Si el usuario acepta.... if respuesta == QMessageBox.Yes: self.subdividirPredio(self.geomEnDivision, False) self.rubberMarca.reset( QgsWkbTypes.PolygonGeometry) #Quitamos lo amarillito for i in range(0, rango): self.eventos.relaciones[i].rubber.reset( QgsWkbTypes.LineGeometry) self.eventos.relaciones[i].vaciarMarcadores() self.eventos.recargarRelaciones() capaPredios.startEditing() capaPredios.dataProvider().deleteFeatures( [self.predioEnDivision.id()]) capaPredios.triggerRepaint() capaPredios.commitChanges() self.VentanaAreas.close() self.limpiarAreas() self.vaciarRubbers() self.UTI.mostrarAlerta( "La division ha sido realizada con exito\nLos cambios se guardaran hasta que asignes las claves.", QMessageBox().Information, "Subdivision completa, Parte 1 de 2") self.irAClaves( ) #Mostramos la ventana que llena las claves iface.actionSelect().trigger() else: self.UTI.mostrarAlerta( "Las lineas de division no deben atravesar construcciones ni condominios\nLas lineas rojas presentan un corte invalido", QMessageBox().Critical, "Error en subdivision") else: self.UTI.mostrarAlerta( "Primero debes dibujar las lineas de corte\nAsegurate que las lineas atraviesen por completo el predio", QMessageBox().Critical, "Error en subdivision") #print(cuentaSalida) ################################################################################## def vaciarLineasCorte(self): rango = len(self.eventos.relaciones) - 1 for i in range(0, rango): self.eventos.relaciones[i].rubber.reset(QgsWkbTypes.LineGeometry) self.eventos.relaciones[i].vaciarMarcadores() self.eventos.recargarRelaciones() #------------------------------------------------------------------------------------- def subdividirPredio(self, geometria, modoPre): #Subdividir capaHori = QgsProject.instance().mapLayersByName( 'horizontales.geom')[0] capaPredio = QgsProject.instance().mapLayer( self.ACA.obtenerIdCapa('predios.geom')) capaVert = QgsProject.instance().mapLayersByName('verticales')[0] self.listaNuevosPredios = [] self.geomsAreas = [] listaParam = [] #La lista que llega al fileteo #rango = corte rango = len(self.eventos.relaciones) - 1 #print('**********************************************') #print(self.eventos.relaciones) #print(rango) #print('**********************************************') for i in range(0, rango): geom = self.eventos.relaciones[i].geom print('-----------------*****------------------------') print(self.eventos.relaciones[i]) print(geom) print('-----------------*****------------------------') if geom != None: listaParam.append( geom.asPolyline()) #Generamos los polyline van a partir #print('aaaaaaaaaaa', listaParam) salida = self.filetear( geometria, listaParam) #Mandamos filetear el poligono con las lineas if modoPre: #Si es modoPre, es solo para visaulizar cuantos poligonos quedarian... for cadaUno in salida: self.geomsAreas.append(cadaUno) return len(salida) else: #Si no, efectuamos realmente el corte for cadaUno in salida: if cadaUno.isEmpty(): continue nuevoFeat = QgsFeature() nuevoFeat.setGeometry(cadaUno) #Agregamos cada predio a la capa y le ponemos sus atributos self.asignarAtributos(nuevoFeat) capaPredio.startEditing() capaPredio.dataProvider().addFeatures([nuevoFeat]) capaPredio.triggerRepaint() capaPredio.commitChanges() self.listaNuevosPredios.append(nuevoFeat.geometry().asWkt()) self.apagarHerramientas() self.dlg.btnCargarPredio.setEnabled(True) ################################################################################## #Metodo para filetear los predios con lineas def filetear(self, poligono, lineas): listaActuales = [] #Lista de las geometrias en espera de ser cortadas listaActuales.append( poligono) #Agregamos el poligono a cortar en la lista de espera listaSiguiente = [ poligono ] #Agregamos le poligono a cortar en la lista de la siguiente interacion for linea in lineas: #Iteramos cada linea de corte listaActuales = listaSiguiente #Igualamos la lista de corte a la iteracion anterior listaSiguiente = [ ] #Vaciamos la lista que dara lugar a la siguiente iteracion de corte for actual in listaActuales: #Checamos cada geometria en espera partida = actual.splitGeometry( linea, True ) #Aplicamos el split geometry de qgis, vamos partiendo el poligono if len(partida[1] ) == 0: #Esto ocurre cuando el corte no hizo nada listaSiguiente.append( actual ) #Asi que nos quedamos con la geometria tal cual esta else: #Cuando si hubo corte parte1 = partida[1][ 0] #obtenemos la geometria resultante del corte, VER DOCUMENTACION DE SPLITGEOMETRY PARA ENTENDER parte2 = actual.difference( parte1 ) #Al poligono que se corto, le quitamos la parte previa al corte anterior #De esta forma nos quedamos con la geometria partida en 2 if parte1.area( ) > 0.0: #Checamos que el area de esta parte sea mayor que 0, por motivos de los decimales listaSiguiente.append( parte1 ) #Si es asi, significa un fragmento que puede ser cortado por otra linea if parte2.area() > 0.0: #Lo mismo listaSiguiente.append(parte2) temporal = poligono #Obtenemos una geometria igualita al poligono entrannte for geomSal in listaSiguiente: #Obtenemos las diferencia respeto a los poligonos obtenidos y el entrante, lo que resulte, tambien es parte del corte temporal = temporal.difference(geomSal.buffer(0.0000001, 1)) listaSiguiente.append(temporal) #Aqui ponemos todas las geometrias return listaSiguiente #Retornamos la lista #------------------------------------------------------------------------- def encenderModoDividir(self): #Activamos el modo de dividir self.eventos.modoDividir = True self.eventos.modoEliminar = False self.eventos.modoEditar = False self.dlg.btnDibujarCortes.setEnabled(False) self.dlg.btnEditarCortes.setEnabled(True) self.dlg.btnEliminarCortes.setEnabled(True) self.dlg.btnApagarHerramientas.setEnabled(True) self.dlg.btnConfirmarCortes.setEnabled(True) self.dlg.btnDeshacerTodo.setEnabled(True) self.dlg.btnCargarPredio.setEnabled(False) #iface.mapCanvas().setCursor(self.DBJ.eventos.cursorRedondo) iface.mapCanvas().setCursor(self.UTI.cursorRedondo) if not self.eventos.botonAD.isChecked(): self.eventos.botonAD.trigger() #---------------------------------------------------------------------------- def encenderModoEditar(self): #Activamos el modo de dividir self.eventos.modoDividir = False self.eventos.modoEliminar = False self.eventos.modoEditar = True self.dlg.btnDibujarCortes.setEnabled(True) self.dlg.btnEditarCortes.setEnabled(False) self.dlg.btnEliminarCortes.setEnabled(True) self.dlg.btnApagarHerramientas.setEnabled(True) self.dlg.btnConfirmarCortes.setEnabled(True) self.dlg.btnDeshacerTodo.setEnabled(True) self.dlg.btnCargarPredio.setEnabled(False) #iface.mapCanvas().setCursor(self.DBJ.eventos.cursorRedondo) iface.mapCanvas().setCursor(self.UTI.cursorRedondo) if not self.eventos.botonAD.isChecked(): self.eventos.botonAD.trigger() #---------------------------------------------------------------------------- def encenderModoEliminar(self): #Activamos el modo de eliminar self.eventos.modoDividir = False self.eventos.modoEliminar = True self.eventos.modoEditar = False self.dlg.btnDibujarCortes.setEnabled(True) self.dlg.btnEditarCortes.setEnabled(True) self.dlg.btnEliminarCortes.setEnabled(False) self.dlg.btnApagarHerramientas.setEnabled(True) self.dlg.btnConfirmarCortes.setEnabled(True) self.dlg.btnCargarPredio.setEnabled(False) #iface.mapCanvas().setCursor(self.DBJ.eventos.cursorCuadro) iface.mapCanvas().setCursor(self.UTI.cursorCuadro) if self.eventos.botonAD.isChecked(): self.eventos.botonAD.trigger() #---------------------------------------------------------------------------- def apagarHerramientas(self): #Apagamos las herramientas self.eventos.modoDividir = False self.eventos.modoEliminar = False self.eventos.modoEditar = False self.dlg.btnDibujarCortes.setEnabled(True) self.dlg.btnEliminarCortes.setEnabled(True) self.dlg.btnEditarCortes.setEnabled(True) self.dlg.btnApagarHerramientas.setEnabled(False) self.dlg.btnConfirmarCortes.setEnabled(True) self.dlg.btnCargarPredio.setEnabled(False) #iface.mapCanvas().setCursor(self.DBJ.eventos.cursorCruz) iface.mapCanvas().setCursor(self.UTI.cursorCruz) if self.eventos.botonAD.isChecked(): self.eventos.botonAD.trigger() #----------------------------------------------------------------- def rollBack(self): #Deshacemos cambios mensaje = "Todos los cambio se perderan, el area de trabajo se limpiara... deseas continuar?" respuesta = QMessageBox.question(iface.mainWindow(), "Cancelar cambios", mensaje, QMessageBox.Yes, QMessageBox.No) #Si el usuario acepta.... if respuesta == QMessageBox.Yes: self.eventos.modoDividir = False self.eventos.modoEliminar = False self.dlg.close() self.VentanaClaves.dlg.close() self.vaciarRubbers() self.predioEnDivision = None self.geomEnDivision = None self.VentanaAreas.close() self.UTI.limpiarCanvas() #------------------------------------------------------------ def vaciarRubbers(self): rango = len(self.eventos.relaciones) - 1 for i in range(0, rango): self.eventos.relaciones[i].rubber.reset(QgsWkbTypes.LineGeometry) #self.eventos.relaciones[i].geom = None self.eventos.relaciones[i].vaciarMarcadores() self.eventos.recargarRelaciones() self.rubberMarca.reset(QgsWkbTypes.PolygonGeometry) #self.eventos.vaciarMarcadores() #----------------------------------------------------------------- def asignarAtributos(self, feat): #Asignamos los atributos capaPredios = QgsProject.instance().mapLayer( self.ACA.obtenerIdCapa('predios.geom')) campos = capaPredios.fields() nombres = [campo.name() for campo in campos] listaAsignacion = [] for nombre in nombres: idx = capaPredios.fields().lookupField(nombre) if nombre == 'sup_terr': attr = feat.geometry().area() elif nombre == 'sup_contruccion': attr = self.calcularSupConst(feat) elif nombre == 'clave': attr = '' elif nombre == 'cve_cat': attr = '' elif nombre == 'id': attr = '' elif nombre == 'cve_usuario': attr = self.UTI.decodeRot13(QSettings().value('usuario')) else: attr = self.predioEnDivision.attributes()[idx] listaAsignacion.append(attr) capaPredios.startEditing() feat.setAttributes(listaAsignacion) capaPredios.triggerRepaint() capaPredios.commitChanges() #------------------------------------------------------------ def calcularSupConst(self, feat): #calculamos superficie de construccion capaConstru = QgsProject.instance().mapLayer( self.ACA.obtenerIdCapa('construcciones')) capaCondH = QgsProject.instance().mapLayer( self.ACA.obtenerIdCapa('horizontales.geom')) listaFinal = [] listaPrimera = [] #Renombrar construcciones cuentaConstruccion = 1 capaConstru.startEditing() geomFeat = feat.geometry() #--------Renombrar construcciones---- for construccion in capaConstru.getFeatures(): geomConstru = construccion.geometry() if geomConstru.buffer(-0.0000001, 1).intersects( geomFeat ): #Sacamos las construcciones dentro del predio fusionado listaPrimera.append(construccion) else: if self.contarIntegraciones( geomConstru.buffer(-0.0000001, 1), 'predios.geom' ) == 0: #Obtenemos los aleros del predio fusionado if geomConstru.buffer( 0.0000001, 1).intersection(geomFeat).area() > 0.000000001: listaPrimera.append(construccion) for construccion in listaPrimera: geomConstru = construccion.geometry() seIncluye = True for condominio in capaCondH.getFeatures(): geomHori = condominio.geometry() if geomConstru.buffer(-0.0000001, 1).intersects(geomHori): seIncluye = False break if seIncluye: listaFinal.append(construccion) supConst = 0 #Renombramos ls volumenes for construccion in listaFinal: geomConstru = construccion.geometry() construccion['nom_volumen'] = 'V' + str(cuentaConstruccion) niveles = construccion['num_niveles'] if niveles <= 0: niveles = 1 capaConstru.updateFeature(construccion) cuentaConstruccion += 1 supConst += (geomConstru.area() * niveles) capaConstru.triggerRepaint() capaConstru.commitChanges() return supConst #-------------------------------------------------------------------------------------------------- def irAClaves(self): #Pintamos la ventanita de asignar clavees self.VentanaClaves.predioOriginal = self.predioEnDivision self.VentanaClaves.obtieneCapaPredios() self.VentanaClaves.dlg.show() self.dlg.btnDibujarCortes.setEnabled(False) self.dlg.btnEditarCortes.setEnabled(False) self.dlg.btnEliminarCortes.setEnabled(False) self.dlg.btnApagarHerramientas.setEnabled(False) self.dlg.btnConfirmarCortes.setEnabled(False) self.dlg.btnCargarPredio.setEnabled(False) self.dlg.btnDeshacerCortes.setEnabled(False) self.dlg.btnLlamarCalcular.setEnabled(False) self.dlg.btnCancelarSub.setEnabled(False) self.dlg.comboPredios.setEnabled(False) self.enClaves = True #------------------------------------------------------------------------- def irAreas(self): self.limpiarAreas() self.rubberMarca.reset(QgsWkbTypes.PolygonGeometry) geoTemp = QgsGeometry.fromWkt(self.geomEnDivision.asWkt()) self.subdividirPredio(geoTemp, True) self.listaColores = [] for geom in self.geomsAreas: if geom.area() <= 0: continue newRub = self.eventos.crearNuevoRubberPoly() # obtener una lista de vertices del tipo QgsPointXY listaVertices = self.UTI.obtenerVerticesPoligono(geom) listaVertices.append(listaVertices[0]) rangoVertices = len(listaVertices) for x in range(0, rangoVertices - 2): newRub.addPoint(listaVertices[x], True) newRub.show() self.rubbersAreas.append(newRub) self.VentanaAreas.mostrarAreas() #-------------------------------------------------------------------- def limpiarAreas(self): for rub in self.rubbersAreas: rub.reset(QgsWkbTypes.PolygonGeometry) self.rubbersAreas = [] #------------------------------------------------------------------ def quitarAreas(self): self.limpiarAreas() n = 0 #Obtenemos todos los vertices de la geometria en division if self.geomEnDivision == None: return self.pintarAreaPredioSubdiv() ''' ver = self.geomEnDivision.vertexAt(0) listaVertices = [] while(ver != QgsPoint(0,0)): n +=1 ver=self.geomEnDivision.vertexAt(n) listaVertices.append(ver) listaVertices.append(listaVertices[0]) rangoVertices = len(listaVertices) for x in range(0, rangoVertices-2): vertice = listaVertices[x] self.rubberMarca.addPoint(QgsPointXY(vertice.x(), vertice.y()), True) self.rubberMarca.show() #Aqui pintamos de amarillito la geometria en division ''' #-------------------------------------------------------------------------- def pintarAreaPredioSubdiv(self, geom=None): if geom is None: geom = self.geomEnDivision polygon = geom.asPolygon() listaVertices = [] n = len(polygon[0]) for i in range(n): listaVertices.append(polygon[0][i]) listaVertices.append(listaVertices[0]) rangoVertices = len(listaVertices) for x in range(0, rangoVertices - 2): self.rubberMarca.addPoint(listaVertices[x], True) self.rubberMarca.show( ) #Aqui pintamos de amarillito la geometria en division def consumeWSGeneral(self, url_cons=""): url = url_cons data = "" try: self.headers['Authorization'] = self.UTI.obtenerToken() response = requests.get(url, headers=self.headers) except requests.exceptions.RequestException as e: self.createAlert( "Error de servidor--, 'consumeWSGeneral()' '" + str(e) + "'", QMessageBox().Critical, "Error de servidor") return if response.status_code == 200: data = response.content elif response.status_code == 403: self.createAlert('Sin Permisos para ejecutar la acción', QMessageBox().Critical, "Usuarios") return None else: self.createAlert( 'Error en peticion "consumeWSGeneral()":\n' + response.text, QMessageBox().Critical, "Error de servidor") return return json.loads(data) def createAlert(self, mensaje, icono=QMessageBox().Critical, titulo='Operaciones'): #Create QMessageBox self.msg = QMessageBox() #Add message self.msg.setText(mensaje) #Add icon of critical error self.msg.setIcon(icono) #Add tittle self.msg.setWindowTitle(titulo) #Show of message dialog self.msg.show() # Run the dialog event loop result = self.msg.exec_()
self.ui.statusBar.showMessage(text) ## =============自定义槽函数=============================== ## ===========窗体测试程序================================= if __name__ == "__main__": #用于当前窗体测试 app = QApplication(sys.argv) #创建GUI应用程序 # 读取注册表里的语言设置 QCoreApplication.setOrganizationName("mySoft") QCoreApplication.setApplicationName("Demo11_1") ##organization="mySoft" #用于注册表 ##appName="Demo11_1" #HKEY_CURRENT_USER/Software/mySoft/Demo11_1 regSettings=QSettings(QCoreApplication.organizationName(), QCoreApplication.applicationName()) #创建 Language=regSettings.value("Language","EN") #读取Language键的值,缺省"EN" trans=QTranslator() if Language=="EN": trans.load("appLang_EN.qm") else: trans.load("appLang_CN.qm") QCoreApplication.installTranslator(trans) form=QmyMainWindow() #创建窗体 form.setTranslator(trans,Language) #赋值给QmyMainWindow的类变量translator form.show() sys.exit(app.exec_())
class LanguageManager(): mInstance = None def instance(): if (not LanguageManager.mInstance): LanguageManager.mInstance = LanguageManager() return LanguageManager.mInstance def deleteInstance(): del LanguageManager.mInstance LanguageManager.mInstance = None ## # Installs the translators on the application for Qt and Tiled. Should be # called again when the language changes. ## def installTranslators(self): # Delete previous translators del self.mQtTranslator del self.mAppTranslator self.mQtTranslator = QTranslator() self.mAppTranslator = QTranslator() language = preferences.Preferences.instance().language() if language == '': language = QLocale.system().name() qtTranslationsDir = QLibraryInfo.location( QLibraryInfo.TranslationsPath) if (self.mQtTranslator.load("qt_" + language, qtTranslationsDir)): QCoreApplication.installTranslator(self.mQtTranslator) else: del self.mQtTranslator self.mQtTranslator = None if (self.mAppTranslator.load("tiled_" + language, self.mTranslationsDir)): QCoreApplication.installTranslator(self.mAppTranslator) else: del self.mAppTranslator self.mAppTranslator = None ## # Returns the available languages as a list of country codes. ## def availableLanguages(self): if (self.mLanguages.isEmpty()): self.loadAvailableLanguages() return self.mLanguages def __init__(self): self.mQtTranslator = None self.mAppTranslator = None self.mLanguages = QStringList() self.mTranslationsDir, _ = os.path.split(sys.argv[0]) if sys.platform == 'win32': self.mTranslationsDir += "/../translations" elif sys.platform == 'darwin': self.mTranslationsDir += "/../Translations" else: self.mTranslationsDir += "/../share/tiled/translations" def __del__(self): del self.mQtTranslator del self.mAppTranslator def loadAvailableLanguages(self): self.mLanguages.clear() nameFilters = QStringList() nameFilters.append("tiled_*.qm") iterator = QDirIterator(self.mTranslationsDir, nameFilters, QDir.Files | QDir.Readable) while (iterator.hasNext()): iterator.next() baseName = iterator.fileInfo().completeBaseName() # Cut off "tiled_" from the start self.mLanguages.append(baseName[6:])
app = QCoreApplication(sys.argv) # Load POT template (all English strings) POT_source = open(os.path.join(language_path, 'OpenShot', 'OpenShot.pot')).read() all_strings = re.findall('^msgid \"(.*)\"', POT_source, re.MULTILINE) print("Scanning {} strings in all translation files...".format( len(all_strings))) # Loop through folders/languages for filename in fnmatch.filter(os.listdir(language_path), 'OpenShot.*.qm'): lang_code = filename[:-3] # Install language translator = QTranslator(app) # Load translation if translator.load(lang_code, language_path): app.installTranslator(translator) print("\n=================================================") print("Showing translations for {}".format(filename)) print("=================================================") # Loop through all test strings for source_string in all_strings: translated_string = app.translate("", source_string) if source_string != translated_string: print(' {} => {}'.format(source_string, translated_string)) # Remove translator app.removeTranslator(translator)
class Ui_Form_Manager(Ui_Form): def __init__(self, ax, canvas, config: configparser.ConfigParser, config_path: str, lang: str): self.ax = ax self.canvas = canvas self.config = config self.config_path = config_path self.dialog = QtWidgets.QDialog() self.setupUi(self.dialog) self.retranslateUi(self.dialog) # 翻译家 self.trans = QTranslator() lang_qm = os.path.join(os.path.dirname(self.config_path), 'langs/{}.qm'.format(lang)) self.trans.load(lang_qm) _app = QApplication.instance() # 获取app实例 _app.installTranslator(self.trans) # 重新翻译主界面 self.retranslateUi(self.dialog) self.init_gui() self.pushButton.clicked.connect(self.confirm_slot) self.pushButton_2.clicked.connect(self.cancel_slot) self.pushButton_3.clicked.connect(self.apply_slot) self.pushButton_4.clicked.connect(self.get_all_fonts) self.dialog.exec_() # 初始化之后再执行 def init_gui(self): self.get_all_fonts() self.set_combox_items() self.get_all_settings() self.lineEdit.setText(self.ax.get_xlabel()) self.lineEdit_2.setText(self.ax.get_ylabel()) try: self.lineEdit_3.setText(self.ax.get_zlabel()) # 如果没有z轴,这个输入框变灰 except Exception as e: self.lineEdit_3.setDisabled(True) if self.canvas.figure._suptitle: self.lineEdit_4.setText(self.canvas.figure._suptitle.get_text()) self.lineEdit_5.setText(self.ax.get_title()) self.lineEdit_6.setText( str(tuple([round(i, 2) for i in self.ax.get_xlim()]))) self.lineEdit_7.setText( str(tuple([round(i, 2) for i in self.ax.get_ylim()]))) try: self.lineEdit_8.setText( str(tuple([round(i, 2) for i in self.ax.get_zlim()]))) except Exception as e: self.lineEdit_8.setDisabled(True) # 刻度间隔不好获取,所以就默认留空 # self.lineEdit_9.setText(self.ax.xaxis.get_major_locator()) # self.lineEdit_10.setText(self.ax.yaxis.get_major_locator()) try: self.ax.zaxis.get_major_locator() except Exception as e: self.lineEdit_11.setDisabled(True) try: self.ax.zaxis.get_minor_locator() except Exception as e: self.lineEdit_14.setDisabled(True) def apply_slot(self): self.ax.set_xlabel(self.lineEdit.text()) self.ax.set_ylabel(self.lineEdit_2.text()) if self.lineEdit_3.isEnabled(): self.ax.set_zlabel(self.lineEdit_3.text()) if self.lineEdit_4.isModified(): self.canvas.figure.suptitle(self.lineEdit_4.text()) if self.lineEdit_5.isModified(): self.ax.set_title(self.lineEdit_5.text()) if self.lineEdit_6.isModified(): value = self._is_right_tuple(self.lineEdit_6.text(), "X坐标轴范围输入有误") self.ax.set_xlim(value) if self.lineEdit_7.isModified(): value = self._is_right_tuple(self.lineEdit_7.text(), "Y坐标轴范围输入有误") self.ax.set_ylim(value) if self.lineEdit_8.isEnabled() and self.lineEdit_8.isModified(): value = self._is_right_tuple(self.lineEdit_6.text(), "Z坐标轴范围输入有误") self.ax.set_zlim(value) try: if self.lineEdit_9.isModified(): self.ax.xaxis.set_major_locator( MultipleLocator(ast.literal_eval(self.lineEdit_9.text()))) if self.lineEdit_10.isModified(): self.ax.yaxis.set_major_locator( MultipleLocator(ast.literal_eval(self.lineEdit_10.text()))) if self.lineEdit_11.isModified(): self.ax.zaxis.set_major_locator( MultipleLocator(ast.literal_eval(self.lineEdit_11.text()))) if self.lineEdit_12.isModified(): self.ax.xaxis.set_minor_locator( MultipleLocator(ast.literal_eval(self.lineEdit_12.text()))) if self.lineEdit_13.isModified(): self.ax.yaxis.set_minor_locator( MultipleLocator(ast.literal_eval(self.lineEdit_13.text()))) if self.lineEdit_14.isModified(): self.ax.zaxis.set_minor_locator( MultipleLocator(ast.literal_eval(self.lineEdit_14.text()))) except Exception as e: QtWidgets.QMessageBox.warning(self.dialog, "错误", "坐标轴刻度输入有误,请确保输入的是数字,且主刻度间隔>次刻度间隔") return self.set_all_settings() with open(self.config_path, "w+", encoding='utf-8') as f: self.config.write(f) def _is_right_tuple(self, tuple_str, message): try: value = tuple(ast.literal_eval(tuple_str)) assert len(value) == 2 assert str(value[0]).isdigit() and str(value[1]).isdigit() return value except Exception as e: QtWidgets.QMessageBox.warning(self.dialog, "错误", message) return def _is_digit(self, num_str): value = re.compile(r'^[-+]?[0-9]+\.[0-9]+$') result = value.match(num_str) if result: return True else: return False def confirm_slot(self): self.apply_slot() self.dialog.close() def cancel_slot(self): self.dialog.close() def get_all_fonts(self): self.fonts = dict() for font in fontManager.ttflist: self.fonts.update({font.name: font.fname}) self.comboBox.addItems( sorted(self.fonts.keys(), key=lambda x: x.lower())) self.comboBox_2.addItems( sorted(self.fonts.keys(), key=lambda x: x.lower())) self.comboBox_3.addItems( sorted(self.fonts.keys(), key=lambda x: x.lower())) def get_all_settings(self): # font if os.path.exists(self.config['font']['local_font_path']): self.comboBox.setCurrentText(self.config['font']['local_font']) if os.path.exists(self.config['font']['english_font_path']): self.comboBox_2.setCurrentText(self.config['font']['english_font']) if os.path.exists(self.config['font']['mix_font_path']): self.comboBox_3.setCurrentText(self.config['font']['mix_font']) # annotation self.lineEdit_16.setText(self.config['annotation']['axis_style']) self.comboBox_8.setCurrentText(self.config['annotation']['bg_color']) self.comboBox_12.setCurrentText( self.config['annotation']['border_color']) self.lineEdit_17.setText(self.config['annotation']['border']) self.lineEdit_19.setText(self.config['annotation']['offset']) self.lineEdit_20.setText(self.config['annotation']['arrow_width']) self.comboBox_9.setCurrentText( self.config['annotation']['arrow_color']) self.comboBox_10.setCurrentText( self.config['annotation']['arrow_shape']) self.lineEdit_21.setText(self.config['annotation']['text_size']) self.comboBox_11.setCurrentText( self.config['annotation']['text_color']) self.checkBox_2.setChecked( eval(self.config['annotation']['show_point'])) self.checkBox_4.setChecked(eval( self.config['annotation']['show_text'])) self.checkBox_5.setChecked( eval(self.config['annotation']['show_arrow'])) # grid self.comboBox_4.setCurrentText(self.config['grid']['axis']) self.comboBox_5.setCurrentText(self.config['grid']['color']) self.comboBox_6.setCurrentText(self.config['grid']['which']) self.comboBox_7.setCurrentText(self.config['grid']['linestyle']) self.lineEdit_15.setText(self.config['grid']['linewidth']) # draw self.comboBox_13.setCurrentText(self.config['draw']['tab']) self.lineEdit_18.setText(self.config['draw']['width']) self.lineEdit_22.setText(self.config['draw']['height']) self.lineEdit_23.setText(self.config['draw']['dpi']) self.comboBox_14.setCurrentText(self.config['draw']['style']) def set_all_settings(self): # font self.config.set('font', 'local_font', self.comboBox.currentText()) self.config.set('font', 'local_font_path', self.fonts[self.comboBox.currentText()]) self.config.set('font', 'english_font', self.comboBox_2.currentText()) self.config.set('font', 'english_font_path', self.fonts[self.comboBox_2.currentText()]) self.config.set('font', 'mix_font', self.comboBox_3.currentText()) self.config.set('font', 'mix_font_path', self.fonts[self.comboBox_3.currentText()]) # annotation self.config['annotation']['axis_style'] = self.lineEdit_16.text() self.config['annotation']['bg_color'] = self.comboBox_8.currentText() self.config['annotation'][ 'border_color'] = self.comboBox_12.currentText() self.config['annotation']['border'] = self.lineEdit_17.text() self.config['annotation']['offset'] = self.lineEdit_19.text() self.config['annotation']['arrow_width'] = self.lineEdit_20.text() self.config['annotation']['arrow_color'] = self.comboBox_9.currentText( ) self.config['annotation'][ 'arrow_shape'] = self.comboBox_10.currentText() self.config['annotation']['text_size'] = self.lineEdit_21.text() self.config['annotation']['text_color'] = self.comboBox_11.currentText( ) self.config['annotation']['show_point'] = str( self.checkBox_2.isChecked()) self.config['annotation']['show_text'] = str( self.checkBox_4.isChecked()) self.config['annotation']['show_arrow'] = str( self.checkBox_5.isChecked()) # grid self.config['grid']['axis'] = self.comboBox_4.currentText() self.config['grid']['color'] = self.comboBox_5.currentText() self.config['grid']['which'] = self.comboBox_6.currentText() self.config['grid']['linestyle'] = self.comboBox_7.currentText() self.config['grid']['linewidth'] = self.lineEdit_15.text() # draw self.config['draw']['tab'] = self.comboBox_13.currentText() self.config['draw']['width'] = self.lineEdit_18.text() self.config['draw']['height'] = self.lineEdit_22.text() self.config['draw']['dpi'] = self.lineEdit_23.text() self.config['draw']['style'] = self.comboBox_14.currentText() def set_combox_items(self): index = 0 self.color_dict = dict() self.color_dict.update(mcolors.BASE_COLORS) self.color_dict.update(mcolors.TABLEAU_COLORS) self.color_dict.update(mcolors.CSS4_COLORS) self.color_dict.update(mcolors.XKCD_COLORS) color = QtGui.QColor() for color_name in self.color_dict.keys(): self.comboBox_5.addItem(color_name) self.comboBox_8.addItem(color_name) self.comboBox_9.addItem(color_name) self.comboBox_11.addItem(color_name) self.comboBox_12.addItem(color_name) color.setNamedColor(mcolors.to_hex(color_name)) self.comboBox_5.model().item(index).setBackground(color) self.comboBox_8.model().item(index).setBackground(color) self.comboBox_9.model().item(index).setBackground(color) self.comboBox_11.model().item(index).setBackground(color) self.comboBox_12.model().item(index).setBackground(color) index += 1 self.comboBox_4.addItems(grid_axis) self.comboBox_6.addItems(grid_which) self.comboBox_7.addItems(linestyles) self.comboBox_10.addItems(arrowstyles) self.comboBox_13.addItems(draw_tabs) styles_list = plt.style.available styles_list.append('None') styles_list = sorted(styles_list, key=lambda x: x.lower()) self.comboBox_14.addItems(styles_list)
class BuildingBeta: """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', 'BuildingBeta_{}.qm'.format(locale)) if os.path.exists(locale_path): self.translator = QTranslator() self.translator.load(locale_path) if qVersion() > '4.3.3': QCoreApplication.installTranslator(self.translator) # Create the dialog (after translation) and keep reference self.dlg = BuildingBetaDialog() # Declare instance attributes self.actions = [] self.menu = self.tr(u'&Building Beta API') # TODO: We are going to let the user set this up in a future iteration self.toolbar = self.iface.addToolBar(u'BuildingBeta') self.toolbar.setObjectName(u'BuildingBeta') #bj 10/5/2018 self.dlg.lineEdit.clear() #self.dlg.pushButton.clicked.connect(self.select_output_file) self.dlg.pushButton.clicked.connect(self.embedded_address_search) #self.dlg.comboBox. self.dlg.pushButton_2.clicked.connect(self.embedded_select_address) # 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('BuildingBeta', 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/building_beta/icon.png' self.add_action(icon_path, text=self.tr(u'Building Beta API'), callback=self.run, parent=self.iface.mainWindow()) def unload(self): """Removes the plugin menu item and icon from QGIS GUI.""" for action in self.actions: self.iface.removePluginMenu(self.tr(u'&Building Beta API'), action) self.iface.removeToolBarIcon(action) # remove the toolbar del self.toolbar def run(self): """Run method that performs all the real work""" # show the dialog self.dlg.show() # Run the dialog event loop result = self.dlg.exec_() # See if OK was pressed if result: # Do something useful here - delete the line containing pass and # substitute with your code. pass def embedded_address_search(self): bl_url = 'https://api.psma.com.au/beta/v1/addresses/?addressString=?' #key = credentials.API_KEY # bl_url = 'https://api.psma.com.au/beta/v1/' headers = {"Authorization": key, "Accept": "application/json"} address_name = self.dlg.lineEdit.text() print(address_name) address_name_format = re.sub(' ', '%20', address_name) # address_name_format = self.(padAddress) ### eg from above.... self.dlg.pushButton.clicked.connect(self.embedded_address_search) bl_address_serarch = bl_url + address_name_format # + '/footprint2d/' response = requests.get(bl_address_serarch, headers=headers, verify=False) data3 = response.json() data2 = json.loads(response.text) print("data3") print(data3) address_limiter = 0 layer_list = [] for item in data3['data']: # .'address_id': print(item) # 9th april trace. item_id = item['addressId'] # out on the 9th april to work with links and pageination. address_limiter = address_limiter + 1 # print(item_id) # print address_formatted layer_list.append(item_id) # + "-" + address_formatted) self.dlg.comboBox.addItems(layer_list) def embedded_select_address(self): index = self.dlg.comboBox.currentIndex() print("index = " + str(index)) focus_addr = self.dlg.comboBox.currentText() print(focus_addr) bl_buildingIDs = 'https://api.psma.com.au/beta/v1/addresses/' + focus_addr + '/' ###key = credentials.API_KEY key = 'InsertKeyHere' # bl_url = 'https://api.psma.com.au/beta/v1/' headers = {"Authorization": key, "Accept": "application/json"} response = requests.get(bl_buildingIDs, headers=headers, verify=False) data = response.json() print(data) # data2 = json.loads(response.text) # data2 = json.dumps(data) buildings = data['relatedBuildingIds'] print(buildings) layer_list = [] # self.dlg.listView.setModel(buildings) displayInt = 0 for building in buildings: displayInt = displayInt + 1 item_id = building print(item_id) # layer_list.append(item_id) bl_url = 'https://api.psma.com.au/beta/v1/buildings/' key = 'INSERTKEY HERE' headers = {"Authorization": key, "Accept": "application/json"} building_id = building bl_urlBuildingLinks = bl_url + building_id + '/footprint2d/' print(bl_urlBuildingLinks) response2 = requests.get(bl_urlBuildingLinks, headers=headers, verify=False) data2 = response2.json() data3 = json.dumps(data2) print(data3) vlayer = QgsVectorLayer(data3, focus_addr + "_" + building_id, "ogr") print(vlayer) ### #QgsMapLayerRegistry.instance().addMapLayer(vlayer) QgsProject.instance().addMapLayer(vlayer) # if displayInt == 1: #8/5/2018 removed for demon. # canvas = qgis.utils.iface.mapCanvas() # canvas.setExtent(vlayer.extent()) # vLayer = iface.activeLayer() # canvas = qgis.utils.iface.mapCanvas() # canvas.setExtent(vlayer.extent()) # vLayer = iface.activeLayer() # canvas = iface.mapCanvas() # extent = vLayer.extent() # canvas.setExtent(extent) self.dlg.lineEdit.clear() self.dlg.comboBox.clear()
class SP_CroquiFiscal: """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', 'SP_CroquiFiscal_{}.qm'.format(locale)) 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'&Croqui Fiscal') # Check if plugin was started the first time in current QGIS session # Must be set in initGui() to survive plugin reloads self.first_start = 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('SP_CroquiFiscal', message) def spurb_add_submenu(self, submenu): # if self.spurbanismo_menu != None: self.spurbanismo_menu.addMenu(submenu) else: self.iface.addPluginToMenu("&sp_urbanismo-bug", submenu.menuAction()) 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: # Adds plugin icon to Plugins toolbar self.iface.addToolBarIcon(action) if add_to_menu: self.iface.addPluginToMenu( self.menu, action) # Cria o MENU superior v2 # self.spurbanismo_menu = QMenu(self.iface.mainWindow()) # self.spurbanismo_menu.setObjectName("SPUrbMenu") # self.spurbanismo_menu.setTitle("SP_Urbanismo") # self.cadastro_menu = QMenu(QCoreApplication.translate("sp_urbanismo", "&Cadastro")) # self.spurb_add_submenu(self.cadastro_menu) self.actions.append(action) return action def initGui(self): """Create the menu entries and toolbar icons inside the QGIS GUI.""" icon_path = ':/plugins/croqui_fiscal/icon.png' self.add_action( icon_path, text=self.tr(u'SPUrb Croqui Fiscal'), callback=self.run, parent=self.iface.mainWindow()) # will be set False in run() self.first_start = True def select_output(self): global folderName folderName = QFileDialog.getExistingDirectory( self.dlg, caption="Pasta de Croqui Fiscal", directory=os.path.expanduser("~")+r'\downloads') self.dlg._diretorio.setText(folderName) # Recarrega os valores de CAMPOS def load_fields(self): layers = [l.layer() for l in QgsProject.instance().layerTreeRoot().children()] # Recebe a camada selecionada choosedLayerIndex = self.dlg._camada.currentIndex() choosedLayers = layers[choosedLayerIndex] # Carrega os campos possíveis fields = list(choosedLayers.fields()) fields_name = [n.name() for n in fields] self.dlg._setor.clear() self.dlg._setor.addItems(fields_name) self.dlg._quadra.clear() self.dlg._quadra.addItems(fields_name) self.dlg._setor.setCurrentIndex(self.dlg._setor.findText('qd_setor')) self.dlg._quadra.setCurrentIndex(self.dlg._setor.findText('qd_fiscal')) return fields_name def unload(self): """Removes the plugin menu item and icon from QGIS GUI.""" for action in self.actions: self.iface.removePluginMenu( self.tr(u'&Croqui Fiscal'), action) self.iface.removeToolBarIcon(action) def run(self): """Run method that performs all the real work""" # Create the dialog with elements (after translation) and keep reference # Only create GUI ONCE in callback, so that it will only load when the plugin is started if self.first_start == True: self.first_start = False self.dlg = SP_CroquiFiscalDialog() self.dlg._diretorio_botao.clicked.connect(self.select_output) # LAYERS OPTIONS # Fetch the currently loaded layers layers = QgsProject.instance().layerTreeRoot().children() # Clear the contents of the comboBox from previous runs self.dlg._camada.clear() # Populate the comboBox with names of all the loaded layers self.dlg._camada.addItems([layer.name() for layer in layers]) # Choose the active Layer layers = [l.layer() for l in layers] index = layers.index(iface.activeLayer()) if index is not None: self.dlg._camada.setCurrentIndex(index) # FIELDS OPTION self.load_fields() self.dlg._load_fields.clicked.connect(self.load_fields) # --Dentro da função # self.dlg._setor.setCurrentIndex(self.dlg._setor.findText('qd_setor')) # self.dlg._quadra.setCurrentIndex(self.dlg._setor.findText('qd_fiscal')) # Diretório padrão - para reconhecer qual a pasta em que usuário gosta de salvar Diretorio_QuadrasFiscais = "\\".join(os.path.dirname(__file__).split('/')) Diretorio_QuadrasFiscais = "\\".join([Diretorio_QuadrasFiscais, r'Diretorio_QuadrasFiscais.txt']) if os.path.exists(Diretorio_QuadrasFiscais): with open(Diretorio_QuadrasFiscais) as file: # print(Diretorio_QuadrasFiscais) folderName = file.read() self.dlg._diretorio.setText(folderName) # show the dialog self.dlg.show() # Run the dialog event loop result = self.dlg.exec_() # See if OK was pressed if result: if self.dlg._selectedFeatures.isChecked(): # Obtem as feições selecionadas da camada indicada choosedLayerIndex = self.dlg._camada.currentIndex() choosedLayers = layers[choosedLayerIndex]#.layer() selectedFeatures = choosedLayers.selectedFeatures() # Retorna os campos selecionados Campo_Setor = self.dlg._setor.currentText () Campo_Quadra = self.dlg._quadra.currentText () print(Campo_Quadra, Campo_Setor) # Obtem os valores distintos de SQ, somente das que são do tipo FISCAL SQ_Lista = set() # Limpa gratuitamente o SQ_Lista field_index = choosedLayers.fields().indexFromName('qd_tipo') # Verifica se existe o campo de TIPO da quadra for feature in selectedFeatures: if field_index != -1: # Verifica se existe o campo de TIPO da quadra if feature['qd_tipo'] == 'F': SQ_Lista.add(feature[Campo_Setor]+feature[Campo_Quadra]) else: SQ_Lista.add(feature[Campo_Setor]+feature[Campo_Quadra]) else: SQ_Lista = self.dlg._SQ_list.text() SQ_Lista = set(SQ_Lista.split(', ')) print(SQ_Lista) # Verifica se todos os SQ possuem 3 dígitos for SQ in SQ_Lista: if len(SQ) != 6: self.iface.messageBar().pushMessage("Falha", "Alguns SQs ({}) não possuem 6 dígitos!".format(SQ), level=Qgis.Critical, duration=10) return None now = datetime.now() ano = now.year mes = now.month now = str(ano) + '-' + str(mes) # Verifica qual provedor usar PRODAM = self.dlg._servidor.isChecked() # Loop para cada SQ for SQ in SQ_Lista: if PRODAM: # Requerimento ao endereço da PRODAM uri = 'http://sf9402.app.prodam/intranet/frmConsultaCroquiPDF.aspx?pstrSetor={0:0>3}&pstrQuadra={1:0>3}'.format(SQ[:3], SQ[3:]) else: # Requerimento ao endereço do GeoSampa Cidadão uri = 'http://geosampa.prefeitura.sp.gov.br/PaginasPublicas/DownloadCroqui.aspx?setor={0:0>3}&quadra={1:0>3}'.format(SQ[:3], SQ[3:]) ################################ fileobj = urllib.request.urlopen (uri) # fileobj = "" ########## MODO DE TESTE # print(uri) ########## MODO DE TESTE ##TODO: Criar diretório # Cria um novo arquivo e salva o conteúdo file = open(folderName + r'\CroquiFiscal---{0:0>3}_{1:0>3}---{2}.pdf'.format(SQ[:3], SQ[3:], now), 'bw') # file.write(fileobj) ########## MODO DE TESTE file.write(urllib.request.urlopen(uri).read()) file.close() self.iface.messageBar().pushMessage("Sucesso", "Arquivos salvos em " + folderName, level=Qgis.Success, duration=5)
class checkupdate(QWidget): def __init__(self, persepolis_setting): super().__init__() # defining UI self.persepolis_setting = persepolis_setting icons = ':/' + \ str(self.persepolis_setting.value('settings/icons')) + '/' self.setWindowIcon( QIcon.fromTheme('persepolis', QIcon(':/persepolis.svg'))) # add support for other languages locale = str(self.persepolis_setting.value('settings/locale')) QLocale.setDefault(QLocale(locale)) self.translator = QTranslator() if self.translator.load(':/translations/locales/ui_' + locale, 'ts'): QCoreApplication.installTranslator(self.translator) self.setWindowTitle( QCoreApplication.translate("update_src_ui_tr", 'Checking for newer version')) # installed version self.client_version = '3.10' # first line text self.update_label = QLabel( QCoreApplication.translate( "update_src_ui_tr", "The newest is the best , We recommend to update Persepolis")) self.update_label.setTextFormat(QtCore.Qt.RichText) self.update_label.setAlignment(QtCore.Qt.AlignCenter) # second line text self.version_label = QLabel( QCoreApplication.translate( "update_src_ui_tr", 'This is Persepolis Download Manager version 3.1.0')) self.version_label.setAlignment(QtCore.Qt.AlignCenter) # release link self.link_label = QLabel( '<a href=https://github.com/persepolisdm/persepolis/releases>https://github.com/persepolisdm/persepolis/releases</a>' ) self.link_label.setAlignment(QtCore.Qt.AlignCenter) self.link_label.setOpenExternalLinks(True) # version status self.status_label = QLabel() self.status_label.setTextFormat(QtCore.Qt.RichText) self.status_label.setAlignment(QtCore.Qt.AlignCenter) # update button self.check_button = QPushButton( QCoreApplication.translate("update_src_ui_tr", "Check for new update")) self.check_button.clicked.connect(self.updateCheck) # verticalLayout vbox = QVBoxLayout() vbox.addWidget(self.update_label) vbox.addWidget(self.version_label) vbox.addWidget(self.link_label) vbox.addWidget(self.check_button) vbox.addWidget(self.status_label) # horizontalLayout hbox = QHBoxLayout() hbox.addLayout(vbox) # window layout self.setLayout(hbox) # window size and position size = self.persepolis_setting.value('checkupdate/size', QSize(360, 250)) position = self.persepolis_setting.value('checkupdate/position', QPoint(300, 300)) self.resize(size) self.move(position) # checking methode def updateCheck(self, button): self.check_button.setText( QCoreApplication.translate("update_src_ui_tr", 'Checking...')) try: # get information dictionary from github updatesource = requests.get( 'https://persepolisdm.github.io/version') updatesource_text = updatesource.text updatesource_dict = ast.literal_eval(updatesource_text) # get latest stable version server_version = updatesource_dict['version'] # Comparison if float(server_version) > float(self.client_version): self.status_label.setText( QCoreApplication.translate( "update_src_ui_tr", 'A newer Persepolis release is available')) if os_type == 'Windows': self.winUpdatedl() # this function download latest release # find system architect if platform.architecture()[0] == '64bit': osCommands.xdgOpen(updatesource_dict['win64dlurl']) elif platform.architecture()[0] == '32bit': osCommands.xdgOpen(updatesource_dict['win32dlurl']) elif os_type == 'Darwin': osCommands.xdgOpen( updatesource_dict['macdlurl'] ) # it will download latest release for mac elif float(server_version) == float(self.client_version): self.status_label.setText( QCoreApplication.translate( "update_src_ui_tr", 'Latest version is installed :)')) elif float(server_version) < float(self.client_version): self.status_label.setText( QCoreApplication.translate("update_src_ui_tr", 'You are using beta version')) except Exception as e: self.status_label.setText( QCoreApplication.translate( "update_src_ui_tr", 'An error occured while checking for updates.')) self.check_button.setText( QCoreApplication.translate("update_src_ui_tr", 'Check for new update')) def closeEvent(self, event): # saving window size and position self.persepolis_setting.setValue('checkupdate/size', self.size()) self.persepolis_setting.setValue('checkupdate/position', self.pos()) self.persepolis_setting.sync() event.accept()
class suiviAvis: """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', 'suiviAvis_{}.qm'.format(locale)) if os.path.exists(locale_path): self.translator = QTranslator() self.translator.load(locale_path) if qVersion() > '4.3.3': QCoreApplication.installTranslator(self.translator) # Create the dialog (after translation) and keep reference self.dlg = suiviAvisDialog() # Declare instance attributes self.actions = [] self.menu = self.tr(u'&Suivi Avis') # TODO: We are going to let the user set this up in a future iteration self.toolbar = self.iface.addToolBar(u'suiviAvis') self.toolbar.setObjectName(u'suiviAvis') # 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('suiviAvis', 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/suivi_avis/icon.png' self.add_action(icon_path, text=self.tr(u'Suivi Avis'), callback=self.run, parent=self.iface.mainWindow()) self.dlg.tabWidget.currentChanged.connect(self.tab_changed) self.dlg.extractPolyButton.clicked.connect(self.extract) self.dlg.butGenCSV.clicked.connect(self.genCSV) self.dlg.butListInsee.clicked.connect(self.listInsee) self.dlg.updateMapButton.clicked.connect(self.lectureOffice) def tab_changed(self): tabName = self.dlg.tabWidget.tabText(self.dlg.tabWidget.currentIndex()) try: self.dlg.TabFileWidget.fileChanged.disconnect() except: pass print("tab changed, index {0} : {1}".format( self.dlg.tabWidget.currentIndex(), tabName)) if (tabName == "Masque"): self.prep_extract() elif (tabName == "Tab2map"): self.prep_office() def genCSV(self): fs = QFileDialog() fs.setWindowTitle("-- Tableur de suivi --") fs.setFileMode(QFileDialog.FileMode.ExistingFile) fs.setDirectory( os.path.dirname( os.path.dirname(QgsProject.instance().absolutePath()))) fs.setNameFilter("SCalc (*.ods);; Excel(*.xls);; All Files (*.*)") fs.selectNameFilter("*.ods") ret = fs.exec() if (ret == QFileDialog.DialogCode.Accepted): print(fs.selectedFiles()[0]) self.message("Lecture tableur ...") QGuiApplication.setOverrideCursor(Qt.WaitCursor) c = pe.get_book(file_name=fs.selectedFiles()[0]) s = c.sheet_by_name(self.dlg.defNomOngletMailing.displayText()) s.save_as(os.path.splitext(fs.selectedFiles()[0])[0] + ".csv") self.message("CSV sauve ...") QGuiApplication.restoreOverrideCursor() def listInsee(self): pass def extract(self): print("recherche") ee = extractPoly(self) ee.recherche() def lectureOffice(self): print("Update") ee = updateSuivi(self) ee.update() def prep_office(self): self.dlg.TabFileWidget.setDialogTitle("-- Tableur de suivi --") self.dlg.TabFileWidget.setStorageMode(QgsFileWidget.GetFile) self.dlg.TabFileWidget.setDefaultRoot( os.path.dirname( os.path.dirname(QgsProject.instance().absolutePath()))) self.dlg.TabFileWidget.setFilter("*.ods;;*.xls;;*.*") self.dlg.TabFileWidget.setSelectedFilter(".ods") self.dlg.TabFileWidget.fileChanged.connect(self.lecture_onglet) layers = QgsProject.instance().mapLayers() for k in layers: layer = layers[k] if (layer.type() == QgsMapLayer.LayerType.VectorLayer): if (QgsWkbTypes.geometryType(layer.wkbType()) == QgsWkbTypes.GeometryType.PolygonGeometry): print(layer.name()) self.dlg.TabLayer.addItem(layer.name(), layer) idx = self.dlg.TabLayer.findText(self.dlg.defNomLayer.displayText()) if (idx != -1): self.dlg.TabLayer.setCurrentIndex(idx) def lecture_onglet(self, chemin): print("fileChanged : " + chemin) self.message("Lecture des onglets") QGuiApplication.setOverrideCursor(Qt.WaitCursor) c = pe.get_book(file_name=chemin) self.dlg.TabOnglet.clear() for s in c.sheet_names(): if (s.startswith("file:")): pass else: self.dlg.TabOnglet.addItem(s) QGuiApplication.restoreOverrideCursor() idx = self.dlg.TabOnglet.findText( self.dlg.defNomOngletSuivi.displayText()) if (idx != -1): self.dlg.TabOnglet.setCurrentIndex(idx) self.message("Done") def prep_extract(self): self.dlg.MasqueListeCouches.clear() self.dlg.MasqueLignePoint.clear() layers = QgsProject.instance().mapLayers() for k in layers: layer = layers[k] if (layer.type() == QgsMapLayer.LayerType.VectorLayer): if (QgsWkbTypes.geometryType(layer.wkbType()) == QgsWkbTypes.GeometryType.PolygonGeometry): print(layer.name()) self.dlg.MasqueListeCouches.addItem(layer.name(), layer) elif (QgsWkbTypes.geometryType(layer.wkbType()) == QgsWkbTypes.GeometryType. PointGeometry) or \ (QgsWkbTypes.geometryType(layer.wkbType()) == QgsWkbTypes.GeometryType. LineGeometry): if (QgsProject.instance().layerTreeRoot().findLayer( layer.id()).isVisible()): self.dlg.MasqueLignePoint.addItem(layer.name(), layer) self.dlg.MasqueNomCouche.setText(self.dlg.defNomLayer.displayText()) def message(self, msg): self.dlg.Message.setText(msg) self.dlg.Message.repaint() def unload(self): """Removes the plugin menu item and icon from QGIS GUI.""" for action in self.actions: self.iface.removePluginMenu(self.tr(u'&Suivi Avis'), action) self.iface.removeToolBarIcon(action) # remove the toolbar del self.toolbar def run(self): """Run method that performs all the real work""" # show the dialog self.dlg.show() self.tab_changed() # initialise le tab actif # Run the dialog event loop result = self.dlg.exec_() # See if OK was pressed if result: # Do something useful here - delete the line containing pass and # substitute with your code. pass
class VideoFinderAddLink(AddLinkWindow): running_thread = None threadPool = {} def __init__(self, parent, receiver_slot, settings, video_dict={}): super().__init__(parent, receiver_slot, settings, video_dict) self.setWindowTitle( QCoreApplication.translate("ytaddlink_src_ui_tr", 'Video Finder')) self.size_label.hide() # empty lists for no_audio and no_video and video_audio files self.no_audio_list = [] self.no_video_list = [] self.video_audio_list = [] self.media_title = '' # add support for other languages locale = str(self.persepolis_setting.value('settings/locale')) QLocale.setDefault(QLocale(locale)) self.translator = QTranslator() if self.translator.load(':/translations/locales/ui_' + locale, 'ts'): QCoreApplication.installTranslator(self.translator) # extension_label self.extension_label = QLabel(self.link_frame) self.change_name_horizontalLayout.addWidget(self.extension_label) # Fetch Button self.url_submit_pushButtontton = QPushButton(self.link_frame) self.link_horizontalLayout.addWidget(self.url_submit_pushButtontton) # Status Box self.status_box_textEdit = QTextEdit(self.link_frame) self.status_box_textEdit.setMaximumHeight(150) self.link_verticalLayout.addWidget(self.status_box_textEdit) # Select format horizontal layout select_format_horizontalLayout = QHBoxLayout() # Selection Label self.select_format_label = QLabel(self.link_frame) select_format_horizontalLayout.addWidget(self.select_format_label) # Selection combobox self.media_comboBox = QComboBox(self.link_frame) self.media_comboBox.setMinimumWidth(200) select_format_horizontalLayout.addWidget(self.media_comboBox) # Duration label self.duration_label = QLabel(self.link_frame) select_format_horizontalLayout.addWidget(self.duration_label) self.format_selection_frame = QFrame(self) self.format_selection_frame.setLayout(select_format_horizontalLayout) self.link_verticalLayout.addWidget(self.format_selection_frame) # advanced_format_selection_checkBox self.advanced_format_selection_checkBox = QCheckBox(self) self.link_verticalLayout.addWidget( self.advanced_format_selection_checkBox) # advanced_format_selection_frame self.advanced_format_selection_frame = QFrame(self) self.link_verticalLayout.addWidget( self.advanced_format_selection_frame) advanced_format_selection_horizontalLayout = QHBoxLayout( self.advanced_format_selection_frame) # video_format_selection self.video_format_selection_label = QLabel( self.advanced_format_selection_frame) self.video_format_selection_comboBox = QComboBox( self.advanced_format_selection_frame) # audio_format_selection self.audio_format_selection_label = QLabel( self.advanced_format_selection_frame) self.audio_format_selection_comboBox = QComboBox( self.advanced_format_selection_frame) for widget in [ self.video_format_selection_label, self.video_format_selection_comboBox, self.audio_format_selection_label, self.audio_format_selection_comboBox ]: advanced_format_selection_horizontalLayout.addWidget(widget) # Set Texts self.url_submit_pushButtontton.setText( QCoreApplication.translate("ytaddlink_src_ui_tr", 'Fetch Media List')) self.select_format_label.setText( QCoreApplication.translate("ytaddlink_src_ui_tr", 'Select a format')) self.video_format_selection_label.setText( QCoreApplication.translate("ytaddlink_src_ui_tr", 'Video format:')) self.audio_format_selection_label.setText( QCoreApplication.translate("ytaddlink_src_ui_tr", 'Audio format:')) self.advanced_format_selection_checkBox.setText( QCoreApplication.translate("ytaddlink_src_ui_tr", 'Advanced options')) # Add Slot Connections self.url_submit_pushButtontton.setEnabled(False) self.change_name_lineEdit.setEnabled(False) self.ok_pushButton.setEnabled(False) self.download_later_pushButton.setEnabled(False) self.format_selection_frame.setEnabled(True) self.advanced_format_selection_frame.setEnabled(False) self.advanced_format_selection_checkBox.toggled.connect( self.advancedFormatFrame) self.url_submit_pushButtontton.clicked.connect(self.submitClicked) self.media_comboBox.activated.connect( partial(self.mediaSelectionChanged, 'video_audio')) self.video_format_selection_comboBox.activated.connect( partial(self.mediaSelectionChanged, 'video')) self.audio_format_selection_comboBox.activated.connect( partial(self.mediaSelectionChanged, 'audio')) self.link_lineEdit.textChanged.disconnect( super().linkLineChanged) # Should be disconnected. self.link_lineEdit.textChanged.connect(self.linkLineChangedHere) self.setMinimumSize(650, 480) self.status_box_textEdit.hide() self.format_selection_frame.hide() self.advanced_format_selection_frame.hide() self.advanced_format_selection_checkBox.hide() if 'link' in video_dict.keys() and video_dict['link']: self.link_lineEdit.setText(video_dict['link']) self.url_submit_pushButtontton.setEnabled(True) else: # check clipboard clipboard = QApplication.clipboard() text = clipboard.text() if (("tp:/" in text[2:6]) or ("tps:/" in text[2:7])): self.link_lineEdit.setText(str(text)) self.url_submit_pushButtontton.setEnabled(True) def advancedFormatFrame(self, button): if self.advanced_format_selection_checkBox.isChecked(): self.advanced_format_selection_frame.setEnabled(True) self.format_selection_frame.setEnabled(False) self.mediaSelectionChanged( 'video', int(self.video_format_selection_comboBox.currentIndex())) else: self.advanced_format_selection_frame.setEnabled(False) self.format_selection_frame.setEnabled(True) self.mediaSelectionChanged('video_audio', int(self.media_comboBox.currentIndex())) def getReadableSize(self, size): try: return '{:1.2f} MB'.format(int(size) / 1048576) except: return str(size) def getReadableDuration(self, seconds): try: seconds = int(seconds) hours = seconds // 3600 seconds = seconds % 3600 minutes = seconds // 60 seconds = seconds % 60 return '{:02d}:{:02d}:{:02d}'.format(hours, minutes, seconds) except: return str(seconds) # Define native slots def urlChanged(self, value): if ' ' in value or value == '': self.url_submit_pushButtontton.setEnabled(False) self.url_submit_pushButtontton.setToolTip( QCoreApplication.translate("ytaddlink_src_ui_tr", 'Please enter a valid video link')) else: self.url_submit_pushButtontton.setEnabled(True) self.url_submit_pushButtontton.setToolTip('') def submitClicked(self, button=None): # Clear media list self.media_comboBox.clear() self.format_selection_frame.hide() self.advanced_format_selection_checkBox.hide() self.advanced_format_selection_frame.hide() self.video_format_selection_comboBox.clear() self.audio_format_selection_comboBox.clear() self.change_name_lineEdit.clear() self.threadPool.clear() self.change_name_checkBox.setChecked(False) self.video_audio_list.clear() self.no_video_list.clear() self.no_audio_list.clear() self.url_submit_pushButtontton.setEnabled(False) self.status_box_textEdit.setText( QCoreApplication.translate("ytaddlink_src_ui_tr", 'Fetching Media Info...')) self.status_box_textEdit.show() self.ok_pushButton.setEnabled(False) self.download_later_pushButton.setEnabled(False) dictionary_to_send = deepcopy(self.plugin_add_link_dictionary) # More options more_options = self.collectMoreOptions() for k in more_options.keys(): dictionary_to_send[k] = more_options[k] dictionary_to_send['link'] = self.link_lineEdit.text() fetcher_thread = MediaListFetcherThread(self.fetchedResult, dictionary_to_send, self) self.parent.threadPool.append(fetcher_thread) self.parent.threadPool[len(self.parent.threadPool) - 1].start() def fileNameChanged(self, value): if value.strip() == '': self.ok_pushButton.setEnabled(False) def mediaSelectionChanged(self, combobox, index): try: if combobox == 'video_audio': if self.media_comboBox.currentText() == 'Best quality': self.change_name_lineEdit.setText(self.media_title) self.extension_label.setText('.' + self.no_audio_list[-1]['ext']) else: self.change_name_lineEdit.setText(self.media_title) self.extension_label.setText( '.' + self.video_audio_list[index]['ext']) self.change_name_checkBox.setChecked(True) elif combobox == 'video': if self.video_format_selection_comboBox.currentText( ) != 'No video': self.change_name_lineEdit.setText(self.media_title) self.extension_label.setText('.' + self.no_audio_list[index - 1]['ext']) self.change_name_checkBox.setChecked(True) else: if self.audio_format_selection_comboBox.currentText( ) != 'No audio': self.change_name_lineEdit.setText(self.media_title) self.extension_label.setText('.' + self.no_video_list[ int(self.audio_format_selection_comboBox. currentIndex()) - 1]['ext']) self.change_name_checkBox.setChecked(True) else: self.change_name_lineEdit.setChecked(False) elif combobox == 'audio': if self.audio_format_selection_comboBox.currentText( ) != 'No audio' and self.video_format_selection_comboBox.currentText( ) == 'No video': self.change_name_lineEdit.setText(self.media_title) self.extension_label.setText('.' + self.no_video_list[index - 1]['ext']) self.change_name_checkBox.setChecked(True) elif (self.audio_format_selection_comboBox.currentText() == 'No audio' and self.video_format_selection_comboBox.currentText() != 'No video') or ( self.audio_format_selection_comboBox.currentText() != 'No audio' and self.video_format_selection_comboBox.currentText() != 'No video'): self.change_name_lineEdit.setText(self.media_title) self.extension_label.setText('.' + self.no_audio_list[ int(self.video_format_selection_comboBox.currentIndex( )) - 1]['ext']) self.change_name_checkBox.setChecked(True) elif self.audio_format_selection_comboBox.currentText( ) == 'No audio' and self.video_format_selection_comboBox.currentText( ) == 'No video': self.change_name_checkBox.setChecked(False) except Exception as ex: logger.sendToLog(ex, "ERROR") def fetchedResult(self, media_dict): self.url_submit_pushButtontton.setEnabled(True) if 'error' in media_dict.keys(): self.status_box_textEdit.setText('<font color="#f11">' + str(media_dict['error']) + '</font>') self.status_box_textEdit.show() else: # Show the media list # add no audio and no video options to the comboboxes self.video_format_selection_comboBox.addItem('No video') self.audio_format_selection_comboBox.addItem('No audio') self.media_title = media_dict['title'] if 'formats' not in media_dict.keys( ) and 'entries' in media_dict.keys(): formats = media_dict['entries'] formats = formats[0] media_dict['formats'] = formats['formats'] elif 'formats' not in media_dict.keys( ) and 'format' in media_dict.keys(): media_dict['formats'] = [media_dict.copy()] try: i = 0 for f in media_dict['formats']: no_audio = False no_video = False text = '' if 'acodec' in f.keys(): # only video, no audio if f['acodec'] == 'none': no_audio = True # resolution if 'height' in f.keys(): text = text + ' ' + '{}p'.format(f['height']) if 'vcodec' in f.keys(): # if f['vcodec'] == 'none' and f['acodec'] != 'none': # continue # No video, show audio bit rate if f['vcodec'] == 'none': text = text + '{}kbps'.format(f['abr']) no_video = True if 'ext' in f.keys(): text = text + ' ' + '.{}'.format(f['ext']) if 'filesize' in f.keys() and f['filesize']: # Youtube api does not supply file size for some formats, so check it. text = text + ' ' + '{}'.format( self.getReadableSize(f['filesize'])) else: # Start spider to find file size input_dict = deepcopy(self.plugin_add_link_dictionary) input_dict['link'] = f['url'] more_options = self.collectMoreOptions() for key in more_options.keys(): input_dict[key] = more_options[key] size_fetcher = FileSizeFetcherThread(input_dict, i) self.threadPool[str(i)] = { 'thread': size_fetcher, 'item_id': i } self.parent.threadPool.append(size_fetcher) self.parent.threadPool[len(self.parent.threadPool) - 1].start() self.parent.threadPool[len(self.parent.threadPool) - 1].FOUND.connect( self.findFileSize) # Add current format to the related comboboxes if no_audio: self.no_audio_list.append(f) self.video_format_selection_comboBox.addItem(text) elif no_video: self.no_video_list.append(f) self.audio_format_selection_comboBox.addItem(text) else: self.video_audio_list.append(f) self.media_comboBox.addItem(text) i = i + 1 self.status_box_textEdit.hide() if 'duration' in media_dict.keys(): self.duration_label.setText( 'Duration ' + self.getReadableDuration(media_dict['duration'])) self.format_selection_frame.show() self.advanced_format_selection_checkBox.show() self.advanced_format_selection_frame.show() self.ok_pushButton.setEnabled(True) self.download_later_pushButton.setEnabled(True) # if we have no options for separate audio and video, then hide advanced_format_selection... if len(self.no_audio_list) == 0 and len( self.no_video_list) == 0: self.advanced_format_selection_checkBox.hide() self.advanced_format_selection_frame.hide() # set index of comboboxes on best available quality. if len(self.no_audio_list) != 0 and len( self.no_video_list) != 0: self.media_comboBox.addItem('Best quality') self.media_comboBox.setCurrentIndex( len(self.video_audio_list)) elif len(self.video_audio_list) != 0: self.media_comboBox.setCurrentIndex( len(self.video_audio_list) - 1) if len(self.no_audio_list) != 0: self.video_format_selection_comboBox.setCurrentIndex( len(self.no_audio_list)) if len(self.no_video_list) != 0: self.audio_format_selection_comboBox.setCurrentIndex( len(self.no_video_list)) # if we have only audio or we have only video then hide media_comboBox if len(self.video_audio_list) == 0: self.media_comboBox.hide() self.select_format_label.hide() # only video if len(self.no_video_list) != 0 and len( self.no_audio_list) == 0: self.mediaSelectionChanged( 'video', int(self.video_format_selection_comboBox. currentIndex())) self.advanced_format_selection_checkBox.setChecked( True) self.advanced_format_selection_checkBox.hide() # only audio elif len(self.no_video_list) == 0 and len( self.no_audio_list) != 0: self.mediaSelectionChanged( 'audio', int(self.audio_format_selection_comboBox. currentIndex())) self.advanced_format_selection_checkBox.setChecked( True) self.advanced_format_selection_checkBox.hide() # audio and video else: self.mediaSelectionChanged( 'video_audio', int(self.media_comboBox.currentIndex())) except Exception as ex: logger.sendToLog(ex, "ERROR") def findFileSize(self, result): try: item_id = self.threadPool[str(result['thread_key'])]['item_id'] if result['file_size'] and result['file_size'] != '0': text = self.media_comboBox.itemText(item_id) self.media_comboBox.setItemText( item_id, '{} - {}'.format(text, result['file_size'])) except Exception as ex: logger.sendToLog(ex, "ERROR") def linkLineChangedHere(self, lineEdit): if str(lineEdit) == '': self.url_submit_pushButtontton.setEnabled(False) else: self.url_submit_pushButtontton.setEnabled(True) # This method collects additional information like proxy ip, user, password etc. def collectMoreOptions(self): options = { 'ip': None, 'port': None, 'proxy_user': None, 'proxy_passwd': None, 'download_user': None, 'download_passwd': None } if self.proxy_checkBox.isChecked(): options['ip'] = self.ip_lineEdit.text() options['port'] = self.port_spinBox.value() options['proxy_user'] = self.proxy_user_lineEdit.text() options['proxy_passwd'] = self.proxy_pass_lineEdit.text() if self.download_checkBox.isChecked(): options['download_user'] = self.download_user_lineEdit.text() options['download_passwd'] = self.download_pass_lineEdit.text() # These info (keys) are required for spider to find file size, because spider() does not check if key exists. additional_info = [ 'header', 'load_cookies', 'user_agent', 'referer', 'out' ] for i in additional_info: if i not in self.plugin_add_link_dictionary.keys(): options[i] = None return options # user submitted information by pressing ok_pushButton, so get information # from VideoFinderAddLink window and return them to the mainwindow with callback! def okButtonPressed(self, button, download_later): link_list = [] # separate audio format and video format is selected. if self.advanced_format_selection_checkBox.isChecked(): if self.video_format_selection_comboBox.currentText( ) == 'No video' and self.audio_format_selection_comboBox.currentText( ) != 'No audio': # only audio link must be added to the link_list audio_link = self.no_video_list[ self.audio_format_selection_comboBox.currentIndex() - 1]['url'] link_list.append(audio_link) elif self.video_format_selection_comboBox.currentText( ) != 'No video' and self.audio_format_selection_comboBox.currentText( ) == 'No audio': # only video link must be added to the link_list video_link = self.no_audio_list[ self.video_format_selection_comboBox.currentIndex() - 1]['url'] link_list.append(video_link) elif self.video_format_selection_comboBox.currentText( ) != 'No video' and self.audio_format_selection_comboBox.currentText( ) != 'No audio': # video and audio links must be added to the link_list audio_link = self.no_video_list[ self.audio_format_selection_comboBox.currentIndex() - 1]['url'] video_link = self.no_audio_list[ self.video_format_selection_comboBox.currentIndex() - 1]['url'] link_list = [video_link, audio_link] elif self.video_format_selection_comboBox.currentText( ) == 'No video' and self.audio_format_selection_comboBox.currentText( ) == 'No audio': # no video and audio is selected! REALLY?!. user is DRUNK! close the window! :)) self.close() else: if self.media_comboBox.currentText() == 'Best quality': # the last item in no_video_list and no_audio_list are the best. video_link = self.no_audio_list[-1]['url'] audio_link = self.no_video_list[-1]['url'] link_list = [video_link, audio_link] else: audio_and_video_link = self.video_audio_list[ self.media_comboBox.currentIndex()]['url'] link_list.append(audio_and_video_link) # write user's new inputs in persepolis_setting for next time :) self.persepolis_setting.setValue('add_link_initialization/ip', self.ip_lineEdit.text()) self.persepolis_setting.setValue('add_link_initialization/port', self.port_spinBox.value()) self.persepolis_setting.setValue('add_link_initialization/proxy_user', self.proxy_user_lineEdit.text()) self.persepolis_setting.setValue( 'add_link_initialization/download_user', self.download_user_lineEdit.text()) # get proxy information if not (self.proxy_checkBox.isChecked()): ip = None port = None proxy_user = None proxy_passwd = None else: ip = self.ip_lineEdit.text() if not (ip): ip = None port = self.port_spinBox.value() if not (port): port = None proxy_user = self.proxy_user_lineEdit.text() if not (proxy_user): proxy_user = None proxy_passwd = self.proxy_pass_lineEdit.text() if not (proxy_passwd): proxy_passwd = None # get download username and password information if not (self.download_checkBox.isChecked()): download_user = None download_passwd = None else: download_user = self.download_user_lineEdit.text() if not (download_user): download_user = None download_passwd = self.download_pass_lineEdit.text() if not (download_passwd): download_passwd = None # check that if user limits download speed. if not (self.limit_checkBox.isChecked()): limit = 0 else: if self.limit_comboBox.currentText() == "KiB/s": limit = str(self.limit_spinBox.value()) + str("K") else: limit = str(self.limit_spinBox.value()) + str("M") # get start time for download if user set that. if not (self.start_checkBox.isChecked()): start_time = None else: start_time = self.start_time_qDataTimeEdit.text() # get end time for download if user set that. if not (self.end_checkBox.isChecked()): end_time = None else: end_time = self.end_time_qDateTimeEdit.text() # set name for file(s) if self.change_name_checkBox.isChecked(): name = str(self.change_name_lineEdit.text()) if name == '': name = 'video_finder_file' else: name = 'video_finder_file' # video finder always finds extension # but if it can't find file extension # use mp4 for extension. if str(self.extension_label.text()) == '': extension = '.mp4' else: extension = str(self.extension_label.text()) # did user select separate audio and video? if len(link_list) == 2: video_name = name + extension audio_name = name + '.' + \ str(self.no_video_list[self.audio_format_selection_comboBox.currentIndex() - 1]['ext']) name_list = [video_name, audio_name] else: name_list = [name + extension] # get number of connections connections = self.connections_spinBox.value() # get download_path download_path = self.download_folder_lineEdit.text() # referer if self.referer_lineEdit.text() != '': referer = self.referer_lineEdit.text() else: referer = None # header if self.header_lineEdit.text() != '': header = self.header_lineEdit.text() else: header = None # user_agent if self.user_agent_lineEdit.text() != '': user_agent = self.user_agent_lineEdit.text() else: user_agent = None # load_cookies if self.load_cookies_lineEdit.text() != '': load_cookies = self.load_cookies_lineEdit.text() else: load_cookies = None add_link_dictionary_list = [] if len(link_list) == 1: # save information in a dictionary(add_link_dictionary). add_link_dictionary = { 'referer': referer, 'header': header, 'user_agent': user_agent, 'load_cookies': load_cookies, 'out': name_list[0], 'start_time': start_time, 'end_time': end_time, 'link': link_list[0], 'ip': ip, 'port': port, 'proxy_user': proxy_user, 'proxy_passwd': proxy_passwd, 'download_user': download_user, 'download_passwd': download_passwd, 'connections': connections, 'limit_value': limit, 'download_path': download_path } add_link_dictionary_list.append(add_link_dictionary) else: video_add_link_dictionary = { 'referer': referer, 'header': header, 'user_agent': user_agent, 'load_cookies': load_cookies, 'out': name_list[0], 'start_time': start_time, 'end_time': end_time, 'link': link_list[0], 'ip': ip, 'port': port, 'proxy_user': proxy_user, 'proxy_passwd': proxy_passwd, 'download_user': download_user, 'download_passwd': download_passwd, 'connections': connections, 'limit_value': limit, 'download_path': download_path } audio_add_link_dictionary = { 'referer': referer, 'header': header, 'user_agent': user_agent, 'load_cookies': load_cookies, 'out': name_list[1], 'start_time': None, 'end_time': end_time, 'link': link_list[1], 'ip': ip, 'port': port, 'proxy_user': proxy_user, 'proxy_passwd': proxy_passwd, 'download_user': download_user, 'download_passwd': download_passwd, 'connections': connections, 'limit_value': limit, 'download_path': download_path } add_link_dictionary_list = [ video_add_link_dictionary, audio_add_link_dictionary ] # get category of download category = str(self.add_queue_comboBox.currentText()) del self.plugin_add_link_dictionary # return information to mainwindow self.callback(add_link_dictionary_list, download_later, category) # close window self.close()
class MzSTools: """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', 'MzSTools_{}.qm'.format(locale)) if os.path.exists(locale_path): self.translator = QTranslator() self.translator.load(locale_path) if qVersion() > '4.3.3': QCoreApplication.installTranslator(self.translator) # Create the dialog (after translation) and keep reference self.dlg = MzSToolsDialog() # Declare instance attributes self.actions = [] self.menu = self.tr(u'&MzS Tools') # TODO: We are going to let the user set this up in a future iteration self.toolbar = self.iface.addToolBar(u'MzSTools') self.toolbar.setObjectName(u'MzSTools') # 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('MzSTools', 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/mzs_tools/icon.png' self.add_action(icon_path, text=self.tr(u'MzS Tools'), callback=self.run, parent=self.iface.mainWindow()) def unload(self): """Removes the plugin menu item and icon from QGIS GUI.""" for action in self.actions: self.iface.removePluginMenu(self.tr(u'&MzS Tools'), action) self.iface.removeToolBarIcon(action) # remove the toolbar del self.toolbar def run(self): """Run method that performs all the real work""" # show the dialog self.dlg.show() # Run the dialog event loop result = self.dlg.exec_() # See if OK was pressed if result: # Do something useful here - delete the line containing pass and # substitute with your code. pass
class FragScapeDialog(QtWidgets.QDialog, FORM_CLASS): def __init__(self, parent=None): """Constructor.""" super(FragScapeDialog, self).__init__(parent) # Set up the user interface from Designer. # After setupUI you can access any designer object by doing # self.<objectname>, and you can use autoconnect slots - see # http://qt-project.org/doc/qt-4.8/designer-using-a-ui-file.html # #widgets-and-dialogs-with-auto-connect self.provider = FragScapeAlgorithmsProvider() fsGlobalAlg = FragScapeAlgorithm() fsGlobalAlg.initAlgorithm() self.provider.alglist.append(fsGlobalAlg) self.setupUi(self) def initTabs(self): global progressFeedback logConnector = log.LogConnector(self) logConnector.initGui() self.feedback = feedbacks.ProgressFeedback(self) feedbacks.progressFeedback = self.feedback utils.debug("progressFeedback = " + str(feedbacks.progressFeedback)) self.context = QgsProcessingContext() self.context.setFeedback(feedbacks.progressFeedback) self.fsModel = FragScapeModel(self.context, feedbacks.progressFeedback) self.paramsConnector = params.ParamsConnector(self, self.fsModel.paramsModel) params.params = self.paramsConnector.model self.landuseConnector = landuse.LanduseConnector( self, self.fsModel.landuseModel) self.fragmConnector = fragm.FragmConnector(self, self.fsModel.fragmModel) self.reportingConnector = reporting.ReportingConnector( self, self.fsModel.reportingModel) tabConnector = tabs.TabConnector(self) self.connectors = { "Params": self.paramsConnector, "Log": logConnector, "Landuse": self.landuseConnector, "Fragm": self.fragmConnector, "Reporting": self.reportingConnector, "Progress": feedbacks.progressFeedback, "Tabs": tabConnector } self.recomputeParsers() def initGui(self): QgsApplication.processingRegistry().addProvider(self.provider) self.switchLangEn() for k, tab in self.connectors.items(): tab.initGui() def modeIsVector(self): return self.paramsConnector.modeIsVector() def getVectorWidgets(self): widgets = [] return widgets def getRasterWidgets(self): widgets = [self.rasterResolution] return widgets # Exception hook, i.e. function called when exception raised. # Displays traceback and error message in log tab. # Ignores CustomException : exception raised from FragScape and already displayed. def exceptionHook(self, excType, excValue, tracebackobj): utils.debug("bioDispHook") if excType == utils.CustomException: utils.debug("Ignoring custom exception : " + str(excValue)) else: tbinfofile = StringIO() traceback.print_tb(tracebackobj, None, tbinfofile) tbinfofile.seek(0) tbinfo = tbinfofile.read() errmsg = str(excType.__name__) + " : " + str(excValue) separator = '-' * 80 #sections = [separator, errmsg, separator] #utils.debug(str(sections)) msg = separator + "\n" + errmsg + "\n" + separator #msg = '\n'.join(sections) utils.debug(str(msg)) #final_msg = tbinfo + "\n" + msg utils.warn("Traceback : " + tbinfo) utils.error_msg(msg, prefix="Unexpected error") self.mTabWidget.setCurrentWidget(self.logTab) #feedbacks.progressConnector.clear() # Connects view and model components for each tab. # Connects global elements such as project file and language management. def connectComponents(self): for k, tab in self.connectors.items(): tab.connectComponents() # Main tab connectors self.saveProjectAs.clicked.connect(self.saveModelAsAction) self.saveProject.clicked.connect(self.saveModel) self.openProject.clicked.connect(self.loadModelAction) self.langEn.clicked.connect(self.switchLangEn) self.langFr.clicked.connect(self.switchLangFr) self.aboutButton.clicked.connect(self.openHelpDialog) feedbacks.progressFeedback.connectComponents() sys.excepthook = self.exceptionHook # Initialize or re-initialize global variables. def initializeGlobals(self): pass def unload(self): self.fsModel = None QgsApplication.processingRegistry().removeProvider(self.provider) def initLog(self): utils.print_func = self.txtLog.append # Switch language to english. def switchLang(self, lang): utils.debug("switchLang " + str(lang)) plugin_dir = os.path.dirname(__file__) lang_path = os.path.join(plugin_dir, 'i18n', 'FragScape_' + lang + '.qm') if os.path.exists(lang_path): self.translator = QTranslator() self.translator.load(lang_path) if qVersion() > '4.3.3': utils.debug("Installing translator " + str(lang_path)) QCoreApplication.installTranslator(self.translator) else: utils.internal_error("Unexpected qVersion : " + str(qVersion())) else: utils.warn("No translation file : " + str(en_path)) self.retranslateUi(self) utils.curr_language = lang self.connectors["Tabs"].loadHelpFile() def switchLangEn(self): self.switchLang("en") self.langEn.setChecked(True) self.langFr.setChecked(False) def switchLangFr(self): self.switchLang("fr") self.langEn.setChecked(False) self.langFr.setChecked(True) def openHelpDialog(self): utils.debug("openHelpDialog") about_dlg = FragScapeAboutDialog(self) about_dlg.show() # Recompute self.parsers in case they have been reloaded def recomputeParsers(self): self.parsers = [ self.paramsConnector, self.landuseConnector, self.fragmConnector.model, self.reportingConnector ] # Return XML string describing project def toXML(self): xmlStr = self.fsModel.toXML() return xmlStr # Save project to 'fname' def saveModelAs(self, fname): self.recomputeParsers() xmlStr = self.fsModel.toXML() self.paramsConnector.setProjectFile(fname) utils.writeFile(fname, xmlStr) utils.info("FragScape model saved into file '" + fname + "'") def saveModelAsAction(self): fname = qgsUtils.saveFileDialog(parent=self, msg="Sauvegarder le projet sous", filter="*.xml") if fname: self.saveModelAs(fname) # Save project to projectFile if existing def saveModel(self): fname = self.fsModel.paramsModel.projectFile utils.checkFileExists(fname, "Project ") self.saveModelAs(fname) # Load project from 'fname' if existing def loadModel(self, fname): utils.debug("loadModel " + str(fname)) utils.checkFileExists(fname) config_parsing.setConfigParsers(self.parsers) self.paramsConnector.setProjectFile(fname) config_parsing.parseConfig(fname) utils.info("FragScape model loaded from file '" + fname + "'") def loadModelAction(self): fname = qgsUtils.openFileDialog(parent=self, msg="Ouvrir le projet", filter="*.xml") if fname: self.loadModel(fname)
class bridgePanel(QMainWindow, QObject): start = pyqtSignal() stop = pyqtSignal() def __init__(self, app): super().__init__() self.bridgetreasureChest = bridgetreasureChest.bridgetreasureChest() self.app = app self.translate = QCoreApplication.translate self.__v2rayshellVersion = "20180423" self.__windowTitile = "V2Ray-shell" + " " + self.__v2rayshellVersion self.runv2raycore = False self.iconStart = QIcon() self.iconStop = QIcon() self.__iconSize = QSize(32, 32) self.iconStart.addPixmap(QPixmap(filePath + "/icons/start.png"), QIcon.Normal, QIcon.On) self.iconStop.addPixmap(QPixmap(filePath + "/icons/stop.png"), QIcon.Disabled, QIcon.On) self.currentRowRightClicked = False self.v2rayshellTrayIcon = QSystemTrayIcon() self.v2rayshellTrayIcon.setIcon(self.iconStart) self.v2rayshellTrayIcon.show() self.radioButtonGroup = QButtonGroup() self.setV2RayshellLanguage() self.trytimes = self.bridgetreasureChest.getConnectiontrytimes() self.interval = self.bridgetreasureChest.getConnectioninterval() self.proxyTryConnect = proxyTryconnect() if v2rayshellDebug: self.proxyTryConnect.setresetTime(6, 3) else: self.proxyTryConnect.setresetTime(self.interval, self.trytimes) self.labelBridge = (self.translate("bridgePanel", "Start/Stop"), self.translate("bridgePanel", "Host Name"), self.translate("bridgePanel", "Config Name"), self.translate("bridgePanel", "Proxy"), self.translate("bridgePanel", "Time Lag")) self.checkTrayicon = QTimer() self.createBridgePanel() def createBridgePanel(self): self.setWindowTitle(self.__windowTitile) self.setWindowIcon(self.iconStart) menubar = self.menuBar() self.statusBar() self.actionNewV2rayConfigFile = QAction( self.translate("bridgePanel", "Add V2Ray-core Config File"), self) self.actionNewV2rayConfigFile.setShortcut(QKeySequence.New) self.actionNewV2rayConfigFile.setStatusTip( self.translate("bridgePanel", "Add V2Ray-core Config File")) self.actionSaveV2rayshellConfigFile = QAction( self.translate("bridgePanel", "Save V2Ray-shell Config File"), self) self.actionSaveV2rayshellConfigFile.setShortcut(QKeySequence.Save) self.actionSaveV2rayshellConfigFile.setStatusTip( self.translate("bridgePanel", "Save V2Ray-shell Config File")) self.actionReloadV2rayshellConfigFile = QAction( self.translate("bridgePanel", "Open V2Ray-shell Config File"), self) self.actionReloadV2rayshellConfigFile.setShortcut(QKeySequence.Open) self.actionReloadV2rayshellConfigFile.setStatusTip( self.translate("bridgePanel", "Open V2Ray-shell Config File")) self.actionQuitV2rayshellPanel = QAction( self.translate("bridgePanel", "Quit"), self) if sys.platform.startswith('win'): self.actionQuitV2rayshellPanel.setShortcut("Ctrl+Q") else: self.actionQuitV2rayshellPanel.setShortcut(QKeySequence.Quit) self.actionQuitV2rayshellPanel.setStatusTip( self.translate("bridgePanel", "Quit V2Ray-shell")) fileMenu = menubar.addMenu( self.translate("bridgePanel", "&File")) fileMenu.addAction(self.actionNewV2rayConfigFile) fileMenu.addSeparator() fileMenu.addAction(self.actionReloadV2rayshellConfigFile) fileMenu.addAction(self.actionSaveV2rayshellConfigFile) fileMenu.addSeparator() fileMenu.addAction(self.actionQuitV2rayshellPanel) self.texteditBridge = QTextEdit(self) self.texteditBridge.setReadOnly(True) self.tableWidgetBridge = QTableWidget() self.tableWidgetBridge.setRowCount(0) self.tableWidgetBridge.setColumnCount(5) self.tableWidgetBridge.setHorizontalHeaderLabels(self.labelBridge) self.tableWidgetBridge.setSelectionMode(QAbstractItemView.SingleSelection) self.tableWidgetBridge.setSelectionBehavior(QAbstractItemView.SelectRows) self.tableWidgetBridge.setEditTriggers(QAbstractItemView.NoEditTriggers) #self.tableWidgetBridge.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch) self.tableWidgetBridge.setContextMenuPolicy(Qt.CustomContextMenu) self.popMenu = popMenu = QMenu(self.tableWidgetBridge) self.actionpopMenuAddV2rayConfigFile = QAction( self.translate("bridgePanel", "Add V2Ray Config File"), self) self.actionpopMenuAddV2rayConfigFile.setShortcut("Ctrl+n") self.actionpopMenuEditV2rayConfigFile = QAction( self.translate("bridgePanel", "Edit V2Ray Config File"), self) self.actionpopMenuProxyCheckTimeLag = QAction( self.translate("bridgePanel", "Proxy Time Lag Check..."), self) self.actionpopMenuDeleteRow = QAction( self.translate("bridgePanel", "Delete"), self) popMenu.addAction(self.actionpopMenuAddV2rayConfigFile) popMenu.addAction(self.actionpopMenuEditV2rayConfigFile) popMenu.addAction(self.actionpopMenuProxyCheckTimeLag) popMenu.addAction(self.actionpopMenuDeleteRow) self.actionopenV2rayshellPreferencesPanel = QAction( self.translate("bridgePanel", "preferences"), self) self.actionopenV2rayshellPreferencesPanel.setStatusTip( self.translate("bridgePanel", "Setting V2Ray-shell")) optionMenu = menubar.addMenu(self.translate("bridgePanel", "&options")) optionMenu.addAction(self.actionpopMenuProxyCheckTimeLag) optionMenu.addAction(self.actionopenV2rayshellPreferencesPanel) helpMenu = menubar.addMenu(self.translate("bridgePanel", "&help")) self.actioncheckv2raycoreupdate = QAction( self.translate("bridgePanel", "check V2Ray-core update"), self) self.actionv2rayshellBugreport = QAction(self.translate("bridgePanel", "Bug Report"), self) self.actionaboutv2rayshell = QAction(self.translate("bridgePanel", "About"), self) helpMenu.addAction(self.actioncheckv2raycoreupdate) helpMenu.addAction(self.actionv2rayshellBugreport) helpMenu.addAction(self.actionaboutv2rayshell) toolBar = QToolBar() self.actionV2rayStart = QAction(self.translate("bridgePanel", "Start")) self.actionV2rayStart.setIcon(self.style().standardIcon(getattr(QStyle, "SP_MediaPlay"))) self.actionV2rayStop = QAction(self.translate("bridgePanel", "Stop")) self.actionV2rayStop.setIcon(self.style().standardIcon(getattr(QStyle, "SP_MediaStop"))) toolBar.addAction(self.actionV2rayStart) toolBar.addAction(self.actionV2rayStop) self.addToolBar(toolBar) self.trayIconMenu = QMenu() self.v2rayshellTrayIcon.setContextMenu(self.trayIconMenu) self.trayIconMenushowhidePanel = QAction(self.translate("bridgePanel", "Show/Hide")) self.trayIconMenuclosePanel = QAction(self.translate("bridgePanel", "Quit")) self.trayIconMenu.addAction(self.trayIconMenushowhidePanel) self.trayIconMenu.addSeparator() self.trayIconMenu.addAction(self.trayIconMenuclosePanel) self.splitterBridge = QSplitter(Qt.Vertical) self.splitterBridge.addWidget(self.tableWidgetBridge) self.splitterBridge.addWidget(self.texteditBridge) self.setCentralWidget(self.splitterBridge) self.createBridgePanelSignals() self.onloadV2rayshellConfigFile(init = True) self.onv2raycoreStart() self.autocheckv2raycoreUpdate() def createBridgePanelSignals(self): self.actionNewV2rayConfigFile.triggered.connect(self.tableWidgetBridgeAddNewV2rayConfigFile) self.actionReloadV2rayshellConfigFile.triggered.connect(self.onloadV2rayshellConfigFile) self.actionSaveV2rayshellConfigFile.triggered.connect(self.onsaveV2rayshellConfigFile) self.actionopenV2rayshellPreferencesPanel.triggered.connect(self.createBridgepreferencesPanel) self.actionpopMenuAddV2rayConfigFile.triggered.connect(self.tableWidgetBridgeAddNewV2rayConfigFile) self.actionpopMenuEditV2rayConfigFile.triggered.connect(self.oncreatenauticalChartPanel) self.actionpopMenuDeleteRow.triggered.connect(self.tableWidgetBridgeDelete) self.actionpopMenuProxyCheckTimeLag.triggered.connect(self.onproxyserverTimeLagTest) self.actioncheckv2raycoreupdate.triggered.connect(self.onopenv2rayupdatePanel) self.actionv2rayshellBugreport.triggered.connect(self.bugReportPanel) self.actionQuitV2rayshellPanel.triggered.connect(self.close) self.actionV2rayStart.triggered.connect(self.onv2raycoreStart) self.actionV2rayStop.triggered.connect(self.onv2raycoreStop) self.actionaboutv2rayshell.triggered.connect(self.about) self.radioButtonGroup.buttonClicked.connect(self.onradioButtonClicked) self.tableWidgetBridge.cellDoubleClicked.connect(self.ontableWidgetBridgecellDoubleClicked) self.tableWidgetBridge.customContextMenuRequested.connect(self.ontableWidgetBridgeRightClicked) self.v2rayshellTrayIcon.activated.connect(self.restorebridgePanel) self.trayIconMenushowhidePanel.triggered.connect(self.onsystemTrayIconMenushowhidebridgePanel) self.trayIconMenuclosePanel.triggered.connect(self.close) self.proxyTryConnect.reconnectproxy.connect(self.swapNextConfigFile) self.start.connect(self.onupdateinstallFinishedstartNewV2raycore) self.stop.connect(self.onv2raycoreStop) self.checkTrayicon.timeout.connect(self.checkSystemTrayIconStatus) self.checkTrayicon.start(1000 * 60) def checkSystemTrayIconStatus(self): """ maybe auto startup will missing trayicon """ if not self.v2rayshellTrayIcon.isVisible(): self.v2rayshellTrayIcon.show() else: self.checkTrayicon.disconnect() def setV2RayshellLanguage(self): self.trans = QTranslator() language = self.bridgetreasureChest.getLanguage() allLanguages = self.bridgetreasureChest.getAllLanguage() if language and allLanguages: if language in allLanguages: self.trans.load(allLanguages[language]) self.app.installTranslator(self.trans) def autocheckv2raycoreUpdate(self): self.bridgeSingal = (self.start, self.stop) self.v2rayshellautoUpdate = updatePanel.autoCheckUpdate( bridgetreasureChest=self.bridgetreasureChest, bridgeSingal=self.bridgeSingal) def event(self, event): if (event.type() == QEvent.WindowStateChange and self.isMinimized()): self.setWindowFlags(self.windowFlags() & ~Qt.Tool) self.v2rayshellTrayIcon.show() return True else: return super(bridgePanel, self).event(event) def onsystemTrayIconMenushowhidebridgePanel(self): if self.isHidden(): self.showNormal() elif self.isVisible(): self.hide() def restorebridgePanel(self, reason): if reason == QSystemTrayIcon.Trigger: if self.isVisible(): self.hide() elif self.isHidden(): self.showNormal() def close(self): super(bridgePanel, self).close() self.v2rayshellTrayIcon.hide() self.onv2raycoreStop() def closeEvent(self, event): self.close() event.accept() sys.exit(self.app.exec_()) def onv2raycoreStop(self): if (self.runv2raycore): self.runv2raycore.stop.emit() try: # force stop checking proxy time lag del self.autoCheckTimer except Exception: pass def onupdateinstallFinishedstartNewV2raycore(self): self.onloadV2rayshellConfigFile(init = True) self.onv2raycoreStart() def onv2raycoreStart(self): currentActiveRow = False rowCount = self.tableWidgetBridge.rowCount() for i in range(rowCount): currentActiveRow = self.tableWidgetBridge.cellWidget(i, 0) if currentActiveRow.isChecked(): self.texteditBridge.clear() option = self.tableWidgetBridge.item(i, 2) if option: option = '-config="{}" -format=json'.format(option.text()) else: option = "" filePath = self.bridgetreasureChest.getV2raycoreFilePath() if (not filePath): filePath = "v2ray" self.runv2raycore = runV2raycore.runV2raycore( outputTextEdit = self.texteditBridge, v2rayPath = filePath, v2rayOption = option, bridgetreasureChest = self.bridgetreasureChest) self.runv2raycore.start.emit() self.autocheckProxy(i) break else: del currentActiveRow def autocheckProxy(self, row): # TODO """ Frequent access to the server may cause suspicion of DDOS attacks, which may put the VPS server at risk. """ enableAutoCheck = self.bridgetreasureChest.getConnectionEnable() if (enableAutoCheck): self.proxyStatus = proxyTest.proxyStatus() self.autoCheckTimer = QTimer() invervalTime = self.bridgetreasureChest.getConnectioninterval() timeout = self.bridgetreasureChest.getConnectiontimeout() proxyAddress = self.getProxyAddressFromTableWidget(row) if proxyAddress: self.autoCheckTimer.timeout.connect(lambda: self.startCheckProxy( timeout = timeout, proxyAddress = proxyAddress, row = row, proxyStatus = self.proxyStatus)) self.bridgetreasureChest.setProxy(proxyAddress) if v2rayshellDebug: self.autoCheckTimer.start(6000) else: self.autoCheckTimer.start(1000 * invervalTime) self.autoCheckTimer.singleShot(100, lambda: self.startCheckProxy( timeout = timeout, proxyAddress = proxyAddress, row = row, proxyStatus = self.proxyStatus)) def setTableWidgetTimelag(self, row, proxyStatus): newlabelTimelag = self.setlabelTimeLagColor(proxyStatus) oldlabelTimelag = self.tableWidgetBridge.cellWidget(row, 4) del oldlabelTimelag self.tableWidgetBridge.setCellWidget(row, 4, newlabelTimelag) self.tableWidgetBridge.resizeColumnsToContents() def startCheckProxy(self, timeout, proxyAddress, row, proxyStatus): if (proxyAddress): proxyStatus.clear() proxyStatus.signal.connect( lambda: self.setTableWidgetTimelag(row, proxyStatus)) self.proxy = proxyTest.proxyTest(proxyprotocol = proxyAddress[0], proxyhostname = proxyAddress[1], proxyhostport = int(proxyAddress[2]), getproxyStatus = proxyStatus, timeout = int(timeout)) def setlabelTimeLagColor(self, proxyStatus=False): labelTimeLag = QLabel() if (proxyStatus and not proxyStatus.getProxyError()): labelFont = QFont() labelFont.setPointSize(12) labelFont.setBold(True) labelTimeLag.setFont(labelFont) forestGreen = "QLabel {color: rgb(34, 139, 34)}" darkOrange = "QLabel {color: rgb(255, 140, 0)}" red = "QLabel {color: rgb(194,24,7)}" if (proxyStatus.getElapsedTime() < 260): labelTimeLag.setStyleSheet(forestGreen) elif (proxyStatus.getElapsedTime() > 420): labelTimeLag.setStyleSheet(red) else: labelTimeLag.setStyleSheet(darkOrange) labelTimeLag.setText("{} ms".format(str(proxyStatus.getElapsedTime()))) return labelTimeLag elif (proxyStatus and proxyStatus.getProxyError()): labelTimeLag.setText("{}:{}".format(proxyStatus.getProxyErrorString(), proxyStatus.getProxyErrorCode())) self.proxyTryConnect.trytimesDecrease() return labelTimeLag def swapNextConfigFile(self): self.onv2raycoreStop() try: self.trytimes = self.bridgetreasureChest.getConnectiontrytimes() self.interval = self.bridgetreasureChest.getConnectioninterval() self.proxyTryConnect.stopperiodicCheckProxyStatus() if v2rayshellDebug: self.proxyTryConnect.setresetTime(6, 3) else: self.proxyTryConnect.setresetTime(self.interval, self.trytimes) except Exception: self.proxyTryConnect.setresetTime(60, 3) if (self.bridgetreasureChest.connectionisSwitch()): # swap next row's configFile buttons = self.radioButtonGroup.buttons() buttonsNumber = len(buttons) activeRow = False for i in range(buttonsNumber): if buttons[i].isChecked(): buttons[i].setChecked(False) if i == buttonsNumber-1: buttons[0].setChecked(True) activeRow = 0 break else: buttons[i + 1].setChecked(True) activeRow = i + 1 break # change the row icons for i in range(buttonsNumber): widget = self.tableWidgetBridge.cellWidget(i, 0) if (widget): widget.setIcon(self.iconStop) widget.setIconSize(self.__iconSize) if (widget.isChecked()): pass widget = self.tableWidgetBridge.cellWidget(activeRow, 0) if widget: widget.setIcon(self.iconStart) widget.setIconSize(self.__iconSize) self.onv2raycoreStart() def onopenv2rayupdatePanel(self): currentActiveRow = False rowCount = self.tableWidgetBridge.rowCount() currentRow = False for i in range(rowCount): currentActiveRow = self.tableWidgetBridge.cellWidget(i, 0) if currentActiveRow.isChecked(): currentRow = i break if (currentActiveRow and currentActiveRow.isChecked()): proxy = self.tableWidgetBridge.item(currentRow, 3) proxy = proxy.text().split(":") protocol = QNetworkProxy.Socks5Proxy if (proxy[0] == "socks"): protocol = QNetworkProxy.Socks5Proxy elif (proxy[0] == "http"): protocol = QNetworkProxy.HttpProxy hostName = proxy[1] hostPort = int(proxy[2]) v2rayAPI = updatePanel.v2rayAPI() self.createupdatePanel = updatePanel.v2rayUpdatePanel(v2rayapi = v2rayAPI, protocol = protocol, proxyhostName = hostName, port = hostPort, bridgetreasureChest = self.bridgetreasureChest) self.createupdatePanel.createPanel() self.createupdatePanel.setAttribute(Qt.WA_DeleteOnClose) self.createupdatePanel.setWindowIcon(self.iconStart) self.createupdatePanel.setWindowTitle( self.translate("bridgePanel", "Check V2Ray-core update")) self.createupdatePanel.resize(QSize(1024, 320)) self.createupdatePanel.move( QApplication.desktop().screen().rect().center()-self.createupdatePanel.rect().center()) self.createupdatePanel.show() self.createupdatePanel.exec_() else: self.noPoxyServerRunning() def ontableWidgetBridgeRightClicked(self, pos): index = self.tableWidgetBridge.indexAt(pos) clickedRow.rightClickedRow = index.row() clickedRow.mousePos = QCursor().pos() self.popMenu.move(QCursor().pos()) self.popMenu.show() def ontableWidgetBridgecellDoubleClicked(self, row, column): if(column == 1): hostName, ok = QInputDialog.getText(self, self.translate("bridgePanel", 'Host Name'), self.translate("bridgePanel", 'Enter Host Name:')) if(ok): self.tableWidgetBridge.setItem(row, column, QTableWidgetItem(str(hostName))) self.tableWidgetBridge.resizeColumnsToContents() elif(column == 2): fileNames = self.onopenV2rayConfigJSONFile() if (fileNames): for fileName in fileNames: self.tableWidgetBridge.setItem(row, column, QTableWidgetItem(str(fileName))) self.tableWidgetBridge.resizeColumnsToContents() elif(column == 3): self.onproxyserverTimeLagTest() elif(column == 4): self.onproxyserverTimeLagTest() def getProxyAddressFromTableWidget(self, row): proxy = self.tableWidgetBridge.item(row, 3) try: proxy = proxy.text().split(":") except Exception: return False if (proxy[0] == "socks"): proxy[0] = QNetworkProxy.Socks5Proxy elif (proxy[0] == "http"): proxy[0] = QNetworkProxy.HttpProxy if len(proxy) < 3: return False else: return proxy def onproxyserverTimeLagTest(self): proxyStatus = proxyTest.proxyStatus() """ right clicked mouse button pop a menu check proxy """ currentActiveRow = False rowCount = self.tableWidgetBridge.rowCount() currentRow = False for i in range(rowCount): currentActiveRow = self.tableWidgetBridge.cellWidget(i, 0) if currentActiveRow.isChecked(): currentRow = i break if (currentActiveRow and currentActiveRow.isChecked()): proxy = self.getProxyAddressFromTableWidget(currentRow) protocol = proxy[0] hostName = proxy[1] hostPort = int(proxy[2]) proxy = proxyTest.proxyTestPanel(proxyhostname = hostName, proxyhostport = hostPort, proxyprotocol = protocol, getproxyStatus = proxyStatus) proxy.createproxyTestPanel() proxy.setAttribute(Qt.WA_DeleteOnClose) proxy.setWindowTitle(self.translate("bridgePanel", "Proxy Time Lag Check")) proxy.setWindowIcon(self.iconStart) proxy.resize(QSize(600, 480)) proxy.move(QApplication.desktop().screen().rect().center()-proxy.rect().center()) proxy.show() proxy.exec_() else: self.noPoxyServerRunning() def noPoxyServerRunning(self): warningPanel = QDialog() warningPanel.setAttribute(Qt.WA_DeleteOnClose) warningPanel.setWindowTitle(self.translate("bridgePanel", "Warnnig...")) warningPanel.setWindowIcon(self.iconStop) labelMsg = QLabel( self.translate("bridgePanel", "There no any server is running, \n[File]->[Add V2Ray-core Config File] (Ctrl+n) add a config.json.")) vbox = QVBoxLayout() vbox.addWidget(labelMsg) warningPanel.setLayout(vbox) warningPanel.move(QApplication.desktop().screen().rect().center()-warningPanel.rect().center()) warningPanel.open() warningPanel.exec_() def getProxyAddressFromJSONFile(self, filePath): from bridgehouse.editMap.port import treasureChest, openV2rayJSONFile tempTreasureChest = treasureChest.treasureChest() openV2rayJSONFile.openV2rayJSONFile(filePath, tempTreasureChest, disableLog = True).initboundJSONData() inbound = tempTreasureChest.getInbound() if (inbound): try: protocol = inbound["protocol"] ipAddress = inbound["listen"] port = inbound["port"] if (protocol == "socks" or protocol == "http"): return "{}:{}:{}".format(protocol, ipAddress, port) else: return False except Exception: return False else: return False def onradioButtonClicked(self, e): rowCount = self.tableWidgetBridge.rowCount() # radioButtonClickedRow = 0 for i in range(rowCount): widget = self.tableWidgetBridge.cellWidget(i, 0) if (widget): widget.setIcon(self.iconStop) widget.setIconSize(self.__iconSize) if (widget.isChecked()): # radioButtonClickedRow = i pass e.setIcon(self.iconStart) e.setIconSize(self.__iconSize) def onloadV2rayshellConfigFile(self, init = False): """ when the script first start, and auto load v2ray-shell config file. """ if init: self.settingv2rayshelltableWidget() else: def openV2rayshellConfigFile(): options = QFileDialog.Options() filePath, _ = QFileDialog.getOpenFileName(self, self.translate("bridgePanel", "Open V2Ray-sehll Config File"), "", "V2Ray-shell config file (*.v2rayshell)", options = options) if (filePath): self.bridgetreasureChest.clear() self.tableWidgetBridge.setRowCount(0) self.bridgetreasureChest.initbridgeJSONData(v2rayshellConfigFileName = filePath) self.settingv2rayshelltableWidget() openV2rayshellConfigFile() def onopenV2rayConfigJSONFile(self): """ open a new v2ray config file to tabelWidget """ options = QFileDialog.Options() filePaths, _ = QFileDialog.getOpenFileNames(self, self.translate("bridgePanel", "Open V2Ray-core Config File"), "", """ V2Ray config file (*.json);; All File (*);; """, options = options) if (filePaths): return filePaths else: return False def createBridgepreferencesPanel(self): self.createpreferencesPanel = bridgePreference.bridgepreferencesPanel(self.bridgetreasureChest) self.createpreferencesPanel.setAttribute(Qt.WA_DeleteOnClose) self.createpreferencesPanel.createpreferencesPanel() self.createpreferencesPanel.setWindowIcon(self.iconStart) self.createpreferencesPanel.move( QApplication.desktop().screen().rect().center()-self.createpreferencesPanel.rect().center()) self.createpreferencesPanel.open() self.createpreferencesPanel.exec_() def settingv2rayshelltableWidget(self): v2rayConfigFiles = self.bridgetreasureChest.getV2raycoreconfigFiles() if not v2rayConfigFiles:return v2rayConfigFilesNumber = len(v2rayConfigFiles) if (v2rayConfigFilesNumber): self.tableWidgetBridge.setRowCount(0) for i in range(v2rayConfigFilesNumber): try: enable = bool(v2rayConfigFiles[i]["enable"]) hostName = str(v2rayConfigFiles[i]["hostName"]) configFileName = str(v2rayConfigFiles[i]["configFileName"]) except Exception: pass radioButtonStopStart = QRadioButton(self) radioButtonStopStart.setIcon(self.iconStop if not enable else self.iconStart) radioButtonStopStart.setChecked(True if enable else False) radioButtonStopStart.setIconSize(self.__iconSize) self.radioButtonGroup.addButton(radioButtonStopStart) self.tableWidgetBridge.setRowCount(i+1) self.tableWidgetBridge.setCellWidget(i, 0, radioButtonStopStart) self.tableWidgetBridge.setItem(i, 1, QTableWidgetItem(hostName)) self.tableWidgetBridge.setItem(i, 2, QTableWidgetItem(configFileName)) self.tableWidgetBridge.setItem(i, 3, QTableWidgetItem(self.getProxyAddressFromJSONFile(configFileName))) self.tableWidgetBridge.resizeColumnsToContents() #self.tableWidgetBridge.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch) def onsaveV2rayshellConfigFile(self): self.bridgetreasureChest.clearconfigFiles() rowCount = self.tableWidgetBridge.rowCount() for i in range(rowCount): enable = self.tableWidgetBridge.cellWidget(i, 0) if enable and enable.isChecked(): enable = True else: enable = False hostName = self.tableWidgetBridge.item(i, 1) if hostName: hostName = hostName.text() else: hostName = "" config = self.tableWidgetBridge.item(i, 2) if config: config = config.text() else: config = "" self.bridgetreasureChest.setV2raycoreconfigFiles(enable, hostName, configFileName = config) self.bridgetreasureChest.save.emit() def oncreatenauticalChartPanel(self): v2rayConfigFileName = self.tableWidgetBridge.item(clickedRow.rightClickedRow, 2) if (v2rayConfigFileName): nc = nauticalChartPanel.nauticalChartPanel(v2rayConfigFileName.text()) nc.setAttribute(Qt.WA_DeleteOnClose) nc.createPanel() nc.setWindowTitle( self.translate("bridgePanel", "V2Ray config file edit")) nc.setWindowIcon(self.iconStart) nc.setGeometry(0, 0, 1024, 768) # move widget to center nc.move(QApplication.desktop().screen().rect().center()-nc.rect().center()) nc.show() nc.exec_() def tableWidgetBridgeAddNewV2rayConfigFile(self): configFileNames = self.onopenV2rayConfigJSONFile() if (configFileNames): for configFileName in configFileNames: rowCount = self.tableWidgetBridge.rowCount() radioButtonStopStart = QRadioButton(self) radioButtonStopStart.setIcon(self.iconStop) radioButtonStopStart.setIconSize(self.__iconSize) self.radioButtonGroup.addButton(radioButtonStopStart) self.tableWidgetBridge.setRowCount(rowCount+1) self.tableWidgetBridge.setCellWidget(rowCount, 0, radioButtonStopStart) self.tableWidgetBridge.setItem(rowCount, 1, QTableWidgetItem("")) self.tableWidgetBridge.setItem(rowCount, 2, QTableWidgetItem(configFileName)) self.tableWidgetBridge.setItem(rowCount, 3, QTableWidgetItem(self.getProxyAddressFromJSONFile(configFileName))) self.tableWidgetBridge.resizeColumnsToContents() else: pass def tableWidgetBridgeDelete(self): self.tableWidgetBridge.removeRow(clickedRow.rightClickedRow) def validateV2rayJSONFile(self, JSONData): """ simply validate a V2Ray json file. """ try: JSONData["inbound"] JSONData["outbound"] except KeyError: return False else: return True def about(self): NineteenEightySeven = QLabel( self.translate("bridgePanel", """Across the Great Wall, we can reach every corner in the world.""")) ### Crossing the Great Wall to Join the World Timeless = QLabel( self.translate("bridgePanel", """You weren't thinking about that when you were creating it.\nBecause if you did? You never would have gone through with it.""")) DwayneRichardHipp = QLabel( self.translate("bridgePanel", """May you do good and not evil.\nMay you find forgiveness for yourself and forgive others.\nMay you share freely, never taking more than you give.""")) vbox = QVBoxLayout() vbox.addWidget(NineteenEightySeven) vbox.addWidget(Timeless) vbox.addWidget(DwayneRichardHipp) dialogAbout = QDialog() dialogAbout.setAttribute(Qt.WA_DeleteOnClose) dialogAbout.setWindowTitle(self.translate("bridgePanel", "About V2Ray-shell")) dialogAbout.setWindowIcon(self.iconStart) dialogAbout.move( QApplication.desktop().screen().rect().center()-dialogAbout.rect().center()) dialogAbout.setLayout(vbox) dialogAbout.open() dialogAbout.exec_() def bugReportPanel(self): self.bugReport = bugReport.bugReport() self.bugReport.setAttribute(Qt.WA_DeleteOnClose) self.bugReport.setWindowTitle(self.translate("bridgePanel", "Bug Report")) self.bugReport.setWindowIcon(self.iconStart) self.bugReport.createPanel() self.bugReport.show() self.bugReport.setGeometry(250, 150, 1024, 768)
s = f.read() f.close() self.Edit.setText(s) self.filename = fn def runCode(self): self.msg('run') def msg(self, m): self.msgwin.setText(self.tr(m)) if __name__ == '__main__': app = QApplication(sys.argv) # translation stuff lang=QLocale.system().name() t=QTranslator() t.load("lang/"+lang, os.path.dirname(__file__)) app.installTranslator(t) t1=QTranslator() t1.load("qt_"+lang, QLibraryInfo.location(QLibraryInfo.TranslationsPath)) app.installTranslator(t1) mw = Expt() mw.show() sys.exit(app.exec_())
class OAMQGIS3: """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', 'OAMQGIS3_{}.qm'.format(locale)) 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'&OAMQGIS3 EXPRESS') # QSettings objects self.settings = QSettings('QGIS', 'OAM_QGIS3_EXPRESS') # self.settings = QSettings() # Check if plugin was started the first time in current QGIS session # Must be set in initGui() to survive plugin reloads self.first_start_search_dialog = None # self.first_start = 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('OAMQGIS3', 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: # Adds plugin icon to Plugins toolbar self.iface.addToolBarIcon(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/oam_qgis3_express/icon/search_icon.png' self.add_action( icon_path, text=self.tr(u'Image Search'), callback=self.displaySearchDialog, parent=self.iface.mainWindow()) """ icon_path = ':/plugins/oam_qgis3_express/icon/sample_icon.png' self.add_action( icon_path, text=self.tr(u'Sample Item'), callback=self.run, parent=self.iface.mainWindow()) """ # will be set False in displaySearchDialog() and run() self.first_start_search_dialog = True # self.first_start = True def unload(self): """Removes the plugin menu item and icon from QGIS GUI.""" for action in self.actions: self.iface.removePluginMenu( self.tr(u'&OAMQGIS3 EXPRESS'), action) self.iface.removeToolBarIcon(action) """Please refer to the displaySearchDialog function below""" """ def run(self): # Create the dialog with elements (after translation) and keep reference # Only create GUI ONCE in callback, so that it will only load when the plugin is started if self.first_start == True: self.first_start = False self.dlg = OAMQGIS3Dialog() # show the dialog self.dlg.show() # Run the dialog event loop result = self.dlg.exec_() # See if OK was pressed if result: # Do something useful here - delete the line containing pass and # substitute with your code. pass """ def displaySearchDialog(self): if self.first_start_search_dialog == True: self.first_start_search_dialog = False self.imgSearchDialog = ImgSearchDialog(self.iface, self.settings) # show the dialog self.imgSearchDialog.show() self.imgSearchDialog.activateWindow() self.imgSearchDialog.raise_() # Run the dialog event loop result = self.imgSearchDialog.exec_() print(result) # See if OK was pressed if result: # Do something useful here - delete the line containing pass and # substitute with your code. pass
cerrar.exec_() if cerrar.clickedButton() == botonSalir: event.accept() else: event.ignore() # =============================================================== if __name__ == "__main__": import sys aplicacion = QApplication(sys.argv) traductor = QTranslator(aplicacion) lugar = QLocale.system().name() path = QLibraryInfo.location(QLibraryInfo.TranslationsPath) traductor.load("qtbase_%s" % lugar, path) aplicacion.installTranslator(traductor) fuente = QFont() fuente.setPointSize(10) aplicacion.setFont(fuente) ventana = Siacle() ventana.showMaximized() sys.exit(aplicacion.exec_())
class QmyMainWindow(QMainWindow): _tr = QCoreApplication.translate #替代符 def __init__(self, parent=None): super().__init__(parent) #调用父类构造函数,创建窗体 self.ui=Ui_MainWindow() #创建UI对象 self.ui.setupUi(self) #构造UI界面 text=self._tr("QmyMainWindow","文件名: ") self.ui.statusBar.showMessage(text) actionGroup= QActionGroup(self) actionGroup.addAction(self.ui.actLang_CN) actionGroup.addAction(self.ui.actLang_EN) actionGroup.setExclusive(True) self.__translator=None #QTranslator对象 self.setCentralWidget(self.ui.textEdit) ## ============自定义功能函数================================ def setTranslator(self,translator,Language): self.__translator=translator if Language=="EN": self.ui.actLang_EN.setChecked(True) else: self.ui.actLang_CN.setChecked(True) ## ===========由connectSlotsByName() 自动连接的槽函数===================== @pyqtSlot() ##英语界面 def on_actLang_EN_triggered(self): QCoreApplication.removeTranslator(self.__translator) self.__translator=QTranslator() self.__translator.load("appLang_EN.qm") QCoreApplication.installTranslator(self.__translator) self.ui.retranslateUi(self) regSettings=QSettings(QCoreApplication.organizationName(), QCoreApplication.applicationName()) regSettings.setValue("Language","EN") #保存设置 @pyqtSlot() ##汉语界面 def on_actLang_CN_triggered(self): QCoreApplication.removeTranslator(self.__translator) self.__translator=QTranslator() self.__translator.load("appLang_CN.qm") QCoreApplication.installTranslator(self.__translator) self.ui.retranslateUi(self) regSettings=QSettings(QCoreApplication.organizationName(), QCoreApplication.applicationName()) regSettings.setValue("Language","CN") #保存设置 @pyqtSlot(bool) ##设置粗体 def on_actFont_Bold_triggered(self, checked): fmt=self.ui.textEdit.currentCharFormat() if (checked == True): fmt.setFontWeight(QFont.Bold) else: fmt.setFontWeight(QFont.Normal) self.ui.textEdit.mergeCurrentCharFormat(fmt) @pyqtSlot(bool) ##设置斜体 def on_actFont_Italic_triggered(self,checked): fmt=self.ui.textEdit.currentCharFormat() fmt.setFontItalic(checked) self.ui.textEdit.mergeCurrentCharFormat(fmt) @pyqtSlot(bool) ##设置下划线 def on_actFont_UnderLine_triggered(self,checked): fmt=self.ui.textEdit.currentCharFormat() fmt.setFontUnderline(checked) self.ui.textEdit.mergeCurrentCharFormat(fmt) def on_textEdit_copyAvailable(self, avi): ##文本框内容可copy self.ui.actEdit_Cut.setEnabled(avi) self.ui.actEdit_Copy.setEnabled(avi) self.ui.actEdit_Paste.setEnabled(self.ui.textEdit.canPaste()) def on_textEdit_selectionChanged(self): ##文本选择内容发生变化 fmt=self.ui.textEdit.currentCharFormat() self.ui.actFont_Bold.setChecked(fmt.font().bold()) self.ui.actFont_Italic.setChecked(fmt.fontItalic()) self.ui.actFont_UnderLine.setChecked(fmt.fontUnderline()) def on_textEdit_customContextMenuRequested(self,pos): ##标准右键菜单 popMenu=self.ui.textEdit.createStandardContextMenu() popMenu.exec(pos) @pyqtSlot(bool) ##设置工具栏按钮样式 def on_actSys_ToggleText_triggered(self,checked): btnStyle=Qt.ToolButtonIconOnly if(checked): btnStyle=Qt.ToolButtonTextUnderIcon self.ui.mainToolBar.setToolButtonStyle(btnStyle) def on_actFile_New_triggered(self): ##新建文件,不实现具体功能 text=self._tr("QmyMainWindow","新建文件") self.ui.statusBar.showMessage(text) def on_actFile_Open_triggered(self): ##打开文件,不实现具体功能 text=self._tr("QmyMainWindow","打开的文件:") self.ui.statusBar.showMessage(text) def on_actFile_Save_triggered(self): ##保存文件,不实现具体功能 text=self._tr("QmyMainWindow","文件已保存") self.ui.statusBar.showMessage(text)
class PreferencesWindow(Setting_Ui): def __init__(self, parent, persepolis_setting): super().__init__(persepolis_setting) self.persepolis_setting = persepolis_setting self.parent = parent self.grandparent = parent.persepolis_main self.persepolis_setting.beginGroup('settings') # initialization self.tries_spinBox.setValue( int(self.persepolis_setting.value('max-tries'))) self.wait_spinBox.setValue( int(self.persepolis_setting.value('retry-wait'))) self.time_out_spinBox.setValue( int(self.persepolis_setting.value('timeout'))) self.connections_spinBox.setValue( int(self.persepolis_setting.value('connections'))) self.rpc_port_spinbox.setValue( int(self.persepolis_setting.value('rpc-port'))) # add support for other languages locale = str(self.persepolis_setting.value('settings/locale')) QLocale.setDefault(QLocale(locale)) self.translator = QTranslator() if self.translator.load(':/translations/locales/ui_' + locale, 'ts'): QCoreApplication.installTranslator(self.translator) # wait_queue wait_queue_list = self.persepolis_setting.value('wait-queue') q_time = QTime(int(wait_queue_list[0]), int(wait_queue_list[1])) self.wait_queue_time.setTime(q_time) # change aria2 path self.aria2_path_pushButton.clicked.connect(self.changeAria2Path) self.aria2_path_checkBox.toggled.connect(self.ariaCheckBoxToggled) aria2_path = self.persepolis_setting.value('settings/aria2_path') self.aria2_path_lineEdit.setEnabled(False) if aria2_path != None: self.aria2_path_checkBox.setChecked(True) self.aria2_path_lineEdit.setText(str(aria2_path)) self.ariaCheckBoxToggled('aria2') if os_type == 'Linux' or os_type == 'FreeBSD' or os_type == 'OpenBSD': for widget in self.aria2_path_checkBox, self.aria2_path_lineEdit, self.aria2_path_pushButton: widget.hide() # save_as_tab self.download_folder_lineEdit.setText( str(self.persepolis_setting.value('download_path'))) self.temp_download_lineEdit.setText( str(self.persepolis_setting.value('download_path_temp'))) # subfolder if str(self.persepolis_setting.value('subfolder')) == 'yes': self.subfolder_checkBox.setChecked(True) else: self.subfolder_checkBox.setChecked(False) # notifications_tab self.volume_label.setText( 'Volume : ' + str(self.persepolis_setting.value('sound-volume'))) self.volume_dial.setValue( int(self.persepolis_setting.value('sound-volume'))) # set style # find available styles(It's depends on operating system and desktop environments). available_styles = QStyleFactory.keys() for style in available_styles: # 'GTK' or 'gtk' styles may cause to crashing! Eliminate them! if 'gtk' not in str(style) and 'GTK' not in str(style): self.style_comboBox.addItem(style) # System >> for system default style # when user select System for style section, the default system style is using. self.style_comboBox.addItem('System') current_style_index = self.style_comboBox.findText( str(self.persepolis_setting.value('style'))) if current_style_index != -1: self.style_comboBox.setCurrentIndex(current_style_index) # available language available_language = [ 'en_US', 'fa_IR', 'ar', 'zh_CN', 'fr_FR', 'pl_PL', 'nl_NL', 'pt_BR', 'es_ES', 'hu', 'tr', 'tr_TR' ] for lang in available_language: self.lang_comboBox.addItem(str(QLocale(lang).nativeLanguageName()), lang) current_locale = self.lang_comboBox.findData( str(self.persepolis_setting.value('locale'))) self.lang_comboBox.setCurrentIndex(current_locale) self.current_icon = self.persepolis_setting.value('icons') # icon size size = ['128', '64', '48', '32', '24', '16'] self.icons_size_comboBox.addItems(size) current_icons_size_index = self.icons_size_comboBox.findText( str(self.persepolis_setting.value('toolbar_icon_size'))) self.icons_size_comboBox.setCurrentIndex(current_icons_size_index) # call setDarkLightIcon if index is changed self.icons_size_comboBox.currentIndexChanged.connect( self.setDarkLightIcon) # set notification notifications = ['Native notification', 'QT notification'] self.notification_comboBox.addItems(notifications) current_notification_index = self.notification_comboBox.findText( str(self.persepolis_setting.value('notification'))) self.notification_comboBox.setCurrentIndex(current_notification_index) # set font font_setting = QFont() font_setting.setFamily(str(self.persepolis_setting.value('font'))) self.fontComboBox.setCurrentFont(font_setting) self.font_size_spinBox.setValue( int(self.persepolis_setting.value('font-size'))) # sound frame self.sound_frame.setEnabled(False) self.enable_notifications_checkBox.toggled.connect(self.soundFrame) if str(self.persepolis_setting.value('sound')) == 'yes': self.enable_notifications_checkBox.setChecked(True) else: self.enable_notifications_checkBox.setChecked(False) # connect folder buttons self.download_folder_lineEdit.setEnabled(False) self.download_folder_pushButton.clicked.connect( self.downloadFolderPushButtonClicked) self.temp_download_lineEdit.setEnabled(False) self.temp_download_pushButton.clicked.connect( self.tempDownloadPushButtonClicked) # dial self.volume_dial.setNotchesVisible(True) self.volume_dial.valueChanged.connect(self.dialChanged) # start_persepolis_if_browser_executed_checkBox if str(self.persepolis_setting.value('browser-persepolis')) == 'yes': self.start_persepolis_if_browser_executed_checkBox.setChecked(True) else: self.start_persepolis_if_browser_executed_checkBox.setChecked( False) # hide window if str(self.persepolis_setting.value('hide-window')) == 'yes': self.hide_window_checkBox.setChecked(True) else: self.hide_window_checkBox.setChecked(False) # tray icon if str(self.persepolis_setting.value('tray-icon')) == 'yes': self.enable_system_tray_checkBox.setChecked(True) else: self.enable_notifications_checkBox.setChecked(False) # show_menubar if str(self.persepolis_setting.value('show-menubar')) == 'yes': self.show_menubar_checkbox.setChecked(True) else: self.show_menubar_checkbox.setChecked(False) if platform.system() == 'Darwin': self.show_menubar_checkbox.setChecked(True) self.show_menubar_checkbox.hide() # show_sidepanel if str(self.persepolis_setting.value('show-sidepanel')) == 'yes': self.show_sidepanel_checkbox.setChecked(True) else: self.show_sidepanel_checkbox.setChecked(False) # show ProgressWindow if str(self.persepolis_setting.value('show-progress')) == 'yes': self.show_progress_window_checkbox.setChecked(True) else: self.show_progress_window_checkbox.setChecked(False) # after download dialog if str(self.persepolis_setting.value('after-dialog')) == 'yes': self.after_download_checkBox.setChecked(True) else: self.after_download_checkBox.setChecked(False) # run persepolis at startup checkBox if str(self.persepolis_setting.value('startup')) == 'yes': self.startup_checkbox.setChecked(True) else: self.startup_checkbox.setChecked(False) # font_checkBox if str(self.persepolis_setting.value('custom-font')) == 'yes': self.font_checkBox.setChecked(True) else: self.font_checkBox.setChecked(False) self.fontCheckBoxState(self.font_checkBox) # keep_awake_checkBox if str(self.persepolis_setting.value('awake')) == 'yes': self.keep_awake_checkBox.setChecked(True) else: self.keep_awake_checkBox.setChecked(False) # columns_tab if str(self.persepolis_setting.value('column0')) == 'yes': self.column0_checkBox.setChecked(True) else: self.column0_checkBox.setChecked(False) if str(self.persepolis_setting.value('column1')) == 'yes': self.column1_checkBox.setChecked(True) else: self.column1_checkBox.setChecked(False) if str(self.persepolis_setting.value('column2')) == 'yes': self.column2_checkBox.setChecked(True) else: self.column2_checkBox.setChecked(False) if str(self.persepolis_setting.value('column3')) == 'yes': self.column3_checkBox.setChecked(True) else: self.column3_checkBox.setChecked(False) if str(self.persepolis_setting.value('column4')) == 'yes': self.column4_checkBox.setChecked(True) else: self.column4_checkBox.setChecked(False) if str(self.persepolis_setting.value('column5')) == 'yes': self.column5_checkBox.setChecked(True) else: self.column5_checkBox.setChecked(False) if str(self.persepolis_setting.value('column6')) == 'yes': self.column6_checkBox.setChecked(True) else: self.column6_checkBox.setChecked(False) if str(self.persepolis_setting.value('column7')) == 'yes': self.column7_checkBox.setChecked(True) else: self.column7_checkBox.setChecked(False) if str(self.persepolis_setting.value('column10')) == 'yes': self.column10_checkBox.setChecked(True) else: self.column10_checkBox.setChecked(False) if str(self.persepolis_setting.value('column11')) == 'yes': self.column11_checkBox.setChecked(True) else: self.column11_checkBox.setChecked(False) if str(self.persepolis_setting.value('column12')) == 'yes': self.column12_checkBox.setChecked(True) else: self.column12_checkBox.setChecked(False) # video_finder try: # Integer casting may raise exception. self.max_links_spinBox.setValue( int(persepolis_setting.value('video_finder/max_links', 3))) except: pass # shortcuts self.qshortcuts_list = [ self.parent.exitAction_shortcut, self.parent.minimizeAction_shortcut, self.parent.removeSelectedAction_shortcut, self.parent.deleteSelectedAction_shortcut, self.parent.moveUpSelectedAction_shortcut, self.parent.moveDownSelectedAction_shortcut, self.parent.addlinkAction_shortcut, self.parent.videoFinderAddLinkAction_shortcut, self.parent.addtextfileAction_shortcut ] self.shortcuts_list = [ self.parent.exitAction_shortcut.key().toString(), self.parent.minimizeAction_shortcut.key().toString(), self.parent.removeSelectedAction_shortcut.key().toString(), self.parent.deleteSelectedAction_shortcut.key().toString(), self.parent.moveUpSelectedAction_shortcut.key().toString(), self.parent.moveDownSelectedAction_shortcut.key().toString(), self.parent.addlinkAction_shortcut.key().toString(), self.parent.videoFinderAddLinkAction_shortcut.key().toString(), self.parent.addtextfileAction_shortcut.key().toString() ] # add shortcuts to the shortcut_table j = 0 for shortcut in self.shortcuts_list: item = QTableWidgetItem(shortcut) # align center item.setTextAlignment(0x0004 | 0x0080) # insert item in shortcut_table self.shortcut_table.setItem(j, 1, item) j = j + 1 # If user doubleclicks on a row, then run showCaptureKeyboardWindow method self.shortcut_table.itemDoubleClicked.connect( self.showCaptureKeyboardWindow) # ok cancel default button self.cancel_pushButton.clicked.connect(self.close) self.defaults_pushButton.clicked.connect( self.defaultsPushButtonPressed) self.ok_pushButton.clicked.connect(self.okPushButtonPressed) # font_checkBox connect self.font_checkBox.stateChanged.connect(self.fontCheckBoxState) # saving initial value of self.persepolis_setting in self.first_key_value_dict # at the end! in the okPushButtonPressed method, first_key_value_dict will compared with second_key_value_dict. # if any thing changed , then a message box notify user about "some changes take effect after restarting persepolis". self.first_key_value_dict = {} for member in self.persepolis_setting.allKeys(): self.first_key_value_dict[member] = str( self.persepolis_setting.value(member)) # if style_comboBox is changed, self.styleComboBoxChanged is called. self.style_comboBox.currentIndexChanged.connect( self.styleComboBoxChanged) self.styleComboBoxChanged() self.color_comboBox.currentIndexChanged.connect(self.setDarkLightIcon) self.persepolis_setting.endGroup() # setting window size and position size = self.persepolis_setting.value('PreferencesWindow/size', QSize(578, 565)) position = self.persepolis_setting.value('PreferencesWindow/position', QPoint(300, 300)) self.resize(size) self.move(position) # run this method if user doubleclicks on an item in shortcut_table def showCaptureKeyboardWindow(self): # show KeyCapturingWindow keyboard_capture_window = KeyCapturingWindow(self.callBack, self.persepolis_setting) self.parent.capturekeywindows_list.append(keyboard_capture_window) self.parent.capturekeywindows_list[ len(self.parent.capturekeywindows_list) - 1].show() def callBack(self, keys): # do nothing if keys is empty if not (keys): return # check that if shortcut used before. if keys in self.shortcuts_list: self.msgBox = QMessageBox() self.msgBox.setText( QCoreApplication.translate( "setting_src_ui_tr", "<b><center>This shortcut has been used before!\ Use another one!</center></b>")) self.msgBox.setIcon(QMessageBox.Warning) reply = self.msgBox.exec_() # set new shortcut else: selected_row = self.shortcut_table.selectionModel().selectedRows( )[0].row() item = QTableWidgetItem(keys) # align center item.setTextAlignment(0x0004 | 0x0080) # insert item in shortcut_table self.shortcut_table.setItem(selected_row, 1, item) # set keys in shortcuts_list self.shortcuts_list[selected_row] = keys # active color_comboBox only when user is select "Fusion" style. def styleComboBoxChanged(self, index=None): # clear color_comboBox self.color_comboBox.clear() # get current style selected_style = self.style_comboBox.currentText() if selected_style != 'Fusion': # color_comboBox item color_scheme = ['System'] # add item self.color_comboBox.addItems(color_scheme) # set 'System' for color_scheme current_color_index = self.color_comboBox.findText('System') self.color_comboBox.setCurrentIndex(current_color_index) # disable color_comboBox self.color_comboBox.setEnabled(False) else: # enable color_comboBox self.color_comboBox.setEnabled(True) # color_comboBox items color_scheme = ['Dark Fusion', 'Light Fusion'] # add items self.color_comboBox.addItems(color_scheme) current_color_index = self.color_comboBox.findText( str(self.persepolis_setting.value('color-scheme'))) # it means user's prefered color_scheme is not valid in color_comboBox. if current_color_index == -1: current_color_index = 0 self.color_comboBox.setCurrentIndex(current_color_index) self.setDarkLightIcon() # this method sets dark icons for dark color schemes # and light icons for light color schemes. def setDarkLightIcon(self, index=None): dark_theme = None # find selected style selected_style = self.style_comboBox.currentText() # clear icon_comboBox self.icon_comboBox.clear() # Papirus icons can be used with small sizes(smaller than 48) # get user's selected icons size selected_size = int(self.icons_size_comboBox.currentText()) if selected_style == 'Fusion': if self.color_comboBox.currentText() == 'Dark Fusion': dark_theme = True else: dark_theme = False elif selected_style == 'Adwaita-Dark': dark_theme = True elif selected_style == 'Adwaita' or selected_style == 'macintosh': dark_theme = False if dark_theme == True: self.icon_comboBox.clear() if selected_size < 48: icons = ['Breeze-Dark', 'Papirus-Dark'] else: icons = ['Breeze-Dark'] self.icon_comboBox.addItems(icons) # current_icons_index is -1, if findText couldn't find icon index. current_icons_index = self.icon_comboBox.findText( str(self.persepolis_setting.value('icons', self.current_icon))) if current_icons_index == -1: current_icons_index = 0 self.icon_comboBox.setCurrentIndex(current_icons_index) elif dark_theme == False: if selected_size < 48: icons = ['Breeze', 'Papirus', 'Papirus-Light'] else: icons = ['Breeze', 'Papirus'] self.icon_comboBox.addItems(icons) # current_icons_index is -1, if findText couldn't find icon index. current_icons_index = self.icon_comboBox.findText( str(self.persepolis_setting.value('icons', self.current_icon))) if current_icons_index == -1: current_icons_index = 0 self.icon_comboBox.setCurrentIndex(current_icons_index) else: if selected_size < 48: icons = [ 'Breeze', 'Breeze-Dark', 'Papirus', 'Papirus-Dark', 'Papirus-Light' ] else: icons = ['Breeze', 'Breeze-Dark', 'Papirus'] self.icon_comboBox.addItems(icons) # current_icons_index is -1, if findText couldn't find icon index. current_icons_index = self.icon_comboBox.findText( str(self.persepolis_setting.value('icons', self.current_icon))) if current_icons_index == -1: current_icons_index = 0 self.icon_comboBox.setCurrentIndex(current_icons_index) def fontCheckBoxState(self, checkBox): # deactive fontComboBox and font_size_spinBox if font_checkBox not checked! if self.font_checkBox.isChecked(): self.fontComboBox.setEnabled(True) self.font_size_spinBox.setEnabled(True) else: self.fontComboBox.setEnabled(False) self.font_size_spinBox.setEnabled(False) # close window with ESC key def keyPressEvent(self, event): if event.key() == Qt.Key_Escape: self.close() def closeEvent(self, event): # saving window size and position self.persepolis_setting.setValue('PreferencesWindow/size', self.size()) self.persepolis_setting.setValue('PreferencesWindow/position', self.pos()) self.persepolis_setting.sync() event.accept() if self.parent.isVisible() == False: self.parent.minMaxTray(event) self.close() def soundFrame(self, checkBox): if self.enable_notifications_checkBox.isChecked(): self.sound_frame.setEnabled(True) else: self.sound_frame.setEnabled(False) def ariaCheckBoxToggled(self, checkBox): if self.aria2_path_checkBox.isChecked(): self.aria2_path_pushButton.setEnabled(True) else: self.aria2_path_pushButton.setEnabled(False) def changeAria2Path(self, button): cwd = sys.argv[0] cwd = os.path.dirname(cwd) f_path, filters = QFileDialog.getOpenFileName(self, 'Select aria2 path', cwd) # if path is correct: if os.path.isfile(str(f_path)): self.aria2_path_lineEdit.setText(str(f_path)) else: self.aria2_path_checkBox.setChecked(False) def downloadFolderPushButtonClicked(self, button): download_path = str( self.persepolis_setting.value('settings/download_path')) fname = QFileDialog.getExistingDirectory(self, 'Select a directory', download_path) if fname: # Returns pathName with the '/' separators converted to separators that are appropriate for the underlying operating system. # On Windows, toNativeSeparators("c:/winnt/system32") returns # "c:\winnt\system32". fname = QDir.toNativeSeparators(fname) self.download_folder_lineEdit.setText(fname) self.persepolis_setting.setValue('settings/download_path', str(fname)) def tempDownloadPushButtonClicked(self, button): download_path_temp = str( self.persepolis_setting.value('settings/download_path_temp')) fname = QFileDialog.getExistingDirectory(self, 'Open f', download_path_temp) if fname: self.temp_download_lineEdit.setText(fname) self.persepolis_setting.setValue('settings/download_path_temp', str(fname)) def dialChanged(self, dial): self.volume_label.setText('Volume : ' + str(self.volume_dial.value())) def defaultsPushButtonPressed(self, button): self.persepolis_setting.beginGroup('settings') self.setting_dict = returnDefaultSettings() self.tries_spinBox.setValue(int(self.setting_dict['max-tries'])) self.wait_spinBox.setValue(int(self.setting_dict['retry-wait'])) self.time_out_spinBox.setValue(int(self.setting_dict['timeout'])) self.connections_spinBox.setValue(int( self.setting_dict['connections'])) self.rpc_port_spinbox.setValue(int(self.setting_dict['rpc-port'])) self.aria2_path_lineEdit.setText('') self.aria2_path_checkBox.setChecked(False) # wait-queue wait_queue_list = self.setting_dict['wait-queue'] q_time = QTime(wait_queue_list[0], wait_queue_list[1]) self.wait_queue_time.setTime(q_time) # save_as_tab self.download_folder_lineEdit.setText( str(self.setting_dict['download_path'])) self.temp_download_lineEdit.setText( str(self.setting_dict['download_path_temp'])) self.subfolder_checkBox.setChecked(True) # notifications_tab self.volume_label.setText('Volume : ' + str(self.setting_dict['sound-volume'])) self.volume_dial.setValue(int(self.setting_dict['sound-volume'])) # set style current_style_index = self.style_comboBox.findText( str(self.setting_dict['style'])) self.style_comboBox.setCurrentIndex(current_style_index) # set language current_locale = self.lang_comboBox.findData( str(self.setting_dict['locale'])) self.lang_comboBox.setCurrentIndex(current_locale) # set color_scheme current_color_index = self.color_comboBox.findText( str(self.setting_dict['color-scheme'])) self.color_comboBox.setCurrentIndex(current_color_index) # set icons current_icons_index = self.icon_comboBox.findText( str(self.setting_dict['icons'])) self.icon_comboBox.setCurrentIndex(current_icons_index) # set icons size current_icons_size_index = self.icons_size_comboBox.findText( str(self.setting_dict['toolbar_icon_size'])) self.icons_size_comboBox.setCurrentIndex(current_icons_size_index) # set notification current_notification_index = self.notification_comboBox.findText( str(self.setting_dict['notification'])) self.notification_comboBox.setCurrentIndex(current_notification_index) # set font self.font_checkBox.setChecked(False) font_setting = QFont() font_setting.setFamily(str(self.setting_dict['font'])) self.fontComboBox.setCurrentFont(font_setting) self.font_size_spinBox.setValue(int(self.setting_dict['font-size'])) # sound frame self.enable_notifications_checkBox.setChecked(True) # start_persepolis_if_browser_executed_checkBox self.start_persepolis_if_browser_executed_checkBox.setChecked(True) # hide window self.hide_window_checkBox.setChecked(True) # tray icon self.enable_system_tray_checkBox.setChecked(True) # after_download_checkBox self.after_download_checkBox.setChecked(True) # hide menubar for linux if platform.system == 'Darwin': self.show_menubar_checkbox.setChecked(True) else: self.show_menubar_checkbox.setChecked(False) # show side panel self.show_sidepanel_checkbox.setChecked(True) # show progress window self.show_progress_window_checkbox.setChecked(True) # run persepolis at startup checkBox self.startup_checkbox.setChecked(False) # keep_awake_checkBox self.keep_awake_checkBox.setChecked(False) # columns_tab self.column0_checkBox.setChecked(True) self.column1_checkBox.setChecked(True) self.column2_checkBox.setChecked(True) self.column3_checkBox.setChecked(True) self.column4_checkBox.setChecked(True) self.column5_checkBox.setChecked(True) self.column6_checkBox.setChecked(True) self.column7_checkBox.setChecked(True) self.column10_checkBox.setChecked(True) self.column11_checkBox.setChecked(True) self.column12_checkBox.setChecked(True) # video finder self.max_links_spinBox.setValue(3) # shortcuts self.shortcuts_list = [ self.setting_dict['shortcuts/quit_shortcut'], self.setting_dict['shortcuts/hide_window_shortcut'], self.setting_dict['shortcuts/remove_shortcut'], self.setting_dict['shortcuts/delete_shortcut'], self.setting_dict['shortcuts/move_up_selection_shortcut'], self.setting_dict['shortcuts/move_down_selection_shortcut'], self.setting_dict['shortcuts/add_new_download_shortcut'], self.setting_dict['shortcuts/video_finder_shortcut'], self.setting_dict['shortcuts/import_text_shortcut'] ] # add shortcuts to the shortcut_table j = 0 for shortcut in self.shortcuts_list: item = QTableWidgetItem(shortcut) # align center item.setTextAlignment(0x0004 | 0x0080) # insert item in shortcut_table self.shortcut_table.setItem(j, 1, item) j = j + 1 self.persepolis_setting.endGroup() def okPushButtonPressed(self, button): self.persepolis_setting.beginGroup('settings') self.persepolis_setting.setValue('max-tries', self.tries_spinBox.value()) self.persepolis_setting.setValue('retry-wait', self.wait_spinBox.value()) self.persepolis_setting.setValue('timeout', self.time_out_spinBox.value()) self.persepolis_setting.setValue('connections', self.connections_spinBox.value()) self.persepolis_setting.setValue('rpc-port', self.rpc_port_spinbox.value()) self.persepolis_setting.setValue('download_path', self.download_folder_lineEdit.text()) self.persepolis_setting.setValue('download_path_temp', self.temp_download_lineEdit.text()) self.persepolis_setting.setValue('sound-volume', self.volume_dial.value()) self.persepolis_setting.setValue( 'notification', self.notification_comboBox.currentText()) self.persepolis_setting.setValue( 'wait-queue', self.wait_queue_time.text().split(':')) # change aria2_path if self.aria2_path_checkBox.isChecked(): self.persepolis_setting.setValue( 'settings/aria2_path', str(self.aria2_path_lineEdit.text())) # changing icons icons = self.icon_comboBox.currentText() self.persepolis_setting.setValue('icons', icons) if icons != self.current_icon: # it means icons changed for windows_list in [ self.parent.logwindow_list, self.parent.about_window_list, self.parent.addlinkwindows_list, self.parent.propertieswindows_list, self.parent.afterdownload_list, self.parent.text_queue_window_list, self.parent.progress_window_list, self.parent.plugin_queue_window_list ]: for window in windows_list: window.changeIcon(icons) self.parent.changeIcon(icons) # icons size icons_size = self.icons_size_comboBox.currentText() self.persepolis_setting.setValue('toolbar_icon_size', icons_size) icons_size = int(icons_size) self.parent.toolBar.setIconSize(QSize(icons_size, icons_size)) self.parent.toolBar2.setIconSize(QSize(icons_size, icons_size)) # style style = str(self.style_comboBox.currentText()) self.persepolis_setting.setValue('style', style) # language locale = str( self.lang_comboBox.itemData(self.lang_comboBox.currentIndex())) self.persepolis_setting.setValue('locale', locale) # color_scheme color_scheme = self.color_comboBox.currentText() self.persepolis_setting.setValue('color-scheme', color_scheme) # font and font size current_font = self.fontComboBox.currentFont() current_font = current_font.key() current_font = current_font.split(',') font = str(current_font[0]) self.persepolis_setting.setValue('font', font) font_size = self.font_size_spinBox.value() self.persepolis_setting.setValue('font-size', font_size) if self.font_checkBox.isChecked(): custom_font = 'yes' else: custom_font = 'no' self.persepolis_setting.setValue('custom-font', custom_font) # if user select qt notification >> enable_system_tray icon if self.persepolis_setting.value('notification') == 'QT notification': self.enable_system_tray_checkBox.setChecked(True) # start_persepolis_if_browser_executed_checkBox if self.start_persepolis_if_browser_executed_checkBox.isChecked(): self.persepolis_setting.setValue('browser-persepolis', 'yes') else: self.persepolis_setting.setValue('browser-persepolis', 'no') # hide_window_checkBox if self.hide_window_checkBox.isChecked(): self.persepolis_setting.setValue('hide-window', 'yes') else: self.persepolis_setting.setValue('hide-window', 'no') # enable_system_tray_checkBox if self.enable_system_tray_checkBox.isChecked(): self.persepolis_setting.setValue('tray-icon', 'yes') self.parent.system_tray_icon.show() self.parent.minimizeAction.setEnabled(True) self.parent.trayAction.setChecked(True) else: self.persepolis_setting.setValue('tray-icon', 'no') self.parent.system_tray_icon.hide() self.parent.minimizeAction.setEnabled(False) self.parent.trayAction.setChecked(False) # after_download_checkBox if self.after_download_checkBox.isChecked(): self.persepolis_setting.setValue('after-dialog', 'yes') else: self.persepolis_setting.setValue('after-dialog', 'no') # show_menubar_checkbox if self.show_menubar_checkbox.isChecked(): self.persepolis_setting.setValue('show-menubar', 'yes') self.parent.menubar.show() self.parent.toolBar2.hide() self.parent.showMenuBarAction.setChecked(True) else: self.persepolis_setting.setValue('show-menubar', 'no') self.parent.menubar.hide() self.parent.toolBar2.show() self.parent.showMenuBarAction.setChecked(False) # show_sidepanel_checkbox if self.show_sidepanel_checkbox.isChecked(): self.persepolis_setting.setValue('show-sidepanel', 'yes') self.parent.category_tree_qwidget.show() else: self.persepolis_setting.setValue('show-sidepanel', 'no') self.parent.category_tree_qwidget.hide() # show_progress_window_checkbox if self.show_progress_window_checkbox.isChecked(): self.persepolis_setting.setValue('show-progress', 'yes') else: self.persepolis_setting.setValue('show-progress', 'no') if self.startup_checkbox.isChecked(): self.persepolis_setting.setValue('startup', 'yes') if not (startup.checkstartup() ): # checking existance of Persepolis in system's startup startup.addstartup() # adding Persepolis to system's startup else: self.persepolis_setting.setValue('startup', 'no') if startup.checkstartup( ): # checking existance of Persepolis in system's startup startup.removestartup( ) # removing Persepolis from system's startup # keep_awake_checkBox if self.keep_awake_checkBox.isChecked(): self.persepolis_setting.setValue('awake', 'yes') self.parent.keep_awake_checkBox.setChecked(True) else: self.persepolis_setting.setValue('awake', 'no') self.parent.keep_awake_checkBox.setChecked(False) # this section creates temporary download folder and download folder and # download sub folders if they did not existed. download_path_temp = self.persepolis_setting.value( 'download_path_temp') download_path = self.persepolis_setting.value('download_path') folder_list = [download_path_temp, download_path] if self.subfolder_checkBox.isChecked(): self.persepolis_setting.setValue('subfolder', 'yes') for folder in [ 'Audios', 'Videos', 'Others', 'Documents', 'Compressed' ]: folder_list.append(os.path.join(download_path, folder)) else: self.persepolis_setting.setValue('subfolder', 'no') for folder in folder_list: osCommands.makeDirs(folder) if self.enable_notifications_checkBox.isChecked(): self.persepolis_setting.setValue('sound', 'yes') else: self.persepolis_setting.setValue('sound', 'no') # columns_tab if self.column0_checkBox.isChecked(): self.persepolis_setting.setValue('column0', 'yes') self.parent.download_table.setColumnHidden(0, False) if self.parent.download_table.isColumnHidden(0): self.parent.download_table.setColumnWidth(0, 100) else: self.persepolis_setting.setValue('column0', 'no') self.parent.download_table.setColumnHidden(0, True) if self.column1_checkBox.isChecked(): self.persepolis_setting.setValue('column1', 'yes') self.parent.download_table.setColumnHidden(1, False) if self.parent.download_table.isColumnHidden(1): self.parent.download_table.setColumnWidth(1, 100) else: self.persepolis_setting.setValue('column1', 'no') self.parent.download_table.setColumnHidden(1, True) if self.column2_checkBox.isChecked(): self.persepolis_setting.setValue('column2', 'yes') self.parent.download_table.setColumnHidden(2, False) if self.parent.download_table.isColumnHidden(2): self.parent.download_table.setColumnWidth(2, 100) else: self.persepolis_setting.setValue('column2', 'no') self.parent.download_table.setColumnHidden(2, True) if self.column3_checkBox.isChecked(): self.persepolis_setting.setValue('column3', 'yes') self.parent.download_table.setColumnHidden(3, False) if self.parent.download_table.isColumnHidden(3): self.parent.download_table.setColumnWidth(3, 100) else: self.persepolis_setting.setValue('column3', 'no') self.parent.download_table.setColumnHidden(3, True) if self.column4_checkBox.isChecked(): self.persepolis_setting.setValue('column4', 'yes') self.parent.download_table.setColumnHidden(4, False) if self.parent.download_table.isColumnHidden(4): self.parent.download_table.setColumnWidth(4, 100) else: self.persepolis_setting.setValue('column4', 'no') self.parent.download_table.setColumnHidden(4, True) if self.column5_checkBox.isChecked(): self.persepolis_setting.setValue('column5', 'yes') self.parent.download_table.setColumnHidden(5, False) if self.parent.download_table.isColumnHidden(5): self.parent.download_table.setColumnWidth(5, 100) else: self.persepolis_setting.setValue('column5', 'no') self.parent.download_table.setColumnHidden(5, True) if self.column6_checkBox.isChecked(): self.persepolis_setting.setValue('column6', 'yes') self.parent.download_table.setColumnHidden(6, False) if self.parent.download_table.isColumnHidden(6): self.parent.download_table.setColumnWidth(6, 100) else: self.persepolis_setting.setValue('column6', 'no') self.parent.download_table.setColumnHidden(6, True) if self.column7_checkBox.isChecked(): self.persepolis_setting.setValue('column7', 'yes') self.parent.download_table.setColumnHidden(7, False) if self.parent.download_table.isColumnHidden(7): self.parent.download_table.setColumnWidth(7, 100) else: self.persepolis_setting.setValue('column7', 'no') self.parent.download_table.setColumnHidden(7, True) if self.column10_checkBox.isChecked(): self.persepolis_setting.setValue('column10', 'yes') self.parent.download_table.setColumnHidden(10, False) if self.parent.download_table.isColumnHidden(10): self.parent.download_table.setColumnWidth(10, 100) else: self.persepolis_setting.setValue('column10', 'no') self.parent.download_table.setColumnHidden(10, True) if self.column11_checkBox.isChecked(): self.persepolis_setting.setValue('column11', 'yes') self.parent.download_table.setColumnHidden(11, False) if self.parent.download_table.isColumnHidden(11): self.parent.download_table.setColumnWidth(11, 100) else: self.persepolis_setting.setValue('column11', 'no') self.parent.download_table.setColumnHidden(11, True) if self.column12_checkBox.isChecked(): self.persepolis_setting.setValue('column12', 'yes') self.parent.download_table.setColumnHidden(12, False) if self.parent.download_table.isColumnHidden(12): self.parent.download_table.setColumnWidth(12, 100) else: self.persepolis_setting.setValue('column12', 'no') self.parent.download_table.setColumnHidden(12, True) # shortcuts # set new shortcuts i = 0 for qshortcut in self.qshortcuts_list: # set keys for QShortcut qshortcut.setKey(self.shortcuts_list[i]) i = i + 1 # video_finder self.persepolis_setting.setValue('video_finder/max_links', self.max_links_spinBox.value()) # saving value of persepolis_setting in second_key_value_dict. self.second_key_value_dict = {} for member in self.persepolis_setting.allKeys(): self.second_key_value_dict[member] = str( self.persepolis_setting.value(member)) # comparing first_key_value_dict with second_key_value_dict show_message_box = False for key in self.first_key_value_dict.keys(): if self.first_key_value_dict[key] != self.second_key_value_dict[ key]: if key in [ 'locale', 'aria2_path', 'download_path_temp', 'download_path', 'custom-font', 'rpc-port', 'max-tries', 'retry-wait', 'timeout', 'connections', 'style', 'font', 'font-size', 'color-scheme' ]: show_message_box = True # if any thing changed that needs restarting, then notify user about "Some changes take effect after restarting persepolis" if show_message_box: restart_messageBox = QMessageBox() restart_messageBox.setText( QCoreApplication.translate( "setting_src_ui_tr", '<b><center>Restart Persepolis Please!</center></b><br><center>Some changes take effect after restarting Persepolis</center>' )) restart_messageBox.setWindowTitle( QCoreApplication.translate("setting_src_ui_tr", 'Restart Persepolis!')) restart_messageBox.exec_() # applying changes self.persepolis_setting.endGroup() self.persepolis_setting.sync() self.close()
class ForestAgroClassification: """QGIS Plugin Implementation.""" no_ortho = True 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', 'ForestAgroClassification_{}.qm'.format(locale)) 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'&Geoscan Forest') # Check if plugin was started the first time in current QGIS session # Must be set in initGui() to survive plugin reloads self.first_start = 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('Geoscan Forest', 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: # Adds plugin icon to Plugins toolbar self.iface.addToolBarIcon(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/forest_agro_plugin/icon.png' self.add_action(icon_path, text=self.tr(u'Geoscan Forest'), callback=self.run, parent=self.iface.mainWindow()) # will be set False in run() self.first_start = True def unload(self): """Removes the plugin menu item and icon from QGIS GUI.""" for action in self.actions: self.iface.removePluginMenu(self.tr(u'&Geoscan Forest'), action) self.iface.removeToolBarIcon(action) def run(self): """Run method that performs all the real work""" # Create the dialog with elements (after translation) and keep reference # Only create GUI ONCE in callback, so that it will only load when the plugin is started if self.first_start == True: self.first_start = False self.dlg = ForestAgroClassificationDialog() self.configure_GUI() #функция, которая полностью настраивает интерфейс # show the dialog self.dlg.show() def start_compute(self): #if we have active task then do nothing, else start task isActive = False try: isActive = globals()['ForestAgroComputeObj'].isActive() except: pass if not isActive: from .forest_agro_compute import ForestAgroCompute # hide progress elements -> show only when task is running self.dlg.PB_start.setEnabled(False) self.dlg.PB_cancel.setHidden(False) globals()['ForestAgroComputeObj'] = ForestAgroCompute( "Geoscan Forest Task") globals()['ForestAgroComputeObj'].progress_changed.connect( self.progress_bar_value_changed) globals()['ForestAgroComputeObj'].on_finished.connect( self.task_finished) globals()['ForestAgroComputeObj'].points_draw.connect( self.points_draw) globals()['ForestAgroComputeObj'].polys_draw.connect( self.polys_draw) globals()['ForestAgroComputeObj'].log_sig.connect(self.update_log) globals()['ForestAgroComputeObj'].dem_required = False globals( )['ForestAgroComputeObj'].winSize = self.dlg.SB_win_size.value() globals( )['ForestAgroComputeObj'].canopy_segmentation_required = self.dlg.CB_segmentation_req.isChecked( ) globals( )['ForestAgroComputeObj'].result_path = self.dlg.LE_result_path.text( ) globals()['ForestAgroComputeObj'].images_path = [ self.dlg.CB_ortho_layer.currentData().dataProvider(). dataSourceUri() ] # form search_area arrays if self.dlg.CB_interest_area.currentIndex() != 0: features = self.dlg.CB_interest_area.currentData().getFeatures( ) interest_area = [] try: for feature in features: poly = [] geom = feature.geometry() x = geom.asPolygon() for i in x[0]: poly.append((i.x(), i.y())) interest_area.append(poly) except: # default select or some error pass globals()['ForestAgroComputeObj'].search_area = interest_area QgsApplication.taskManager().addTask( globals()['ForestAgroComputeObj']) def progress_bar_value_changed(self, value): # change progress bar value self.dlg.PrB_main.setValue(value) def configure_GUI(self): # signals self.dlg.PB_start.clicked.connect(self.start_compute) # start button self.dlg.PB_result_dir.clicked.connect( self.get_result_dir_path ) # button to choose where results must be saved self.dlg.PB_cancel.clicked.connect( self.exit_task) # button to choose where results must be saved # hide params button // need to be implemented self.dlg.PB_seg_configue.setHidden(True) # hide progress elements -> show only when task is running try: globals()['ForestAgroComputeObj'].isActive() except: self.dlg.PB_cancel.setHidden(True) # set True for no_ortho (if we have valid ortho, we set False later) self.no_ortho = True # clear all combobox when open main window self.dlg.CB_ortho_layer.clear() self.dlg.CB_interest_area.clear() # default item if there are no valid vector polygons self.dlg.CB_interest_area.addItem("Whole orthophoto") # filling comboboxes with items from qgis gui layers = self.iface.mapCanvas().layers() for i in layers: # if type == raster -> add this layer to orthophotos list if (i.type() == 1): self.dlg.CB_ortho_layer.addItem(i.name(), userData=i) self.no_ortho = False # if type == vector and geometryType == polygon -> add this layer to interest area list if i.type() == 0: if i.geometryType() == 2: if "Canopy" not in i.name(): self.dlg.CB_interest_area.addItem(i.name(), userData=i) # if there are no valid rasters -> add default if self.dlg.CB_ortho_layer.count() == 0: self.dlg.CB_ortho_layer.addItem("No matching rasters found.") self.update_control() def update_control(self): # This feature will enable and disable the ability to interact with system elements. # For example, if there are no orthophoto available, then the start button must be turned off. PB_should_be_Enabled = \ (not self.no_ortho) and \ (not self.dlg.LE_result_path.text() == "") self.dlg.PB_start.setEnabled(PB_should_be_Enabled) def get_result_dir_path(self): #open dialog in user home dir; choose only directory to save results dir = QFileDialog.getExistingDirectory(None, "Open Directory", "", QFileDialog.ShowDirsOnly) self.dlg.LE_result_path.setText(dir) self.update_control() # /////////////////////////////////////////////////// def task_finished(self): self.update_control() self.dlg.PrB_main.setValue(0) self.dlg.TE_log.append("Job aborted!") self.dlg.PB_cancel.setHidden(True) self.dlg.PB_cancel.setText("Cancel") self.dlg.PB_cancel.setEnabled(True) def update_log(self, log_str): self.dlg.TE_log.append(log_str) def exit_task(self): self.dlg.PB_cancel.setText("Wait...") self.dlg.PB_cancel.setEnabled(False) QgsApplication.taskManager().activeTasks()[0].cancel() def polys_draw(self, path): print(path) self.iface.addVectorLayer(path, "Canopy_", "ogr") def points_draw(self, path): print(path) self.iface.addVectorLayer(path, "Trees_", "ogr")
def loadQtTranslation(self, file, language = "default"): #TODO Add support for specifying a language from preferences path = None if language == "default": path = self._getDefaultLanguage(file) else: path = Resources.getPath(Resources.i18n, language, "LC_MESSAGES", file + ".qm") # If all else fails, fall back to english. if not path: Logger.log("w", "Could not find any translations matching {0} for file {1}, falling back to english".format(language, file)) try: path = Resources.getPath(Resources.i18n, "en", "LC_MESSAGES", file + ".qm") except FileNotFoundError: Logger.log("w", "Could not find English translations for file {0}. Switching to developer english.".format(file)) return translator = QTranslator() if not translator.load(path): Logger.log("e", "Unable to load translations %s", file) return # Store a reference to the translator. # This prevents the translator from being destroyed before Qt has a chance to use it. self._translators[file] = translator # Finally, install the translator so Qt can use it. self.installTranslator(translator)
def __init__(self, argv, qapp): ''' Create a new "cutecoin" application :param argv: The argv parameters of the call ''' super().__init__() self.accounts = {} self.current_account = None self.monitor = None self.available_version = (True, __version__, "") config.parse_arguments(argv) self._network_manager = QNetworkAccessManager() self._network_manager.finished.connect(self.read_available_version) self.preferences = {'account': "", 'lang': 'en_GB', 'ref': 0 } self.load() translator = QTranslator(qapp) logging.debug("Loading translations") locale = self.preferences['lang'] QLocale.setDefault(QLocale(locale)) if translator.load(":/i18n/{0}".format(locale)): if QCoreApplication.installTranslator(translator): logging.debug("Loaded i18n/{0}".format(locale)) else: logging.debug("Couldn't load translation")