Ejemplo n.º 1
0
 def getThemeIcon(self, icon):
     settings = QSettings()
     pluginPath = os.path.dirname(__file__)
     themePath = "icons" + QDir.separator() + settings.value("/Themes", "default") + QDir.separator() + icon
     defaultPath = "icons" + QDir.separator() + "default" + QDir.separator() + icon
     if QFile.exists(pluginPath + QDir.separator() + themePath):
         return QIcon(":" + themePath)
     elif QFile.exists(pluginPath + QDir.separator() + defaultPath):
         return QIcon(":" + defaultPath)
     else:
         return QIcon()
Ejemplo n.º 2
0
Archivo: scj.py Proyecto: Ptaah/SCJ
 def __init__(self, file=None, format=None, createDir=False):
     super(SCJ, self).__init__()
     self.format = format
     self.filename = file
     self.file = QFileInfo(self.filename)
     self.file.makeAbsolute()
     self.suffix = self.file.suffix()
     if createDir:
         self.outputdir = u"%s-%s" % (self.file.path(), self.format)
     else:
         self.outputdir = self.file.path()
     self.output = u"%s%c%s.%s" % ( self.outputdir,
                                    QDir.separator().unicode(),
                                    self.file.completeBaseName(),
                                    self.format)
     if self.format != "mp3":
         self.command = [ u"/usr/bin/sox", u"-S", u"%s" % self.filename,
                          u"-t", u"%s" % self.format, u"%s" % self.output ]
         self.pipecmd = None
     else:
         self.command = [ u"/usr/bin/sox", u"-S", u"%s" % self.filename,
                          u"-t", u"wav", u"-" ]
         self.pipecmd = [ u"/usr/bin/ffmpeg", u"-y", u"-i", u"-",
                          u"-f", u"%s" % self.format, u"%s" % self.output ]
     self.value = 0
     self.process = None
     self.retCode = None
     self.running = False
     self.log = QString(u"")
Ejemplo n.º 3
0
def get(name):
    """ Retrieve setting and convert result
    """
    home_dir = QDesktopServices.storageLocation(QDesktopServices.HomeLocation)
    stdPwlDict = unicode(home_dir + QDir.separator() +  "my-dict.txt")
    settings = QSettings("Davide Setti", "Lector")
    if name == 'scanner:height':
        return settings.value(name, QVariant(297)).toInt()[0]
    elif name == 'scanner:width':
        return settings.value(name, QVariant(210)).toInt()[0]
    elif name == 'scanner:resolution':
        return settings.value(name, QVariant(300)).toInt()[0]
    elif name == 'scanner:mode':
        return str(settings.value(name, QVariant("Color")).toString())
    elif name == 'scanner:device':
        return str(settings.value(name).toString())
    elif name == 'editor:font':
        return settings.value(name, QFont(QFont("Courier New", 10)))
    elif name == 'editor:symbols':
        return settings.value(name).toString()
    elif name in ('editor:clear', 'editor:spell', 'editor:whiteSpace',
                  'spellchecker:pwlLang',):
        return str(settings.value(name, "true").toString()).lower() == "true"
    elif name in ('log:errors'):
        return str(settings.value(name, "false").toString()).lower() == "true"
    elif name == 'spellchecker:pwlDict':
        return str(settings.value(name, stdPwlDict).toString())
    else:
        return str(settings.value(name).toString())
Ejemplo n.º 4
0
    def testComposition(self, page=0, pixelDiff=0 ):
        if self.mComposition is None:
            myMessage = "Composition not valid"
            return False, myMessage

        #load expected image
        self.setControlName("expected_"+self.mTestName)

        # get width/height, create image and render the composition to it
        outputImage = QImage( self.mSize, QImage.Format_RGB32 )

        self.mComposition.setPlotStyle( QgsComposition.Print )
        outputImage.setDotsPerMeterX( self.mDotsPerMeter )
        outputImage.setDotsPerMeterY( self.mDotsPerMeter )
        QgsMultiRenderChecker.drawBackground( outputImage )
        p = QPainter( outputImage )
        self.mComposition.renderPage( p, page )
        p.end()

        renderedFilePath = QDir.tempPath() + QDir.separator() + QFileInfo(self.mTestName).baseName() + "_rendered.png"
        outputImage.save( renderedFilePath, "PNG" )

        self.setRenderedImage( renderedFilePath )

        testResult = self.runTest( self.mTestName, pixelDiff )

        return testResult, self.report()
