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_()
Esempio n. 2
0
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_()
Esempio n. 3
0
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
Esempio n. 4
0
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():
  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_())
Esempio n. 6
0
	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 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_()
Esempio n. 8
0
    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)
Esempio n. 9
0
 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")
Esempio n. 10
0
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_())
Esempio n. 11
0
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)
Esempio n. 12
0
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())
Esempio n. 13
0
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()
Esempio n. 14
0
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 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)
Esempio n. 16
0
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_())
Esempio n. 17
0
def main():
    """Main app function."""
    import sys
    from os.path import dirname, realpath, exists
    app = QApplication(sys.argv)
    filePath = dirname(realpath(__file__))
    locale = QLocale.system().name()
    if locale == 'es_CU':
        locale = 'es_ES'
    # locale = 'es_ES'
    appTranslator = QTranslator()
    if exists(filePath + '/translations/'):
        appTranslator.load(filePath + "/translations/videomorph_" + locale)
    else:
        appTranslator.load(
            "/usr/share/videomorph/translations/videomorph_" + locale)
    app.installTranslator(appTranslator)
    qtTranslator = QTranslator()
    qtTranslator.load("qt_" + locale,
                      QLibraryInfo.location(QLibraryInfo.TranslationsPath))
    app.installTranslator(qtTranslator)
    mainWin = MMWindow()
    if mainWin.check_conversion_lib():
        mainWin.show()
        sys.exit(app.exec_())
Esempio n. 18
0
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_()
Esempio n. 19
0
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_()
Esempio n. 20
0
 def setup_translation(self):
     self.tr("Test translator")
     sys_locale = QLocale.system()
     lang_code = QLocale.languageToString(sys_locale.language())
     logger.info('System language: {0}, {1}'.format(lang_code, sys_locale.bcp47Name()))
     translator = QTranslator(self)
     # bool load(locale, filename, prefix = '', directory = '', suffix = '')
     res = translator.load(sys_locale, 'xnovacmd', '_', './translations')
     # Loads filename + prefix + ui language name + suffix (".qm" if the suffix is not specified),
     # which may be an absolute file name or relative to directory.
     # Returns true if the translation is successfully loaded; otherwise returns false.
     if res:
         logger.info('Loaded translation OK')
         self.installTranslator(translator)
     else:
         logger.warn('Failed to load translator!')
Esempio n. 21
0
    def __init__(self, iface):
        """Plugin Initialization

           :param iface: Interface QGis
        """

        # Save reference to the QGIS interface
        self.iface = iface
        self.toolBar = None
        self.act_hotlink = None
        self.__mapTool = None
        self.__oldMapTool = None
        self.canvas = self.iface.mapCanvas()
        self.active = False
        self.optionShowTips = False
        self.read()

        locale = QSettings().value("locale/userLocale")
        myLocale = locale[0:2]

        localePath = QFileInfo(os.path.realpath(__file__)).path()+"/i18n/Hotlink_" + \
            myLocale + ".qm"

        if QFileInfo(localePath).exists():
            self.translator = QTranslator()
            self.translator.load(localePath)
            QCoreApplication.installTranslator(self.translator)
    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',
            'EncodedPolylineExporter_{}.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 = EncodedPolylineExporterDialog(iface)

        # Declare instance attributes
        self.actions = []
        self.menu = self.tr(u'&Encoded Polyline Exporter')
        # TODO: We are going to let the user set this up in a future iteration
        self.toolbar = self.iface.addToolBar(u'EncodedPolylineExporter')
        self.toolbar.setObjectName(u'EncodedPolylineExporter')
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()
Esempio n. 24
0
File: app.py Progetto: c-geek/sakia
    def __init__(self, qapp, loop, identities_registry):
        """
        Init a new "sakia" application
        :param QCoreApplication qapp: Qt Application
        :param quamash.QEventLoop loop: quamash.QEventLoop instance
        :param sakia.core.registry.IdentitiesRegistry identities_registry: IdentitiesRegistry instance
        :return:
        """

        super().__init__()
        self.qapp = qapp
        self.accounts = {}
        self._current_account = None
        self.loop = loop
        self.available_version = (True,
                                  __version__,
                                  "")
        self._translator = QTranslator(self.qapp)
        self._identities_registry = identities_registry
        self.preferences = {'account': "",
                            'lang': 'en_GB',
                            'ref': 0,
                            'expert_mode': False,
                            'digits_after_comma': 6,
                            'maximized': False,
                            'notifications': True,
                            'enable_proxy': False,
                            'proxy_type': "HTTP",
                            'proxy_address': "",
                            'proxy_port': 8080,
                            'international_system_of_units': True,
                            'auto_refresh': False,
                            'forgetfulness':False
                            }
Esempio n. 25
0
    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',
            'flowTrace_{}.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'&Flow Trace')

        # 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
Esempio n. 26
0
    def __init__(self, parent, dict, persepolis_setting):
        super().__init__(persepolis_setting)
        self.persepolis_setting = persepolis_setting
        self.dict = dict
        self.parent = parent

        # 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)

        # connecting buttons
        self.open_pushButtun.clicked.connect(self.openFile)
        self.open_folder_pushButtun.clicked.connect(self.openFolder)
        self.ok_pushButton.clicked.connect(self.okButtonPressed)

        # labels
        # find gid
        gid = self.dict['gid']

        # get file_path from data base
        self.add_link_dict = self.parent.persepolis_db.searchGidInAddLinkTable(gid)
        file_path = self.add_link_dict['download_path']

        # save_as
        self.save_as_lineEdit.setText(file_path)
        self.save_as_lineEdit.setToolTip(file_path)

        # link
        link = str(self.dict['link'])
        self.link_lineEdit.setText(link)
        self.link_lineEdit.setToolTip(link)

        # file_name

        window_title = str(self.dict['file_name'])
        file_name = QCoreApplication.translate("after_download_src_ui_tr", "<b>File name</b>: ") + \
                window_title
 
        self.setWindowTitle(window_title)

        self.file_name_label.setText(file_name)

        # size
        size = QCoreApplication.translate("after_download_src_ui_tr", "<b>Size</b>: ") + str(self.dict['size'])
        self.size_label.setText(size)

        # disable link_lineEdit and save_as_lineEdit
        self.link_lineEdit.setEnabled(False)
        self.save_as_lineEdit.setEnabled(False)

         # set window size and position
        size = self.persepolis_setting.value(
            'AfterDownloadWindow/size', QSize(570, 290))
        position = self.persepolis_setting.value(
            'AfterDownloadWindow/position', QPoint(300, 300))
        self.resize(size)
        self.move(position)
Esempio n. 27
0
def run():
    app = QApplication(sys.argv)
    app.setOrganizationName("manuskript")
    app.setOrganizationDomain("www.theologeek.ch")
    app.setApplicationName("manuskript")
    app.setApplicationVersion(_version)

    icon = QIcon()
    for i in [16, 31, 64, 128, 256, 512]:
        icon.addFile(appPath("icons/Manuskript/icon-{}px.png".format(i)))
    qApp.setWindowIcon(icon)

    app.setStyle("Fusion")

    # Load style from QSettings
    settings = QSettings(app.organizationName(), app.applicationName())
    if settings.contains("applicationStyle"):
        style = settings.value("applicationStyle")
        app.setStyle(style)

    # Translation process
    locale = QLocale.system().name()

    appTranslator = QTranslator()
    # By default: locale
    translation = appPath(os.path.join("i18n", "manuskript_{}.qm".format(locale)))

    # Load translation from settings
    if settings.contains("applicationTranslation"):
        translation = appPath(os.path.join("i18n", settings.value("applicationTranslation")))
        print("Found translation in settings:", translation)

    if appTranslator.load(translation):
        app.installTranslator(appTranslator)
        print(app.tr("Loaded translation: {}.").format(translation))

    else:
        print(app.tr("Warning: failed to load translator for locale {}...").format(locale))

    QIcon.setThemeSearchPaths(QIcon.themeSearchPaths() + [appPath("icons")])
    QIcon.setThemeName("NumixMsk")
    # qApp.setWindowIcon(QIcon.fromTheme("im-aim"))

    # Seperating launch to avoid segfault, so it seem.
    # Cf. http://stackoverflow.com/questions/12433491/is-this-pyqt-4-python-bug-or-wrongly-behaving-code
    launch()
Esempio n. 28
0
 def loadTransFile(self, transFileName):
     """
     Public slot to load a translation file.
     
     @param transFileName file name of the translation file (string)
     @return reference to the new translator object (QTranslator)
     """
     tr = QTranslator()
     if tr.load(transFileName):
         return tr
     
     E5MessageBox.warning(
         self.parent(),
         self.tr("Load Translator"),
         self.tr("""<p>The translation file <b>{0}</b> could"""
                 """ not be loaded.</p>""").format(transFileName))
     return None
Esempio n. 29
0
class PLANHEAT:
    """QGIS Plugin Implementation."""
    def __init__(self, iface, master_dlg):
        """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',
                                   'PLANHEAT_{}.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.pluginIsActive = False
        self.dockwidget = None

        self.master_dlg = master_dlg

    # 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('PLANHEAT', message)

    def onClosePlugin(self, tree, base_path):
        """Cleanup necessary items here when plugin dockwidget is closed"""

        self.check_temp_is_saved(tree, base_path)

        clear_all_caches()
        temp_folder = get_temp_folder()
        if temp_folder:
            temp_folder = None
        print("closed")
        # disconnects
        #self.dockwidget.closingPlugin.disconnect(lambda: self.onClosePlugin(tree, base_path))
        self.dockwidget.treeWidget.itemDoubleClicked.disconnect(
            node_preferences_action)
        self.dockwidget.runButton.clicked.disconnect()
        self.dockwidget.loadButton.clicked.disconnect()
        self.dockwidget.saveButton.clicked.disconnect()
        self.dockwidget.resultButton.clicked.disconnect()
        self.dockwidget.treeWidget.clear()
        self.dockwidget.titleLabel.setText("")
        # remove this statement if dockwidget is to remain
        # for reuse if plugin is reopened
        # Commented next statement since it causes QGIS crashe
        # when closing the docked window:
        # self.dockwidget = None

        self.pluginIsActive = False

        # serialize the cache
        APICacheSerializer.serialize()

        # Reopen master dialog
        self.master_dlg.show()
        self.master_dlg.closeMapping.emit()
        #self.master_dlg.startButton.setEnabled(True)
        #self.master_dlg.returnButton.setEnabled(True)

    def run(self, type, base_path):
        """Run method that loads and starts the plugin"""
        # deserialize the cache
        APICacheSerializer.deserialize()

        if ProjectTypeEnum.DEMAND_CURRENT == type:
            openCMMB = self.start_planning_module()

            if not openCMMB:
                self.master_dlg.show()
                self.master_dlg.closeMapping.emit()
                return None

        if not self.pluginIsActive:
            self.pluginIsActive = True

            # dockwidget may not exist if:
            #    first run of plugin
            #    removed on close (see self.onClosePlugin method)
            if self.dockwidget == None:
                # Create the dockwidget (after translation) and keep reference
                self.dockwidget = PLANHEATDockWidget()
                self.dockwidget.sizePolicy().setRetainSizeWhenHidden(True)

            # empty tree
            tree = self.dockwidget.treeWidget
            tree.setExpandsOnDoubleClick(False)
            tree.itemDoubleClicked.connect(node_preferences_action)
            tree.setContextMenuPolicy(Qt.CustomContextMenu)
            tree.customContextMenuRequested.connect(
                lambda: open_right_click_menu(tree))
            if ProjectTypeEnum.SUPPLY == type:
                self.dockwidget.setWindowTitle("PLANHEAT SUPPLY")
            elif ProjectTypeEnum.DEMAND_CURRENT == type:
                self.dockwidget.setWindowTitle("PLANHEAT CURRENT DEMAND")
            elif ProjectTypeEnum.DEMAND_FUTURE == type:
                self.dockwidget.setWindowTitle("PLANHEAT FUTURE DEMAND")
            # connect to provide cleanup on closing of dockwidget
            self.dockwidget.closingPlugin.connect(
                lambda: self.onClosePlugin(tree, base_path))

            # show the dockwidget
            if ProjectTypeEnum.DEMAND_CURRENT != type or openCMMB:
                self.iface.addDockWidget(Qt.RightDockWidgetArea,
                                         self.dockwidget)
                self.dockwidget.show()

            self.dockwidget.runButton.clicked.connect(
                lambda: run_all_nodes(tree, type.value, only_checked=True))
            self.dockwidget.loadButton.clicked.connect(
                lambda: load_tree_dialog(self.dockwidget, type, base_path))
            self.dockwidget.saveButton.clicked.connect(
                lambda: self.save_db_and_outputs(tree, base_path))
            self.dockwidget.resultButton.clicked.connect(
                lambda: show_result_dialog(type.value))
            if ProjectTypeEnum.DEMAND_CURRENT != type or openCMMB:
                load_tree_dialog(self.dockwidget, type, base_path)
        return self.dockwidget

    def start_planning_module(self):
        planning_run = planning_module.PlanheatMappingPlugin(self.iface)
        planning_dialog = planning_run.run()
        return planning_run.openCMMB

    def save_db_and_outputs(self, tree, base_path):
        print("Saving db and outputs")

        save_tree(tree)

        # uncommit if we want to clean results
        non_temp_folder = os.path.join(base_path, '..')
        #for f in os.listdir(non_temp_folder):
        #    if f != "temp" and os.path.isdir(os.path.join(non_temp_folder, f)):
        #        shutil.rmtree(os.path.join(non_temp_folder, f))
        #    elif os.path.isfile(os.path.join(non_temp_folder, f)):
        #        os.remove(os.path.join(non_temp_folder, f))

        # copyt data from temp
        for file in os.listdir(base_path):
            if os.path.isfile(os.path.join(base_path, file)):
                shutil.copy2(os.path.join(base_path, file),
                             os.path.join(non_temp_folder, file))

        # clean temp folder
        for f in os.listdir(base_path):
            if os.path.isfile(os.path.join(base_path, f)):
                try:
                    os.remove(os.path.join(base_path, f))
                except:
                    "Can't delete {0}".format(os.path.join(base_path, f))
        # Saving cache as well
        APICacheSerializer.serialize()

    def check_temp_is_saved(self, tree, base_path):
        unsaved_file = False
        if os.path.exists(base_path):
            for f in os.listdir(base_path):
                tmp_time = os.path.getmtime(os.path.join(base_path, f))
                if os.path.exists(os.path.join(base_path, '..', f)):
                    saved_time = os.path.getmtime(
                        os.path.join(base_path, '..', f))
                    if saved_time < tmp_time:
                        unsaved_file = True
                        break
                elif f != "temp" and not ".aux" in f:
                    unsaved_file = True
                    break
        if unsaved_file:
            msg = QMessageBox(self.dockwidget)
            msg.setIcon(QMessageBox.Question)
            msg.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
            msg.setWindowTitle("Save calculations")
            msg.setText(
                "Some calculations are unsaved. Would you like to save them")
            retval = msg.exec_()
            if retval == QMessageBox.Yes:
                self.save_db_and_outputs(tree, base_path)
Esempio n. 30
0
    def __init__(self, resources, sys_argv):
        """
        Init main window.
        """

        super().__init__()
        self.setupUi(self)

        # load args.
        self._args = Args(resources)

        # load translations.
        self._func_tr_()

        # init qt args.
        app_icon = QIcon()
        app_icon.addPixmap(QPixmap(":/images/images/icon_128.png"),
                           QIcon.Normal, QIcon.Off)
        self.setWindowIcon(app_icon)
        self.setMinimumSize(640, 480)

        self._setup_workarea()
        self._setup_result()
        self._setup_rule()
        self._setup_mode()
        self._setup_operation()
        self._setup_script()
        self._setup_channel()
        self._setup_transformation()
        self._setup_settings()

        self.tabifyDockWidget(self.script_dock_widget,
                              self.operation_dock_widget)
        self.tabifyDockWidget(self.transformation_dock_widget,
                              self.mode_dock_widget)
        self.tabifyDockWidget(self.channel_dock_widget, self.rule_dock_widget)

        self.actionOpen.triggered.connect(self._wget_operation.open_btn.click)
        self.actionSave.triggered.connect(self._wget_operation.save_btn.click)
        self.actionImport.triggered.connect(
            self._wget_operation.import_btn.click)
        self.actionExport.triggered.connect(
            self._wget_operation.export_btn.click)
        self.actionQuit.triggered.connect(self.close)

        self.actionCreate.triggered.connect(
            self._wget_operation.create_btn.click)
        self.actionLocate.triggered.connect(
            self._wget_operation.locate_btn.click)
        self.actionAttach.triggered.connect(
            self._wget_operation.attach_btn.click)
        self.actionSettings.triggered.connect(self._wget_settings.showup)

        self.actionWheel.triggered.connect(lambda x: self._inner_create(False)
                                           (False))
        self.actionImage.triggered.connect(lambda x: self._inner_locate(False)
                                           (False))
        self.actionDepot.triggered.connect(lambda x: self._inner_attach(False)
                                           (False))

        self.actionRule.triggered.connect(
            self._inner_show_or_hide(self.rule_dock_widget))
        self.actionChannel.triggered.connect(
            self._inner_show_or_hide(self.channel_dock_widget))
        self.actionOperation.triggered.connect(
            self._inner_show_or_hide(self.operation_dock_widget))
        self.actionScript.triggered.connect(
            self._inner_show_or_hide(self.script_dock_widget))
        self.actionMode.triggered.connect(
            self._inner_show_or_hide(self.mode_dock_widget))
        self.actionTransformation.triggered.connect(
            self._inner_show_or_hide(self.transformation_dock_widget))
        self.actionResult.triggered.connect(
            self._inner_show_or_hide(self.result_dock_widget))
        self.actionAll.triggered.connect(self._inner_all_show_or_hide)

        self.actionHomepage.triggered.connect(
            lambda x: QDesktopServices.openUrl(QUrl(self._args.info_main_site)
                                               ))
        self.actionUpdate.triggered.connect(lambda x: QDesktopServices.openUrl(
            QUrl(self._args.info_update_site)))
        self.actionAbout.triggered.connect(lambda x: self._show_about())

        self.rule_dock_widget.visibilityChanged.connect(
            lambda x: self.actionRule.setChecked(self.rule_dock_widget.
                                                 isVisible()))
        self.channel_dock_widget.visibilityChanged.connect(
            lambda x: self.actionChannel.setChecked(self.channel_dock_widget.
                                                    isVisible()))
        self.operation_dock_widget.visibilityChanged.connect(
            lambda x: self.actionOperation.setChecked(
                self.operation_dock_widget.isVisible()))
        self.script_dock_widget.visibilityChanged.connect(
            lambda x: self.actionScript.setChecked(self.script_dock_widget.
                                                   isVisible()))
        self.mode_dock_widget.visibilityChanged.connect(
            lambda x: self.actionMode.setChecked(self.mode_dock_widget.
                                                 isVisible()))
        self.transformation_dock_widget.visibilityChanged.connect(
            lambda x: self.actionTransformation.setChecked(
                self.transformation_dock_widget.isVisible()))
        self.result_dock_widget.visibilityChanged.connect(
            lambda x: self.actionResult.setChecked(self.result_dock_widget.
                                                   isVisible()))

        shortcut = QShortcut(QKeySequence("Alt+H"), self)
        shortcut.activated.connect(self.actionHomepage.trigger)
        shortcut = QShortcut(QKeySequence("F1"), self)
        shortcut.activated.connect(self.actionHomepage.trigger)

        shortcut = QShortcut(QKeySequence("Alt+U"), self)
        shortcut.activated.connect(self.actionUpdate.trigger)
        shortcut = QShortcut(QKeySequence("F2"), self)
        shortcut.activated.connect(self.actionUpdate.trigger)

        shortcut = QShortcut(QKeySequence("Alt+B"), self)
        shortcut.activated.connect(self.actionAbout.trigger)
        shortcut = QShortcut(QKeySequence("F3"), self)
        shortcut.activated.connect(self.actionAbout.trigger)

        shortcut = QShortcut(QKeySequence("Alt+O"), self)
        shortcut.activated.connect(self._wget_operation.open_btn.click)
        shortcut = QShortcut(QKeySequence("Ctrl+O"), self)
        shortcut.activated.connect(self._wget_operation.open_btn.click)

        shortcut = QShortcut(QKeySequence("Alt+S"), self)
        shortcut.activated.connect(self._wget_operation.save_btn.click)
        shortcut = QShortcut(QKeySequence("Ctrl+S"), self)
        shortcut.activated.connect(self._wget_operation.save_btn.click)

        shortcut = QShortcut(QKeySequence("Alt+I"), self)
        shortcut.activated.connect(self._wget_operation.import_btn.click)
        shortcut = QShortcut(QKeySequence("Ctrl+I"), self)
        shortcut.activated.connect(self._wget_operation.import_btn.click)

        shortcut = QShortcut(QKeySequence("Alt+E"), self)
        shortcut.activated.connect(self._wget_operation.export_btn.click)
        shortcut = QShortcut(QKeySequence("Ctrl+E"), self)
        shortcut.activated.connect(self._wget_operation.export_btn.click)

        shortcut = QShortcut(QKeySequence("Alt+Q"), self)
        shortcut.activated.connect(self.close)
        shortcut = QShortcut(QKeySequence("Esc"), self)
        shortcut.activated.connect(self.close)

        shortcut = QShortcut(QKeySequence("Alt+T"), self)
        shortcut.activated.connect(self._wget_settings.showup)
        shortcut = QShortcut(QKeySequence("`"), self)
        shortcut.activated.connect(self._wget_settings.showup)

        shortcut = QShortcut(QKeySequence("Alt+C"), self)
        shortcut.activated.connect(self._wget_operation.create_btn.click)
        shortcut = QShortcut(QKeySequence("Ctrl+W"), self)
        shortcut.activated.connect(self._wget_operation.create_btn.click)

        shortcut = QShortcut(QKeySequence("Alt+L"), self)
        shortcut.activated.connect(self._wget_operation.locate_btn.click)
        shortcut = QShortcut(QKeySequence("Ctrl+G"), self)
        shortcut.activated.connect(self._wget_operation.locate_btn.click)

        shortcut = QShortcut(QKeySequence("Alt+A"), self)
        shortcut.activated.connect(self._wget_operation.attach_btn.click)
        shortcut = QShortcut(QKeySequence("Ctrl+D"), self)
        shortcut.activated.connect(self._wget_operation.attach_btn.click)

        # install translator.
        self._tr = QTranslator()
        self._app = QApplication.instance()
        self._install_translator()

        # focus on wheel.
        self._wget_wheel.setFocus()

        if len(sys_argv) > 1:
            try:
                if sys_argv[1].split(".")[-1].lower() in ("png", "bmp", "jpg",
                                                          "jpeg", "tif",
                                                          "tiff"):
                    self._inner_locate(False)(False)
                    self._wget_image.open_image(sys_argv[1])

                else:
                    with open(sys_argv[1], "r", encoding='utf-8') as f:
                        color_dict = json.load(f)

                        if isinstance(color_dict,
                                      dict) and "type" in color_dict:
                            if color_dict["type"] == "depot":
                                self._inner_attach(False)(False)
                                self._wget_operation.dp_open(sys_argv[1])

                            elif color_dict["type"] == "set":
                                self._wget_operation.dp_import(sys_argv[1])

            except Exception as err:
                pass

        # install stylesheet.
        """
