Example #1
0
    def __init__(self):
        super(MainWindow, self).__init__()

        # The tabs, one per counter
        self.tabs = QTabWidget()
        #self.tabs.currentChanged.connect(self.currentTabChanged)
        #self.current_tab = 0
        self.setupTabs()

        self.setCentralWidget(self.tabs)

        self.statusBar()
        
        exitAction = QAction(QIcon('exit.png'), '&Exit', self)        
        exitAction.setShortcut('Ctrl+Q')
        exitAction.setStatusTip('Exit application')
        exitAction.triggered.connect(qApp.quit)

        registerAction = QAction('Register', self)
        registerAction.setShortcut('Ctrl+R')
        registerAction.setStatusTip('Register new counter entry')
        registerAction.triggered.connect(self.register)


        menuBar = self.menuBar()
        fileMenu = menuBar.addMenu("&File")

        fileMenu.addAction(registerAction)
        fileMenu.addAction(exitAction)

        self.setWindowTitle("Monepy - v %s" % version)
Example #2
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
Example #3
0
def layercontextmenu( layer, pos, parent=None ):
    '''Show a context menu to manipulate properties of layer.

    layer -- a volumina layer instance
    pos -- QPoint 

    '''
    menu = QMenu("Menu", parent)

    # Title
    title = QAction("%s" % layer.name, menu)
    title.setEnabled(False)
    menu.addAction(title)

    # Export
    global _has_lazyflow
    if _has_lazyflow:    
        export = QAction("Export...",menu)
        export.setStatusTip("Export Layer...")
        export.triggered.connect( partial( get_settings_and_export_layer, layer, menu ) )

    menu.addAction(export)
    menu.addSeparator()
    _add_actions( layer, menu )

    # Layer-custom context menu items
    menu.addSeparator()
    for name, callback in layer.contexts:
        action = QAction(name, menu)
        action.triggered.connect(callback)
        menu.addAction(action)

    menu.exec_(pos)
Example #4
0
def create_action(parent, text, shortcut=None, icon=None, tip=None,
                  toggled=None, triggered=None, data=None,
                  context=Qt.WindowShortcut):
    """Create a QAction"""
    action = QAction(text, parent)
    if triggered is not None:
        parent.connect(action, SIGNAL("triggered()"), triggered)
    if toggled is not None:
        parent.connect(action, SIGNAL("toggled(bool)"), toggled)
        action.setCheckable(True)
    if icon is not None:
        if isinstance(icon, (str, unicode)):
            icon = get_icon(icon)
        action.setIcon( icon )
    if shortcut is not None:
        action.setShortcut(shortcut)
    if tip is not None:
        action.setToolTip(tip)
        action.setStatusTip(tip)
    if data is not None:
        action.setData(QVariant(data))
    #TODO: Hard-code all shortcuts and choose context=Qt.WidgetShortcut
    # (this will avoid calling shortcuts from another dockwidget
    #  since the context thing doesn't work quite well with these widgets)
    action.setShortcutContext(context)
    return action
class ProcessingDirnoProviderPlugin:

    def __init__(self, iface):
        self.provider = DirnoAlgorithmProvider()
        self.iface = iface

    def initGui(self):
        Processing.addProvider(self.provider)
        self.profilAction = QAction(QIcon(os.path.dirname(__file__) + "/icons/iconProvider.png"), "Ajouter un profil", self.iface.mainWindow())
        self.profilAction.setObjectName("dirnoAction")
        self.profilAction.setWhatsThis("Dirno plugin")
        self.profilAction.setStatusTip("This is status tip")
        #QObject.connect(self.profilAction, SIGNAL("triggered()"), self.run)

        # add toolbar button and menu item
        #self.iface.addToolBarIcon(self.profilAction)
        self.iface.addPluginToMenu("&Dirno scripts", self.profilAction)
        self.profilAction.triggered.connect(self.launchDirnoAlgorithProfilDialog)

    def unload(self):
        Processing.removeProvider(self.provider)
        self.iface.removePluginMenu("&Dirno scripts", self.profilAction)
        #self.iface.removeToolBarIcon(self.profilAction)

    def launchDirnoAlgorithProfilDialog(self):
        return DirnoAlgorithmProfilDialog()
Example #6
0
    def initUI(self):
        closeAction = QAction('Close', self)
        closeAction.setShortcut('Ctrl+Q')
        closeAction.setStatusTip('Close Application')
        closeAction.triggered.connect(lambda: sys.exit(0))

        loadAction = QAction('Load Protocol', self)
        loadAction.setStatusTip('Load the Default Protocol')
        loadAction.triggered.connect(self.find_pcl_file)

        menubar = self.menuBar()
        file_menu = menubar.addMenu('&File')
        file_menu.addAction(closeAction)
        load_menu = menubar.addMenu('&Load')
        load_menu.addAction(loadAction)

        self.toolbar = self.addToolBar('Exit')
        self.toolbar.addAction(closeAction)

        load_menu.addSeparator()
        for idx, recent_pcl in enumerate(self.recent_pcls):
            new_action = QAction("%d %s" % (idx + 1, recent_pcl['name']), self)
            new_action.triggered.connect(self.open_recent_pcl)
            new_action.setData(QVariant(recent_pcl['filename']))
            load_menu.addAction(new_action)

        self.setWindowTitle('fealines')
        self.show_empty_screen()
        self.showMaximized()
Example #7
0
    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):


        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
Example #8
0
    def addNewAction(
            self,
            iconPath,
            text,
            callback=None,
            enabled=True,
            checkable=False,
            addToMenu=True,
            addToToolbar=True,
            tip=None,
            whatsThis=None,
            parent=None):
        """Add a toolbar icon to the toolbar"""

        if parent is None:
            parent = self.iface.mainWindow()
        action = QAction(QIcon(iconPath), text, parent)
        if tip is not None:
            action.setStatusTip(tip)
        if whatsThis is not None:
            action.setWhatsThis(whatsThis)

        if callback is not None:
            action.triggered.connect(callback)
        action.setEnabled(enabled)
        action.setCheckable(checkable)

        self.addAction(action, addToMenu, addToToolbar)
        return action
    def load(self):
        self.initTranslations()
        import vtk, VtkWidget, VtkWindow, Objects, Helpers
        self.vtk = vtk
        self.VtkWidget = VtkWidget
        self.VtkWindow = VtkWindow
        self.Objects = Objects
        self.Helpers = Helpers
        xpm = QPixmap()
        xpm.loadFromData(self.getFile('3dwin.xpm').read())
        winIcon = QIcon(xpm)
        self.winManager = SubWinManager(glb.mainWin.workSpace, self.VtkWindow.VtkWindow,
                QCoreApplication.translate('VtkWindow', "Vtk Window"), winIcon)
        testAction = QAction(winIcon,
            QCoreApplication.translate('VtkWindow', '&VtkWindow Test'), glb.mainWin)
        testAction.setStatusTip(QCoreApplication.translate('VtkWindow', 'Show a new Vtk test window'))
        QWidget.connect(testAction, SIGNAL("triggered()"), self.test)
        glb.mainWin.plugInMenu.addAction(testAction)

        ftActions = glb.fileTypeActions
        ftActions.addType('application/x-3ds', '.3ds')
        ftActions.addAction(self.show3DS, ('application/x-3ds',),
            QCoreApplication.translate('VtkWindow', 'Open in VtkWindow'), 5)
        ftActions.addType('application/x-vrml', '.wrl')
        ftActions.addAction(self.showVRML, ('application/x-vrml',),
            QCoreApplication.translate('VtkWindow', 'Open in VtkWindow'), 5)

        return True
Example #10
0
    def createAction(self, text="", slot=None, shortcut=None, icon=None,
                     tip=None, checkable=False, signal="triggered()"):
        """Create action out of keyword arguments. Return action.

        Keyword arguments:
        text -- User visible text (default "")
        slot -- function to call (default None)
        shortcut -- Key sequence (default None)
        icon -- Name of icon file (default None)
        tip -- Tooltip (default None)
        checkable -- Should action be checkable (default None)
        signal -- Signal to emit (default "triggered()")

        """
        action = QAction(text, self)
        if icon is not None:
            action.setIcon(QIcon(":/resource/{0}.png".format(icon)))
        if shortcut is not None:
            action.setShortcut(shortcut)
        if tip is not None:
            action.setToolTip(tip)
            action.setStatusTip(tip)
        if slot is not None:
            self.connect(action, SIGNAL(signal), slot)
        if checkable:
            action.setCheckable(True)
        return action
Example #11
0
 def create_action(self, name, shortcut, status_tip, callback, enabled=True):
     action = QAction(name, self)
     action.setShortcut(shortcut)
     action.setStatusTip(status_tip)
     action.triggered.connect(callback)
     action.setEnabled(enabled)
     return action
Example #12
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, 'show_config_warning', 'yes')
     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
     try:
         matplotlib.use('SV4Agg')
     except:
         if cfg.getboolean(cfgsec, 'show_config_warning'):
             QTimer().singleShot(8000, showConfigWarning)
     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 Test'), SimuVis4.Globals.mainWin)
     testAction.setStatusTip(QCoreApplication.translate('MatPlot', 'Show a matplotlib test window'))
     QWidget.connect(testAction, SIGNAL("triggered()"), self.test)
     SimuVis4.Globals.mainWin.plugInMenu.addAction(testAction)
     return True
Example #13
0
def layercontextmenu( layer, pos, parent=None, volumeEditor = None ):
    '''Show a context menu to manipulate properties of layer.

    layer -- a volumina layer instance
    pos -- QPoint 

    '''
    def onExport():
        
        if _has_lazyflow:
            inputArray = layer.datasources[0].request((slice(None),)).wait()
            expDlg = ExportDialog(parent = menu)
            g = Graph()
            piper = OpArrayPiper(g)
            piper.inputs["Input"].setValue(inputArray)
            expDlg.setInput(piper.outputs["Output"],g)
        expDlg.show()
        
    menu = QMenu("Menu", parent)
    title = QAction("%s" % layer.name, menu)
    title.setEnabled(False)
    
    export = QAction("Export...",menu)
    export.setStatusTip("Export Layer...")
    export.triggered.connect(onExport)
    
    menu.addAction(title)
    menu.addAction(export)
    menu.addSeparator()
    _add_actions( layer, menu )
    menu.exec_(pos)    
class ToggleActiveLayerPlugin:

  def __init__(self, iface):
    self.iface = iface
    self.canvas = iface.mapCanvas() 

    self.action = None
    self.tool = ToggleActiveLayerMapTool( self.iface )

  def initGui(self):
    title = "Toggle visibility of active layer"
    icon = QIcon( os.path.join( os.path.dirname(__file__), 'toggleactivelayer.png' ) )
    self.action = QAction( icon, title, self.iface.mainWindow() )
    self.action.setObjectName( "ToggleActiveLayerPlugin" )
    self.action.setWhatsThis( title )
    self.action.setStatusTip( title )
    self.action.triggered.connect( self.run )

    # Maptool
    self.action.setCheckable( True )
    self.tool.setAction( self.action )

    self.iface.addToolBarIcon( self.action )

  def unload(self):
    self.canvas.unsetMapTool( self.tool )
    self.iface.removeToolBarIcon( self.action )
    del self.action

  @pyqtSlot()
  def run(self):
    if self.canvas.mapTool() != self.tool:
      self.canvas.setMapTool( self.tool)
Example #15
0
class MapSwipePlugin:

  def __init__(self, iface):
    
    def translate():
      #
      # For create file 'qm'
      # 1) Define that files need for translation: mapswipetool.pro
      # 2) Create 'ts': pylupdate4 -verbose mapswipetool.pro
      # 3) Edit your translation: QtLinquist
      # 4) Create 'qm': lrelease *.ts 
      #
      dirname = os.path.dirname( os.path.abspath(__file__) )
      locale = QSettings().value("locale/userLocale")
      localePath = os.path.join( dirname, "i18n", "%s_%s.qm" % ( name_src, locale ) )
      if os.path.exists(localePath):
        self.translator = QTranslator()
        self.translator.load(localePath)
        if qVersion() > '4.3.3':
          QCoreApplication.installTranslator(self.translator)      

    self.iface = iface
    self.canvas = iface.mapCanvas() 
    self.action = None # Define by initGui
    self.tool = MapSwipeTool( self.iface )
    self.prevTool = None # Define by run

    name_src = "mapswipetool"
    translate()

  def initGui(self):
    title = "Map swipe tool"
    icon = QIcon( os.path.join( os.path.dirname(__file__), 'mapswipetool.png' ) )
    self.action = QAction( icon, title, self.iface.mainWindow() )
    self.action.setObjectName( "MapSwipeTool" )
    self.action.setWhatsThis( title )
    self.action.setStatusTip( title )
    self.action.triggered.connect( self.run )
    self.menu = "&Map swipe tool"

    # Maptool
    self.action.setCheckable( True )
    self.tool.setAction( self.action )

    self.iface.addToolBarIcon( self.action )
    self.iface.addPluginToMenu( self.menu, self.action )

  def unload(self):
    self.canvas.unsetMapTool( self.tool )
    self.iface.removeToolBarIcon( self.action )
    self.iface.removePluginMenu( self.menu, self.action )
    del self.action

  @pyqtSlot()
  def run(self):
    if self.canvas.mapTool() != self.tool:
      self.prevTool = self.canvas.mapTool()
      self.canvas.setMapTool( self.tool )
    else:
      self.canvas.setMapTool( self.prevTool )
Example #16
0
    def __init__(self, Ui_MainWindow, timeout=1000):
        super(FellesGui, self).__init__()

        self.setAttribute(Qt.WA_DeleteOnClose)

        exitAction = QAction('Quit', self)
        exitAction.setShortcut('Ctrl+Q')
        exitAction.setStatusTip('Quit application')
        print("Push 'Ctrl+Q' to quit the application")
        exitAction.triggered.connect(self.close)

        # Create Widget for the purpose of updating the widgets periodically
        #self.timer = QTimer()
        #self.timer.timeout.connect(self.paintEvent)
        #self.timer.start(timeout)

        # --> Instantiate UI  !!! This is where the widgets are initiated !!!
        self.buildUi(Ui_MainWindow)

        # --> Setup the Menu Bar
        fileMenu = self.menuBar().addMenu('&File')
        fileMenu.addAction(exitAction)

        # --> Order widgets to connect to their slaves
        self.initialiseSlaves.emit()

        # -->  Initialise "Threads" performing the sampling
        ports = QFellesWidgetBaseClass.___ports___.keys()
        self.sampling_threads = [ FellesThread(port) for port in ports ]

        #self.statusBar().showMessage.connect(FellesThread.sample_failed)
        self.statusBar().showMessage('Idling...')
Example #17
0
    def initUI(self):      

        self.textEdit = QTextEdit()
        self.textEdit.setReadOnly(True)
        
        self.setCentralWidget(self.textEdit)
        self.statusBar()

        icon_open = QIcon.fromTheme("document-open", QIcon(":/open.png"))
        icon_save = QIcon.fromTheme("document-save-as")
        icon_copy = QIcon.fromTheme("edit-copy")
        icon_clear = QIcon.fromTheme("edit-clear")

        openFile = QAction(QIcon(icon_open), 'Open', self)
        openFile.setShortcut('Ctrl+O')
        openFile.setStatusTip('Open new File')
        openFile.triggered.connect(self.showLoadDialog)

        self.saveFile = QAction(QIcon(icon_save), 'Save', self)
        self.saveFile.setShortcut('Ctrl+S')
        self.saveFile.setStatusTip('Save data to File')
        self.saveFile.triggered.connect(self.showSaveDialog)
        self.saveFile.setDisabled(True)

        self.clearData = QAction(QIcon(icon_clear), 'Clear', self)
        self.clearData.setShortcut('Ctrl+D')
        self.clearData.setStatusTip('Clear data')
        self.clearData.triggered.connect(self.clear_event)
        self.clearData.setDisabled(True)

        self.copyData = QAction(QIcon(icon_copy), 'Copy', self)
        self.copyData.setShortcut('Ctrl+C')
        self.copyData.setStatusTip('Copy data to clipboard')
        self.copyData.triggered.connect(self.copy_event)
        self.copyData.setDisabled(True)

        exitAction = QAction(QIcon(), 'Exit', self)
        exitAction.setShortcut('Ctrl+Q')
        exitAction.triggered.connect(qApp.quit)

        menubar = self.menuBar()
        fileMenu = menubar.addMenu('&File')
        fileMenu.addAction(openFile)
        fileMenu.addAction(self.saveFile)   
        fileMenu.addAction(self.copyData)
        fileMenu.addAction(self.clearData)
        fileMenu.addSeparator()
        fileMenu.addAction(exitAction)

        fileToolBar = self.addToolBar("Load and Save")
        fileToolBar.setIconSize(QSize(22, 22))
        fileToolBar.addAction(openFile)
        fileToolBar.addAction(self.saveFile)
        fileToolBar.addAction(self.copyData)
        fileToolBar.addAction(self.clearData)

        self.setGeometry(300, 300, 400, 600)
        self.setWindowTitle('File dialog')
        self.show()
Example #18
0
class MetaSearchPlugin(object):
    """base plugin"""

    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"

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

    def unload(self):
        """teardown"""

        # remove the plugin menu item and icon
        self.iface.removePluginWebMenu(self.web_menu, self.action_run)
        self.iface.removePluginWebMenu(self.web_menu, self.action_help)
        self.iface.removeWebToolBarIcon(self.action_run)

    def run(self):
        """open MetaSearch"""

        self.dialog.exec_()

    def help(self):
        """open help in user's default web browser"""

        open_url(self.context.metadata.get("general", "homepage"))
Example #19
0
 def load(self):
     self.initTranslations()
     import Meteo2Nc
     self.Meteo2Nc = Meteo2Nc
     self.menu = QMenu(QCoreApplication.translate('SmileKit', 'SMILE'))
     mn2ncAction = QAction(QIcon(), QCoreApplication.translate('SmileKit', 'Meteonorm weather import'), SimuVis4.Globals.mainWin)
     mn2ncAction.setStatusTip(QCoreApplication.translate('SmileKit', 'Convert Meteonorm weather files to netCDF format'))
     QObject.connect(mn2ncAction, SIGNAL("triggered()"), self.showMn2NcWindow)
     self.menu.addAction(mn2ncAction)
     SimuVis4.Globals.mainWin.plugInMenu.addMenu(self.menu)
     return True
Example #20
0
    def __init__(self, config):
        # Initialize the object as a QWidget and
        # set its title and minimum width

        QWidget.__init__(self)

        self.config = config
        self.peerList = config.peerList
        self.setWindowTitle('BlastShare')
        self.setMinimumSize(320, 480)
        self.setMaximumWidth(320)
        self.prefw = None
        
        # connects the signals!
        self.connect(self.peerList,
                     SIGNAL("initTransfer"), self.sendFileToPeer)

        ''' Will add feature in future version '''
        '''
        shareFilesAction = QAction(QIcon('exit.png'), '&Share File(s)', self)
        shareFilesAction.setShortcut('Ctrl+O')
        shareFilesAction.setStatusTip('Share File(s)')
        shareFilesAction.triggered.connect(quitApp)
        '''
        
        preferencesAction = QAction(QIcon('exit.png'), '&Preferences', self)
        preferencesAction.setShortcut('Ctrl+P')
        preferencesAction.setStatusTip('Preferences')
        preferencesAction.triggered.connect(self.editPreferences)

        exitAction = QAction(QIcon('exit.png'), '&Exit', self)
        exitAction.setShortcut('Ctrl+Q')
        exitAction.setStatusTip('Exit application')
        exitAction.triggered.connect(quitApp)

        menubar = QMenuBar()
        fileMenu = menubar.addMenu('&File')
        
        ''' Will enable in future versions '''
        # fileMenu.addAction(shareFilesAction)
        
        fileMenu.addAction(preferencesAction)
        fileMenu.addAction(exitAction)

        layout = QVBoxLayout()
        layout.setContentsMargins(QMargins(0, 0, 0, 0))
        self.setLayout(layout)
        
        statusBar = QStatusBar()
        statusBar.showMessage('Ready')
        
        layout.addWidget(menubar)
        layout.addWidget(self.peerList)
        layout.addWidget(statusBar)