Ejemplo n.º 5
0
	def __init__(self, path,parent):
		QtCore.QObject.__init__(self,parent)
		self.path=path
		self.serialPort=None
		self.modelBoard=None
		self.currentProcess=None
		self.settings = QSettings(self.path+QDir.separator()+"ino.ini",QSettings.IniFormat)
		setMB = self.settings.value("build/board-model")
		if setMB.isValid():
			self.modelBoard=setMB.toString()
Ejemplo n.º 6
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 (QgsInterface)
        """
        # Save reference to the QGIS interface
        self.iface = iface
        # initialize plugin directory
        self.plugin_dir = QDir().cleanPath(QFileInfo(__file__).absolutePath())
        # initialize locale
        locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = QDir.cleanPath(self.plugin_dir + QDir.separator() +
                                     'i18n' + QDir.separator() +
                                     '{}.qm'.format(locale))
        print locale_path
        if QFileInfo(locale_path).exists():
            print "exists"
            self.translator = QTranslator()
            self.translator.load(locale_path)

            if qVersion() > '4.3.3':
                QCoreApplication.installTranslator(self.translator)

        # init result log
        log_path_2 = QSettings().value("SurveyingCalculation/log_path",
                                       config.log_path)

        if len(log_path_2) > 0:
            log_path = log_path_2
        else:
            log_path = QDir.cleanPath(self.plugin_dir + QDir.separator() +
                                      'log' + QDir.separator() + 'log.txt')
        self.log = ResultLog(log_path)

        self.newp_dlg = NewPointDialog()
        self.single_dlg = SingleDialog(self.log)
        self.traverse_dlg = TraverseDialog(self.log)
        self.network_dlg = NetworkDialog(self.log)
        self.transformation_dlg = TransformationDialog(self.log)
        self.plotbytemplate_dlg = BatchPlottingDialog(self.iface, False)
        self.batchplotting_dlg = BatchPlottingDialog(self.iface, True)
Ejemplo n.º 7
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 (QgsInterface)
        """
        # Save reference to the QGIS interface
        self.iface = iface
        # initialize plugin directory
        self.plugin_dir = QDir().cleanPath( QFileInfo(__file__).absolutePath() )
        # initialize locale
        locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = QDir.cleanPath(self.plugin_dir + QDir.separator() + 'i18n' +
                                     QDir.separator() + '{}.qm'.format(locale))
        print locale_path
        if QFileInfo(locale_path).exists():
            print "exists"
            self.translator = QTranslator()
            self.translator.load(locale_path)

            if qVersion() > '4.3.3':
                QCoreApplication.installTranslator(self.translator)

        # init result log
        log_path_2 = QSettings().value("SurveyingCalculation/log_path",config.log_path)
        
        if len(log_path_2) > 0:
            log_path = log_path_2
        else:
            log_path = QDir.cleanPath(self.plugin_dir + QDir.separator() + 'log' + 
                                      QDir.separator() + 'log.txt')
        self.log = ResultLog(log_path)

        self.newp_dlg = NewPointDialog()
        self.single_dlg = SingleDialog(self.log)
        self.traverse_dlg = TraverseDialog(self.log)
        self.network_dlg = NetworkDialog(self.log)
        self.transformation_dlg = TransformationDialog(self.log)
        self.plotbytemplate_dlg = BatchPlottingDialog(self.iface, False)
        self.batchplotting_dlg = BatchPlottingDialog(self.iface, True)