Esempio n. 31
0
    def __init__(self, persepolis_setting):
        super().__init__()

        self.persepolis_setting = persepolis_setting

        # 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)

        # set ui direction
        ui_direction = self.persepolis_setting.value('ui_direction')

        if ui_direction == 'rtl':
            self.setLayoutDirection(Qt.RightToLeft)

        elif ui_direction in 'ltr':
            self.setLayoutDirection(Qt.LeftToRight)

        icons = ':/' + str(
            self.persepolis_setting.value('settings/icons')) + '/'

        self.setWindowIcon(
            QIcon.fromTheme('persepolis', QIcon(':/persepolis.svg')))
        self.setWindowTitle(
            QCoreApplication.translate("after_download_ui_tr",
                                       "Persepolis Download Manager"))
        #complete_label
        self.verticalLayout_1 = QVBoxLayout()
        self.verticalLayout_1.setContentsMargins(21, 21, 21, 21)

        self.complete_label = QLabel()
        self.verticalLayout_1.addWidget(self.complete_label)
        # file_name_label
        self.file_name_label = QLabel()
        self.verticalLayout_1.addWidget(self.file_name_label)
        # size_label
        self.size_label = QLabel()
        self.verticalLayout_1.addWidget(self.size_label)

        # link
        self.link_label = QLabel()
        self.verticalLayout_1.addWidget(self.link_label)

        self.link_lineEdit = QLineEdit()
        self.verticalLayout_1.addWidget(self.link_lineEdit)
        # save_as
        self.save_as_label = QLabel()
        self.verticalLayout_1.addWidget(self.save_as_label)
        self.save_as_lineEdit = QLineEdit()
        self.verticalLayout_1.addWidget(self.save_as_lineEdit)
        # open_pushButtun
        button_horizontalLayout = QHBoxLayout()
        button_horizontalLayout.setContentsMargins(10, 10, 10, 10)

        button_horizontalLayout.addStretch(1)
        self.open_pushButtun = QPushButton()
        self.open_pushButtun.setIcon(QIcon(icons + 'file'))
        button_horizontalLayout.addWidget(self.open_pushButtun)

        # open_folder_pushButtun
        self.open_folder_pushButtun = QPushButton()
        self.open_folder_pushButtun.setIcon(QIcon(icons + 'folder'))
        button_horizontalLayout.addWidget(self.open_folder_pushButtun)

        # ok_pushButton
        self.ok_pushButton = QPushButton()
        self.ok_pushButton.setIcon(QIcon(icons + 'ok'))
        button_horizontalLayout.addWidget(self.ok_pushButton)

        self.verticalLayout_1.addLayout(button_horizontalLayout)
        # dont_show_checkBox
        self.dont_show_checkBox = QCheckBox()
        self.verticalLayout_1.addWidget(self.dont_show_checkBox)

        self.setLayout(self.verticalLayout_1)

        # labels
        self.open_pushButtun.setText(
            QCoreApplication.translate("after_download_ui_tr",
                                       "  Open File  "))
        self.open_folder_pushButtun.setText(
            QCoreApplication.translate("after_download_ui_tr",
                                       "Open Download Folder"))
        self.ok_pushButton.setText(
            QCoreApplication.translate("after_download_ui_tr", "   OK   "))
        self.dont_show_checkBox.setText(
            QCoreApplication.translate("after_download_ui_tr",
                                       "Don't show this message again."))
        self.complete_label.setText(
            QCoreApplication.translate("after_download_ui_tr",
                                       "<b>Download Completed!</b>"))
        self.save_as_label.setText(
            QCoreApplication.translate("after_download_ui_tr",
                                       "<b>Save as</b> : "))
        self.link_label.setText(
            QCoreApplication.translate("after_download_ui_tr",
                                       "<b>Link</b> : "))
Esempio n. 32
0

if __name__ == '__main__':
    #add RaySession/src/bin to $PATH
    ray.addSelfBinToPath()

    #create app
    app = QCoreApplication(sys.argv)
    app.setApplicationName("RaySession")
    app.setOrganizationName("RaySession")

    initDaemonTools()

    ### Translation process
    locale = QLocale.system().name()
    appTranslator = QTranslator()

    if appTranslator.load("%s/locale/raysession_%s" % (getCodeRoot(), locale)):
        app.installTranslator(appTranslator)

    _translate = app.translate

    #check arguments
    parser = ArgParser()

    #manage session_root
    session_root = CommandLineArgs.session_root
    if not session_root:
        session_root = "%s/%s" % (os.getenv('HOME'),
                                  _translate('daemon', 'Ray Network Sessions'))