Example #21
0
def layercontextmenu( layer, pos, parent=None, volumeEditor = None ):
    '''Show a context menu to manipulate properties of layer.

    layer -- a volumina layer instance
    pos -- QPoint 

    '''
    def onExport():
        sourceTags = [True for l in layer.datasources]
        for i, source in enumerate(layer.datasources):
            if not hasattr(source, "dataSlot"):
                 sourceTags[i] = False
        if not any(sourceTags):
            raise RuntimeError("can not export from a non-lazyflow data source (layer=%r, datasource=%r)" % (type(layer), type(layer.datasources[0])) )


        expDlg = ExportDialog(parent = menu, layername = layer.name)
        if not _has_lazyflow:
            raise RuntimeError("lazyflow not installed") 
        import lazyflow
        dataSlots = [slot.dataSlot for (slot, isSlot) in
                     zip(layer.datasources, sourceTags) if isSlot is True]
        op = lazyflow.operators.OpMultiArrayStacker(dataSlots[0].getRealOperator())
        for slot in dataSlots:
            assert isinstance(slot, lazyflow.graph.Slot), "slot is of type %r" % (type(slot))
            assert isinstance(slot.getRealOperator(), lazyflow.graph.Operator), "slot's operator is of type %r" % (type(slot.getRealOperator()))
        op.AxisFlag.setValue("c")
        op.Images.resize(len(dataSlots))
        for i,islot in enumerate(op.Images):
            islot.connect(dataSlots[i])
        expDlg.setInput(op.Output)

        expDlg.show()
        
    menu = QMenu("Menu", parent)
    title = QAction("%s" % layer.name, menu)
    title.setEnabled(False)
    
    export = QAction("Export...",menu)
    export.setStatusTip("Export Layer...")
    export.triggered.connect(onExport)
    
    menu.addAction(title)
    menu.addAction(export)
    menu.addSeparator()
    _add_actions( layer, menu )

    menu.addSeparator()
    for name, callback in layer.contexts:
        action = QAction(name, menu)
        action.triggered.connect(callback)
        menu.addAction(action)

    menu.exec_(pos)    
    def add_action( self, icon_path,  text, callback, enabled_flag=True,  add_to_menu=True, add_to_toolbar=True, status_tip=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

        :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 add_to_toolbar:
            self.toolbar.addAction(action)

        if add_to_menu:
            self.iface.addPluginToDatabaseMenu( self.menu, action)

        self.actions.append(action)

        return action
Example #23
0
 def addDockAction(self, iconPath, text, callback=None, enabled=True, checkable=False, tip=None, whatsThis=None):
     action = QAction(QIcon(iconPath), text, self._dock)
     if callback is not None:
         action.triggered.connect(callback)
     action.setEnabled(enabled)
     action.setCheckable(checkable)
     if tip is not None:
         action.setStatusTip(tip)
     if whatsThis is not None:
         action.setWhatsThis(whatsThis)
     self._dock.toolbar.addAction(action)
     # self.actions.append(action)
     return action
Example #24
0
    def __init__(self, parent=None):
        QMainWindow.__init__(self, parent)

        self.setIconSize(QSize(48, 48))

        self.widtab = QTabWidget()
        # widtab.addTab(QLabel("Tab1"), "Tab 1")
        self._bba = {}
        # self._bba_plot_data = []
        self._canvas_wid = []
        #
        self.setCentralWidget(self.widtab)

        #
        # file menu
        #
        self.fileMenu = self.menuBar().addMenu("&File")
        fileQuitAction = QAction(QIcon(":/file_quit.png"), "&Quit", self)
        fileQuitAction.setShortcut("Ctrl+Q")
        fileQuitAction.setToolTip("Quit the application")
        fileQuitAction.setStatusTip("Quit the application")
        self.connect(fileQuitAction, SIGNAL("triggered()"), self.close)
        fileConfigAction = QAction("&Config", self)
        #
        fileOpenAction = QAction(QIcon(":file_quit.png"), "&Open...", self)
        fileOpenAction.setToolTip("Open an existing data file")
        self.connect(fileOpenAction, SIGNAL("triggered()"), self.fileOpen)

        self.fileMenu.addAction(fileOpenAction)
        self.fileMenu.addAction(fileQuitAction)
        self.fileMenu.addAction(fileConfigAction)

        self.controlMenu = self.menuBar().addMenu("&Control")

        controlGoAction = QAction(QIcon(":/control_play.png"), "&Go", self)
        controlGoAction.setShortcut("Ctrl+G")
        # fileQuitAction.setToolTip("Quit the application")
        # fileQuitAction.setStatusTip("Quit the application")
        # fileQuitAction.setIcon(Qt.QIcon(":/filequit.png"))
        self.controlMenu.addAction(controlGoAction)
        self.connect(controlGoAction, SIGNAL("triggered()"), self.align)

        # help
        self.helpMenu = self.menuBar().addMenu("&Help")

        # toolbar = QToolBar(self)
        # self.addToolBar(toolbar)
        fileToolBar = self.addToolBar("File")
        fileToolBar.setObjectName("FileToolBar")
        fileToolBar.addAction(fileQuitAction)
        fileToolBar.addAction(controlGoAction)
Example #25
0
 def createAction(self, text, slot=None, shortcut=None, icon=None, tip=None, checkable=False):
     action = QAction(text, self)
     if slot is not None:
         action.triggered.connect(slot)
     if shortcut is not None:
         action.setShortcut(shortcut)
     if icon is not None:
         action.setIcon(QIcon(":/{}.png".format(icon)))
     if tip is not None:
         action.setToolTip(tip)
         action.setStatusTip(tip)
     if checkable:
         action.setCheckable(True)
     return action
Example #26
0
def createAction(parent, text, slot=None, shortcut=None, icon=None, tip=None, checkable=False, signal="triggered()"):
    action = QAction(text, parent)
    if icon is not None:
        action.setIcon(QIcon(":/%s.png" % icon))
    if shortcut is not None:
        action.setShortcut(shortcut)
    if tip is not None:
        action.setToolTip(tip)
        action.setStatusTip(tip)
    if slot is not None:
        parent.connect(action, SIGNAL(signal), slot)
    if checkable:
        action.setCheckable(True)
    return action
Example #27
0
 def load(self):
     import GraphicsWindow, Items
     self.GraphicsWindow = GraphicsWindow
     self.Items = Items
     xpm = QPixmap()
     xpm.loadFromData(self.getFile('graphicswin.xpm').read())
     winIcon = QIcon(xpm)
     self.winManager = SubWinManager(SimuVis4.Globals.mainWin.workSpace, self.GraphicsWindow.GraphicsWindow,
         QCoreApplication.translate('Graphics', "GraphicsView"), winIcon)
     testAction = QAction(winIcon,
         QCoreApplication.translate('Graphics', '&Graphics Test'), SimuVis4.Globals.mainWin)
     testAction.setStatusTip(QCoreApplication.translate('Graphics', 'Show a new graphics window'))
     QWidget.connect(testAction, SIGNAL("triggered()"), self.test)
     SimuVis4.Globals.mainWin.plugInMenu.addAction(testAction)
     return True
Example #28
0
 def set_menu_items(self, db, tag, names):
     """Some of the menus change their content dynamically in runtime.
        This method updates menu specified by 'tag' with the items
        given in 'names'.
     """
     menu, fb = self.dynamic_menus[tag]
     group = QActionGroup(self, exclusive=True)
     menu.clear()
     for name in names:
         action = QAction(name, self, checkable=True)
         action.setStatusTip('Select item')
         action.triggered.connect(partial(fb, self, db, name))
         a = group.addAction(action)
         menu.addAction(a)
         if db.selection[tag] == name:
             a.toggle()
Example #29
0
def create_action(parent, text, slot=None, shortcut=None, icon=None, tip=None,
    checkable=False, signal="triggered()"):
    '''Helper function that creates QActions with a given QObject parent.'''
    action = QAction(text, parent)
    if icon is not None:
        action.setIcon(QIcon(":/%s.png" % icon))
    if shortcut is not None:
        action.setShortcut(shortcut)
    if tip is not None:
        action.setToolTip(tip)
        action.setStatusTip(tip)
    if slot is not None:
        QObject.connect(action, SIGNAL(signal), slot)
    if checkable:
        action.setCheckable(True)
    return action
Example #30
0
 def createAction(self, text, slot=None, shortcut=None, icon=None, tip=None,
                  checkable=False, signal="triggered()"):
     """Borrowed from 'Rapid GUI Development with PyQT by Mark Summerset'"""
     action = QAction(text, self)
     if icon is not None:
         action.setIcon(QIcon.fromTheme(icon, QIcon(":/%s.png" % icon)))
     if shortcut is not None and not shortcut.isEmpty():
         action.setShortcut(shortcut)
         tip += " (%s)" % shortcut.toString()
     if tip is not None:
         action.setToolTip(tip)
         action.setStatusTip(tip)
     if slot is not None:
         self.connect(action, SIGNAL(signal), slot)
     if checkable:
         action.setCheckable()
     return action
Example #31
0
    def add_action(self,
                   icon_path,
                   text,
                   callback,
                   store_val,
                   enabled_flag=True,
                   add_to_menu=True,
                   add_to_toolbar=True,
                   status_tip=None,
                   whats_this=None,
                   parent=None,
                   dialog=mainPlugDialog()):
        # type: (object, object, object, object, object, object, object,
        # object, object, object, object) -> object
        """Add a toolbar icon to the toolbar.

        :param store_val: This value is the position to store the Dialog within the dialog list, Note that this position
        can and will interfere with standard operation if it is stored in an incorrect position at this time
        :type store_val: int

        :param dialog: The dialog you wish to Display to users
        :type dialog: function

        :param icon_path: Path to the icon for this action. Can be a resource
            path (e.g. ':/plugins/foo/bar.png') or a normal file system path.
        :type icon_path: str

        :param text: Text that should be shown in menu items for this action.
        :type text: str

        :param callback: Function to be called when the action is triggered.
        :type callback: function

        :param enabled_flag: A flag indicating if the action should be enabled
            by default. Defaults to True.
        :type enabled_flag: bool

        :param add_to_menu: Flag indicating whether the action should also
            be added to the menu. Defaults to True.
        :type add_to_menu: bool

        :param add_to_toolbar: Flag indicating whether the action should also
            be added to the toolbar. Defaults to True.
        :type add_to_toolbar: bool

        :param status_tip: Optional text to show in a popup when mouse pointer
            hovers over the action.
        :type status_tip: str

        :param parent: Parent widget for the new action. Defaults None.
        :type parent: QWidget

        :param whats_this: Optional text to show in the status bar when the
            mouse pointer hovers over the action.

        :returns: The action that was created. Note that the action is also
            added to self.actions list.
        :rtype: QAction
        """

        # Create the dialog (after translation) and keep reference

        # noinspection PyTypeChecker
        self.DialogStore[store_val] = dialog

        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
Example #32
0
def createAction(parent,
                 label,
                 callback=None,
                 icon=None,
                 tip=None,
                 shortcut=None,
                 data=None,
                 toggled=False,
                 tooltip=None,
                 cb_arg=None,
                 cb_args=None,
                 iconText=None,
                 checkable=None):
    """
    Create a QAction

    @param parent: 
    @type parent:

    @param label: 
    @type label:

    @param callback: 
    @type callback:

    @param icon: 
    @type icon:

    @param tip: 
    @type tip:

    @param shortcut: 
    @type shortcut:

    @param data: 
    @type data:

    @param toggled: 
    @type toggled:

    @return:
    @rtype:
    """
    action = QAction(label, parent)
    if toggled:
        if callback is not None:
            action.toggled.connect(callback)
            action.setCheckable(True)
    else:
        if callback is not None:
            if cb_arg is None:
                action.triggered.connect(callback)
            else:
                if cb_args is None:
                    action.triggered.connect(lambda: callback(cb_arg))
                else:
                    action.triggered.connect(lambda: callback(**cb_args))
    if icon:
        action.setIcon(icon)
    if shortcut:
        action.setShortcut(shortcut)
    if tip:
        action.setStatusTip(tip)
    if tooltip:
        action.setToolTip(tooltip)
    if data is not None:
        action.setData(data)
    if iconText is not None:
        action.setIconText(iconText)
    if checkable is not None:
        action.setCheckable(checkable)
    return action
Example #33
0
    def __init__(self,initlc=False):        ####INITLC FOR TRACING ONLY DELETE IN PRODUCTION
        super(LDSMain, self).__init__()
        
        self.layers = None
        self.groups = None
        self.gpr = None
        self.gvs = None
        
        initcc = True
        #if init=False no point reading gpr vals
        wcount = 0
        while initcc and wcount<self.MAX_WIZARD_ATTEMPTS:
            try:
                self.initConfigConnector(initlc=initlc)
                initcc = False
                break
            except MalformedConnectionString as mcse:
                ldslog.warn('Connection String malformed or missing. '+str(mcse))
                self.runWizardDialog(None,None)
                wcount += 1
            except DriverInitialisationException as die:
                ldslog.warn('Cannot Initialise selected driver. '+str(die))
                self.runWizardDialog(None,None)
                wcount += 1
                #self.initConfigConnector(self.DEF_RVALS)
                #initcc = False
            except Exception as e:
                ldslog.error('Unhandled Exception in Config Setup. '+str(e))
                wcount += 1
        else:
            raise e

        self.setGeometry(*self.WGEO)
        self.setWindowTitle('LDS Data Replicator')
        self.setWindowIcon(QIcon(LINZ))
        
        self.statusbar = self.statusBar()
        self.statusbar.showMessage('Ready')
        
        self.controls = LDSControls(self)
        
        self.setCentralWidget(self.controls)
        
        openUCAction = QAction(QIcon(OPEN), 'Open &User Config', self)        
        openUCAction.setShortcut('Ctrl+U')
        openUCAction.setStatusTip('Open User Preferences Editor')
        openUCAction.triggered.connect(self.launchUCEditor)
        
        openLCAction = QAction(QIcon(OPEN), 'Open &Layer Config', self)        
        openLCAction.setShortcut('Ctrl+L')
        openLCAction.setStatusTip('Open Layer Config File (only applies to external LC storage)')
        openLCAction.triggered.connect(self.launchLCEditor)
        #self.enableLCEdit(openLCAction)
        
        initUCAction = QAction(QIcon(UC), 'Database &Setup Wizard', self)   
        initUCAction.setShortcut('Ctrl+S')
        initUCAction.setStatusTip('Open Database Setup Wizard')
        initUCAction.triggered.connect(self.runWizardAction)
        
        initLCAction = QAction(QIcon(LC), 'Layer &Config Editor', self)   
        initLCAction.setShortcut('Ctrl+C')
        initLCAction.setStatusTip('Open Layer Config Editor')
        initLCAction.triggered.connect(self.runLayerConfigAction)
        
        exitAction = QAction(QIcon(EXIT), '&Exit', self)        
        exitAction.setShortcut('Ctrl+E')
        exitAction.setStatusTip('Exit Application')
        exitAction.triggered.connect(self.close)#qApp.quit)
        
        helpAction = QAction(QIcon(HELP), '&Help', self)        
        helpAction.setShortcut('Ctrl+H')
        helpAction.setStatusTip('Open Help Document')
        helpAction.triggered.connect(self.launchHelpFile)
        
        self.menubar = self.menuBar()

        fileMenu = self.menubar.addMenu('&File')
        fileMenu.addAction(openUCAction)
        fileMenu.addAction(openLCAction)
        fileMenu.addSeparator()
        fileMenu.addAction(initUCAction)
        fileMenu.addAction(initLCAction)
        fileMenu.addSeparator()
        fileMenu.addAction(exitAction)

        helpMenu = self.menubar.addMenu('&Help')
        helpMenu.addAction(helpAction)
class StartOutofBoundsAngles:
    def __init__(self, iface):

        self.iface = iface

        self.tableSchema = 'edgv'
        self.geometryColumn = 'geom'
        self.keyColumn = 'id'
        self.angle = 10

    def initGui(self):
        # cria uma ação que iniciará a configuração do plugin
        pai = self.iface.mainWindow()
        icon_path = ':/plugins/StartOutofBoundsAngles/icon.png'
        self.action = QAction(
            QIcon(icon_path),
            u"Acessa banco de dados para encontrar anglos fechados.", pai)
        self.action.setObjectName("Start database")
        self.action.setStatusTip(None)
        self.action.setWhatsThis(None)
        self.action.triggered.connect(self.run)
        # Adicionar o botão icone
        self.iface.addToolBarIcon(self.action)

    def unload(self):
        # remove o item de ícone do QGIS GUI.
        self.iface.removeToolBarIcon(self.action)

    def run(self):

        ##################################
        ###### PEGA A LAYER ATIVA ########
        ##################################

        layer = self.iface.activeLayer()

        if not layer:
            self.iface.messageBar().pushMessage("Erro",
                                                u"Esperando uma Active Layer!",
                                                level=QgsMessageBar.CRITICAL,
                                                duration=4)
            return
        if layer.featureCount() == 0:
            self.iface.messageBar().pushMessage(
                "Erro",
                u"a camada não possui feições!",
                level=QgsMessageBar.CRITICAL,
                duration=4)
            return

        parametros = layer.source().split(
            " "
        )  # recebe todos os parametros em uma lista ( senha, porta, password etc..)

        ####################################
        ###### INICIANDO CONEXÃO DB ########
        ####################################

        # Outra opção para isso, seria usar ex: self.dbname.. self.host.. etc.. direto dentro do laço for.
        dbname = ""
        host = ""
        port = 0
        user = ""
        password = ""

        for i in parametros:
            part = i.split("=")

            # Recebe os parametros guardados na própria Layer

            if "dbname" in part[0]:
                dbname = part[1].replace("'", "")

            elif "host" in part[0]:
                host = part[1].replace("'", "")

            elif "port" in part[0]:
                port = int(part[1].replace("'", ""))

            elif "user" in part[0]:
                user = part[1].replace("'", "")

            elif "password" in part[0]:
                password = part[1].split("|")[0].replace("'", "")

        print dbname, host, port, user, password

        # Testa se os parametros receberam os valores pretendidos, caso não, apresenta a mensagem informando..
        if len(dbname) == 0 or len(host) == 0 or port == 0 or len(
                user) == 0 or len(password) == 0:
            self.iface.messageBar().pushMessage(
                "Erro",
                u'Um dos parametros não foram devidamente recebidos!',
                level=QgsMessageBar.CRITICAL,
                duration=4)
            return

    ####################################
    #### SETA VALORES DE CONEXÃO DB ####
    ####################################

        connection = QSqlDatabase.addDatabase('QPSQL')
        connection.setHostName(host)
        connection.setPort(port)
        connection.setUserName(user)
        connection.setPassword(password)
        connection.setDatabaseName(dbname)

        if not connection.isOpen(
        ):  # Testa se a conexão esta recebendo os parametros adequadamente.
            if not connection.open():
                print 'Error connecting to database!'
                self.iface.messageBar().pushMessage(
                    "Erro",
                    u'Error connecting to database!',
                    level=QgsMessageBar.CRITICAL,
                    duration=4)
                print connection.lastError().text()
                return

    ####################################
    ###### CRIAÇÃO DE MEMORY LAYER #####
    ####################################

        layerCrs = layer.crs().authid()  # Passa o formato (epsg: numeros)

        flagsLayerName = layer.name() + "_flags"
        flagsLayerExists = False

        for l in QgsMapLayerRegistry.instance().mapLayers().values(
        ):  # Recebe todas as camadas que estão abertas
            if l.name() == flagsLayerName:  # ao encontrar o nome pretendido..
                self.flagsLayer = l  # flagslayer vai receber o nome..
                self.flagsLayerProvider = l.dataProvider()
                flagsLayerExists = True  # se encontrado os parametros buscados, recebe True.
                break

        if flagsLayerExists == False:  # se não encontrado os parametros buscados, recebe False.
            tempString = "Point?crs="
            tempString += str(layerCrs)

            self.flagsLayer = QgsVectorLayer(tempString, flagsLayerName,
                                             "memory")
            self.flagsLayerProvider = self.flagsLayer.dataProvider()
            self.flagsLayerProvider.addAttributes([
                QgsField("flagId", QVariant.Int),
                QgsField("geomId", QVariant.String),
                QgsField("motivo", QVariant.String)
            ])
            self.flagsLayer.updateFields()

        self.flagsLayer.startEditing()
        ids = [feat.id() for feat in self.flagsLayer.getFeatures()]
        self.flagsLayer.deleteFeatures(ids)
        self.flagsLayer.commitChanges()

        lista_fid = []  # Iniciando lista
        for f in layer.getFeatures():
            lista_fid.append(
                str(f.id())
            )  # Guarda na lista. A lista de Feature ids passa tipo "int", foi convertido e guardado como "str".

        source = layer.source().split(" ")
        self.tableName = ""  # Inicia vazio
        layerExistsInDB = False

        for i in source:

            if "table=" in i or "layername=" in i:  # Se encontrar os atributos pretendidos dentre todos do for
                self.tableName = source[source.index(i)].split(".")[
                    1]  # Faz split em ponto e pega a segunda parte.
                self.tableName = self.tableName.replace('"', '')
                layerExistsInDB = True
                break

        if layerExistsInDB == False:
            self.iface.messageBar().pushMessage(
                "Erro",
                u"Provedor da camada corrente não provem do banco de dados!",
                level=QgsMessageBar.CRITICAL,
                duration=4)
            return

        geomType = layer.geometryType()

        if geomType == QGis.Line:

            # Busca através do SQL
            sql = """
            WITH result AS (SELECT points."{4}", points.anchor, (degrees
                                        (
                                            ST_Azimuth(points.anchor, points.pt1) - ST_Azimuth(points.anchor, points.pt2)
                                        )::decimal + 360) % 360 as angle
                        FROM
                        (SELECT
                              ST_PointN("{3}", generate_series(1, ST_NPoints("{3}")-2)) as pt1, 
                              ST_PointN("{3}", generate_series(2, ST_NPoints("{3}")-1)) as anchor,
                              ST_PointN("{3}", generate_series(3, ST_NPoints("{3}"))) as pt2,
                              linestrings."{4}" as "{4}" 
                            FROM
                              (SELECT "{4}" as "{4}", (ST_Dump("{3}")).geom as "{3}"
                               FROM only "{0}"."{1}"
                               ) AS linestrings WHERE ST_NPoints(linestrings."{3}") > 2 ) as points)
            select distinct "{4}", ST_AsText(anchor), angle from result where (result.angle % 360) < {2} or result.angle > (360.0 - ({2} % 360.0)) and result.{4} in ({5})""".format(
                self.tableSchema, self.tableName, self.angle,
                self.geometryColumn, self.keyColumn, ",".join(lista_fid))

        elif geomType == QGis.Polygon:
            sql = """
            WITH result AS (SELECT points."{4}", points.anchor, (degrees
                                        (
                                            ST_Azimuth(points.anchor, points.pt1) - ST_Azimuth(points.anchor, points.pt2)
                                        )::decimal + 360) % 360 as angle
                        FROM
                        (SELECT
                              ST_PointN("{3}", generate_series(1, ST_NPoints("{3}")-1)) as pt1,
                              ST_PointN("{3}", generate_series(1, ST_NPoints("{3}")-1) %  (ST_NPoints("{3}")-1)+1) as anchor,
                              ST_PointN("{3}", generate_series(2, ST_NPoints("{3}")) %  (ST_NPoints("{3}")-1)+1) as pt2,
                              linestrings."{4}" as "{4}"
                            FROM
                              (SELECT "{4}" as "{4}", (ST_Dump(ST_Boundary(ST_ForceRHR((ST_Dump("{3}")).geom)))).geom as "{3}"
                               FROM only "{0}"."{1}" 
                               ) AS linestrings WHERE ST_NPoints(linestrings."{3}") > 2 ) as points)
            select distinct "{4}", ST_AsText(anchor), angle from result where (result.angle % 360) < {2} or result.angle > (360.0 - ({2} % 360.0)) and result.{4} in ({5})""".format(
                self.tableSchema, self.tableName, self.angle,
                self.geometryColumn, self.keyColumn, ",".join(lista_fid))
        query = QSqlQuery(sql)

        self.flagsLayer.startEditing()
        flagCount = 0  # iniciando contador que será referência para os IDs da camada de memória.

        listaFeatures = []
        while query.next():
            id = query.value(0)
            local = query.value(1)
            angulo = query.value(2)
            flagId = flagCount

            print id, local, angulo

            flagFeat = QgsFeature()
            flagGeom = QgsGeometry.fromWkt(
                local)  # passa o local onde foi localizado o erro.
            flagFeat.setGeometry(flagGeom)
            flagFeat.initAttributes(3)
            flagFeat.setAttribute(
                0, flagId
            )  # insere o id definido para a coluna 0 da layer de memória.
            flagFeat.setAttribute(
                1, id
            )  # insere o id da geometria  para a coluna 1 da layer de memória.
            flagFeat.setAttribute(
                2, u"Ângulo para os vértices adjacentes inferior à tolerância")

            # TypeError: fromWkt(QString): argument 1 has unexpected type 'long'
            #     Traceback (most recent call last):
            #     File "/home/piangers/.qgis2/python/plugins/StartDuplic/StartDuplic.py", line 177, in run
            #     flagGeom = QgsGeometry.fromWkt(local) # passa o local onde foi localizado o erro.

            listaFeatures.append(flagFeat)

            flagCount += 1  # incrementando o contador a cada iteração

        self.flagsLayerProvider.addFeatures(listaFeatures)
        self.flagsLayer.commitChanges()  # Aplica as alterações à camada.

        QgsMapLayerRegistry.instance().addMapLayer(
            self.flagsLayer)  # Adicione a camada no mapa

        if flagCount == 0:

            QgsMapLayerRegistry.instance().removeMapLayer(self.flagsLayer.id())
            self.iface.messageBar().pushMessage(
                "Aviso",
                u"Não foi encontrado Flags em \"" + layer.name() + "\" !",
                level=QgsMessageBar.CRITICAL,
                duration=4)

            return
        if len(query.lastError().text()) == 1:
            self.iface.messageBar().pushMessage(
                "Aviso",
                "foram geradas " + str(flagCount) + " flags para a camada \"" +
                layer.name() + "\" !",
                level=QgsMessageBar.INFO,
                duration=4)
        else:
            self.iface.messageBar().pushMessage("Erro",
                                                u"a geração de flags falhou!",
                                                level=QgsMessageBar.CRITICAL,
                                                duration=4)
            print query.lastError().text()
Example #35
0
    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):
        """Agrega una acción la la barra de herramientas, y al menú del plugin.

        :param icon_path: Ruta del icono. Puede ser la ruta de un recurso recurso
            (ejemplo: ':/plugins/foo/bar.png') o una ruta normal del sistema de archivos
        :type icon_path: str

        :param text: Texto que será mostrado en el menu de opciones de plugin para esta accion.
        :type text: str

        :param callback: Función que será llamada cuando se hace click sobre la acción.
        :type callback: function

        :param enabled_flag: Una bandera que indica si la acción debería ser activada
            por defecto. Por defecto este valor esta en True.
        :type enabled_flag: bool

        :param add_to_menu: Una bandera indicando si la acción debería ser agregada
            al menú de opciones del plugin. Por defecto esta en True
        :type add_to_menu: bool

        :param add_to_toolbar: Una bandera indicando si la acción debería ser agregada
            a la barra de herramientas del plugin. Por defecto esta en True
        :type add_to_toolbar: bool

        :param status_tip: Texto opcional que aparecerá cuando el puntero del mouse
            se pocisione sobre la acción.
        :type status_tip: str

        :param parent: Widget padre de la nueva acción. Por defecto será None
        :type parent: QWidget

        :param whats_this: Texto opcional para mostrar en la barra de estatus,
            cuando el puntero del mouse se pocisione sobre la acción.

        :returns: La acción que fue creada. Notar que la acción también es
            agregada a 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
Example #36
0
class Plugin:
    """The QGIS interface implementation for the Risk in a box plugin.

    This class acts as the 'glue' between QGIS and our custom logic.
    It creates a toolbar and menubar entry and launches the InaSAFE user
    interface if these are activated.
    """
    def __init__(self, iface):
        """Class constructor.

        On instantiation, the plugin instance will be assigned a copy
        of the QGIS iface object which will allow this plugin to access and
        manipulate the running QGIS instance that spawned it.

        Args:
            iface - a Quantum GIS QGisAppInterface instance. This instance
                is automatically passed to the plugin by QGIS when it loads the
                plugin.
        Returns:
           None.
        Raises:
           no exceptions explicitly raised.
        """

        # Save reference to the QGIS interface
        self.iface = iface
        self.translator = None
        self.setupI18n()
        #print self.tr('InaSAFE')
        utilities.setupLogger()

    #noinspection PyArgumentList
    def setupI18n(self, thePreferredLocale=None):
        """Setup internationalisation for the plugin.

        See if QGIS wants to override the system locale
        and then see if we can get a valid translation file
        for whatever locale is effectively being used.

        Args:
           thePreferredLocale - optional parameter which if set
           will override any other way of determining locale..
        Returns:
           None.
        Raises:
           TranslationLoadException
        """
        myOverrideFlag = QSettings().value('locale/overrideFlag',
                                           QVariant(False)).toBool()

        if thePreferredLocale is not None:
            myLocaleName = thePreferredLocale
        elif myOverrideFlag:
            myLocaleName = QSettings().value('locale/userLocale',
                                             QVariant('')).toString()
        else:
            myLocaleName = QLocale.system().name()
            # NOTES: we split the locale name because we need the first two
            # character i.e. 'id', 'af, etc
            myLocaleName = str(myLocaleName).split('_')[0]

        # Also set the system locale to the user overridden local
        # so that the inasafe library functions gettext will work
        # .. see:: :py:func:`common.utilities`
        os.environ['LANG'] = str(myLocaleName)

        LOGGER.debug(
            '%s %s %s %s' % (thePreferredLocale, myOverrideFlag,
                             QLocale.system().name(), os.environ['LANG']))

        myRoot = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
        myTranslationPath = os.path.join(
            myRoot, 'safe_qgis', 'i18n',
            'inasafe_' + str(myLocaleName) + '.qm')

        if os.path.exists(myTranslationPath):
            self.translator = QTranslator()
            myResult = self.translator.load(myTranslationPath)
            if not myResult:
                myMessage = 'Failed to load translation for %s' % myLocaleName
                raise TranslationLoadError(myMessage)
            QCoreApplication.installTranslator(self.translator)

        LOGGER.debug('%s %s' %
                     (myTranslationPath, os.path.exists(myTranslationPath)))

    def tr(self, theString):
        """We implement this ourself since we do not inherit QObject.

        Args:
           theString - string for translation.
        Returns:
           Translated version of theString.
        Raises:
           no exceptions explicitly raised.
        """
        return QCoreApplication.translate('Plugin', theString)

    #noinspection PyCallByClass
    def initGui(self):
        """Gui initialisation procedure (for QGIS plugin api).

        This method is called by QGIS and should be used to set up
        any graphical user interface elements that should appear in QGIS by
        default (i.e. before the user performs any explicit action with the
        plugin).

        Args:
           None.
        Returns:
           None.
        Raises:
           no exceptions explicitly raised.
        """
        # Import dock here as it needs to be imported AFTER i18n is set up
        from safe_qgis.dock import Dock
        self.dockWidget = None
        #--------------------------------------
        # Create action for plugin dockable window (show/hide)
        #--------------------------------------
        # pylint: disable=W0201
        self.actionDock = QAction(QIcon(':/plugins/inasafe/icon.svg'),
                                  self.tr('Toggle InaSAFE Dock'),
                                  self.iface.mainWindow())
        self.actionDock.setObjectName('InaSAFEDockToggle')
        self.actionDock.setStatusTip(self.tr('Show/hide InaSAFE dock widget'))
        self.actionDock.setWhatsThis(self.tr('Show/hide InaSAFE dock widget'))
        self.actionDock.setCheckable(True)
        self.actionDock.setChecked(True)
        QObject.connect(self.actionDock, SIGNAL('triggered()'),
                        self.showHideDockWidget)
        # add to plugin toolbar
        self.iface.addToolBarIcon(self.actionDock)
        # add to plugin menu
        self.iface.addPluginToMenu(self.tr('InaSAFE'), self.actionDock)

        #--------------------------------------
        # Create action for keywords editor
        #--------------------------------------
        self.actionKeywordsDialog = QAction(
            QIcon(':/plugins/inasafe/show-keyword-editor.svg'),
            self.tr('InaSAFE Keyword Editor'), self.iface.mainWindow())
        self.actionKeywordsDialog.setStatusTip(
            self.tr('Open InaSAFE keywords editor'))
        self.actionKeywordsDialog.setWhatsThis(
            self.tr('Open InaSAFE keywords editor'))
        self.actionKeywordsDialog.setEnabled(False)

        QObject.connect(self.actionKeywordsDialog, SIGNAL('triggered()'),
                        self.showKeywordsEditor)

        self.iface.addToolBarIcon(self.actionKeywordsDialog)
        self.iface.addPluginToMenu(self.tr('InaSAFE'),
                                   self.actionKeywordsDialog)

        #--------------------------------------
        # Create action for reset icon
        #--------------------------------------
        self.actionResetDock = QAction(
            QIcon(':/plugins/inasafe/reset-dock.svg'), self.tr('Reset Dock'),
            self.iface.mainWindow())
        self.actionResetDock.setStatusTip(self.tr('Reset the InaSAFE Dock'))
        self.actionResetDock.setWhatsThis(self.tr('Reset the InaSAFE Dock'))
        QObject.connect(self.actionResetDock, SIGNAL('triggered()'),
                        self.resetDock)

        self.iface.addToolBarIcon(self.actionResetDock)
        self.iface.addPluginToMenu(self.tr('InaSAFE'), self.actionResetDock)

        #--------------------------------------
        # Create action for options dialog
        #--------------------------------------
        self.actionOptions = QAction(
            QIcon(':/plugins/inasafe/configure-inasafe.svg'),
            self.tr('InaSAFE Options'), self.iface.mainWindow())
        self.actionOptions.setStatusTip(self.tr('Open InaSAFE options dialog'))
        self.actionOptions.setWhatsThis(self.tr('Open InaSAFE options dialog'))
        QObject.connect(self.actionOptions, SIGNAL('triggered()'),
                        self.showOptions)

        self.iface.addToolBarIcon(self.actionOptions)
        self.iface.addPluginToMenu(self.tr('InaSAFE'), self.actionOptions)

        #--------------------------------------
        # Create action for impact functions doc dialog
        #--------------------------------------
        self.actionImpactFunctionsDoc = QAction(
            QIcon(':/plugins/inasafe/show-impact-functions.svg'),
            self.tr('InaSAFE Impact Functions Browser'),
            self.iface.mainWindow())
        self.actionImpactFunctionsDoc.setStatusTip(
            self.tr('Open InaSAFE Impact Functions Browser'))
        self.actionImpactFunctionsDoc.setWhatsThis(
            self.tr('Open InaSAFE Impact Functions Browser'))
        QObject.connect(self.actionImpactFunctionsDoc, SIGNAL('triggered()'),
                        self.showImpactFunctionsDoc)

        self.iface.addToolBarIcon(self.actionImpactFunctionsDoc)
        self.iface.addPluginToMenu(self.tr('InaSAFE'),
                                   self.actionImpactFunctionsDoc)

        # Short cut for Open Impact Functions Doc
        self.keyAction = QAction("Test Plugin", self.iface.mainWindow())
        self.iface.registerMainWindowAction(self.keyAction, "F7")
        QObject.connect(self.keyAction, SIGNAL("triggered()"),
                        self.keyActionF7)

        #---------------------------------------
        # Create action for minimum needs dialog
        #---------------------------------------
        self.actionMinimumNeeds = QAction(
            QIcon(':/plugins/inasafe/show-minimum-needs.svg'),
            self.tr('InaSAFE Minimum Needs Tool'), self.iface.mainWindow())
        self.actionMinimumNeeds.setStatusTip(
            self.tr('Open InaSAFE minimum needs tool'))
        self.actionMinimumNeeds.setWhatsThis(
            self.tr('Open InaSAFE minimum needs tool'))
        QObject.connect(self.actionMinimumNeeds, SIGNAL('triggered()'),
                        self.showMinimumNeeds)

        self.iface.addToolBarIcon(self.actionMinimumNeeds)
        self.iface.addPluginToMenu(self.tr('InaSAFE'), self.actionMinimumNeeds)

        #---------------------------------------
        # Create action for converter dialog
        #---------------------------------------
        self.actionConverter = QAction(
            QIcon(':/plugins/inasafe/show-minimum-needs.svg'),
            self.tr('InaSAFE Converter'), self.iface.mainWindow())
        self.actionConverter.setStatusTip(self.tr('Open InaSAFE Converter'))
        self.actionConverter.setWhatsThis(self.tr('Open InaSAFE Converter'))
        QObject.connect(self.actionConverter, SIGNAL('triggered()'),
                        self.showConverter)

        self.iface.addToolBarIcon(self.actionConverter)
        self.iface.addPluginToMenu(self.tr('InaSAFE'), self.actionConverter)

        #--------------------------------------
        # Create action for import OSM Dialog
        #--------------------------------------
        self.actionImportDlg = QAction(
            QIcon(':/plugins/inasafe/osm-download.png'),
            self.tr('InaSAFE OpenStreetMap Downloader'),
            self.iface.mainWindow())
        self.actionImportDlg.setStatusTip(
            self.tr('InaSAFE OpenStreetMap Downloader'))
        self.actionImportDlg.setWhatsThis(
            self.tr('InaSAFE OpenStreetMap Downloader'))
        QObject.connect(self.actionImportDlg, SIGNAL('triggered()'),
                        self.showImportDlg)

        self.iface.addToolBarIcon(self.actionImportDlg)
        self.iface.addPluginToMenu(self.tr('InaSAFE'), self.actionImportDlg)

        #--------------------------------------
        # create dockwidget and tabify it with the legend
        #--------------------------------------
        self.dockWidget = Dock(self.iface)
        self.iface.addDockWidget(Qt.RightDockWidgetArea, self.dockWidget)
        myLegendTab = self.iface.mainWindow().findChild(QApplication, 'Legend')

        if myLegendTab:
            self.iface.mainWindow().tabifyDockWidget(myLegendTab,
                                                     self.dockWidget)
            self.dockWidget.raise_()
        #
        # Hook up a slot for when the current layer is changed
        #
        QObject.connect(self.iface,
                        SIGNAL("currentLayerChanged(QgsMapLayer*)"),
                        self.layerChanged)

        #
        # Hook up a slot for when the dock is hidden using its close button
        # or  view-panels
        #
        QObject.connect(self.dockWidget, SIGNAL("visibilityChanged (bool)"),
                        self.toggleActionDock)

        # pylint: disable=W0201

    def unload(self):
        """Gui breakdown procedure (for QGIS plugin api).

        This method is called by QGIS and should be used to *remove*
        any graphical user interface elements that should appear in QGIS.

        Args:
           None.
        Returns:
           None.
        Raises:
           no exceptions explicitly raised.
        """
        # Remove the plugin menu item and icon
        self.iface.removePluginMenu(self.tr('InaSAFE'), self.actionDock)
        self.iface.removeToolBarIcon(self.actionDock)
        self.iface.removePluginMenu(self.tr('InaSAFE'),
                                    self.actionKeywordsDialog)
        self.iface.removeToolBarIcon(self.actionKeywordsDialog)
        self.iface.removePluginMenu(self.tr('InaSAFE'), self.actionResetDock)
        self.iface.removeToolBarIcon(self.actionResetDock)
        self.iface.removePluginMenu(self.tr('InaSAFE'), self.actionOptions)
        self.iface.removeToolBarIcon(self.actionOptions)
        self.iface.removePluginMenu(self.tr('InaSAFE'),
                                    self.actionMinimumNeeds)
        self.iface.removeToolBarIcon(self.actionMinimumNeeds)
        self.iface.removePluginMenu(self.tr('InaSAFE'),
                                    self.actionImpactFunctionsDoc)
        self.iface.removeToolBarIcon(self.actionImpactFunctionsDoc)
        self.iface.mainWindow().removeDockWidget(self.dockWidget)
        self.dockWidget.setVisible(False)
        self.dockWidget.destroy()
        QObject.disconnect(self.iface,
                           SIGNAL("currentLayerChanged(QgsMapLayer*)"),
                           self.layerChanged)

    def toggleActionDock(self, checked):
        """check or uncheck the toggle inaSAFE toolbar button.

        This slot is called when the user hides the inaSAFE panel using its
        close button or using view->panels

        .. see also:: :func:`Plugin.initGui`.

        Args:
           checked - if actionDock has to be checked or not
        Returns:
           None.
        Raises:
           no exceptions explicitly raised.
        """

        self.actionDock.setChecked(checked)

    # Run method that performs all the real work
    def showHideDockWidget(self):
        """Show or hide the dock widget.

        This slot is called when the user clicks the toolbar icon or
        menu item associated with this plugin. It will hide or show
        the dock depending on its current state.

        .. see also:: :func:`Plugin.initGui`.

        Args:
           None.
        Returns:
           None.
        Raises:
           no exceptions explicitly raised.
        """
        if self.dockWidget.isVisible():
            self.dockWidget.setVisible(False)
        else:
            self.dockWidget.setVisible(True)
            self.dockWidget.raise_()

    def showMinimumNeeds(self):
        """Show the minimum needs dialog.

        This slot is called when the user clicks the minimum needs toolbar
        icon or menu item associated with this plugin.

        .. see also:: :func:`Plugin.initGui`.

        Args:
           None.
        Returns:
           None.
        Raises:
           no exceptions explicitly raised.
        """
        # import here only so that it is AFTER i18n set up
        from safe_qgis.minimum_needs import MinimumNeeds

        myDialog = MinimumNeeds(self.iface.mainWindow())
        myDialog.show()

    def showOptions(self):
        """Show the options dialog.

        This slot is called when the user clicks the options toolbar
        icon or menu item associated with this plugin

        .. see also:: :func:`Plugin.initGui`.

        Args:
           None.
        Returns:
           None.
        Raises:
           no exceptions explicitly raised.
        """
        # import here only so that it is AFTER i18n set up
        from safe_qgis.options_dialog import OptionsDialog

        myDialog = OptionsDialog(self.iface.mainWindow(), self.iface,
                                 self.dockWidget)
        myDialog.show()

    def showKeywordsEditor(self):
        """Show the keywords editor.

        This slot is called when the user clicks the keyword editor toolbar
        icon or menu item associated with this plugin

        .. see also:: :func:`Plugin.initGui`.

        Args:
           None.

        Returns:
           None.

        Raises:
           no exceptions explicitly raised.
        """
        # import here only so that it is AFTER i18n set up
        from safe_qgis.keywords_dialog import KeywordsDialog

        if self.iface.activeLayer() is None:
            return
        myDialog = KeywordsDialog(self.iface.mainWindow(), self.iface,
                                  self.dockWidget)
        myDialog.setModal(True)
        myDialog.show()

    def showImpactFunctionsDoc(self):
        """Show the impact function doc

        This slot is called when the user clicks the impact functions
        toolbar icon or menu item associated with this plugin

        .. see also:: :func:`Plugin.initGui`.

        Args:
           None.
        Returns:
           None.
        Raises:
           no exceptions explicitly raised.
        """
        # import here only so that it is AFTER i18n set up
        from safe_qgis.impact_functions_doc import ImpactFunctionsDoc

        myDialog = ImpactFunctionsDoc(self.iface.mainWindow())
        myDialog.show()

    def showConverter(self):
        """Show the converter dialog.

        This slot is called when the user clicks the impact functions
        toolbar icon or menu item associated with this plugin

        .. see also:: :func:`Plugin.initGui`.

        Args:
           None.
        Returns:
           None.
        Raises:
           no exceptions explicitly raised.
        """
        # import here only so that it is AFTER i18n set up
        from safe_qgis.converter_dialog import ConverterDialog

        myDialog = ConverterDialog(self.iface.mainWindow())
        myDialog.show()

    def showImportDlg(self):
        from safe_qgis.import_dialog import ImportDialog

        dlg = ImportDialog(self.iface.mainWindow(), self.iface)
        dlg.setModal(True)
        dlg.show()

    def resetDock(self):
        """Reset the dock to its default state.

        This slot is called when the user clicks the reset icon in the toolbar
        or the reset menu item associated with this plugin

        .. see also:: :func:`Plugin.initGui`.

        Args:
           None.
        Returns:
           None.
        Raises:
           no exceptions explicitly raised.
        """
        self.dockWidget.getLayers()

    def layerChanged(self, theLayer):
        """Enable or disable the keywords editor icon.

        This slot is called when the user clicks the keyword editor toolbar
        icon or menu item associated with this plugin

        .. see also:: :func:`Plugin.initGui`.

        Args:
           None.
        Returns:
           None.
        Raises:
           no exceptions explicitly raised.
        """
        if theLayer is None:
            self.actionKeywordsDialog.setEnabled(False)
        else:
            self.actionKeywordsDialog.setEnabled(True)
        self.dockWidget.layerChanged(theLayer)

    def keyActionF7(self):
        '''Executed when user press F7'''
        self.showConverter()
Example #37
0
class LogView(QDialog, FORM_CLASS):
    """
    Class documentation goes here.
    """
    rollbackLayer = pyqtSignal(QTreeWidgetItem)
    diffLayer = pyqtSignal()
    checkoutLayer = pyqtSignal(str)
    checkoutTag = pyqtSignal(str, str)
    createBranch = pyqtSignal(str)

    def __init__(self, parent):
        """
        Constructor
        """
        QDialog.__init__(self, None)
        self.setupUi(self)

        self.iface = parent.iface
        self.tools = PgVersionTools(parent)

        self.tagAction = QAction(QIcon(""),
                                 self.tr("Set Tag for current revision"), self)
        self.tagAction.setStatusTip(self.tr("Set Tag for current revision"))
        self.tagAction.triggered.connect(self.setTag)
        self.treeWidget.addAction(self.tagAction)

        self.branchAction = QAction(QIcon(""),
                                    self.tr("Branch the current revision"),
                                    self)
        self.branchAction.setStatusTip(
            self.tr("Create branch for current revision"))
        self.branchAction.triggered.connect(self.create_branch)
        self.treeWidget.addAction(self.branchAction)

        self.treeWidget.setContextMenuPolicy(Qt.ActionsContextMenu)

    def set_version_table_id(self, id):
        self.version_table_id = id

    def setLayer(self, theLayer):
        self.theLayer = theLayer
        self.setWindowTitle(
            self.tr('Logview for layer %s' % (self.theLayer.name())))

    def createTagList(self):

        self.cmbTags.clear()

        # Add tags into tag cmb
        myDb = self.tools.layerDB('tags', self.theLayer)
        sql = "select vtag.tags_id, vtag.version_table_id, vtag.tag_text, vtag.revision \
          from versions.version_tags as vtag,\
               versions.version_tables as vtab \
          where vtab.version_view_schema = '%s' \
            and vtab.version_view_name = '%s' \
            and vtab.version_table_id = vtag.version_table_id \
          order by vtag.tags_id desc " % (self.tools.layerSchema(
            self.theLayer), self.tools.layerTable(self.theLayer))
        result = myDb.read(sql)

        self.version_table_id = result['VERSION_TABLE_ID'][0]
        self.cmbTags.addItem(' ------ ', -1)
        for i in range(len(result['TAG_TEXT'])):
            self.cmbTags.addItem(result['TAG_TEXT'][i], result['REVISION'][i])

    def setTag(self):
        result, ok = QInputDialog.getText(self,
                                          self.tr("Set Tag for Revision "),
                                          self.tr(""), QLineEdit.Normal)

        if ok:

            if self.hasTag():
                QMessageBox.information(
                    None, self.tr('Warning'),
                    self.tr('This version is already tagged'))
            else:
                myDb = self.tools.layerDB('tags', self.theLayer)
                sql = "insert into versions.version_tags (version_table_id, revision,  tag_text) \
                  values \
                  (%s, %s, '%s')" % (self.version_table_id,
                                     self.treeWidget.currentItem().text(0),
                                     result)
                myDb.run(sql)

                self.createTagList()

    def create_branch(self):
        result, ok = QInputDialog.getText(
            self, self.tr("Create branch for Revision "), self.tr(""),
            QLineEdit.Normal)

        if ok:
            if self.branchExists():
                QMessageBox.information(None, self.tr('Warning'),
                                        self.tr('Branch already exists'))
            else:
                myDb = self.tools.layerDB('tags', self.theLayer)
                sql = "select versions.pgvsmakebranch(%s, '%s')" % (
                    self.version_table_id, result)
                myDb.run(sql)

    def branchExists(self):
        return False

    def hasTag(self):

        try:
            sql = "select count(revision) \
              from versions.version_tags \
              where version_table_id = %s \
                and revision = %s " % (self.version_table_id,
                                       self.treeWidget.currentItem().text(0))

            myDb = self.tools.layerDB('tags', self.theLayer)
            result = myDb.read(sql)
            if result['COUNT'][0] <> '0':
                return True
            else:
                return False
        except:
            pass

    @pyqtSlot()
    def on_btnRollback_clicked(self):
        try:
            self.rollbackLayer.emit(self.treeWidget.currentItem())
            self.close()
        except:
            QMessageBox.information(
                None, self.tr('Warning'),
                self.tr('Please select a revision for checkout'))

    @pyqtSlot()
    def on_btnDiff_clicked(self):
        self.diffLayer.emit()
        self.close()

    @pyqtSlot()
    def on_btnCheckout_clicked(self):
        self.checkoutLayer.emit(self.treeWidget.currentItem().text(0))
        self.close()

    @pyqtSlot()
    def on_buttonBox_rejected(self):
        """
        Slot documentation goes here.
        """
        self.close()

    @pyqtSlot()
    def on_btnTag_clicked(self):
        if self.cmbTags.currentIndex() > 0:
            self.checkoutTag.emit(
                self.cmbTags.itemData(self.cmbTags.currentIndex()),
                self.cmbTags.itemText(self.cmbTags.currentIndex()))
Example #38
0
class GdalTools:
    def __init__(self, iface):
        if not valid:
            return

        # Save reference to the QGIS interface
        self.iface = iface
        try:
            self.QgisVersion = unicode(QGis.QGIS_VERSION_INT)
        except:
            self.QgisVersion = unicode(QGis.qgisVersion)[0]

        if QGis.QGIS_VERSION[0:3] < "1.5":
            # For i18n support
            userPluginPath = qgis.utils.home_plugin_path + "/GdalTools"
            systemPluginPath = qgis.utils.sys_plugin_path + "/GdalTools"

            overrideLocale = QSettings().value("locale/overrideFlag",
                                               False,
                                               type=bool)
            if not overrideLocale:
                localeFullName = QLocale.system().name()
            else:
                localeFullName = QSettings().value("locale/userLocale",
                                                   "",
                                                   type=str)

            if QFileInfo(userPluginPath).exists():
                translationPath = userPluginPath + "/i18n/GdalTools_" + localeFullName + ".qm"
            else:
                translationPath = systemPluginPath + "/i18n/GdalTools_" + localeFullName + ".qm"

            self.localePath = translationPath
            if QFileInfo(self.localePath).exists():
                self.translator = QTranslator()
                self.translator.load(self.localePath)
                QCoreApplication.installTranslator(self.translator)

        # The list of actions added to menus, so we can remove them when unloading the plugin
        self._menuActions = []

    def initGui(self):
        if not valid:
            return
        if int(self.QgisVersion) < 1:
            QMessageBox.warning(
                self.iface.getMainWindow(), "Gdal Tools",
                QCoreApplication.translate("GdalTools",
                                           "QGIS version detected: ") +
                unicode(self.QgisVersion) + ".xx\n" +
                QCoreApplication.translate(
                    "GdalTools",
                    "This version of Gdal Tools requires at least QGIS version 1.0.0\nPlugin will not be enabled."
                ))
            return None

        from tools.GdalTools_utils import GdalConfig, LayerRegistry
        self.GdalVersionNum = GdalConfig.versionNum()
        LayerRegistry.setIface(self.iface)

        # find the Raster menu
        rasterMenu = None
        menu_bar = self.iface.mainWindow().menuBar()
        actions = menu_bar.actions()

        rasterText = QCoreApplication.translate("QgisApp", "&Raster")

        for a in actions:
            if a.menu() is not None and a.menu().title() == rasterText:
                rasterMenu = a.menu()
                break

        if rasterMenu is None:
            # no Raster menu, create and insert it before the Help menu
            self.menu = QMenu(rasterText, self.iface.mainWindow())
            lastAction = actions[len(actions) - 1]
            menu_bar.insertMenu(lastAction, self.menu)
        else:
            self.menu = rasterMenu
            self._menuActions.append(self.menu.addSeparator())

        # projections menu (Warp (Reproject), Assign projection)
        self.projectionsMenu = QMenu(
            QCoreApplication.translate("GdalTools", "Projections"),
            self.iface.mainWindow())
        self.projectionsMenu.setObjectName("projectionsMenu")

        self.warp = QAction(
            QIcon(":/icons/warp.png"),
            QCoreApplication.translate("GdalTools", "Warp (Reproject)..."),
            self.iface.mainWindow())
        self.warp.setObjectName("warp")
        self.warp.setStatusTip(
            QCoreApplication.translate(
                "GdalTools", "Warp an image into a new coordinate system"))
        QObject.connect(self.warp, SIGNAL("triggered()"), self.doWarp)

        self.projection = QAction(
            QIcon(":icons/projection-add.png"),
            QCoreApplication.translate("GdalTools", "Assign Projection..."),
            self.iface.mainWindow())
        self.projection.setObjectName("projection")
        self.projection.setStatusTip(
            QCoreApplication.translate("GdalTools",
                                       "Add projection info to the raster"))
        QObject.connect(self.projection, SIGNAL("triggered()"),
                        self.doProjection)

        self.extractProj = QAction(
            QIcon(":icons/projection-export.png"),
            QCoreApplication.translate("GdalTools", "Extract Projection..."),
            self.iface.mainWindow())
        self.extractProj.setObjectName("extractProj")
        self.extractProj.setStatusTip(
            QCoreApplication.translate(
                "GdalTools", "Extract projection information from raster(s)"))
        QObject.connect(self.extractProj, SIGNAL("triggered()"),
                        self.doExtractProj)

        self.projectionsMenu.addActions(
            [self.warp, self.projection, self.extractProj])

        # conversion menu (Rasterize (Vector to raster), Polygonize (Raster to vector), Translate, RGB to PCT, PCT to RGB)
        self.conversionMenu = QMenu(
            QCoreApplication.translate("GdalTools", "Conversion"),
            self.iface.mainWindow())
        self.conversionMenu.setObjectName("conversionMenu")

        if self.GdalVersionNum >= 1300:
            self.rasterize = QAction(
                QIcon(":/icons/rasterize.png"),
                QCoreApplication.translate("GdalTools",
                                           "Rasterize (Vector to Raster)..."),
                self.iface.mainWindow())
            self.rasterize.setObjectName("rasterize")
            self.rasterize.setStatusTip(
                QCoreApplication.translate(
                    "GdalTools", "Burns vector geometries into a raster"))
            QObject.connect(self.rasterize, SIGNAL("triggered()"),
                            self.doRasterize)
            self.conversionMenu.addAction(self.rasterize)

        if self.GdalVersionNum >= 1600:
            self.polygonize = QAction(
                QIcon(":/icons/polygonize.png"),
                QCoreApplication.translate("GdalTools",
                                           "Polygonize (Raster to Vector)..."),
                self.iface.mainWindow())
            self.polygonize.setObjectName("polygonize")
            self.polygonize.setStatusTip(
                QCoreApplication.translate(
                    "GdalTools",
                    "Produces a polygon feature layer from a raster"))
            QObject.connect(self.polygonize, SIGNAL("triggered()"),
                            self.doPolygonize)
            self.conversionMenu.addAction(self.polygonize)

        self.translate = QAction(
            QIcon(":/icons/translate.png"),
            QCoreApplication.translate("GdalTools",
                                       "Translate (Convert Format)..."),
            self.iface.mainWindow())
        self.translate.setObjectName("translate")
        self.translate.setStatusTip(
            QCoreApplication.translate(
                "GdalTools", "Converts raster data between different formats"))
        QObject.connect(self.translate, SIGNAL("triggered()"),
                        self.doTranslate)

        self.paletted = QAction(
            QIcon(":icons/24-to-8-bits.png"),
            QCoreApplication.translate("GdalTools", "RGB to PCT..."),
            self.iface.mainWindow())
        self.paletted.setObjectName("paletted")
        self.paletted.setStatusTip(
            QCoreApplication.translate(
                "GdalTools", "Convert a 24bit RGB image to 8bit paletted"))
        QObject.connect(self.paletted, SIGNAL("triggered()"), self.doPaletted)

        self.rgb = QAction(
            QIcon(":icons/8-to-24-bits.png"),
            QCoreApplication.translate("GdalTools", "PCT to RGB..."),
            self.iface.mainWindow())
        self.rgb.setObjectName("rgb")
        self.rgb.setStatusTip(
            QCoreApplication.translate(
                "GdalTools", "Convert an 8bit paletted image to 24bit RGB"))
        QObject.connect(self.rgb, SIGNAL("triggered()"), self.doRGB)

        self.conversionMenu.addActions(
            [self.translate, self.paletted, self.rgb])

        # extraction menu (Clipper, Contour)
        self.extractionMenu = QMenu(
            QCoreApplication.translate("GdalTools", "Extraction"),
            self.iface.mainWindow())
        self.extractionMenu.setObjectName("extractionMenu")

        if self.GdalVersionNum >= 1600:
            self.contour = QAction(
                QIcon(":/icons/contour.png"),
                QCoreApplication.translate("GdalTools", "Contour..."),
                self.iface.mainWindow())
            self.contour.setObjectName("contour")
            self.contour.setStatusTip(
                QCoreApplication.translate(
                    "GdalTools", "Builds vector contour lines from a DEM"))
            QObject.connect(self.contour, SIGNAL("triggered()"),
                            self.doContour)
            self.extractionMenu.addAction(self.contour)

        self.clipper = QAction(
            QIcon(":icons/raster-clip.png"),
            QCoreApplication.translate("GdalTools", "Clipper..."),
            self.iface.mainWindow())
        self.clipper.setObjectName("clipper")
        #self.clipper.setStatusTip( QCoreApplication.translate( "GdalTools", "Converts raster data between different formats") )
        QObject.connect(self.clipper, SIGNAL("triggered()"), self.doClipper)

        self.extractionMenu.addActions([self.clipper])

        # analysis menu (DEM (Terrain model), Grid (Interpolation), Near black, Proximity (Raster distance), Sieve)
        self.analysisMenu = QMenu(
            QCoreApplication.translate("GdalTools", "Analysis"),
            self.iface.mainWindow())
        self.analysisMenu.setObjectName("analysisMenu")

        if self.GdalVersionNum >= 1600:
            self.sieve = QAction(
                QIcon(":/icons/sieve.png"),
                QCoreApplication.translate("GdalTools", "Sieve..."),
                self.iface.mainWindow())
            self.sieve.setObjectName("sieve")
            self.sieve.setStatusTip(
                QCoreApplication.translate("GdalTools",
                                           "Removes small raster polygons"))
            QObject.connect(self.sieve, SIGNAL("triggered()"), self.doSieve)
            self.analysisMenu.addAction(self.sieve)

        if self.GdalVersionNum >= 1500:
            self.nearBlack = QAction(
                QIcon(":/icons/nearblack.png"),
                QCoreApplication.translate("GdalTools", "Near Black..."),
                self.iface.mainWindow())
            self.nearBlack.setObjectName("nearBlack")
            self.nearBlack.setStatusTip(
                QCoreApplication.translate(
                    "GdalTools",
                    "Convert nearly black/white borders to exact value"))
            QObject.connect(self.nearBlack, SIGNAL("triggered()"),
                            self.doNearBlack)
            self.analysisMenu.addAction(self.nearBlack)

        if self.GdalVersionNum >= 1700:
            self.fillNodata = QAction(
                QIcon(":/icons/fillnodata.png"),
                QCoreApplication.translate("GdalTools", "Fill nodata..."),
                self.iface.mainWindow())
            self.fillNodata.setObjectName("fillNodata")
            self.fillNodata.setStatusTip(
                QCoreApplication.translate(
                    "GdalTools",
                    "Fill raster regions by interpolation from edges"))
            QObject.connect(self.fillNodata, SIGNAL("triggered()"),
                            self.doFillNodata)
            self.analysisMenu.addAction(self.fillNodata)

        if self.GdalVersionNum >= 1600:
            self.proximity = QAction(
                QIcon(":/icons/proximity.png"),
                QCoreApplication.translate("GdalTools",
                                           "Proximity (Raster Distance)..."),
                self.iface.mainWindow())
            self.proximity.setObjectName("proximity")
            self.proximity.setStatusTip(
                QCoreApplication.translate("GdalTools",
                                           "Produces a raster proximity map"))
            QObject.connect(self.proximity, SIGNAL("triggered()"),
                            self.doProximity)
            self.analysisMenu.addAction(self.proximity)

        if self.GdalVersionNum >= 1500:
            self.grid = QAction(
                QIcon(":/icons/grid.png"),
                QCoreApplication.translate("GdalTools",
                                           "Grid (Interpolation)..."),
                self.iface.mainWindow())
            self.grid.setObjectName("grid")
            self.grid.setStatusTip(
                QCoreApplication.translate(
                    "GdalTools", "Create raster from the scattered data"))
            QObject.connect(self.grid, SIGNAL("triggered()"), self.doGrid)
            self.analysisMenu.addAction(self.grid)

        if self.GdalVersionNum >= 1700:
            self.dem = QAction(
                QIcon(":icons/dem.png"),
                QCoreApplication.translate("GdalTools",
                                           "DEM (Terrain Models)..."),
                self.iface.mainWindow())
            self.dem.setObjectName("dem")
            self.dem.setStatusTip(
                QCoreApplication.translate(
                    "GdalTools", "Tool to analyze and visualize DEMs"))
            QObject.connect(self.dem, SIGNAL("triggered()"), self.doDEM)
            self.analysisMenu.addAction(self.dem)

        #self.analysisMenu.addActions( [  ] )

        # miscellaneous menu (Build overviews (Pyramids), Tile index, Information, Merge, Build Virtual Raster (Catalog))
        self.miscellaneousMenu = QMenu(
            QCoreApplication.translate("GdalTools", "Miscellaneous"),
            self.iface.mainWindow())
        self.miscellaneousMenu.setObjectName("miscellaneousMenu")

        if self.GdalVersionNum >= 1600:
            self.buildVRT = QAction(
                QIcon(":/icons/vrt.png"),
                QCoreApplication.translate(
                    "GdalTools", "Build Virtual Raster (Catalog)..."),
                self.iface.mainWindow())
            self.buildVRT.setObjectName("buildVRT")
            self.buildVRT.setStatusTip(
                QCoreApplication.translate(
                    "GdalTools", "Builds a VRT from a list of datasets"))
            QObject.connect(self.buildVRT, SIGNAL("triggered()"),
                            self.doBuildVRT)
            self.miscellaneousMenu.addAction(self.buildVRT)

        self.merge = QAction(
            QIcon(":/icons/merge.png"),
            QCoreApplication.translate("GdalTools", "Merge..."),
            self.iface.mainWindow())
        self.merge.setObjectName("merge")
        self.merge.setStatusTip(
            QCoreApplication.translate(
                "GdalTools", "Build a quick mosaic from a set of images"))
        QObject.connect(self.merge, SIGNAL("triggered()"), self.doMerge)

        self.info = QAction(
            QIcon(":/icons/raster-info.png"),
            QCoreApplication.translate("GdalTools", "Information..."),
            self.iface.mainWindow())
        self.info.setObjectName("info")
        self.info.setStatusTip(
            QCoreApplication.translate(
                "GdalTools", "Lists information about raster dataset"))
        QObject.connect(self.info, SIGNAL("triggered()"), self.doInfo)

        self.overview = QAction(
            QIcon(":icons/raster-overview.png"),
            QCoreApplication.translate("GdalTools",
                                       "Build Overviews (Pyramids)..."),
            self.iface.mainWindow())
        self.overview.setObjectName("overview")
        self.overview.setStatusTip(
            QCoreApplication.translate("GdalTools",
                                       "Builds or rebuilds overview images"))
        QObject.connect(self.overview, SIGNAL("triggered()"), self.doOverview)

        self.tileindex = QAction(
            QIcon(":icons/tiles.png"),
            QCoreApplication.translate("GdalTools", "Tile Index..."),
            self.iface.mainWindow())
        self.tileindex.setObjectName("tileindex")
        self.tileindex.setStatusTip(
            QCoreApplication.translate(
                "GdalTools", "Build a shapefile as a raster tileindex"))
        QObject.connect(self.tileindex, SIGNAL("triggered()"),
                        self.doTileIndex)

        self.miscellaneousMenu.addActions(
            [self.merge, self.info, self.overview, self.tileindex])

        self._menuActions.append(self.menu.addMenu(self.projectionsMenu))
        self._menuActions.append(self.menu.addMenu(self.conversionMenu))
        self._menuActions.append(self.menu.addMenu(self.extractionMenu))

        if not self.analysisMenu.isEmpty():
            self._menuActions.append(self.menu.addMenu(self.analysisMenu))

        self._menuActions.append(self.menu.addMenu(self.miscellaneousMenu))

        self.settings = QAction(
            QCoreApplication.translate("GdalTools", "GdalTools Settings..."),
            self.iface.mainWindow())
        self.settings.setObjectName("settings")
        self.settings.setStatusTip(
            QCoreApplication.translate("GdalTools",
                                       "Various settings for Gdal Tools"))
        QObject.connect(self.settings, SIGNAL("triggered()"), self.doSettings)
        self.menu.addAction(self.settings)
        self._menuActions.append(self.settings)

    def unload(self):
        if not valid:
            return
        for a in self._menuActions:
            self.menu.removeAction(a)

    def doBuildVRT(self):
        from tools.doBuildVRT import GdalToolsDialog as BuildVRT
        d = BuildVRT(self.iface)
        self.runToolDialog(d)

    def doContour(self):
        from tools.doContour import GdalToolsDialog as Contour
        d = Contour(self.iface)
        self.runToolDialog(d)

    def doRasterize(self):
        from tools.doRasterize import GdalToolsDialog as Rasterize
        d = Rasterize(self.iface)
        self.runToolDialog(d)

    def doPolygonize(self):
        from tools.doPolygonize import GdalToolsDialog as Polygonize
        d = Polygonize(self.iface)
        self.runToolDialog(d)

    def doMerge(self):
        from tools.doMerge import GdalToolsDialog as Merge
        d = Merge(self.iface)
        self.runToolDialog(d)

    def doSieve(self):
        from tools.doSieve import GdalToolsDialog as Sieve
        d = Sieve(self.iface)
        self.runToolDialog(d)

    def doProximity(self):
        from tools.doProximity import GdalToolsDialog as Proximity
        d = Proximity(self.iface)
        self.runToolDialog(d)

    def doNearBlack(self):
        from tools.doNearBlack import GdalToolsDialog as NearBlack
        d = NearBlack(self.iface)
        self.runToolDialog(d)

    def doFillNodata(self):
        from tools.doFillNodata import GdalToolsDialog as FillNodata
        d = FillNodata(self.iface)
        self.runToolDialog(d)

    def doWarp(self):
        from tools.doWarp import GdalToolsDialog as Warp
        d = Warp(self.iface)
        self.runToolDialog(d)

    def doGrid(self):
        from tools.doGrid import GdalToolsDialog as Grid
        d = Grid(self.iface)
        self.runToolDialog(d)

    def doTranslate(self):
        from tools.doTranslate import GdalToolsDialog as Translate
        d = Translate(self.iface)
        self.runToolDialog(d)

    def doInfo(self):
        from tools.doInfo import GdalToolsDialog as Info
        d = Info(self.iface)
        self.runToolDialog(d)

    def doProjection(self):
        from tools.doProjection import GdalToolsDialog as Projection
        d = Projection(self.iface)
        self.runToolDialog(d)

    def doOverview(self):
        from tools.doOverview import GdalToolsDialog as Overview
        d = Overview(self.iface)
        self.runToolDialog(d)

    def doClipper(self):
        from tools.doClipper import GdalToolsDialog as Clipper
        d = Clipper(self.iface)
        self.runToolDialog(d)

    def doPaletted(self):
        from tools.doRgbPct import GdalToolsDialog as RgbPct
        d = RgbPct(self.iface)
        self.runToolDialog(d)

    def doRGB(self):
        from tools.doPctRgb import GdalToolsDialog as PctRgb
        d = PctRgb(self.iface)
        self.runToolDialog(d)

    def doTileIndex(self):
        from tools.doTileIndex import GdalToolsDialog as TileIndex
        d = TileIndex(self.iface)
        self.runToolDialog(d)

    def doExtractProj(self):
        from tools.doExtractProj import GdalToolsDialog as ExtractProj
        d = ExtractProj(self.iface)
        d.exec_()

    def doDEM(self):
        from tools.doDEM import GdalToolsDialog as DEM
        d = DEM(self.iface)
        self.runToolDialog(d)

    def runToolDialog(self, dlg):
        dlg.show_()
        dlg.exec_()
        del dlg

    def doSettings(self):
        from tools.doSettings import GdalToolsSettingsDialog as Settings
        d = Settings(self.iface)
        d.exec_()
Example #39
0
class SimpleRichText(QTextEdit):
    def __init__(self, focusin, focusout):
        QTextEdit.__init__(self)
        self.focusin = focusin
        self.focusout = focusout
        self.createActions()

        #self.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)

    def focusOutEvent(self, event):
        #print "focus out"
        self.focusout()

    def focusInEvent(self, event):
        self.focusin()

    def closeEvent(self, event):
        event.accept()

    def createActions(self):
        self.boldAct = QAction(self.tr("&Bold"), self)
        self.boldAct.setCheckable(True)
        self.boldAct.setShortcut(self.tr("Ctrl+B"))
        self.boldAct.setStatusTip(self.tr("Make the text bold"))
        self.connect(self.boldAct, SIGNAL("triggered()"), self.setBold)
        self.addAction(self.boldAct)

        boldFont = self.boldAct.font()
        boldFont.setBold(True)
        self.boldAct.setFont(boldFont)

        self.italicAct = QAction(self.tr("&Italic"), self)
        self.italicAct.setCheckable(True)
        self.italicAct.setShortcut(self.tr("Ctrl+I"))
        self.italicAct.setStatusTip(self.tr("Make the text italic"))
        self.connect(self.italicAct, SIGNAL("triggered()"), self.setItalic)
        self.addAction(self.italicAct)

    def setBold(self):
        format = QTextCharFormat()
        if self.boldAct.isChecked():
            weight = QFont.Bold
        else:
            weight = QFont.Normal
        format.setFontWeight(weight)
        self.setFormat(format)

    def setItalic(self):
        format = QTextCharFormat()
        #format.setFontItalic(self.__italic.isChecked())
        format.setFontItalic(self.italicAct.isChecked())
        self.setFormat(format)

    def setUnderline(self):
        format = QTextCharFormat()
        format.setFontUnderline(self.__underline.isChecked())
        self.setFormat(format)

    def setFormat(self, format):
        self.textCursor().mergeCharFormat(format)
        self.mergeCurrentCharFormat(format)

    def bold(self):
        print("bold")

    def italic(self):
        print("italic")
Example #40
0
class Plugin(object):
    """The QGIS interface implementation for the InaSAFE plugin.

    This class acts as the 'glue' between QGIS and our custom logic.
    It creates a toolbar and menu bar entry and launches the InaSAFE user
    interface if these are activated.
    """
    def __init__(self, iface):
        """Class constructor.

        On instantiation, the plugin instance will be assigned a copy
        of the QGIS iface object which will allow this plugin to access and
        manipulate the running QGIS instance that spawned it.

        :param iface:Quantum GIS iface instance. This instance is
            automatically passed to the plugin by QGIS when it loads the
            plugin.
        :type iface: QGisAppInterface
        """
        # Register all the impact functions
        register_impact_functions()
        # Save reference to the QGIS interface
        self.iface = iface
        self.dock_widget = None
        self.action_import_dialog = None
        self.action_save_scenario = None
        self.action_batch_runner = None
        self.action_shake_converter = None
        self.action_minimum_needs = None
        self.action_global_minimum_needs = None
        self.action_impact_merge_dlg = None
        self.key_action = None
        self.action_options = None
        self.action_keywords_dialog = None
        self.action_keywords_wizard = None
        self.action_function_centric_wizard = None
        self.action_extent_selector = None
        self.translator = None
        self.toolbar = None
        self.actions = []  # list of all QActions we create for InaSAFE
        self.action_dock = None
        self.action_toggle_rubberbands = None
        self.message_bar_item = None
        # Flag indicating if toolbar should show only common icons or not
        self.full_toolbar = False
        # print self.tr('InaSAFE')
        # For enable/disable the keyword editor icon
        self.iface.currentLayerChanged.connect(self.layer_changed)

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

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

    def add_action(self, action, add_to_toolbar=True):
        """Add a toolbar icon to the InaSAFE toolbar.

        :param action: The action that should be added to the toolbar.
        :type action: QAction

        :param add_to_toolbar: Flag indicating whether the action should also
            be added to the InaSAFE toolbar. Defaults to True.
        :type add_to_toolbar: bool

        """
        # store in the class list of actions for easy plugin unloading
        self.actions.append(action)
        self.iface.addPluginToMenu(self.tr('InaSAFE'), action)
        if add_to_toolbar:
            self.toolbar.addAction(action)

    def _create_dock_toggle_action(self):
        """Create action for plugin dockable window (show/hide)."""
        # pylint: disable=W0201
        icon = resources_path('img', 'icons', 'icon.svg')
        self.action_dock = QAction(QIcon(icon), self.tr('Toggle InaSAFE Dock'),
                                   self.iface.mainWindow())
        self.action_dock.setObjectName('InaSAFEDockToggle')
        self.action_dock.setStatusTip(self.tr('Show/hide InaSAFE dock widget'))
        self.action_dock.setWhatsThis(self.tr('Show/hide InaSAFE dock widget'))
        self.action_dock.setCheckable(True)
        self.action_dock.setChecked(True)
        self.action_dock.triggered.connect(self.toggle_dock_visibility)
        self.add_action(self.action_dock)

    def _create_keywords_action(self):
        """Create action for keywords editor."""
        icon = resources_path('img', 'icons', 'show-keyword-editor.svg')
        self.action_keywords_dialog = QAction(
            QIcon(icon), self.tr('InaSAFE Keyword Editor'),
            self.iface.mainWindow())
        self.action_keywords_dialog.setStatusTip(
            self.tr('Open InaSAFE keywords editor'))
        self.action_keywords_dialog.setWhatsThis(
            self.tr('Open InaSAFE keywords editor'))
        self.action_keywords_dialog.setEnabled(False)
        self.action_keywords_dialog.triggered.connect(
            self.show_keywords_editor)
        self.add_action(self.action_keywords_dialog,
                        add_to_toolbar=self.full_toolbar)

    def _create_keywords_wizard_action(self):
        """Create action for keywords creation wizard."""
        icon = resources_path('img', 'icons', 'show-keyword-wizard.svg')
        self.action_keywords_wizard = QAction(
            QIcon(icon), self.tr('InaSAFE Keywords Creation Wizard'),
            self.iface.mainWindow())
        self.action_keywords_wizard.setStatusTip(
            self.tr('Open InaSAFE keywords creation wizard'))
        self.action_keywords_wizard.setWhatsThis(
            self.tr('Open InaSAFE keywords creation wizard'))
        self.action_keywords_wizard.setEnabled(False)
        self.action_keywords_wizard.triggered.connect(
            self.show_keywords_wizard)
        self.add_action(self.action_keywords_wizard)

    def _create_analysis_wizard_action(self):
        """Create action for IF-centric wizard."""
        icon = resources_path('img', 'icons', 'show-wizard.svg')
        self.action_function_centric_wizard = QAction(
            QIcon(icon), self.tr('InaSAFE Impact Function Centric Wizard'),
            self.iface.mainWindow())
        self.action_function_centric_wizard.setStatusTip(
            self.tr('Open InaSAFE impact function centric wizard'))
        self.action_function_centric_wizard.setWhatsThis(
            self.tr('Open InaSAFE impact function centric wizard'))
        self.action_function_centric_wizard.setEnabled(True)
        self.action_function_centric_wizard.triggered.connect(
            self.show_function_centric_wizard)
        self.add_action(self.action_function_centric_wizard)

    def _create_options_dialog_action(self):
        """Create action for options dialog."""
        icon = resources_path('img', 'icons', 'configure-inasafe.svg')
        self.action_options = QAction(QIcon(icon), self.tr('InaSAFE Options'),
                                      self.iface.mainWindow())
        self.action_options.setStatusTip(
            self.tr('Open InaSAFE options dialog'))
        self.action_options.setWhatsThis(
            self.tr('Open InaSAFE options dialog'))
        self.action_options.triggered.connect(self.show_options)
        self.add_action(self.action_options, add_to_toolbar=self.full_toolbar)

    def _create_minimum_needs_action(self):
        """Create action for minimum needs dialog."""
        icon = resources_path('img', 'icons', 'show-minimum-needs.svg')
        self.action_minimum_needs = QAction(
            QIcon(icon), self.tr('InaSAFE Minimum Needs Tool'),
            self.iface.mainWindow())
        self.action_minimum_needs.setStatusTip(
            self.tr('Open InaSAFE minimum needs tool'))
        self.action_minimum_needs.setWhatsThis(
            self.tr('Open InaSAFE minimum needs tool'))
        self.action_minimum_needs.triggered.connect(self.show_minimum_needs)
        self.add_action(self.action_minimum_needs,
                        add_to_toolbar=self.full_toolbar)

    def _create_minimum_needs_options_action(self):
        """Create action for global minimum needs dialog."""
        icon = resources_path('img', 'icons', 'show-global-minimum-needs.svg')
        self.action_global_minimum_needs = QAction(
            QIcon(icon), self.tr('InaSAFE Global Minimum Needs Configuration'),
            self.iface.mainWindow())
        self.action_global_minimum_needs.setStatusTip(
            self.tr('Open InaSAFE global minimum needs configuration'))
        self.action_global_minimum_needs.setWhatsThis(
            self.tr('Open InaSAFE global minimum needs configuration'))
        self.action_global_minimum_needs.triggered.connect(
            self.show_global_minimum_needs_configuration)
        self.add_action(self.action_global_minimum_needs,
                        add_to_toolbar=self.full_toolbar)

    def _create_shakemap_converter_action(self):
        """Create action for converter dialog."""
        icon = resources_path('img', 'icons', 'show-converter-tool.svg')
        self.action_shake_converter = QAction(QIcon(icon),
                                              self.tr('InaSAFE Converter'),
                                              self.iface.mainWindow())
        self.action_shake_converter.setStatusTip(
            self.tr('Open InaSAFE Converter'))
        self.action_shake_converter.setWhatsThis(
            self.tr('Open InaSAFE Converter'))
        self.action_shake_converter.triggered.connect(
            self.show_shakemap_importer)
        self.add_action(self.action_shake_converter,
                        add_to_toolbar=self.full_toolbar)

    def _create_batch_runner_action(self):
        """Create action for batch runner dialog."""
        icon = resources_path('img', 'icons', 'show-batch-runner.svg')
        self.action_batch_runner = QAction(QIcon(icon),
                                           self.tr('InaSAFE Batch Runner'),
                                           self.iface.mainWindow())
        self.action_batch_runner.setStatusTip(
            self.tr('Open InaSAFE Batch Runner'))
        self.action_batch_runner.setWhatsThis(
            self.tr('Open InaSAFE Batch Runner'))
        self.action_batch_runner.triggered.connect(self.show_batch_runner)
        self.add_action(self.action_batch_runner,
                        add_to_toolbar=self.full_toolbar)

    def _create_save_scenario_action(self):
        """Create action for save scenario dialog."""
        icon = resources_path('img', 'icons', 'save-as-scenario.svg')
        self.action_save_scenario = QAction(QIcon(icon),
                                            self.tr('Save Current Scenario'),
                                            self.iface.mainWindow())
        message = self.tr('Save current scenario to text file')
        self.action_save_scenario.setStatusTip(message)
        self.action_save_scenario.setWhatsThis(message)
        # noinspection PyUnresolvedReferences
        self.action_save_scenario.triggered.connect(self.save_scenario)
        self.add_action(self.action_save_scenario,
                        add_to_toolbar=self.full_toolbar)

    def _create_osm_downloader_action(self):
        """Create action for import OSM Dialog."""
        icon = resources_path('img', 'icons', 'show-osm-download.svg')
        self.action_import_dialog = QAction(
            QIcon(icon), self.tr('InaSAFE OpenStreetMap Downloader'),
            self.iface.mainWindow())
        self.action_import_dialog.setStatusTip(
            self.tr('InaSAFE OpenStreetMap Downloader'))
        self.action_import_dialog.setWhatsThis(
            self.tr('InaSAFE OpenStreetMap Downloader'))
        self.action_import_dialog.triggered.connect(self.show_osm_downloader)
        self.add_action(self.action_import_dialog)

    def _create_impact_merge_action(self):
        """Create action for impact layer merge Dialog."""
        icon = resources_path('img', 'icons', 'show-impact-merge.svg')
        self.action_impact_merge_dlg = QAction(
            QIcon(icon), self.tr('InaSAFE Impact Layer Merge'),
            self.iface.mainWindow())
        self.action_impact_merge_dlg.setStatusTip(
            self.tr('InaSAFE Impact Layer Merge'))
        self.action_impact_merge_dlg.setWhatsThis(
            self.tr('InaSAFE Impact Layer Merge'))
        self.action_impact_merge_dlg.triggered.connect(self.show_impact_merge)
        self.add_action(self.action_impact_merge_dlg,
                        add_to_toolbar=self.full_toolbar)

    def _create_rubber_bands_action(self):
        """Create action for toggling rubber bands."""
        icon = resources_path('img', 'icons', 'toggle-rubber-bands.svg')
        self.action_toggle_rubberbands = QAction(
            QIcon(icon), self.tr('Toggle Scenario Outlines'),
            self.iface.mainWindow())
        message = self.tr('Toggle rubber bands showing scenarion extents.')
        self.action_toggle_rubberbands.setStatusTip(message)
        self.action_toggle_rubberbands.setWhatsThis(message)
        # Set initial state
        self.action_toggle_rubberbands.setCheckable(True)
        settings = QSettings()
        flag = bool(settings.value('inasafe/showRubberBands', False,
                                   type=bool))
        self.action_toggle_rubberbands.setChecked(flag)
        # noinspection PyUnresolvedReferences
        self.action_toggle_rubberbands.triggered.connect(
            self.dock_widget.toggle_rubber_bands)
        self.add_action(self.action_toggle_rubberbands)

    def _create_analysis_extent_action(self):
        """Create action for analysis extent dialog."""
        icon = resources_path('img', 'icons', 'set-extents-tool.svg')
        self.action_extent_selector = QAction(
            QIcon(icon), self.tr('Set InaSAFE Analysis Area'),
            self.iface.mainWindow())
        self.action_extent_selector.setStatusTip(
            self.tr('Set the analysis area for InaSAFE'))
        self.action_extent_selector.setWhatsThis(
            self.tr('Set the analysis area for InaSAFE'))
        self.action_extent_selector.triggered.connect(
            self.show_extent_selector)
        self.add_action(self.action_extent_selector)

    def _create_test_layers_action(self):
        """Create action for adding layers (developer mode, non final only)."""
        final_release = release_status() == 'final'
        settings = QSettings()
        self.developer_mode = settings.value('inasafe/developer_mode',
                                             False,
                                             type=bool)
        if not final_release and self.developer_mode:
            icon = resources_path('img', 'icons', 'add-test-layers.svg')
            self.action_add_layers = QAction(QIcon(icon),
                                             self.tr('Add Some Test Layers'),
                                             self.iface.mainWindow())
            self.action_add_layers.setStatusTip(
                self.tr('Add some test layers'))
            self.action_add_layers.setWhatsThis(
                self.tr('Add some test layers'))
            self.action_add_layers.triggered.connect(self.add_test_layers)

            self.add_action(self.action_add_layers)

    def _create_dock(self):
        """Create dockwidget and tabify it with the legend."""
        # Import dock here as it needs to be imported AFTER i18n is set up
        from safe.gui.widgets.dock import Dock
        self.dock_widget = Dock(self.iface)
        self.iface.addDockWidget(Qt.RightDockWidgetArea, self.dock_widget)
        legend_tab = self.iface.mainWindow().findChild(QApplication, 'Legend')
        if legend_tab:
            self.iface.mainWindow().tabifyDockWidget(legend_tab,
                                                     self.dock_widget)
            self.dock_widget.raise_()

    def initGui(self):
        """Gui initialisation procedure (for QGIS plugin api).

        .. note:: Don't change the name of this method from initGui!

        This method is called by QGIS and should be used to set up
        any graphical user interface elements that should appear in QGIS by
        default (i.e. before the user performs any explicit action with the
        plugin).
        """
        self.toolbar = self.iface.addToolBar('InaSAFE')
        self.toolbar.setObjectName('InaSAFEToolBar')

        self.dock_widget = None
        # Now create the actual dock
        self._create_dock()
        # And all the menu actions
        # Configuration Group
        self._create_options_dialog_action()
        self._create_minimum_needs_options_action()
        self._create_analysis_extent_action()
        self._create_dock_toggle_action()
        self._create_rubber_bands_action()
        # TODO: add menu separator - Wizards
        self._create_keywords_wizard_action()
        self._create_analysis_wizard_action()
        # TODO: add menu separator - Data
        self._create_osm_downloader_action()
        self._create_shakemap_converter_action()
        self._create_minimum_needs_action()
        self._create_test_layers_action()
        # TODO: add menu separator - Analysis
        self._create_batch_runner_action()
        self._create_impact_merge_action()
        self._create_save_scenario_action()
        # TODO: This action (and related code) will be deprecated
        # keywords dialog to be replaced by keywords wizard
        self._create_keywords_action()

        # Hook up a slot for when the dock is hidden using its close button
        # or  view-panels
        #
        self.dock_widget.visibilityChanged.connect(self.toggle_inasafe_action)
        # Also deal with the fact that on start of QGIS dock may already be
        # hidden.
        self.action_dock.setChecked(self.dock_widget.isVisible())

    def clear_modules(self):
        """Unload inasafe functions and try to return QGIS to before InaSAFE.

        .. todo:: I think this function can be removed. TS.
        """
        # next lets force remove any inasafe related modules
        modules = []
        for module in sys.modules:
            if 'inasafe' in module:
                # Check if it is really one of our modules i.e. exists in the
                # plugin directory
                tokens = module.split('.')
                path = ''
                for myToken in tokens:
                    path += os.path.sep + myToken
                parent = os.path.abspath(
                    os.path.join(__file__, os.path.pardir, os.path.pardir))
                full_path = os.path.join(parent, path + '.py')
                if os.path.exists(os.path.abspath(full_path)):
                    LOGGER.debug('Removing: %s' % module)
                    modules.append(module)
        for module in modules:
            del (sys.modules[module])
        for module in sys.modules:
            if 'inasafe' in module:
                print module

        # Lets also clean up all the path additions that were made
        package_path = os.path.abspath(
            os.path.join(os.path.dirname(__file__), os.path.pardir))
        LOGGER.debug('Path to remove: %s' % package_path)
        # We use a list comprehension to ensure duplicate entries are removed
        LOGGER.debug(sys.path)
        sys.path = [y for y in sys.path if package_path not in y]
        LOGGER.debug(sys.path)

    def unload(self):
        """GUI breakdown procedure (for QGIS plugin api).

        .. note:: Don't change the name of this method from unload!

        This method is called by QGIS and should be used to *remove*
        any graphical user interface elements that should appear in QGIS.
        """
        # Remove the plugin menu item and icon
        for myAction in self.actions:
            self.iface.removePluginMenu(self.tr('InaSAFE'), myAction)
            self.iface.removeToolBarIcon(myAction)
        self.iface.mainWindow().removeDockWidget(self.dock_widget)
        self.iface.mainWindow().removeToolBar(self.toolbar)
        self.dock_widget.setVisible(False)
        self.dock_widget.destroy()
        self.iface.currentLayerChanged.disconnect(self.layer_changed)

    def toggle_inasafe_action(self, checked):
        """Check or un-check the toggle inaSAFE toolbar button.

        This slot is called when the user hides the inaSAFE panel using its
        close button or using view->panels.

        :param checked: True if the dock should be shown, otherwise False.
        :type checked: bool
        """

        self.action_dock.setChecked(checked)

    # Run method that performs all the real work
    def toggle_dock_visibility(self):
        """Show or hide the dock widget."""
        if self.dock_widget.isVisible():
            self.dock_widget.setVisible(False)
        else:
            self.dock_widget.setVisible(True)
            self.dock_widget.raise_()

    def add_test_layers(self):
        """Add standard test layers."""
        from safe.test.utilities import load_standard_layers
        load_standard_layers()

    def show_extent_selector(self):
        """Show the extent selector widget for defining analysis extents."""
        # import here only so that it is AFTER i18n set up
        from safe.gui.tools.extent_selector_dialog import ExtentSelectorDialog

        widget = ExtentSelectorDialog(
            self.iface,
            self.iface.mainWindow(),
            extent=self.dock_widget.extent.user_extent,
            crs=self.dock_widget.extent.user_extent_crs)
        widget.clear_extent.connect(
            self.dock_widget.extent.clear_user_analysis_extent)
        widget.extent_defined.connect(
            self.dock_widget.define_user_analysis_extent)
        # Needs to be non modal to support hide -> interact with map -> show
        widget.show()  # non modal

    def show_minimum_needs(self):
        """Show the minimum needs dialog."""
        # import here only so that it is AFTER i18n set up
        from safe.gui.tools.minimum_needs.needs_calculator_dialog import (
            NeedsCalculatorDialog)

        dialog = NeedsCalculatorDialog(self.iface.mainWindow())
        dialog.show()  # non modal

    def show_global_minimum_needs_configuration(self):
        """Show the minimum needs dialog."""
        # import here only so that it is AFTER i18n set up
        from safe.gui.tools.minimum_needs.needs_manager_dialog import (
            NeedsManagerDialog)

        dialog = NeedsManagerDialog(parent=self.iface.mainWindow(),
                                    dock=self.dock_widget)
        dialog.exec_()  # modal

    def show_impact_merge(self):
        """Show the impact layer merge dialog."""
        # import here only so that it is AFTER i18n set up
        from safe.gui.tools.impact_merge_dialog import ImpactMergeDialog

        dialog = ImpactMergeDialog(self.iface.mainWindow())
        dialog.exec_()  # modal

    def show_options(self):
        """Show the options dialog."""
        # import here only so that it is AFTER i18n set up
        from safe.gui.tools.options_dialog import OptionsDialog

        dialog = OptionsDialog(self.iface, self.dock_widget,
                               self.iface.mainWindow())
        dialog.exec_()  # modal

    def show_keywords_editor(self):
        """Show the keywords editor."""
        # import here only so that it is AFTER i18n set up
        from safe.gui.tools.keywords_dialog import KeywordsDialog

        # Next block is a fix for #776
        if self.iface.activeLayer() is None:
            return

        try:
            keyword_io = KeywordIO()
            keyword_io.read_keywords(self.iface.activeLayer())
        except UnsupportedProviderError:
            # noinspection PyUnresolvedReferences,PyCallByClass
            # noinspection PyTypeChecker,PyArgumentList
            QMessageBox.warning(
                None, self.tr('Unsupported layer type'),
                self.tr('The layer you have selected cannot be used for '
                        'analysis because its data type is unsupported.'))
            return
        # End of fix for #776
        # Fix for #793
        except NoKeywordsFoundError:
            # we will create them from scratch in the dialog
            pass
        # End of fix for #793
        # Fix for filtered-layer
        except InvalidParameterError, e:
            # noinspection PyTypeChecker,PyTypeChecker,PyArgumentList
            QMessageBox.warning(None, self.tr('Invalid Layer'), e.message)
            return

        dialog = KeywordsDialog(self.iface.mainWindow(), self.iface,
                                self.dock_widget)
        dialog.exec_()  # modal
Example #41
0
class Plugin(object):
    """The QGIS interface implementation for the InaSAFE plugin.

    This class acts as the 'glue' between QGIS and our custom logic.
    It creates a toolbar and menu bar entry and launches the InaSAFE user
    interface if these are activated.
    """
    def __init__(self, iface):
        """Class constructor.

        On instantiation, the plugin instance will be assigned a copy
        of the QGIS iface object which will allow this plugin to access and
        manipulate the running QGIS instance that spawned it.

        :param iface:Quantum GIS iface instance. This instance is
            automatically passed to the plugin by QGIS when it loads the
            plugin.
        :type iface: QGisAppInterface
        """
        # Save reference to the QGIS interface
        self.iface = iface
        self.dock_widget = None
        self.action_import_dialog = None
        self.action_save_scenario = None
        self.action_batch_runner = None
        self.action_shake_converter = None
        self.action_minimum_needs = None
        self.action_minimum_needs_config = None
        self.action_multi_buffer = None
        self.key_action = None
        self.action_options = None
        self.action_keywords_wizard = None
        self.action_function_centric_wizard = None
        self.action_extent_selector = None
        self.translator = None
        self.toolbar = None
        self.wizard = None
        self.actions = []  # list of all QActions we create for InaSAFE
        self.action_dock = None
        self.action_toggle_rubberbands = None
        self.message_bar_item = None
        # Flag indicating if toolbar should show only common icons or not
        self.full_toolbar = False
        # print self.tr('InaSAFE')
        # For enable/disable the keyword editor icon
        self.iface.currentLayerChanged.connect(self.layer_changed)

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

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

    def add_action(self, action, add_to_toolbar=True, add_to_legend=False):
        """Add a toolbar icon to the InaSAFE toolbar.

        :param action: The action that should be added to the toolbar.
        :type action: QAction

        :param add_to_toolbar: Flag indicating whether the action should also
            be added to the InaSAFE toolbar. Defaults to True.
        :type add_to_toolbar: bool

        """
        # store in the class list of actions for easy plugin unloading
        self.actions.append(action)
        self.iface.addPluginToMenu(self.tr('InaSAFE'), action)
        if add_to_toolbar:
            self.toolbar.addAction(action)
        if add_to_legend:
            # The id is the action name without spaces, tabs ...
            self.iface.legendInterface().addLegendLayerAction(
                action, self.tr('InaSAFE'), ''.join(action.text().split()),
                QgsMapLayer.VectorLayer, True)
            self.iface.legendInterface().addLegendLayerAction(
                action, self.tr('InaSAFE'), ''.join(action.text().split()),
                QgsMapLayer.RasterLayer, True)

    def _create_dock_toggle_action(self):
        """Create action for plugin dockable window (show/hide)."""
        # pylint: disable=W0201
        icon = resources_path('img', 'icons', 'icon.svg')
        self.action_dock = QAction(QIcon(icon), self.tr('Toggle InaSAFE Dock'),
                                   self.iface.mainWindow())
        self.action_dock.setObjectName('InaSAFEDockToggle')
        self.action_dock.setStatusTip(self.tr('Show/hide InaSAFE dock widget'))
        self.action_dock.setWhatsThis(self.tr('Show/hide InaSAFE dock widget'))
        self.action_dock.setCheckable(True)
        self.action_dock.setChecked(True)
        self.action_dock.triggered.connect(self.toggle_dock_visibility)
        self.add_action(self.action_dock)

        # --------------------------------------
        # Create action for keywords creation wizard
        # -------------------------------------

    def _create_keywords_wizard_action(self):
        """Create action for keywords creation wizard."""
        icon = resources_path('img', 'icons', 'show-keyword-wizard.svg')
        self.action_keywords_wizard = QAction(
            QIcon(icon), self.tr('Keywords Creation Wizard'),
            self.iface.mainWindow())
        self.action_keywords_wizard.setStatusTip(
            self.tr('Open InaSAFE keywords creation wizard'))
        self.action_keywords_wizard.setWhatsThis(
            self.tr('Open InaSAFE keywords creation wizard'))
        self.action_keywords_wizard.setEnabled(False)
        self.action_keywords_wizard.triggered.connect(
            self.show_keywords_wizard)
        self.add_action(self.action_keywords_wizard, add_to_legend=True)

    def _create_analysis_wizard_action(self):
        """Create action for IF-centric wizard."""
        icon = resources_path('img', 'icons', 'show-wizard.svg')
        self.action_function_centric_wizard = QAction(
            QIcon(icon), self.tr('Impact Function Centric Wizard'),
            self.iface.mainWindow())
        self.action_function_centric_wizard.setStatusTip(
            self.tr('Open InaSAFE impact function centric wizard'))
        self.action_function_centric_wizard.setWhatsThis(
            self.tr('Open InaSAFE impact function centric wizard'))
        self.action_function_centric_wizard.setEnabled(True)
        self.action_function_centric_wizard.triggered.connect(
            self.show_function_centric_wizard)
        self.add_action(self.action_function_centric_wizard)

    def _create_options_dialog_action(self):
        """Create action for options dialog."""
        icon = resources_path('img', 'icons', 'configure-inasafe.svg')
        self.action_options = QAction(QIcon(icon), self.tr('Options'),
                                      self.iface.mainWindow())
        self.action_options.setStatusTip(
            self.tr('Open InaSAFE options dialog'))
        self.action_options.setWhatsThis(
            self.tr('Open InaSAFE options dialog'))
        self.action_options.triggered.connect(self.show_options)
        self.add_action(self.action_options, add_to_toolbar=self.full_toolbar)

    def _create_minimum_needs_action(self):
        """Create action for minimum needs dialog."""
        icon = resources_path('img', 'icons', 'show-minimum-needs.svg')
        self.action_minimum_needs = QAction(
            QIcon(icon), self.tr('Minimum Needs Calculator'),
            self.iface.mainWindow())
        self.action_minimum_needs.setStatusTip(
            self.tr('Open InaSAFE minimum needs calculator'))
        self.action_minimum_needs.setWhatsThis(
            self.tr('Open InaSAFE minimum needs calculator'))
        self.action_minimum_needs.triggered.connect(self.show_minimum_needs)
        self.add_action(self.action_minimum_needs,
                        add_to_toolbar=self.full_toolbar)

    def _create_multi_buffer_action(self):
        """Create action for multi buffer dialog."""
        icon = resources_path('img', 'icons', 'show-multi-buffer.svg')
        self.action_multi_buffer = QAction(QIcon(icon),
                                           self.tr('Multi Buffer'),
                                           self.iface.mainWindow())
        self.action_multi_buffer.setStatusTip(
            self.tr('Open InaSAFE multi buffer'))
        self.action_multi_buffer.setWhatsThis(
            self.tr('Open InaSAFE multi buffer'))
        self.action_multi_buffer.triggered.connect(self.show_multi_buffer)
        self.add_action(self.action_multi_buffer,
                        add_to_toolbar=self.full_toolbar)

    def _create_minimum_needs_options_action(self):
        """Create action for global minimum needs dialog."""
        icon = resources_path('img', 'icons', 'show-global-minimum-needs.svg')
        self.action_minimum_needs_config = QAction(
            QIcon(icon), self.tr('Minimum Needs Configuration'),
            self.iface.mainWindow())
        self.action_minimum_needs_config.setStatusTip(
            self.tr('Open InaSAFE minimum needs configuration'))
        self.action_minimum_needs_config.setWhatsThis(
            self.tr('Open InaSAFE minimum needs configuration'))
        self.action_minimum_needs_config.triggered.connect(
            self.show_minimum_needs_configuration)
        self.add_action(self.action_minimum_needs_config,
                        add_to_toolbar=self.full_toolbar)

    def _create_shakemap_converter_action(self):
        """Create action for converter dialog."""
        icon = resources_path('img', 'icons', 'show-converter-tool.svg')
        self.action_shake_converter = QAction(QIcon(icon),
                                              self.tr('Shakemap Converter'),
                                              self.iface.mainWindow())
        self.action_shake_converter.setStatusTip(
            self.tr('Open InaSAFE Converter'))
        self.action_shake_converter.setWhatsThis(
            self.tr('Open InaSAFE Converter'))
        self.action_shake_converter.triggered.connect(
            self.show_shakemap_importer)
        self.add_action(self.action_shake_converter,
                        add_to_toolbar=self.full_toolbar)

    def _create_batch_runner_action(self):
        """Create action for batch runner dialog."""
        icon = resources_path('img', 'icons', 'show-batch-runner.svg')
        self.action_batch_runner = QAction(QIcon(icon),
                                           self.tr('Batch Runner'),
                                           self.iface.mainWindow())
        self.action_batch_runner.setStatusTip(self.tr('Open Batch Runner'))
        self.action_batch_runner.setWhatsThis(self.tr('Open Batch Runner'))
        self.action_batch_runner.triggered.connect(self.show_batch_runner)
        self.add_action(self.action_batch_runner,
                        add_to_toolbar=self.full_toolbar)

    def _create_save_scenario_action(self):
        """Create action for save scenario dialog."""
        icon = resources_path('img', 'icons', 'save-as-scenario.svg')
        self.action_save_scenario = QAction(QIcon(icon),
                                            self.tr('Save Current Scenario'),
                                            self.iface.mainWindow())
        message = self.tr('Save current scenario to text file')
        self.action_save_scenario.setStatusTip(message)
        self.action_save_scenario.setWhatsThis(message)
        # noinspection PyUnresolvedReferences
        self.action_save_scenario.triggered.connect(self.save_scenario)
        self.add_action(self.action_save_scenario,
                        add_to_toolbar=self.full_toolbar)

    def _create_osm_downloader_action(self):
        """Create action for import OSM Dialog."""
        icon = resources_path('img', 'icons', 'show-osm-download.svg')
        self.action_import_dialog = QAction(
            QIcon(icon), self.tr('OpenStreetMap Downloader'),
            self.iface.mainWindow())
        self.action_import_dialog.setStatusTip(
            self.tr('OpenStreetMap Downloader'))
        self.action_import_dialog.setWhatsThis(
            self.tr('OpenStreetMap Downloader'))
        self.action_import_dialog.triggered.connect(self.show_osm_downloader)
        self.add_action(self.action_import_dialog)

    def _create_add_osm_layer_action(self):
        """Create action for import OSM Dialog."""
        icon = resources_path('img', 'icons', 'add-osm-tiles-layer.svg')
        self.action_add_osm_layer = QAction(
            QIcon(icon), self.tr('Add OpenStreetMap Tile Layer'),
            self.iface.mainWindow())
        self.action_add_osm_layer.setStatusTip(
            self.tr('Add OpenStreetMap Tile Layer'))
        self.action_add_osm_layer.setWhatsThis(
            self.tr('Use this to add an OSM layer to your map. '
                    'It needs internet access to function.'))
        self.action_add_osm_layer.triggered.connect(self.add_osm_layer)
        self.add_action(self.action_add_osm_layer)

    def _create_show_definitions_action(self):
        """Create action for showing definitions."""
        icon = resources_path('img', 'icons', 'defintions.svg')
        self.action_show_definitions = QAction(QIcon(icon),
                                               self.tr('InaSAFE Help'),
                                               self.iface.mainWindow())
        self.action_show_definitions.setStatusTip(self.tr('Show InaSAFE Help'))
        self.action_show_definitions.setWhatsThis(
            self.
            tr('Use this to show a document describing all InaSAFE concepts.'))
        self.action_show_definitions.triggered.connect(self.show_definitions)
        self.add_action(self.action_show_definitions, add_to_toolbar=True)

    def _create_add_petabencana_layer_action(self):
        """Create action for import OSM Dialog."""
        icon = resources_path('img', 'icons', 'add-petabencana-layer.svg')
        self.action_add_petabencana_layer = QAction(
            QIcon(icon), self.tr('Add PetaBencana Flood Layer'),
            self.iface.mainWindow())
        self.action_add_petabencana_layer.setStatusTip(
            self.tr('Add PetaBencana Flood Layer'))
        self.action_add_petabencana_layer.setWhatsThis(
            self.tr('Use this to add a PetaBencana layer to your map. '
                    'It needs internet access to function.'))
        self.action_add_petabencana_layer.triggered.connect(
            self.add_petabencana_layer)
        self.add_action(self.action_add_petabencana_layer,
                        add_to_toolbar=False)

    def _create_rubber_bands_action(self):
        """Create action for toggling rubber bands."""
        icon = resources_path('img', 'icons', 'toggle-rubber-bands.svg')
        self.action_toggle_rubberbands = QAction(
            QIcon(icon), self.tr('Toggle Scenario Outlines'),
            self.iface.mainWindow())
        message = self.tr('Toggle rubber bands showing scenario extents.')
        self.action_toggle_rubberbands.setStatusTip(message)
        self.action_toggle_rubberbands.setWhatsThis(message)
        # Set initial state
        self.action_toggle_rubberbands.setCheckable(True)
        settings = QSettings()
        flag = bool(settings.value('inasafe/showRubberBands', False,
                                   type=bool))
        self.action_toggle_rubberbands.setChecked(flag)
        # noinspection PyUnresolvedReferences
        self.action_toggle_rubberbands.triggered.connect(
            self.dock_widget.toggle_rubber_bands)
        self.add_action(self.action_toggle_rubberbands)

    def _create_analysis_extent_action(self):
        """Create action for analysis extent dialog."""
        icon = resources_path('img', 'icons', 'set-extents-tool.svg')
        self.action_extent_selector = QAction(QIcon(icon),
                                              self.tr('Set Analysis Area'),
                                              self.iface.mainWindow())
        self.action_extent_selector.setStatusTip(
            self.tr('Set the analysis area for InaSAFE'))
        self.action_extent_selector.setWhatsThis(
            self.tr('Set the analysis area for InaSAFE'))
        self.action_extent_selector.triggered.connect(
            self.show_extent_selector)
        self.add_action(self.action_extent_selector)

    def _create_test_layers_action(self):
        """Create action for adding layers (developer mode, non final only)."""
        final_release = release_status() == 'final'
        settings = QSettings()
        self.developer_mode = settings.value('inasafe/developer_mode',
                                             False,
                                             type=bool)
        if not final_release and self.developer_mode:
            icon = resources_path('img', 'icons', 'add-test-layers.svg')
            self.action_add_layers = QAction(QIcon(icon),
                                             self.tr('Add Test Layers'),
                                             self.iface.mainWindow())
            self.action_add_layers.setStatusTip(self.tr('Add test layers'))
            self.action_add_layers.setWhatsThis(self.tr('Add test layers'))
            self.action_add_layers.triggered.connect(self.add_test_layers)

            self.add_action(self.action_add_layers)

    def _create_run_test_action(self):
        """Create action for running tests (developer mode, non final only)."""
        final_release = release_status() == 'final'
        settings = QSettings()
        self.developer_mode = settings.value('inasafe/developer_mode',
                                             False,
                                             type=bool)
        if not final_release and self.developer_mode:

            default_package = unicode(
                settings.value('inasafe/testPackage', 'safe', type=str))
            msg = self.tr('Run tests in %s' % default_package)

            self.test_button = QToolButton()
            self.test_button.setMenu(QMenu())
            self.test_button.setPopupMode(QToolButton.MenuButtonPopup)

            icon = resources_path('img', 'icons', 'run-tests.svg')
            self.action_run_tests = QAction(QIcon(icon), msg,
                                            self.iface.mainWindow())

            self.action_run_tests.setStatusTip(msg)
            self.action_run_tests.setWhatsThis(msg)
            self.action_run_tests.triggered.connect(self.run_tests)

            self.test_button.menu().addAction(self.action_run_tests)
            self.test_button.setDefaultAction(self.action_run_tests)

            self.action_select_package = QAction(QIcon(icon),
                                                 self.tr('Select package'),
                                                 self.iface.mainWindow())

            self.action_select_package.setStatusTip(
                self.tr('Select Test Package'))
            self.action_select_package.setWhatsThis(
                self.tr('Select Test Package'))
            self.action_select_package.triggered.connect(
                self.select_test_package)
            self.test_button.menu().addAction(self.action_select_package)
            self.toolbar.addWidget(self.test_button)

            self.add_action(self.action_run_tests, add_to_toolbar=False)
            self.add_action(self.action_select_package, add_to_toolbar=False)

    def _create_dock(self):
        """Create dockwidget and tabify it with the legend."""
        # Import dock here as it needs to be imported AFTER i18n is set up
        from safe.gui.widgets.dock import Dock
        self.dock_widget = Dock(self.iface)
        self.dock_widget.setObjectName('InaSAFE-Dock')
        self.iface.addDockWidget(Qt.RightDockWidgetArea, self.dock_widget)
        legend_tab = self.iface.mainWindow().findChild(QApplication, 'Legend')
        if legend_tab:
            self.iface.mainWindow().tabifyDockWidget(legend_tab,
                                                     self.dock_widget)
            self.dock_widget.raise_()

    def initGui(self):
        """Gui initialisation procedure (for QGIS plugin api).

        .. note:: Don't change the name of this method from initGui!

        This method is called by QGIS and should be used to set up
        any graphical user interface elements that should appear in QGIS by
        default (i.e. before the user performs any explicit action with the
        plugin).
        """
        self.toolbar = self.iface.addToolBar('InaSAFE')
        self.toolbar.setObjectName('InaSAFEToolBar')
        self.dock_widget = None
        # Now create the actual dock
        self._create_dock()
        # And all the menu actions
        # Configuration Group
        self._create_dock_toggle_action()
        self._create_options_dialog_action()
        self._create_minimum_needs_options_action()
        self._create_analysis_extent_action()
        self._create_rubber_bands_action()
        self._add_spacer_to_menu()
        self._create_keywords_wizard_action()
        self._create_analysis_wizard_action()
        self._add_spacer_to_menu()
        self._create_osm_downloader_action()
        self._create_add_osm_layer_action()
        self._create_add_petabencana_layer_action()
        self._create_shakemap_converter_action()
        self._create_minimum_needs_action()
        self._create_multi_buffer_action()
        self._create_test_layers_action()
        self._create_run_test_action()
        self._add_spacer_to_menu()
        self._create_batch_runner_action()
        self._create_save_scenario_action()
        self._add_spacer_to_menu()
        self._create_show_definitions_action()

        # Hook up a slot for when the dock is hidden using its close button
        # or  view-panels
        #
        self.dock_widget.visibilityChanged.connect(self.toggle_inasafe_action)
        # Also deal with the fact that on start of QGIS dock may already be
        # hidden.
        self.action_dock.setChecked(self.dock_widget.isVisible())

    def _add_spacer_to_menu(self):
        """Create a spacer to the menu to separate action groups."""
        separator = QAction(self.iface.mainWindow())
        separator.setSeparator(True)
        self.iface.addPluginToMenu(self.tr('InaSAFE'), separator)

    @staticmethod
    def clear_modules():
        """Unload inasafe functions and try to return QGIS to before InaSAFE.

        .. todo:: I think this function can be removed. TS.
        """
        # next lets force remove any inasafe related modules
        modules = []
        for module in sys.modules:
            if 'inasafe' in module:
                # Check if it is really one of our modules i.e. exists in the
                # plugin directory
                tokens = module.split('.')
                path = ''
                for myToken in tokens:
                    path += os.path.sep + myToken
                parent = os.path.abspath(
                    os.path.join(__file__, os.path.pardir, os.path.pardir))
                full_path = os.path.join(parent, path + '.py')
                if os.path.exists(os.path.abspath(full_path)):
                    LOGGER.debug('Removing: %s' % module)
                    modules.append(module)
        for module in modules:
            del (sys.modules[module])
        for module in sys.modules:
            if 'inasafe' in module:
                print module

        # Lets also clean up all the path additions that were made
        package_path = os.path.abspath(
            os.path.join(os.path.dirname(__file__), os.path.pardir))
        LOGGER.debug('Path to remove: %s' % package_path)
        # We use a list comprehension to ensure duplicate entries are removed
        LOGGER.debug(sys.path)
        sys.path = [y for y in sys.path if package_path not in y]
        LOGGER.debug(sys.path)

    def unload(self):
        """GUI breakdown procedure (for QGIS plugin api).

        .. note:: Don't change the name of this method from unload!

        This method is called by QGIS and should be used to *remove*
        any graphical user interface elements that should appear in QGIS.
        """
        # Remove the plugin menu item and icon
        if self.wizard:
            self.wizard.deleteLater()
        for myAction in self.actions:
            self.iface.removePluginMenu(self.tr('InaSAFE'), myAction)
            self.iface.removeToolBarIcon(myAction)
            self.iface.legendInterface().removeLegendLayerAction(myAction)
        self.iface.mainWindow().removeDockWidget(self.dock_widget)
        self.iface.mainWindow().removeToolBar(self.toolbar)
        self.dock_widget.setVisible(False)
        self.dock_widget.destroy()
        self.iface.currentLayerChanged.disconnect(self.layer_changed)

    def toggle_inasafe_action(self, checked):
        """Check or un-check the toggle inaSAFE toolbar button.

        This slot is called when the user hides the inaSAFE panel using its
        close button or using view->panels.

        :param checked: True if the dock should be shown, otherwise False.
        :type checked: bool
        """

        self.action_dock.setChecked(checked)

    # Run method that performs all the real work
    def toggle_dock_visibility(self):
        """Show or hide the dock widget."""
        if self.dock_widget.isVisible():
            self.dock_widget.setVisible(False)
        else:
            self.dock_widget.setVisible(True)
            self.dock_widget.raise_()

    def add_test_layers(self):
        """Add standard test layers."""
        from safe.test.utilities import load_standard_layers
        load_standard_layers()
        rect = QgsRectangle(106.806, -6.195, 106.837, -6.167)
        self.iface.mapCanvas().setExtent(rect)

    def select_test_package(self):
        """Select the test package."""
        settings = QSettings()
        default_package = 'safe'
        user_package = unicode(
            settings.value('inasafe/testPackage', default_package, type=str))

        test_package, _ = QInputDialog.getText(
            self.iface.mainWindow(), self.tr('Select the python test package'),
            self.tr('Select the python test package'), QLineEdit.Normal,
            user_package)

        if test_package == '':
            test_package = default_package

        settings.setValue('inasafe/testPackage', test_package)
        msg = self.tr('Run tests in %s' % test_package)
        self.action_run_tests.setWhatsThis(msg)
        self.action_run_tests.setText(msg)

    def run_tests(self):
        """Run unit tests in the python console."""
        from PyQt4.QtGui import QDockWidget
        main_window = self.iface.mainWindow()
        action = main_window.findChild(QAction, 'mActionShowPythonDialog')
        action.trigger()
        settings = QSettings()
        package = unicode(
            settings.value('inasafe/testPackage', 'safe', type=str))
        for child in main_window.findChildren(QDockWidget, 'PythonConsole'):
            if child.objectName() == 'PythonConsole':
                child.show()
                for widget in child.children():
                    if 'PythonConsoleWidget' in str(widget.__class__):
                        # print "Console widget found"
                        shell = widget.shell
                        shell.runCommand(
                            'from inasafe.test_suite import test_package')
                        shell.runCommand('test_package(\'%s\')' % package)
                        break

    def show_extent_selector(self):
        """Show the extent selector widget for defining analysis extents."""
        # import here only so that it is AFTER i18n set up
        from safe.gui.tools.extent_selector_dialog import ExtentSelectorDialog
        widget = ExtentSelectorDialog(
            self.iface,
            self.iface.mainWindow(),
            extent=self.dock_widget.extent.user_extent,
            crs=self.dock_widget.extent.crs)
        widget.clear_extent.connect(
            self.dock_widget.extent.clear_user_analysis_extent)
        widget.extent_defined.connect(
            self.dock_widget.define_user_analysis_extent)
        # This ensures that run button state is updated on dialog close
        widget.extent_selector_closed.connect(
            self.dock_widget.validate_impact_function)
        # Needs to be non modal to support hide -> interact with map -> show
        widget.show()  # non modal

    def show_minimum_needs(self):
        """Show the minimum needs dialog."""
        # import here only so that it is AFTER i18n set up
        from safe.gui.tools.minimum_needs.needs_calculator_dialog import (
            NeedsCalculatorDialog)

        dialog = NeedsCalculatorDialog(self.iface.mainWindow())
        dialog.exec_()

    def show_minimum_needs_configuration(self):
        """Show the minimum needs dialog."""
        # import here only so that it is AFTER i18n set up
        from safe.gui.tools.minimum_needs.needs_manager_dialog import (
            NeedsManagerDialog)

        dialog = NeedsManagerDialog(parent=self.iface.mainWindow(),
                                    dock=self.dock_widget)
        dialog.exec_()  # modal

    def show_options(self):
        """Show the options dialog."""
        # import here only so that it is AFTER i18n set up
        from safe.gui.tools.options_dialog import OptionsDialog

        dialog = OptionsDialog(self.iface, self.dock_widget,
                               self.iface.mainWindow())
        dialog.exec_()  # modal

    def show_keywords_wizard(self):
        """Show the keywords creation wizard."""
        # import here only so that it is AFTER i18n set up
        from safe.gui.tools.wizard.wizard_dialog import WizardDialog

        if self.iface.activeLayer() is None:
            return

        # Don't break an existing wizard session if accidentally clicked
        if self.wizard and self.wizard.isVisible():
            return

        # Prevent spawning multiple copies since the IFCW is non modal
        if not self.wizard:
            self.wizard = WizardDialog(self.iface.mainWindow(), self.iface,
                                       self.dock_widget)
        self.wizard.set_keywords_creation_mode()
        self.wizard.exec_()  # modal

    def show_function_centric_wizard(self):
        """Show the function centric wizard."""
        # import here only so that it is AFTER i18n set up
        from safe.gui.tools.wizard.wizard_dialog import WizardDialog

        # Don't break an existing wizard session if accidentally clicked
        if self.wizard and self.wizard.isVisible():
            return

        # Prevent spawning multiple copies since it is non modal
        if not self.wizard:
            self.wizard = WizardDialog(self.iface.mainWindow(), self.iface,
                                       self.dock_widget)
        self.wizard.set_function_centric_mode()
        # non-modal in order to hide for selecting user extent
        self.wizard.show()

    def show_shakemap_importer(self):
        """Show the converter dialog."""
        # import here only so that it is AFTER i18n set up
        from safe.gui.tools.shake_grid.shakemap_converter_dialog import (
            ShakemapConverterDialog)

        dialog = ShakemapConverterDialog(self.iface.mainWindow(), self.iface,
                                         self.dock_widget)
        dialog.exec_()  # modal

    def show_multi_buffer(self):
        from safe.gui.tools.multi_buffer_dialog import (MultiBufferDialog)

        dialog = MultiBufferDialog(self.iface.mainWindow(), self.iface,
                                   self.dock_widget)
        dialog.exec_()  # modal

    def show_osm_downloader(self):
        """Show the OSM buildings downloader dialog."""
        from safe.gui.tools.osm_downloader_dialog import OsmDownloaderDialog

        dialog = OsmDownloaderDialog(self.iface.mainWindow(), self.iface)
        dialog.show()  # non modal

    def add_osm_layer(self):
        """Add OSM tile layer to the map.

        This uses a gdal wrapper around the OSM tile service - see the
        WorldOSM.gdal file for how it is constructed.
        """
        path = resources_path('osm', 'WorldOSM.gdal')
        layer = QgsRasterLayer(path, self.tr('OpenStreetMap'))
        registry = QgsMapLayerRegistry.instance()

        # For older versions we just add directly to the top of legend
        if QGis.QGIS_VERSION_INT < 20400:
            # True flag adds layer directly to legend
            registry.addMapLayer(layer, True)
            return
        # Otherwise try to add it as the last layer in the list
        # False flag prevents layer being added to legend
        registry.addMapLayer(layer, False)
        root = QgsProject.instance().layerTreeRoot()
        index = len(root.findLayers()) + 1
        # LOGGER.info('Inserting layer %s at position %s' % (
        #    layer.source(), index))
        root.insertLayer(index, layer)
        QgsMapLayerRegistry.instance().addMapLayer(layer)

    def show_definitions(self):
        """Show InaSAFE Definitions (a report showing all key metadata).
        """
        from safe.gui.tools.help_dialog import HelpDialog
        from safe.gui.tools.help import definitions_help
        dialog = HelpDialog(self.iface.mainWindow(),
                            definitions_help.definitions_help())
        dialog.show()  # non modal

    def add_petabencana_layer(self):
        """Add petabencana layer to the map.

        This uses the PetaBencana API to fetch the latest floods in JK. See
        https://data.petabencana.id/floods
        """
        from safe.gui.tools.peta_bencana_dialog import PetaBencanaDialog
        dialog = PetaBencanaDialog(self.iface.mainWindow(), self.iface)
        dialog.show()  # non modal

    def show_batch_runner(self):
        """Show the batch runner dialog."""
        from safe.gui.tools.batch.batch_dialog import BatchDialog

        dialog = BatchDialog(parent=self.iface.mainWindow(),
                             iface=self.iface,
                             dock=self.dock_widget)
        dialog.exec_()  # modal

    def save_scenario(self):
        """Save current scenario to text file"""
        from safe.gui.tools.save_scenario import SaveScenarioDialog

        dialog = SaveScenarioDialog(iface=self.iface, dock=self.dock_widget)
        dialog.save_scenario()

    def _disable_keyword_tools(self):
        """Internal helper to disable the keyword and wizard actions."""
        self.action_keywords_wizard.setEnabled(False)

    def layer_changed(self, layer):
        """Enable or disable keywords editor icon when active layer changes.

        :param layer: The layer that is now active.
        :type layer: QgsMapLayer
        """
        if not layer:
            self._disable_keyword_tools()
            return
        if not hasattr(layer, 'providerType'):
            self._disable_keyword_tools()
            return
        if layer.providerType() == 'wms':
            self._disable_keyword_tools()
            return
        if is_raster_layer(layer) and layer.bandCount() > 1:
            self._disable_keyword_tools()
            return

        self.action_keywords_wizard.setEnabled(True)

    def shortcut_f7(self):
        """Executed when user press F7 - will show the shakemap importer."""
        self.show_shakemap_importer()
Example #42
0
    def add_action(
        self,
        icon_path,
        text,
        callback,
        enabled_flag=True,
        add_to_menu=True,
        add_to_toolbar=True,
        status_tip=None,
        whats_this=None,
        parent=None):
        """Add a toolbar icon to the toolbar.

        :param icon_path: Path to the icon for this action. Can be a resource
            path (e.g. ':/plugins/foo/bar.png') or a normal file system path.
        :type icon_path: str

        :param text: Text that should be shown in menu items for this action.
        :type text: str

        :param callback: Function to be called when the action is triggered.
        :type callback: function

        :param enabled_flag: A flag indicating if the action should be enabled
            by default. Defaults to True.
        :type enabled_flag: bool

        :param add_to_menu: Flag indicating whether the action should also
            be added to the menu. Defaults to True.
        :type add_to_menu: bool

        :param add_to_toolbar: Flag indicating whether the action should also
            be added to the toolbar. Defaults to True.
        :type add_to_toolbar: bool

        :param status_tip: Optional text to show in a popup when mouse pointer
            hovers over the action.
        :type status_tip: str

        :param parent: Parent widget for the new action. Defaults None.
        :type parent: QWidget

        :param whats_this: Optional text to show in the status bar when the
            mouse pointer hovers over the action.

        :returns: The action that was created. Note that the action is also
            added to self.actions list.
        :rtype: QAction
        """

        # Create the dialog (after translation) and keep reference
        self.dlg = RNCLoaderDialog()
        self.dlg.pushButton.clicked.connect(self.selectRootDirectory)
        self.chartModel = QStandardItemModel(self.dlg.chartListView)
        self.filterModel = QSortFilterProxyModel()
        self.filterModel.setDynamicSortFilter(True)
        self.filterModel.setFilterCaseSensitivity(False)
        self.filterModel.setSourceModel(self.chartModel)
        self.dlg.chartListView.setModel(self.filterModel)
        self.dlg.filterLineEdit.textChanged.connect(
            self.filterModel.setFilterWildcard)

        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.addPluginToRasterMenu(
                self.menu,
                action)

        self.actions.append(action)

        return action
Example #43
0
    def __init__(self, font, parent=None):
        super(MainWindow, self).__init__(parent)
        self.font = font
        self.setWindowTitle("Meridien")
        central_widget = QWidget(self)
        self.setCentralWidget(central_widget)

        #Center on screen
        resolution = QDesktopWidget().screenGeometry()
        self.move((resolution.width() / 2) - (self.frameSize().width() / 2),
                  (resolution.height() / 2) - (self.frameSize().height() / 2))
        """
        Setting up menu bar
        """

        close_action = QAction('Close', self)
        close_action.setShortcut("Ctrl+Q")
        close_action.setStatusTip('Leave the app')
        close_action.triggered.connect(lambda: self.close())

        open_refinement_folder = QAction('Open Refinement Folder', self)
        open_refinement_folder.triggered.connect(self.open_refinement_folder)

        self.mainMenu = self.menuBar()
        self.fileMenu = self.mainMenu.addMenu('&File')
        self.fileMenu.addAction(open_refinement_folder)
        self.fileMenu.addAction(close_action)
        self.refinement_folder = ""

        create_new_fsc_plot = QAction('&New FSC plot', self)
        create_new_fsc_plot.triggered.connect(
            self.event_ontriggered_show_fsc_plot)

        create_new_overview_plot = QAction('&New resolution overview plot',
                                           self)
        create_new_overview_plot.triggered.connect(
            self.event_show_resolution_overview_plot)
        self.plotMenu = self.mainMenu.addMenu('&Plot')
        self.plotMenu.addAction(create_new_fsc_plot)
        self.plotMenu.addAction(create_new_overview_plot)
        """
        Setup other components
        """
        self.layout = QGridLayout(central_widget)
        self.setMenuBar(self.mainMenu)

        self.tree = QTreeWidget(self)
        self.tree.setHeaderHidden(True)
        self.layout.addWidget(self.tree, 1, 0)

        self.root_items_path_dictionary = {}

        # Threads
        self.threadpool = QThreadPool()
        self.thread_list = []
        thr = QThread(self)
        thr.start()

        self.reader = DriverFileReader()
        self.reader.moveToThread(thr)
        self.thread_list.append(thr)
        self.timer = QTimer(self)

        # Connect signals
        self.reader.sig_sendfolders.connect(self.fill_tree)
        self.reader.sig_sendfsc.connect(self.show_dialog_fsc)
        self.tree.itemChanged.connect(self._event_select_deselect_all)
        self.sig_update_tree.connect(self.update_tree)
        self.sig_show_overview_plot.connect(
            self.event_show_resolution_overview_plot)
        self.show()
        self.open_refinement_folder()

        self.monitor = None
Example #44
0
class MetaSearchPlugin(object):
    """base plugin"""
    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))

    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)

    def unload(self):
        """teardown"""

        # remove the plugin menu item and icon
        self.iface.removePluginWebMenu(self.web_menu, self.action_run)
        self.iface.removePluginWebMenu(self.web_menu, self.action_help)
        self.iface.removeToolBarIcon(self.action_run)
        self.iface.removeToolBarIcon(self.action_help)

    def run(self):
        """open MetaSearch"""

        self.dialog.exec_()

    def help(self):
        """open help in user's default web browser"""

        open_url(self.context.metadata.get('general', 'homepage'))
    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