Ejemplo n.º 8
0
 def requestFinished(self):
     reply = self.sender()
     self.buttonBox.setEnabled(False)
     if reply.error() != QNetworkReply.NoError:
         self.mResult = reply.errorString()
         if reply.error() == QNetworkReply.OperationCanceledError:
             self.mResult += "<br/><br/>" + QCoreApplication.translate(
                 "QgsPluginInstaller",
                 "If you haven't cancelled the download manually, it might be caused by a timeout. In this case consider increasing the connection timeout value in QGIS options."
             )
         self.reject()
         reply.deleteLater()
         return
     self.file.open(QFile.WriteOnly)
     self.file.write(reply.readAll())
     self.file.close()
     self.stateChanged(0)
     reply.deleteLater()
     pluginDir = qgis.utils.home_plugin_path
     tmpPath = self.file.fileName()
     # make sure that the parent directory exists
     if not QDir(pluginDir).exists():
         QDir().mkpath(pluginDir)
     # if the target directory already exists as a link, remove the link without resolving:
     QFile(pluginDir + unicode(QDir.separator()) +
           self.plugin["id"]).remove()
     try:
         unzip(
             unicode(tmpPath), unicode(pluginDir)
         )  # test extract. If fails, then exception will be raised and no removing occurs
         # removing old plugin files if exist
         removeDir(QDir.cleanPath(
             pluginDir + "/" +
             self.plugin["id"]))  # remove old plugin if exists
         unzip(unicode(tmpPath), unicode(pluginDir))  # final extract.
     except:
         self.mResult = self.tr(
             "Failed to unzip the plugin package. Probably it's broken or missing from the repository. You may also want to make sure that you have write permission to the plugin directory:"
         ) + "\n" + pluginDir
         self.reject()
         return
     try:
         # cleaning: removing the temporary zip file
         QFile(tmpPath).remove()
     except:
         pass
     self.close()
Ejemplo n.º 9
0
 def getThemeIcon(self, icon):
   settings = QSettings()
   pluginPath = os.path.dirname(__file__)
   themePath = "icons" + QDir.separator() + settings.value("/Themes", "default") + QDir.separator() + icon
   defaultPath = "icons" + QDir.separator() + "default" + QDir.separator() + icon
   if QFile.exists(pluginPath + QDir.separator() + themePath):
     return QIcon(":" + themePath)
   elif QFile.exists(pluginPath + QDir.separator() + defaultPath):
     return QIcon(":" + defaultPath)
   else:
     return QIcon()
Ejemplo n.º 10
0
    def generateTrainSet(self):
        """
        Gerneruje zestaw treningowy.
        Przeprowadza naukę sieci neuronowej.
        Parametry treningu sieci są pobierane z elementów GUI.

        Uwaga: Każdorazowo sieć tworzona jest na nowo.
        
        """

        if len(self.ui.o_zbiorTreningowy.text()) == 0:
            QMessageBox.warning(None, "BMMSI",
                                u"Należy podać istniejącą scieżkę")
            return

        gen = GenratorPlikuTestowego()
        gen.generuj(self.ui.o_zbiorTreningowy.text())

        if self.siec_neuronowa is not None:
            del self.siec_neuronowa
            self.siec_neuronowa = None

        ssn_params = [
            25,
        ]  #wartstwa wejściowa
        # warstwy ukryte
        for x in range(self.ui.i_iloscWarstwUkrytych.value()):
            ssn_params.append(self.ui.i_liczbaNeuronowWarstwaUkryta.value())
        # warstwa wyjściowa
        ssn_params.append(4)
        self.siec_neuronowa = SSN(
            2 + self.ui.i_iloscWarstwUkrytych.value(),
            ssn_params,
        )

        self.siec_neuronowa.logEntry.connect(self.addLineToLog)

        self.siec_neuronowa.train(
            (QDir.currentPath() + QDir.separator() + "test.txt"),
            liczbaEpok=self.ui.i_liczbaEpok.value(),
            N=self.ui.i_wspolczynnikUczenia.value(),
            M=self.ui.i_wspolczynnikMomentum.value(),
            min_blad=self.ui.i_limiWartosciBledu.value())

        self.ui.ib_testuj.setEnabled(True)