class GeoportailLU:
    """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',
                                   'GeoportailLU_{}.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 = GeoportailLUDialog()

        # Declare instance attributes
        self.actions = []
        self.menu = self.tr(u'&Geoportal LU')
        # TODO: We are going to let the user set this up in a future iteration
        self.toolbar = self.iface.addToolBar(self.tr(u'Geoportal LU'))
        self.toolbar.setObjectName(self.tr(u'Geoportal LU'))

        # shortcuts
        self.project = QgsProject.instance()
        self.root = self.project.layerTreeRoot()
        self.crs = self.project.crs().authid()

    # 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('GeoportailLU', 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.addPluginToWebMenu(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/geoportail_lu/icon.png'
        self.add_action(icon_path,
                        text=self.tr(u'Geoportal LU'),
                        status_tip=self.tr(u'Geoportal LU'),
                        callback=self.run,
                        parent=self.iface.mainWindow())

        self.dlg.searchButton.clicked.connect(self.update_search)
        self.dlg.addButton.clicked.connect(self.add_result)

    def unload(self):
        """Removes the plugin menu item and icon from QGIS GUI."""
        for action in self.actions:
            self.iface.removePluginWebMenu(self.tr(u'&Geoportal LU'), action)
            self.iface.removeToolBarIcon(action)
        # remove the toolbar
        del self.toolbar

    def run(self):
        """Run method that performs all the real work"""
        # get the current CRS from the project in case it changed since
        # project load
        self.crs = self.project.crs().authid()
        # show the dialog
        self.dlg.show()
        # Run the dialog event loop
        result = self.dlg.exec_()

    def update_search(self):
        """Update the search field with results from input and geoportal
        results"""
        dlg = self.dlg.searchField
        # stopp signal from emitting events while loading results
        dlg.blockSignals(True)

        if len(dlg.currentText()) > 1:
            search_text = dlg.currentText()
            # remove possible entries
            dlg.clear()
            dlg.addItem(search_text)
            # results is a GeoJSON FeatureCollection
            # update combobox with new values
            results = search(dlg.currentText(), 9)
            for result in results['features']:
                dlg.addItem(result['properties']['label'], result)
            dlg.showPopup()

        dlg.blockSignals(False)
        return

    def add_result(self):
        """Get the selected search result from the search field and add it as
        a layer to the map"""
        dlg = self.dlg.searchField

        if dlg.currentIndex() > 0:
            result = dlg.currentData()
            geometry_type = result['geometry']['type']
            properties = result['properties']

            project_crs = int(self.crs.replace('EPSG:', ''))

            # create the geometry from json and reproject eventually
            ogr_geom = ogr.CreateGeometryFromJson(
                json.dumps(result['geometry']))

            # QgsMessageLog.logMessage(
            #     'Reprojection test start',
            #     'Geoportail LU',
            #     Qgis.Info
            # )
            # reproject to project's CRS if necessary
            if project_crs != 4326:
                source_srs = osr.SpatialReference()
                source_srs.ImportFromEPSG(4326)

                target_srs = osr.SpatialReference()
                target_srs.ImportFromEPSG(project_crs)

                # starting from GDAL version 3.0 onwards the CRS axis
                # order is respected.
                # switching to the traditional GIS order puts coordinates back
                # where QGIS expects them -> XY and not YX how most CRS are
                # defined
                # fixes https://github.com/frankbroniewski/geoportaillu/issues/5
                if VersionInfo().startswith('3'):
                    source_srs.SetAxisMappingStrategy(
                        OAMS_TRADITIONAL_GIS_ORDER)
                    target_srs.SetAxisMappingStrategy(
                        OAMS_TRADITIONAL_GIS_ORDER)

                transformation = osr.CoordinateTransformation(
                    source_srs, target_srs)
                ogr_geom.Transform(transformation)

            # create the QGIS Geometry and create fields
            geometry = QgsGeometry.fromWkt(ogr_geom.ExportToWkt())
            # layer string
            fields = '&'.join([
                'field={}:string(200)'.format(k)
                for k, v in properties.items()
            ])
            create_opts = '{}?crs=epsg:{}&{}'.format(geometry_type,
                                                     project_crs, fields)
            result_layer = QgsVectorLayer(create_opts, properties['label'],
                                          'memory')
            fields = result_layer.fields()
            # add feature if layer is valid
            if result_layer.isValid():
                data_provider = result_layer.dataProvider()
                feature = QgsFeature()
                feature.setGeometry(geometry)
                feature.setFields(fields)
                for k, v in properties.items():
                    # feature.setAttribute(k, v)
                    feature[k] = v
                data_provider.addFeatures([feature])
                result_layer.updateExtents()
                # add result to map layer tree
                self.project.addMapLayer(result_layer, False)
                # add a group for storing selected search results as memory
                # layer
                group = self._get_group(self.tr(u'Search Results'))
                group.addLayer(result_layer)
                # zoom to feature & update map
                extent = geometry.boundingBox()
                self.iface.mapCanvas().zoomToFeatureExtent(extent)
                self.iface.mapCanvas().refresh()
                result_layer.triggerRepaint()
            else:
                msg = self.tr(u'Cannot load result layer')
                self.iface.messageBar().pushCritical(self.tr(u'Search Error'),
                                                     msg)

        else:
            self.iface.messageBar().pushInfo('Info',
                                             self.tr(u'Nothing do show!'))

    def _get_group(self, group_name):
        """Get a Layer Tree group by its name. If the group is not found
        it is created."""
        group = self.root.findGroup(group_name)

        if group is None:
            group = self.root.addGroup(group_name)

        return group
Esempio n. 34
0
def main():
    global app

    # register representation factories
    baseRepresentationFactories.registerAllFactories()
    representationFactories.registerAllFactories()
    if hasattr(Qt, "AA_EnableHighDpiScaling"):
        QApplication.setAttribute(Qt.AA_EnableHighDpiScaling)
    platformSpecific.setAppName()
    # 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)
    appFont = platformSpecific.UIFontOverride()
    if appFont is not None:
        app.setFont(appFont)
    app.setStyleSheet(platformSpecific.appStyleSheet())

    # Install stream redirection
    app.outputWindow = OutputWindow()
    # Exception handling
    sys.excepthook = errorReports.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)
    # load menu
    if platformSpecific.useGlobalMenuBar():
        app.fetchMenuBar()
        app.setQuitOnLastWindowClosed(False)
    # bootstrap extensions
    folder = app.getExtensionsDirectory()
    for file in os.listdir(folder):
        if not file.rstrip("\\/ ").endswith(".tfExt"):
            continue
        path = os.path.join(folder, file)
        try:
            extension = TExtension(path)
            if extension.launchAtStartup:
                extension.run()
        except Exception as e:
            msg = QApplication.translate(
                "Extensions", f"The extension at {path} could not be run."
            )
            errorReports.showWarningException(e, msg)
            continue
        app.registerExtension(extension)
    # process files
    args = parser.positionalArguments()
    if not args:
        # maybe load recent file
        loadRecentFile = settings.loadRecentFile()
        if loadRecentFile:
            recentFiles = settings.recentFiles()
            if len(recentFiles) and os.path.exists(recentFiles[0]):
                app.openFile(recentFiles[0])
    else:
        for fontPath in args:
            app.openFile(fontPath)
    # if we did not open a font, spawn new font or go headless
    if not app.allFonts():
        if platformSpecific.shouldSpawnDocument():
            app.newFile()
        else:
            # HACK: on OSX we may want to trigger native QMenuBar display
            # without opening any window. Since Qt infers new menu bar on
            # focus change, fire the signal.
            app.focusWindowChanged.emit(None)
    sys.exit(app.exec_())
Esempio n. 35
0
class gearthview3:
    """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',
                                   'gearthview3_{}.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 = gearthview3Dialog()

        # Declare instance attributes
        self.actions = []
        self.menu = self.tr(u'&gearthview3')
        # TODO: We are going to let the user set this up in a future iteration
        self.toolbar = self.iface.addToolBar(u'gearthview3')
        self.toolbar.setObjectName(u'gearthview3')

    # 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('gearthview3', 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 geodrinx_add_submenu(self, submenu):
        if self.geodrinx_menu != None:
            self.geodrinx_menu.addMenu(submenu)
        else:
            self.iface.addPluginToMenu("geodrinx", submenu.menuAction())

    def initGui(self):
        """Create the menu entries and toolbar icons inside the QGIS GUI."""

        # Uncomment the following two lines to have GEODRINX accessible from a top-level menu
        self.geodrinx_menu = QMenu(
            QCoreApplication.translate("geodrinx", "GEODRINX"))
        self.iface.mainWindow().menuBar().insertMenu(
            self.iface.firstRightStandardMenu().menuAction(),
            self.geodrinx_menu)

        # SentinelView Submenu
        self.gearthview3_menu = QMenu(
            QCoreApplication.translate("geodrinx", "&GEarth"))
        self.geodrinx_add_submenu(self.gearthview3_menu)

        icon = QIcon(
            os.path.dirname(__file__) + "/icons/mmqgis_animate_columns.png")
        self.run_action = QAction(icon, "GEarthView", self.iface.mainWindow())
        self.run_action.triggered.connect(self.run)
        self.gearthview3_menu.addAction(self.run_action)

        icon = QIcon(os.path.dirname(__file__) + "/icons/iconP.png")
        self.PasteFromGE_action = QAction(icon, "PasteFromGE",
                                          self.iface.mainWindow())
        self.PasteFromGE_action.triggered.connect(self.PasteFromGE)
        self.gearthview3_menu.addAction(self.PasteFromGE_action)

        icon = QIcon(os.path.dirname(__file__) + "/icons/iconA.png")
        self.aboutAction = QAction(icon, "About", self.iface.mainWindow())
        self.aboutAction.triggered.connect(self.about)
        self.gearthview3_menu.addAction(self.aboutAction)

        icon_path = ':/plugins/gearthview3/icon.png'
        self.add_action(icon_path,
                        text=self.tr(u'gearthview3'),
                        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'&gearthview3'), action)
            self.iface.removeToolBarIcon(action)
        # remove the toolbar
        del self.toolbar

    def about(self):

        html = '<div class="column-center-inner">'
        html = html + '<div class="main section" id="main" name="Principale"><div class="widget Blog" data-version="1" id="Blog1">'
        html = html + '<div class="blog-posts hfeed"><div class="date-outer"><h2 class="date-header"><span>2018-09-01</span></h2><div class="date-posts"><div class="post-outer">'
        html = html + '<div class="post hentry uncustomized-post-template" itemprop="blogPost" itemscope="itemscope" itemtype="http://schema.org/BlogPosting">'
        html = html + '<meta content="GeoDrinX_theStory_copertina_IMG_2759.JPG" itemprop="image_url">'
        html = html + '<meta content="487125219774924662" itemprop="blogId">'
        html = html + '<meta content="4731451121305966553" itemprop="postId">'
        html = html + '<a name="4731451121305966553"></a>'
        html = html + '<h3 class="post-title entry-title" itemprop="name">GEarthView plugin per QGIS 3</h3><div class="post-header">'
        html = html + '<div class="post-header-line-1"></div>'
        html = html + '</div>'
        html = html + '<div class="post-body entry-content" id="post-body-4731451121305966553" itemprop="description articleBody">'
        html = html + '<div style="text-align: center;">'
        html = html + '<span style="font-size: large;">Iniziato il <b>porting</b> di <a href="https://plugins.qgis.org/plugins/popular/" target="_blank"><b>GEarthView</b> plugin</a> per <a href="https://qgis.org/it/site/" target="_blank"><b>QGIS 3</b></a>.</span></div>'
        html = html + '<div style="text-align: justify;">'
        html = html + '<br>'
        html = html + '<div style="text-align: justify;">'
        html = html + '<span style="font-size: large;"><span style="font-size: small;">&nbsp;Il'
        html = html + ' mondo attende questo evento con ansia&nbsp; :)&nbsp;&nbsp;&nbsp; Chi vuole contribuire allo'
        html = html + ' sviluppo puo farlo anche non solo moralmente, seguendo il seguente '
        html = html + 'link:</span></span></div>'
        html = html + '<div style="text-align: justify;">'
        html = html + '<br></div>'
        html = html + '<div style="text-align: center;">'
        html = html + '<span style="font-size: large;"><span style="font-size: small;"><span style="font-size: large;"><b><a data-saferedirecturl="https://www.google.com/url?hl=it&amp;q=https://paypal.me/pools/c/83roK7pmAK&amp;source=gmail&amp;ust=1523474440605000&amp;usg=AFQjCNFYnkThVKNNYKwOH3Qnkq_Ff2UviQ" href="https://paypal.me/pools/c/83roK7pmAK" target="_blank">https://paypal.me/pools/c/<wbr>83roK7pmAK</a></b></span> </span></span></div>'
        #        html = html + '<br></div>'
        #        html = html + '<div class="separator" style="clear: both; text-align: center;">'
        #        html = html + '<a href="https://4.bp.blogspot.com/-aiKys-7BG-o/Ws0QaCRkBQI/AAAAAAAAB5o/JxDFEf6EvZMOHektL1EGi1kaT_rcr4JQwCLcBGAs/s1600/GeoDrinX_theStory_copertina_IMG_2759.JPG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img src="file:///.GeoDrinX_theStory_copertina_IMG_2759.JPG" width="480" height="640" border="0"></a></div>'
        html = html + '<div style="text-align: justify;">'
        html = html + '<br></div>'
        html = html + '<div style="text-align: justify;">'
        html = html + '<br></div>'
        html = html + '<div style="text-align: justify;">'
        html = html + '<span style="font-size: large;"><span style="font-size: small;">Grandioso ! &nbsp; Grazie.</span></span></div>'
        html = html + '<div style="text-align: justify;">'
        html = html + '<br></div>'
        html = html + '<div style="text-align: justify;">'
        html = html + '<span style="font-size: large;"><span style="font-size: small;">A presto </span></span></div>'
        html = html + '<div style="text-align: justify;">'
        html = html + '<br></div>'
        html = html + '<div style="text-align: justify;">'
        html = html + '<span style="font-size: large;"><span style="font-size: small;"><b>GeoDrinX </b></span></span></div>'
        html = html + '<div style="text-align: justify;">'
        html = html + '</div>'
        html = html + '<div style="clear: both;"></div>'
        html = html + '</div>'

        infoString = QCoreApplication.translate('GEarthView3', html)

        window = self.iface.mainWindow()

        #        pixmap = window.icon.pixmap(QtCore.QSize(150, 150))
        #        pixmap = window.pixmap(QtCore.QSize(150, 150))
        #        msgBox.setIconPixmap(pixmap)
        #        msgBox.setWindowIcon(self.window.icon)

        QMessageBox.information(window, "About GEarthView3 plugin", infoString)

        window.label = QLabel()
        window.label.setGeometry(QtCore.QRect(23, 25, 429, 478))
        window.label.setText("")
        window.label.setPixmap(
            QPixmap("GeoDrinX_theStory_copertina_IMG_2759.JPG"))
        window.label.setScaledContents(True)

# ----------------------------------------------------

    def PasteFromGE(self):

        mapCanvas = self.iface.mapCanvas()

        copyText = QApplication.clipboard().text()

        #---------       Fix bug paste multiholes  -------------------------

        copyText = copyText.replace(
            "\t\t\t\t</LinearRing>\n\t\t\t\t<LinearRing>",
            "\t\t\t\t</LinearRing>\n\t\t\t</innerBoundaryIs>\n\t\t\t<innerBoundaryIs>\n\t\t\t\t<LinearRing>"
        )

        copyText = copyText.replace(
            "\t\t\t\t\t</LinearRing>\n\t\t\t\t\t<LinearRing>",
            "\t\t\t\t</LinearRing>\n\t\t\t</innerBoundaryIs>\n\t\t\t<innerBoundaryIs>\n\t\t\t\t<LinearRing>"
        )

        #---------       Fix bug paste multiholes  -------------------------

        #        print copyText

        tumpdir = unicode(
            QFileInfo(QgsApplication.qgisUserDatabaseFilePath()).path()
        ) + "/python/plugins/gearthview3/_WebServer"

        #<Point>         GEKml_Points.kml
        #<LineString>    GEKml_Lines.kml
        #<Polygon>       GEKml_Polygons.kml

        # Tolgo i livelli precedenti
        #        QgsMapLayerRegistry.instance().removeMapLayer("GEKml_Points")
        #        QgsMapLayerRegistry.instance().removeMapLayer("GEKml_Lines")
        #        QgsMapLayerRegistry.instance().removeMapLayer("GEKml_Polygons")

        for iLayer in range(mapCanvas.layerCount()):
            layer = mapCanvas.layer(iLayer)
            if (layer.name() == "GEKml_Points") or (
                    layer.name() == "GEKml_Lines") or (layer.name()
                                                       == "GEKml_Polygons"):
                QgsProject.instance().removeMapLayer(layer.id())

        GEKml_Points = copyText.find("<Point>")
        GEKml_Lines = copyText.find("<LineString>")
        GEKml_Polygons = copyText.find("<Polygon>")

        if (GEKml_Polygons > 0):

            salvalo2 = codecs.open(tumpdir + "/GEKml_Polygons.kml",
                                   'w',
                                   encoding='utf-8')
            salvalo2.write(copyText)

            salvalo2.close()

            vlayer = QgsVectorLayer(tumpdir + "/GEKml_Polygons.kml",
                                    "GEKml_Polygons", "ogr")
            QgsProject.instance().addMapLayer(vlayer)

        if (GEKml_Lines > 0):

            salvalo2 = codecs.open(tumpdir + "/GEKml_Lines.kml",
                                   'w',
                                   encoding='utf-8')
            salvalo2.write(copyText)

            salvalo2.close()

            vlayer = QgsVectorLayer(tumpdir + "/GEKml_Lines.kml",
                                    "GEKml_Lines", "ogr")
            QgsProject.instance().addMapLayer(vlayer)

        if (GEKml_Points > 0):

            salvalo2 = codecs.open(tumpdir + "/GEKml_Points.kml",
                                   'w',
                                   encoding='utf-8')
            salvalo2.write(copyText)

            salvalo2.close()

            vlayer = QgsVectorLayer(tumpdir + "/GEKml_Points.kml",
                                    "GEKml_Points", "ogr")
            QgsProject.instance().addMapLayer(vlayer)

            #  Dalla versione 2.14  QGIS permette di esportare anche la coordinata Z ---

            #        if QGIS_VERSION_INT >= 21400:

            giaFatto = 0
            if (GEKml_Polygons > 0):
                ret = P3dPoints_Write(self, "GEKml_Polygons")
                giaFatto = 1

            if (GEKml_Lines > 0 and giaFatto == 0):
                ret = P3dPoints_Write(self, "GEKml_Lines")
                giaFatto = 1

            if (GEKml_Points > 0 and giaFatto == 0):
                ret = P3dPoints_Write(self, "GEKml_Points")
                giaFatto = 1

            nomecsv = tumpdir + "/_3dPointsExport/GEKml_3dPoints.csv"
            nomecsv.replace("\\", "/")
            uri = """file:///""" + nomecsv + """?"""
            uri += """type=csv&"""
            uri += """trimFields=no&"""
            uri += """xField=X&"""
            uri += """yField=Y&"""
            uri += """spatialIndex=yes&"""
            uri += """subsetIndex=no&"""
            uri += """watchFile=no&"""
            uri += """crs=epsg:4326"""

            for iLayer in range(mapCanvas.layerCount()):
                layer = mapCanvas.layer(iLayer)
                if (layer):
                    if layer.name() == "GEKml_3dPoints":
                        QgsMapLayerRegistry.instance().removeMapLayer(
                            layer.id())
                    if layer.name() == "GEKml_Extrusions":
                        QgsMapLayerRegistry.instance().removeMapLayer(
                            layer.id())

            vlayer = QgsVectorLayer(uri, "GEKml_3dPoints", "delimitedtext")

            #           QgsMapLayerRegistry.instance().addMapLayer(vlayer)
            QgsProject.instance().addMapLayer(vlayer)

            nomeqml = tumpdir + "/_3dPointsExport/GEKml_3dPoints.qml"
            nomeqml.replace("\\", "/")

            result = vlayer.loadNamedStyle(nomeqml)

# FINE  QGis.QGIS_VERSION_INT >= 21400 ----------------------

#        vlayer.triggerRepaint()

        mapCanvas.refresh()

    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

        GDX_Publisher(self)
    def __init__(self, parent, gid_list, persepolis_setting):
        super().__init__(persepolis_setting)
        self.persepolis_setting = persepolis_setting
        self.parent = parent

        # first item in the gid_list is related to video's link and second item is related to audio's link.
        self.gid_list = gid_list

        # this variable can be changed by checkDownloadInfo method in mainwindow.py 
        # self.gid defines that wich gid is downloaded. 
        self.gid = gid_list[0]


        # this variable used as category name in ShutDownThread
        self.video_finder_plus_gid = 'video_finder_' + str(gid_list[0])

        # connect signals and s***s 
        self.resume_pushButton.clicked.connect(self.resumePushButtonPressed)
        self.stop_pushButton.clicked.connect(self.stopPushButtonPressed)
        self.pause_pushButton.clicked.connect(self.pausePushButtonPressed)
        self.download_progressBar.setValue(0)
        self.limit_pushButton.clicked.connect(self.limitPushButtonPressed)

        self.limit_frame.setEnabled(False)
        self.limit_checkBox.toggled.connect(self.limitCheckBoxToggled)

        self.after_frame.setEnabled(False)
        self.after_checkBox.toggled.connect(self.afterCheckBoxToggled)

        self.after_pushButton.clicked.connect(self.afterPushButtonPressed)

        # 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)

        # check if limit speed actived by user or not
        add_link_dictionary = self.parent.persepolis_db.searchGidInAddLinkTable(gid_list[0])

        limit = str(add_link_dictionary['limit_value'])
        if limit != '0':
            limit_number = limit[:-1]
            limit_unit = limit[-1]
            self.limit_spinBox.setValue(float(limit_number))
            if limit_unit == 'K':
                self.after_comboBox.setCurrentIndex(0)
            else:
                self.after_comboBox.setCurrentIndex(1)
            self.limit_checkBox.setChecked(True)

        self.after_comboBox.currentIndexChanged.connect(self.afterComboBoxChanged)

        self.limit_comboBox.currentIndexChanged.connect(self.limitComboBoxChanged)

        self.limit_spinBox.valueChanged.connect(self.limitComboBoxChanged)

        # set window size and position
        size = self.persepolis_setting.value(
            'ProgressWindow/size', QSize(595, 274))
        position = self.persepolis_setting.value(
            'ProgressWindow/position', QPoint(300, 300))
        self.resize(size)
        self.move(position)