Example #46
0
class StartData:

    def __init__(self, iface):
        
        self.iface = iface

        self.tableSchema = 'edgv'
        self.geometryColumn = 'geom'
        self.keyColumn = 'id'

    def initGui(self): 
        # cria uma ação que iniciará a configuração do plugin 
        pai = self.iface.mainWindow()
        icon_path = ':/plugins/StartData/icon.png'
        self.action = QAction (QIcon (icon_path),u"Acessa banco de dados para revisão", pai)
        self.action.setObjectName ("Stard database")
        self.action.setStatusTip(None)
        self.action.setWhatsThis(None)
        self.action.triggered.connect(self.run)
        # Adicionar o botão icone
        self.iface.addToolBarIcon (self.action) 

    def unload(self):
        # remove o item de ícone do QGIS GUI.
        self.iface.removeToolBarIcon (self.action)
        
        
    def run(self):

    ##################################
    ###### PEGA A LAYER ATIVA ########
    ##################################

        layer = self.iface.activeLayer() 

        if not layer:
            self.iface.messageBar().pushMessage("Erro", u"Esperando uma Active Layer!", level=QgsMessageBar.CRITICAL, duration=4)
            return
        if layer.featureCount() == 0:
            self.iface.messageBar().pushMessage("Erro", u"a camada não possui feições!", level=QgsMessageBar.CRITICAL, duration=4)
            return

        parametros = layer.source().split(" ") # recebe todos os parametros em uma lista ( senha, porta, password etc..)

    ####################################
    ###### INICIANDO CONEXÃO DB ########
    ####################################

        # Outra opção para isso, seria usar ex: self.dbname.. self.host.. etc.. direto dentro do laço for.
        dbname = "" 
        host = ""
        port = 0
        user = ""
        password = ""

        for i in parametros:
            part = i.split("=")
            
        # Recebe os parametros guardados na própria Layer

            if "dbname" in part[0]:
                dbname = part[1].replace("'", "")

            elif "host" in part[0]:
                host = part[1].replace("'", "")

            elif "port" in part[0]:
                port = int(part[1].replace("'", ""))

            elif "user" in part[0]:
                user = part[1].replace("'", "")

            elif "password" in part[0]:
                password = part[1].split("|")[0].replace("'", "")

        #print dbname, host, port, user, password

        # Testa se os parametros receberam os valores pretendidos, caso não, apresenta a mensagem informando..
        if len(dbname) == 0 or len(host) == 0 or port == 0 or len(user) == 0 or len(password) == 0:
            self.iface.messageBar().pushMessage("Erro", u'Um dos parametros não foram devidamente recebidos!', level=QgsMessageBar.CRITICAL, duration=4)
            return

    ####################################
    #### SETA VALORES DE CONEXÃO DB ####
    ####################################

        connection = QSqlDatabase.addDatabase('QPSQL')
        connection.setHostName(host)
        connection.setPort(port)
        connection.setUserName(user)
        connection.setPassword(password)
        connection.setDatabaseName(dbname)

        if not connection.isOpen(): # Testa se a conexão esta recebendo os parametros adequadamente.
            if not connection.open():
                print 'Error connecting to database!'
                self.iface.messageBar().pushMessage("Erro", u'Error connecting to database!', level=QgsMessageBar.CRITICAL, duration=4)
                print connection.lastError().text()
                return

    ####################################
    ###### CRIAÇÃO DE MEMORY LAYER #####
    ####################################
        

        layerCrs = layer.crs().authid() # Passa o formato (epsg: numeros)

        flagsLayerName = layer.name() + "_flags"
        flagsLayerExists = False

        for l in QgsMapLayerRegistry.instance().mapLayers().values(): # Recebe todas as camadas que estão abertas
            if l.name() == flagsLayerName: # ao encontrar o nome pretendido..
                self.flagsLayer = l # flagslayer vai receber o nome..
                self.flagsLayerProvider = l.dataProvider()
                flagsLayerExists = True # se encontrado os parametros buscados, recebe True.
                break
        
        if flagsLayerExists == False: # se não encontrado os parametros buscados, recebe False.
            tempString = "Point?crs="
            tempString += str(layerCrs)

            self.flagsLayer = QgsVectorLayer(tempString, flagsLayerName, "memory")
            self.flagsLayerProvider = self.flagsLayer.dataProvider()
            self.flagsLayerProvider.addAttributes([QgsField("id", QVariant.Int), QgsField("motivo", QVariant.String)])
            self.flagsLayer.updateFields()

        self.flagsLayer.startEditing()
        ids = [feat.id() for feat in self.flagsLayer.getFeatures()]
        self.flagsLayer.deleteFeatures(ids)
        self.flagsLayer.commitChanges()
        
        lista_fid = [] # Iniciando lista
        for f in layer.getFeatures():
            lista_fid.append(str(f.id())) # Guarda na lista. A lista de Feature ids passa tipo "int", foi convertido e guardado como "str".

        source = layer.source().split(" ")
        self.tableName = "" # Inicia vazio
        layerExistsInDB = False
        
        for i in source:
                
            if "table=" in i or "layername=" in i: # Se encontrar os atributos pretendidos dentre todos do for
                self.tableName = source[source.index(i)].split(".")[1] # Faz split em ponto e pega a segunda parte.
                self.tableName = self.tableName.replace('"', '')
                layerExistsInDB = True
                break
             
        if layerExistsInDB == False:
            self.iface.messageBar().pushMessage("Erro", u"Provedor da camada corrente não provem do banco de dados!", level=QgsMessageBar.CRITICAL, duration=4)
            return
        
        # Busca através do SQL 
        query_string  = '''select distinct (reason(ST_IsValidDetail(f."{2}",0))) AS motivo, '''
        query_string += '''ST_AsText(ST_Multi(ST_SetSrid(location(ST_IsValidDetail(f."{2}",0)), ST_Srid(f.{2})))) as local from '''
        query_string += '''(select "{3}", "{2}" from only "{0}"."{1}"  where ST_IsValid("{2}") = 'f' and {3} in ({4})) as f''' 
        query_string  = query_string.format(self.tableSchema, self.tableName, self.geometryColumn, self.keyColumn, ",".join(lista_fid))
        
        query = QSqlQuery(query_string)
        
        self.flagsLayer.startEditing()
        flagCount = 0 # iniciando contador que será referência para os IDs da camada de memória.

        listaFeatures = []
        while query.next():
            motivo = query.value(0)
            local = query.value(1)
            flagId = flagCount

            flagFeat = QgsFeature()
            flagGeom = QgsGeometry.fromWkt(local) # passa o local onde foi localizado o erro.
            flagFeat.setGeometry(flagGeom)
            flagFeat.initAttributes(2)
            flagFeat.setAttribute(0,flagId) # insere o id definido para a coluna 0 da layer de memória.
            flagFeat.setAttribute(1, motivo) # insere o motivo/razão pré-definida para a coluna 1 da layer de memória.

            listaFeatures.append(flagFeat)    

            flagCount += 1 # incrementando o contador a cada iteração

        self.flagsLayerProvider.addFeatures(listaFeatures)
        self.flagsLayer.commitChanges() # Aplica as alterações à camada.
        
        QgsMapLayerRegistry.instance().addMapLayer(self.flagsLayer) # Adicione a camada no mapa
        
        
        ##################################
        ##### TROCA MARCADOR DA LAYER ####
        ##################################
        
        # # AQUI PRETENDO PERSONALIZAR O MARCADOR DA MEMORY LAYER, POREM A PRINCIPIO SÓ ESTA ALTERANDO A LAYER ORIGINAL.
        # for lay in QgsMapLayerRegistry.instance().mapLayers().values():
            
        #     if lay == flagsLayerName and not layer.name():

        #         # Estilo base.    
        #         line = QgsLineSymbolV2()    

        #         # Crie uma linha de marcadores.
        #         marker_line = QgsMarkerLineSymbolLayerV2()
        #         marker_line.setInterval(10)

        #         # Configure o marcador.
        #         simple_marker = QgsSimpleMarkerSymbolLayerV2()
        #         simple_marker.setShape(QgsSimpleMarkerSymbolLayerBase.HalfSquare) # Formato
        #         simple_marker.setSize(3)
        #         simple_marker.setAngle(180)
        #         simple_marker.setColor(QColor('red')) # cor
        #         simple_marker.setOutlineColor(QColor('red')) # cor

        #         # O marcador tem sua própria camada de símbolo.
        #         marker = QgsMarkerSymbolV2()
        #         marker.changeSymbolLayer(0, simple_marker)

        #         # Adicione a camada à camada do marcador.
        #         marker_line.setSubSymbol(marker)

        #         # Finalmente, substitua a camada de símbolo no estilo base.
        #         line.changeSymbolLayer(0, marker_line)

        #         # Adicione o estilo à camada de linha.        
        #         renderer = QgsSingleSymbolRendererV2(line)
        #         layer.setRendererV2(renderer)
        
        if flagCount == 0: 
            
            QgsMapLayerRegistry.instance().removeMapLayer(self.flagsLayer.id())
            self.iface.messageBar().pushMessage("Aviso", u"Não foi encontrado Flags em \"" + layer.name() + "\" !", level=QgsMessageBar.CRITICAL, duration=4)

            return
        if len(query.lastError().text()) == 1:
            self.iface.messageBar().pushMessage("Aviso", "foram geradas " + str(flagCount) + " flags para a camada \"" + layer.name() + "\" !", level=QgsMessageBar.INFO, duration=4)
        else:
            self.iface.messageBar().pushMessage("Erro", u"a geração de flags falhou!", level=QgsMessageBar.CRITICAL, duration=4)
            print query.lastError().text()