Ejemplo n.º 11
0
    def __init__(self, parent=None):
        """
        Konstruktor klasy okna.
        Tworzy okno widoczne na ekranie i połączenia przycisków w stylu Qt.
        
        """
        QtGui.QWidget.__init__(self, parent)

        self.ui = Ui_Form()
        self.ui.setupUi(self)
        self.ui.ib_zbiorTreningowy.clicked.connect(self.chooseFolder)
        self.ui.ib_zbudujTrenujSiec.clicked.connect(self.generateTrainSet)
        self.ui.ib_testuj.clicked.connect(self.testCustomText)
        self.ui.o_zbiorTreningowy.setText(QDir.currentPath() +
                                          QDir.separator() + u"testFolder")

        # Na początku nie mamy zadnej sieci
        self.siec_neuronowa = None
Ejemplo n.º 12
0
    def __init__(self, parent=None):
        """
        Konstruktor klasy okna.
        Tworzy okno widoczne na ekranie i połączenia przycisków w stylu Qt.
        
        """
        QtGui.QWidget.__init__(self, parent)

        self.ui = Ui_Form()
        self.ui.setupUi(self)
        self.ui.ib_zbiorTreningowy.clicked.connect(self.chooseFolder)
        self.ui.ib_zbudujTrenujSiec.clicked.connect(self.generateTrainSet)
        self.ui.ib_testuj.clicked.connect(self.testCustomText)
        self.ui.o_zbiorTreningowy.setText(
            QDir.currentPath()+QDir.separator()+u"testFolder")
        
        # Na początku nie mamy zadnej sieci
        self.siec_neuronowa = None
Ejemplo n.º 13
0
    def generateTrainSet(self):
        """
        Gerneruje zestaw treningowy.
        Przeprowadza naukę sieci neuronowej.
        Parametry treningu sieci są pobierane z elementów GUI.

        Uwaga: Każdorazowo sieć tworzona jest na nowo.
        
        """
        
        if len (self.ui.o_zbiorTreningowy.text()) == 0:
            QMessageBox.warning(None, "BMMSI", u"Należy podać istniejącą scieżkę")
            return
        
        gen = GenratorPlikuTestowego()
        gen.generuj(self.ui.o_zbiorTreningowy.text())
        
        if self.siec_neuronowa is not None:
            del self.siec_neuronowa
            self.siec_neuronowa = None
            
        ssn_params = [25,] #wartstwa wejściowa
        # warstwy ukryte
        for x in range(self.ui.i_iloscWarstwUkrytych.value()):
            ssn_params.append(self.ui.i_liczbaNeuronowWarstwaUkryta.value())
        # warstwa wyjściowa
        ssn_params.append(4)
        self.siec_neuronowa = SSN( 2 + self.ui.i_iloscWarstwUkrytych.value(), 
                                  ssn_params,
                                  )
                                  
        self.siec_neuronowa.logEntry.connect(self.addLineToLog)
        
        self.siec_neuronowa.train((QDir.currentPath()+QDir.separator()+"test.txt"),
                                  liczbaEpok=self.ui.i_liczbaEpok.value(),
                                  N=self.ui.i_wspolczynnikUczenia.value(),
                                  M=self.ui.i_wspolczynnikMomentum.value(),
                                  min_blad = self.ui.i_limiWartosciBledu.value() )
                                  
        self.ui.ib_testuj.setEnabled(True)
 def requestFinished(self):
   reply = self.sender()
   self.buttonBox.setEnabled(False)
   if reply.error() != QNetworkReply.NoError:
     self.mResult = reply.errorString()
     if reply.error() == QNetworkReply.OperationCanceledError:
       self.mResult += "<br/><br/>" + QCoreApplication.translate("QgsPluginInstaller", "If you haven't cancelled the download manually, it might be caused by a timeout. In this case consider increasing the connection timeout value in QGIS options.")
     self.reject()
     reply.deleteLater()
     return
   self.file.open(QFile.WriteOnly)
   self.file.write(reply.readAll())
   self.file.close()
   self.stateChanged(0)
   reply.deleteLater()
   pluginDir = qgis.utils.home_plugin_path
   tmpPath = self.file.fileName()
   # make sure that the parent directory exists
   if not QDir(pluginDir).exists():
     QDir().mkpath(pluginDir)
   # if the target directory already exists as a link, remove the link without resolving:
   QFile(pluginDir+unicode(QDir.separator())+self.plugin["id"]).remove()
   try:
     unzip(unicode(tmpPath), unicode(pluginDir)) # test extract. If fails, then exception will be raised and no removing occurs
     # removing old plugin files if exist
     removeDir(QDir.cleanPath(pluginDir+"/"+self.plugin["id"])) # remove old plugin if exists
     unzip(unicode(tmpPath), unicode(pluginDir)) # final extract.
   except:
     self.mResult = self.tr("Failed to unzip the plugin package. Probably it's broken or missing from the repository. You may also want to make sure that you have write permission to the plugin directory:") + "\n" + pluginDir
     self.reject()
     return
   try:
     # cleaning: removing the temporary zip file
     QFile(tmpPath).remove()
   except:
     pass
   self.close()