Esempio n. 37
0
class EmergencyMapper:
    """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',
            'EmergencyMapper_{}.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'&Emergency Mapper')
        # TODO: We are going to let the user set this up in a future iteration
        self.toolbar = self.iface.addToolBar(u'Emergency Mapper')
        self.toolbar.setObjectName(u'Emergency Mapper')

        #print "** INITIALIZING EmergencyMapper"

        self.pluginIsActive = False
        self.dockwidget = None


    # noinspection PyMethodMayBeStatic
    def tr(self, message):
        """Get the translation for a string using Qt translation API.

        We implement this ourselves since we do not inherit QObject.

        :param message: String for translation.
        :type message: str, QString

        :returns: Translated version of message.
        :rtype: QString
        """
        # noinspection PyTypeChecker,PyArgumentList,PyCallByClass
        return QCoreApplication.translate('EmergencyMapper', 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/Emergency_Mapper/icon.png'
        self.add_action(
            icon_path,
            text=self.tr(u'Emergency Mapper Dock'),
            callback=self.run,
            parent=self.iface.mainWindow())

    #--------------------------------------------------------------------------

    def onClosePlugin(self):
        """Cleanup necessary items here when plugin dockwidget is closed"""

        #print "** CLOSING EmergencyMapper"

        # disconnects
        self.dockwidget.closingPlugin.disconnect(self.onClosePlugin)

        # remove this statement if dockwidget is to remain
        # for reuse if plugin is reopened
        # Commented next statement since it causes QGIS crashe
        # when closing the docked window:
        # self.dockwidget = None

        self.pluginIsActive = False


    def unload(self):
        """Removes the plugin menu item and icon from QGIS GUI."""

        #print "** UNLOAD EmergencyMapper"

        for action in self.actions:
            self.iface.removePluginMenu(
                self.tr(u'&Emergency Mapper'),
                action)
            self.iface.removeToolBarIcon(action)
        # remove the toolbar
        del self.toolbar

    #--------------------------------------------------------------------------

    def run(self):
        """Run method that loads and starts the plugin"""

        if not self.pluginIsActive:
            self.pluginIsActive = True

            #print "** STARTING EmergencyMapper"

            # dockwidget may not exist if:
            #    first run of plugin
            #    removed on close (see self.onClosePlugin method)
            if self.dockwidget == None:
                # Create the dockwidget (after translation) and keep reference
                self.dockwidget = EmergencyMapperDockWidget()

            # connect to provide cleanup on closing of dockwidget
            self.dockwidget.closingPlugin.connect(self.onClosePlugin)

            # show the dockwidget
            # TODO: fix to allow choice of dock location
            self.iface.addDockWidget(Qt.LeftDockWidgetArea, self.dockwidget)
            self.dockwidget.show()
            self.dockwidget.selectAdmin.clicked.connect(self.loadAdmin)
            self.dockwidget.selectHazard.clicked.connect(self.loadHazard)
            self.dockwidget.selectBuilding.clicked.connect(self.loadBuilding)
            self.dockwidget.selectPop.clicked.connect(self.loadPop)
            self.dockwidget.loadBasemap.clicked.connect(self.loadBasemap)
            self.dockwidget.computeRisk.clicked.connect(self.loadRisk)
            self.dockwidget.publishMap.clicked.connect(self.loadPublishMap)

    def loadAdmin(self):
        self.adminui= dialogs.selectAdminDialog()
        self.adminui.show()
        self.adminui.ui.pushButton.clicked.connect(self.loadHazard)

    def loadHazard(self):
        self.adminui = dialogs.selectHazardDialog()
        self.adminui.show()

    def loadBuilding(self):
        self.adminui = dialogs.selectBuildingDialog()
        self.adminui.show()

    def loadPop(self):
        self.adminui = dialogs.selectPopDialog()
        self.adminui.show()

    def loadBasemap(self):
        self.adminui = dialogs.loadBasemapDialog()
        self.adminui.show()

    def loadRisk(self):
        self.adminui = dialogs.loadRiskDialog()
        self.adminui.show()

    def loadPublishMap(self):
        self.adminui = dialogs.publishMapDialog()
        self.adminui.show()
Esempio n. 38
0
class getwkt3:
    """QGIS Plugin Implementation."""

    s = QgsSettings()

    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',
                                   'getwkt3_{}.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 = getwkt3Dialog()
        self.cfg = getwkt3Config()
        # Declare instance attributes
        self.actions = []
        self.menu = self.tr(u'&Get WKT')
        self.toolbar = self.iface.addToolBar(u'getwkt3')
        self.toolbar.setObjectName(u'getwkt3')

    # 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('getwkt3', 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/getwkt3/wkt.png'
        self.add_action(icon_path,
                        text=self.tr(u'Get WKT String'),
                        callback=self.run_wkt,
                        parent=self.iface.mainWindow())

        icon_path = ':/plugins/getwkt3/ewkt.png'
        self.add_action(icon_path,
                        text=self.tr(u'Get EWKT String'),
                        callback=self.run_ewkt,
                        parent=self.iface.mainWindow())

        icon_path = ':/plugins/getwkt3/json.png'
        self.add_action(icon_path,
                        text=self.tr(u'Get JSON String'),
                        callback=self.run_json,
                        parent=self.iface.mainWindow())

        icon_path = ':/plugins/getwkt3/config.png'
        self.add_action(icon_path,
                        text=self.tr(u'Open Config'),
                        callback=self.open_config,
                        parent=self.iface.mainWindow(),
                        add_to_toolbar=False)

    def unload(self):
        """Removes the plugin menu item and icon from QGIS GUI."""
        for action in self.actions:
            self.iface.removePluginVectorMenu(self.tr(u'&Get WKT'), action)
            self.iface.removeToolBarIcon(action)
        # remove the toolbar
        del self.toolbar

    def run_wkt(self):
        """Runs tool to extract WKT"""
        self.run('wkt')

    def run_ewkt(self):
        """Runs tool to extract EWKT"""
        self.run('ewkt')

    def run_json(self):
        """Runs tool to extract JSON"""
        self.run('json')

    def run(self, out_type):
        """Run method that performs all the real work"""
        mc = self.iface.mapCanvas()
        layer = mc.currentLayer()
        if layer is None:
            self.dlg.wktTextEdit.setHtml('<strong style="color:red">'\
            'ERROR:</strong> No selected layer')
        elif layer.type() != QgsMapLayerType.VectorLayer:
            self.dlg.wktTextEdit.setHtml('<strong style="color:red">'\
            'ERROR:</strong> Layer selected is not vector')
        elif layer.selectedFeatureCount() == 0:
            self.dlg.wktTextEdit.setHtml('<strong style="color:red">'\
            'ERROR:</strong> No feature selected')
        elif layer.selectedFeatureCount() > 1:
            self.dlg.wktTextEdit.setHtml('<strong style="color:red">'\
            'ERROR:</strong> More than one feature is selected')
        else:
            feat = layer.selectedFeatures()
            if feat is None:
                self.dlg.wktTextEdit.setHtml('<strong style="color:red">'\
                'ERROR:</strong> No selected features')
            else:
                #Get geom
                geom = feat[0].geometry()
                #Get srid
                try:
                    crs = layer.crs()
                    authid = crs.authid()
                    auth, srid = authid.split(':')
                    if auth != 'EPSG':
                        srid = -1
                except Exception:
                    srid = -1
                #Setup dp for output
                dp_method = self.s.value("getwkt3/dpmethod")
                if dp_method == "custom":
                    try:
                        dp_count = int(self.s.value("getwkt3/dpcustom"))
                    except ValueError:
                        dp_count = None
                elif dp_method == "auto":
                    #Determine crs units
                    crs_units = crs.mapUnits()
                    #Allocate auto dp count based on crs units
                    if crs_units == QgsUnitTypes.DistanceUnit.DistanceFeet:
                        dp_count = 3
                    elif crs_units == QgsUnitTypes.DistanceUnit.DistanceNauticalMiles:
                        dp_count = 8
                    elif crs_units == QgsUnitTypes.DistanceUnit.DistanceYards:
                        dp_count = 3
                    elif crs_units == QgsUnitTypes.DistanceUnit.DistanceMiles:
                        dp_count = 8
                    elif crs_units == QgsUnitTypes.DistanceUnit.DistanceMillimeters:
                        dp_count = 0
                    elif crs_units == QgsUnitTypes.DistanceUnit.DistanceCentimeters:
                        dp_count = 2
                    elif crs_units == QgsUnitTypes.DistanceUnit.DistanceMeters:
                        dp_count = 4
                    elif crs_units == QgsUnitTypes.DistanceUnit.DistanceKilometers:
                        dp_count = 7
                    elif crs_units == QgsUnitTypes.DistanceUnit.DistanceDegrees:
                        dp_count = 8
                    else:
                        dp_count = None
                else:
                    dp_count = None
                #Process export type
                if out_type == 'wkt':
                    wkt = geom.asWkt(
                        dp_count) if not dp_count is None else geom.asWkt()
                    wkt = self.standardise_wkt(wkt)
                    text = wkt
                elif out_type == 'ewkt':
                    wkt = geom.asWkt(
                        dp_count) if not dp_count is None else geom.asWkt()
                    wkt = self.standardise_wkt(wkt)
                    text = 'SRID={0};{1}'.format(srid, wkt)
                elif out_type == 'json':
                    text = geom.asJson(
                        dp_count) if not dp_count is None else geom.asJson()
                else:
                    text = '[{0}] Not Implemented'.format(out_type)
                self.dlg.wktTextEdit.setText("{0}".format(text))
        self.dlg.show()
        # Run the dialog event loop
        self.dlg.exec_()

    def open_config(self):
        """Opens config menu"""
        self.cfg.show()
        self.cfg.exec_()

    def standardise_wkt(self, wkt):
        #Setup standardisers
        standards = {
            "PointZM": "Point Z M",
            "LineStringZM": "LineString Z M",
            "PolygonZM": "Polygon Z M",
            "MultiPointZM": "MultiPoint Z M",
            "MultiLineStringZM": "MultiLineString Z M",
            "MultiPolygonZM": "MultiPolygon Z M",
            "GeometryCollectionZM": "GeometryCollection Z M",
            "CircularStringZM": "CircularString Z M",
            "CompoundCurveZM": "CompoundCurve Z M",
            "CurvePolygonZM": "CurvePolygon Z M",
            "MultiCurveZM": "MultiCurve Z M",
            "MultiSurfaceZM": "MultiSurface Z M",
            "TriangleZM": "Triangle Z M",
            "Point25D": "Point Z",
            "LineString25D": "LineString Z",
            "Polygon25D": "Polygon Z",
            "MultiPoint25D": "MultiPoint Z",
            "MultiLineString25D": "MultiLineString Z",
            "MultiPolygon25D": "MultiPolygon Z",
            "PointZ": "Point Z",
            "LineStringZ": "LineString Z",
            "PolygonZ": "Polygon Z",
            "TriangleZ": "Triangle Z",
            "MultiPointZ": "MultiPoint Z",
            "MultiLineStringZ": "MultiLineString Z",
            "MultiPolygonZ": "MultiPolygon Z",
            "GeometryCollectionZ": "GeometryCollection Z",
            "CircularStringZ": "CircularString Z",
            "CompoundCurveZ": "CompoundCurve Z",
            "CurvePolygonZ": "CurvePolygon Z",
            "MultiCurveZ": "MultiCurve Z",
            "MultiSurfaceZ": "MultiSurface Z",
            "PointM": "Point M",
            "LineStringM": "LineString M",
            "PolygonM": "Polygon M",
            "TriangleM": "Triangle M",
            "MultiPointM": "MultiPoint M",
            "MultiLineStringM": "MultiLineString M",
            "MultiPolygonM": "MultiPolygon M",
            "GeometryCollectionM": "GeometryCollection M",
            "CircularStringM": "CircularString M",
            "CompoundCurveM": "CompoundCurve M",
            "CurvePolygonM": "CurvePolygon M",
            "MultiCurveM": "MultiCurve M",
            "MultiSurfaceM": "MultiSurface M",
            # "Point":"Point",
            # "LineString":"LineString",
            # "Polygon":"Polygon",
            # "Triangle":"Triangle",
            # "MultiPoint":"MultiPoint",
            # "MultiLineString":"MultiLineString",
            # "MultiPolygon":"MultiPolygon",
            # "GeometryCollection":"GeometryCollection",
            # "CircularString":"CircularString",
            # "CompoundCurve":"CompoundCurve",
            # "CurvePolygon":"CurvePolygon",
            # "MultiCurve":"MultiCurve",
            # "MultiSurface":"MultiSurface",
            # "NoGeometry":"NoGeometry",
            # "Unknown":"Unknown",
        }
        #Process all standisers
        for key, value in standards.items():
            wkt = wkt.replace(key, value)
        #Return result
        return wkt
class VideoFinderProgressWindow(VideoFinderProgressWindow_Ui):
    def __init__(self, parent, gid_list, persepolis_setting):
        super().__init__(persepolis_setting)
        self.persepolis_setting = persepolis_setting
        self.parent = parent

        # first item in the gid_list is related to video's link and second item is related to audio's link.
        self.gid_list = gid_list

        # this variable can be changed by checkDownloadInfo method in mainwindow.py 
        # self.gid defines that wich gid is downloaded. 
        self.gid = gid_list[0]


        # this variable used as category name in ShutDownThread
        self.video_finder_plus_gid = 'video_finder_' + str(gid_list[0])

        # connect signals and s***s 
        self.resume_pushButton.clicked.connect(self.resumePushButtonPressed)
        self.stop_pushButton.clicked.connect(self.stopPushButtonPressed)
        self.pause_pushButton.clicked.connect(self.pausePushButtonPressed)
        self.download_progressBar.setValue(0)
        self.limit_pushButton.clicked.connect(self.limitPushButtonPressed)

        self.limit_frame.setEnabled(False)
        self.limit_checkBox.toggled.connect(self.limitCheckBoxToggled)

        self.after_frame.setEnabled(False)
        self.after_checkBox.toggled.connect(self.afterCheckBoxToggled)

        self.after_pushButton.clicked.connect(self.afterPushButtonPressed)

        # 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)

        # check if limit speed actived by user or not
        add_link_dictionary = self.parent.persepolis_db.searchGidInAddLinkTable(gid_list[0])

        limit = str(add_link_dictionary['limit_value'])
        if limit != '0':
            limit_number = limit[:-1]
            limit_unit = limit[-1]
            self.limit_spinBox.setValue(float(limit_number))
            if limit_unit == 'K':
                self.after_comboBox.setCurrentIndex(0)
            else:
                self.after_comboBox.setCurrentIndex(1)
            self.limit_checkBox.setChecked(True)

        self.after_comboBox.currentIndexChanged.connect(self.afterComboBoxChanged)

        self.limit_comboBox.currentIndexChanged.connect(self.limitComboBoxChanged)

        self.limit_spinBox.valueChanged.connect(self.limitComboBoxChanged)

        # set window size and position
        size = self.persepolis_setting.value(
            'ProgressWindow/size', QSize(595, 274))
        position = self.persepolis_setting.value(
            'ProgressWindow/position', QPoint(300, 300))
        self.resize(size)
        self.move(position)

    def closeEvent(self, event):

        # save window size and position
        self.persepolis_setting.setValue('ProgressWindow/size', self.size())
        self.persepolis_setting.setValue('ProgressWindow/position', self.pos())
        self.persepolis_setting.sync()

        self.hide()

    def resumePushButtonPressed(self, button):
        if self.status == "paused":
            answer = download.downloadUnpause(self.gid)
            # if aria2 did not respond , then this function is checking for aria2
            # availability , and if aria2 disconnected then aria2Disconnected is
            # executed
            if not(answer):
                version_answer = download.aria2Version()
                if version_answer == 'did not respond':
                    self.parent.aria2Disconnected()
                    notifySend(QCoreApplication.translate("progress_src_ui_tr", "Aria2 disconnected!"), QCoreApplication.translate("progress_src_ui_tr", "Persepolis is trying to connect! be patient!"),
                               10000, 'warning', parent=self.parent)
                else:
                    notifySend(QCoreApplication.translate("progress_src_ui_tr", "Aria2 did not respond!"), QCoreApplication.translate("progress_src_ui_tr", "Please try again."), 10000,
                               'warning', parent=self.parent)


    def pausePushButtonPressed(self, button):

        if self.status == "downloading":
            answer = download.downloadPause(self.gid)

            # if aria2 did not respond , then this function is checking for aria2
            # availability , and if aria2 disconnected then aria2Disconnected is
            # executed
            if not(answer):
                version_answer = download.aria2Version()
                if version_answer == 'did not respond':
                    self.parent.aria2Disconnected()
                    download.downloadStop(self.gid, self.parent)
                    notifySend("Aria2 disconnected!", "Persepolis is trying to connect! be patient!",
                               10000, 'warning', parent=self.parent)
                else:
                    notifySend(QCoreApplication.translate("progress_src_ui_tr", "Aria2 did not respond!"), QCoreApplication.translate("progress_src_ui_tr", "Try again!"), 10000,
                               'critical', parent=self.parent)

    def stopPushButtonPressed(self, button):
        
        # cancel shut down progress
        dictionary = {'category': self.video_finder_plus_gid,
                'shutdown': 'canceled'}

        self.parent.temp_db.updateQueueTable(dictionary)


        answer = download.downloadStop(self.gid, self.parent)
        
        # if aria2 did not respond , then this function is checking for aria2
        # availability , and if aria2 disconnected then aria2Disconnected is
        # executed
        if answer == 'None':
            version_answer = download.aria2Version()
            if version_answer == 'did not respond':
                self.parent.aria2Disconnected()
                notifySend(QCoreApplication.translate("progress_src_ui_tr", "Aria2 disconnected!"), QCoreApplication.translate("progress_src_ui_tr", "Persepolis is trying to connect! be patient!"),
                           10000, 'warning', parent=self.parent)

    def limitCheckBoxToggled(self, checkBoxes):

        # user checked limit_checkBox
        if self.limit_checkBox.isChecked() == True:
            self.limit_frame.setEnabled(True)
            self.limit_pushButton.setEnabled(True)

        # user unchecked limit_checkBox
        else:
            self.limit_frame.setEnabled(False)

            # check download status is "scheduled" or not!
            for i in [0, 1]:
                gid = self.gid_list[i]
                dictionary = self.parent.persepolis_db.searchGidInDownloadTable(gid) 
                status = dictionary['status']

                if status != 'scheduled':

                    # tell aria2 for unlimiting speed
                    download.limitSpeed(gid, "0")

                else:
                    # update limit value in data_base
                    add_link_dictionary = {'gid': gid, 'limit_value': '0'}
                    self.parent.persepolis_db.updateAddLinkTable([add_link_dictionary])

    def limitComboBoxChanged(self, connect):

        self.limit_pushButton.setEnabled(True)

    def afterComboBoxChanged(self, connect):

        self.after_pushButton.setEnabled(True)

    def afterCheckBoxToggled(self, checkBoxes):

        if self.after_checkBox.isChecked():

            self.after_frame.setEnabled(True)
        else:

            # so user canceled shutdown after download
            # write cancel value in data_base for this gid
            dictionary = {'category': self.video_finder_plus_gid,
                        'shutdown': 'canceled'}

            self.parent.temp_db.updateQueueTable(dictionary)
    
    def afterPushButtonPressed(self, button):

        self.after_pushButton.setEnabled(False)

        # For Linux and Mac OSX and FreeBSD and OpenBSD
        if os_type != 'Windows':  

            # get root password
            passwd, ok = QInputDialog.getText(
                self, 'PassWord', 'Please enter root password:'******'sudo', '-S', 'echo', 'hello'],
                        stdout=subprocess.DEVNULL,
                        stdin=subprocess.PIPE,
                        stderr=subprocess.DEVNULL,
                        shell=False)

                pipe.communicate(passwd.encode())

                answer = pipe.wait()

                # Wrong password
                while answer != 0:

                    passwd, ok = QInputDialog.getText(
                        self, 'PassWord', 'Wrong Password!\nPlease try again.', QLineEdit.Password)

                    if ok:

                        pipe = subprocess.Popen(['sudo', '-S', 'echo', 'hello'],
                                stdout=subprocess.DEVNULL,
                                stdin=subprocess.PIPE,
                                stderr=subprocess.DEVNULL,
                                shell=False)

                        pipe.communicate(passwd.encode())

                        answer = pipe.wait()

                    else:
                        ok = False
                        break

                if ok != False:

                    # if user selects shutdown option after download progress, 
                    # value of 'shutdown' will changed in temp_db for this progress
                    # and "wait" word will be written for this value.
                    # (see ShutDownThread and shutdown.py for more information)
                    # shutDown method will check that value in a loop .
                    # when "wait" changes to "shutdown" then shutdown.py script
                    # will shut down the system.

                    shutdown_enable = ShutDownThread(self.parent, self.video_finder_plus_gid, passwd)
                    self.parent.threadPool.append(shutdown_enable)
                    self.parent.threadPool[len(self.parent.threadPool) - 1].start()

                else:
                    self.after_checkBox.setChecked(False)
            else:
                self.after_checkBox.setChecked(False)

        else:  
            # for Windows
            for gid in gid_list:
                shutdown_enable = ShutDownThread(self.parent, self.video_finder_plus_gid)
                self.parent.threadPool.append(shutdown_enable)
                self.parent.threadPool[len(self.parent.threadPool) - 1].start()

    def limitPushButtonPressed(self, button):

        self.limit_pushButton.setEnabled(False)

        if self.limit_comboBox.currentText() == "KiB/s":

            limit_value = str(self.limit_spinBox.value()) + str("K")
        else:
            limit_value = str(self.limit_spinBox.value()) + str("M")

        # if download was started before , send the limit_speed request to aria2 .
        # else save the request in data_base
        for i in [0, 1]:

            gid = self.gid_list[i]
            dictionary = self.parent.persepolis_db.searchGidInDownloadTable(gid)
            status = dictionary['status']

            if status != 'scheduled':

                download.limitSpeed(self.gid, limit_value)
            else:
                # update limit value in data_base
                add_link_dictionary = {'gid': gid, 'limit_value': limit_value}
                self.parent.persepolis_db.updateAddLinkTable([add_link_dictionary])

    def changeIcon(self, icons):
        icons = ':/' + str(icons) + '/'

        self.resume_pushButton.setIcon(QIcon(icons + 'play'))
        self.pause_pushButton.setIcon(QIcon(icons + 'pause'))
        self.stop_pushButton.setIcon(QIcon(icons + 'stop'))
Esempio n. 40
0
from PyQt5.QtCore import QLocale
from PyQt5.QtCore import QTranslator
from PyQt5.QtWidgets import QApplication

from utils import excepthook, Options, die
from views.main_window import MainWindow
from views.login_form import LoginForm
import resources

if __name__ == '__main__':
    # setting exception hook for pycharm
    sys.excepthook = excepthook

    app = QApplication(sys.argv)
    QLocale().setDefault(QLocale(QLocale.Russian, QLocale.RussianFederation))
    qt_translator = QTranslator()
    qt_translator.load(':/qtbase_ru.qm')
    app.installTranslator(qt_translator)

    login_form = LoginForm()
    if login_form.exec() != LoginForm.Accepted:
        die()

    window = MainWindow()
    window.show()
    app.exec()

    Options.dump()
    die()
Esempio n. 41
0
import sys
from PyQt5.QtWidgets import QApplication
from PyLogicFile.MainForm import MainWin
from PyQt5.QtCore import QTranslator, QCoreApplication, Qt

if __name__ == '__main__':
    app = QApplication(sys.argv)
    translator = QTranslator()
    translator.load('./config/qt_zh_CN.qm')
    app.installTranslator(translator)
    QCoreApplication.setAttribute(Qt.AA_EnableHighDpiScaling)
    win = MainWin()
    win.show()
    sys.exit(app.exec_())


Esempio n. 42
0
class MemSetup(QObject):
    def __init__(self):
        QObject.__init__(self)
        colorama_init()
        self.name = "DevicesInLAN"
        self.author = self.tr("Mariano Mu\xf1oz")
        self.description = self.tr(
            'Show devices in a LAN making an ARP search to find them with a user interface'
        )
        self.epilog = self.tr(
            "If you like this app, please give me a star in https://github.com/turulomio/devicesinlan."
        ) + "\n" + self.tr("Developed by {} 2015-{} \xa9").format(
            self.author, __versiondate__.year)

    ## Sets QApplication Object to make a Qt application
    def setQApplication(self):
        self.app = QCoreApplication(sys.argv)
        self.app.setOrganizationName(self.name)
        self.app.setOrganizationDomain(self.name)
        self.app.setApplicationName(self.name)
        self.translator = QTranslator()
        self.settings = QSettings()

    def mangenerator(self, language):
        from mangenerator import Man

        print("DESCRIPTION in {} is {}".format(language,
                                               self.tr("DESCRIPTION")))

        if language == "en":
            man = Man("man/man1/devicesinlan")
            mangui = Man("man/man1/devicesinlan_gui")
        else:
            man = Man("man/{}/man1/devicesinlan".format(language))
            mangui = Man("man/{}/man1/devicesinlan_gui".format(language))

        mangui.setMetadata(
            "devicesinlan_gui", 1, datetime.date.today(), "Mariano Muñoz",
            self.
            tr("Scans all devices in your LAN. Then you can set an alias to your known devices in order to detect future strange devices in your net."
               ))
        mangui.setSynopsis("[--help] [--version] [--debug DEBUG]")
        mangui.header(self.tr("DESCRIPTION"), 1)
        mangui.paragraph(
            self.tr("In the app menu you have the followings features:"), 1)
        mangui.paragraph(self.tr("Devices > New Scan"), 2, True)
        mangui.paragraph(
            self.
            tr("Searches all devices in the LAN and show them in a new tab. If some device is not in the known devices list it will be shown with a red background. Devices with a green background are trusted devices"
               ), 3)
        mangui.paragraph(self.tr("Devices > Show devices database"), 2, True)
        mangui.paragraph(self.tr("Shows all known devices in a new tab."), 3)
        mangui.paragraph(
            self.tr("Right click allows you to edit known devices database."),
            3)
        mangui.paragraph(self.tr("Devices > Load devices list"), 2, True)
        mangui.paragraph(
            self.tr("Loads a list of known devices in xml format."), 3)
        mangui.paragraph(self.tr("Devices > Save devices list"), 2, True)
        mangui.paragraph(
            self.tr("Saves the known devices list to a xml file."), 3)
        mangui.paragraph(self.tr("Devices > Reset database"), 2, True)
        mangui.paragraph(self.tr("Removes all known devices."), 3)
        mangui.paragraph(
            self.tr("This option erases all known devices in database."), 3)
        mangui.paragraph(self.tr("Configuration > Settings"), 2, True)
        mangui.paragraph(
            self.
            tr("In this dialog you can select your prefered language and you can configure the number of concurrence request."
               ), 3)
        mangui.paragraph(self.tr("Help > Help"), 2, True)
        mangui.paragraph(self.tr("Shows this help information."), 3)
        mangui.paragraph(self.tr("Help > About"), 2, True)
        mangui.paragraph(
            self.tr(
                "Shows information about DevicesInLAN license and authors."),
            3)
        mangui.paragraph(self.tr("Help > Check for updates"), 2, True)
        mangui.paragraph(
            self.tr("Checks for updates in DevicesInLan repository."), 3)
        mangui.paragraph(self.tr("Help > Exit"), 2, True)
        mangui.paragraph(self.tr("Exits from program."), 3)
        mangui.save()
        mangui.saveHTML(
            "devicesinlan/data/devicesinlan_gui.{}.html".format(language))

        man.setMetadata(
            "devicesinlan", 1, datetime.date.today(), "Mariano Muñoz",
            self.
            tr("Scans all devices in your LAN. Then you can set an alias to your known devices in order to detect future strange devices in your net."
               ))
        man.setSynopsis(
            "[--help] [--version] [--debug DEBUG] [ --interface | --add | --remove | --list | --load | --save | --reset ]"
        )

        man.header(self.tr("DESCRIPTION"), 1)
        man.paragraph(
            self.
            tr("If you launch DevicesInLan without parameters a console wizard is launched."
               ), 1)
        man.paragraph(self.tr("Morever you can use one of this parameters."),
                      1)
        man.paragraph("--interface", 2, True)
        man.paragraph(
            self.
            tr("Scans the net of the interface parameter and prints a list of the detected devices."
               ), 3)
        man.paragraph(
            self.
            tr("If a device is not known, it will be showed in red. Devices in green are trusted devices."
               ), 3)
        man.paragraph("--add", 2, True)
        man.paragraph(self.tr("Allows to add a known device from console."), 3)
        man.paragraph("--remove", 2, True)
        man.paragraph(self.tr("Allows to remove a known device from console."),
                      3)
        man.paragraph("--list", 2, True)
        man.paragraph(
            self.tr("Shows all known devices in database from console."), 3)
        man.paragraph("--load", 2, True)
        man.paragraph(self.tr("Loads a list of known devices in xml format."),
                      3)
        man.paragraph("--save", 2, True)
        man.paragraph(self.tr("Saves the known devices list to a xml file."),
                      3)
        man.paragraph("--debug", 2, True)
        man.paragraph(
            self.
            tr("Gives debugging information when running DevicesInLAN. It's deactivated by default"
               ), 3)
        man.paragraph(
            self.
            tr("The parameter can take this options: CRITICAL, ERROR, WARNING, INFO, DEBUG."
               ), 3)
        man.paragraph("--reset", 2, True)
        man.paragraph(self.tr("Removes all known devices."), 3)
        man.save()
        man.saveHTML("devicesinlan/data/devicesinlan.{}.html".format(language))

    ## Sets logging level for the app
    def setLoggingLevel(self, level):
        #Por defecto se pone WARNING y mostrar´ia ERROR y CRITICAL
        logFormat = "%(asctime)s %(levelname)s %(module)s:%(lineno)d at %(funcName)s. %(message)s"
        dateFormat = '%Y%m%d %I%M%S'

        if level == "DEBUG":  #Show detailed information that can help with program diagnosis and troubleshooting. CODE MARKS
            logging.basicConfig(level=logging.DEBUG,
                                format=logFormat,
                                datefmt=dateFormat)
        elif level == "INFO":  #Everything is running as expected without any problem. TIME BENCHMARCKS
            logging.basicConfig(level=logging.INFO,
                                format=logFormat,
                                datefmt=dateFormat)
        elif level == "WARNING":  #The program continues running, but something unexpected happened, which may lead to some problem down the road. THINGS TO DO
            logging.basicConfig(level=logging.WARNING,
                                format=logFormat,
                                datefmt=dateFormat)
        elif level == "ERROR":  #The program fails to perform a certain function due to a bug.  SOMETHING BAD LOGIC
            logging.basicConfig(level=logging.ERROR,
                                format=logFormat,
                                datefmt=dateFormat)
        elif level == "CRITICAL":  #The program encounters a serious error and may stop running. ERRORS
            logging.basicConfig(level=logging.CRITICAL,
                                format=logFormat,
                                datefmt=dateFormat)
        else:
            if level:  #Bad debug parameter
                logging.basicConfig(level=logging.CRITICAL,
                                    format=logFormat,
                                    datefmt=dateFormat)
                logging.critical(
                    "--debug parameter must be DEBUG, INFO, WARNING, ERROR or CRITICAL"
                )
                sys.exit(1)
            else:  #No debug parameter
                logging.propagate = False

    def signal_handler(self, signal, frame):
        print(Style.BRIGHT + Fore.RED +
              self.tr("You pressed 'Ctrl+C', exiting..."))
        sys.exit(0)

    ## Changes Qt current Qtranslator
    ## @param language String with en, es .... None by defautt and search in settings
    def setLanguage(self, language=None):
        if language == None:
            language = self.settings.value("frmSettings/language", "en")
        url = package_filename("devicesinlan",
                               "i18n/devicesinlan_{}.qm".format(language))

        if language == "en":
            logging.info("Changing to default language: en")
            self.app.removeTranslator(self.translator)
            self.translator = QTranslator()
        else:
            self.translator.load(url)
            self.app.installTranslator(self.translator)
            logging.info(
                self.tr("Language changed to {} using {}".format(
                    language, url)))
Esempio n. 43
0
 def dillerComboDegisti(self, dil):
     self.ebeveyn.sistemDili = self.diller[dil]
     translator = QTranslator(qApp)
     translator.load("/usr/share/milis-kur/languages/%s.qm" % (str(dil)))
     qApp.installTranslator(translator)
Esempio n. 44
0
    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)
Esempio n. 45
0
class MyWindow(QMainWindow, Ui_MWin):
    def __init__(self, parent=None):
        super(MyWindow, self).__init__(parent)
        self.setupUi(self)
        try:
            with open('style.qss') as f:
                style = f.read()  # 读取样式表
                self.setStyleSheet(style)
        except:
            print("open stylesheet error")
        self.originText.setFocus(True)
        #  Translator
        self.trans = QTranslator()
        # destination language
        self.dest = 'zh-CN'
        # ui language : 0->zh-CN, 1->en
        self.lan = 0
        # real-time translate
        self.isRealTimeTrans = False
        self.isCopyFromTrans = False
        self.connectSlots()

    def connectSlots(self):
        self.alwaysFront.clicked.connect(self.alwaysFrontFunc)  # windows top
        self.realTimeTrans.clicked.connect(
            self.realTimeTransFunc)  # real-time translate

        self.go.clicked.connect(self.transTextToZhCN)
        self.go.setShortcut("Ctrl+Return")

        self.copy.clicked.connect(self.copySlot)

        # connect to slots
        self.openFile.triggered.connect(self.openFileSlot)
        self.exportFile.triggered.connect(self.exportFileSlot)
        self.exit.triggered.connect(self.close)

        self.actionChinese.triggered.connect(lambda: self.changeLanguage(0))
        self.actionEnglish.triggered.connect(lambda: self.changeLanguage(1))

        self.actionDestChinese.triggered.connect(
            lambda: self.destinationLanguage(0))
        self.actionDestEnglish.triggered.connect(
            lambda: self.destinationLanguage(1))
        self.actionDestJapanese.triggered.connect(
            lambda: self.destinationLanguage(2))
        self.actionDestKorean.triggered.connect(
            lambda: self.destinationLanguage(3))

        self.about.triggered.connect(lambda: QDesktopServices.openUrl(
            QUrl(
                'https://github.com/LewisTian/PyQt5-Apps/tree/master/google-translate'
            )))
        self.about.setShortcut("CTRL+H")
        self.donate.triggered.connect(lambda: QDesktopServices.openUrl(
            QUrl('https://lewistian.github.io/2018/01/01/donate/')))
        self.reportBug.triggered.connect(lambda: QDesktopServices.openUrl(
            QUrl('https://github.com/LewisTian/PyQt5-tools/issues')))

    def openFileSlot(self):
        filename, filetype = QFileDialog.getOpenFileName(
            self, 'Open File', '.')
        if filename:
            print(filename)
            with open(filename, encoding='utf-8') as f:
                try:
                    self.originText.setPlainText(f.read())
                except Exception as e:
                    self.originText.setPlainText(e.args[1])

    def exportFileSlot(self):
        if not self.transText.toPlainText():
            return
        filename, filetype = QFileDialog.getSaveFileName(
            self, 'Save File', '.', '*.txt;;*')
        if filename:
            with open(filename, 'w', encoding='utf-8') as f:
                try:
                    f.write(self.transText.toPlainText())
                except Exception as e:
                    self.transText.setPlainText(e.args[1])

    def changeLanguage(self, lan):
        """:author : Tich
        :param lan: 0=>Chinese, 1=>English
        change ui language
        """
        if lan == 0 and self.lan != 0:
            self.lan = 0
            print("[MainWindow] Change to zh_CN")
            self.trans.load("zh_CN")
        elif lan == 1 and self.lan != 1:
            self.lan = 1
            print("[MainWindow] Change to English")
            self.trans.load("en")
        else:
            return
        _app = QApplication.instance()
        _app.installTranslator(self.trans)
        self.retranslateUi(self)

    def destinationLanguage(self, lan):
        """:author : Tich
        :param lan: 0: Chinese, 1: English, 2: Japanese, 3: Korean
        change destination language
        """
        if lan == 0:
            self.dest = 'zh-CN'
        elif lan == 1:
            self.dest = 'en'
        elif lan == 2:
            self.dest = 'ja'
        elif lan == 3:
            self.dest = 'ko'
        else:
            self.dest = 'en'
        print(self.dest)

    def transTextToZhCN(self):
        text = self.originText.toPlainText()
        if text:
            try:
                # self.transText.setPlainText(trans_To_zh_CN(text))
                # print(text)
                if self.paperMode.isChecked(
                ):  # if paper mode is true, line breaks will re replaced by blanks
                    text = re.sub(r'\n|\s+', ' ', text)
                    text = re.sub(r'', '', text)
                self.originText.setPlainText(text)
                self.t = GTranslator(self.dest, text)
                self.t.start()
                self.transText.setPlainText("")
                self.transText.setPlaceholderText("...")
                self.t.trigger.connect(self.translated)
            except Exception as e:
                print(e.args[1])
                self.transText.setPlainText("error!")

    def translated(self):
        global GTransData
        if GTransData:
            self.transText.setPlainText(GTransData)
        else:
            self.transText.setPlainText("error!")
        GTransData = ""

    def alwaysFrontFunc(self):
        """change window status
        """
        if self.alwaysFront.isChecked():
            # print("Front", self.windowFlags())
            self.setWindowFlags(self.windowFlags()
                                | Qt.WindowStaysOnTopHint)  # always top
            self.show()
        else:
            # print("Back", self.win.windowFlags())
            self.setWindowFlags(Qt.Widget)
            self.show()

    def realTimeTransFunc(self):
        """real-time translate
        this fearure is for paper mode
        """
        # print(self.isRealTimeTrans)
        self.isRealTimeTrans = self.realTimeTrans.isChecked()

    def copySlot(self):
        s = self.transText.toPlainText()
        if s:
            self.isCopyFromTrans = True
            clipboard = QApplication.clipboard()
            clipboard.setText(s)

    def onClipboradChanged(self):
        if self.isCopyFromTrans:
            self.isCopyFromTrans = False
            return
        clipboard = QApplication.clipboard()
        text = clipboard.text()
        if text and self.isRealTimeTrans:
            content = str(text)
            # print(content)
            if self.paperMode.isChecked(
            ):  # if paper mode is true, line breaks will re replaced by blanks
                content = re.sub(r'\n|\s+', ' ', content)
                content = re.sub(r'', '', content)
            self.originText.setPlainText(content)
            try:
                # data = trans_To_zh_CN(content)
                # self.transText.setPlainText(data)
                self.t = GTranslator(self.dest, content)
                self.t.start()
                self.transText.setPlainText("")
                self.transText.setPlaceholderText("...")
                self.t.trigger.connect(self.translated)
            except:
                self.transText.setPlainText("error!")
Esempio n. 46
0
class LayerQuery:
    """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',
                                   'LayerQuery_{}.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 = LayerQueryDialog()

        # Declare instance attributes
        self.actions = []
        self.menu = self.tr(u'&Layer Query')
        # TODO: We are going to let the user set this up in a future iteration
        self.toolbar = self.iface.addToolBar(u'LayerQuery')
        self.toolbar.setObjectName(u'LayerQuery')

    # 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('LayerQuery', 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/layer_query/icon.png'
        self.add_action(icon_path,
                        text=self.tr(u'Query layer attributes'),
                        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'&Layer Query'), 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
