Ejemplo n.º 1
0
class Ui_SLim(object):
    def setupUi(self, SLim):
        SLim.setObjectName(_fromUtf8("SLim"))
        SLim.resize(800, 601)
        self.centralwidget = QWidget(SLim)
        self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
        self.verticalLayout = QVBoxLayout(self.centralwidget)
        self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))
        SLim.setCentralWidget(self.centralwidget)
        self.menubar = QMenuBar(SLim)
        self.menubar.setGeometry(QRect(0, 0, 800, 20))
        self.menubar.setObjectName(_fromUtf8("menubar"))
        SLim.setMenuBar(self.menubar)
        self.statusbar = QStatusBar(SLim)
        self.statusbar.setObjectName(_fromUtf8("statusbar"))
        SLim.setStatusBar(self.statusbar)

        ui_settings = slimUISettings()

        QMetaObject.connectSlotsByName(SLim)

        self.loopers = []
        self.loopers.append(LooperWidget(self.centralwidget, 0, ui_settings.looper))
        self.loopers.append(LooperWidget(self.centralwidget, 1, ui_settings.looper))
        for looper in self.loopers:
            self.verticalLayout.addWidget(looper)

        self.retranslateUi(SLim)

    def retranslateUi(self, SLim):
        for looper in SLim.ui.loopers:
            looper.retranslateUi()
        SLim.setWindowTitle(QApplication.translate("SLim", "MainWindow", None, QApplication.UnicodeUTF8))
Ejemplo n.º 2
0
class MainWindow(QMainWindow, object):
    """
    QMainWindow displays pipeline
    Parameters
    ----------
    port : str
        used port to communicate with pipeline
        Note: The firewall must be configure to accept input/output on this port
    """
    def __init__(self, port):
        super(MainWindow, self).__init__()
        self.setupUi(port)

    def setupUi(self, port):
        self.setObjectName("MainWindow")
        self.resize(600, 600)
        self.centralwidget = QWidget(self)
        p = self.centralwidget.palette()
        self.centralwidget.setAutoFillBackground(True)
        p.setColor(self.centralwidget.backgroundRole(), QColor(126, 135, 152))
        self.centralwidget.setPalette(p)
        self.centralwidget.setObjectName("centralwidget")
        self.gridLayout = QGridLayout(self.centralwidget)
        self.gridLayout.setObjectName("gridLayout")
        self.setCentralWidget(self.centralwidget)
        self.menubar = QMenuBar(self)
        self.menubar.setGeometry(QRect(0, 0, 808, 25))
        self.menubar.setObjectName("menubar")
        self.menuFile = QMenu(self.menubar)
        self.menuFile.setObjectName("menuFile")
        self.setMenuBar(self.menubar)
        self.statusbar = QStatusBar(self)
        self.statusbar.setObjectName("statusbar")
        self.setStatusBar(self.statusbar)
        self.actionQuit = QAction(self)
        self.actionQuit.setObjectName("actionQuit")
        self.menuFile.addSeparator()
        self.menuFile.addAction(self.actionQuit)
        self.menubar.addAction(self.menuFile.menuAction())
        self.actionReset = QAction(self)
        self.actionReset.setObjectName("reset")
        self.menuFile.addSeparator()
        self.menuFile.addAction(self.actionReset)
        self.menubar.addAction(self.menuFile.menuAction())
        # add other GUI objects
        self.graph_widget = GraphWidget(self.statusbar)
        self.gridLayout.addWidget(self.graph_widget, 1, 11, 10, 10)
        pixmap = QPixmap(':/images/cta-logo-mini.png')
        lbl = QLabel()
        lbl.setPixmap(pixmap)
        self.gridLayout.addWidget(lbl, 0, 0)
        p = self.graph_widget.palette()
        self.graph_widget.setAutoFillBackground(True)
        p.setColor(self.graph_widget.backgroundRole(),
                   QColor(255, 255, 255))  # QColor(226, 235, 252))
        self.graph_widget.setPalette(p)
        self.quitButton = QPushButton()  # self.centralwidget)
        self.quitButton.setObjectName("quitButton")
        self.quitButton.setText(
            QApplication.translate("MainWindow", "Quit", None,
                                   QApplication.UnicodeUTF8))
        self.gridLayout.addWidget(self.quitButton, 12, 0, 1, 1)
        self.info_label = InfoLabel(0, 4)
        self.info_label.setAutoFillBackground(True)
        self.gridLayout.addWidget(self.info_label, 1, 0, 1, 5)
        #self.info_label.setAlignment(PyQt4.Qt.AlignCenter);
        palette = QPalette()
        palette.setColor(self.info_label.backgroundRole(), Qt.lightGray)
        self.info_label.setPalette(palette)
        QObject.connect(self.quitButton, SIGNAL("clicked()"), self.stop)
        QObject.connect(self.actionQuit, SIGNAL("triggered()"), self.stop)
        QMetaObject.connectSlotsByName(self)
        self.retranslateUi()
        QObject.connect(self.actionQuit, SIGNAL("triggered()"), self.close)
        QMetaObject.connectSlotsByName(self)
        # Create GuiConnexion for ZMQ comminucation with pipeline
        self.guiconnection = GuiConnexion(gui_port=port,
                                          statusBar=self.statusbar)
        self.guiconnection.message.connect(self.graph_widget.pipechange)
        self.guiconnection.message.connect(self.info_label.pipechange)
        self.guiconnection.reset_message.connect(self.graph_widget.reset)
        self.guiconnection.reset_message.connect(self.info_label.reset)
        self.guiconnection.mode_message.connect(self.info_label.mode_receive)
        QObject.connect(self.actionReset, SIGNAL("triggered()"),
                        self.guiconnection.reset)
        QMetaObject.connectSlotsByName(self)
        # start the process
        self.guiconnection.start()

    def retranslateUi(self):
        self.setWindowTitle(
            QApplication.translate("ctapipe flow based GUI",
                                   "ctapipe flow based GUI", None,
                                   QApplication.UnicodeUTF8))
        self.menuFile.setTitle(
            QApplication.translate("MainWindow", "File", None,
                                   QApplication.UnicodeUTF8))
        self.actionQuit.setText(
            QApplication.translate("MainWindow", "Quit", None,
                                   QApplication.UnicodeUTF8))
        self.actionReset.setText(
            QApplication.translate("MainWindow", "Reset", None,
                                   QApplication.UnicodeUTF8))

    def stop(self):
        """Method connect (via Qt slot) to exit button
        Stops self.guiconnection (for ZMQ communication) process.
        Close main_windows
        """
        self.guiconnection.finish()
        self.guiconnection.join()
        self.close()

    def closeEvent(self, event):
        self.guiconnection.finish()
        self.guiconnection.join()
        event.accept()  # let the window close