Ejemplo n.º 15
0
    def initGui(self):
        """Create the menu entries and toolbar icons inside the QGIS GUI."""

        icon_path = ':/plugins/SurveyingCalculation/icon.png'

        icon_dir = QDir.cleanPath(self.plugin_dir + QDir.separator() + 'icons')
        # build menu
        self.actions = []
        self.menu = QMenu()
        self.menu.setTitle(tr(u'&SurveyingCalculation'))
        self.sc_coord = QAction(
            QIcon(QDir(icon_dir).absoluteFilePath('new_coord.png')),
            tr("New coordinate list ..."), self.iface.mainWindow())
        self.sc_fb = QAction(
            QIcon(QDir(icon_dir).absoluteFilePath('new_fb.png')),
            tr("New fieldbook ..."), self.iface.mainWindow())
        self.sc_load = QAction(
            QIcon(QDir(icon_dir).absoluteFilePath('import_fieldbook.png')),
            tr("Import fieldbook ..."), self.iface.mainWindow())
        self.sc_addp = QAction(
            QIcon(QDir(icon_dir).absoluteFilePath('addp.png')),
            tr("Add new point ..."), self.iface.mainWindow())
        self.sc_calc = QAction(
            QIcon(QDir(icon_dir).absoluteFilePath('single_calc.png')),
            tr("Single point calculations ..."), self.iface.mainWindow())
        self.sc_trav = QAction(
            QIcon(QDir(icon_dir).absoluteFilePath('traverse_calc.png')),
            tr("Traverse calculations ..."), self.iface.mainWindow())
        self.sc_netw = QAction(
            QIcon(QDir(icon_dir).absoluteFilePath('network_calc.png')),
            tr("Network adjustment ..."), self.iface.mainWindow())
        self.sc_tran = QAction(
            QIcon(QDir(icon_dir).absoluteFilePath('coord_calc.png')),
            tr("Coordinate transformation ..."), self.iface.mainWindow())
        self.sc_pdiv = QAction(
            QIcon(QDir(icon_dir).absoluteFilePath('poly_div.png')),
            tr("Polygon division ..."), self.iface.mainWindow())
        self.sc_plot = QAction(
            QIcon(QDir(icon_dir).absoluteFilePath('plot.png')),
            tr("Plot by template ..."), self.iface.mainWindow())
        self.sc_batchplot = QAction(
            QIcon(QDir(icon_dir).absoluteFilePath('batch_plot.png')),
            tr("Batch plotting ..."), self.iface.mainWindow())
        self.sc_settings = QAction(tr("Settings ..."), self.iface.mainWindow())
        self.sc_help = QAction(tr("Help"), self.iface.mainWindow())
        self.sc_about = QAction(tr("About"), self.iface.mainWindow())
        self.menu.addActions([
            self.sc_coord, self.sc_fb, self.sc_load, self.sc_addp,
            self.sc_calc, self.sc_trav, self.sc_netw, self.sc_tran,
            self.sc_plot, self.sc_batchplot, self.sc_settings, self.sc_help,
            self.sc_about
        ])
        self.menu.insertSeparator(self.sc_calc)
        self.menu.insertSeparator(self.sc_plot)
        self.menu.insertSeparator(self.sc_settings)
        self.menu.insertSeparator(self.sc_help)
        menu_bar = self.iface.mainWindow().menuBar()
        actions = menu_bar.actions()
        lastAction = actions[len(actions) - 1]
        menu_bar.insertMenu(lastAction, self.menu)

        self.sc_coord.triggered.connect(self.create_coordlist)
        self.sc_fb.triggered.connect(self.create_fb)
        self.sc_load.triggered.connect(self.load_fieldbook)
        self.sc_addp.triggered.connect(self.addp)
        self.sc_calc.triggered.connect(self.calculations)
        self.sc_trav.triggered.connect(self.traverses)
        self.sc_netw.triggered.connect(self.networks)
        self.sc_tran.triggered.connect(self.transformation)
        self.sc_pdiv.setCheckable(True)
        self.tool_pdiv = LineMapTool(self.iface)
        self.tool_pdiv.setAction(self.sc_pdiv)
        self.sc_pdiv.triggered.connect(self.polygon_division)
        self.sc_plot.triggered.connect(self.plot_by_temp)
        self.sc_batchplot.triggered.connect(self.batch_plotting)
        self.sc_settings.triggered.connect(self.settings)
        self.sc_about.triggered.connect(self.about)
        self.sc_help.triggered.connect(self.help)

        # add icons to toolbar
        self.toolbar = self.iface.addToolBar(u'SurveyingCalculation')
        self.toolbar.setObjectName(u'SurveyingCalculation')
        self.toolbar.addActions([
            self.sc_load, self.sc_addp, self.sc_calc, self.sc_trav,
            self.sc_netw, self.sc_tran, self.sc_pdiv, self.sc_plot,
            self.sc_batchplot
        ])
        self.toolbar.insertSeparator(self.sc_calc)
        self.toolbar.insertSeparator(self.sc_plot)