Esempio n. 47
0
    )
    parser.add_argument(
        '-p',
        '--path',
        help=
        'path to directory with recordings without trailing slash, e.g. file:///home/bob/video'
    )
    args = parser.parse_args()
    # setup Qt application
    style_argv = ['--style', 'Fusion']
    app = QGuiApplication(style_argv)
    app.setWindowIcon(QIcon("images/icon.png"))
    app.setOrganizationName('Christian Wichmann')
    app.setApplicationName('Schnipp!')
    # handle translations
    translator = QTranslator()
    translator.load('i18n/{}.qm'.format(QLocale.system().name()))
    app.installTranslator(translator)
    # start application
    engine = QQmlApplicationEngine()
    fileIO = FileIO()
    engine.rootContext().setContextProperty('FileIO', fileIO)
    imageProcessing = ImageProcessing()
    engine.rootContext().setContextProperty('ImageProcessing', imageProcessing)
    if args.path:
        engine.rootContext().setContextProperty('args', args.path)
    engine.load('schnipp.qml')
    if not engine.rootObjects():
        sys.exit(-1)
    sys.exit(app.exec_())
Esempio n. 48
0
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 == OS.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 == OS.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()
Esempio n. 49
0
    debug = parsed_args.debug
    executable = parsed_args.executable

    app = QApplication(sys.argv)
    app.setApplicationName("RaySession")
    # app.setApplicationVersion(ray.VERSION)
    app.setOrganizationName("RaySession")
    app.setQuitOnLastWindowClosed(False)
    settings = QSettings()
    
    signal.signal(signal.SIGINT, signalHandler)
    signal.signal(signal.SIGTERM, signalHandler)

    # Translation process
    locale = QLocale.system().name()
    appTranslator = QTranslator()
    
    if appTranslator.load(
        "%s/locale/raysession_%s" %
        (os.path.dirname(
            os.path.dirname(
                os.path.dirname(
                    sys.argv[0]))),
         locale)):
        app.installTranslator(appTranslator)
    _translate = app.translate

    timer = QTimer()
    timer.setInterval(200)
    timer.timeout.connect(lambda: None)
    timer.start()