class MainWindow(QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.setWindowIcon(QIcon(":/images/icon.png"))
        self.setCurrentFile("")

        # ----------- 数据 -------------
        self.spreadsheet = Spreadsheet()
        self.setCentralWidget(self.spreadsheet)

        self.findDialog = None
        self.locationLabel = None
        self.formulaLabel = None
        self.recentFiles = None  # QStringList recentFiles;
        self.curFile = None  # QString curFile;

        self.MaxRecentFiles = 5
        self.recentFileActions = [None] * self.MaxRecentFiles
        #
        self.separatorAction = None
        # #
        self.fileMenu = None
        self.editMenu = None
        self.selectSubMenu = None
        self.toolsMenu = None
        self.optionsMenu = None
        self.helpMenu = None
        self.fileToolBar = None
        self.editToolBar = None
        self.newAction = None
        self.openAction = None
        self.saveAction = None
        self.saveAsAction = None
        self.exitAction = None
        self.cutAction = None
        self.copyAction = None
        self.pasteAction = None
        self.deleteAction = None
        self.selectRowAction = None
        self.selectColumnAction = None
        self.selectAllAction = None
        self.findAction = None
        self.goToCellAction = None
        self.recalculateAction = None
        self.sortAction = None
        self.showGridAction = None
        self.autoRecalcAction = None
        self.aboutAction = None
        self.aboutQtAction = None
        # self.qApp = QApplication([]) # 这样写 有问题

        self.createActions()
        self.createMenus()
        self.createContextMenu()
        self.createToolBars()
        self.createStatusBar()

        # self.readSettings()

    # def closeEvent(self, event):
    #     if (self.okToContinue()):
    #         self.writeSettings()
    #         event.accept()
    #     else:
    #         event.ignore()

    @pyqtSlot()
    def newFile(self):
        if (self.okToContinue()):
            pass
            # spreadsheet.clear()
            # setCurrentFile("")

    @pyqtSlot()
    def open(self):
        pass

    @pyqtSlot()
    def save(self):
        pass

    @pyqtSlot()
    def saveAs(self):
        pass

    @pyqtSlot()
    def find(self):
        pass

    @pyqtSlot()
    def goToCell(self):
        pass

    @pyqtSlot()
    def sort(self):
        pass

    # 关于
    @pyqtSlot()
    def about(self):
        QMessageBox.about(
            self, str("About Spreadsheet"),
            str("<h2>Spreadsheet 1.1</h2>"
                "<p>Copyright &copy 2008 Software Inc."
                "<p>Spreadsheet is a small application that "
                "demonstrates QAction, QMainWindow, QMenuBar, "
                "QStatusBar, QTableWidget, QToolBar, and many other "
                "Qt classes."))

    @pyqtSlot()
    def openRecentFile(self):
        pass

    @pyqtSlot()
    def updateStatusBar(self):
        pass

    def spreadsheetModified(self):
        pass

    # 创建 Actions
    def createActions(self):

        # 新建
        self.newAction = QAction(str("&New"), self)
        self.newAction.setIcon(QIcon(":/images/new.png"))
        self.newAction.setShortcut(QKeySequence.New)
        self.newAction.setStatusTip(str("Create a new spreadsheet file"))
        self.connect(self.newAction, SIGNAL("triggered()"), self,
                     SLOT("newFile()"))

        # 打开
        self.openAction = QAction(str("&Open..."), self)
        self.openAction.setIcon(QIcon(":/images/open.png"))
        self.openAction.setShortcut(QKeySequence.Open)
        self.openAction.setStatusTip(str("Open an existing spreadsheet file"))
        self.connect(self.openAction, SIGNAL("triggered()"), self,
                     SLOT("open()"))

        # 保存
        self.saveAction = QAction(str("&Save"), self)
        self.saveAction.setIcon(QIcon(":/images/save.png"))
        self.saveAction.setShortcut(QKeySequence.Save)
        self.saveAction.setStatusTip(str("Save the spreadsheet to disk"))
        self.connect(self.saveAction, SIGNAL("triggered()"), self,
                     SLOT("save()"))

        # 另存为
        self.saveAsAction = QAction(str("Save &As..."), self)
        self.saveAsAction.setStatusTip(
            str("Save the spreadsheet under a name"))
        self.connect(self.saveAsAction, SIGNAL("triggered()"), self,
                     SLOT("saveAs()"))

        for i in range(self.MaxRecentFiles):
            self.recentFileActions[i] = QAction(self)
            self.recentFileActions[i].setVisible(False)
            self.connect(self.recentFileActions[i], SIGNAL("triggered()"),
                         self, SLOT("openRecentFile()"))
        # 退出
        self.exitAction = QAction(str("E&xit"), self)
        self.exitAction.setShortcut(str("Ctrl+Q"))
        self.exitAction.setStatusTip(str("Exit the application"))
        self.connect(self.exitAction, SIGNAL("triggered()"), self,
                     SLOT("close()"))

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

        # 剪切
        self.cutAction = QAction(str("Cu&t"), self)
        self.cutAction.setIcon(QIcon(":/images/cut.png"))
        self.cutAction.setShortcut(QKeySequence.Cut)
        self.cutAction.setStatusTip(
            str("Cut the current selection's contents "
                "to the clipboard"))
        self.connect(self.cutAction, SIGNAL("triggered()"), self.spreadsheet,
                     SLOT("cut()"))

        # 拷贝
        self.copyAction = QAction(str("&Copy"), self)
        self.copyAction.setIcon(QIcon(":/images/copy.png"))
        self.copyAction.setShortcut(QKeySequence.Copy)
        self.copyAction.setStatusTip(
            str("Copy the current selection's contents "
                "to the clipboard"))
        self.connect(self.copyAction, SIGNAL("triggered()"), self.spreadsheet,
                     SLOT("copy()"))

        # 黏贴
        self.pasteAction = QAction(str("&Paste"), self)
        self.pasteAction.setIcon(QIcon(":/images/paste.png"))
        self.pasteAction.setShortcut(QKeySequence.Paste)
        self.pasteAction.setStatusTip(
            str("Paste the clipboard's contents into "
                "the current selection"))
        self.connect(self.pasteAction, SIGNAL("triggered()"), self.spreadsheet,
                     SLOT("paste()"))

        self.deleteAction = QAction(str("&Delete"), self)
        self.deleteAction.setShortcut(QKeySequence.Delete)
        self.deleteAction.setStatusTip(
            str("Delete the current selection's "
                "contents"))
        # self.connect(self.deleteAction, SIGNAL("triggered()"),
        #         self.spreadsheet, SLOT(del()))

        self.selectRowAction = QAction(str("&Row"), self)
        self.selectRowAction.setStatusTip(
            str("Select all the cells in the "
                "current row"))
        self.connect(self.selectRowAction, SIGNAL("triggered()"),
                     self.spreadsheet, SLOT("selectCurrentRow()"))

        self.selectColumnAction = QAction(str("&Column"), self)
        self.selectColumnAction.setStatusTip(
            str("Select all the cells in the "
                "current column"))
        self.connect(self.selectColumnAction, SIGNAL("triggered()"),
                     self.spreadsheet, SLOT("selectCurrentColumn()"))

        self.selectAllAction = QAction(str("&All"), self)
        self.selectAllAction.setShortcut(QKeySequence.SelectAll)
        self.selectAllAction.setStatusTip(
            str("Select all the cells in the "
                "spreadsheet"))
        self.connect(self.selectAllAction, SIGNAL("triggered()"),
                     self.spreadsheet, SLOT("selectAll()"))

        self.findAction = QAction(str("&Find..."), self)
        self.findAction.setIcon(QIcon(":/images/find.png"))
        self.findAction.setShortcut(QKeySequence.Find)
        self.findAction.setStatusTip(str("Find a matching cell"))
        self.connect(self.findAction, SIGNAL("triggered()"), self,
                     SLOT("find()"))

        self.goToCellAction = QAction(str("&Go to Cell..."), self)
        self.goToCellAction.setIcon(QIcon(":/images/gotocell.png"))
        self.goToCellAction.setShortcut(str("Ctrl+G"))
        self.goToCellAction.setStatusTip(str("Go to the specified cell"))
        self.connect(self.goToCellAction, SIGNAL("triggered()"), self,
                     SLOT("goToCell()"))

        self.recalculateAction = QAction(str("&Recalculate"), self)
        self.recalculateAction.setShortcut(str("F9"))
        self.recalculateAction.setStatusTip(
            str("Recalculate all the "
                "spreadsheet's formulas"))
        self.connect(self.recalculateAction, SIGNAL("triggered()"),
                     self.spreadsheet, SLOT("recalculate()"))

        self.sortAction = QAction(str("&Sort..."), self)
        self.sortAction.setStatusTip(
            str("Sort the selected cells or all the "
                "cells"))
        self.connect(self.sortAction, SIGNAL("triggered()"), self,
                     SLOT("sort()"))

        self.showGridAction = QAction(str("&Show Grid"), self)
        self.showGridAction.setCheckable(True)
        self.showGridAction.setChecked(self.spreadsheet.showGrid())
        self.showGridAction.setStatusTip(
            str("Show or hide the spreadsheet's "
                "grid"))
        self.connect(self.showGridAction, SIGNAL("toggled(bool)"),
                     self.spreadsheet, SLOT("setShowGrid(bool)"))

        self.autoRecalcAction = QAction(str("&Auto-Recalculate"), self)
        self.autoRecalcAction.setCheckable(True)
        # self.autoRecalcAction.setChecked(self.spreadsheet.autoRecalculate())
        self.autoRecalcAction.setStatusTip(
            str("Switch auto-recalculation on or "
                "off"))
        # self.connect(self.autoRecalcAction, SIGNAL("toggled(bool)"),\
        # self.spreadsheet, SLOT("setAutoRecalculate(bool)"))

        self.aboutAction = QAction(str("&About"), self)
        self.aboutAction.setStatusTip(str("Show the application's About box"))
        self.connect(self.aboutAction, SIGNAL("triggered()"), self,
                     SLOT("about()"))

        self.aboutQtAction = QAction(str("About &Qt"), self)
        self.aboutQtAction.setStatusTip(str("Show the Qt library's About box"))
        # self.connect(self.aboutQtAction, SIGNAL("triggered()"), self.qApp, SLOT("aboutQt()"))

    # 创建 菜单栏
    def createMenus(self):

        self.fileMenu = self.menuBar().addMenu(str("&File"))
        self.fileMenu.addAction(self.newAction)
        self.fileMenu.addAction(self.openAction)
        self.fileMenu.addAction(self.saveAction)
        self.fileMenu.addAction(self.saveAsAction)
        self.separatorAction = self.fileMenu.addSeparator()

        for i in range(self.MaxRecentFiles):
            self.fileMenu.addAction(self.recentFileActions[i])

        self.fileMenu.addSeparator()
        self.fileMenu.addAction(self.exitAction)

        self.editMenu = self.menuBar().addMenu(str("&Edit"))
        self.editMenu.addAction(self.cutAction)
        self.editMenu.addAction(self.copyAction)
        self.editMenu.addAction(self.pasteAction)
        self.editMenu.addAction(self.deleteAction)

        self.selectSubMenu = self.editMenu.addMenu(str("&Select"))
        self.selectSubMenu.addAction(self.selectRowAction)
        self.selectSubMenu.addAction(self.selectColumnAction)
        self.selectSubMenu.addAction(self.selectAllAction)

        self.editMenu.addSeparator()
        self.editMenu.addAction(self.findAction)
        self.editMenu.addAction(self.goToCellAction)

        self.toolsMenu = self.menuBar().addMenu(str("&Tools"))
        self.toolsMenu.addAction(self.recalculateAction)
        self.toolsMenu.addAction(self.sortAction)

        self.optionsMenu = self.menuBar().addMenu(str("&Options"))
        self.optionsMenu.addAction(self.showGridAction)
        self.optionsMenu.addAction(self.autoRecalcAction)

        self.menuBar().addSeparator()

        helpMenu = self.menuBar().addMenu(str("&Help"))
        helpMenu.addAction(self.aboutAction)
        helpMenu.addAction(self.aboutQtAction)

    # 添加 上下文菜单,右键快捷菜单
    def createContextMenu(self):
        pass
        self.spreadsheet.addAction(self.cutAction)
        self.spreadsheet.addAction(self.copyAction)
        self.spreadsheet.addAction(self.pasteAction)
        self.spreadsheet.setContextMenuPolicy(Qt.ActionsContextMenu)

    def createToolBars(self):
        pass

    def createStatusBar(self):
        pass

    def readSettings(self):
        pass

    def writeSettings(self):
        pass

    def okToContinue(self):
        pass

    # def loadFile(const QString &fileName)
    def loadFile(self, fileName):
        pass

    # def saveFile(const QString &fileName)
    def saveFile(self, fileName):
        pass

    # def setCurrentFile(const QString &fileName)
    def setCurrentFile(self, fileName):
        pass

    def updateRecentFileActions(self):
        pass

    # def strippedName(const QString &fullFileName)
    def strippedName(self, fullFileName):
        pass