Ejemplo n.º 16
0
 def getOutputFileName(self):
     if self.useDirAsOutput:
       if self.outSelector.filename():
         return self.outSelector.filename() + QDir.separator() + "contour.shp"
     return self.outSelector.filename()
Ejemplo n.º 17
0
 def getOutputFileName(self):
     if self.useDirAsOutput:
         if self.outSelector.filename():
             return self.outSelector.filename() + QDir.separator(
             ) + "contour.shp"
     return self.outSelector.filename()
Ejemplo n.º 18
0
'''
QGIS Processing script
(c) 2017 Andreas Plesch
save style in qml file
'''
##X3D=group
##save_raster_style=name
##input_raster=raster
##style_file=output file

import shutil
from PyQt4.QtCore import QFile, QFileInfo, QDir

#saveNamedStyle always writes to .qml
fileInfo = QFileInfo(style_file)
style_file = fileInfo.path() + QDir.separator() + fileInfo.completeBaseName() + ".qml"

file=QFile(style_file)
#touch, create since saveStyle only writes file if it exists
file.open(QFile.ReadWrite)
file.close()

r = processing.getObject(input_raster)
print(r.saveNamedStyle(style_file))
#saveNamedStyle always writes to .qml
#copy back
#fileInfo = QFileInfo(style_file)
#style_file = fileInfo.path() + QDir.separator() + fileInfo.completeBaseName() + ".qml"
#shutil.copy(qml, style_file)