Esempio n. 50
0
from PyQt5.QtCore import Qt
from PyQt5.QtCore import QLocale

__author__ = "Deokyu Lim <*****@*****.**>"


class Form(QWidget):
	def __init__(self):
		QWidget.__init__(self, flags=Qt.Widget)
		self.init_widget()

	def init_widget(self):
		self.setWindowTitle(self.tr("Hello World"))

if __name__ == "__main__":
	app = QApplication(sys.argv)

	# 다국어 지원
	translator = QTranslator()
	translator.load("translate\ko_KR.qm")

	# 현재 시스템 로케일 이름을 출력
	tr_path = "translate\\" + QLocale.system().name() + ".qm"
	print(tr_path)
	# translator.load(tr_path)  # 여기선 사용하지 않으므로 주석

	app.installTranslator(translator)

	form = Form()
	form.show()
	exit(app.exec_())
Esempio n. 51
0
def maximizeWindow(self):
    try:
        window.showMaximized()
    except BaseException as e:
        QMessageBox.information(self, "Warning", str(e))


if __name__ == "__main__":
    app = QApplication(sys.argv)
    if platform.system() == 'Windows':
        app.setStyle(QStyleFactory.create('WindowsVista'))
    # for retina
    if platform.system() == 'Darwin':
        app.setAttribute(Qt.AA_EnableHighDpiScaling, True)
    myLocale = QLocale()
    trans = QTranslator()
    g = genlist_api.Genlist()
    i18nQm = g.resource_path(
        os.path.join('i18n', 'checklister_' + myLocale.name() + '.qm'))
    trans.load(i18nQm)
    app.installTranslator(trans)
    window = MainWindow()
    window.show()
    # window zoom/min/max
    window.actionMinimize.triggered.connect(minimizeWindow)
    window.actionZoom.triggered.connect(normalWindow)
    window.actionMaximize.triggered.connect(maximizeWindow)

    sys.exit(app.exec_())
Esempio n. 52
0
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:
            # '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', '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)
        self.lang_comboBox.currentIndexChanged.connect(
            self.styleComboBoxChanged)
        self.styleComboBoxChanged()

        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()

        # 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))

        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)

# 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)

            # get current language
            selected_language = self.lang_comboBox.currentText()

            # some color schemes wouldn't work properly with Persian language.
            if selected_language == 'فارسی':
                # color_comboBox items
                color_scheme = [
                    'Persepolis Light Blue', 'Persepolis Dark Blue'
                ]

                # add items
                self.color_comboBox.addItems(color_scheme)

                # set 'Persepolis Light Blue' for color_scheme
                current_color_index = self.color_comboBox.findText(
                    'Persepolis Light Blue')
                self.color_comboBox.setCurrentIndex(current_color_index)

            else:
                # color_comboBox items
                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'
                ]

                # add items
                self.color_comboBox.addItems(color_scheme)

                # set 'Persepolis Light Blue' for color_scheme
                current_color_index = self.color_comboBox.findText(
                    'Persepolis Light Blue')
                self.color_comboBox.setCurrentIndex(current_color_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)

    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)

        # 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 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)

# 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
        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()
Esempio n. 53
0
    def beginFinalInit(self):
        """
        @see: startup
        Notice the __init__ method . we just setup the basic widget.
        And after the language , style ,plugins etc had loaded .
        we call this method . 
        
        Never call it unless you know what's it
        """
        #when at linux platform . the icon is not visible at menu .
        for key in self.__actions.keys():
            self.__actions.get(key).setIconVisibleInMenu(True)

        #--------------->>Seeking init <<-----------------#
        # __init__ menu
        self.getMenu("settings").addAction(self.getAction("perferences"))

        #i18n , must restart program to make it in use
        action_languages = QAction(
            QIcon(getPath('iconDir', 'languages.png')),
            QApplication.translate("default", "Languages"), self)
        action_languages.setIconVisibleInMenu(True)
        menu_languages = QMenu(self)

        trans_dir = QDir(getPrccisePath("transDir", "", "coredir"))
        fileNames = trans_dir.entryList(['i18n*.qm'], QDir.Files, QDir.Name)
        qmFiles = [trans_dir.filePath(fn) for fn in fileNames]

        for qmf in qmFiles:
            translator = QTranslator()
            translator.load(qmf)
            action = menu_languages.addAction(
                translator.translate("default", "English"))
            action.triggered.connect(lambda re, locale=translator.translate(
                "default", "locale"): self.__evt_changeLanguage(locale))

        action_languages.setMenu(menu_languages)
        self.getMenu("settings").addAction(action_languages)

        #style menu use signalmapper
        action_style = QAction(QIcon(getPath('iconDir', 'style.png')),
                               QApplication.translate("default", "Style"),
                               self)
        action_style.setIconVisibleInMenu(True)
        menu_style = QMenu(self)
        for style_item in QStyleFactory.keys():
            action = menu_style.addAction(style_item)
            action.triggered.connect(
                lambda re, style_item=style_item: changeStyle(style_item))
        action_style.setMenu(menu_style)
        self.getMenu("settings").addAction(action_style)

        menu_plugin = self.getMenu("plugins")

        menu_plugin.addAction(self.getAction("plguinInfos"))

        menu_plugin.addSeparator()
        menu_plugin.addAction(self.getAction("plguinRequest"))

        #--------------->>Seeking init <<-----------------#
        # __init__ toolbar
        toolBar = self.addToolBar(QApplication.translate("default", "common"))

        toolBar.addAction(self.getAction("perferences"))
        toolBar.addAction(self.getAction("close"))
        toolBar.addAction(self.getAction("gotohome"))
        toolBar.addAction(self.getAction("help"))

        #--------------->>Seeking init <<-----------------#
        # __init__ status bar
        self.statusBar().showMessage("Seeking ...")

        #--------------->>Seeking init <<-----------------#
        #Effects of a loading progress .
        #Results appear in the tab of the interior, the window has no effect on the global
        self.overlay = Overlay(self.centralWidget())
        self.overlay.hide()

        #--------------->>Seeking init <<-----------------#
        #other
        self.emit(SIGNAL('updateWindows()'))
Esempio n. 54
0
    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:
            # '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', '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)
        self.lang_comboBox.currentIndexChanged.connect(
            self.styleComboBoxChanged)
        self.styleComboBoxChanged()

        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()

        # 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))

        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)