Ejemplo n.º 3
0
class MainWindow(QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.dirty = False

        self.setObjectName("MainWindow")
        self.resize(800, 600)
        self.setWindowTitle("GA")  # TODO
        # TODO        app_icon = get_icon('OpenFisca22.png')
        #        self.setWindowIcon(app_icon)
        self.setLocale(QLocale(QLocale.French, QLocale.France))
        self.setDockOptions(QMainWindow.AllowNestedDocks
                            | QMainWindow.AllowTabbedDocks
                            | QMainWindow.AnimatedDocks)

        self.centralwidget = QWidget(self)
        self.gridLayout = QGridLayout(self.centralwidget)
        self.setCentralWidget(self.centralwidget)
        self.centralwidget.hide()

        self.statusbar = QStatusBar(self)
        self.statusbar.setObjectName("statusbar")
        self.setStatusBar(self.statusbar)

        # Showing splash screen
        pixmap = QPixmap(':/images/splash.png', 'png')
        self.splash = QSplashScreen(pixmap)
        font = self.splash.font()
        font.setPixelSize(10)
        self.splash.setFont(font)
        self.splash.show()
        self.splash.showMessage(
            "Initialisation...",
            Qt.AlignBottom | Qt.AlignCenter | Qt.AlignAbsolute,
            QColor(Qt.black))
        #        if CONF.get('main', 'current_version', '') != __version__:
        #            CONF.set('main', 'current_version', __version__)
        # Execute here the actions to be performed only once after
        # each update (there is nothing there for now, but it could
        # be useful some day...

        self.start()

    def start(self, restart=False):
        '''
        Starts main process
        '''
        # Preferences
        self.general_prefs = [PathConfigPage]
        self.apply_settings()

        # Dockwidgets creation
        self.splash.showMessage(
            "Creating widgets...",
            Qt.AlignBottom | Qt.AlignCenter | Qt.AlignAbsolute,
            QColor(Qt.black))

        self.create_dockwidgets()
        self.populate_mainwidow()

        #################################################################
        ## Menu initialization
        #################################################################
        self.splash.showMessage(
            "Creating menubar...",
            Qt.AlignBottom | Qt.AlignCenter | Qt.AlignAbsolute,
            QColor(Qt.black))
        # Menu Fichier
        self.file_menu = self.menuBar().addMenu("Fichier")
        action_export_png = create_action(
            self, 'Exporter le graphique',
            icon='document-save png.png')  #, triggered = None)
        action_export_csv = create_action(
            self, 'Exporter la table',
            icon='document-save csv.png')  #, triggered = None)
        action_pref = create_action(self,
                                    u'Préférences',
                                    QKeySequence.Preferences,
                                    icon='preferences-desktop.png',
                                    triggered=self.edit_preferences)
        action_quit = create_action(self,
                                    'Quitter',
                                    QKeySequence.Quit,
                                    icon='process-stop.png',
                                    triggered=SLOT('close()'))

        file_actions = [
            action_export_png, action_export_csv, None, action_pref, None,
            action_quit
        ]
        add_actions(self.file_menu, file_actions)

        # Menu Edit
        self.edit_menu = self.menuBar().addMenu(u"Édition")
        action_copy = create_action(self,
                                    'Copier',
                                    QKeySequence.Copy,
                                    triggered=self.global_callback,
                                    data='copy')

        edit_actions = [None, action_copy]
        add_actions(self.edit_menu, edit_actions)

        # Menu Projection
        self.projection_menu = self.menuBar().addMenu(u"Projection")
        #
        self.action_refresh_project_population = create_action(
            self,
            u'Calculer les projections de population',
            shortcut='F9',
            icon='calculator_green.png',
            triggered=self.project_population)

        projection_actions = [self.action_refresh_project_population, None]
        add_actions(self.projection_menu, projection_actions)

        # Menu Help
        help_menu = self.menuBar().addMenu("&Aide")
        action_about = create_action(self,
                                     u"&About GA",
                                     triggered=self.helpAbout)
        action_help = create_action(self,
                                    "&Aide",
                                    QKeySequence.HelpContents,
                                    triggered=self.helpHelp)
        help_actions = [action_about, action_help]
        add_actions(help_menu, help_actions)

        # Display Menu
        view_menu = self.createPopupMenu()
        view_menu.setTitle("&Affichage")
        self.menuBar().insertMenu(help_menu.menuAction(), view_menu)

        # Toolbar
        self.main_toolbar = self.create_toolbar(u"Barre d'outil",
                                                'main_toolbar')
        toolbar_actions = [
            action_export_png,
            action_export_csv,
            None,
            self.action_refresh_project_population,
        ]
        add_actions(self.main_toolbar, toolbar_actions)

        # Window settings
        self.splash.showMessage(
            "Restoring settings...",
            Qt.AlignBottom | Qt.AlignCenter | Qt.AlignAbsolute,
            QColor(Qt.black))
        settings = QSettings()
        size = settings.value('MainWindow/Size',
                              QVariant(QSize(800, 600))).toSize()
        self.resize(size)
        position = settings.value('MainWindow/Position',
                                  QVariant(QPoint(0, 0))).toPoint()
        self.move(position)
        self.restoreState(settings.value("MainWindow/State").toByteArray())

        # Connectors

        self.connect(self._param_widget, SIGNAL('population_changed()'),
                     self.refresh_population)
        #        self.connect(self._param_widget, SIGNAL('rates_changed()'), self.refresh_cohorts)
        self.connect(self._param_widget, SIGNAL('state_proj_changed()'),
                     self.refresh_cohorts)

        self.refresh_population()
        self.load_data()

        self.splash.showMessage(
            "Loading survey data...",
            Qt.AlignBottom | Qt.AlignCenter | Qt.AlignAbsolute,
            QColor(Qt.black))
        self.splash.hide()
        return

    def create_toolbar(self, title, object_name, iconsize=24):
        toolbar = self.addToolBar(title)
        toolbar.setObjectName(object_name)
        toolbar.setIconSize(QSize(iconsize, iconsize))
        return toolbar

    def create_dockwidgets(self):
        '''
        Creates dockwidgets
        '''
        self._population_widget = PopulationDataWidget(self)
        self._cohorts_widget = PopulationDataWidget(self)
        self._profiles_widget = ProfilesDataWidget(self)
        self._param_widget = ParametersWidget(self)
        self._plot_widget = PlotWidget(self)

        # TODO
        # plot population pyramides/expenses pyramides
        # générational flow

    def populate_mainwidow(self):
        '''
        Creates all dockwidgets
        '''
        left_widgets = [
            self._profiles_widget, self._population_widget,
            self._cohorts_widget, self._plot_widget
        ]
        first_left_widget = None
        for widget in left_widgets:
            self.addDockWidget(Qt.LeftDockWidgetArea, widget)
            if first_left_widget is None:
                first_left_widget = widget
            else:
                self.tabifyDockWidget(first_left_widget, widget)

    def global_callback(self):
        """Global callback"""
        widget = QApplication.focusWidget()
        action = self.sender()
        callback = unicode(action.data().toString())
        if hasattr(widget, callback):
            getattr(widget, callback)()

    def load_data(self):
        '''
        Loads population and profiles data 
        '''
        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
        try:
            profiles_file = CONF.get('paths', 'profiles_file')
            store = HDFStore(profiles_file, 'r')
            profiles = store['profiles']

        except Exception, e:
            self.population_loaded = False
            QMessageBox.warning(
                self, u"Impossible de lire les données de population",
                u"GA n'a pas réussi à lire les données de population. L'erreur suivante a été renvoyée:\n%s\n\nVous pouvez configuer le chemin vers le fichier de données  Fichier>Paramètres>Chemins>Fichier données population"
                % e)
            return False
        finally:
Ejemplo n.º 4
0
class MainWindow(QMainWindow):
    def __init__(self, parent = None):
        super(MainWindow, self).__init__(parent)
        self.dirty = False
        self.isLoaded = False
        self.calibration_enabled = False
        self.aggregate_enabled = False

        self.setObjectName("MainWindow")
        self.resize(800, 600)
        self.setWindowTitle("OpenFisca")
        app_icon = get_icon('OpenFisca22.png')
        self.setWindowIcon(app_icon)
        self.setLocale(QLocale(QLocale.French, QLocale.France))
        self.setDockOptions(QMainWindow.AllowNestedDocks|QMainWindow.AllowTabbedDocks|QMainWindow.AnimatedDocks)

        self.centralwidget = QWidget(self)
        self.gridLayout = QGridLayout(self.centralwidget)
        self.setCentralWidget(self.centralwidget)
        self.centralwidget.hide()

        self.statusbar = QStatusBar(self)
        self.statusbar.setObjectName("statusbar")
        self.setStatusBar(self.statusbar)

        # Showing splash screen
        pixmap = QPixmap(':/images/splash.png', 'png')
        self.splash = QSplashScreen(pixmap)
        font = self.splash.font()
        font.setPixelSize(10)
        self.splash.setFont(font)
        self.splash.show()
        self.splash.showMessage("Initialisation...", Qt.AlignBottom | Qt.AlignCenter | 
                                Qt.AlignAbsolute, QColor(Qt.black))
#        if CONF.get('main', 'current_version', '') != __version__:
#            CONF.set('main', 'current_version', __version__)
            # Execute here the actions to be performed only once after
            # each update (there is nothing there for now, but it could 
            # be useful some day...
        
        self.scenario = Scenario()
        # Preferences
        self.general_prefs = [SimConfigPage, PathConfigPage, CalConfigPage]
        self.oldXAXIS = 'sal'
        self.reforme = False
        self.apply_settings()
        
        # Dockwidgets creation
        self.splash.showMessage("Creating widgets...", Qt.AlignBottom | Qt.AlignCenter | 
                                Qt.AlignAbsolute, QColor(Qt.black))

        self.create_dockwidgets()
        self.populate_mainwidow()

        #################################################################
        ## Menu initialization
        #################################################################
        self.splash.showMessage("Creating menubar...", Qt.AlignBottom | Qt.AlignCenter | 
                                Qt.AlignAbsolute, QColor(Qt.black))
        # Menu Fichier
        self.file_menu = self.menuBar().addMenu("Fichier")
        action_export_png = create_action(self, 'Exporter le graphique', icon = 'document-save png.png', triggered = self._graph.save_figure)
        action_export_csv = create_action(self, 'Exporter la table', icon = 'document-save csv.png', triggered = self._table.saveCsv)
        action_pref = create_action(self, u'Préférences', QKeySequence.Preferences, icon = 'preferences-desktop.png', triggered = self.edit_preferences)
        action_quit = create_action(self, 'Quitter', QKeySequence.Quit, icon = 'process-stop.png',  triggered = SLOT('close()'))
        
        file_actions = [action_export_png, action_export_csv,None, action_pref, None, action_quit]
        add_actions(self.file_menu, file_actions)

        # Menu Edit
        self.edit_menu = self.menuBar().addMenu(u"Édition")
        action_copy = create_action(self, 'Copier', QKeySequence.Copy, triggered = self.global_callback, data = 'copy')
        
        edit_actions = [None, action_copy]
        add_actions(self.edit_menu, edit_actions)

        # Menu Simulation
        self.simulation_menu = self.menuBar().addMenu(u"Simulation")
        self.action_refresh_bareme      = create_action(self, u'Calculer barèmes', shortcut = 'F8', icon = 'view-refresh.png', triggered = self.refresh_bareme)
        self.action_refresh_calibration = create_action(self, u'Calibrer', shortcut = 'F9', icon = 'view-refresh.png', triggered = self.refresh_calibration)
        self.action_refresh_aggregate   = create_action(self, u'Calculer aggrégats', shortcut = 'F10', icon = 'view-refresh.png', triggered = self.refresh_aggregate)
        action_bareme = create_action(self, u'Barème', icon = 'bareme22.png', toggled = self.modeBareme)
        action_cas_type = create_action(self, u'Cas type', icon = 'castype22.png', toggled = self.modeCasType)
        action_mode_reforme = create_action(self, u'Réforme', icon = 'comparison22.png', toggled = self.modeReforme, tip = u"Différence entre la situation simulée et la situation actuelle")
        mode_group = QActionGroup(self)
        mode_group.addAction(action_bareme)
        mode_group.addAction(action_cas_type)
        self.mode = 'bareme'
        action_bareme.trigger()

        simulation_actions = [self.action_refresh_bareme, self.action_refresh_calibration, self.action_refresh_aggregate , None, action_bareme, action_cas_type, None, action_mode_reforme]
        add_actions(self.simulation_menu, simulation_actions)
        
        # Menu Help
        help_menu = self.menuBar().addMenu("&Aide")
        action_about = create_action(self, u"&About OpenFisca", triggered = self.helpAbout)
        action_help = create_action(self, "&Aide", QKeySequence.HelpContents, triggered = self.helpHelp)
        help_actions = [action_about, action_help]
        add_actions(help_menu, help_actions)
                
        # Display Menu
        view_menu = self.createPopupMenu()
        view_menu.setTitle("&Affichage")
        self.menuBar().insertMenu(help_menu.menuAction(),
                                  view_menu)
        
        # Toolbar
        self.main_toolbar = self.create_toolbar(u"Barre d'outil", 'main_toolbar')
        toolbar_actions = [action_export_png, action_export_csv, None, self.action_refresh_bareme,
                           self.action_refresh_calibration, self.action_refresh_aggregate, None,
                            action_bareme, action_cas_type, None, action_mode_reforme]
        add_actions(self.main_toolbar, toolbar_actions)


        self.connect(self._menage,     SIGNAL('changed()'), self.changed_bareme)
        self.connect(self._parametres, SIGNAL('changed()'), self.changed_param)
        self.connect(self._aggregate_output, SIGNAL('calculated()'), self.calculated)
        self.connect(self._calibration, SIGNAL('param_or_margins_changed()'), self.param_or_margins_changed)
        self.connect(self._calibration, SIGNAL('calibrated()'), self.calibrated)
        
        # Window settings
        self.splash.showMessage("Restoring settings...", Qt.AlignBottom | Qt.AlignCenter | 
                                Qt.AlignAbsolute, QColor(Qt.black))
        settings = QSettings()
        size = settings.value('MainWindow/Size', QVariant(QSize(800,600))).toSize()
        self.resize(size)
        position = settings.value('MainWindow/Position', QVariant(QPoint(0,0))).toPoint()
        self.move(position)
        self.restoreState(settings.value("MainWindow/State").toByteArray())



        self.splash.showMessage("Loading survey data...", Qt.AlignBottom | Qt.AlignCenter | 
                                Qt.AlignAbsolute, QColor(Qt.black))
        
        self.enable_aggregate(True)
        self.enable_calibration(True)
        
        self.refresh_bareme()
        
        self.isLoaded = True
        self.splash.hide()

    def create_toolbar(self, title, object_name, iconsize=24):
        toolbar = self.addToolBar(title)
        toolbar.setObjectName(object_name)
        toolbar.setIconSize( QSize(iconsize, iconsize) )
        return toolbar

    def create_dockwidgets(self):
        # Création des dockwidgets
        self._parametres = ParamWidget('data/param.xml', self)
        self._menage = ScenarioWidget(self.scenario, self)
        self._graph = Graph(self)
        self._table = OutTable(self)
        self._aggregate_output = AggregateOutputWidget(self)
        self._calibration = CalibrationWidget(self)
        self._dataframe_widget = DataFrameDock(self)
        
    def populate_mainwidow(self):
        self.addDockWidget(Qt.RightDockWidgetArea, self._parametres)
        self.addDockWidget(Qt.RightDockWidgetArea, self._menage)
        self.addDockWidget(Qt.LeftDockWidgetArea, self._graph)
        self.addDockWidget(Qt.LeftDockWidgetArea, self._table)
        self.addDockWidget(Qt.LeftDockWidgetArea, self._aggregate_output)
        self.addDockWidget(Qt.LeftDockWidgetArea, self._calibration)
        self.addDockWidget(Qt.LeftDockWidgetArea, self._dataframe_widget)
        self.tabifyDockWidget(self._dataframe_widget, self._aggregate_output)
        self.tabifyDockWidget(self._aggregate_output, self._calibration)
        self.tabifyDockWidget(self._calibration, self._table)
        self.tabifyDockWidget(self._table, self._graph)
        

    def global_callback(self):
        """Global callback"""
        widget = QApplication.focusWidget()
        action = self.sender()
        callback = unicode(action.data().toString())
        if hasattr(widget, callback):
            getattr(widget, callback)()


    def load_survey_data(self):
        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
        try:
            # liberate some memory before loading new data
            self.reset_aggregate()
            gc.collect()
            fname = CONF.get('paths', 'survey_data_file')
            self.survey = DataTable(InputTable, survey_data = fname)
            self._dataframe_widget.set_dataframe(self.survey.table)
            return True
        except Exception, e:
            self.aggregate_enabled = False
            QMessageBox.warning(self, u"Impossible de lire les données", 
                                u"OpenFisca n'a pas réussi à lire les données d'enquête et passe en mode barème. L'erreur suivante a été renvoyé:\n%s\n\nVous pouvez charger des nouvelles données d'enquête dans Fichier>Paramètres>Chemins>Données d'enquête"%e)
            return False
        finally:
Ejemplo n.º 5
0
class MainWindow(QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.dirty = False
        self.isLoaded = False
        self.calibration_enabled = False
        self.aggregate_enabled = False

        self.setObjectName("MainWindow")
        self.resize(800, 600)
        self.setWindowTitle("OpenFisca")
        app_icon = get_icon('OpenFisca22.png')
        self.setWindowIcon(app_icon)
        self.setLocale(QLocale(QLocale.French, QLocale.France))
        self.setDockOptions(QMainWindow.AllowNestedDocks
                            | QMainWindow.AllowTabbedDocks
                            | QMainWindow.AnimatedDocks)

        self.centralwidget = QWidget(self)
        self.gridLayout = QGridLayout(self.centralwidget)
        self.setCentralWidget(self.centralwidget)
        self.centralwidget.hide()

        self.statusbar = QStatusBar(self)
        self.statusbar.setObjectName("statusbar")
        self.setStatusBar(self.statusbar)

        # Showing splash screen
        pixmap = QPixmap(':/images/splash.png', 'png')
        self.splash = QSplashScreen(pixmap)
        font = self.splash.font()
        font.setPixelSize(10)
        self.splash.setFont(font)
        self.splash.show()
        self.splash.showMessage(
            "Initialisation...",
            Qt.AlignBottom | Qt.AlignCenter | Qt.AlignAbsolute,
            QColor(Qt.black))
        #        if CONF.get('main', 'current_version', '') != __version__:
        #            CONF.set('main', 'current_version', __version__)
        # Execute here the actions to be performed only once after
        # each update (there is nothing there for now, but it could
        # be useful some day...

        self.scenario = Scenario()
        # Preferences
        self.general_prefs = [SimConfigPage, PathConfigPage, CalConfigPage]
        self.oldXAXIS = 'sal'
        self.reforme = False
        self.apply_settings()

        # Dockwidgets creation
        self.splash.showMessage(
            "Creating widgets...",
            Qt.AlignBottom | Qt.AlignCenter | Qt.AlignAbsolute,
            QColor(Qt.black))

        self.create_dockwidgets()
        self.populate_mainwidow()

        #################################################################
        ## Menu initialization
        #################################################################
        self.splash.showMessage(
            "Creating menubar...",
            Qt.AlignBottom | Qt.AlignCenter | Qt.AlignAbsolute,
            QColor(Qt.black))
        # Menu Fichier
        self.file_menu = self.menuBar().addMenu("Fichier")
        action_export_png = create_action(self,
                                          'Exporter le graphique',
                                          icon='document-save png.png',
                                          triggered=self._graph.save_figure)
        action_export_csv = create_action(self,
                                          'Exporter la table',
                                          icon='document-save csv.png',
                                          triggered=self._table.saveCsv)
        action_pref = create_action(self,
                                    u'Préférences',
                                    QKeySequence.Preferences,
                                    icon='preferences-desktop.png',
                                    triggered=self.edit_preferences)
        action_quit = create_action(self,
                                    'Quitter',
                                    QKeySequence.Quit,
                                    icon='process-stop.png',
                                    triggered=SLOT('close()'))

        file_actions = [
            action_export_png, action_export_csv, None, action_pref, None,
            action_quit
        ]
        add_actions(self.file_menu, file_actions)

        # Menu Edit
        self.edit_menu = self.menuBar().addMenu(u"Édition")
        action_copy = create_action(self,
                                    'Copier',
                                    QKeySequence.Copy,
                                    triggered=self.global_callback,
                                    data='copy')

        edit_actions = [None, action_copy]
        add_actions(self.edit_menu, edit_actions)

        # Menu Simulation
        self.simulation_menu = self.menuBar().addMenu(u"Simulation")

        self.action_refresh_bareme = create_action(
            self,
            u'Calculer barèmes',
            shortcut='F9',
            icon='calculator_green.png',
            triggered=self.refresh_bareme)
        self.action_refresh_aggregate = create_action(
            self,
            u'Calculer aggrégats',
            shortcut='F10',
            icon='calculator_blue.png',
            triggered=self.refresh_aggregate)

        self.action_calibrate = create_action(self,
                                              u'Caler les poids',
                                              shortcut='CTRL+K',
                                              icon='scale22.png',
                                              triggered=self.calibrate)

        action_bareme = create_action(self,
                                      u'Barème',
                                      icon='bareme22.png',
                                      toggled=self.modeBareme)
        action_cas_type = create_action(self,
                                        u'Cas type',
                                        icon='castype22.png',
                                        toggled=self.modeCasType)
        action_mode_reforme = create_action(
            self,
            u'Réforme',
            icon='comparison22.png',
            toggled=self.modeReforme,
            tip=
            u"Différence entre la situation simulée et la situation actuelle")
        mode_group = QActionGroup(self)
        mode_group.addAction(action_bareme)
        mode_group.addAction(action_cas_type)
        self.mode = 'bareme'
        action_bareme.trigger()

        simulation_actions = [
            self.action_refresh_bareme, self.action_refresh_aggregate, None,
            self.action_calibrate, None, action_bareme, action_cas_type, None,
            action_mode_reforme
        ]
        add_actions(self.simulation_menu, simulation_actions)

        # Menu Help
        help_menu = self.menuBar().addMenu("&Aide")
        action_about = create_action(self,
                                     u"&About OpenFisca",
                                     triggered=self.helpAbout)
        action_help = create_action(self,
                                    "&Aide",
                                    QKeySequence.HelpContents,
                                    triggered=self.helpHelp)
        help_actions = [action_about, action_help]
        add_actions(help_menu, help_actions)

        # Display Menu
        view_menu = self.createPopupMenu()
        view_menu.setTitle("&Affichage")
        self.menuBar().insertMenu(help_menu.menuAction(), view_menu)

        # Toolbar
        self.main_toolbar = self.create_toolbar(u"Barre d'outil",
                                                'main_toolbar')
        toolbar_actions = [
            action_export_png, action_export_csv, None,
            self.action_refresh_bareme, self.action_refresh_aggregate, None,
            self.action_calibrate, None, action_bareme, action_cas_type, None,
            action_mode_reforme
        ]
        add_actions(self.main_toolbar, toolbar_actions)

        self.connect(self._menage, SIGNAL('changed()'), self.changed_bareme)
        self.connect(self._parametres, SIGNAL('changed()'), self.changed_param)
        self.connect(self._aggregate_output, SIGNAL('calculated()'),
                     self.calculated)
        self.connect(self, SIGNAL('weights_changed()'), self.refresh_aggregate)
        self.connect(self, SIGNAL('bareme_only()'), self.switch_bareme_only)

        # Window settings
        self.splash.showMessage(
            "Restoring settings...",
            Qt.AlignBottom | Qt.AlignCenter | Qt.AlignAbsolute,
            QColor(Qt.black))
        settings = QSettings()
        size = settings.value('MainWindow/Size',
                              QVariant(QSize(800, 600))).toSize()
        self.resize(size)
        position = settings.value('MainWindow/Position',
                                  QVariant(QPoint(0, 0))).toPoint()
        self.move(position)
        self.restoreState(settings.value("MainWindow/State").toByteArray())

        self.splash.showMessage(
            "Loading survey data...",
            Qt.AlignBottom | Qt.AlignCenter | Qt.AlignAbsolute,
            QColor(Qt.black))

        self.enable_aggregate(True)

        self.refresh_bareme()

        self.isLoaded = True
        self.splash.hide()

    def create_toolbar(self, title, object_name, iconsize=24):
        toolbar = self.addToolBar(title)
        toolbar.setObjectName(object_name)
        toolbar.setIconSize(QSize(iconsize, iconsize))
        return toolbar

    def create_dockwidgets(self):
        # Création des dockwidgets
        self._parametres = ParamWidget('data/param.xml', self)
        self._menage = ScenarioWidget(self.scenario, self)
        self._graph = Graph(self)
        self._table = OutTable(self)
        self._aggregate_output = AggregateOutputWidget(self)
        self._dataframe_widget = ExploreDataWidget(self)

    def populate_mainwidow(self):
        '''
        Creates all dockwidgets
        '''
        self.addDockWidget(Qt.RightDockWidgetArea, self._parametres)
        self.addDockWidget(Qt.RightDockWidgetArea, self._menage)
        self.addDockWidget(Qt.LeftDockWidgetArea, self._graph)
        self.addDockWidget(Qt.LeftDockWidgetArea, self._table)
        self.addDockWidget(Qt.LeftDockWidgetArea, self._aggregate_output)
        self.addDockWidget(Qt.LeftDockWidgetArea, self._dataframe_widget)
        self.tabifyDockWidget(self._dataframe_widget, self._aggregate_output)
        self.tabifyDockWidget(self._aggregate_output, self._table)
        self.tabifyDockWidget(self._table, self._graph)

    def global_callback(self):
        """Global callback"""
        widget = QApplication.focusWidget()
        action = self.sender()
        callback = unicode(action.data().toString())
        if hasattr(widget, callback):
            getattr(widget, callback)()

    def load_survey_data(self):
        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
        try:
            # liberate some memory before loading new data
            self.reset_aggregate()
            gc.collect()
            fname = CONF.get('paths', 'survey_data/file')
            self.survey = DataTable(InputTable, survey_data=fname)
            self._dataframe_widget.set_dataframe(self.survey.table)
            return True
        except Exception, e:
            self.aggregate_enabled = False
            QMessageBox.warning(
                self, u"Impossible de lire les données",
                u"OpenFisca n'a pas réussi à lire les données d'enquête et passe en mode barème. L'erreur suivante a été renvoyé:\n%s\n\nVous pouvez charger des nouvelles données d'enquête dans Fichier>Paramètres>Chemins>Données d'enquête"
                % e)
            self.emit(SIGNAL('baremeOnly()'))
            return False
        finally:
Ejemplo n.º 6
0
class ViewerWnd(QMainWindow):
    def __init__(self, app, dictOpts):
        QMainWindow.__init__(self)
        self.setWindowTitle("PostGIS Layer Viewer - v.1.6.1")
        self.setTabPosition(Qt.BottomDockWidgetArea, QTabWidget.North)

        self.canvas = QgsMapCanvas()
        self.canvas.setCanvasColor(Qt.white)
        self.canvas.useImageToRender(True)
        self.canvas.enableAntiAliasing(True)
        self.setCentralWidget(self.canvas)

        actionZoomIn = QAction(QIcon(imgs_dir + "mActionZoomIn.png"),
                               QString("Zoom in"), self)
        actionZoomOut = QAction(QIcon(imgs_dir + "mActionZoomOut.png"),
                                QString("Zoom out"), self)
        actionPan = QAction(QIcon(imgs_dir + "mActionPan.png"), QString("Pan"),
                            self)
        actionZoomFullExtent = QAction(
            QIcon(imgs_dir + "mActionZoomFullExtent.png"),
            QString("Zoom full"), self)

        actionZoomIn.setCheckable(True)
        actionZoomOut.setCheckable(True)
        actionPan.setCheckable(True)

        self.connect(actionZoomIn, SIGNAL("triggered()"), self.zoomIn)
        self.connect(actionZoomOut, SIGNAL("triggered()"), self.zoomOut)
        self.connect(actionPan, SIGNAL("triggered()"), self.pan)
        self.connect(actionZoomFullExtent, SIGNAL("triggered()"),
                     self.zoomFullExtent)

        self.actionGroup = QActionGroup(self)
        self.actionGroup.addAction(actionPan)
        self.actionGroup.addAction(actionZoomIn)
        self.actionGroup.addAction(actionZoomOut)

        # Create the toolbar
        self.toolbar = self.addToolBar("Map tools")
        self.toolbar.addAction(actionPan)
        self.toolbar.addAction(actionZoomIn)
        self.toolbar.addAction(actionZoomOut)
        self.toolbar.addAction(actionZoomFullExtent)

        # Create the map tools
        self.toolPan = QgsMapToolPan(self.canvas)
        self.toolPan.setAction(actionPan)
        self.toolZoomIn = QgsMapToolZoom(self.canvas, False)  # false = in
        self.toolZoomIn.setAction(actionZoomIn)
        self.toolZoomOut = QgsMapToolZoom(self.canvas, True)  # true = out
        self.toolZoomOut.setAction(actionZoomOut)

        # Create the statusbar
        self.statusbar = QStatusBar(self)
        self.statusbar.setObjectName("statusbar")
        self.setStatusBar(self.statusbar)

        self.lblXY = QLabel()
        self.lblXY.setFrameStyle(QFrame.Box)
        self.lblXY.setMinimumWidth(170)
        self.lblXY.setAlignment(Qt.AlignCenter)
        self.statusbar.setSizeGripEnabled(False)
        self.statusbar.addPermanentWidget(self.lblXY, 0)

        self.lblScale = QLabel()
        self.lblScale.setFrameStyle(QFrame.StyledPanel)
        self.lblScale.setMinimumWidth(140)
        self.statusbar.addPermanentWidget(self.lblScale, 0)

        self.createLegendWidget()  # Create the legend widget

        self.connect(app, SIGNAL("loadPgLayer"), self.loadLayer)
        self.connect(self.canvas, SIGNAL("scaleChanged(double)"),
                     self.changeScale)
        self.connect(self.canvas, SIGNAL("xyCoordinates(const QgsPoint&)"),
                     self.updateXY)

        self.pan()  # Default

        self.plugins = Plugins(self, self.canvas, dictOpts['-h'],
                               dictOpts['-p'], dictOpts['-d'], dictOpts['-U'],
                               dictOpts['-W'])

        self.createAboutWidget()
        self.layerSRID = '-1'
        self.loadLayer(dictOpts)

    def zoomIn(self):
        self.canvas.setMapTool(self.toolZoomIn)

    def zoomOut(self):
        self.canvas.setMapTool(self.toolZoomOut)

    def pan(self):
        self.canvas.setMapTool(self.toolPan)

    def zoomFullExtent(self):
        self.canvas.zoomToFullExtent()

    def about(self):
        pass

    def createLegendWidget(self):
        """ Create the map legend widget and associate it to the canvas """
        self.legend = Legend(self)
        self.legend.setCanvas(self.canvas)
        self.legend.setObjectName("theMapLegend")

        self.LegendDock = QDockWidget("Layers", self)
        self.LegendDock.setObjectName("legend")
        self.LegendDock.setTitleBarWidget(QWidget())
        self.LegendDock.setWidget(self.legend)
        self.LegendDock.setContentsMargins(0, 0, 0, 0)
        self.addDockWidget(Qt.BottomDockWidgetArea, self.LegendDock)

    def createAboutWidget(self):
        self.AboutDock = QDockWidget("About", self)
        self.AboutDock.setObjectName("about")
        self.AboutDock.setTitleBarWidget(QWidget())
        self.AboutDock.setContentsMargins(0, 0, 0, 0)
        self.tabifyDockWidget(self.LegendDock, self.AboutDock)
        self.LegendDock.raise_()  # legendDock at the top

        from PyQt4.QtCore import QRect
        from PyQt4.QtGui import QSizePolicy, QGridLayout, QFont
        font = QFont()
        font.setFamily("Sans Serif")
        font.setPointSize(8.7)
        self.AboutWidget = QWidget()
        self.AboutWidget.setFont(font)
        self.AboutWidget.setObjectName("AboutWidget")
        self.AboutDock.setWidget(self.AboutWidget)
        self.labelAbout = QLabel(self.AboutWidget)
        self.labelAbout.setAlignment(Qt.AlignCenter)
        self.labelAbout.setWordWrap(True)
        self.gridLayout = QGridLayout(self.AboutWidget)
        self.gridLayout.setContentsMargins(0, 0, 0, 0)
        self.gridLayout.setObjectName("gridLayout")
        self.gridLayout.addWidget(self.labelAbout, 0, 1, 1, 1)
        self.labelAbout.setTextInteractionFlags(Qt.LinksAccessibleByMouse
                                                | Qt.LinksAccessibleByKeyboard
                                                | Qt.TextSelectableByKeyboard
                                                | Qt.TextSelectableByMouse)
        self.labelAbout.setOpenExternalLinks(True)
        self.labelAbout.setText("<html><head/><body><a href=\"http://geotux.tuxfamily.org/index.php/en/geo-blogs/item/293-consola-sql-para-plugin-pgadmin-postgis-viewer\">PostGIS Layer Viewer</a> v.1.6.1 (2015.02.24)<br \><br \>" \
            "Copyright (c) 2010 Ivan Mincik,<br \>[email protected]<br \>" \
            u"Copyright (c) 2011-2015 Germán Carrillo,<br \>[email protected]<br \><br \>" \
            "<i>Licensed under the terms of GNU GPL v.2.0</i><br \><br \>" \
            "Based on PyQGIS. Plugin Fast SQL Layer by Pablo T. Carreira.</body></html>" )

    def loadLayer(self, dictOpts):
        print 'I: Loading the layer...'
        self.layerSRID = dictOpts[
            'srid']  # To access the SRID when querying layer properties

        if not self.isActiveWindow():
            self.activateWindow()
            self.raise_()

        if dictOpts['type'] == 'vector':
            # QGIS connection
            uri = QgsDataSourceURI()
            uri.setConnection(dictOpts['-h'], dictOpts['-p'], dictOpts['-d'],
                              dictOpts['-U'], dictOpts['-W'])
            uri.setDataSource(dictOpts['-s'], dictOpts['-t'], dictOpts['-g'])
            layer = QgsVectorLayer(uri.uri(),
                                   dictOpts['-s'] + '.' + dictOpts['-t'],
                                   "postgres")
        elif dictOpts['type'] == 'raster':
            connString = "PG: dbname=%s host=%s user=%s password=%s port=%s mode=2 " \
                "schema=%s column=%s table=%s" % ( dictOpts['-d'], dictOpts['-h'],
                dictOpts['-U'], dictOpts['-W'], dictOpts['-p'], dictOpts['-s'],
                dictOpts['col'], dictOpts['-t'] )
            layer = QgsRasterLayer(connString,
                                   dictOpts['-s'] + '.' + dictOpts['-t'])

            if layer.isValid():
                layer.setContrastEnhancement(
                    QgsContrastEnhancement.StretchToMinimumMaximum)

        self.addLayer(layer, self.layerSRID)

    def addLayer(self, layer, srid='-1'):
        if layer.isValid():
            # Only in case that srid != -1, read the layer SRS properties, otherwise don't since it will return 4326
            if srid != '-1':
                self.layerSRID = layer.crs().description() + ' (' + str(
                    layer.crs().postgisSrid()) + ')'
            else:
                self.layerSRID = 'Unknown SRS (-1)'

            if self.canvas.layerCount() == 0:
                self.canvas.setExtent(layer.extent())

                if srid != '-1':
                    print 'I: Map SRS (EPSG): %s' % self.layerSRID
                    self.canvas.setMapUnits(layer.crs().mapUnits())
                else:
                    print 'I: Unknown Reference System'
                    self.canvas.setMapUnits(0)  # 0: QGis.Meters

            return QgsMapLayerRegistry.instance().addMapLayer(layer)
        return False

    def activeLayer(self):
        """ Returns the active layer in the layer list widget """
        return self.legend.activeLayer()

    def getLayerProperties(self, l):
        """ Create a layer-properties string (l:layer)"""
        print 'I: Generating layer properties...'
        if l.type() == 0:  # Vector
            wkbType = [
                "WKBUnknown", "WKBPoint", "WKBLineString", "WKBPolygon",
                "WKBMultiPoint", "WKBMultiLineString", "WKBMultiPolygon",
                "WKBNoGeometry", "WKBPoint25D", "WKBLineString25D",
                "WKBPolygon25D", "WKBMultiPoint25D", "WKBMultiLineString25D",
                "WKBMultiPolygon25D"
            ]
            properties = "Source: %s\n" \
                         "Geometry type: %s\n" \
                         "Number of features: %s\n" \
                         "Number of fields: %s\n" \
                         "SRS (EPSG): %s\n" \
                         "Extent: %s " \
                          % ( l.source(), wkbType[l.wkbType()], l.featureCount(),
                              l.dataProvider().fields().count(), self.layerSRID,
                              l.extent().toString() )
        elif l.type() == 1:  # Raster
            rType = [
                "GrayOrUndefined (single band)", "Palette (single band)",
                "Multiband", "ColorLayer"
            ]
            properties = "Source: %s\n" \
                         "Raster type: %s\n" \
                         "Width-Height (pixels): %sx%s\n" \
                         "Bands: %s\n" \
                         "SRS (EPSG): %s\n" \
                         "Extent: %s" \
                         % ( l.source(), rType[l.rasterType()], l.width(), l.height(),
                             l.bandCount(), self.layerSRID, l.extent().toString() )

        self.layerSRID = '-1'  # Initialize the srid
        return properties

    def changeScale(self, scale):
        self.lblScale.setText("Scale 1:" + formatNumber(scale))

    def updateXY(self, p):
        if self.canvas.mapUnits() == 2:  # Degrees
            self.lblXY.setText( formatToDegrees( p.x() ) + " | " \
                + formatToDegrees( p.y() ) )
        else:  # Unidad lineal
            self.lblXY.setText( formatNumber( p.x() ) + " | " \
                + formatNumber( p.y() ) + "" )
class ViewerWnd( QMainWindow ):
    def __init__( self, app, dictOpts ):
        QMainWindow.__init__( self )
        self.setWindowTitle( "PostGIS Layer Viewer - v.1.6.1" )
        self.setTabPosition( Qt.BottomDockWidgetArea, QTabWidget.North )

        self.canvas = QgsMapCanvas()
        self.canvas.setCanvasColor( Qt.white )
        self.canvas.useImageToRender( True )
        self.canvas.enableAntiAliasing( True )
        self.setCentralWidget( self.canvas )

        actionZoomIn = QAction( QIcon( imgs_dir + "mActionZoomIn.png" ), QString( "Zoom in" ), self )
        actionZoomOut = QAction( QIcon( imgs_dir + "mActionZoomOut.png" ), QString( "Zoom out" ), self )
        actionPan = QAction( QIcon( imgs_dir + "mActionPan.png" ), QString( "Pan" ), self )
        actionZoomFullExtent = QAction( QIcon( imgs_dir + "mActionZoomFullExtent.png" ), QString( "Zoom full" ), self )

        actionZoomIn.setCheckable( True )
        actionZoomOut.setCheckable( True )
        actionPan.setCheckable( True )

        self.connect(actionZoomIn, SIGNAL( "triggered()" ), self.zoomIn )
        self.connect(actionZoomOut, SIGNAL( "triggered()" ), self.zoomOut )
        self.connect(actionPan, SIGNAL( "triggered()" ), self.pan )
        self.connect(actionZoomFullExtent, SIGNAL( "triggered()" ), self.zoomFullExtent )

        self.actionGroup = QActionGroup( self )
        self.actionGroup.addAction( actionPan )
        self.actionGroup.addAction( actionZoomIn )
        self.actionGroup.addAction( actionZoomOut )        

        # Create the toolbar
        self.toolbar = self.addToolBar( "Map tools" )
        self.toolbar.addAction( actionPan )
        self.toolbar.addAction( actionZoomIn )
        self.toolbar.addAction( actionZoomOut )
        self.toolbar.addAction( actionZoomFullExtent )

        # Create the map tools
        self.toolPan = QgsMapToolPan( self.canvas )
        self.toolPan.setAction( actionPan )
        self.toolZoomIn = QgsMapToolZoom( self.canvas, False ) # false = in
        self.toolZoomIn.setAction( actionZoomIn )
        self.toolZoomOut = QgsMapToolZoom( self.canvas, True ) # true = out
        self.toolZoomOut.setAction( actionZoomOut )
        
        # Create the statusbar
        self.statusbar = QStatusBar( self )
        self.statusbar.setObjectName( "statusbar" )
        self.setStatusBar( self.statusbar )

        self.lblXY = QLabel()
        self.lblXY.setFrameStyle( QFrame.Box )
        self.lblXY.setMinimumWidth( 170 )
        self.lblXY.setAlignment( Qt.AlignCenter )
        self.statusbar.setSizeGripEnabled( False )
        self.statusbar.addPermanentWidget( self.lblXY, 0 )

        self.lblScale = QLabel()
        self.lblScale.setFrameStyle( QFrame.StyledPanel )
        self.lblScale.setMinimumWidth( 140 )
        self.statusbar.addPermanentWidget( self.lblScale, 0 )

        self.createLegendWidget()   # Create the legend widget

        self.connect( app, SIGNAL( "loadPgLayer" ), self.loadLayer )
        self.connect( self.canvas, SIGNAL( "scaleChanged(double)" ),
            self.changeScale )
        self.connect( self.canvas, SIGNAL( "xyCoordinates(const QgsPoint&)" ),
            self.updateXY )

        self.pan() # Default

        self.plugins = Plugins( self, self.canvas, dictOpts['-h'], dictOpts['-p'], dictOpts['-d'], dictOpts['-U'], dictOpts['-W'] )

        self.createAboutWidget()
        self.layerSRID = '-1'
        self.loadLayer( dictOpts )
    
    def zoomIn( self ):
        self.canvas.setMapTool( self.toolZoomIn )

    def zoomOut( self ):
        self.canvas.setMapTool( self.toolZoomOut )

    def pan( self ):
        self.canvas.setMapTool( self.toolPan )

    def zoomFullExtent( self ):
        self.canvas.zoomToFullExtent()
    
    def about( self ):
        pass

    def createLegendWidget( self ):
        """ Create the map legend widget and associate it to the canvas """
        self.legend = Legend( self )
        self.legend.setCanvas( self.canvas )
        self.legend.setObjectName( "theMapLegend" )

        self.LegendDock = QDockWidget( "Layers", self )
        self.LegendDock.setObjectName( "legend" )
        self.LegendDock.setTitleBarWidget( QWidget() )
        self.LegendDock.setWidget( self.legend )
        self.LegendDock.setContentsMargins ( 0, 0, 0, 0 )
        self.addDockWidget( Qt.BottomDockWidgetArea, self.LegendDock )

    def createAboutWidget( self ):
        self.AboutDock = QDockWidget( "About", self )
        self.AboutDock.setObjectName( "about" )
        self.AboutDock.setTitleBarWidget( QWidget() )
        self.AboutDock.setContentsMargins( 0, 0, 0, 0 )
        self.tabifyDockWidget( self.LegendDock, self.AboutDock )
        self.LegendDock.raise_() # legendDock at the top

        from PyQt4.QtCore import QRect
        from PyQt4.QtGui import QSizePolicy, QGridLayout, QFont
        font = QFont()
        font.setFamily("Sans Serif")
        font.setPointSize(8.7)
        self.AboutWidget = QWidget()
        self.AboutWidget.setFont( font )
        self.AboutWidget.setObjectName("AboutWidget") 
        self.AboutDock.setWidget( self.AboutWidget )
        self.labelAbout = QLabel( self.AboutWidget )
        self.labelAbout.setAlignment(Qt.AlignCenter)
        self.labelAbout.setWordWrap(True)
        self.gridLayout = QGridLayout(self.AboutWidget)
        self.gridLayout.setContentsMargins(0, 0, 0, 0)
        self.gridLayout.setObjectName("gridLayout")
        self.gridLayout.addWidget(self.labelAbout, 0, 1, 1, 1)
        self.labelAbout.setTextInteractionFlags(Qt.LinksAccessibleByMouse|Qt.LinksAccessibleByKeyboard|Qt.TextSelectableByKeyboard|Qt.TextSelectableByMouse) 
        self.labelAbout.setOpenExternalLinks( True )
        self.labelAbout.setText("<html><head/><body><a href=\"http://geotux.tuxfamily.org/index.php/en/geo-blogs/item/293-consola-sql-para-plugin-pgadmin-postgis-viewer\">PostGIS Layer Viewer</a> v.1.6.1 (2015.02.24)<br \><br \>" \
            "Copyright (c) 2010 Ivan Mincik,<br \>[email protected]<br \>" \
            u"Copyright (c) 2011-2015 Germán Carrillo,<br \>[email protected]<br \><br \>" \
            "<i>Licensed under the terms of GNU GPL v.2.0</i><br \><br \>" \
            "Based on PyQGIS. Plugin Fast SQL Layer by Pablo T. Carreira.</body></html>" )

    def loadLayer( self, dictOpts ):
        print 'I: Loading the layer...'
        self.layerSRID = dictOpts[ 'srid' ] # To access the SRID when querying layer properties

        if not self.isActiveWindow():
            self.activateWindow()            
            self.raise_() 

        if dictOpts['type'] == 'vector':
            # QGIS connection
            uri = QgsDataSourceURI()
            uri.setConnection( dictOpts['-h'], dictOpts['-p'], dictOpts['-d'], 
                dictOpts['-U'], dictOpts['-W'] )
            uri.setDataSource( dictOpts['-s'], dictOpts['-t'], dictOpts['-g'] )
            layer = QgsVectorLayer( uri.uri(), dictOpts['-s'] + '.' + dictOpts['-t'],
                "postgres" )        
        elif dictOpts['type'] == 'raster':          
            connString = "PG: dbname=%s host=%s user=%s password=%s port=%s mode=2 " \
                "schema=%s column=%s table=%s" % ( dictOpts['-d'], dictOpts['-h'], 
                dictOpts['-U'], dictOpts['-W'], dictOpts['-p'], dictOpts['-s'], 
                dictOpts['col'], dictOpts['-t'] )
            layer = QgsRasterLayer( connString, dictOpts['-s'] + '.' + dictOpts['-t'] )
            
            if layer.isValid():
                layer.setContrastEnhancement( QgsContrastEnhancement.StretchToMinimumMaximum )

        self.addLayer( layer, self.layerSRID )

    def addLayer( self, layer, srid='-1' ):
        if layer.isValid():
            # Only in case that srid != -1, read the layer SRS properties, otherwise don't since it will return 4326
            if srid != '-1': 
               self.layerSRID = layer.crs().description() + ' (' + str( layer.crs().postgisSrid() ) + ')'
            else:
               self.layerSRID = 'Unknown SRS (-1)'

            if self.canvas.layerCount() == 0:
                self.canvas.setExtent( layer.extent() )

                if srid != '-1':
                    print 'I: Map SRS (EPSG): %s' % self.layerSRID                    
                    self.canvas.setMapUnits( layer.crs().mapUnits() )
                else:
                    print 'I: Unknown Reference System'
                    self.canvas.setMapUnits( 0 ) # 0: QGis.Meters

            return QgsMapLayerRegistry.instance().addMapLayer( layer )
        return False

    def activeLayer( self ):
        """ Returns the active layer in the layer list widget """
        return self.legend.activeLayer()

    def getLayerProperties( self, l ):
        """ Create a layer-properties string (l:layer)"""
        print 'I: Generating layer properties...'
        if l.type() == 0: # Vector
            wkbType = ["WKBUnknown","WKBPoint","WKBLineString","WKBPolygon",
                       "WKBMultiPoint","WKBMultiLineString","WKBMultiPolygon",
                       "WKBNoGeometry","WKBPoint25D","WKBLineString25D","WKBPolygon25D",
                       "WKBMultiPoint25D","WKBMultiLineString25D","WKBMultiPolygon25D"]
            properties = "Source: %s\n" \
                         "Geometry type: %s\n" \
                         "Number of features: %s\n" \
                         "Number of fields: %s\n" \
                         "SRS (EPSG): %s\n" \
                         "Extent: %s " \
                          % ( l.source(), wkbType[l.wkbType()], l.featureCount(), 
                              l.dataProvider().fields().count(), self.layerSRID, 
                              l.extent().toString() )
        elif l.type() == 1: # Raster
            rType = [ "GrayOrUndefined (single band)", "Palette (single band)", "Multiband", "ColorLayer" ]
            properties = "Source: %s\n" \
                         "Raster type: %s\n" \
                         "Width-Height (pixels): %sx%s\n" \
                         "Bands: %s\n" \
                         "SRS (EPSG): %s\n" \
                         "Extent: %s" \
                         % ( l.source(), rType[l.rasterType()], l.width(), l.height(),
                             l.bandCount(), self.layerSRID, l.extent().toString() )

        self.layerSRID = '-1' # Initialize the srid 
        return properties

    def changeScale( self, scale ):
        self.lblScale.setText( "Scale 1:" + formatNumber( scale ) )

    def updateXY( self, p ):
        if self.canvas.mapUnits() == 2: # Degrees
            self.lblXY.setText( formatToDegrees( p.x() ) + " | " \
                + formatToDegrees( p.y() ) )
        else: # Unidad lineal
            self.lblXY.setText( formatNumber( p.x() ) + " | " \
                + formatNumber( p.y() ) + "" )
Ejemplo n.º 8
0
class MainWindow(QMainWindow):
   """ MainWindow(QMainWindow) This is the class/object for the main window 
       of the GUI application. This main window and GUI applicaiton are a Single
       Document Interface (SDI) Application. """

   # ---------------------------------------------------------------------------
   def __init__(self, parent = None):  
      """ MainWindow constructor  """         
   
      # Text messages for the class are set here 
      self.genericMsg = "WARNING -- Your changes have NOT been saved.\nAre you sure you want to %s\nand lose all of your changes?"
      self.quit_msg   = self.genericMsg %"exit the program"   
      self.new_msg    = self.genericMsg %"start a new file"   
      self.open_msg   = self.genericMsg %"open a new file"   
      self.close_msg  = self.genericMsg %"close this file"
      
      self.testcases       = [] # \
      self.testsuitefolder = "" #  \__ Start with a clean slate.
      
      # Read the confuration file data into the local class namespace as the
      # class will need this information.  
      try:
         self.configs = {}
         self.configs = configFile2dictionary(CONFIG_FILE)
         # print self.configs 
         if len(self.configs) == 0:
            raise Exception ("Failed to read configurations from \"%s\"" %CONFIG_FILE)
         self.configs['testcasefolder'] = os.path.join(MY_PATH, self.configs['testcasefolder'])
         self.configs['resultshome']  = os.path.join(MY_PATH, self.configs['resultshome'])
      except Exception as e:
         # TODO: SHow this as a message box as well
         print e
         print "Using default configurations"
         self.configs['testcasefolder'] = "/tmp/testcases"
         self.configs['resultshome']  = "/var/www/html/results"
        
      # Call to the Super Class for QT MainWindow
      super(MainWindow, self).__init__() # Don't ask, just do it.

      # Set up a way to write to the Console Area in from a separate thread. This 
      # allows for real-time output to the consoleArea.   
      self.consoleMessage   = pyqtSignal(str)
      self.connect(self, SIGNAL("self.consoleMessage"), self.updateConsole)
      
      # Set up a way to write to the Debug Area from a separate thread. This 
      # allows for real-time output to the consoleArea.   
      self.debugMessage   = pyqtSignal(str)
      self.connect(self, SIGNAL("self.debugMessage"), self.updateDebug)
            
      # Set up a way to write to the Results Area from a separate thread. This 
      # allows for real-time output to the resultsArea.   
      self.resultsMessage   = pyqtSignal(str)
      self.connect(self, SIGNAL("self.resultsMessage"), self.updateResults)      

      # The Steps for creating the main windows
      self.create_menubarActions()
      self.create_menubar()
      self.create_toolbarActions()
      self.create_toolbar()
      self.createWidgets()
      self.paint_mainWindow()
      self.setState(0) # This needs fixed, see setState()
     
   # ---------------------------------------------------------------------------   
   def create_menubarActions(self):
      # 
      # Create the menubar actions that will server as the link between 
      # menubar items and function calls. NOTE: Every 'triggered' argument 
      # must point to a valid function.  
      
      # File Menu Actions  - - - - - - - - - - - - - - - - - - - - - - - - - - - 
      self.mbExit   = QAction( "E&xit",    self, shortcut="Alt+E", statusTip="Exit the application",  triggered=self.cleanExit)       
      self.mbNew    = QAction( "N&ew",     self, shortcut="Alt+N", statusTip="Create a new file",     triggered=self.newFile)      
      self.mbOpen   = QAction( "O&pen",    self, shortcut="Alt+O", statusTip="Open an existing file", triggered=self.openFile)
      self.mbClose  = QAction( "C&lose",   self, shortcut="Alt+C", statusTip="Close a file",          triggered=self.closeFile)
      self.mbSave   = QAction( "S&ave",    self, shortcut="Alt+S", statusTip="Save the  file",        triggered=self.saveFile)
      self.mbSaveAs = QAction( "Save A&s", self, shortcut="Alt+A", statusTip="Save a file as",        triggered=self.saveAsFile)
      
      # Script Menu Actions  - - - - - - - - - - - - - - - - - - - - - - - - - - 
      self.mbRun   = QAction( "R&un",  self, shortcut="Alt+R", statusTip="Run the loaded file",       triggered=self.runScript)
      self.mbStop  = QAction( "S&top", self, shortcut="Alt+S", statusTip="Stop script execution ",    triggered=self.stopScript) 
      self.mbDebug = QAction( "D&ebug",self, shortcut="Alt+D", statusTip="Debug the loaded file",     triggered=self.debugScript)
      
      # Help Menu Actions   -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -
      self.mbHelp  = QAction( "H&elp",  self, shortcut="Alt+H", statusTip="Display help",             triggered=self.showHelp) 
      self.mbAbout = QAction( "A&bout", self, shortcut="Alt+A", statusTip="About This program",       triggered=self.showAbout)    
   
   
   # ---------------------------------------------------------------------------
   def create_toolbarActions(self):
      # Create the actions for the toolbar. Status tips and shortcut keys for 
      # the toolbar components are defined here. NOTE: Every 'triggered' 
      # connection must point to a valid function.   
      self.tbExit = QAction(QIcon(os.path.join(RESOURCE_PATH, 'Exit.png')), 'Exit', self)
      self.tbExit.setShortcut('Ctrl+Q')
      self.tbExit.setStatusTip('Exit application')
      self.tbExit.triggered.connect(self.cleanExit)
      
      self.tbNew = QAction(QIcon(os.path.join(RESOURCE_PATH, 'New.png')), 'New', self)
      self.tbNew.setShortcut('Ctrl+N')
      self.tbNew.setStatusTip('Start a new file')
      self.tbNew.triggered.connect(self.newFile)

      self.tbOpen = QAction(QIcon(os.path.join(RESOURCE_PATH, 'Open.png')), 'Open', self)
      self.tbOpen.setShortcut('Ctrl+O')
      self.tbOpen.setStatusTip('Open an existing file')
      self.tbOpen.triggered.connect(self.openFile)

      self.tbSave = QAction(QIcon(os.path.join(RESOURCE_PATH, 'Save.png')), 'Save', self)
      self.tbSave.setShortcut('Ctrl+S')
      self.tbSave.setStatusTip('Save to a file ')
      self.tbSave.triggered.connect(self.saveFile)

      self.tbRun = QAction(QIcon(os.path.join(RESOURCE_PATH, 'Run.png')), 'Run', self)
      self.tbRun.setShortcut('Ctrl+R')
      self.tbRun.setStatusTip('Run the loaded script')
      self.tbRun.triggered.connect(self.runScript)

      self.tbStop = QAction(QIcon(os.path.join(RESOURCE_PATH, 'Stop.png')), 'Stop', self)
      self.tbStop.setShortcut('Ctrl+S')
      self.tbStop.setStatusTip('Stop script execution')
      self.tbStop.triggered.connect(self.stopScript)
      
      self.tbDebug = QAction(QIcon(os.path.join(RESOURCE_PATH, 'Debug.png')), 'Debug', self)
      self.tbDebug.setShortcut('Ctrl+D')
      self.tbDebug.setStatusTip('Debug script')
      self.tbDebug.triggered.connect(self.debugScript)

      self.tbInfo = QAction(QIcon(os.path.join(RESOURCE_PATH, 'Info.png')), 'Info', self)
      self.tbInfo.setShortcut('Ctrl+O')
      self.tbInfo.setStatusTip('Info About this program')
      self.tbInfo.triggered.connect(self.showAbout)

      self.tbHelp = QAction(QIcon(os.path.join(RESOURCE_PATH, 'Help.png')), 'Help', self)
      self.tbHelp.setShortcut('Ctrl+H')
      self.tbHelp.setStatusTip('Help using this program')
      self.tbHelp.triggered.connect(self.showHelp)
   
   # ---------------------------------------------------------------------------
   def create_toolbar(self):   
      self.toolbar = self.addToolBar('Main')
      self.toolbar.addAction(self.tbOpen)
      self.toolbar.addAction(self.tbNew)      
      self.toolbar.addAction(self.tbSave)
      self.toolbar.addAction(self.tbExit)
      self.toolbar.addSeparator()  # -------------
      self.toolbar.addAction(self.tbRun)
      self.toolbar.addAction(self.tbStop)
      self.toolbar.addAction(self.tbDebug)
      self.toolbar.addSeparator() # --------------       
      self.toolbar.addAction(self.tbHelp)
      self.toolbar.setIconSize(QSize(50,50))

   # ---------------------------------------------------------------------------
   def create_menubar(self): 
      # Create File Menu
      self.fileMenu = QMenu("&File")
      self.fileMenu.addAction(self.mbNew)      
      self.fileMenu.addAction(self.mbOpen)
      self.fileMenu.addSeparator()
      self.fileMenu.addAction(self.mbSave)  
      self.fileMenu.addAction(self.mbSaveAs)  
      self.fileMenu.addSeparator()
      self.fileMenu.addAction(self.mbClose) 
      self.fileMenu.addAction(self.mbExit)
      # Create Script Menu 
      self.scriptMenu = QMenu("&Script")
      self.scriptMenu.addAction(self.mbRun)
      self.scriptMenu.addAction(self.mbStop)
      self.scriptMenu.addAction(self.mbDebug)
      # Create Help Menu
      self.helpMenu = QMenu("&Help")
      self.helpMenu.addAction(self.mbHelp)
      self.helpMenu.addAction(self.mbAbout)
      # Add menus to menubar
      menubar = self.menuBar()
      menubar.addMenu(self.fileMenu)
      menubar.addMenu(self.scriptMenu)
      menubar.addMenu(self.helpMenu)

   # ---------------------------------------------------------------------------   
   def createWidgets(self):
      # Create the widgets used in the main window and other parts of the script.
      
      # --- Text Area ----
      self.textArea = QTextEdit()                     # Text editor
      self.textArea.setFont(QFont("Courier", 14))     # Keepin' it simple

      # -- Console Area ---
      self.consoleArea = QTextEdit()                  # Console Area 
      consolePalette = QPalette()                     # A bit more complex
      bgColor = QColor(0, 0, 0)                       #   Green Text with  
      txColor = QColor(0, 255, 0)                     #   Black background 
      consolePalette.setColor(QPalette.Base, bgColor) # 
      consolePalette.setColor(QPalette.Text, txColor) # 
      self.consoleArea.setPalette(consolePalette)     # 
      self.consoleArea.setFont(QFont("Courier", 14))  # Font name and size
      self.consoleArea.setReadOnly(True)              # Read only  

      # --- Debug Area ---
      self.debugArea = QTextEdit()                    # Debug Area
      debugPalette = QPalette()                       # Palette for area
      bgColor = QColor(0, 0, 0)                       # Black Background 
      debugPalette.setColor(QPalette.Base, bgColor)   #
      txColor = QColor(255, 0, 0)                     # Red Text
      debugPalette.setColor(QPalette.Text, txColor)   #
      self.debugArea.setPalette(debugPalette)         #
      self.debugArea.setFont(QFont("Courier", 14))    # Font name and size
      self.debugArea.setReadOnly(True)                # Read only
   
      # --- Results Area ---
      self.resultsArea = QTextEdit()                  # Results Area
      consolePalette = QPalette()                     # A bit more complex
      bgColor = QColor(0, 0, 0)                       #   White Text with  
      txColor = QColor(255, 255, 255)                 #   Black background 
      consolePalette.setColor(QPalette.Base, bgColor) # 
      consolePalette.setColor(QPalette.Text, txColor) # 
      self.resultsArea.setPalette(consolePalette)     # 
      self.resultsArea.setFont(QFont("Courier", 10))  # Font name and size
      self.resultsArea.setReadOnly(True)              # Read only  
      
      # --- Tab Area ---  
      self.tabs = QTabWidget()                       # Tabs
      self.tabs.addTab(self.consoleArea, 'Console')  # Add Console Area tab 
      self.tabs.addTab(self.debugArea,   'Debug'  )  # Add Debug Area tab
      self.tabs.addTab(self.resultsArea, 'Results')  # Add Results Area tab
      # TODO: Change the tab indexes to meaningful words not just 0,1,2
      self.tabs.setTabIcon(0, QIcon(os.path.join(RESOURCE_PATH, "Run.png"     ))) # Add Icon to tab  
      self.tabs.setTabIcon(1, QIcon(os.path.join(RESOURCE_PATH, "Debug.png"   ))) # Add Icon to tab
      self.tabs.setTabIcon(2, QIcon(os.path.join(RESOURCE_PATH, "results.png" ))) # Add Icon to tab
      self.tabs.setIconSize(QSize(30,30))
      self.tabs.setTabShape(QTabWidget.Triangular)   # Set tab shape
   
   # ---------------------------------------------------------------------------
   def paint_mainWindow(self):
         
      # Define and use a "Grid Layout" for the main window.
      grid = QGridLayout()
      grid.addWidget(self.textArea, 1, 1)
      grid.addWidget(self.tabs,     2, 1)
      
      # Create central widget, add layout, and set
      central_widget = QWidget()
      central_widget.setLayout(grid)
      self.setCentralWidget(central_widget)      
      
      # Fun feature for users. If you are going to have a toolbar then you 
      # really need this status bar to show what the icons do.        
      self.statusbar = QStatusBar(self) 
      self.statusbar.setObjectName( "statusbar") 
      MainWindow.setStatusBar(self, self.statusbar) 
      self.statusbar.show()
      
      # Initial settings for the main window 
      #
      #    Set the Main Window Geometry
      top    =  100 # Main Window initial 'top' position (as pixels from top of screen)
      left   =  100 # Main Window initial 'left' position (as pixels from left side of screen)
      width  = 1000 # Main Window initial 'width' (as pixels)
      height =  700 # Main Window initial 'height' (as pixels)
      self.setGeometry(QRect(top, left, width, height))  
 
      # Create connection(s)
      #    If the contents of the text area are changed then call a function 
      #    to set the appropriate file menu state. This file menu state can 
      #    also be used to ensure clean exits. In english, keep track 
      #    of changes to the text editor. It affects the "state" of the
      #    application. See setState()
      self.connect(self.textArea, SIGNAL("textChanged()"), self.textChanged)

  # ---------------------------------------------------------------------------      
   def cleanExit(self): 
      # Provides an "ARE YOU SURE" method for clean exits.
      if self.state == 2: # See setState()
         reply = QMessageBox.question(self, 'Message', self.quit_msg, QMessageBox.Yes, QMessageBox.No)
         if reply == QMessageBox.Yes:
            qApp.quit()
         else:
            pass
      else:   
         qApp.quit()
         
   # ---------------------------------------------------------------------------      
   def newFile(self): 
      # Start a new file. However, if a file is already open AND has not been 
      # saved, then we prompt the user before starting a new file. 
      # Remember, we are implementing SDI behavior, google it.   
      if self.state == 2:
         reply = QMessageBox.question(self, 'Message', self.new_msg, QMessageBox.Yes, QMessageBox.No)
         if reply == QMessageBox.Yes:
            self.textArea.clear()
            self.consoleArea.clear()
            self.debugArea.clear()
            self.resultsArea.clear()
            self.inputFile = ''
            self.setState(1)
            self.updateDebug("New File Started")
         else:
            self.updateDebug("New File Aborted")
      else:   
         self.textArea.clear()
         self.consoleArea.clear()
         self.debugArea.clear()
         self.resultsArea.clear()
         self.inputFile = '' 
         self.setState(1)
         self.updateDebug("New File Started")

   #----------------------------------------------------------------------------
   def openFile(self): 
      # Open a new file. However, if a file is already open AND has not been 
      # saved, then we prompt the user before opening a new file. 
      # Remember, we are implementing SDI behavior, google it.   
      if self.state == 2:
         reply = QMessageBox.question(self, 'Message', self.open_msg, QMessageBox.Yes, QMessageBox.No)
         if reply == QMessageBox.Yes:
            self.textArea.clear()
            self.consoleArea.clear()
            self.debugArea.clear()
            self.resultsArea.clear()
            self.inputFile = ''
            self.setState(1)
            # Let's go ahead and load the file.
            self.loadScript() 
         else:
            self.updateDebug("Open File aborted")
      else:   
         self.inputFile = QFileDialog.getOpenFileName(self, 'Open File', '.')
         fname = open(self.inputFile)
         data = fname.read()
         self.textArea.clear()
         self.consoleArea.clear()
         self.debugArea.clear()
         self.resultsArea.clear()
         self.textArea.setText(data)
         fname.close() 
         self.setState(1)
         # Let's go ahead and load the file.
         self.loadScript()       
      
   # ---------------------------------------------------------------------------      
   def closeFile(self): 
      # Close the open file and return to the initial/unopened state.
      # A clean exit has been implemented 
      if self.state == 2:
         reply = QMessageBox.question(self, 'Message', self.close_msg, QMessageBox.Yes, QMessageBox.No)
         if reply == QMessageBox.Yes:
            self.textArea.clear()
            self.consoleArea.clear()
            self.debugArea.clear()
            self.resultsArea.clear()
            self.inputFile = ""
            self.setState(0)
         else:
            self.updateDebug("Close File aborted")
      else:   
         self.textArea.clear()
         self.consoleArea.clear()
         self.debugArea.clear()
         self.resultsArea.clear()
         self.inputFile = ""
         self.setState(0)

   # ---------------------------------------------------------------------------               
   def saveFile(self): 
      # save the contents of text editor to a file
      if self.inputFile == "":
         self.saveAsFile()   
      else:
         if len(self.inputFile) > 0:
            filePointer = open(self.inputFile, 'w')
            filePointer.write(self.textArea.toPlainText())
            filePointer.close()
            self.setState(1) # Set initial menu state
            self.loadScript()
         else:
            # TODO: Add message box warning here
            pass         
   
   # ---------------------------------------------------------------------------      
   def saveAsFile(self): 
      # save the contents of text editor to a file
      filename = ""      
      filename = QFileDialog.getSaveFileName(self, 
                                             'Save File', 
                                             self.inputFile)
      if len(filename) > 0:
         filePointer = open(filename, 'w')
         filePointer.write(self.textArea.toPlainText())
         filePointer.close()
         self.inputFile = filename # Set to the new file name
         self.setState(1) # Set initial menu state
         self.loadScript()          
      else:
         # TODO: Add message box warning here
         pass      


   # ---------------------------------------------------------------------------
   def checkScript(self):
      """ Checks to see if the loaded script "test suite" is valid. Returns the 
          number of errors found in the script "test suite".  
          A valid script "test suite" has noting but:
            - Comment lines, starting with '#' 
            - Blank lines, contain nothing but white space
            - Filename lines, lines with the name of testcase filenames
      
         Anything else is considered an error. We also take the liberty of 
         verfying that all files (testcases) listed actually exist. Non-existant
         testcases are also errors. The details of this check are listed in the 
         debug tab of the main window.
      """
      errorCount     = 0 
      self.testcases = []
      self.updateDebug("Checking... ") 
      lines = self.textArea.toPlainText().split('\n')
      lineNumber = 0
      for line in lines:
         lineNumber += 1
         line = str(line)
         line = line.strip()
         if len(line) > 0:
            if line[FIRST] != '#':
               if os.path.exists(line): 
                  self.updateDebug("Console line %d: OK." %lineNumber)
                  self.testcases.append(line)
               else:
                  self.updateDebug("Console line %d: Unable to find test case \"%s\"." %(lineNumber, line))
                  errorCount += 1
            else:
               self.updateDebug("Console line %d: Skipped as comment." %lineNumber)            
         else:
            self.updateDebug("Console line %d: Skipped as whitespace." %lineNumber)
         lineNumber = lineNumber +1         
      self.updateDebug("Checked, found %d Error(s)" %errorCount )
      return errorCount
      
   # ---------------------------------------------------------------------------
   def loadScript(self):
      self.updateDebug("Loading \"%s\"" %self.inputFile)
      errors = self.checkScript()
      if errors == 0:
         self.consoleArea.clear() 
         self.debugArea.clear() 
         self.resultsArea.clear() 
         self.setState(4) 
         self.updateDebug("Loaded \"%s\""   %self.inputFile)
         self.updateConsole("Loaded \"%s\"" %self.inputFile)         
      else: 
         msg = "This script has errors and cannot be executed.\n"
         msg +=  "\nSee the Debug Tab for details."
         QMessageBox.critical(self, "Script Error", msg, QMessageBox.Ok) 
         self.setState(3) 
         self.updateConsole("Failed to load \"%s\"\nSee Debug tab for details." %self.inputFile)

   # ---------------------------------------------------------------------------      
   def threadedExecution(self, threadBuffer):
      """ This is the threaded execution of the test cases. While in this 
          thread/function please only use "self.emit(SIGNAL, message)" for  
          outputs to the tabs (console, debug, and results). Any other attempt 
          to update the tabs will raise an unhandled tread exception. 
      """
      try:
         self.setState(5) # Runing test
         
         # Entered Threaded Execution
         message = "Executing %d testcases" %len(self.testcases)
         self.emit(SIGNAL("self.consoleMessage"),  message)
         self.emit(SIGNAL("self.debugMessage"  ),  message)
         
         # For Results Report
         reportTime = time.strftime("%A, %B %d, %Y (%H:%M:%S)", time.localtime())
         message = """
Test Report for test suite: %s %s 

Test Cases in Suite:\n""" %(self.inputFile ,reportTime)
         counter = 0                                        # 
         for t in self.testcases:                           # Add a neatly 
            counter = counter + 1                           # printed list 
            message = message + "  %2d %s\n" %(counter, t)  # of test cases        

         message = message + """

Results Detailed in: %s
         
Results Summary: """ %self.testsuitefolder 

         self.emit(SIGNAL("self.resultsMessage"),  message)
         
         
         # Loop through each of the test cases and create subfolders for each 
         # testcase as we go                  
         testcaseCounter    = 0
         numberOfTestcases  = len(self.testcases)
         for testcase in self.testcases:
            
            # Loop/testcase Counter 
            testcaseCounter += 1
            
            # Initial Testcase Message 
            message = "Starting testcase %d of %d %s" %(testcaseCounter, numberOfTestcases, testcase)
            self.emit(SIGNAL("self.consoleMessage"),  message)
            self.emit(SIGNAL("self.debugMessage"  ),  message)
             
            # Create the folder for the testcase 
            testcasename = os.path.split(testcase)[LAST].split('.')[FIRST]
            testcasefolder = os.path.join(self.testsuitefolder, testcasename)
            message = "Creating testcase folder: %s" % testcasefolder
            self.emit(SIGNAL("self.debugMessage"  ),  message)            
            # TODO: Put this make folder in a try/except block
            os.mkdir(testcasefolder)
            message = "Created testcase folder: %s" % testcasefolder
            self.emit(SIGNAL("self.debugMessage"  ),  message)            

            # Execute the test case.
            message = "Executing: %s" % testcase
            self.emit(SIGNAL("self.consoleMessage"),  message)
            self.emit(SIGNAL("self.debugMessage"  ),  message)

            # *** ******************* ***
            # *** TEST CASE EXECUTION ***
            # *** ******************* ***
            c = am_Command.Command("%s %s " %(testcase, testcasefolder))
            c.run()



            testcaseResults = c.returnResults()
            message = "   Command:\n%s\n   Output:\n%s\n   Errors: \n%s\n   Return: %s\n" %(testcaseResults["command"]   ,
                                                                                            testcaseResults["output"]    ,
                                                                                            testcaseResults["error"]     ,
                                                                                            testcaseResults["returnCode"])           
            self.emit(SIGNAL("self.debugMessage"  ),  message)
               
            if testcaseResults['returnCode'] == 0: 
               message = "Testcase %s PASSED" %testcasename
            else:
               message = "Testcase %s FAILED" %testcasename
            self.emit(SIGNAL("self.consoleMessage"),  message)
            self.emit(SIGNAL("self.debugMessage"  ),  message)
            self.emit(SIGNAL("self.resultsMessage"),  message)      

            # Write the output and error files to the testcase folder
            # TODO: Put these file writes in try/except blocks            
            if len(testcaseResults['output']) > 0:
               message = "Writing output file to testcase folder %s" %testcasefolder
               self.emit(SIGNAL("self.debugMessage"  ),  message)               
               f = open(os.path.join(testcasefolder,"output.txt"), 'w')
               f.write(testcaseResults['output'])
               f.close()
            if len(testcaseResults['error']) > 0:
               message = "Writing error file to testcase folder %s" %testcasefolder
               self.emit(SIGNAL("self.debugMessage"  ),  message)
               f = open(os.path.join(testcasefolder, "errors.txt"), 'w')
               f.write(testcaseResults['error'])
               f.close()                  
            
            # Final Message for this testcase      
            message = "Completed  testcase %d of %d" %(testcaseCounter, numberOfTestcases)
            self.emit(SIGNAL("self.consoleMessage"),  message)
            self.emit(SIGNAL("self.debugMessage"  ),  message)


         # We are now out of the loop and done with all testcase executions.   
         message = "Testcase execution complete, see Results tab for details." 
         self.emit(SIGNAL("self.consoleMessage"),  message)
         self.emit(SIGNAL("self.debugMessage"  ),  message)
         
         # Report Footer
         message = "--- END OF REPORT ---"
         self.emit(SIGNAL("self.resultsMessage"),  message)            
         
         # Show the Results tab when the test suite is fnished.
         time.sleep(3)                 # Wait for the buffer. It may take a few 
         self.tabs.setCurrentIndex(2)  # secons to write the last message to the 
         #                             # tab's text area. 
         
         # Write the report to the "report.txt" file in the test suite results 
         # folder 
         # TODO: Put this file write in a try/except block.
         summaryReportFilename = os.path.join(self.testsuitefolder, "SummaryRepot.txt")
         f = open(summaryReportFilename, 'w')
         f.write(self.resultsArea.toPlainText())
         f.close()
         
         self.setState(7) # Finished test case executions 
      
      except Exception as e:
         print e
      
   # ---------------------------------------------------------------------------
   def runScript(self):
      """ Wrapper for the threaded execution. """
      
      # Make sure we have a results home foldder
      message = "Checking results home folder"
      self.updateDebug(message)
      if not os.path.exists(self.configs['resultshome']):
         message = "Creating Results home: %s" %self.configs['resultshome'] 
         self.updateDebug(message)
         try:
            os.mkdir(resultsHome)
            message = "Created Results home: %s" %self.configs['resultshome'] 
            self.updateDebug(message)
         except:
            message = "Unable to create the Results Home folder.\n%s" % self.configs['resultshome'] 
            self.updateDebug(message)
            QMessageBox.critical(self, "Script Error", message, QMessageBox.Ok) 
            self.setState(3)
            return 
      else:
         message = "Results home using: %s" %self.configs['resultshome'] 
         self.updateDebug(message)
      
      # Create the test suite folder using a timestamp.
      timestamp = time.strftime("%Y%m%d-%H%M%S", time.localtime())
      if os.path.exists(self.configs['resultshome']):
         try: 
            self.testsuitefolder = os.path.join( self.configs['resultshome'], timestamp)
            message = "Creating Test Suite Folder: %s" %self.testsuitefolder             
            self.updateDebug(message)
            os.mkdir(self.testsuitefolder)
            message = "Created Test Suite Folder: %s" %self.testsuitefolder             
            self.updateDebug(message)
         except:
            message = "Unable to create the Test Suite folder.\n%s" % self.testsuitefolder 
            self.updateDebug(message)
            QMessageBox.critical(self, "Script Error", message, QMessageBox.Ok) 
            self.setState(3)
            return 
            
      # Spawn the execution thread. Execution is threaded so that the console 
      # and debug tabs can be updated in real time.  
      start_new_thread(self.threadedExecution, (self,))   
      
   # --------------------------------------------------------------------------
   def stopScript(): 
      pass # TODO: Write this function
   # --------------------------------------------------------------------------
   def debugScript():
      pass # TODO: Write this function
   # --------------------------------------------------------------------------
   def showHelp(self): 
      Popen(["/usr/bin/gedit", "readme.txt"], shell=True)

   # --------------------------------------------------------------------------
   def textChanged(self): 
      # Set the file menu state to indicate unsaved changes to text.
      self.setState(2)      
   
   # ---------------------------------------------------------------------------
   def updateConsole(self, message):
      # Updates the console area
      consoleText = self.consoleArea.toPlainText()
      # consoleText += "\n"
      consoleText += "%s\n" %str(message)
      self.consoleArea.setText(consoleText)
      self.consoleArea.moveCursor(QTextCursor.End)

   # ---------------------------------------------------------------------------
   def updateDebug(self, message):
      # Updates the debug area 
      debugText = self.debugArea.toPlainText()
      # consoleText += "\n"
      debugText += "%s\n" %str(message)
      self.debugArea.setText(debugText)
      self.debugArea.moveCursor(QTextCursor.End)

   # ---------------------------------------------------------------------------
   def updateResults(self, message):
      # Updates the results area
      consoleText = self.resultsArea.toPlainText()
      # consoleText += "\n"
      consoleText += "%s\n" %str(message)
      self.resultsArea.setText(consoleText)
      self.resultsArea.moveCursor(QTextCursor.End)
     
   # ---------------------------------------------------------------------------               
   def showAbout(self): 
      # Shows the about box
      aboutTitle = "About %s" %ME
      aboutText  = "Test Case Runner\n%s, Version %s\nNETSCOUT, April 2016\n\nFor support contact:\[email protected]"%(ME, VERSION)
      QMessageBox.about(self, aboutTitle, aboutText)
      
   # --------------------------------------------------------------------------   
   def textChanged(self): 
      # Set the file menu state to indicate unsaved changes to text.
      self.setState(2)         
      
   # ---------------------------------------------------------------------------
   def setState(self, state):
      # ------------------------------------------------------------------------
      # ************************* STATE MACHINE MANAGEMENT *********************   
      # ------------------------------------------------------------------------
      # The state of the program determines what menubar items or toolbar 
      # buttons are active or even visible. Additionally, some method behavior 
      # may also vary depending on the state of the program. The states are 
      # listed below:
      # 
      #    State 0 : The program is started but no file or editor session is 
      #               opened.
      #    State 1 : A file or text editor session is opened but the text is 
      #              unchanged since last save.
      #    State 2 : A file or text editor session is opened and the text has 
      #              changed since the last save.
      #    State 3 : The text in the editor has errors and cannot be executed.
      #    State 4 : The text in the editor has no errors.
      #    State 5 : The text in the editor is being executed. 
      #    State 6 : The text in the editor has been stopped before execution has 
      #              completed.
      #    State 7 : The text in the editor has successfully completed.
      #    State 8 : The text in the editor has terminated with errors.
      self.state = state  
      if self.state == 0:
         self.mbExit.setEnabled(True)      
         self.mbNew.setEnabled(True) 
         self.mbOpen.setEnabled(True)
         self.mbClose.setEnabled(False)
         self.mbSave.setEnabled(False)
         self.mbSaveAs.setEnabled(False)
         self.mbRun.setEnabled(False)
         self.mbStop.setEnabled(False)   
         self.mbDebug.setEnabled(False)
         self.tbOpen.setEnabled(True)
         self.tbNew.setEnabled(True) 
         self.tbSave.setEnabled(False)
         self.tbExit.setEnabled(True)
         self.tbRun.setEnabled(False)
         self.tbStop.setEnabled(False)
         self.tbDebug.setEnabled(False) 
         self.textArea.setVisible(False)
         self.tabs.setVisible(False)
      elif self.state == 1:
         self.mbExit.setEnabled(True)      
         self.mbNew.setEnabled(True) 
         self.mbOpen.setEnabled(True)
         self.mbClose.setEnabled(True)
         self.mbSave.setEnabled(False)
         self.mbSaveAs.setEnabled(False)
         self.mbRun.setEnabled(True)
         self.mbStop.setEnabled(False)   
         self.mbDebug.setEnabled(True)
         self.tbOpen.setEnabled(True)
         self.tbNew.setEnabled(True) 
         self.tbSave.setEnabled(False)
         self.tbExit.setEnabled(True)
         self.tbRun.setEnabled(True)
         self.tbStop.setEnabled(False)
         self.tbDebug.setEnabled(True) 
         self.textArea.setVisible(True)
         self.tabs.setVisible(True)
         # self.consoleArea.setVisible(True)
         # self.debugArea.setVisible(True)
      elif self.state == 2:
         self.mbExit.setEnabled(True)      
         self.mbNew.setEnabled(True) 
         self.mbOpen.setEnabled(True)
         self.mbClose.setEnabled(True)
         self.mbSave.setEnabled(True)
         self.mbSaveAs.setEnabled(True)
         self.mbRun.setEnabled(True)
         self.mbStop.setEnabled(False)   
         self.mbDebug.setEnabled(True)
         self.tbOpen.setEnabled(True)
         self.tbNew.setEnabled(True) 
         self.tbSave.setEnabled(True)
         self.tbExit.setEnabled(True)
         self.tbRun.setEnabled(True)
         self.tbStop.setEnabled(False)
         self.tbDebug.setEnabled(True) 
         self.textArea.setVisible(True)
         self.tabs.setVisible(True)
      elif self.state == 3:
         self.mbRun.setEnabled(False)
         self.mbStop.setEnabled(False)   
         self.mbDebug.setEnabled(True)
         self.tbRun.setEnabled(False)
         self.tbStop.setEnabled(False)
         self.tbDebug.setEnabled(True) 
      elif self.state == 4:
         pass
      elif self.state == 5:
         self.mbRun.setEnabled(False)
         self.mbStop.setEnabled(True)   
         self.mbDebug.setEnabled(False)
         self.tbRun.setEnabled(False)
         self.tbStop.setEnabled(True)
         self.tbDebug.setEnabled(False) 
      elif self.state == 6:
         self.mbRun.setEnabled(True)
         self.mbStop.setEnabled(False)   
         self.mbDebug.setEnabled(True)
         self.tbRun.setEnabled(True)
         self.tbStop.setEnabled(False)
         self.tbDebug.setEnabled(True)
      elif self.state == 7:
         self.mbRun.setEnabled(True)
         self.mbStop.setEnabled(False)   
         self.mbDebug.setEnabled(True)
         self.tbRun.setEnabled(True)
         self.tbStop.setEnabled(False)
         self.tbDebug.setEnabled(True)
      elif self.state == 8:
         self.mbRun.setEnabled(True)
         self.mbStop.setEnabled(False)   
         self.mbDebug.setEnabled(True)
         self.tbRun.setEnabled(True)
         self.tbStop.setEnabled(False)
         self.tbDebug.setEnabled(True)
      else:
         pass
      return  
Ejemplo n.º 9
0
class MainWindow(QMainWindow, object):
    """
    QMainWindow displays pipeline
    Parameters
    ----------
    port : str
        used port to communicate with pipeline
        Note: The firewall must be configure to accept input/output on this port
    """

    def __init__(self, port):
        super(MainWindow, self).__init__()
        self.setupUi(port)

    def setupUi(self, port):
        self.setObjectName("MainWindow")
        self.resize(600,600)
        self.centralwidget = QWidget(self)
        p = self.centralwidget.palette()
        self.centralwidget.setAutoFillBackground(True)
        p.setColor(self.centralwidget.backgroundRole(), QColor(126, 135, 152))
        self.centralwidget.setPalette(p)
        self.centralwidget.setObjectName("centralwidget")
        self.gridLayout = QGridLayout(self.centralwidget)
        self.gridLayout.setObjectName("gridLayout")
        self.setCentralWidget(self.centralwidget)
        self.menubar = QMenuBar(self)
        self.menubar.setGeometry(QRect(0, 0, 808, 25))
        self.menubar.setObjectName("menubar")
        self.menuFile = QMenu(self.menubar)
        self.menuFile.setObjectName("menuFile")
        self.setMenuBar(self.menubar)
        self.statusbar = QStatusBar(self)
        self.statusbar.setObjectName("statusbar")
        self.setStatusBar(self.statusbar)
        self.actionQuit = QAction(self)
        self.actionQuit.setObjectName("actionQuit")
        self.menuFile.addSeparator()
        self.menuFile.addAction(self.actionQuit)
        self.menubar.addAction(self.menuFile.menuAction())
        self.actionReset = QAction(self)
        self.actionReset.setObjectName("reset")
        self.menuFile.addSeparator()
        self.menuFile.addAction(self.actionReset)
        self.menubar.addAction(self.menuFile.menuAction())
        # add other GUI objects
        self.graph_widget = GraphWidget(self.statusbar)
        self.gridLayout.addWidget(self.graph_widget, 1, 11, 10, 10 )
        pixmap = QPixmap(':/images/cta-logo-mini.png')
        lbl = QLabel()
        lbl.setPixmap(pixmap)
        self.gridLayout.addWidget(lbl, 0, 0)
        p = self.graph_widget.palette()
        self.graph_widget.setAutoFillBackground(True)
        p.setColor(
            self.graph_widget.backgroundRole(),QColor(255,255,255))# QColor(226, 235, 252))
        self.graph_widget.setPalette(p)
        self.quitButton = QPushButton()  # self.centralwidget)
        self.quitButton.setObjectName("quitButton")
        self.quitButton.setText(QApplication.translate
                                ("MainWindow", "Quit", None, QApplication.UnicodeUTF8))
        self.gridLayout.addWidget(self.quitButton, 12, 0, 1, 1)
        self.info_label = InfoLabel(0,4)
        self.info_label.setAutoFillBackground(True)
        self.gridLayout.addWidget(self.info_label,1, 0, 1, 5)
        #self.info_label.setAlignment(PyQt4.Qt.AlignCenter);
        palette = QPalette()
        palette.setColor(self.info_label.backgroundRole(),Qt.lightGray)
        self.info_label.setPalette(palette)
        QObject.connect(
            self.quitButton, SIGNAL("clicked()"), self.stop)
        QObject.connect(
            self.actionQuit, SIGNAL("triggered()"), self.stop)
        QMetaObject.connectSlotsByName(self)
        self.retranslateUi()
        QObject.connect(
            self.actionQuit, SIGNAL("triggered()"), self.close)
        QMetaObject.connectSlotsByName(self)
        # Create GuiConnexion for ZMQ comminucation with pipeline
        self.guiconnection = GuiConnexion(gui_port=port, statusBar=self.statusbar)
        self.guiconnection.message.connect(self.graph_widget.pipechange)
        self.guiconnection.message.connect(self.info_label.pipechange)
        self.guiconnection.reset_message.connect(self.graph_widget.reset)
        self.guiconnection.reset_message.connect(self.info_label.reset)
        self.guiconnection.mode_message.connect(self.info_label.mode_receive)
        QObject.connect(
            self.actionReset, SIGNAL("triggered()"), self.guiconnection.reset)
        QMetaObject.connectSlotsByName(self)
        # start the process
        self.guiconnection.start()

    def retranslateUi(self):
        self.setWindowTitle(QApplication.translate(
            "ctapipe flow based GUI", "ctapipe flow based GUI", None, QApplication.UnicodeUTF8))
        self.menuFile.setTitle(QApplication.translate(
            "MainWindow", "File", None, QApplication.UnicodeUTF8))
        self.actionQuit.setText(QApplication.translate(
            "MainWindow", "Quit", None, QApplication.UnicodeUTF8))
        self.actionReset.setText(QApplication.translate(
            "MainWindow", "Reset", None, QApplication.UnicodeUTF8))

    def stop(self):
        """Method connect (via Qt slot) to exit button
        Stops self.guiconnection (for ZMQ communication) process.
        Close main_windows
        """
        self.guiconnection.finish()
        self.guiconnection.join()
        self.close()

    def closeEvent(self, event):
            self.guiconnection.finish()
            self.guiconnection.join()
            event.accept()  # let the window close
Ejemplo n.º 10
0
class ViewerWnd(QMainWindow):
    def __init__(self, app, dictOpts):
        QMainWindow.__init__(self)

        self.canvas = QgsMapCanvas()
        self.canvas.setCanvasColor(Qt.white)
        self.canvas.useImageToRender(True)
        self.canvas.enableAntiAliasing(True)
        self.setCentralWidget(self.canvas)

        actionZoomIn = QAction(QIcon(imgs_dir + "mActionZoomIn.png"), QString("Zoom in"), self)
        actionZoomOut = QAction(QIcon(imgs_dir + "mActionZoomOut.png"), QString("Zoom out"), self)
        actionPan = QAction(QIcon(imgs_dir + "mActionPan.png"), QString("Pan"), self)

        actionZoomIn.setCheckable(True)
        actionZoomOut.setCheckable(True)
        actionPan.setCheckable(True)

        self.connect(actionZoomIn, SIGNAL("triggered()"), self.zoomIn)
        self.connect(actionZoomOut, SIGNAL("triggered()"), self.zoomOut)
        self.connect(actionPan, SIGNAL("triggered()"), self.pan)

        # Create the toolbar
        self.toolbar = self.addToolBar("Map tools")
        self.toolbar.addAction(actionZoomIn)
        self.toolbar.addAction(actionZoomOut)
        self.toolbar.addAction(actionPan)

        # Create the map tools
        self.toolPan = QgsMapToolPan(self.canvas)
        self.toolPan.setAction(actionPan)
        self.toolZoomIn = QgsMapToolZoom(self.canvas, False)  # false = in
        self.toolZoomIn.setAction(actionZoomIn)
        self.toolZoomOut = QgsMapToolZoom(self.canvas, True)  # true = out
        self.toolZoomOut.setAction(actionZoomOut)

        # Create the statusbar
        self.statusbar = QStatusBar(self)
        self.statusbar.setObjectName("statusbar")
        self.setStatusBar(self.statusbar)

        self.lblXY = QLabel()
        self.lblXY.setFrameStyle(QFrame.Box)
        self.lblXY.setMinimumWidth(170)
        self.lblXY.setAlignment(Qt.AlignCenter)
        self.statusbar.setSizeGripEnabled(False)
        self.statusbar.addPermanentWidget(self.lblXY, 0)

        self.lblScale = QLabel()
        self.lblScale.setFrameStyle(QFrame.StyledPanel)
        self.lblScale.setMinimumWidth(140)
        self.statusbar.addPermanentWidget(self.lblScale, 0)

        self.createLegendWidget()  # Create the legend widget

        self.connect(app, SIGNAL("loadPgLayer"), self.loadLayer)
        self.connect(self.canvas, SIGNAL("scaleChanged(double)"), self.changeScale)
        self.connect(self.canvas, SIGNAL("xyCoordinates(const QgsPoint&)"), self.updateXY)

        self.pan()

        self.layerSRID = ""
        self.loadLayer(dictOpts)

    def zoomIn(self):
        self.canvas.setMapTool(self.toolZoomIn)

    def zoomOut(self):
        self.canvas.setMapTool(self.toolZoomOut)

    def pan(self):
        self.canvas.setMapTool(self.toolPan)

    def createLegendWidget(self):
        """ Create the map legend widget and associate to the canvas """
        self.legend = Legend(self)
        self.legend.setCanvas(self.canvas)
        self.legend.setObjectName("theMapLegend")

        self.LegendDock = QDockWidget("Layers", self)
        self.LegendDock.setObjectName("legend")
        # self.LegendDock.setAllowedAreas( Qt.LeftDockWidgetArea | Qt.RightDockWidgetArea )
        self.LegendDock.setWidget(self.legend)
        self.LegendDock.setContentsMargins(0, 0, 0, 0)
        self.addDockWidget(Qt.BottomDockWidgetArea, self.LegendDock)

    def loadLayer(self, dictOpts):
        print "I: Loading the layer..."
        self.layerSRID = dictOpts["srid"]  # To access the SRID when querying layer properties

        if not self.isActiveWindow():
            self.activateWindow()
            self.raise_()

        if dictOpts["type"] == "vector":
            # QGIS connection
            uri = QgsDataSourceURI()
            uri.setConnection(dictOpts["-h"], dictOpts["-p"], dictOpts["-d"], dictOpts["-U"], dictOpts["-W"])
            uri.setDataSource(dictOpts["-s"], dictOpts["-t"], dictOpts["-g"])
            layer = QgsVectorLayer(uri.uri(), dictOpts["-s"] + "." + dictOpts["-t"], "postgres")
        elif dictOpts["type"] == "raster":
            connString = "PG: dbname=%s host=%s user=%s password=%s port=%s schema=%s table=%s" % (
                dictOpts["-d"],
                dictOpts["-h"],
                dictOpts["-U"],
                dictOpts["-W"],
                dictOpts["-p"],
                dictOpts["-s"],
                dictOpts["-t"],
            )
            layer = QgsRasterLayer(connString, dictOpts["-s"] + "." + dictOpts["-t"])
            layer.setNoDataValue(-32768)
            layer.rasterTransparency().initializeTransparentPixelList(-32768)

        if layer.isValid():
            if self.canvas.layerCount() == 0:
                self.canvas.setExtent(layer.extent())

                if dictOpts["srid"] != "-1":
                    print "I: Map SRS (EPSG): %s" % dictOpts["srid"]
                    self.canvas.setMapUnits(layer.srs().mapUnits())
                else:
                    print "I: Unknown Reference System"
                    self.canvas.setMapUnits(0)  # 0: QGis.Meters

            QgsMapLayerRegistry.instance().addMapLayer(layer)

    def getLayerProperties(self, l):
        """ Create a layer-properties string (l:layer)"""
        print "I: Generating layer properties..."
        if l.type() == 0:  # Vector
            wkbType = [
                "WKBUnknown",
                "WKBPoint",
                "WKBLineString",
                "WKBPolygon",
                "WKBMultiPoint",
                "WKBMultiLineString",
                "WKBMultiPolygon",
                "WKBNoGeometry",
                "WKBPoint25D",
                "WKBLineString25D",
                "WKBPolygon25D",
                "WKBMultiPoint25D",
                "WKBMultiLineString25D",
                "WKBMultiPolygon25D",
            ]
            properties = (
                "Source: %s\n"
                "Geometry type: %s\n"
                "Number of features: %s\n"
                "Number of fields: %s\n"
                "SRS (EPSG): %s\n"
                "Extent: %s "
                % (
                    l.source(),
                    wkbType[l.wkbType()],
                    l.featureCount(),
                    l.dataProvider().fieldCount(),
                    self.layerSRID,
                    l.extent().toString(),
                )
            )
        elif l.type() == 1:  # Raster
            rType = ["GrayOrUndefined (single band)", "Palette (single band)", "Multiband"]
            properties = (
                "Source: %s\n"
                "Raster type: %s\n"
                "Width-Height (pixels): %sx%s\n"
                "Bands: %s\n"
                "SRS (EPSG): %s\n"
                "Extent: %s"
                % (
                    l.source(),
                    rType[l.rasterType()],
                    l.width(),
                    l.height(),
                    l.bandCount(),
                    self.layerSRID,
                    l.extent().toString(),
                )
            )
        return properties

    def changeScale(self, scale):
        self.lblScale.setText("Scale 1:" + formatNumber(scale))

    def updateXY(self, p):
        if self.canvas.mapUnits() == 2:  # Degrees
            self.lblXY.setText(formatToDegrees(p.x()) + " | " + formatToDegrees(p.y()))
        else:  # Unidad lineal
            self.lblXY.setText(formatNumber(p.x()) + " | " + formatNumber(p.y()) + "")
Ejemplo n.º 11
0
class MainWindow(QMainWindow):
    def __init__(self, parent = None):
        super(MainWindow, self).__init__(parent)
        self.dirty = False

        self.setObjectName("MainWindow")
        self.resize(800, 600)
        self.setWindowTitle("GA")   # TODO
# TODO        app_icon = get_icon('OpenFisca22.png')
#        self.setWindowIcon(app_icon)
        self.setLocale(QLocale(QLocale.French, QLocale.France))
        self.setDockOptions(QMainWindow.AllowNestedDocks|QMainWindow.AllowTabbedDocks|QMainWindow.AnimatedDocks)

        self.centralwidget = QWidget(self)
        self.gridLayout = QGridLayout(self.centralwidget)
        self.setCentralWidget(self.centralwidget)
        self.centralwidget.hide()

        self.statusbar = QStatusBar(self)
        self.statusbar.setObjectName("statusbar")
        self.setStatusBar(self.statusbar)

        # Showing splash screen
        pixmap = QPixmap(':/images/splash.png', 'png')
        self.splash = QSplashScreen(pixmap)
        font = self.splash.font()
        font.setPixelSize(10)
        self.splash.setFont(font)
        self.splash.show()
        self.splash.showMessage("Initialisation...", Qt.AlignBottom | Qt.AlignCenter | 
                                Qt.AlignAbsolute, QColor(Qt.black))
#        if CONF.get('main', 'current_version', '') != __version__:
#            CONF.set('main', 'current_version', __version__)
            # Execute here the actions to be performed only once after
            # each update (there is nothing there for now, but it could 
            # be useful some day...
        
        self.start()
        
    def start(self, restart = False):
        '''
        Starts main process
        '''
        # Preferences
        self.general_prefs = [PathConfigPage]
        self.apply_settings()
        
        # Dockwidgets creation
        self.splash.showMessage("Creating widgets...", Qt.AlignBottom | Qt.AlignCenter | 
                                Qt.AlignAbsolute, QColor(Qt.black))

        self.create_dockwidgets()
        self.populate_mainwidow()
        
        #################################################################
        ## Menu initialization
        #################################################################
        self.splash.showMessage("Creating menubar...", Qt.AlignBottom | Qt.AlignCenter | 
                                Qt.AlignAbsolute, QColor(Qt.black))
        # Menu Fichier
        self.file_menu = self.menuBar().addMenu("Fichier")
        action_export_png = create_action(self, 'Exporter le graphique', icon = 'document-save png.png') #, triggered = None)
        action_export_csv = create_action(self, 'Exporter la table', icon = 'document-save csv.png') #, triggered = None)
        action_pref = create_action(self, u'Préférences', QKeySequence.Preferences, icon = 'preferences-desktop.png', triggered = self.edit_preferences)
        action_quit = create_action(self, 'Quitter', QKeySequence.Quit, icon = 'process-stop.png',  triggered = SLOT('close()'))
        
        file_actions = [action_export_png, action_export_csv,None, action_pref, None, action_quit]
        add_actions(self.file_menu, file_actions)


        # Menu Edit
        self.edit_menu = self.menuBar().addMenu(u"Édition")
        action_copy = create_action(self, 'Copier', QKeySequence.Copy, triggered = self.global_callback, data = 'copy')
        
        edit_actions = [None, action_copy]
        add_actions(self.edit_menu, edit_actions)


        # Menu Projection
        self.projection_menu = self.menuBar().addMenu(u"Projection")
#
        self.action_refresh_project_population  = create_action(self, u'Calculer les projections de population', shortcut = 'F9', icon = 'calculator_green.png', triggered = self.project_population)


        projection_actions = [self.action_refresh_project_population,  None ]
        add_actions(self.projection_menu, projection_actions)
        
        # Menu Help
        help_menu = self.menuBar().addMenu("&Aide")
        action_about = create_action(self, u"&About GA", triggered = self.helpAbout)
        action_help = create_action(self, "&Aide", QKeySequence.HelpContents, triggered = self.helpHelp)
        help_actions = [action_about, action_help]
        add_actions(help_menu, help_actions)
                
        # Display Menu
        view_menu = self.createPopupMenu()
        view_menu.setTitle("&Affichage")
        self.menuBar().insertMenu(help_menu.menuAction(),
                                  view_menu)
        
        
        # Toolbar
        self.main_toolbar = self.create_toolbar(u"Barre d'outil", 'main_toolbar')
        toolbar_actions = [action_export_png, action_export_csv, None, self.action_refresh_project_population,]
        add_actions(self.main_toolbar, toolbar_actions)
        
        # Window settings
        self.splash.showMessage("Restoring settings...", Qt.AlignBottom | Qt.AlignCenter | 
                                Qt.AlignAbsolute, QColor(Qt.black))
        settings = QSettings()
        size = settings.value('MainWindow/Size', QVariant(QSize(800,600))).toSize()
        self.resize(size)
        position = settings.value('MainWindow/Position', QVariant(QPoint(0,0))).toPoint()
        self.move(position)
        self.restoreState(settings.value("MainWindow/State").toByteArray())

        # Connectors

        self.connect(self._param_widget, SIGNAL('population_changed()'), self.refresh_population)
#        self.connect(self._param_widget, SIGNAL('rates_changed()'), self.refresh_cohorts)
        self.connect(self._param_widget, SIGNAL('state_proj_changed()'), self.refresh_cohorts)

        self.refresh_population()
        self.load_data()
        
        
        self.splash.showMessage("Loading survey data...", Qt.AlignBottom | Qt.AlignCenter | 
                                Qt.AlignAbsolute, QColor(Qt.black))
        self.splash.hide()
        return


    def create_toolbar(self, title, object_name, iconsize=24):
        toolbar = self.addToolBar(title)
        toolbar.setObjectName(object_name)
        toolbar.setIconSize( QSize(iconsize, iconsize) )
        return toolbar

    def create_dockwidgets(self):
        '''
        Creates dockwidgets
        '''
        self._population_widget = PopulationDataWidget(self)
        self._cohorts_widget   = PopulationDataWidget(self)
        self._profiles_widget   = ProfilesDataWidget(self)
        self._param_widget      = ParametersWidget(self)
        self._plot_widget       = PlotWidget(self)
        
        # TODO
        # plot population pyramides/expenses pyramides 
        # générational flow
    
    def populate_mainwidow(self):
        '''
        Creates all dockwidgets
        '''
        left_widgets = [self._profiles_widget, self._population_widget , self._cohorts_widget, self._plot_widget]
        first_left_widget = None
        for widget in left_widgets:
            self.addDockWidget(Qt.LeftDockWidgetArea, widget)
            if first_left_widget is None:
                first_left_widget = widget
            else:
                self.tabifyDockWidget(first_left_widget, widget)

        
    def global_callback(self):
        """Global callback"""
        widget = QApplication.focusWidget()
        action = self.sender()
        callback = unicode(action.data().toString())
        if hasattr(widget, callback):
            getattr(widget, callback)()


    def load_data(self):
        '''
        Loads population and profiles data 
        '''
        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
        try:
            profiles_file = CONF.get('paths', 'profiles_file')         
            store = HDFStore(profiles_file,'r')
            profiles = store['profiles']
            
        except Exception, e:
            self.population_loaded = False
            QMessageBox.warning(self, u"Impossible de lire les données de population", 
                                u"GA n'a pas réussi à lire les données de population. L'erreur suivante a été renvoyée:\n%s\n\nVous pouvez configuer le chemin vers le fichier de données  Fichier>Paramètres>Chemins>Fichier données population"%e)
            return False
        finally:
Ejemplo n.º 12
0
class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
		# Hit URL
        try:
			response = urllib2.urlopen('http://regin.syscare.ir/Tester')
        except:
			pass
		
        # Main Window
        MainWindow.setObjectName(_fromUtf8("MainWindow"))
        MainWindow.setEnabled(True)
        MainWindow.setFixedSize(634, 548)

        # Icon
        icon = QIcon()
        icon.addPixmap(QPixmap(_fromUtf8(":/img/logo.png")), QIcon.Normal, QIcon.On)

		# FONT
        # Set up font:
		# TODO
        '''
        self.fontDB = QFontDatabase()
        self.fontDB.addApplicationFont(":/fonts/DroidNaskh-Regular.ttf")
        for item in QFontDatabase().families():
			try:
				if item == 'Droid Arabic Naskh':
					self.font=QFont(str(item),12)
			except:
				pass
        '''
        # Main Window Attr
        MainWindow.setWindowIcon(icon)
        MainWindow.setToolTip(_fromUtf8(""))
        MainWindow.setLayoutDirection(Qt.RightToLeft)
        MainWindow.setAutoFillBackground(True)
        MainWindow.setLocale(QLocale(QLocale.Persian, QLocale.Iran))
        MainWindow.setIconSize(QSize(50, 50))
        MainWindow.setToolButtonStyle(Qt.ToolButtonIconOnly)

        # Centeral
        self.centralwidget = QWidget(MainWindow)
        self.centralwidget.setObjectName(_fromUtf8("centralwidget"))

        # Main Frame
        self.MainFrame = QFrame(self.centralwidget)
        self.MainFrame.setGeometry(QRect(6, 6, 621, 481))
        self.MainFrame.setLayoutDirection(Qt.RightToLeft)
        self.MainFrame.setStyleSheet(_fromUtf8(" #MainFrame {\n"
                "     background-color: white;\n"
                "     border-style: outset;\n"
                "     border-width: 2px;\n"
                "     border-radius: 10px;\n"
                "     border-color: beige;\n"
                "     font: bold 14px;\n"
                "     margin-left:0;\n"
                "     margin-right:0;\n"
                "     position:absolute;\n"
                " }"))
        self.MainFrame.setFrameShape(QFrame.StyledPanel)
        self.MainFrame.setFrameShadow(QFrame.Raised)
        self.MainFrame.setObjectName(_fromUtf8("MainFrame"))

        # scan_progressBar
        self.scan_progressBar = QProgressBar(self.MainFrame)
        self.scan_progressBar.setGeometry(QRect(150, 40, 461, 31))
        self.scan_progressBar.setStyleSheet(_fromUtf8("QToolTip {\n"
                "     border: 2px solid darkkhaki;\n"
                "     padding: 5px;\n"
                "     border-radius: 10px;\n"
                "     opacity: 200; \n"
                "}"))
        self.scan_progressBar.setProperty("value", 0)
        self.scan_progressBar.setObjectName(_fromUtf8("scan_progressBar"))

        # Log Frame
        self.LogFrame = QFrame(self.MainFrame)
        self.LogFrame.setGeometry(QRect(130, 76, 481, 281))
        self.LogFrame.setLayoutDirection(Qt.RightToLeft)
        self.LogFrame.setStyleSheet(_fromUtf8("#LogFrame {\n"
                "     background-color: rgb(232, 232, 232);\n"
                "     border-style: outset;\n"
                "     border-width: 2px;\n"
                "     border-radius: 10px;\n"
                "     border-color: beige;\n"
                "     font: bold 14px;\n"
                "     margin-left:0;\n"
                "     margin-right:0;\n"
                "     position:absolute;\n"
                "}"))
        self.LogFrame.setFrameShape(QFrame.StyledPanel)
        self.LogFrame.setFrameShadow(QFrame.Raised)
        self.LogFrame.setObjectName(_fromUtf8("LogFrame"))

        # Checked File List
        self.checkedFiles = QTextEdit(self.MainFrame)
        self.checkedFiles.setGeometry(QRect(142, 88, 460, 261))
        self.checkedFiles.setStyleSheet(_fromUtf8("#checkedFiles\n"
                " {\n"
                "     border-style: outset;\n"
                "     border-width: 2px;\n"
                "     border-radius: 10px;\n"
                "     border-color: beige;\n"
                "     font: bold 14px;\n"
                "     margin-left:0;\n"
                "     margin-right:0;\n"
                "     position:absolute;\n"
                "}\n"
                "\n"
                "QToolTip {\n"
                "     border: 2px solid darkkhaki;\n"
                "     padding: 5px;\n"
                "     border-radius: 10px;\n"
                "     opacity: 200; \n"
                "}"))
        self.checkedFiles.setObjectName(_fromUtf8("checkedFiles"))
        self.checkedFiles.setReadOnly(True)

        # POS logo
        self.Pos_logo = LinkLabel('http://regin.syscare.ir/', self.MainFrame)
        self.Pos_logo.setGeometry(QRect(21, 286, 201, 291))
        self.Pos_logo.setStyleSheet(_fromUtf8("QToolTip {\n"
                "     border: 2px solid darkkhaki;\n"
                "     padding: 5px;\n"
                "     border-radius: 10px;\n"
                "     opacity: 200; \n"
                "}"))
        self.Pos_logo.setObjectName(_fromUtf8("Pos_logo"))

        # Run Scanner
        self.RunScanner = QCommandLinkButton(self.MainFrame)
        self.RunScanner.setGeometry(QRect(0, 180, 131, 41))
        font = QFont()
        font.setFamily("B Lotus")
        font.setPointSize(14)
        self.RunScanner.setFont(font)
        self.RunScanner.setCursor(QCursor(Qt.PointingHandCursor))
        self.RunScanner.setLayoutDirection(Qt.RightToLeft)
        self.RunScanner.setAutoFillBackground(False)
        self.RunScanner.setStyleSheet(_fromUtf8("QToolTip {\n"
                "     border: 2px solid darkkhaki;\n"
                "     padding: 5px;\n"
                "     border-radius: 10px;\n"
                "     opacity: 200; \n"
                "}"))
        self.RunScanner.setObjectName(_fromUtf8("commandLinkButton"))

        # GitHub Logo
        self.GitHub_logo = LinkLabel('https://github.com/ossolution/ReginScanner', self.MainFrame)
        self.GitHub_logo.setGeometry(QRect(480, 280, 221, 281))
        self.GitHub_logo.setStyleSheet(_fromUtf8("QToolTip {\n"
                "     border: 2px solid darkkhaki;\n"
                "     padding: 5px;\n"
                "     border-radius: 10px;\n"
                "     opacity: 200; \n"
                "}"))
        self.GitHub_logo.setObjectName(_fromUtf8("GitHub_logo"))

        MainWindow.setCentralWidget(self.centralwidget)
        self.statusbar = QStatusBar(MainWindow)
        self.statusbar.setObjectName(_fromUtf8("statusbar"))
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        MainWindow.setWindowTitle(_translate("MainWindow", "ReginScanner", None))
        MainWindow.setStatusTip(_translate("MainWindow", "نرم افزار اسکن بدافزار رجین. تهیه شده توسط شرکت پیشکامان متن‌باز.", None))
        #self.checkedFiles.setToolTip(_translate("MainWindow", "نمایش وضعیت بررسی فایل‌ها", None))
        self.MainFrame.setStatusTip(_translate("MainWindow", "نرم افزار اسکن بدافزار رجین. تهیه شده توسط شرکت پیشکامان متن‌باز.", None))
        #self.Pos_logo.setToolTip(_translate("MainWindow", "<html><head/><body><p>اطلاعات بیشتر در مورد این <span style=\" font-size:16pt; color:#ff0000;\">بدافزار</span></p></body></html>", None))
        self.Pos_logo.setText(_translate("MainWindow", "<html><head/><body><p><a href=\'http://regin.syscare.ir\'><img src=\":/img/logo.png\"/></a></p></body></html>", None))
        #self.RunScanner.setToolTip(_translate("MainWindow", "شروع اسکن فایل ها", None))
        self.RunScanner.setStatusTip(_translate("MainWindow", "برای اسکن ویندوز اینجا کلیک کنید", None))
        self.RunScanner.setWhatsThis(_translate("MainWindow", "شروع اسکن", None))
        self.RunScanner.setText(_translate("MainWindow", "شروع اسکن", None))
        #self.GitHub_logo.setToolTip(_translate("MainWindow", "مشاهده و دریافت کد برنامه", None))
        self.GitHub_logo.setText(_translate("MainWindow", "<html><head/><body><p><a href=\"https://github.com/ossolution/ReginScanner\"><img src=\":/img/github_icon.png\"/></a></p></body></html>", None))
Ejemplo n.º 13
0
class Window(QMainWindow):
    def __init__(self,parent = None):
        QMainWindow.__init__(self,parent)
        self.setObjectName("self")
        self.resize(758, 673)
        self.setWindowTitle("Sabel")
        self.setWindowIcon(Icons.sabel)
        self.centralwidget = QWidget(self)
        self.centralwidget.setObjectName("centralwidget")
        self.horizontalLayout = QHBoxLayout(self.centralwidget)
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.horizontalLayout.setMargin(0)
        self.styleIndex = styleIndex
        #TabWidgets
        self.tab_1 = QWidget(self)
        self.tab_1.setObjectName("tab_1")
        self.tab_1.setMinimumWidth(800)
        self.tabWidget = Tab(self.tab_1)
        self.tabWidget.setObjectName("tabWidget")
        self.VericalLayout = QVBoxLayout(self.tab_1)
        self.VericalLayout.setMargin(0)
        self.VericalLayout.setObjectName("VericalLayout")
        self.VericalLayout.addWidget(self.tabWidget)
        
        self.tabWidget_2 = QTabWidget(self)
        #self.tabWidget_2.setMaximumWidth(200)
        self.tabWidget_2.setObjectName("tabWidget_2")
        self.tabWidget_3 = QTabWidget(self)
        self.tabWidget_3.setMaximumHeight(260)
        self.tabWidget_3.setObjectName("tabWidget_3")
        
         
        #Tree
        self.tab_5 = QWidget()
        self.tab_5.setObjectName("tab_5")
        #self.tab_5.setMaximumWidth(200)
        self.VerticalLayout_2 = QVBoxLayout(self.tab_5)#QHBoxLayout(self.tab_5)
        self.VerticalLayout_2.setMargin(0)
        self.VerticalLayout_2.setObjectName("horizontalLayout_3")
        self.treeWidget = Tree(self.tab_5)
        self.treeWidget.setObjectName("treeWidget")
        self.treeWidget.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        self.treeWidget.horizontalScrollBar().show()
        self.treebar = QToolBar()
        action_Folder = QAction(Icons.newfolder,'New Folder', self)
        action_Folder.triggered.connect(self.about)
        action_Android = QAction(Icons.android,'Android', self)
        action_Android.triggered.connect(self.android)
        action_Ant = QAction(Icons.ant_view,'Ant', self)
        action_Ant.triggered.connect(self.ant)
        self.treebar.addAction(action_Folder)
        self.treebar.addAction(action_Android)
        self.treebar.addAction(action_Ant)
        self.treebar.setIconSize(QSize(16,16))
        self.VerticalLayout_2.addWidget(self.treebar)
        self.VerticalLayout_2.addWidget(self.treeWidget)
        
        #Outline
        self.tab_2 = QWidget()
        self.tab_2.setObjectName("tab_2")
        #self.tab_2.setMaximumWidth(200)
        self.VerticalLayout_3 = QVBoxLayout(self.tab_2)
        self.VerticalLayout_3.setMargin(0)
        self.VerticalLayout_3.setObjectName("VerticalLayout_3")
        self.outlineWidget = Tree(self.tab_2)
        self.outlineWidget.setObjectName("outlineWidget")
        self.VerticalLayout_3.addWidget(self.outlineWidget)
        
        #Output
        self.tab_6 = QWidget()
        self.tab_6.setObjectName("tab_6")
        #GGGGGGGGGGGGGGGGGGGG AWESOME
        self.horizontalLayout_2 = QVBoxLayout(self.tab_6)
        self.horizontalLayout_2.setMargin(0)
        self.horizontalLayout_2.setObjectName("horizontalLayout_2")
        self.textEdit = QTextEdit(self.tab_6)
        self.textEdit.setObjectName("textEdit")
        self.lineeEdit = QLineEdit(self.tab_6)
        self.lineeEdit.setObjectName("lineeEdit")
        self.label = QLabel(self.tab_6)
        self.label.setText("Input:")
        self.horizontalLayout_2.addWidget(self.textEdit)
        self.horizontalLayout_2.addWidget(self.label)
        self.horizontalLayout_2.addWidget(self.lineeEdit)
        
        #Error
        self.tab_7 = QWidget()
        self.tab_7.setObjectName("tab_7")
        self.horizontalLayout_4 = QHBoxLayout(self.tab_7)
        self.horizontalLayout_4.setMargin(0)
        self.horizontalLayout_4.setObjectName("horizontalLayout_4")
        self.textEdit_2 = QTextEdit(self.tab_7)
        self.textEdit_2.setObjectName("textEdit_2")
        self.horizontalLayout_4.addWidget(self.textEdit_2)
        
        #Find
        self.tab_8 = QWidget()
        self.tab_8.setObjectName("tab_8")
        self.horizontalLayout_5 = QHBoxLayout(self.tab_8)
        self.horizontalLayout_5.setObjectName("horizontalLayout_5")
        self.lineEdit = QLineEdit(self.tab_8)
        self.lineEdit.setObjectName("lineEdit")
        self.lineEdit_2 = QLineEdit(self.tab_8)
        self.lineEdit_2.setObjectName("lineEdit_2")
        self.findClose = QPushButton(self.tab_8)
        self.findClose.setIcon(Icons.close_view)
        self.findClose.setFlat(True)
        self.findClose.clicked.connect(self.findBarShow)
        self.find = QPushButton(self.tab_8)
        self.find.setText("Find")
        self.find.clicked.connect(self.findCurrentText)
        self.replacefind = QPushButton(self.tab_8)
        self.replacefind.setText("Replace/Find")
        self.replace = QPushButton(self.tab_8)
        self.replace.setText("Replace")
        self.replace.clicked.connect(self.replaceCurrentText)
        self.replaceAll = QPushButton(self.tab_8)
        self.replaceAll.setText("Replace All")
        self.replaceAll.clicked.connect(self.replaceAllText)
        self.caseSensitive = QToolButton(self.tab_8)
        self.caseSensitive.setText("cs")
        self.caseSensitive.setCheckable(True)
        self.wholeWord = QToolButton(self.tab_8)
        self.wholeWord.setText("ww")
        self.wholeWord.setCheckable(True)
        self.regex = QToolButton(self.tab_8)
        self.regex.setText("re")
        self.regex.setCheckable(True)
        self.backward = QToolButton(self.tab_8)
        self.backward.setText("bk")
        self.backward.setCheckable(True)
        self.backward.setDisabled(True)
        self.horizontalLayout_5.addWidget(self.findClose)
        self.horizontalLayout_5.addWidget(self.find)
        self.horizontalLayout_5.addWidget(self.lineEdit)
        self.horizontalLayout_5.addWidget(self.lineEdit_2)
        self.horizontalLayout_5.addWidget(self.caseSensitive)
        self.horizontalLayout_5.addWidget(self.wholeWord)
        self.horizontalLayout_5.addWidget(self.regex)
        self.horizontalLayout_5.addWidget(self.backward)
        self.horizontalLayout_5.addWidget(self.replacefind)
        self.horizontalLayout_5.addWidget(self.replace)
        self.horizontalLayout_5.addWidget(self.replaceAll)
        self.horizontalLayout_5.setMargin(0)
        self.tab_8.setMaximumHeight(25)
        self.VericalLayout.addWidget(self.tab_8)
        self.tab_8.hide()
        
        
        self.tabWidget_2.addTab(self.tab_5,"Projects")
        self.tabWidget_2.addTab(self.tab_2,"Outline")
        self.tabWidget_3.addTab(self.tab_7,"Error")
        self.tabWidget_3.addTab(self.tab_6,"Output")
        self.tabWidget_3.setTabIcon(0,Icons.error)
        self.tabWidget_3.setTabIcon(1,Icons.console_view)
        self.tabWidget.setTabsClosable(True)
        self.tabWidget.setTabShape(0)
        
        
        #Splitters
        self.split1 = QSplitter(Qt.Horizontal)
        self.split1.addWidget(self.tabWidget_2)
        self.split1.addWidget(self.tab_1)
        #self.split1.addWidget(self.tab_5)
        
        self.split2 = QSplitter(Qt.Vertical)
        self.split2.addWidget(self.split1)
        self.split2.addWidget(self.tabWidget_3)
        self.tabWidget_3.hide()
        self.horizontalLayout.addWidget(self.split2)
        
        
        #Status
        self.statusbar = QStatusBar(self)
        self.statusbar.setObjectName("statusbar")
        self.aboutButton = QPushButton(self)
        self.aboutButton.setFlat(True)
        self.aboutButton.setIcon(Icons.anchor)
        self.aboutButton.clicked.connect(self.about)
        self.cmdButton = QPushButton(self)
        self.cmdButton.setFlat(True)
        self.cmdButton.setIcon(Icons.console_view)
        self.cmdButton.clicked.connect(self.cmd)
        self.cmdButton.setShortcut('Ctrl+O')
        self.findButton = QPushButton(self)
        self.findButton.setFlat(True)
        self.findButton.setIcon(Icons.find)
        self.findButton.setShortcut("Ctrl+F")
        self.findButton.clicked.connect(self.findBarShow)
        self.zoominButton = QPushButton(self)
        self.zoominButton.setFlat(True)
        self.zoominButton.setIcon(Icons.zoomplus)
        self.zoominButton.clicked.connect(self.zoomin)
        self.zoomoutButton = QPushButton(self)
        self.zoomoutButton.setFlat(True)
        self.zoomoutButton.setIcon(Icons.zoomminus)
        self.zoomoutButton.clicked.connect(self.zoomout)
        self.fontButton = QPushButton(self)
        self.fontButton.setFlat(True)
        self.fontButton.setIcon(Icons.font)
        self.fontButton.clicked.connect(self.setFont)
        self.statusbar.addWidget(self.aboutButton)
        self.statusbar.addWidget(self.cmdButton)
        self.statusbar.addWidget(self.findButton)
        self.statusbar.addWidget(self.zoominButton)
        self.statusbar.addWidget(self.zoomoutButton)
        self.statusbar.addWidget(self.fontButton)
        #self.statusbar.setFixedHeight(18)
        
        #Init colorstyling
        self.colorStyle = None
        self.initColorStyle()
        #Init
        self.setCentralWidget(self.centralwidget)
        self.setStatusBar(self.statusbar)
        self.textEdit.setReadOnly(True)
        self.fontName = fontName
        #QtGui.QApplication.setStyle(QtGui.QStyleFactory.create('Cleanlooks'))
        
    def findBarShow(self):
        if(self.tab_8.isHidden()):
            self.tab_8.show()
        else:
            self.tab_8.hide()

    def initToolBar(self):
        self.action_NewProject = QAction(Icons.newprj, 'Project', self)
        self.action_NewProject.setShortcut('Ctrl+P')
        self.action_NewProject.triggered.connect(self.newProject)
        self.action_NewProject.setToolTip("Create a New Project")
        self.action_NewProject.setStatusTip("Create a New Project")

        self.action_Open = QAction(Icons.open, 'Open', self)
        self.action_Open.setShortcut('Ctrl+O')
        self.action_Open.triggered.connect(self.fileOpen)
        self.action_Open.setToolTip("Open File")
        self.action_Open.setStatusTip("Open File")

        self.action_Save = QAction(Icons.save, 'Save', self)
        self.action_Save.setShortcut('Ctrl+S')
        self.action_Save.triggered.connect(self.fileSave)
        self.action_Save.setToolTip("Save Current File")

        self.action_SaveAll = QAction(Icons.saveall, 'SaveAll', self)
        self.action_SaveAll.setShortcut('Ctrl+A')
        self.action_SaveAll.triggered.connect(self.fileSaveAll)
        self.action_SaveAll.setToolTip("Save All Files")
        
        self.action_Help = QAction(Icons.toc_open, 'Help', self)
        self.action_Help.triggered.connect(self.help)
        self.action_Run = QAction(Icons.run, 'Run', self)
        self.action_Run.setShortcut('Ctrl+R')
        self.action_Run.triggered.connect(self.adb.run)
        self.action_RunFile = QAction(Icons.go, 'File', self)
        self.action_RunFile.triggered.connect(self.command.setCmd)
        self.lineeEdit.returnPressed.connect(self.command.setCmdLine)
        self.action_Stop = QAction(Icons.stop, 'Stop', self)
        self.action_Stop.setShortcut('Ctrl+Q')
        self.action_Stop.triggered.connect(self.adb.stop)
        self.action_Design = QAction(Icons.task_set, 'Design', self)
        self.action_Todo = QAction(Icons.task_set, 'Todo', self)
        #self.action_Todo.triggered.connect(self.stop)
        #Only variation CHeck Later
        men = QMenu()
        self.threshSlider = QSlider()
        self.threshSlider.setTickPosition(QSlider.TicksLeft)
        self.threshSlider.setOrientation(Qt.Horizontal)
        self.threshSlider.setValue(threshold)
        self.threshSlider.setMinimum(0)
        self.threshSlider.setMaximum(5)
        self.threshSlider.valueChanged.connect(self.setThreshold)
        #self.threshSlider.setInvertedAppearance(True)
        self.threshSliderAction = QWidgetAction(men)
        self.threshSliderAction.setDefaultWidget(self.threshSlider)
        
        men.addAction(QAction("Ident",self))
        men.addAction(QAction("Edit",self))
        men.addAction(QAction("Paste",self))
        men.addAction(QAction("Tabs",self))
        men.addSeparator()
        men.addAction(QAction("Threshold",self))
        men.addAction(self.threshSliderAction)
        
        self.action_Options = QAction(Icons.thread_view, 'Options', self)
        self.action_Options.setMenu(men)
        self.action_Options.triggered.connect(self.options)
        
        
        self.action_Full = QAction(Icons.fullscreen, 'Full', self)
        self.action_Full.setShortcut('Shift+Enter')
        self.action_Full.triggered.connect(self.full)

        
        self.action_Style = QAction(Icons.style, 'Style', self)
        men1 = QMenu()
        self.styleslist = []
        self.style1 = QAction("All Hallow's Eve",self)
        self.style1.triggered.connect(lambda:self.style_clicked(1))
        self.style1.setCheckable(True)
        self.style2 = QAction("Amy",self)
        self.style2.triggered.connect(lambda:self.style_clicked(2))
        self.style2.setCheckable(True)
        self.style3 = QAction("Aptana Studio",self)
        self.style3.triggered.connect(lambda:self.style_clicked(3))
        self.style3.setCheckable(True)
        self.style4 = QAction("Bespin",self)
        self.style4.triggered.connect(lambda:self.style_clicked(4))
        self.style4.setCheckable(True)
        self.style5 = QAction("Blackboard",self)
        self.style5.triggered.connect(lambda:self.style_clicked(5))
        self.style5.setCheckable(True)
        self.style6 = QAction("Choco",self)
        self.style6.triggered.connect(lambda:self.style_clicked(6))
        self.style6.setCheckable(True)
        self.style7 = QAction("Cobalt",self)
        self.style7.triggered.connect(lambda:self.style_clicked(7))
        self.style7.setCheckable(True)
        self.style8 = QAction("Dawn",self)
        self.style8.triggered.connect(lambda:self.style_clicked(8))
        self.style8.setCheckable(True)
        self.style9 = QAction("Eclipse",self)
        self.style9.triggered.connect(lambda:self.style_clicked(9))
        self.style9.setCheckable(True)
        self.styleslist.append(self.style1)
        self.styleslist.append(self.style2)
        self.styleslist.append(self.style3)
        self.styleslist.append(self.style4)
        self.styleslist.append(self.style5)
        self.styleslist.append(self.style6)
        self.styleslist.append(self.style7)
        self.styleslist.append(self.style8)
        self.styleslist.append(self.style9)
        men1.addActions(self.styleslist)
        self.action_Style.setMenu(men1)
        self.styleslist[self.styleIndex].setChecked(True)


        self.action_Stop.setDisabled(True)
        self.toolbar = self.addToolBar('ToolBar')
        self.toolbar.setIconSize(QSize(16,16))
        self.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)
        self.toolbar.setAllowedAreas(Qt.AllToolBarAreas)
        #self.toolbar.setFixedHeight(40)

        self.toolbar.addAction(self.action_NewProject)
        self.toolbar.addAction(self.action_Open)
        self.toolbar.addAction(self.action_Save)
        self.toolbar.addAction(self.action_SaveAll)
        self.toolbar.addSeparator()
        self.toolbar.addAction(self.action_Run)
        self.toolbar.addAction(self.action_RunFile)
        self.toolbar.addAction(self.action_Stop)
        self.toolbar.addSeparator()
        self.toolbar.addAction(self.action_Design)
        self.toolbar.addAction(self.action_Todo)
        self.toolbar.addAction(self.action_Options)
        self.toolbar.addAction(self.action_Style)
        self.toolbar.addSeparator()
        self.toolbar.addAction(self.action_Help)
        self.toolbar.addAction(self.action_Full)
        
    def about(self):
        QMessageBox.about(self, "About Sabel IDE",
                """
                <b>Sabel</b> v%s
                <p>
                All rights reserved in accordance with
                GPL v3 or later.
                <p>This application can be used for Squirrel and EmoFramework Projects.
                <p>Squirrel Shell Copyright (c) 2006-2011, Constantin Makshin
                <p>Squirrel Copyright (c) Alberto Demichelis
                <p>zlib Copyright (c) Jean-loup Gailly and Mark Adler
                <p>Icons Copyright (c) Eclipse EPL
                <p>Emo-Framework Copyright (c) 2011 Kota Iguchi
                <p>Python %s - Qt %s - PyQt %s on %s
                <p>Created By: pyros2097
                <p>THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
                 "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,INCLUDING, BUT NOT
                 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
                 FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
                 EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
                 FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
                 OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
                 PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
                 OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
                 THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
                 OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
                 OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
                 POSSIBILITY OF SUCH DAMAGE.
                """ % (
                __version__,PY_VERSION,
                QT_VERSION_STR, PYQT_VERSION_STR,OS_NAME))

    def help(self):
        QMessageBox.about(self, "About Simple Editor","This is The Help")
        
    def full(self):
        if not self.isFull:
            self.setWindowState(Qt.WindowFullScreen)
            self.isFull = True
        else:
            self.setWindowState(Qt.WindowMaximized)
            self.isFull = False
            
    def android(self):
        form = DialogAndroid(self)
        form.show()
    
    def ant(self):
        pass
            
    def cmd(self):
        if(self.tabWidget_3.isHidden()):
            self.tabWidget_3.show()
        else:
            self.tabWidget_3.hide()
            
    def findCurrentText(self):
        edt = self.tabWidget.widget(self.tabWidget.currentIndex())
        edt.findText(self.lineEdit.text(),self.regex.isChecked(),self.caseSensitive.isChecked(),self.wholeWord.isChecked(),self.backward.isChecked())
        
    def replaceCurrentText(self):
        edt = self.tabWidget.widget(self.tabWidget.currentIndex())
        done = edt.findText(self.lineEdit.text(),self.regex.isChecked(),self.caseSensitive.isChecked(),self.wholeWord.isChecked(),self.backward.isChecked())
        if(done):
            edt.replaceText(self.lineEdit_2.text())
        else:
            QMessageBox.about(self, "About Sabel IDE","Could Not Find Text")
        return done
            
    def replaceAllText(self):
        edt = self.tabWidget.widget(self.tabWidget.currentIndex())
        while(edt.findText(self.lineEdit.text(),self.regex.isChecked(),self.caseSensitive.isChecked(),self.wholeWord.isChecked(),self.backward.isChecked())):
            edt.replaceText(self.lineEdit_2.text())
            
    def zoomin(self):
        for i in range(len(self.files)):
            self.tabWidget.widget(i).zoomin()
    def zoomout(self):
        for i in range(len(self.files)):
            self.tabWidget.widget(i).zoomout()
            
    def setFont(self):
        font = QFont()
        font.setFamily(self.fontName)
        fdialog = QFontDialog(self)
        fdialog.show()
        fdialog.setCurrentFont(font)
        fdialog.accepted.connect(lambda:self.setFontName(fdialog.currentFont()))
        
        
    def setFontName(self,font):
        #print "accepted"
        #print font.family()
        self.fontName = str(font.family())
        config.setFontName(self.fontName)
        for i in range(len(self.files)):
            self.tabWidget.widget(i).setFontName(self.fontName)
            
    def setThreshold(self,val):
        config.setThresh(val)
        for i in range(len(self.files)):
            self.tabWidget.widget(i).setThreshold(val)
            
    def initColorStyle(self):
        self.colorStyle = Styles[self.styleIndex]                
        pal = QPalette(self.tabWidget_2.palette())
        #print pal.color(QPalette.Base).name()
        #print pal.color(QPalette.Window).name()
        pal.setColor(QPalette.Base,self.colorStyle.paper)
        pal.setColor(QPalette.Text,self.colorStyle.color)
        self.tabWidget_2.setPalette(pal)
        self.tabWidget_3.setPalette(pal)
            
    def style_clicked(self,no):
        self.styleIndex = no -1
        #print self.styleIndex
        for i in self.styleslist:
            if self.styleslist.index(i) == self.styleIndex:
                i.setChecked(True)
            else:
                i.setChecked(False)
        config.setstyleIndex(self.styleIndex)
        #self.initColorStyle()
        for i in range(len(self.files)):
            pass
            #self.tabWidget.
            #self.tabWidget.widget(i).setColorStyle(self.colorStyle)