Ejemplo n.º 19
0
    def initGui(self):
        """Create the menu entries and toolbar icons inside the QGIS GUI."""

        icon_path = ':/plugins/SurveyingCalculation/icon.png'
        
        icon_dir = QDir.cleanPath( self.plugin_dir + QDir.separator() + 'icons')
        # build menu
        self.actions = []
        self.menu = QMenu()
        self.menu.setTitle(tr(u'&SurveyingCalculation'))
        self.sc_coord = QAction(QIcon(QDir(icon_dir).absoluteFilePath('new_coord.png')), tr("New coordinate list ..."), self.iface.mainWindow())
        self.sc_fb = QAction(QIcon(QDir(icon_dir).absoluteFilePath('new_fb.png')),tr("New fieldbook ..."), self.iface.mainWindow())
        self.sc_load = QAction(QIcon(QDir(icon_dir).absoluteFilePath('import_fieldbook.png')), tr("Import fieldbook ..."), self.iface.mainWindow())
        self.sc_addp = QAction(QIcon(QDir(icon_dir).absoluteFilePath('addp.png')), tr("Add new point ..."), self.iface.mainWindow())
        self.sc_calc = QAction(QIcon(QDir(icon_dir).absoluteFilePath('single_calc.png')), tr("Single point calculations ..."), self.iface.mainWindow())
        self.sc_trav = QAction(QIcon(QDir(icon_dir).absoluteFilePath('traverse_calc.png')), tr("Traverse calculations ..."), self.iface.mainWindow())
        self.sc_netw = QAction(QIcon(QDir(icon_dir).absoluteFilePath('network_calc.png')), tr("Network adjustment ..."), self.iface.mainWindow())
        self.sc_tran = QAction(QIcon(QDir(icon_dir).absoluteFilePath('coord_calc.png')), tr("Coordinate transformation ..."), self.iface.mainWindow())
        self.sc_pdiv = QAction(QIcon(QDir(icon_dir).absoluteFilePath('poly_div.png')), tr("Polygon division ..."), self.iface.mainWindow())
        self.sc_plot = QAction(QIcon(QDir(icon_dir).absoluteFilePath('plot.png')), tr("Plot by template ..."), self.iface.mainWindow())
        self.sc_batchplot = QAction(QIcon(QDir(icon_dir).absoluteFilePath('batch_plot.png')), tr("Batch plotting ..."), self.iface.mainWindow())
        self.sc_settings = QAction(tr("Settings ..."), self.iface.mainWindow())
        self.sc_help = QAction(tr("Help"), self.iface.mainWindow())
        self.sc_about = QAction(tr("About"), self.iface.mainWindow())
        self.menu.addActions([self.sc_coord, self.sc_fb, self.sc_load,
            self.sc_addp, self.sc_calc, self.sc_trav, self.sc_netw,
            self.sc_tran, self.sc_plot, self.sc_batchplot, self.sc_settings,
            self.sc_help, self.sc_about])
        self.menu.insertSeparator(self.sc_calc)
        self.menu.insertSeparator(self.sc_plot)
        self.menu.insertSeparator(self.sc_settings)
        self.menu.insertSeparator(self.sc_help)
        menu_bar = self.iface.mainWindow().menuBar()
        actions = menu_bar.actions()
        lastAction = actions[len(actions) - 1]
        menu_bar.insertMenu(lastAction, self.menu)

        self.sc_coord.triggered.connect(self.create_coordlist)
        self.sc_fb.triggered.connect(self.create_fb)
        self.sc_load.triggered.connect(self.load_fieldbook)
        self.sc_addp.triggered.connect(self.addp)
        self.sc_calc.triggered.connect(self.calculations)
        self.sc_trav.triggered.connect(self.traverses)
        self.sc_netw.triggered.connect(self.networks)
        self.sc_tran.triggered.connect(self.transformation)
        self.sc_pdiv.setCheckable(True)
        self.tool_pdiv = LineMapTool(self.iface)
        self.tool_pdiv.setAction(self.sc_pdiv)
        self.sc_pdiv.triggered.connect(self.polygon_division)
        self.sc_plot.triggered.connect(self.plot_by_temp)
        self.sc_batchplot.triggered.connect(self.batch_plotting)
        self.sc_settings.triggered.connect(self.settings)
        self.sc_about.triggered.connect(self.about)
        self.sc_help.triggered.connect(self.help)

        # add icons to toolbar
        self.toolbar = self.iface.addToolBar(u'SurveyingCalculation')
        self.toolbar.setObjectName(u'SurveyingCalculation')
        self.toolbar.addActions([self.sc_load, self.sc_addp, self.sc_calc, self.sc_trav,
            self.sc_netw, self.sc_tran, self.sc_pdiv, self.sc_plot, self.sc_batchplot])
        self.toolbar.insertSeparator(self.sc_calc)
        self.toolbar.insertSeparator(self.sc_plot)