Esempio n. 55
0
class AutoFieldsProximus:
    """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',
                                   'AutoFieldsProximus_{}.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'&Auto Fields Proximus')

        # 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('AutoFieldsProximus', 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/auto_fields_proximus/icon.png'
        self.add_action(icon_path,
                        text=self.tr(u'Updates fields automatically'),
                        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'&Auto Fields Proximus'),
                                        action)
            self.iface.removeToolBarIcon(action)

    def run(self):
        """Run method that performs all the real work"""
        result = 1
        if result == 1:
            # Do something useful here - delete the line containing pass and
            # substitute with your code.
            requested_layers = [
                'dtps', 'subd_micr', 'ducts', 'phases', 'manholes', 'zones',
                'dtps_fttb', 'subd_micr_fttb', 'ducts_fttb', 'phases_fttb',
                'manholes_fttb', 'zones_fttb', 'copper_cables',
                'street_cabinet', 'splices', 'trenches'
            ]

            project = QgsProject.instance()

            #Global variables
            QgsExpressionContextUtils.setProjectVariable(
                project, 'herbestrating', '0')
            herbestrating = float(
                QgsExpressionContextUtils.projectScope(project).variable(
                    'herbestrating'))

            #Template Version to not remove old functionality
            template_version = QgsExpressionContextUtils.projectScope(
                project).variable('version')
            if template_version == NULL:
                template_version = 'depreciated_version'

#
#            QgsExpressionContextUtils.setProjectVariable(project,'myvar','Hello World!')
#            QgsExpressionContextUtils.projectScope(project).variable('myvar')

#uc = unitcost

            def calculate_fields_subd_micr():
                print("StartSubd_micro__")
                lyr.startEditing()
                id = lyr.dataProvider().fieldNameIndex('id')
                code = lyr.dataProvider().fieldNameIndex('code')
                lengt_subd = lyr.dataProvider().fieldNameIndex(
                    'lengt_subd')  #f[2]
                lengt_micr = lyr.dataProvider().fieldNameIndex('lengt_micr')
                cost_tot = lyr.dataProvider().fieldNameIndex('cost_tot')
                dtps = lyr.dataProvider().fieldNameIndex('dtps')
                phase_nr = lyr.dataProvider().fieldNameIndex('phase_nr')
                print(id, code, lengt_subd, lengt_micr, cost_tot, dtps,
                      phase_nr)

                uc_subd = 3.08
                uc_micr = 3.11

                for f in my_features:
                    #Variables
                    geolength = f.geometry().length()

                    f[id] = f.id()  # feature id
                    # Lengte microcable: code like micr en overlengte dtps
                    if f[code] in ['MICRO']:
                        print("micro")
                        # Microcable check
                        f[lengt_micr] = round(geolength) + (8 * f[dtps])

                        # No subduct
                        f[lengt_subd] = 0

                    elif f[code] in ['SUBD']:
                        print("subduct")
                        # No microcable
                        f[lengt_micr] = 0

                        # Subduct check
                        f[lengt_subd] = round(geolength)

                    elif f[code] in ['SUBD_MICRO']:
                        print("Subduct_micro")
                        # Microcable check
                        f[lengt_micr] = round(geolength) + (8 * f[dtps])

                        # Subduct check
                        f[lengt_subd] = round(geolength)

                    else:
                        print("not found")
                        f[lengt_micr] = 0
                        f[lengt_subd] = 0

                    f[cost_tot] = round(f[lengt_subd] * uc_subd +
                                        f[lengt_micr] * uc_micr)
                    lyr.updateFeature(f)
                lyr.commitChanges()

            def calculate_fields_ducts():
                print("StartDucts__")
                lyr.startEditing()
                id = lyr.dataProvider().fieldNameIndex('id')
                lengt_duct = lyr.dataProvider().fieldNameIndex('lengt_duct')
                cost_tot = lyr.dataProvider().fieldNameIndex('cost_tot')
                diameter = lyr.dataProvider().fieldNameIndex('diameter')
                type = lyr.dataProvider().fieldNameIndex('type')
                phase_nr = lyr.dataProvider().fieldNameIndex('phase_nr')
                ofp_nr = lyr.dataProvider().fieldNameIndex('ofp_nr')
                print(id, lengt_duct, cost_tot, diameter, type, phase_nr,
                      ofp_nr)

                uc_trench = 13.2
                uc_repav = 33
                uc_drill_pit = 298
                uc_drill = 97.90
                uc_area_repav = 59.40

                uc_duct = 11.72

                print(template_version)

                for f in my_features:
                    f[id] = f.id()  # feature id
                    f[lengt_duct] = round(f.geometry().length())
                    lyr.updateFeature(f)

                    if template_version == 'depreciated_version':
                        if f[type].lower() == 'buis':
                            f[cost_tot] = round(f[lengt_duct] *
                                                (uc_trench + uc_duct +
                                                 uc_repav * herbestrating))
                        elif f[type].lower() == 'double':
                            f[cost_tot] = round(f[lengt_duct] *
                                                (uc_trench + 2 * uc_duct +
                                                 uc_repav * herbestrating))
                        elif f[type].lower() == 'triple':
                            f[cost_tot] = round(f[lengt_duct] *
                                                (uc_trench + 3 * uc_duct +
                                                 uc_repav * herbestrating))
                        elif f[type].lower() == 'bo':
                            f[cost_tot] = round(
                                (f[lengt_duct] * uc_drill) -
                                (f[lengt_duct] *
                                 (uc_trench + uc_repav * herbestrating)) +
                                uc_drill_pit + (2 * 2.5 * uc_area_repav))
                        elif f[type].lower() == 'ov':
                            f[cost_tot] = round(f[lengt_duct] *
                                                (uc_repav *
                                                 (1 - herbestrating)))
                        else:
                            f[cost_tot] = round(f[lengt_duct] *
                                                (uc_trench + uc_duct +
                                                 uc_repav * herbestrating))

                    else:
                        if f[type].lower() == 'buis':
                            f[cost_tot] = round(f[lengt_duct] * (uc_duct))
                        elif f[type].lower() == 'intro':
                            f[cost_tot] == round(f[lengt_duct] * (uc_duct))

                    lyr.updateFeature(f)
                lyr.commitChanges()

            def calculate_fields_dtps():
                print("Startdtps__")
                lyr.startEditing()
                id = lyr.dataProvider().fieldNameIndex('id')
                cluster = lyr.dataProvider().fieldNameIndex('cluster')
                dtp = lyr.dataProvider().fieldNameIndex('dtp')
                units_a = lyr.dataProvider().fieldNameIndex('units_a')
                units_b = lyr.dataProvider().fieldNameIndex('units_b')
                fiber = lyr.dataProvider().fieldNameIndex('fiber')
                cost_tot = lyr.dataProvider().fieldNameIndex('cost_tot')
                phase_nr = lyr.dataProvider().fieldNameIndex('phase_nr')
                comments = lyr.dataProvider().fieldNameIndex('comments')
                ofp = lyr.dataProvider().fieldNameIndex('ofp')
                print(id, cluster, dtp, units_a, units_b, fiber, cost_tot,
                      phase_nr, comments, ofp)

                uc_dtp = 303.8
                uc_fiber_joint = 23.8

                for f in my_features:
                    f[id] = f.id()  # feature id
                    f[cost_tot] = round(uc_dtp +
                                        (f[fiber] * uc_fiber_joint)) + 240

                    lyr.updateFeature(f)
                lyr.commitChanges()

            def calculate_fields_phases():
                print("StartPhases__")
                lyr.startEditing()
                id = lyr.dataProvider().fieldNameIndex('id')
                cost_ofp = lyr.dataProvider().fieldNameIndex('cost_ofp')
                phase_nr = lyr.dataProvider().fieldNameIndex('phase_nr')
                total_cost = lyr.dataProvider().fieldNameIndex('total_cost')
                job_id = lyr.dataProvider().fieldNameIndex('job_id')
                path = lyr.dataProvider().fieldNameIndex('path')
                unit_cost = lyr.dataProvider().fieldNameIndex('unit_cost')
                ofp_amount = lyr.dataProvider().fieldNameIndex('ofp_amount')
                print(id, cost_ofp, phase_nr, total_cost, job_id, path,
                      unit_cost, ofp_amount)  #phase nr -1 wordt 2
                print("phases")

                #Must be deleted soon! (Calculation moved to manholes)
                uc_ofp = 4902
                uc_ov_joint = 421

                for f in my_features:
                    f[id] = f.id()  # feature id
                    #                    lyr.updateFeature(f)
                    if f[ofp_amount] == NULL:
                        f[cost_ofp] = 0
                    else:
                        f[cost_ofp] = f[ofp_amount] * (uc_ofp + uc_ov_joint)

                    if f[job_id] == NULL:
                        pass
                    else:
                        f[path] = 'https://intra.web.bc/JMS/ejms/bridge/app/job?ID=' + f[
                            job_id]

                    if f[phase_nr] == NULL or f[phase_nr] < 0:
                        f[phase_nr] = f[id] + 1
                    else:
                        pass

                    #Phases total_cost and unit_cost: TO DO

                    lyr.updateFeature(f)
                lyr.commitChanges()

            def calculate_fields_zones():
                print("StartZones__")
                lyr.startEditing()
                id = lyr.dataProvider().fieldNameIndex('id')
                cost_ofp = lyr.dataProvider().fieldNameIndex('cost_ofp')
                zone_nr = lyr.dataProvider().fieldNameIndex('zone_nr')
                total_cost = lyr.dataProvider().fieldNameIndex('total_cost')
                job_id = lyr.dataProvider().fieldNameIndex('job_id')
                path = lyr.dataProvider().fieldNameIndex('path')
                unit_cost = lyr.dataProvider().fieldNameIndex('unit_cost')
                ofp_amount = lyr.dataProvider().fieldNameIndex('ofp_amount')
                print(id, cost_ofp, zone_nr, total_cost, job_id, path,
                      unit_cost, ofp_amount)
                print("zones")

                #Must be deleted soon! (Calculation moved to manholes)
                uc_ofp = 4902
                uc_ov_joint = 421

                for f in my_features:
                    f[id] = f.id()  # feature id
                    f[cost_ofp] = f[ofp_amount] * (uc_ofp + uc_ov_joint)
                    if f[job_id] == NULL:
                        pass
                    else:
                        f[path] = 'https://intra.web.bc/JMS/ejms/bridge/app/job?ID=' + f[
                            job_id]

                    #Phases total_cost and unit_cost: TO DO

                    if f[zone_nr] == NULL or f[zone_nr] < 0:
                        f[zone_nr] = f[id] + 1
                    else:
                        pass

                    lyr.updateFeature(f)
                lyr.commitChanges()

            def calculate_fields_manholes():
                print("Manholes__")
                lyr.startEditing()
                id = lyr.dataProvider().fieldNameIndex('id')
                cost = lyr.dataProvider().fieldNameIndex('cost')
                subtype = lyr.dataProvider().fieldNameIndex('subtype')
                phase_nr = lyr.dataProvider().fieldNameIndex('phase_nr')
                angle = lyr.dataProvider().fieldNameIndex('angle')
                ofp = lyr.dataProvider().fieldNameIndex('ofp')
                print(id, cost, subtype, phase_nr, angle, ofp)

                for f in my_features:

                    uc_manhole = 2196
                    uc_ofp = 4902
                    uc_ov_joint = 421

                    f[id] = f.id()  # feature id
                    if f[ofp] != NULL:
                        num_ofp = int(f[ofp])
                    else:
                        num_ofp = 0

                    if f[subtype] in [
                            'T Branch', 'End Cap', 'Link', 'CR', 'Cable Room',
                            'Virtual Manhole', 'Left-right coupling',
                            'OFP bestaande bak'
                    ]:
                        f[cost] = 0
                    else:
                        f[cost] = uc_manhole
#If there is an amount of ofp's, update cost
                    if num_ofp == NULL or num_ofp <= 0:
                        pass
                    else:
                        f[cost] = f[cost] + num_ofp * uc_ofp
                    lyr.updateFeature(f)
                lyr.commitChanges()

            def calculate_fields_copper_cables():
                print("Start_Copper_cables__")
                lyr.startEditing()
                id = lyr.dataProvider().fieldNameIndex('id')
                cable_code = lyr.dataProvider().fieldNameIndex('cable_code')
                length = lyr.dataProvider().fieldNameIndex('length')
                subnet = lyr.dataProvider().fieldNameIndex('subnet')
                dbb = lyr.dataProvider().fieldNameIndex('dbb')
                cost = lyr.dataProvider().fieldNameIndex('cost')
                workorder = lyr.dataProvider().fieldNameIndex('workorder')
                print(id, cable_code, length, subnet, dbb, cost, workorder)

                uc_copper_cable = 9.52

                for f in my_features:
                    f[id] = f.id()  # feature id
                    f[length] = round(f.geometry().length())
                    lyr.updateFeature(f)

                    # Te leggen koperkabels
                    if workorder == 'Te leggen':
                        f[cost] = round(f[length] * uc_copper_cable)

                    #Anders: te verwijderen koperkabels (nog te veranderen) []
                    else:
                        f[cost] = round(f[length] * uc_copper_cable)

                    lyr.updateFeature(f)

                lyr.commitChanges()

            def calculate_fields_street_cabinet():
                print("Street_cabinet")
                lyr.startEditing()
                id = lyr.dataProvider().fieldNameIndex('id')
                name = lyr.dataProvider().fieldNameIndex('name')
                type = lyr.dataProvider().fieldNameIndex('type')
                workorder = lyr.dataProvider().fieldNameIndex('workorder')
                cost = lyr.dataProvider().fieldNameIndex('cost')
                print(id, name, type, workorder, cost)

                for f in my_features:
                    f[id] = f.id()  # feature id
                    lyr.updateFeature(f)

                    #                    # Te leggen koperkabels
                    #                    if workorder == 'te plaatsen':
                    #                        #kost moet hier komen
                    #                        f[cost] = f[cost]
                    #
                    #                    #Anders: te verwijderen koperkabels (nog te veranderen) []
                    #                    else:
                    #                        f[cost] = f[cost]

                    lyr.updateFeature(f)

                lyr.commitChanges()

            def calculate_fields_splices():
                print("Splices")
                lyr.startEditing()
                id = lyr.dataProvider().fieldNameIndex('id')
                splice_typ = lyr.dataProvider().fieldNameIndex('splice_typ')
                las_A = lyr.dataProvider().fieldNameIndex('las_A')
                las_B = lyr.dataProvider().fieldNameIndex('las_B')
                subnet_nr = lyr.dataProvider().fieldNameIndex('subnet_nr')
                descr = lyr.dataProvider().fieldNameIndex('descr')
                dbb = lyr.dataProvider().fieldNameIndex('dbb')
                Cost = lyr.dataProvider().fieldNameIndex('Cost')
                print(id, splice_typ, las_A, las_B, subnet_nr, descr, dbb,
                      Cost)

                uc_lasput = 153
                uc_pairs = 2.03  # of 1.73?

# Cost = Aantal te lassen paren + lasput

#cost = (las_A + las_B)//2 * uc_pairs + uc_lasput

            def calculate_fields_trenches():
                print("Trenches")
                lyr.startEditing()
                id = lyr.dataProvider().fieldNameIndex('id')
                trench_len = lyr.dataProvider().fieldNameIndex('trench_len')
                type = lyr.dataProvider().fieldNameIndex('type')
                phase_nr = lyr.dataProvider().fieldNameIndex('phase_nr')
                cost_tot = lyr.dataProvider().fieldNameIndex('cost_tot')
                repav_leng = lyr.dataProvider().fieldNameIndex('repav_leng')

                print(id, trench_len, type, phase_nr, cost_tot, repav_leng)

                uc_trench = 13.2
                #                uc_duct = 11.72
                uc_repavement = 33
                uc_drill_pit = 298
                uc_drill = 97.90
                uc_area_repav = 59.40

                for f in my_features:
                    f[id] = f.id()  # feature id
                    f[trench_len] = round(f.geometry().length())
                    lyr.updateFeature(f)

                    repavement_cost = uc_repavement * f[repav_leng]

                    if f[type] == 'enkel sleuf':
                        f[cost_tot] = round(f[trench_len] * uc_trench +
                                            repavement_cost)
                    elif f[type] == 'boring':
                        #                        repavement_cost = 0
                        #drilling cost: drilling length cost and 2 pits of 2.5 * unitaire cost area
                        f[cost_tot] = round(f[trench_len] * uc_drill +
                                            uc_drill_pit +
                                            (2 * 2.5 * uc_area_repav))

                    #formule? + drilling_cost
                    elif f[type] == 'oversteek':
                        repavement_cost = uc_repavement * trench_len
                        f[cost_tot] = round(f[trench_len] * uc_trench +
                                            repavement_cost)
                    else:
                        pass
                    print(f[cost_tot])
                    lyr.updateFeature(f)
                lyr.commitChanges()

            def calculate_fields_copper_cables():
                print("Copper_cables")
                lyr.startEditing()
                id = lyr.dataProvider().fieldNameIndex('id')
                cable_code = lyr.dataProvider().fieldNameIndex('cable_code')
                length = lyr.dataProvider().fieldNameIndex('length')
                cost = lyr.dataProvider().fieldNameIndex('cost')
                workorder = lyr.dataProvider().fieldNameIndex('workorder')

                for f in my_features:
                    cable_codes_uc = {8322006: 15.7}

                    f[length] = f.geometry().length()
                    print(f[length])
                    #        cable_code_key = f[cable_code]
                    #        print(cable_code_key)

                    if f[workorder].lower() == 'te leggen':
                        #            print(cable_code_key)
                        print(cable_codes_uc.get(f[cable_code]))
                        f[cost] = cable_codes_uc.get(f[cable_code]) * f[length]
                        print(f[cost])

                    lyr.updateFeature(f)
                lyr.commitChanges()

#            def get_layer():
#                layer_name = lyr.name()
#
#                if layer_name == 'dtps' or layer_name == 'dtps_fttb':
#                    calculate_fields_dtps()
#
#                elif layer_name == 'manholes' or layer_name == 'manholes_fttb':
#                    calculate_fields_manholes()
#
#                elif layer_name == 'subd_micr' or layer_name == 'subd_micr_fttb':
#                    calculate_fields_subd_micr()
#
#                elif layer_name == 'ducts' or layer_name == 'ducts_fttb':
#                    calculate_fields_ducts()
#
#                elif layer_name == 'phases' or layer_name == 'phases_fttb':
#                    calculate_fields_phases()
#
#                elif layer_name == 'zones' or layer_name == 'zones_fttb':
#                    calculate_fields_zones()
#
#                elif layer_name == 'copper_cables':
#                    calculate_fields_copper_cables()
#
#                elif layer_name == 'street_cabinet':
#                    calculate_fields_street_cabinet()
#
#                elif layer_name == 'splices':
#                    calculate_fields_splices()
#
#                elif layer_name == 'trenches':
#                    print('******************************')
#                    calculate_fields_trenches()
#
#                else:
#                    print("Do nothing")
#                    pass

            for lyr in QgsProject.instance().mapLayers().values():
                if lyr.name() in requested_layers:
                    #Save before starting the process
                    lyr.commitChanges()
                    my_features = lyr.getFeatures()
                    #                    print(lyr.name(), my_features)
                    #                    get_layer()

                    #To catch if requested layers don't have functions
                    try:
                        calculateFields = 'calculate_fields_' + lyr.name()
                        locals()[calculateFields]()
                    except:
                        pass
                else:
                    pass
                success = 1

            if success == 1:
                self.iface.messageBar().pushMessage(
                    "Success",
                    "Fields updated succesfully",
                    level=Qgis.Success,
                    duration=5)
            else:
                self.iface.messageBar().pushMessage(
                    "Error",
                    "Make sure to fill in all required fields",
                    level=Qgis.Critical)
Esempio n. 56
0
class MainWindow(QMainWindow, Ui_MainWindow):

    def __init__(self):

        super(MainWindow, self).__init__()
        self.setupUi(self)

        self.initialize()
        # Connect slots function.
        self.connect_slots()
        self.get_fdem_simulation_parameters()

    def initialize(self):

        # Set the display position of the mainwindow.
        desktop = QApplication.desktop()
        x = (desktop.width() - self.width()) // 2
        y = (desktop.height()-65 - self.height()) // 2
        self.move(x, y)

        # Desine the translator to translate interface languages.
        self.trans = QTranslator(self)
        # Define the Result class to record the results in the process.
        self.result = Result()
        # Define the fdem forward simulation thread class.
        self.thread_cal_fdem = ThreadCalFdem()
        # Define the fdem inversion thread class.
        self.thread_inv_fdem = ThreadInvFdem()

        # Define the figure to show data in the interface.
        self.fig_scenario = Figure(figsize=(4.21, 3.91))
        self.canvas_scenario = FigureCanvasQTAgg(self.fig_scenario)
        self.gl_detection_scenario.addWidget(self.canvas_scenario)

        self.fig_discretize = Figure(figsize=(4.21, 3.91))
        self.canvas_discretize = FigureCanvasQTAgg(self.fig_discretize)
        self.gl_discretize.addWidget(self.canvas_discretize)

        self.fig_magnetic_field = Figure(figsize=(4.21, 3.91))
        self.canvas_magnetic_field = FigureCanvasQTAgg(self.fig_magnetic_field)
        self.gl_magnetic_field_data.addWidget(self.canvas_magnetic_field)

        self.pbar_rfs.setVisible(False)
        self.pbar_rfi.setVisible(False)

    def connect_slots(self):

        # When the forward calculation of FDEM is finished, the result process
        # function will be called.
        self.thread_cal_fdem.trigger.connect(self.run_fdem_forward_result_process)
        # When the FDEM inversion is finished, the result process function will
        # be called.
        self.thread_inv_fdem.trigger.connect(self.run_fdem_inv_result_process)
        # When language is changed.
        self.actionChinese.triggered.connect(self.select_Chinese)
        self.actionEnglish.triggered.connect(self.select_English)
        # When detection method is changed.
        self.tab_signal_type.currentChanged.connect(
            self.select_detection_method)
        # When run inversion button is clicked in fdem.
        self.pb_run_fdem_inversion.clicked.connect(
            self.run_fdem_inversion)
        # When run forward simulation button is clicked in fdem.
        self.pb_run_fdem_forward_simulation.clicked.connect(
            self.run_fdem_forward_calculate)

        # When parameters are update in fdem interface.
        self.le_detector_radius.editingFinished.connect(
            self.get_fdem_simulation_parameters)
        self.le_detector_current.editingFinished.connect(
            self.get_fdem_simulation_parameters)
        self.le_detector_frequency.editingFinished.connect(
            self.get_fdem_simulation_parameters)
        self.le_detector_pitch.editingFinished.connect(
            self.get_fdem_simulation_parameters)
        self.le_detector_roll.editingFinished.connect(
            self.get_fdem_simulation_parameters)
        self.le_target_conductivity.editingFinished.connect(
            self.get_fdem_simulation_parameters)
        self.le_target_permeability.editingFinished.connect(
            self.get_fdem_simulation_parameters)
        self.le_target_radius.editingFinished.connect(
            self.get_fdem_simulation_parameters)
        self.le_target_length.editingFinished.connect(
            self.get_fdem_simulation_parameters)
        self.le_target_pitch.editingFinished.connect(
            self.get_fdem_simulation_parameters)
        self.le_target_roll.editingFinished.connect(
            self.get_fdem_simulation_parameters)
        self.le_target_position_x.editingFinished.connect(
            self.get_fdem_simulation_parameters)
        self.le_target_position_y.editingFinished.connect(
            self.get_fdem_simulation_parameters)
        self.le_target_position_z.editingFinished.connect(
            self.get_fdem_simulation_parameters)
        self.le_collection_spacing.editingFinished.connect(
            self.get_fdem_simulation_parameters)
        self.le_collection_height.editingFinished.connect(
            self.get_fdem_simulation_parameters)
        self.le_collection_SNR.editingFinished.connect(
            self.get_fdem_simulation_parameters)
        self.le_collection_x_min.editingFinished.connect(
            self.get_fdem_simulation_parameters)
        self.le_collection_x_max.editingFinished.connect(
            self.get_fdem_simulation_parameters)
        self.le_collection_y_min.editingFinished.connect(
            self.get_fdem_simulation_parameters)
        self.le_collection_y_max.editingFinished.connect(
            self.get_fdem_simulation_parameters)
        self.cb_collection_direction.currentIndexChanged.connect(
            self.get_fdem_simulation_parameters)
        self.cb_optimization_algorithm.currentIndexChanged.connect(
            self.get_fdem_simulation_parameters)
        self.le_optimization_tol.editingFinished.connect(
            self.get_fdem_simulation_parameters)
        self.le_optimization_iterations.editingFinished.connect(
            self.get_fdem_simulation_parameters)

    def get_fdem_simulation_parameters(self):
        """
        When parameters are update in fdem interface, the parameters used for
        calculation will be updated.

        """

        self.detector = Detector(
            float(self.le_detector_radius.text()),
            float(self.le_detector_current.text()),
            float(self.le_detector_frequency.text()),
            float(self.le_detector_pitch.text()),
            float(self.le_detector_roll.text())
            )
        self.target = Target(
            float(self.le_target_conductivity.text()),
            float(self.le_target_permeability.text()),
            float(self.le_target_radius.text()),
            float(self.le_target_pitch.text()),
            float(self.le_target_roll.text()),
            float(self.le_target_length.text()),
            float(self.le_target_position_x.text()),
            float(self.le_target_position_y.text()),
            float(self.le_target_position_z.text())
            )
        self.collection = Collection(
            float(self.le_collection_spacing.text()),
            float(self.le_collection_height.text()),
            float(self.le_collection_SNR.text()),
            float(self.le_collection_x_min.text()),
            float(self.le_collection_x_max.text()),
            float(self.le_collection_y_min.text()),
            float(self.le_collection_y_max.text()),
            self.cb_collection_direction.currentText()
            )

        # Judge whether the current secondary field data can be directly used
        # in classification.
        self.result.check_fdem_mag_data = False

        # Update the detection scenario.
        show_fdem_detection_scenario(self.fig_scenario,
                                     self.target, self.collection)
        self.canvas_scenario.draw()

    def get_tdem_simulation_parameters(self):
        pass

    def run_fdem_forward_calculate(self):
        """
        When 'run forward simulation' button is clicked in fdem interface, this
        function will ba called.

        """

        # Disable buttons.
        self.pb_run_fdem_forward_simulation.setEnabled(False)
        self.pbar_rfs.setVisible(True)

        # Update the parameters in the thread.
        self.thread_cal_fdem.detector = self.detector
        self.thread_cal_fdem.target = self.target
        self.thread_cal_fdem.collection = self.collection

        # Output begin
        text = self.result.output_forward_begin()
        self.tb_output_box.setText(text)

        # show the fdem_forward porgram is running by progressbar
        self.pbar_rfs.setMinimum(0)  # let the progressbar to scroll
        self.pbar_rfs.setMaximum(0)  # let the progressbar to scroll

        # Start the thread.
        self.thread_cal_fdem.start()

    def run_fdem_forward_result_process(self, receiver_locs,
                                        mag_data, mesh, mapped_model):
        """
        When the forward calculation of FDEM is finished, the result process
        function will be called.

        """

        # Adding noise to the origin magnetic field data.
        mag_data = mag_data_add_noise(mag_data, self.collection.SNR)

        mag_data_total = np.sqrt(np.square(mag_data[:, 0])
                                 + np.square(mag_data[:, 1])
                                 + np.square(mag_data[:, 2]))

        if self.collection.collection_direction in ["x-axis", "x轴"]:
            mag_data_plotting = mag_data[:, 0]
        elif self.collection.collection_direction in ["y-axis", "y轴"]:
            mag_data_plotting = mag_data[:, 1]
        elif self.collection.collection_direction in ["z-axis", "z轴"]:
            mag_data_plotting = mag_data[:, 2]
        elif self.collection.collection_direction in ["Total", "总场"]:
            mag_data_plotting = mag_data_total

        # Plot discetize
        ind = int(mesh.hx.size / 2)
        range_x = [self.collection.x_min, self.collection.x_max]
        range_y = [-6, 0]
        show_discretize(self.fig_discretize, mesh, mapped_model, 'Y', ind,
                        range_x, range_y, self.target.conductivity)
        self.canvas_discretize.draw()

        # Plot secondary field.
        show_fdem_mag_map(self.fig_magnetic_field, receiver_locs,
                          mag_data_plotting)
        self.canvas_magnetic_field.draw()

        # Save the results to result class.
        self.result.fdem_mag_data = mag_data
        self.result.fdem_receiver_locs = receiver_locs

        if self.cb_func_save_data.isChecked():
            self.result.save_mag_data(self.get_save_fdem_dir())
        self.result.check_fdem_mag_data = True

        # Output finish information.
        text = self.result.output_forward_end()
        self.tb_output_box.setText(text)
        self.tab_show.setCurrentWidget(self.tab_magnetic_field_data)
        self.pb_run_fdem_forward_simulation.setEnabled(True)

        # let the progressBar stop scrolling,it means the  fdem_forward porgram is stoping
        self.pbar_rfs.setMaximum(100)
        self.pbar_rfs.setValue(100)

    def run_fdem_classification_calculate(self):
        pass

    def run_fdem_classification_result_process(self):
        pass

    def run_fdem_inversion(self):
        """
        When 'run fdem inversion' button is clicked in fdem interface, this
        function will ba called.
        """

        if self.result.check_fdem_mag_data is False:
            text = self.result.output_check_mag_data()
            self.tb_output_box.setText(text)
        else:
            self.pb_run_fdem_inversion.setEnabled(False)
            self.pbar_rfi.setVisible(True)

            # Constructing objective function
            self.thread_inv_fdem.fun = lambda x: inv_objective_function(
                self.detector, self.result.fdem_receiver_locs,
                self.result.fdem_mag_data, x)
            self.thread_inv_fdem.grad = lambda x: inv_objectfun_gradient(
                self.detector, self.result.fdem_receiver_locs,
                self.result.fdem_mag_data, x)
            self.thread_inv_fdem.jacobian = lambda x: inv_residual_vector_grad(
                self.detector, self.result.fdem_receiver_locs, x)

            # Update the parameters associated with the optimization algorithm.
            self.thread_inv_fdem.method = \
                self.cb_optimization_algorithm.currentText()
            self.thread_inv_fdem.iterations = \
                float(self.le_optimization_iterations.text())
            self.thread_inv_fdem.tol = float(self.le_optimization_tol.text())

            # Output begin
            text = self.result.output_data_process_begin()
            self.tb_output_box.setText(text)

            self.pbar_rfi.setMinimum(0)  # let the progressbar to scroll
            self.pbar_rfi.setMaximum(0)  # let the progressbar to scroll

            # Start the thread.
            self.thread_inv_fdem.start()

    def run_fdem_inv_result_process(self, estimate_parameters):

        estimate_properties = estimate_parameters[:3]
        est_ploar_and_orientation = \
            polar_tensor_to_properties(estimate_parameters[3:])
        estimate_properties = np.append(estimate_properties,
                                        est_ploar_and_orientation)
        self.result.fdem_estimate_properties = estimate_properties

        true_properties = np.array(self.target.position)
        true_polarizability = self.target.get_principal_axis_polarizability(
            self.detector.frequency)
        true_properties = np.append(true_properties, true_polarizability)
        true_properties = np.append(true_properties, self.target.pitch)
        true_properties = np.append(true_properties, self.target.roll)
        self.result.fdem_true_properties = true_properties
        self.result.fdem_estimate_error = abs(self.result.fdem_true_properties - self.result.fdem_estimate_properties)

        self.result.fdem_optimization_algorithm = \
            self.cb_optimization_algorithm.currentText()

        text = self.result.output_fdem_result()
        self.tb_output_box.setText(text)
        if self.cb_func_save_data.isChecked():
            self.result.save_result(self.get_save_fdem_dir())

        self.pb_run_fdem_inversion.setEnabled(True)
        self.pbar_rfi.setMaximum(100)
        self.pbar_rfi.setValue(100)

    def select_detection_method(self):
        """
        When detection method is changed, this function will be called.
        """

        if self.tab_signal_type.currentWidget() == self.tab_FDEM:
            self.pb_run_fdem_forward_simulation.setVisible(True)
            self.pb_run_fdem_inversion.setVisible(True)
            self.pb_run_tdem_forward_simulation.setVisible(False)
            self.pb_run_tdem_classification.setVisible(False)

            self.result.current_method = 'fdem'
            self.get_fdem_simulation_parameters()
        else:
            self.pb_run_fdem_forward_simulation.setVisible(False)
            self.pb_run_fdem_inversion.setVisible(False)
            self.pb_run_tdem_forward_simulation.setVisible(True)
            self.pb_run_tdem_classification.setVisible(True)

            self.result.current_method = 'tdem'

    def select_Chinese(self):
        """
        Translate English on the interface into Chinese.

        Referenceres
        ------------
        https://blog.csdn.net/CholenMine/article/details/80725088

        """
        self.trans.load('./translation/zh_CN')
        _app = QApplication.instance()
        _app.installTranslator(self.trans)
        self.retranslateUi(self)

        self.result.current_language = 'cn'

    def select_English(self):
        _app = QApplication.instance()
        _app.removeTranslator(self.trans)
        self.retranslateUi(self)

        self.result.current_language = 'en'

    def get_save_fdem_dir(self):
        """
        to get the parameters about this target scene to make fiel save the data about fdem_forward_simulation

        Returns
        -------
        file_name : str
            the file name to save the data about fdem_forward_simulation and fdem_inversion

        """
        file_name = "T.pos=[{:g},{:g},{:g}];T.R={:g};T.L={:g};T.pitch={:g};T.roll={:g};C.snr={:g};C.sp={:g};C.h={:g};" \
                    "C.x=[{:g},{:g}];" \
                    "C.y=[{:g},{:g}]".format(self.target.position[0], self.target.position[1],
                                             self.target.position[2],
                                             self.target.radius, self.target.length, self.target.pitch,
                                             self.target.roll,
                                             self.collection.SNR, self.collection.spacing, self.collection.height,
                                             self.collection.x_min, self.collection.x_max, self.collection.y_min,
                                             self.collection.y_max)
        return file_name
Esempio n. 57
0
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')

    try:
        # See https://github.com/retext-project/retext/issues/399
        # and https://launchpad.net/bugs/941826
        ctypes.CDLL('libGL.so.1', ctypes.RTLD_GLOBAL)
    except OSError:
        pass

    # Needed for Qt WebEngine on Windows
    QApplication.setAttribute(Qt.AA_ShareOpenGLContexts)
    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)
    initializeDataDirs()
    RtTranslator = QTranslator()
    for path in datadirs:
        if RtTranslator.load('retext_' + globalSettings.uiLanguage,
                             join(path, 'locale')):
            break
    QtTranslator = QTranslator()
    QtTranslator.load("qtbase_" + 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
    readStdIn = False
    if globalSettings.openLastFilesOnStartup:
        window.restoreLastOpenedFiles()
    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
        elif fileName == '-':
            readStdIn = True

    inputData = ''
    if readStdIn and sys.stdin is not None:
        if sys.stdin.isatty():
            print('Reading stdin, press ^D to end...')
        inputData = 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())
Esempio n. 58
0
class ClusterMap:
    """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',
                                   'Clustering_{}.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.provider = ClusteringProvider()

    # 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('ClusterMap', message)

    def initProcessing(self):
        self.provider = ClusteringProvider()
        QgsApplication.processingRegistry().addProvider(self.provider)

    def initGui(self):
        """Create the menu entries and toolbar icons inside the QGIS GUI."""
        #QgsApplication.processingRegistry().addProvider(self.provider)
        self.initProcessing()

        actionMeans = QAction(
            QIcon(
                os.path.join(os.path.dirname(__file__),
                             'clustering_provider/cluster2.png')),
            u"K-Means Clustering", self.iface.mainWindow())
        actionMeans.triggered.connect(self.runKmeans)

        actionHierarchical = QAction(
            QIcon(
                os.path.join(os.path.dirname(__file__),
                             'clustering_provider/hierarquico.png')),
            u"Hierarchical Clustering", self.iface.mainWindow())
        actionHierarchical.triggered.connect(self.runHierarchical)

        self.actions = [actionMeans, actionHierarchical]
        for action in self.actions:
            self.iface.addPluginToVectorMenu(u"&ClusterMap", action)
            self.iface.addToolBarIcon(action)

    def unload(self):
        QgsApplication.processingRegistry().removeProvider(self.provider)

        for action in self.actions:
            self.iface.removeToolBarIcon(action)
            self.iface.removePluginVectorMenu(u"&ClusterMap", action)
            del action

    def runKmeans(self):
        processing.execAlgorithmDialog("ClusterMap:kmeansclustering")

    def runHierarchical(self):
        processing.execAlgorithmDialog("ClusterMap:hierarchicalclustering")
Esempio n. 59
-4
    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)
Esempio n. 60
-5
    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")