Esempio n. 1
0
def main():
    signal.signal(signal.SIGINT, sigint_handler)
    
    app = QCoreApplication(sys.argv)
    
    ex = GUIServer()
    sys.exit(app.exec_())
Esempio n. 2
0
 def end(self):
     self.cleanup()
     # Remove the help tip set in mousePressEvent
     self.macro = None
     helpevent = QuickHelpTipEvent("", "")
     QCoreApplication.postEvent(self.document, helpevent)
     UserInteraction.end(self)
Esempio n. 3
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',
            'segreg_{}.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 = segregDialog()

        # Declare instance attributes
        self.actions = []
        self.menu = self.tr(u'&Segreg')
        # TODO: We are going to let the user set this up in a future iteration
        self.toolbar = self.iface.addToolBar(u'segreg')
        self.toolbar.setObjectName(u'segreg')
    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',
            '{}_{}.qm'.format(DelimitationToolbox.__modname__, 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.dock = None
Esempio n. 5
0
def startPlugin(packageName):
  """ initialize the plugin """
  global plugins, active_plugins, iface

  if packageName in active_plugins: return False

  package = sys.modules[packageName]

  errMsg = QCoreApplication.translate("Python", "Couldn't load plugin %1" ).arg(packageName)

  # create an instance of the plugin
  try:
    plugins[packageName] = package.classFactory(iface)
  except:
    _unloadPluginModules(packageName)
    msg = QCoreApplication.translate("Python", "%1 due an error when calling its classFactory() method").arg(errMsg)
    showException(sys.exc_type, sys.exc_value, sys.exc_traceback, msg)
    return False

  # initGui
  try:
    plugins[packageName].initGui()
  except:
    del plugins[packageName]
    _unloadPluginModules(packageName)
    msg = QCoreApplication.translate("Python", "%1 due an error when calling its initGui() method" ).arg( errMsg )
    showException(sys.exc_type, sys.exc_value, sys.exc_traceback, msg)
    return False

  # add to active plugins
  active_plugins.append(packageName)

  return True
Esempio n. 6
0
    def initGui(self):
        # Actions
        self.action_convert = QAction(QIcon(path.join(_current_path, 'convert.png')),
                                      QCoreApplication.translate('RuGeocoder', 'Convert CSV to SHP'),
                                      self.iface.mainWindow())
        QObject.connect(self.action_convert, SIGNAL("triggered()"), self.run_convert)

        self.action_batch_geocoding = QAction(QIcon(path.join(_current_path, 'icon.png')),
                                              QCoreApplication.translate('RuGeocoder', 'Batch geocoding'),
                                              self.iface.mainWindow())
        QObject.connect(self.action_batch_geocoding, SIGNAL('triggered()'), self.run_batch)

        self.action_quick_geocoding = self.__quick_tlb.toggleViewAction()
        self.action_quick_geocoding.setIcon(QIcon(path.join(_current_path, 'edit-find-project.png')))
        self.action_quick_geocoding.setText(QCoreApplication.translate('RuGeocoder', '&Quick geocoding toolbox'))

        # Add toolbar button and menu item
        self.toolbar.addAction(self.action_convert)
        self.iface.addPluginToWebMenu(self.menu_name, self.action_convert)

        self.toolbar.addAction(self.action_batch_geocoding)
        self.iface.addPluginToWebMenu(self.menu_name, self.action_batch_geocoding)

        self.toolbar.addSeparator()

        self.toolbar.addAction(self.action_quick_geocoding)
        self.iface.addPluginToWebMenu(self.menu_name, self.action_quick_geocoding)
Esempio n. 7
0
  def switchToolMode( self ):
      self.setCommandViewerEnabled( not self.batchCheck.isChecked() )
      self.progressBar.setVisible( self.batchCheck.isChecked() )

      self.inSelector.setType( self.inSelector.FILE if self.batchCheck.isChecked() else self.inSelector.FILE_LAYER )
      self.outSelector.clear()

      if self.batchCheck.isChecked():
        self.inFileLabel = self.label.text()
        self.outFileLabel = self.label_2.text()
        self.label.setText( QCoreApplication.translate( "GdalTools", "&Input directory" ) )
        self.label_2.setText( QCoreApplication.translate( "GdalTools", "&Output directory" ) )

        QObject.disconnect( self.inSelector, SIGNAL( "selectClicked()" ), self.fillInputFile )
        QObject.disconnect( self.outSelector, SIGNAL( "selectClicked()" ), self.fillOutputFileEdit )

        QObject.connect( self.inSelector, SIGNAL( "selectClicked()" ), self.fillInputDir )
        QObject.connect( self.outSelector, SIGNAL( "selectClicked()" ), self.fillOutputDir )
      else:
        self.label.setText( self.inFileLabel )
        self.label_2.setText( self.outFileLabel )

        QObject.disconnect( self.inSelector, SIGNAL( "selectClicked()" ), self.fillInputDir )
        QObject.disconnect( self.outSelector, SIGNAL( "selectClicked()" ), self.fillOutputDir )

        QObject.connect( self.inSelector, SIGNAL( "selectClicked()" ), self.fillInputFile )
        QObject.connect( self.outSelector, SIGNAL( "selectClicked()" ), self.fillOutputFileEdit )
 def slotSave(self):
     language = StoreInfoParser.instance().getLanguage()
     m_pTranslator = QTranslator()
     exePath = "./"
     if language == "chinese":
         QmName = "zh_CN.qm"
     else:
         QmName = "en_US.qm"
     if(m_pTranslator.load(QmName, exePath)):
         QCoreApplication.instance().installTranslator(m_pTranslator)
         
     """改变当前的分辨率"""
     screenName = self.resolutionCombox.itemData(0, Qt.UserRole + 1).toString()
     if not screenName.isEmpty() and not screenName.isNull():
         self.curResolutionValue = self.getCurrentScreenResolution(str(screenName))
         if self.curResolutionValue:
             reScreen = self.resolutionCombox.currentText()
             if reScreen == "800x600":
                pass 
             else:
                pass
             #弹出提示框,默认为取消
             rb = MessageBox(self.tr("making sure set the resolution to current"), self).exec_()
             if rb == QDialog.Accepted:
                self.jytcapi.jysetdispconf(str(reScreen))
             elif rb == QDialog.Rejected:
                pass
Esempio n. 9
0
	def popUp(self):

		"""Popup from the tray"""

		# Reposition the window
		r = QDesktopWidget().availableGeometry()
		s = self.size()
		pos = getConfig(u"pos")
		if pos == u"Top right":
			x = r.left() + r.width()-s.width()
			y = r.top()
		elif pos == u"Top left":
			x = r.left()
			y = r.top()
		elif pos == u"Bottom right":
			x = r.left() + r.width()-s.width()
			y = r.top() + r.height()-s.height()
		elif pos == u"Bottom left":
			x = r.left()
			y = r.top() + r.height()-s.height()
		else:
			x = r.left() + r.width()/2 - s.width()/2
			y = r.top() + r.height()/2 - s.height()/2
		self.move(x, y)

		# Show it
		self.show()
		QCoreApplication.processEvents()
		self.raise_()
		self.activateWindow()

		# Focus the search box
		self.ui.lineEditQuery.selectAll()
		self.ui.lineEditQuery.setFocus()
Esempio n. 10
0
    def __init__(self, iface):
        """init"""

        self.iface = iface
        self.context = StaticContext()
        self.action_run = None
        self.action_help = None
        self.web_menu = '&MetaSearch'

        LOGGER.debug('Setting up i18n')

        locale_name = str(QLocale.system().name()).split('_')[0]

        LOGGER.debug('Locale name: %s', locale_name)

        # load if exists
        tr_file = os.path.join(self.context.ppath, 'locale', locale_name,
                               'LC_MESSAGES', 'ui.qm')

        if os.path.exists(tr_file):
            self.translator = QTranslator()
            result = self.translator.load(tr_file)
            if not result:
                msg = 'Failed to load translation: %s' % tr_file
                LOGGER.error(msg)
                raise RuntimeError(msg)
            QCoreApplication.installTranslator(self.translator)

        LOGGER.debug(translate('Translation loaded: %s' % tr_file))
Esempio n. 11
0
 def slotShowRestartNetworkInfo(self, status):
     """显示重启网络的状态信息"""
     
     language = StoreInfoParser.instance().getLanguage()
     m_pTranslator = QTranslator()
     exePath = "./"
     if language == "chinese":
         QmName = "zh_CN.qm"
     else:
         QmName = "en_US.qm"
     if(m_pTranslator.load(QmName, exePath)):
         QCoreApplication.instance().installTranslator(m_pTranslator)
     
     if status == "Start":
         #InfoHintDialog(self.tr("restarting network, please wait ...")).exec_()
         self.waitingDlg.setHintInfo(self.tr("restarting network, please wait ..."))
     elif status == "Success":
         #InfoHintDialog(self.tr("network setting success")).exec_()
         self.waitingDlg.setHintInfo(self.tr("network setting success"))
     elif status == "Failed":
         #InfoHintDialog(self.tr("network restart failed")).exec_()
         self.waitingDlg.setHintInfo(self.tr("network restart failed"))
     else:
         return
     
     if self.waitingDlg.isHidden():
         desktop = QApplication.desktop()
         self.waitingDlg.move((desktop.width() - self.waitingDlg.width())/2, (desktop.height() - self.waitingDlg.height())/2)
         self.waitingDlg.exec_()
Esempio n. 12
0
 def scrollPage(self, degrees=180, afterScroll=None):
     # do 180 degree scroll down
     event = QWheelEvent(QCursor.pos(), -1 * (degrees / 15) * 120, Qt.MouseButtons(), Qt.KeyboardModifiers(),
                         Qt.Vertical)
     QCoreApplication.postEvent(self, event)
     if afterScroll:
         afterScroll(self)
Esempio n. 13
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", "AttributeSplit_{}.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 = AttributeSplitDialog(iface)

        # Declare instance attributes
        self.actions = []
        self.menu = self.tr(u"&Attribute Split")
        self.toolbar = self.iface.addToolBar(u"AttributeSplit")
        self.toolbar.setObjectName(u"AttributeSplit")
Esempio n. 14
0
 def restart(self, num_processors=None, wait=False):
     if num_processors is not None:
         assert sum(num_processors) <= MAX_NUMBER_PROCESSORS, \
             'total number of additional processors must be %d or less' % MAX_NUMBER_PROCESSORS
     # stop new items from being processed
     self.shutdown_processors()
     # attempt to stop current processors
     if self._local_file_thread is not None:
         self._local_file_thread.worker.stop()
     if self._local_folder_thread is not None:
         self._local_folder_thread.worker.stop()
     if self._remote_file_thread is not None:
         self._remote_file_thread.worker.stop()
     if self._remote_folder_thread is not None:
         self._remote_folder_thread.worker.stop()
     for p in self._processors_pool:
         p.worker.stop()
     if wait:
         while self.is_active():
             QCoreApplication.processEvents()
             sleep(0.1)
     self.set_max_processors(num_processors)
     # re-enable new items to trigger processing
     self.init_processors()
     # launch processors for new items in the queue, if any
     self.launch_processors()
Esempio n. 15
0
    def __init__(self, layers):
        """
        Constructor
        """
        QDialog.__init__(self)
        self.__layers = layers
        self.setWindowTitle(QCoreApplication.translate("VDLTools", "Edition Confirmation"))
        self.__layout = QGridLayout()

        titleLabel = QLabel(QCoreApplication.translate("VDLTools", "Do you really want to edit these layers ?"))
        self.__layout.addWidget(titleLabel, 0, 0, 1, 2)

        pos = 1
        for layer in self.__layers:
            label = QLabel(" - " + layer.name())
            self.__layout.addWidget(label, pos, 0, 1, 2)
            pos += 1

        self.__cancelButton = QPushButton(QCoreApplication.translate("VDLTools", "Cancel"))
        self.__cancelButton.setMinimumHeight(20)
        self.__cancelButton.setMinimumWidth(100)

        pos = len(self.__layers) + 1
        self.__layout.addWidget(self.__cancelButton, pos, 0)

        self.__okButton = QPushButton(QCoreApplication.translate("VDLTools", "OK"))
        self.__okButton.setMinimumHeight(20)
        self.__okButton.setMinimumWidth(100)
        self.__layout.addWidget(self.__okButton, pos, 1)


        self.setLayout(self.__layout)
Esempio n. 16
0
 def itemAction(self, mi,):
     # FIXME: use a MIME-Handler here
     i = self.model.itemFromIndex(mi)
     t, nc = i.ncItem
     QMessageBox.information(self,
             QCoreApplication.translate('NetCDF3', 'netCDF3: Item clicked'),
             QCoreApplication.translate('NetCDF3', 'You clicked an item in the netCDF3-browser'))
Esempio n. 17
0
    def __init__(self, iface):
        # Save reference to the QGIS interface
        self.iface = iface

        # i18n support
        override_locale = QSettings().value('locale/overrideFlag', False, type=bool)
        if not override_locale:
            locale_full_name = QLocale.system().name()
        else:
            locale_full_name = QSettings().value('locale/userLocale', '', type=unicode)

        self.locale_path = '%s/i18n/rugeocoder_%s.qm' % (_current_path, locale_full_name[0:2])
        if QFileInfo(self.locale_path).exists():
            self.translator = QTranslator()
            self.translator.load(self.locale_path)
            QCoreApplication.installTranslator(self.translator)

        # menu && toolbars
        self.menu_name = self.tr(u'&RuGeocoder')
        self.toolbar = self.iface.addToolBar(self.menu_name)
        self.toolbar.setObjectName(u'RuGeocoderToolbar')

        # instances
        self.__converter_dlg = ConverterDialog()
        self.__geocoder_dlg = BatchGeocodingDialog()

        # Dock tree panel
        self.__quick_tlb = QuickGeocodingToolbox(self.iface)
        self.iface.addDockWidget(PluginSettings.dock_area(), self.__quick_tlb)
        self.__quick_tlb.setFloating(PluginSettings.dock_floating())
        self.__quick_tlb.resize(PluginSettings.dock_size())
        self.__quick_tlb.move(PluginSettings.dock_pos())
        self.__quick_tlb.setVisible(PluginSettings.dock_visibility())
        self.__quick_tlb.set_active_geocoder(PluginSettings.dock_geocoder_name())
        self.__quick_tlb.setWindowIcon(QIcon(path.join(_current_path, 'edit-find-project.png')))
Esempio n. 18
0
    def __init__(self, iface):
        """init"""

        self.iface = iface
        self.context = StaticContext()
        self.action_run = None
        self.action_help = None
        self.dialog = None
        self.web_menu = '&MetaSearch'

        LOGGER.debug('Setting up i18n')

        # TODO: does this work for locales like: pt_BR ?
        locale_name = QSettings().value("locale/userLocale")[0:2]
        # this one below does not pick up when you load QGIS with --lang param
#        locale_name = str(QLocale.system().name()).split('_')[0]

        LOGGER.debug('Locale name: %s', locale_name)

        # load if exists
        tr_file = os.path.join(self.context.ppath, 'locale', locale_name,
                               'LC_MESSAGES', 'ui.qm')

        if os.path.exists(tr_file):
            self.translator = QTranslator()
            result = self.translator.load(tr_file)
            if not result:
                msg = 'Failed to load translation: %s' % tr_file
                LOGGER.error(msg)
                raise RuntimeError(msg)
            QCoreApplication.installTranslator(self.translator)

        LOGGER.debug(QCoreApplication.translate('MetaSearch',
                     'Translation loaded: %s' % tr_file))
Esempio n. 19
0
def removeDir(path):
    result = ""
    if not QFile(path).exists():
        result = QCoreApplication.translate("QgsPluginInstaller", "Nothing to remove! Plugin directory doesn't exist:") + "\n" + path
    elif QFile(path).remove(): # if it is only link, just remove it without resolving.
        pass
    else:
        fltr = QDir.Dirs | QDir.Files | QDir.Hidden
        iterator = QDirIterator(path, fltr, QDirIterator.Subdirectories)
        while iterator.hasNext():
            item = iterator.next()
            if QFile(item).remove():
                pass
        fltr = QDir.Dirs | QDir.Hidden
        iterator = QDirIterator(path, fltr, QDirIterator.Subdirectories)
        while iterator.hasNext():
            item = iterator.next()
            if QDir().rmpath(item):
                pass
    if QFile(path).exists():
        result = QCoreApplication.translate("QgsPluginInstaller", "Failed to remove the directory:") + "\n" + path + "\n" + QCoreApplication.translate("QgsPluginInstaller", "Check permissions or remove it manually")
    # restore plugin directory if removed by QDir().rmpath()
    pluginDir = qgis.utils.home_plugin_path
    if not QDir(pluginDir).exists():
        QDir().mkpath(pluginDir)
    return result
Esempio n. 20
0
    def initGui(self):
        """startup"""

        # run
        run_icon = QIcon('%s/%s' % (self.context.ppath,
                                    'images/MetaSearch.png'))
        self.action_run = QAction(run_icon, 'MetaSearch',
                                  self.iface.mainWindow())
        self.action_run.setWhatsThis(QCoreApplication.translate('MetaSearch',
                                     'MetaSearch plugin'))
        self.action_run.setStatusTip(QCoreApplication.translate('MetaSearch',
                                     'Search Metadata Catalogues'))

        self.action_run.triggered.connect(self.run)

        self.iface.addToolBarIcon(self.action_run)
        self.iface.addPluginToWebMenu(self.web_menu, self.action_run)

        # help
        help_icon = QIcon('%s/%s' % (self.context.ppath, 'images/help.png'))
        self.action_help = QAction(help_icon, 'Help', self.iface.mainWindow())
        self.action_help.setWhatsThis(QCoreApplication.translate('MetaSearch',
                                      'MetaSearch plugin help'))
        self.action_help.setStatusTip(QCoreApplication.translate('MetaSearch',
                                      'Get Help on MetaSearch'))
        self.action_help.triggered.connect(self.help)

        self.iface.addPluginToWebMenu(self.web_menu, self.action_help)

        # prefab the dialog but not open it yet
        self.dialog = MetaSearchDialog(self.iface)
Esempio n. 21
0
 def defineCharacteristicsFromFile(self):
     lines = open(self.descriptionFile)
     line = lines.readline().strip('\n').strip()
     self.name = line
     if '|' in self.name:
         tokens = self.name.split('|')
         self.name = tokens[0]
         self.i18n_name = QCoreApplication.translate("SAGAAlgorithm", unicode(self.name))
         self.cmdname = tokens[1]
     else:
         self.cmdname = self.name
         self.i18n_name = QCoreApplication.translate("SAGAAlgorithm", unicode(self.name))
         self.name = self.name[0].upper() + self.name[1:].lower()
     line = lines.readline().strip('\n').strip()
     self.undecoratedGroup = line
     self.group = SagaGroupNameDecorator.getDecoratedName(self.undecoratedGroup)
     self.i18n_group = QCoreApplication.translate("SAGAAlgorithm", self.group)
     line = lines.readline().strip('\n').strip()
     while line != '':
         if line.startswith('Hardcoded'):
             self.hardcodedStrings.append(line[len('Harcoded|') + 1:])
         elif line.startswith('Parameter'):
             self.addParameter(getParameterFromString(line))
         elif line.startswith('AllowUnmatching'):
             self.allowUnmatchingGridExtents = True
         elif line.startswith('Extent'):
             # An extent parameter that wraps 4 SAGA numerical parameters
             self.extentParamNames = line[6:].strip().split(' ')
             self.addParameter(ParameterExtent(self.OUTPUT_EXTENT,
                               'Output extent', '0,1,0,1'))
         else:
             self.addOutput(getOutputFromString(line))
         line = lines.readline().strip('\n').strip()
     lines.close()
Esempio n. 22
0
    def change_i18n(self, new_locale):
        """Change internationalisation for the plugin.

        Override the system locale  and then see if we can get a valid
        translation file for whatever locale is effectively being used.

        :param new_locale: The new locale i.e. 'id', 'af', etc.
        :type new_locale: str

        :raises: TranslationLoadException
        """

        os.environ['INASAFE_LANG'] = str(new_locale)

        LOGGER.debug('%s %s %s' % (
            new_locale, QLocale.system().name(), os.environ['INASAFE_LANG']))

        root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
        translation_path = os.path.join(
            root, 'safe_qgis', 'i18n',
            'inasafe_' + str(new_locale) + '.qm')

        if os.path.exists(translation_path):
            self.translator = QTranslator()
            result = self.translator.load(translation_path)
            if not result:
                message = 'Failed to load translation for %s' % new_locale
                raise TranslationLoadError(message)
            # noinspection PyTypeChecker,PyCallByClass
            QCoreApplication.installTranslator(self.translator)

        LOGGER.debug('%s %s' % (
            translation_path, os.path.exists(translation_path)))
Esempio n. 23
0
    def __init__(self, iface):

        self.iface = iface
        self.plugin_dir = dirname(__file__)
        # initialize locale
        locale = QSettings().value("locale/userLocale")[0:2]
        locale_path = join(
            self.plugin_dir,
            'i18n',
            'GeoHealth_{}.qm'.format(locale))

        if exists(locale_path):
            self.translator = QTranslator()
            self.translator.load(locale_path)

            if qVersion() > '4.3.3':
                # noinspection PyCallByClass,PyTypeChecker,PyArgumentList
                QCoreApplication.installTranslator(self.translator)

        self.plugin_menu = None
        self.geohealth_menu = None
        self.main_action = None
        self.xy_action = None
        self.blur_action = None
        self.incidence_action = None
        self.density_action = None
        self.histogram_action = None

        # Add to processing
        self.provider = Provider()
        Processing.addProvider(self.provider, True)
Esempio n. 24
0
    def __init__(self, parent):
        QDialog.__init__(self, parent)
        self.setWindowTitle(QCoreApplication.translate("SettingsDialogPythonConsole", "Settings Python Console"))
        self.parent = parent
        self.setupUi(self)

        self.listPath = []
        self.lineEdit.setReadOnly(True)

        self.restoreSettings()
        self.initialCheck()

        self.addAPIpath.setIcon(QIcon(":/images/themes/default/symbologyAdd.png"))
        self.addAPIpath.setToolTip(QCoreApplication.translate("PythonConsole", "Add API path"))
        self.removeAPIpath.setIcon(QIcon(":/images/themes/default/symbologyRemove.png"))
        self.removeAPIpath.setToolTip(QCoreApplication.translate("PythonConsole", "Remove API path"))

        self.preloadAPI.stateChanged.connect(self.initialCheck)
        self.addAPIpath.clicked.connect(self.loadAPIFile)
        self.removeAPIpath.clicked.connect(self.removeAPI)
        self.compileAPIs.clicked.connect(self._prepareAPI)

        self.resetFontColor.setIcon(QIcon(":/images/themes/default/console/iconResetColorConsole.png"))
        self.resetFontColor.setIconSize(QSize(18, 18))
        self.resetFontColorEditor.setIcon(QIcon(":/images/themes/default/console/iconResetColorConsole.png"))
        self.resetFontColorEditor.setIconSize(QSize(18, 18))
        self.resetFontColor.clicked.connect(self._resetFontColor)
        self.resetFontColorEditor.clicked.connect(self._resetFontColorEditor)
Esempio n. 25
0
    def mousePressEvent(self, event):
        anchor_item = self.scene.item_at(event.scenePos(),
                                         items.NodeAnchorItem,
                                         buttons=Qt.LeftButton)
        if anchor_item and event.button() == Qt.LeftButton:
            # Start a new link starting at item
            self.from_item = anchor_item.parentNodeItem()
            if isinstance(anchor_item, items.SourceAnchorItem):
                self.direction = NewLinkAction.FROM_SOURCE
                self.source_item = self.from_item
            else:
                self.direction = NewLinkAction.FROM_SINK
                self.sink_item = self.from_item

            event.accept()

            helpevent = QuickHelpTipEvent(
                self.tr("Create a new link"),
                self.tr('<h3>Create new link</h3>'
                        '<p>Drag a link to an existing node or release on '
                        'an empty spot to create a new node.</p>'
#                        '<a href="help://orange-canvas/create-new-links">'
#                        'More ...</a>'
                        )
            )
            QCoreApplication.postEvent(self.document, helpevent)

            return True
        else:
            # Whoever put us in charge did not know what he was doing.
            self.cancel(self.ErrorReason)
            return False
Esempio n. 26
0
    def test_methodinvoke(self):
        executor = ThreadExecutor()
        state = [None, None]

        class StateSetter(QObject):
            @Slot(object)
            def set_state(self, value):
                state[0] = value
                state[1] = QThread.currentThread()

        def func(callback):
            callback(QThread.currentThread())

        obj = StateSetter()
        f1 = executor.submit(func, methodinvoke(obj, "set_state", (object,)))
        f1.result()

        # So invoked method can be called
        QCoreApplication.processEvents()

        self.assertIs(state[1], QThread.currentThread(),
                      "set_state was called from the wrong thread")

        self.assertIsNot(state[0], QThread.currentThread(),
                         "set_state was invoked in the main thread")

        executor.shutdown(wait=True)
Esempio n. 27
0
    def saveAsScriptFile(self, index=None):
        tabWidget = self.tabEditorWidget.currentWidget()
        if not index:
            index = self.tabEditorWidget.currentIndex()
        if not tabWidget.path:
            fileName = self.tabEditorWidget.tabText(index) + '.py'
            folder = self.settings.value("pythonConsole/lastDirPath", QDir.home())
            pathFileName = os.path.join(folder, fileName)
            fileNone = True
        else:
            pathFileName = tabWidget.path
            fileNone = False
        saveAsFileTr = QCoreApplication.translate("PythonConsole", "Save File As")
        filename = QFileDialog.getSaveFileName(self,
                                               saveAsFileTr,
                                               pathFileName, "Script file (*.py)")
        if filename:
            try:
                tabWidget.save(filename)
            except (IOError, OSError) as error:
                msgText = QCoreApplication.translate('PythonConsole',
                                                     'The file <b>{0}</b> could not be saved. Error: {1}').format(tabWidget.path,
                                                                                                                  error.strerror)
                self.callWidgetMessageBarEditor(msgText, 2, False)
                if fileNone:
                    tabWidget.path = None
                else:
                    tabWidget.path = pathFileName
                return

            if not fileNone:
                self.updateTabListScript(pathFileName, action='remove')
Esempio n. 28
0
    def __init__(self):
        """
        Constructor
        """
        QDialog.__init__(self)
        self.setWindowTitle(QCoreApplication.translate("VDLTools", "Display Attributes Confirmation"))
        self.resize(300, 100)
        self.__layout = QGridLayout()

        self.__confirmLabel = QLabel(
            QCoreApplication.translate("VDLTools",
                                       "Do you want to display the attributes tables for the selected features ?"))

        self.__layout.addWidget(self.__confirmLabel, 0, 0, 1, 2)

        self.__okButton = QPushButton(QCoreApplication.translate("VDLTools", "Yes"))
        self.__okButton.setMinimumHeight(20)
        self.__okButton.setMinimumWidth(100)

        self.__cancelButton = QPushButton(QCoreApplication.translate("VDLTools", "No"))
        self.__cancelButton.setMinimumHeight(20)
        self.__cancelButton.setMinimumWidth(100)

        self.__layout.addWidget(self.__okButton, 1, 0)
        self.__layout.addWidget(self.__cancelButton, 1, 1)

        self.setLayout(self.__layout)
Esempio n. 29
0
 def load(self):
     self.initTranslations()
     cfg = SimuVis4.Globals.config
     cfgsec = self.name.lower()
     if not cfg.has_section(cfgsec):
         cfg.add_section(cfgsec)
     cfg.set_def(cfgsec, 'set_default_backend', 'yes')
     cfg.set_def(cfgsec, 'zoom_step_factor', '0.189207115002721')
     cfg.set_def(cfgsec, 'mouse_wheel_step', '15')
     glb = SimuVis4.Globals
     import matplotlib
     if matplotlib.__version__ < mplMinVersion or matplotlib.__version__ > mplMaxVersion:
         SimuVis4.Globals.logger.error(unicode(QCoreApplication.translate('MatPlot', 'MatPlot: need matplotlib version between %s and %s, but found %s')) % \
             (mplMinVersion, mplMaxVersion, matplotlib.__version__))
         return False
     self.matplotlib = matplotlib
     if cfg.getboolean(cfgsec, 'set_default_backend'):
         try:
             sys.path.append(os.path.split(__file__)[0])
             matplotlib.use('module://backend_sv4agg')
         except:
             pass
     import backend_sv4agg
     self.backend_sv4agg = backend_sv4agg
     dpath = matplotlib.rcParams['datapath']
     tmp = os.path.join(dpath, 'images')
     if os.path.isdir(tmp):
         dpath = tmp
     winIcon = QIcon(os.path.join(dpath, 'matplotlib.png'))
     testAction = QAction(winIcon,
         QCoreApplication.translate('MatPlot', '&MatPlot/PyLab Test'), SimuVis4.Globals.mainWin)
     testAction.setStatusTip(QCoreApplication.translate('MatPlot', 'Show a matplotlib/pylab test window'))
     QWidget.connect(testAction, SIGNAL("triggered()"), self.test)
     SimuVis4.Globals.mainWin.plugInMenu.addAction(testAction)
     return True
Esempio n. 30
0
 def _do_read(self):
     # Read messages from the socket and put them into the incoming queue
     # until nothing more can be read.
     while True:
         try:
             buf = self._socket.recv(4096)
         except socket.error as e:
             if e.errno in (errno.EAGAIN, errno.EWOULDBLOCK):
                 break
             self._log.error("recv() error {0}".format(e.errno))
             self.close()
             break
         if buf == b"":
             self._log.error("peer closed connection")
             self.close()
             break
         # XXX: should not be using protocol private attributes
         # Expose .error and .get_message() ?
         nbytes = self._protocol.data_received(buf)
         if self._protocol._error:
             self._log.error("parse error {0!s}", self._protocol._error)
             self.close()
             break
         while self._protocol._queue.qsize():
             message = self._protocol._queue.get(block=False)
             self._incoming.append(message)
     # Schedule a dispatch if there are incoming messages
     if self._incoming:
         QCoreApplication.instance().postEvent(self, _Dispatch())