Ejemplo n.º 20
0
    def _completion_event(self, event):
        if (self.completion_enabled) and ((self.mode == Console.MODE_CODE_EDITING or self.mode == Console.MODE_RAW_INPUT) and len(event.text()) != 0):
            completion_prefix = self.wordUnderCursor() + event.text()
            try:
                dct, key = self._guessDictPrefix(event.text())
                need_dict_completion = True
                in_string_prefix = None
            except:
                need_dict_completion = False
                in_string_prefix = self._guessStringPrefix(event.text())
            len_or_dot = len(completion_prefix) >= 3 or event.text() == '.' or (event.text() == ' ' and (event.modifiers() & Qt.ControlModifier)) or need_dict_completion
            if event.modifiers() & Qt.ControlModifier:
                completion_prefix = completion_prefix[:-1]
            need_import_completion = self.textToCursor()[:-len(completion_prefix)].strip(' ') in ['from', 'import']

            if (len_or_dot and unicode(completion_prefix[-1]) not in TextBlock.WORD_STOP_CHARS and len(event.text()) > 0) or in_string_prefix is not None:
                try:
                    # Filename completion when in string
                    if in_string_prefix is not None:
                        logger.debug(msg("Filename completion"))
                        model = QDirModel()
                        # model = QFileSystemModel()
                        # logger.debug(msg("Current Path:", QDir.currentPath()))
                        # model.setRootPath(QDir.currentPath())
                        if len(in_string_prefix) == 0 or not in_string_prefix[0] == os.sep:
                            in_string_prefix = unicode(
                                QDir.currentPath()+QDir.separator() + in_string_prefix)
                        logger.debug(msg("prefix", in_string_prefix))
                        self.completer.setModel(model)
                        self.completer.setCompletionPrefix(in_string_prefix)
                    # Complete import of packages
                    elif need_import_completion:
                        logger.debug(msg(
                            "Getting import completions for ", completion_prefix, "..."))
                        completions = self.get_import_completions(
                            unicode(completion_prefix).strip(' '), _timeout=0.1, _default=None)
                        if completions is None:
                            logger.debug(msg("Completions timeouted ..."))
                            self._widgetKeyPressEvent(event)
                            return True
                        logger.debug(msg(
                            "Got completions:", ','.join(completions)))
                        model = QStringListModel(completions)
                        self.completer.setModel(model)
                        self.completer.setCompletionPrefix(unicode(completion_prefix).strip(' '))
                    elif need_dict_completion:
                        logger.debug(msg(
                            "Getting dict completions for ", dct, "key == ", key))
                        completions = self.get_dict_completions(dct, key, _timeout=0.01, _default=None)
                        if completions is None:
                            logger.debug(msg("No completions ..."))
                            self._widgetKeyPressEvent(event)
                            return True
                        logger.debug(msg(
                            "Got completions:", ','.join(completions)))
                        model = QStringListModel(completions)
                        self.completer.setModel(model)
                        self.completer.setCompletionPrefix(key)
                    # Otherwise we do normal code completion
                    else:
                        logger.debug(msg(
                            "Getting code completions for ", completion_prefix, "..."))
                        completions = self.get_completions(
                            completion_prefix, _timeout=0.1, _default=None)
                        if completions is None:
                            logger.debug(msg("Completions timeouted ..."))
                            self._widgetKeyPressEvent(event)
                            return True
                        logger.debug(msg(
                            "Got completions:", ','.join(completions)))
                        model = QStringListModel(completions)
                        self.completer.setModel(model)
                        self.completer.setCompletionPrefix(completion_prefix)
                    self.completer.popup().setCurrentIndex(
                        self.completer.completionModel().index(0, 0))
                except Exception, e:
                    logger.debug(msg("Exception when completing:", str(e)))
                    if completion_prefix != self.completer.completionPrefix():
                        self.completer.setCompletionPrefix(completion_prefix)
                        self.completer.popup().setCurrentIndex(
                            self.completer.completionModel().index(0, 0))
                cursor_rect = self.widget.cursorRect()
                cursor_rect.setWidth(self.completer.popup().sizeHintForColumn(
                    0) + self.completer.popup().verticalScrollBar().sizeHint().width())
                self.completer.complete(cursor_rect)
            else:
                self.completer.popup().hide()
                self.widget.clearFocus()
                self.widget.setFocus(Qt.ActiveWindowFocusReason)
            return False