示例#1
0
文件: tabs.py 项目: koll00/Gui_SM
    def __init__(self, parent, actions=None, menu=None,
                 corner_widgets=None, menu_use_tooltips=False):
        QTabWidget.__init__(self, parent)
        
        self.setUsesScrollButtons(True)
        
        self.corner_widgets = {}
        self.menu_use_tooltips = menu_use_tooltips
        
        if menu is None:
            self.menu = QMenu(self)
            if actions:
                add_actions(self.menu, actions)
        else:
            self.menu = menu
            
        # Corner widgets
        if corner_widgets is None:
            corner_widgets = {}
        corner_widgets.setdefault(Qt.TopLeftCorner, [])
        corner_widgets.setdefault(Qt.TopRightCorner, [])
        self.browse_button = create_toolbutton(self,
                                          icon=get_icon("browse_tab.png"),
                                          tip=_("Browse tabs"))
        self.browse_tabs_menu = QMenu(self)
        self.browse_button.setMenu(self.browse_tabs_menu)
        self.browse_button.setPopupMode(self.browse_button.InstantPopup)
        self.connect(self.browse_tabs_menu, SIGNAL("aboutToShow()"),
                     self.update_browse_tabs_menu)
        corner_widgets[Qt.TopLeftCorner] += [self.browse_button]

        self.set_corner_widgets(corner_widgets)
 def __init__(self, parent = None, dnd = False):
     """
     Constructor
     
     @param parent reference to the parent widget (QWidget)
     @keyparam dnd flag indicating the support for Drag & Drop (boolean)
     """
     QTabWidget.__init__(self, parent)
     
     if dnd:
         if not hasattr(self, 'setMovable'):
             self.__tabBar = E4DnDTabBar(self)
             self.connect(self.__tabBar, SIGNAL("tabMoveRequested(int, int)"), 
                          self.moveTab)
             self.setTabBar(self.__tabBar)
         else:
             self.__tabBar = E4WheelTabBar(self)
             self.setTabBar(self.__tabBar)
             self.setMovable(True)
     else:
         self.__tabBar = E4WheelTabBar(self)
         self.setTabBar(self.__tabBar)
     
     self.__lastCurrentIndex = -1
     self.__currentIndex = -1
     self.connect(self, SIGNAL("currentChanged(int)"), self.__currentChanged)
示例#3
0
    def focusInEvent(self, event):
        QTabWidget.focusInEvent(self, event)
        self.emit(SIGNAL("changeActualTab(QTabWidget)"), self)

        #custom behavior after the default
        editorWidget = self.currentWidget()
        if not editorWidget:
            return
        #Check never saved
        if editorWidget.newDocument:
            return
        #Check if we should ask to the user
        if not editorWidget.ask_if_externally_modified:
            return
        #Check external modifications!
        if editorWidget.check_external_modification() and \
            not self.question_already_open:
                #dont ask again if you are already asking!
            self.question_already_open = True
            val = QMessageBox.question(self, 'The file has changed on disc!',
                                self.tr("Do you want to reload it?"),
                                QMessageBox.Yes, QMessageBox.No)
            if val == QMessageBox.Yes:
                self.emit(SIGNAL("reloadFile()"))
            else:
                #dont ask again while the current file is open
                editorWidget.ask_if_externally_modified = False
        #we can ask again
        self.question_already_open = False
示例#4
0
    def __init__(self, parent):
        ##self.parent = parent
        QTabWidget.__init__(self, parent)
        self.addTab(PaveNumerique(parent), u" Pavé numérique ")
        self.addTab(Options(parent), u"Options")
        self.setTabPosition(QTabWidget.South)
        self.setStyleSheet(
            """
QTabBar::tab:selected {
background: white;
border: 1px solid #C4C4C3;
border-top-color: white; /* same as the pane color */
border-bottom-left-radius: 4px;
border-bottom-right-radius: 4px;
border-top-left-radius: 0px;
border-top-right-radius: 0px;
min-width: 8ex;
padding: 7px;
}
QStackedWidget {background:white}
QTabBar QToolButton {
background:white;
border: 1px solid #C4C4C3;
border-top-color: white; /* same as the pane color */
border-bottom-left-radius: 4px;
border-bottom-right-radius: 4px;
border-top-left-radius: 0px;
border-top-right-radius: 0px;
}
"""
        )
示例#5
0
class PluginErrorDialog(QDialog):
    """
    Dialog with tabs each tab is a python traceback
    """

    def __init__(self):
        QDialog.__init__(self)
        self.setWindowTitle(self.tr("Plugin error report"))
        self.resize(525, 400)
        vbox = QVBoxLayout(self)
        label = QLabel(self.tr("Some plugins have errors and were removed"))
        vbox.addWidget(label)
        self._tabs = QTabWidget()
        vbox.addWidget(self._tabs)
        hbox = QHBoxLayout()
        btnAccept = QPushButton(self.tr("Accept"))
        btnAccept.setMaximumWidth(100)
        hbox.addWidget(btnAccept)
        vbox.addLayout(hbox)
        # signals
        self.connect(btnAccept, SIGNAL("clicked()"), self.close)

    def add_traceback(self, plugin_name, traceback_msg):
        traceback_widget = TracebackWidget(traceback_msg)
        self._tabs.addTab(traceback_widget, plugin_name)
示例#6
0
 def __init__(self, parent):
     QTabWidget.__init__(self, parent)
     self.setTabsClosable(True)
     self.setMovable(True)
     self.setAcceptDrops(True)
     self.notOpening = True
     self.__lastOpened = []
     self._resyntax = []
     self.navigator = TabNavigator()
     self.setCornerWidget(self.navigator, Qt.TopRightCorner)
     self._parent = parent
     self.follow_mode = False
     self._change_map = {}
     #On some plataforms there are problem with focusInEvent
     self.question_already_open = False
     #Keep track of the tab titles
     self.titles = []
     self.dontLoopInExpandTitle = False
     self.connect(NinjaFileSystemWatcher,
         SIGNAL("fileChanged(int, QString)"), self._file_changed)
     self.connect(self, SIGNAL("tabCloseRequested(int)"), self.removeTab)
     self.connect(self.navigator.btnPrevious, SIGNAL("clicked()"),
         lambda: self._navigate_code(False))
     self.connect(self.navigator.btnNext, SIGNAL("clicked()"),
         lambda: self._navigate_code(True))
示例#7
0
class GertMainWindow(QMainWindow):
    """An application (window widget) with a list of "tasks" on the left side and a panel on the right side"""

    def __init__(self):
        """Constructor"""
        QMainWindow.__init__(self)

        self.resize(900, 700)
        self.setWindowTitle('gERT')

        self.tabs = QTabWidget()
        self.setCentralWidget(self.tabs)

        self.help_dock = HelpDock.getInstance()
        self.addDockWidget(Qt.RightDockWidgetArea, self.help_dock)


        self.__createMenu()
        self.save_function = None
        self.__fetchSettings()


    def setSaveFunction(self, save_function):
        """Set the function to be called when the save menu choice is selected."""
        self.save_function = save_function

    def addTab(self, name, tab_widget):
        self.tabs.addTab(tab_widget, name)

    def __save(self):
        if not self.save_function is None:
            self.save_function()

    def __createMenu(self):
        file_menu = self.menuBar().addMenu("&File")
        file_menu.addAction("Save Config File", self.__save)
        file_menu.addAction("Close", self.__quit)

        view_menu = self.menuBar().addMenu("&View")
        view_menu.addAction(self.help_dock.toggleViewAction())

    def __quit(self):
        self.__saveSettings()
        qApp.quit()

    def __saveSettings(self):
        settings = QSettings("Statoil", "ErtGui")
        settings.setValue("geometry", self.saveGeometry())
        settings.setValue("windowState", self.saveState())

    def closeEvent(self, event):
        #Use QT settings saving mechanism
        #settings stored in ~/.config/Statoil/ErtGui.conf
        self.__saveSettings()
        QMainWindow.closeEvent(self, event)

    def __fetchSettings(self):
        settings = QSettings("Statoil", "ErtGui")
        self.restoreGeometry(settings.value("geometry").toByteArray())
        self.restoreState(settings.value("windowState").toByteArray())
示例#8
0
    def __init__(self, parent=None, iface=None):
        QTabWidget.__init__(self, parent)
        self.setupUi(self)

        self._notif_bar = None
        self._ol_loaded = False
        self._overlay_layer = None
        self.sel_highlight = None
        self.memory_layer = None
        self._db_session = STDMDb.instance().session

        self.set_iface(iface)

        #Web config
        self._web_spatial_loader = WebSpatialLoader(self.spatial_web_view, self)

        #Connect signals
        self._web_spatial_loader.loadError.connect(self.on_spatial_browser_error)
        self._web_spatial_loader.loadProgress.connect(self.on_spatial_browser_loading)
        self._web_spatial_loader.loadFinished.connect(self.on_spatial_browser_finished)
        self._web_spatial_loader.zoomChanged.connect(self.on_map_zoom_level_changed)
        self.rbGMaps.toggled.connect(self.on_load_GMaps)
        self.rbOSM.toggled.connect(self.on_load_OSM)
        self.zoomSlider.sliderReleased.connect(self.on_zoom_changed)
        self.btnResetMap.clicked.connect(self.on_reset_web_map)
        self.btnSync.clicked.connect(self.on_sync_extents)
        QgsMapLayerRegistry.instance().layersWillBeRemoved.connect(self._on_overlay_to_be_removed)
示例#9
0
	def __init__(self):
		QTabWidget.__init__(self, None)
		self.ui = uic.loadUi ("./ui/chatWindow.ui", self)
		self.currentChanged.connect (self.resetTitle)
		self.connect(self, QtCore.SIGNAL('triggered()'), self.closeEvent)
		# user ID -> tab number
		self.tabs = {}
示例#10
0
文件: acerca_de.py 项目: ekimdev/edis
class AcercaDe(QDialog):

    def __init__(self, parent):
        QDialog.__init__(self, parent, Qt.WindowMinMaxButtonsHint)
        self.setWindowTitle(self.tr("Acerca de EDIS"))
        box = QVBoxLayout(self)
        label_logo = QLabel()
        label_logo.setPixmap(QPixmap(paths.ICONOS['icon']))
        label_titulo = QLabel(self.tr("<h1>EDIS</h1>\n<i>Simple Integrated "
                              "Development Environment</i>"))
        box_logo = QHBoxLayout()
        self.tabs = QTabWidget()
        self.tabs.addTab(AboutTab(), self.tr("Acerca de"))
        self.tabs.addTab(ReportarBugTab(), self.tr("Reportar bug"))
        box_logo.addWidget(label_logo)
        box_logo.addWidget(label_titulo)
        box.addLayout(box_logo)
        box.addWidget(self.tabs)

        box_boton = QHBoxLayout()
        box_boton.addSpacerItem(QSpacerItem(1, 0, QSizePolicy.Expanding))
        boton_ok = QPushButton(self.tr("Ok"))
        box_boton.addWidget(boton_ok)
        box.addLayout(box_boton)

        boton_ok.clicked.connect(self.close)
示例#11
0
class PluginPreferences(QWidget):
    """
    Plugins section widget in NINJA-IDE Preferences
    """

    def __init__(self):
        QWidget.__init__(self)
        self.plugin_manager = plugin_manager.PluginManager()
        vbox = QVBoxLayout(self)
        self._tabs = QTabWidget()
        vbox.addWidget(self._tabs)
        # load widgets
        self._load_widgets()

    def _load_widgets(self):
        logger.info("Loading plugins preferences widgets")
        # Collect the preferences widget for each active plugin
        for plugin in self.plugin_manager.get_active_plugins():
            plugin_name = plugin.metadata.get("name")
            try:
                preferences_widget = plugin.get_preferences_widget()
                if preferences_widget:
                    self._tabs.addTab(preferences_widget, plugin_name)
            except Exception, reason:
                logger.error("Unable to add the preferences widget (%s): %s", plugin_name, reason)
                continue
示例#12
0
 def __init__(self, parent):
     QTabWidget.__init__(self, parent)
     self.addTab(APropos(parent), u"À propos")
     self.addTab(Licence(parent), u"Licence")
     self.addTab(Notes(parent), u"Notes de version")
     self.addTab(Credits(parent), u"Crédits")
     self.setTabPosition(QTabWidget.South)
     self.setStyleSheet(
         """
     QTabBar::tab:selected {
     background: white;
     border: 1px solid #C4C4C3;
     border-top-color: white; /* same as the pane color */
     border-bottom-left-radius: 4px;
     border-bottom-right-radius: 4px;
     border-top-left-radius: 0px;
     border-top-right-radius: 0px;
     min-width: 8ex;
     padding: 7px;
     }
     QStackedWidget {background:white}
     QTabBar QToolButton {
     background:white;
     border: 1px solid #C4C4C3;
     border-top-color: white; /* same as the pane color */
     border-bottom-left-radius: 4px;
     border-bottom-right-radius: 4px;
     border-top-left-radius: 0px;
     border-top-right-radius: 0px;
     }
     """
     )
示例#13
0
    def _create_central_widget(self):

        tabs = QTabWidget()

        splitter = QSplitter()
        self.treeview = QTreeView()
        self.treeview.header().hide()
        self.treeview.resize(500, 0)
        splitter.addWidget(self.treeview)

        self.editwidget = QWidget()
        self.editwidget.setLayout(QVBoxLayout())
        self.editwidget.resize(300, 300)
        self.editwidget.setMinimumSize(300, 100)
        splitter.addWidget(self.editwidget)

        self.glwidget = GLWidget()
        splitter.addWidget(self.glwidget)

        splitter.setStretchFactor(0, 2)
        splitter.setStretchFactor(1, 2)
        splitter.setStretchFactor(2, 4)

        tabs.addTab(splitter, "Mesh")

        tabs.addTab(self._create_run(), "Run")

        self.setCentralWidget(tabs)
示例#14
0
    def __init__(self, connection):
        QTabWidget.__init__(self)

        self.connection = connection

        self.setupUi(self)
        self.tableProcessList.verticalHeader().hide()

        cur = self.connection.cursor()
        cur.execute("SHOW TABLES IN information_schema LIKE 'PROCESSLIST'")
        self.processListInInfoSchema = cur.rowcount

        if self.processListInInfoSchema:
            self.processListColumns = []
            cur.execute("SHOW COLUMNS IN information_schema.PROCESSLIST")
            for column in cur.fetchall():
                self.processListColumns.append(column[0])

            try:
                self.processListColumns.remove("TIME_MS")
                idx_time = self.processListColumns.index("TIME")
                self.processListColumns[idx_time] = "TIME + TIME_MS/1000 AS TIME"
            except ValueError:
                pass

        else:
            self.chkShowIdle.hide()

        self.refresh()

        self.timer = QTimer(self)
        self.timer.timeout.connect(self.on_timer_timeout)
        self.on_spinSeconds_valueChanged(self.spinSeconds.value())
        self.on_chkAutoRefresh_stateChanged()
示例#15
0
class MainWindow(myDialog):
    _dbViewWin = None
    
    def __init__(self, parent = None, *args, **kwargs):
        super(MainWindow, self).__init__(parent, *args, **kwargs)
        self.setWindowTitle("DocAnalyzer")
        self.myLayout.setContentsMargins(0, 0, 0, 0)
        
        self._tabWidget = QTabWidget(self)
        self._analyzerTab = AnalyzerTab(self._tabWidget)
        self._viewTab = ViewTab(self._tabWidget)
        self._viewTab.clicked.connect(self.openDBView)
        
        self._tabWidget.addTab(self._viewTab, "View")
        self._tabWidget.addTab(self._analyzerTab, "Analyze")

        self.myLayout.addRow(self._tabWidget)
#         self.setFixedSize(400, 300)

        
    def openDBView(self, dbName):
        if not dbName:
            messageBox(QMessageBox.Critical, "Fehler", "Der Name darf nicht leer sein!",  self, QMessageBox.Ok)
            return None
        
#         if self._dbViewWin == None:
        self._dbViewWin = ViewWindow(self, "%s.sqlite" %str(dbName))
        self._dbViewWin.show()
示例#16
0
    def __init__(self, parent=None):
        QTabWidget.__init__(self, parent)
        self.setTabPosition(QTabWidget.East)
        self.__ide = parent
        self._workingDirectory = ''

        #Searching the Preferences
        self._treeProjects = None
        if settings.SHOW_PROJECT_EXPLORER:
            self.add_tab_projects()
        self._treeSymbols = None
        if settings.SHOW_SYMBOLS_LIST:
            self.add_tab_symbols()
        self._inspector = None
        if settings.SHOW_WEB_INSPECTOR and settings.WEBINSPECTOR_SUPPORTED:
            self.add_tab_inspector()
        self._listErrors = None
        if settings.SHOW_ERRORS_LIST:
            self.add_tab_errors()

        #Now we see if there is any tab, if there is not, we hide the widget
        if self.count() == 0:
            self.hide()

        key = Qt.Key_1
        for i in xrange(10):
            if sys.platform == "darwin":
                short = TabShortcuts(
                    QKeySequence(Qt.CTRL + Qt.ALT + key), self, i)
            else:
                short = TabShortcuts(QKeySequence(Qt.ALT + key), self, i)
            key += 1
            self.connect(short, SIGNAL("activated()"), self._change_tab_index)
        short = TabShortcuts(QKeySequence(Qt.ALT + Qt.Key_0), self, 10)
        self.connect(short, SIGNAL("activated()"), self._change_tab_index)
示例#17
0
class PluginErrorDialog(QDialog):
    """
    Dialog with tabs each tab is a python traceback
    """
    def __init__(self):
        QDialog.__init__(self)
        self.setWindowTitle(translations.TR_PLUGIN_ERROR_REPORT)
        self.resize(600, 400)
        vbox = QVBoxLayout(self)
        label = QLabel(translations.TR_SOME_PLUGINS_REMOVED)
        vbox.addWidget(label)
        self._tabs = QTabWidget()
        vbox.addWidget(self._tabs)
        hbox = QHBoxLayout()
        btnAccept = QPushButton(translations.TR_ACCEPT)
        btnAccept.setMaximumWidth(100)
        hbox.addWidget(btnAccept)
        vbox.addLayout(hbox)
        #signals
        self.connect(btnAccept, SIGNAL("clicked()"), self.close)

    def add_traceback(self, plugin_name, traceback_msg):
        """Add a Traceback to the widget on a new tab"""
        traceback_widget = TracebackWidget(traceback_msg)
        self._tabs.addTab(traceback_widget, plugin_name)
示例#18
0
    def __init__(self, parent):
        QTabWidget.__init__(self, parent)
        self.setTabsClosable(True)
        self.setMovable(True)
        self.setAcceptDrops(True)
        self.notOpening = True
        self.__lastOpened = []
        self._resyntax = []
        self.navigator = TabNavigator()
        self.setCornerWidget(self.navigator, Qt.TopRightCorner)
        self._parent = parent
        # Configure tabs size behavior
#        self.setElideMode(Qt.ElideRight)
#        self.tabBar().setExpanding(True)
#        self.tabBar().setUsesScrollButtons(False)
        #On some plataforms there are problem with focusInEvent
        self.question_already_open = False
        #Keep track of the tab titles
        self.titles = []
        self.dontLoopInExpandTitle = False

        self.connect(self, SIGNAL("tabCloseRequested(int)"), self.removeTab)
        self.connect(self.navigator.btnPrevious, SIGNAL("clicked()"),
            lambda: self._navigate_code(False))
        self.connect(self.navigator.btnNext, SIGNAL("clicked()"),
            lambda: self._navigate_code(True))
示例#19
0
    def _init_gui_tab_and_groupbox_widgets(self):
        #top area for main stuff
        group_box_main_config = QGroupBox("Configuration")
        main_config_layout = QFormLayout()

        widget_delimiter = self._init_gui_delimiter_entries()

        tab_widget = QTabWidget()
        tab_widget.addTab(widget_delimiter, "delimiter")
        tab_widget.addTab(self.color_choosing_widget, "colors")

        #widget for bottom = save button
        save_widget = QWidget()
        layout_save_widget = QFormLayout()
        save_button = QPushButton("save", self)
        QObject.connect(save_button, SIGNAL('clicked()'), self._save_config)
        layout_save_widget.addWidget(save_button)
        save_widget.setLayout(layout_save_widget)
        main_config_layout.addRow(self.checkbox_start_with_last_opened_file)
        group_box_main_config.setLayout(main_config_layout)
        tab_widget_layout = QVBoxLayout()
        tab_widget_layout.addWidget(group_box_main_config)
        tab_widget_layout.addWidget(tab_widget)
        tab_widget_layout.addWidget(save_widget)
        return tab_widget_layout
示例#20
0
 def __init__(self, parent, actions=None, menu=None):
     QTabWidget.__init__(self, parent)
     if menu is None:
         self.menu = QMenu(self)
         if actions:
             add_actions(self.menu, actions)
     else:
         self.menu = menu
示例#21
0
    def __init__(self, connection, dbName):
        QTabWidget.__init__(self)

        self.connection = connection
        self.dbName = dbName

        self.setupUi(self)
        self.groupProgress.setVisible(False)
示例#22
0
    def __init__( self, parent = None ):
        QTabWidget.__init__( self, parent )

        self.setDocumentMode( True )
        self.setTabsClosable( True )
        self.setupActions()

        self.connect( self, SIGNAL( 'tabCloseRequested(int)' ), self.slotClose )
示例#23
0
 def __init__(self, parent):
     self.parent = parent
     self.feuille = parent.feuille
     QTabWidget.__init__(self, parent)
     self.description = ProprietesDescription(self)
     self.addTab(self.description, u"Description")
     self.statistiques = ProprietesStatistiques(self)
     self.addTab(self.statistiques, u"Statistiques")
示例#24
0
 def setup_page(self):
     tabs = QTabWidget()
     names = self.get_option("names")
     names.pop(names.index(CUSTOM_COLOR_SCHEME_NAME))
     names.insert(0, CUSTOM_COLOR_SCHEME_NAME)
     fieldnames = {
                   "background":     _("Background:"),
                   "currentline":    _("Current line:"),
                   "occurence":      _("Occurence:"),
                   "ctrlclick":      _("Link:"),
                   "sideareas":      _("Side areas:"),
                   "matched_p":      _("Matched parentheses:"),
                   "unmatched_p":    _("Unmatched parentheses:"),
                   "normal":         _("Normal text:"),
                   "keyword":        _("Keyword:"),
                   "builtin":        _("Builtin:"),
                   "definition":     _("Definition:"),
                   "comment":        _("Comment:"),
                   "string":         _("String:"),
                   "number":         _("Number:"),
                   "instance":       _("Instance:"),
                   }
     from SMlib.widgets.sourcecode import syntaxhighlighters
     assert all([key in fieldnames
                 for key in syntaxhighlighters.COLOR_SCHEME_KEYS])
     for tabname in names:
         cs_group = QGroupBox(_("Color scheme"))
         cs_layout = QGridLayout()
         for row, key in enumerate(syntaxhighlighters.COLOR_SCHEME_KEYS):
             option = "%s/%s" % (tabname, key)
             value = self.get_option(option)
             name = fieldnames[key]
             if isinstance(value, basestring):
                 label, clayout = self.create_coloredit(name, option,
                                                        without_layout=True)
                 label.setAlignment(Qt.AlignRight|Qt.AlignVCenter)
                 cs_layout.addWidget(label, row+1, 0)
                 cs_layout.addLayout(clayout, row+1, 1)
             else:
                 label, clayout, cb_bold, cb_italic = self.create_scedit(
                                         name, option, without_layout=True)
                 label.setAlignment(Qt.AlignRight|Qt.AlignVCenter)
                 cs_layout.addWidget(label, row+1, 0)
                 cs_layout.addLayout(clayout, row+1, 1)
                 cs_layout.addWidget(cb_bold, row+1, 2)
                 cs_layout.addWidget(cb_italic, row+1, 3)
         cs_group.setLayout(cs_layout)
         if tabname in sh.COLOR_SCHEME_NAMES:
             def_btn = self.create_button(_("Reset to default values"),
                                      lambda: self.reset_to_default(tabname))
             tabs.addTab(self.create_tab(cs_group, def_btn), tabname)
         else:
             tabs.addTab(self.create_tab(cs_group), tabname)
     
     vlayout = QVBoxLayout()
     vlayout.addWidget(tabs)
     self.setLayout(vlayout)
示例#25
0
    def __init__(self):
        QTabWidget.__init__(self)
        TabCentralGeneric.__init__(self)
        self.setTabsClosable(True)
        self.setMovable(True)
        self.setAcceptDrops(True)
        self.notOpening = True

        self.connect(self, SIGNAL("tabCloseRequested(int)"), self._close_tab)
示例#26
0
    def __init__(self, main):
        QTabWidget.__init__(self)
        PropertiesGeneric.__init__(self)
        self.setTabPosition(QTabWidget.East)

        self._treeProjects = TreeProjectsWidget(main)
        self._treeSymbols = TreeSymbolsWidget()
        self.addTab(self._treeProjects, 'Projects')
        self.addTab(self._treeSymbols, 'Symbols')
示例#27
0
 def mousePressEvent(self, event):
     """Override Qt method"""
     if event.button() == Qt.MidButton:
         index = self.tabBar().tabAt(event.pos())
         if index >= 0:
             self.emit(SIGNAL("close_tab(int)"), index)
             event.accept()
             return
     QTabWidget.mousePressEvent(self, event)
示例#28
0
    def __init__(self):
        QTabWidget.__init__(self)
        self.setWindowTitle("Case Management")
        self.setMinimumWidth(600)

        self.addCreateNewCaseTab()
        self.addInitializeFromScratchTab()
        self.addInitializeFromExistingTab()
        self.addShowCaseInfo()
示例#29
0
 def mousePressEvent(self, event):
     QTabWidget.mousePressEvent(self, event)
     if self.follow_mode:
         return
     if event.button() == Qt.RightButton:
         index = self.tabBar().tabAt(event.pos())
         self.setCurrentIndex(index)
         widget = self.widget(index)
         if type(widget) is editor.Editor:
             #show menu
             menu = QMenu()
             actionAdd = menu.addAction(self.tr("Add to Project..."))
             actionRun = menu.addAction(self.tr("Run this File!"))
             menuSyntax = menu.addMenu(self.tr("Change Syntax"))
             self._create_menu_syntax(menuSyntax)
             menu.addSeparator()
             actionClose = menu.addAction(self.tr("Close This Tab"))
             actionCloseAll = menu.addAction(self.tr("Close All Tabs"))
             actionCloseAllNotThis = menu.addAction(
                 self.tr("Close Other Tabs"))
             menu.addSeparator()
             actionSplitH = menu.addAction(
                 self.tr("Split this Tab (Vertically)"))
             actionSplitV = menu.addAction(
                 self.tr("Split this Tab (Horizontally)"))
             #Connect split actions
             self.connect(actionSplitH, SIGNAL("triggered()"),
                 lambda: self._split_this_tab(True))
             self.connect(actionSplitV, SIGNAL("triggered()"),
                 lambda: self._split_this_tab(False))
             menu.addSeparator()
             actionCopyPath = menu.addAction(
                 self.tr("Copy file location to Clipboard"))
             actionReopen = menu.addAction(
                 self.tr("Reopen last closed File"))
             if len(self.__lastOpened) == 0:
                 actionReopen.setEnabled(False)
             #Connect actions
             self.connect(actionRun, SIGNAL("triggered()"),
                 self._run_this_file)
             self.connect(actionAdd, SIGNAL("triggered()"),
                 self._add_to_project)
             self.connect(actionClose, SIGNAL("triggered()"),
                 lambda: self.removeTab(index))
             self.connect(actionCloseAllNotThis, SIGNAL("triggered()"),
                 self._close_all_tabs_except_this)
             self.connect(actionCloseAll, SIGNAL("triggered()"),
                 self._close_all_tabs)
             self.connect(actionCopyPath, SIGNAL("triggered()"),
                 self._copy_file_location)
             self.connect(actionReopen, SIGNAL("triggered()"),
                 self._reopen_last_tab)
             menu.exec_(event.globalPos())
     if event.button() == Qt.MidButton:
         index = self.tabBar().tabAt(event.pos())
         self.removeTab(index)
示例#30
0
 def __init__(self, parent):
     self.parent = parent
     self.objets = parent.objets
     QTabWidget.__init__(self, parent)
     self.affichage = ProprietesAffichage(self)
     self.addTab(self.affichage, u"Affichage")
     self.infos = ProprietesInfos(self)
     self.addTab(self.infos, u"Informations")
     self.avance = ProprietesAvance(self)
     self.addTab(self.avance, u"Avancé")
示例#31
0
class WeatherStation(QApplication):
    HOST = "localhost"
    PORT = 4223

    ipcon = None
    lcd = None
    al = None
    al_v2 = None
    hum = None
    baro = None

    projects = []
    active_project = None

    error_msg = None

    def __init__(self, args):
        super(QApplication, self).__init__(args)

        self.error_msg = QErrorMessage()
        self.ipcon = IPConnection()

        signal.signal(signal.SIGINT, self.exit_demo)
        signal.signal(signal.SIGTERM, self.exit_demo)

        timer = QTimer(self)
        timer.setSingleShot(True)
        timer.timeout.connect(self.connect)
        timer.start(1)

        self.lcd_timer = QTimer(self)
        self.lcd_timer.timeout.connect(self.mute_lcd)
        self.lcd_timer.start(10000)

    def exit_demo(self, signl=None, frme=None):
        try:
            self.ipcon.disconnect()
            self.timer.stop()
            self.tabs.destroy()
        except:
            pass

        sys.exit()

    def open_gui(self):
        self.main = MainWindow(self)
        self.main.setFixedSize(930, 530)
        self.main.setWindowIcon(
            QIcon(load_pixmap('starter_kit_weather_station_demo-icon.png')))

        self.tabs = QTabWidget()

        widget = QWidget()
        layout = QVBoxLayout()
        layout.addWidget(self.tabs)
        widget.setLayout(layout)

        self.main.setCentralWidget(widget)

        self.projects.append(ProjectEnvDisplay(self.tabs, self))
        self.projects.append(ProjectStatistics(self.tabs, self))
        self.projects.append(ProjectXively(self.tabs, self))

        self.tabs.addTab(self.projects[0], "Display Environment Measurements")
        self.tabs.addTab(self.projects[1],
                         "Show Statistics with Button Control")
        self.tabs.addTab(self.projects[2], "Connect to Xively")

        self.active_project = self.projects[0]

        self.tabs.currentChanged.connect(self.tabChangedSlot)
        self.tabs.setCurrentIndex(1)

        self.main.setWindowTitle("Starter Kit: Weather Station Demo " +
                                 DEMO_VERSION)
        self.main.show()

    def connect(self):
        try:
            self.ipcon.connect(WeatherStation.HOST, WeatherStation.PORT)
        except Error as e:
            self.error_msg.showMessage('Connection Error: ' +
                                       str(e.description) +
                                       "\nBrickd installed and running?")
            return
        except socket.error as e:
            self.error_msg.showMessage('Socket error: ' + str(e) +
                                       "\nBrickd installed and running?")
            return

        self.ipcon.register_callback(IPConnection.CALLBACK_ENUMERATE,
                                     self.cb_enumerate)
        self.ipcon.register_callback(IPConnection.CALLBACK_CONNECTED,
                                     self.cb_connected)

        try:
            self.ipcon.enumerate()
        except Error as e:
            self.error_msg.showMessage('Enumerate Error: ' +
                                       str(e.description))
            return

        self.open_gui()

    def tabChangedSlot(self, tabIndex):

        if self.lcd is not None:
            self.lcd.clear_display()

        self.active_project = self.projects[tabIndex]

    def cb_illuminance(self, illuminance):
        for p in self.projects:
            p.update_illuminance(illuminance / 10.0)

    def cb_illuminance_v2(self, illuminance):
        for p in self.projects:
            p.update_illuminance(illuminance / 100.0)

    def cb_humidity(self, humidity):
        for p in self.projects:
            p.update_humidity(humidity / 10.0)

    def cb_air_pressure(self, air_pressure):
        for p in self.projects:
            p.update_air_pressure(air_pressure / 1000.0)

        try:
            temperature = self.baro.get_chip_temperature()
        except Error as e:
            print('Could not get temperature: ' + str(e.description))
            return

        for p in self.projects:
            p.update_temperature(temperature / 100.0)

    def configure_custom_chars(self):
        c = [[0x00 for x in range(8)] for y in range(8)]

        c[0] = [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff]
        c[1] = [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff]
        c[2] = [0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff]
        c[3] = [0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]
        c[4] = [0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff]
        c[5] = [0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]
        c[6] = [0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]
        c[7] = [0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]

        for i in range(len(c)):
            self.lcd.set_custom_character(i, c[i])

    def cb_button_pressed(self, button):
        if self.lcd.is_backlight_on():
            for p in self.projects:
                p.button_pressed(button)
        else:
            self.lcd.backlight_on()
            self.lcd_timer.start()

    def mute_lcd(self):
        self.lcd.backlight_off()

    def cb_enumerate(self, uid, connected_uid, position, hardware_version,
                     firmware_version, device_identifier, enumeration_type):
        if enumeration_type == IPConnection.ENUMERATION_TYPE_CONNECTED or \
           enumeration_type == IPConnection.ENUMERATION_TYPE_AVAILABLE:
            if device_identifier == LCD20x4.DEVICE_IDENTIFIER:
                try:
                    self.lcd = LCD20x4(uid, self.ipcon)
                    self.lcd.clear_display()
                    self.lcd.backlight_on()
                    self.lcd.register_callback(
                        self.lcd.CALLBACK_BUTTON_PRESSED,
                        self.cb_button_pressed)
                    self.configure_custom_chars()
                except Error as e:
                    self.error_msg.showMessage('LCD 20x4 init failed: ' +
                                               str(e.description))
                    self.lcd = None
            elif device_identifier == AmbientLight.DEVICE_IDENTIFIER:
                try:
                    self.al = AmbientLight(uid, self.ipcon)
                    self.al.set_illuminance_callback_period(1000)
                    self.al.register_callback(self.al.CALLBACK_ILLUMINANCE,
                                              self.cb_illuminance)
                except Error as e:
                    self.error_msg.showMessage('Ambient Light init failed: ' +
                                               str(e.description))
                    self.al = None
            elif device_identifier == AmbientLightV2.DEVICE_IDENTIFIER:
                try:
                    self.al_v2 = AmbientLightV2(uid, self.ipcon)
                    self.al_v2.set_configuration(
                        AmbientLightV2.ILLUMINANCE_RANGE_64000LUX,
                        AmbientLightV2.INTEGRATION_TIME_200MS)
                    self.al_v2.set_illuminance_callback_period(1000)
                    self.al_v2.register_callback(
                        self.al_v2.CALLBACK_ILLUMINANCE,
                        self.cb_illuminance_v2)
                except Error as e:
                    self.error_msg.showMessage(
                        'Ambient Light 2.0 init failed: ' + str(e.description))
                    self.al = None
            elif device_identifier == Humidity.DEVICE_IDENTIFIER:
                try:
                    self.hum = Humidity(uid, self.ipcon)
                    self.hum.set_humidity_callback_period(1000)
                    self.hum.register_callback(self.hum.CALLBACK_HUMIDITY,
                                               self.cb_humidity)
                except Error as e:
                    self.error_msg.showMessage('Humidity init failed: ' +
                                               str(e.description))
                    self.hum = None
            elif device_identifier == Barometer.DEVICE_IDENTIFIER:
                try:
                    self.baro = Barometer(uid, self.ipcon)
                    self.baro.set_air_pressure_callback_period(1000)
                    self.baro.register_callback(
                        self.baro.CALLBACK_AIR_PRESSURE, self.cb_air_pressure)
                except Error as e:
                    self.error_msg.showMessage('Barometer init failed: ' +
                                               str(e.description))
                    self.baro = None

    def cb_connected(self, connected_reason):
        if connected_reason == IPConnection.CONNECT_REASON_AUTO_RECONNECT:

            while True:
                try:
                    self.ipcon.enumerate()
                    break
                except Error as e:
                    self.error_msg.showMessage('Enumerate Error: ' +
                                               str(e.description))
                    time.sleep(1)
示例#32
0
文件: db_manager.py 项目: jarped/QGIS
    def setupUi(self):
        self.setWindowTitle(self.tr("DB Manager"))
        self.setWindowIcon(QIcon(":/db_manager/icon"))
        self.resize(QSize(700, 500).expandedTo(self.minimumSizeHint()))

        # create central tab widget and add the first 3 tabs: info, table and preview
        self.tabs = QTabWidget()
        self.info = InfoViewer(self)
        self.tabs.addTab(self.info, self.tr("Info"))
        self.table = TableViewer(self)
        self.tabs.addTab(self.table, self.tr("Table"))
        self.preview = LayerPreview(self)
        self.tabs.addTab(self.preview, self.tr("Preview"))
        self.setCentralWidget(self.tabs)

        # display close button for all tabs but the first 3 ones, i.e.
        # HACK: just hide the close button where not needed (GS)
        self.tabs.setTabsClosable(True)
        self.tabs.tabCloseRequested.connect(self.close_tab)
        tabbar = self.tabs.tabBar()
        for i in range(3):
            btn = tabbar.tabButton(i, QTabBar.RightSide) if tabbar.tabButton(
                i, QTabBar.RightSide) else tabbar.tabButton(
                    i, QTabBar.LeftSide)
            btn.resize(0, 0)
            btn.hide()

        # Creates layout for message bar
        self.layout = QGridLayout(self.info)
        self.layout.setContentsMargins(0, 0, 0, 0)
        spacerItem = QSpacerItem(20, 40, QSizePolicy.Minimum,
                                 QSizePolicy.Expanding)
        self.layout.addItem(spacerItem, 1, 0, 1, 1)
        # init messageBar instance
        self.infoBar = QgsMessageBar(self.info)
        sizePolicy = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed)
        self.infoBar.setSizePolicy(sizePolicy)
        self.layout.addWidget(self.infoBar, 0, 0, 1, 1)

        # create database tree
        self.dock = QDockWidget("Tree", self)
        self.dock.setObjectName("DB_Manager_DBView")
        self.dock.setFeatures(QDockWidget.DockWidgetMovable)
        self.tree = DBTree(self)
        self.dock.setWidget(self.tree)
        self.addDockWidget(Qt.LeftDockWidgetArea, self.dock)

        # create status bar
        self.statusBar = QStatusBar(self)
        self.setStatusBar(self.statusBar)

        # create menus
        self.menuBar = QMenuBar(self)
        self.menuDb = QMenu(self.tr("&Database"), self)
        self.menuBar.addMenu(self.menuDb)
        self.menuSchema = QMenu(self.tr("&Schema"), self)
        actionMenuSchema = self.menuBar.addMenu(self.menuSchema)
        self.menuTable = QMenu(self.tr("&Table"), self)
        actionMenuTable = self.menuBar.addMenu(self.menuTable)
        self.menuHelp = None  # QMenu(self.tr("&Help"), self)
        # actionMenuHelp = self.menuBar.addMenu(self.menuHelp)

        self.setMenuBar(self.menuBar)

        # create toolbar
        self.toolBar = QToolBar("Default", self)
        self.toolBar.setObjectName("DB_Manager_ToolBar")
        self.addToolBar(self.toolBar)

        # create menus' actions

        # menu DATABASE
        sep = self.menuDb.addSeparator()
        sep.setObjectName("DB_Manager_DbMenu_placeholder")
        sep.setVisible(False)

        self.actionRefresh = self.menuDb.addAction(
            QIcon(":/db_manager/actions/refresh"), self.tr("&Refresh"),
            self.refreshActionSlot, QKeySequence("F5"))
        self.actionSqlWindow = self.menuDb.addAction(
            QIcon(":/db_manager/actions/sql_window"), self.tr("&SQL window"),
            self.runSqlWindow, QKeySequence("F2"))
        self.menuDb.addSeparator()
        self.actionClose = self.menuDb.addAction(QIcon(), self.tr("&Exit"),
                                                 self.close,
                                                 QKeySequence("CTRL+Q"))

        # menu SCHEMA
        sep = self.menuSchema.addSeparator()
        sep.setObjectName("DB_Manager_SchemaMenu_placeholder")
        sep.setVisible(False)

        actionMenuSchema.setVisible(False)

        # menu TABLE
        sep = self.menuTable.addSeparator()
        sep.setObjectName("DB_Manager_TableMenu_placeholder")
        sep.setVisible(False)

        self.actionImport = self.menuTable.addAction(
            QIcon(":/db_manager/actions/import"),
            self.tr("&Import layer/file"), self.importActionSlot)
        self.actionExport = self.menuTable.addAction(
            QIcon(":/db_manager/actions/export"), self.tr("&Export to file"),
            self.exportActionSlot)
        self.menuTable.addSeparator()
        #self.actionShowSystemTables = self.menuTable.addAction(self.tr("Show system tables/views"), self.showSystemTables)
        #self.actionShowSystemTables.setCheckable(True)
        #self.actionShowSystemTables.setChecked(True)
        actionMenuTable.setVisible(False)

        # add actions to the toolbar
        self.toolBar.addAction(self.actionRefresh)
        self.toolBar.addAction(self.actionSqlWindow)
        self.toolBar.addAction(self.actionImport)
        self.toolBar.addAction(self.actionExport)
示例#33
0
class Dialog(QDialog):
    def __init__(self, parent=None):
        super(Dialog, self).__init__(parent)

        self._info = None
        self._text = ''
        self._convertedtext = ''
        self._encoding = None
        self.mainwindow = parent

        self.fromVersionLabel = QLabel()
        self.fromVersion = QLineEdit()
        self.reason = QLabel()
        self.toVersionLabel = QLabel()
        self.toVersion = QLineEdit()
        self.lilyChooser = lilychooser.LilyChooser()
        self.messages = QTextBrowser()
        self.diff = QTextBrowser(lineWrapMode=QTextBrowser.NoWrap)
        self.uni_diff = QTextBrowser(lineWrapMode=QTextBrowser.NoWrap)
        self.copyCheck = QCheckBox(
            checked=QSettings().value('convert_ly/copy_messages', True, bool))
        self.tabw = QTabWidget()

        self.tabw.addTab(self.messages, '')
        self.tabw.addTab(self.diff, '')
        self.tabw.addTab(self.uni_diff, '')

        self.buttons = QDialogButtonBox(QDialogButtonBox.Reset
                                        | QDialogButtonBox.Save
                                        | QDialogButtonBox.Ok
                                        | QDialogButtonBox.Cancel)
        self.buttons.button(QDialogButtonBox.Ok).clicked.connect(self.accept)
        self.buttons.rejected.connect(self.reject)
        self.buttons.button(QDialogButtonBox.Reset).clicked.connect(self.run)
        self.buttons.button(QDialogButtonBox.Save).clicked.connect(
            self.saveFile)

        layout = QVBoxLayout()
        self.setLayout(layout)

        grid = QGridLayout()
        grid.addWidget(self.fromVersionLabel, 0, 0)
        grid.addWidget(self.fromVersion, 0, 1)
        grid.addWidget(self.reason, 0, 2, 1, 3)
        grid.addWidget(self.toVersionLabel, 1, 0)
        grid.addWidget(self.toVersion, 1, 1)
        grid.addWidget(self.lilyChooser, 1, 3, 1, 2)

        layout.addLayout(grid)
        layout.addWidget(self.tabw)
        layout.addWidget(self.copyCheck)
        layout.addWidget(widgets.Separator())
        layout.addWidget(self.buttons)

        app.translateUI(self)
        qutil.saveDialogSize(self, 'convert_ly/dialog/size', QSize(600, 300))
        app.settingsChanged.connect(self.readSettings)
        self.readSettings()
        self.finished.connect(self.saveCopyCheckSetting)
        self.lilyChooser.currentIndexChanged.connect(
            self.slotLilyPondVersionChanged)
        self.slotLilyPondVersionChanged()

    def translateUI(self):
        self.fromVersionLabel.setText(_("From version:"))
        self.toVersionLabel.setText(_("To version:"))
        self.copyCheck.setText(_("Save convert-ly messages in document"))
        self.copyCheck.setToolTip(
            _("If checked, the messages of convert-ly are appended as a "
              "comment to the end of the document."))
        self.tabw.setTabText(0, _("&Messages"))
        self.tabw.setTabText(1, _("&Changes"))
        self.tabw.setTabText(2, _("&Diff"))
        self.buttons.button(QDialogButtonBox.Reset).setText(_("Run Again"))
        self.buttons.button(QDialogButtonBox.Save).setText(_("Save as file"))
        self.setCaption()

    def saveCopyCheckSetting(self):
        QSettings().setValue('convert_ly/copy_messages',
                             self.copyCheck.isChecked())

    def readSettings(self):
        font = textformats.formatData('editor').font
        self.diff.setFont(font)
        diffFont = QFont("Monospace")
        diffFont.setStyleHint(QFont.TypeWriter)
        self.uni_diff.setFont(diffFont)

    def slotLilyPondVersionChanged(self):
        self.setLilyPondInfo(self.lilyChooser.lilyPondInfo())

    def setCaption(self):
        version = self._info and self._info.versionString() or _("<unknown>")
        title = _("Convert-ly from LilyPond {version}").format(version=version)
        self.setWindowTitle(app.caption(title))

    def setLilyPondInfo(self, info):
        self._info = info
        self.setCaption()
        self.toVersion.setText(info.versionString())
        self.setConvertedText()
        self.setDiffText()
        self.messages.clear()

    def setConvertedText(self, text=''):
        self._convertedtext = text
        self.buttons.button(QDialogButtonBox.Ok).setEnabled(bool(text))
        if text:
            self.diff.setHtml(
                htmldiff.htmldiff(self._text,
                                  text,
                                  _("Current Document"),
                                  _("Converted Document"),
                                  wrapcolumn=100))
        else:
            self.diff.clear()

    def setDiffText(self, text=''):
        if text:
            difflist = list(
                difflib.unified_diff(self._text.split('\n'), text.split('\n'),
                                     _("Current Document"),
                                     _("Converted Document")))
            diffHLstr = self.diffHighl(difflist)
            self.uni_diff.setHtml(diffHLstr)
        else:
            self.uni_diff.clear()

    def convertedText(self):
        return self._convertedtext or ''

    def setDocument(self, doc):
        v = documentinfo.docinfo(doc).version_string()
        if v:
            self.fromVersion.setText(v)
            self.reason.setText(_("(set in document)"))
        else:
            self.reason.clear()
        self._text = doc.toPlainText()
        self._encoding = doc.encoding() or 'UTF-8'
        self.setConvertedText()
        self.setDiffText()

    def run(self):
        """Runs convert-ly (again)."""
        fromVersion = self.fromVersion.text()
        toVersion = self.toVersion.text()
        if not fromVersion or not toVersion:
            self.messages.setPlainText(
                _("Both 'from' and 'to' versions need to be set."))
            return
        info = self._info
        command = info.toolcommand(info.ly_tool('convert-ly'))
        command += ['-f', fromVersion, '-t', toVersion, '-']

        # if the user wants english messages, do it also here: LANGUAGE=C
        env = None
        if os.name == "nt":
            # Python 2.7 subprocess on Windows chokes on unicode in env
            env = util.bytes_environ()
        else:
            env = dict(os.environ)
        if sys.platform.startswith('darwin'):
            try:
                del env['PYTHONHOME']
            except KeyError:
                pass
            try:
                del env['PYTHONPATH']
            except KeyError:
                pass
        if QSettings().value("lilypond_settings/no_translation", False, bool):
            if os.name == "nt":
                # Python 2.7 subprocess on Windows chokes on unicode in env
                env[b'LANGUAGE'] = b'C'
            else:
                env['LANGUAGE'] = 'C'

        with qutil.busyCursor():
            try:
                proc = subprocess.Popen(command,
                                        env=env,
                                        stdin=subprocess.PIPE,
                                        stdout=subprocess.PIPE,
                                        stderr=subprocess.PIPE)
                out, err = proc.communicate(
                    util.platform_newlines(self._text).encode(self._encoding))
            except OSError as e:
                self.messages.setPlainText(
                    _("Could not start {convert_ly}:\n\n"
                      "{message}\n").format(convert_ly=command[0], message=e))
                return
            out = util.universal_newlines(out.decode('UTF-8'))
            err = util.universal_newlines(err.decode('UTF-8'))
            self.messages.setPlainText(err)
            self.setConvertedText(out)
            self.setDiffText(out)
            if not out or self._convertedtext == self._text:
                self.messages.append('\n' +
                                     _("The document has not been changed."))

    def saveFile(self):
        """Save content in tab as file"""
        tabdata = self.getTabData(self.tabw.currentIndex())
        doc = self.mainwindow.currentDocument()
        orgname = doc.url().toLocalFile()
        filename = os.path.splitext(
            orgname)[0] + '[' + tabdata.filename + ']' + '.' + tabdata.ext
        caption = app.caption(_("dialog title", "Save File"))
        filetypes = '{0} (*.txt);;{1} (*.htm);;{2} (*)'.format(
            _("Text Files"), _("HTML Files"), _("All Files"))
        filename = QFileDialog.getSaveFileName(self.mainwindow, caption,
                                               filename, filetypes)
        if not filename:
            return False  # cancelled
        with open(filename, 'wb') as f:
            f.write(tabdata.text.encode('utf-8'))

    def getTabData(self, index):
        """Get content of current tab from current index"""
        if index == 0:
            return FileInfo('message', 'txt', self.messages.toPlainText())
        elif index == 1:
            return FileInfo('html-diff', 'html', self.diff.toHtml())
        elif index == 2:
            return FileInfo('uni-diff', 'diff', self.uni_diff.toPlainText())

    def diffHighl(self, difflist):
        """Return highlighted version of input."""
        result = []
        for l in difflist:
            if l.startswith('-'):
                s = '<span style="color: red; white-space: pre-wrap;">'
            elif l.startswith('+'):
                s = '<span style="color: green; white-space: pre-wrap;">'
            else:
                s = '<span style="white-space: pre-wrap;">'
            h = l.replace('&', '&amp;').replace('<',
                                                '&lt;').replace('>', '&gt;')
            result.append(s + h + '</span>')
        return '<br>'.join(result)
示例#34
0
    def createWidgets (self):
        """
        QtWidgets creation
        
        QTreeWidget (Id, Name, Init at, Sched at, Start at, Stop at, User, Duration)
         _______________
        |    QToolBar   |
        |---------------|
         _______________
        |               |
        |---------------|
        |               |
        |               |
        |_______________|
        """

        #self.mainTab = QTabWidget()


        layout = QVBoxLayout()

        topLayout = QHBoxLayout()

        # waiting tree widget
        self.tabWaiting = QTabWidget()

        #self.waitingBox = QGroupBox("Waiting")
        self.waitingBox = QFrame(self)
        self.testWaiting = QTreeWidget(self)
        self.testWaiting.setSelectionMode(QAbstractItemView.ExtendedSelection)
        self.waitingToolbar = QToolBar(self)
        self.labelsWaiting = [ self.tr("No.") , self.tr("Group"), self.tr("Schedulation Type"),
                              self.tr("Project"), self.tr("Name") , self.tr("Next run"), 
                              self.tr("Repeat"), self.tr("Probes"), self.tr("Notifications") , 
                              self.tr("Tests result"), self.tr("Author")  ]
        self.testWaiting.setHeaderLabels(self.labelsWaiting)
        self.testWaiting.setIndentation(10)
        self.testWaiting.setContextMenuPolicy(Qt.CustomContextMenu)
        layoutWaiting = QVBoxLayout()
        layoutWaiting.addWidget(self.waitingToolbar)
        layoutWaiting.addWidget(self.testWaiting)
        self.waitingBox.setLayout(layoutWaiting)

        self.tabWaiting.addTab( self.waitingBox, "Scheduled" )

        self.enqueuedBox = QFrame(self)
        layoutEnqueued = QVBoxLayout()

        self.testEnqueued = QTreeWidget(self)
        self.labelsEnqueued = [ self.tr("Group of tests")  ] 
        self.testEnqueued.setHeaderLabels(self.labelsEnqueued)
        self.testEnqueued.setIndentation(10)

        layoutEnqueued.addWidget(self.testEnqueued)
        self.enqueuedBox.setLayout(layoutEnqueued)
        self.tabWaiting.addTab( self.enqueuedBox, "Waiting" )


        # current tree widget
        self.currentBox = QGroupBox("Running")
        self.testManager = QTreeWidget(self)
        self.testManager.setSelectionMode(QAbstractItemView.ExtendedSelection)
        self.dockToolbar = QToolBar(self)
        self.labels  = [ self.tr("No."), self.tr("Project"), self.tr("Name"), self.tr("Started at"),
                         self.tr("Author"), self.tr("Recursive") ]
        self.testManager.setHeaderLabels(self.labels)
        self.testManager.setIndentation(10)
        self.testManager.setContextMenuPolicy(Qt.CustomContextMenu)
        layoutCurrent = QVBoxLayout()
        layoutCurrent.addWidget(self.dockToolbar)
        layoutCurrent.addWidget(self.testManager)
        self.currentBox.setLayout(layoutCurrent)
        
        v_splitter = QSplitter(self)      
        v_splitter.addWidget( self.tabWaiting )
        v_splitter.addWidget( self.currentBox ) 
        topLayout.addWidget(v_splitter)

        # history tree widget
        self.historyBox = QGroupBox("History")
        self.testHistory = QTreeWidget(self)
        self.historyToolbar = QToolBar(self)
        self.labels2 = [ self.tr("Id"),  self.tr("Schedulation Type"),  self.tr("Project") , self.tr("Name"), 
                         self.tr("Sched at"), self.tr("Run start"), self.tr("Run end"), self.tr("Author"), 
                         self.tr("Duration (in sec.)"), self.tr("Run Result") ]
        self.testHistory.setHeaderLabels(self.labels2)
        
        self.statsBox = QGroupBox("Summary")
        self.nbRunningLabel = QLabel("0")
        self.nbWaitingLabel = QLabel("0")
        self.nbHistoryLabel = QLabel("0")
        self.nbCompleteHistoryLabel = QLabel("0")
        self.nbErrorHistoryLabel = QLabel("0")
        self.nbKilledHistoryLabel = QLabel("0")
        self.nbCancelledHistoryLabel = QLabel("0")
        layout2 = QFormLayout()
        layout2.addRow(QLabel("Running"), self.nbRunningLabel )
        layout2.addRow(QLabel("Waiting"), self.nbWaitingLabel )
        layout2.addRow( QLabel(""), QLabel("") )
        layout2.addRow(QLabel("History"), self.nbHistoryLabel )
        layout2.addRow(QLabel(" - COMPLETE"), self.nbCompleteHistoryLabel )
        layout2.addRow(QLabel(" - ERROR"), self.nbErrorHistoryLabel )
        layout2.addRow(QLabel(" - KILLED"), self.nbKilledHistoryLabel )
        layout2.addRow(QLabel(" - CANCELLED"), self.nbCancelledHistoryLabel )
        self.statsBox.setLayout(layout2)

        layoutHistory = QVBoxLayout()
        layoutHistory.addWidget(self.historyToolbar)
        layoutHistory.addWidget(self.testHistory)
        self.historyBox.setLayout(layoutHistory)
        
        subLayout = QHBoxLayout()
        subLayout.addWidget(self.historyBox)
        subLayout.addWidget(self.statsBox)

        frame_left = QFrame(self)
        frame_left.setFrameShape(QFrame.NoFrame)
        frame_left.setLayout(topLayout)

        frame_right = QFrame(self)
        frame_right.setFrameShape(QFrame.NoFrame)
        frame_right.setLayout(subLayout)

        topLayout.setContentsMargins(0,0,0,0)
        subLayout.setContentsMargins(0,0,0,0)

        splitter1 = QSplitter(Qt.Vertical)
        splitter1.addWidget(frame_left)
        splitter1.addWidget(frame_right)

        layout.addWidget(splitter1)
        self.setLayout(layout)
示例#35
0
 def addTab(self, tab, title):
     QTabWidget.addTab(self, tab, title)
示例#36
0
文件: apbba.py 项目: huyong1979/aphla
class BbaMainWindow(QMainWindow):
    """
    the main window
    """
    def __init__(self, parent = None):
        QMainWindow.__init__(self, parent)

        self.setIconSize(QSize(48, 48))

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

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

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

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

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

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

        #toolbar = QToolBar(self)
        #self.addToolBar(toolbar)
        fileToolBar = self.addToolBar("File")
        fileToolBar.setObjectName("FileToolBar")
        fileToolBar.addAction(fileQuitAction)
        fileToolBar.addAction(controlGoAction)
        #

    def chooseBpm(self):
        #print self.bpm
        bpm = []
        bpmmask = self.plot1.curve1.mask[:]
        for i in range(len(self.bpm)):
            if bpmmask[i]:
                bpm.append((self.bpm[i], Qt.Unchecked))
            else:
                bpm.append((self.bpm[i], Qt.Checked))

        form = ElementPickDlg(bpm, 'BPM', self)

        if form.exec_():
            choice = form.result()
            for i in range(len(self.bpm)):
                if self.bpm[i] in choice:
                    self.plot1.setMask(i, 0)
                    self.plot2.setMask(i, 0)
                else:
                    self.plot1.setMask(i, 1)
                    self.plot2.setMask(i, 1)

    def fileOpen(self):
        """
        open a HDF5 file, show pictures as tabs
        """
        fname = QFileDialog.getOpenFileName(self,
                "Open data file", '.', "HDF5 files (*.h5, *.hdf5)")
        if not fname: return

        import h5py
        f = h5py.File(str(fname), 'r')
        for grp in f.keys():
            for img in f[grp].keys():
                ds1 = f[grp][img]
                #if ds1.get('attr', None) is None: continue
                if ds1.attrs.get('CLASS', None) != 'IMAGE': continue
                # the fourth alpha, needs be 255.
                d1 = np.ones(ds1.shape[:2] + (4,), dtype=np.uint8) * 255
                d1[:,:,:3] = np.asarray(ds1)

                wid = QWidget()
                l = QVBoxLayout(wid)
                imageLabel = QLabel(self)
                imageLabel.setText("Text")
                #imageLabel
                im1 = Image.fromarray(d1)
                pxm = QPixmap.fromImage(ImageQt.ImageQt(im1))
                #pxm.save("j.png")
                imageLabel.setPixmap(pxm)
                imageLabel.adjustSize()
                l.addWidget(imageLabel)
                self.widtab.addTab(wid, "%s:%s" % (grp, img))
        f.close()

    def _load_conf_h5(self, h5file, grp = "bba"):
        pass

    def align_quad(self, **kwargs):
        """
        """
        for quadname in confdat['bowtie_align']:
            bbconf = confdat['bowtie_align'][quadname]
            print("Quadrupole:", bbconf['Q'], caget(bbconf['Q'][2].encode('ascii')))
            for i in range(0, len(bbconf['COR_BPM']), 2):
                ac = bba.BbaBowtie()
                ac.quad, s, ac.quad_pvsp, ac.dqk1 = bbconf['Q'][:4]
                ac.bpm, s, ac.bpm_pvrb = bbconf['COR_BPM'][i][:3]
                ac.trim, s, ac.trim_pvsp, kickrg, obtpv = bbconf['COR_BPM'][i+1][:5]
                ac.quad_pvrb = ac.quad_pvsp
                ac.trim_pvrb = ac.trim_pvsp
                ac.kick = np.linspace(kickrg[0], kickrg[1], 4)
                ac.orbit_pvrb = confdat[obtpv]
                #ca.bpm = conf['
                # fix the utf-8
                ac.align()
                aclist = self._bba.setdefault(quadname, [])
                aclist.append(ac)

                print("Plotting ...")
                wid = QWidget(self)
                l = QVBoxLayout(wid)
                cv1 = BbaMplCanvas(wid)
                cv2 = BbaMplCanvas(wid)
                #x = np.linspace(0, 2*np.pi, 100)
                #cv1.axes.plot(x, np.sin(x) + np.random.rand(len(x))*.2, 'ro-')
                #cv2.axes.plot(x, np.tan(x) + np.random.rand(len(x))*.2, 'go-')
                ac.plot(cv1.axes, cv2.axes, factor=(1e6, 1e6))
                l.addWidget(cv1)
                l.addWidget(cv2)
                cv1.draw()
                cv2.draw()
                data1 = np.fromstring(cv1.tostring_rgb(), dtype=np.uint8, sep='')
                w, h = cv1.get_width_height()
                data1 = data1.reshape(h, w, 3)
                data2 = np.fromstring(cv2.tostring_rgb(), dtype=np.uint8, sep='')
                w, h = cv2.get_width_height()
                data2 = data2.reshape(h, w, 3)
                aclist.append([data1, data2])
                self.widtab.addTab(wid, "%s:%d" % (quadname, self.widtab.count()+1))
                #wid.setFocus()
                self.widtab.setCurrentIndex(self.widtab.count() - 1)
            # moving to the next quadname
        self.write()


    def write(self):
        import h5py
        print("FIXME: using hard coded file name: apbba.hdf5")
        f = h5py.File('apbba.hdf5', 'w')
        for quadname, rec in self._bba.items():
            for i in range(0, len(rec), 2):
                ac = rec[i]
                # name the group as quad:index
                grp = f.create_group("%s:%d" %(ac.quad, i/2))
                k, m, n = np.shape(ac.orbit)
                dset = grp.create_dataset("orbit", (k, m, n), 'd')
                dset[:, :, :] = ac.orbit
                grp['keep'] = ac.mask
                grp['trim_fitted'] = ac.trim_fitted
                grp['trim_pvsp'] = ac.trim_pvsp

                for j in range(len(rec[i+1])):
                    data = rec[i+1][j]
                    h, w, d = np.shape(data)
                    dset = grp.create_dataset("image_%02d"%j, (h, w, d), dtype=np.uint8)
                    dset[:,:,:] = data[:,:,:]
                    dset.attrs['CLASS'] = 'IMAGE'
                    dset.attrs['IMAGE_VERSION'] = '1.2'
                    dset.attrs['IMAGE_SUBCLASS'] = 'IMAGE_TRUECOLOR'

        f.close()
示例#37
0
 def startTabs(self, name_of_first_tab):
     self.__tab_widget = QTabWidget()
     self.__layout_queue.append(self.__layout)
     self.__layout = None
     self.addTab(name_of_first_tab)
示例#38
0
 def mousePressEvent(self, event):
     QTabWidget.mousePressEvent(self, event)
     if self.follow_mode:
         return
     if event.button() == Qt.RightButton:
         index = self.tabBar().tabAt(event.pos())
         self.setCurrentIndex(index)
         widget = self.widget(index)
         if type(widget) is editor.Editor:
             #show menu
             menu = QMenu()
             actionAdd = menu.addAction(self.tr("Add to Project..."))
             actionRun = menu.addAction(self.tr("Run this File!"))
             menuSyntax = menu.addMenu(self.tr("Change Syntax"))
             self._create_menu_syntax(menuSyntax)
             menu.addSeparator()
             actionClose = menu.addAction(self.tr("Close This Tab"))
             actionCloseAll = menu.addAction(self.tr("Close All Tabs"))
             actionCloseAllNotThis = menu.addAction(
                 self.tr("Close Other Tabs"))
             menu.addSeparator()
             if self._parent.splitted:
                 actionMoveSplit = menu.addAction(
                     self.tr("Move this Tab to the other Split"))
                 actionCloseSplit = menu.addAction(
                     self.tr("Close Split"))
                 #Connect split actions
                 self.connect(actionMoveSplit, SIGNAL("triggered()"),
                     lambda: self._parent.move_tab_to_next_split(self))
                 self.connect(actionCloseSplit, SIGNAL("triggered()"),
                     lambda: self._parent.split_tab(
                         self._parent.orientation() == Qt.Horizontal))
             else:
                 actionSplitH = menu.addAction(
                     self.tr("Split this Tab (Vertically)"))
                 actionSplitV = menu.addAction(
                     self.tr("Split this Tab (Horizontally)"))
                 #Connect split actions
                 self.connect(actionSplitH, SIGNAL("triggered()"),
                     lambda: self._split_this_tab(True))
                 self.connect(actionSplitV, SIGNAL("triggered()"),
                     lambda: self._split_this_tab(False))
             menu.addSeparator()
             actionCopyPath = menu.addAction(
                 self.tr("Copy file location to Clipboard"))
             actionReopen = menu.addAction(
                 self.tr("Reopen last closed File"))
             if len(self.__lastOpened) == 0:
                 actionReopen.setEnabled(False)
             #Connect actions
             self.connect(actionRun, SIGNAL("triggered()"),
                 self._run_this_file)
             self.connect(actionAdd, SIGNAL("triggered()"),
                 self._add_to_project)
             self.connect(actionClose, SIGNAL("triggered()"),
                 lambda: self.removeTab(index))
             self.connect(actionCloseAllNotThis, SIGNAL("triggered()"),
                 self._close_all_tabs_except_this)
             self.connect(actionCloseAll, SIGNAL("triggered()"),
                 self._close_all_tabs)
             self.connect(actionCopyPath, SIGNAL("triggered()"),
                 self._copy_file_location)
             self.connect(actionReopen, SIGNAL("triggered()"),
                 self._reopen_last_tab)
             menu.exec_(event.globalPos())
     if event.button() == Qt.MidButton:
         index = self.tabBar().tabAt(event.pos())
         self.removeTab(index)
class VerdictPage(QWidget):
    """
    Verdict Export Page
    """
    ExportResults = pyqtSignal(list, dict)

    def __init__(self, parent, core, debugMode=False):
        """
        Constructor
        @param parent:
        """
        QWidget.__init__(self, parent)
        self.__core = core
        self.__debugMode = debugMode
        self.__rawXml = ""
        self.__listCsv = ""

        self.createWidgets()
        self.creationConnections()

        if self.__debugMode: self.onCheckboxesChanged(toggled=False)

    def core(self):
        """
        """
        return self.__core

    def creationConnections(self):
        """
        QtSignals connection:
        """
        self.testsTable.LoadTestcases.connect(self.onLoadTestcases)
        self.testcasesTable.LoadSteps.connect(self.onLoadSteps)
        self.ignoreTestcases.toggled.connect(self.onCheckboxesChanged)
        self.ignoreUncomplete.toggled.connect(self.onCheckboxesChanged)
        self.exportButton.clicked.connect(self.onExportClicked)

    def createWidgets(self):
        """
        """
        self.listingTab = QTabWidget()
        self.listingTab.setMinimumWidth(650)

        layoutGrid = QGridLayout()

        self.testSetPath = QLineEdit()
        self.testSetName = QLineEdit()

        self.testsTable = TestsTableView(self, core=self.core())
        self.testcasesTable = TestcasesTableView(self, core=self.core())

        self.stepsTable = StepsTableView(self, core=self.core())

        self.listingTab.addTab(self.testsTable, "Test(s)")
        self.listingTab.addTab(self.testcasesTable, "Testcase(s)")
        self.listingTab.addTab(self.stepsTable, "Steps(s)")

        self.ignoreTestcases = QCheckBox("Ignore testcase(s)")
        if self.core().settings().cfg()["export-results"]["ignore-testcase"]:
            self.ignoreTestcases.setCheckState(Qt.Checked)

        self.ignoreUncomplete = QCheckBox("Ignore uncomplete result(s)")
        if self.core().settings().cfg()["export-results"]["ignore-uncomplete"]:
            self.ignoreUncomplete.setCheckState(Qt.Checked)

        self.addMissingFoldersCheckBox = QCheckBox(
            self.tr("Create missing folders"))
        if self.core().settings().cfg()["export-results"]["add-folders"]:
            self.addMissingFoldersCheckBox.setCheckState(Qt.Checked)

        self.addTestsetCheckBox = QCheckBox(self.tr("Create testset"))
        if self.core().settings().cfg()["export-results"]["add-testset"]:
            self.addTestsetCheckBox.setCheckState(Qt.Checked)

        self.addTestinstanceCheckBox = QCheckBox(
            self.tr("Add test instance in testset"))
        if self.core().settings().cfg()["export-results"]["add-testinstance"]:
            self.addTestinstanceCheckBox.setCheckState(Qt.Checked)

        optionsLayout = QHBoxLayout()
        optionsLayout.addWidget(self.ignoreTestcases)
        optionsLayout.addWidget(self.ignoreUncomplete)
        optionsLayout.addStretch(1)

        # optionsTsLayout = QHBoxLayout()
        # optionsTsLayout.addWidget(self.addTestsetCheckBox)
        # optionsTsLayout.addWidget(self.addTestinstanceCheckBox)
        # optionsTsLayout.addStretch(1)

        layoutGrid.addWidget(QLabel("Remote Test Set Path:"), 0, 0)
        layoutGrid.addWidget(self.testSetPath, 0, 1)
        # layoutGrid.addWidget(self.addMissingFoldersCheckBox, 1, 1)
        layoutGrid.addWidget(QLabel("Remote Test Set Name:"), 2, 0)
        layoutGrid.addWidget(self.testSetName, 2, 1)
        # layoutGrid.addLayout(optionsTsLayout, 3, 1)
        layoutGrid.addWidget(QLabel("Local result(s):"), 4, 0)
        layoutGrid.addLayout(optionsLayout, 4, 1)
        layoutGrid.addWidget(QLabel("Test(s) Verdict:"), 5, 0)
        layoutGrid.addWidget(self.listingTab, 5, 1)

        self.exportStatusLabel = QLabel("Status: Disconnected", self)
        self.exportButton = QPushButton(self.tr("Export Result"), self)
        self.exportButton.setMinimumWidth(300)

        layoutRight = QHBoxLayout()
        layoutRight.addWidget(self.exportButton)
        layoutRight.addWidget(self.exportStatusLabel)
        layoutRight.addStretch(1)

        layoutGrid.addWidget(QLabel("Controls:"), 6, 0)
        layoutGrid.addLayout(layoutRight, 6, 1)

        layoutMain = QHBoxLayout()
        layoutMain.addLayout(layoutGrid)

        self.setLayout(layoutMain)

    def onExportClicked(self):
        """
        """
        testsetPath = self.testSetPath.text()
        if not len(testsetPath):
            QMessageBox.warning(
                self, self.tr("Export Result"),
                self.tr("Please to specific the remote testset path!"))
            return
        testsetName = self.testSetName.text()
        if not len(testsetName):
            QMessageBox.warning(
                self, self.tr("Export Result"),
                self.tr("Please to specific the remote testset name!"))
            return

        testcases = []
        if self.ignoreTestcases.isChecked():
            indexes = self.testsTable.selectionModel().selectedRows()
            if not len(indexes):
                QMessageBox.warning(self, self.tr("Export Result"),
                                    self.tr("Please to select one test!"))
                return

            error = False
            for index in indexes:
                selectedIndex = index.row()
                row = self.testsTable.model.getData()[selectedIndex]
                testcases.append(row)

        else:
            indexes = self.testcasesTable.selectionModel().selectedRows()
            if not len(indexes):
                QMessageBox.warning(self, self.tr("Export Result"),
                                    self.tr("Please to select one testcase!"))
                return

            error = False
            for index in indexes:
                selectedIndex = index.row()
                row = self.testcasesTable.model.getData()[selectedIndex]
                testcases.append(row)

        config = {
            "TestSet_Path": testsetPath,
            "TestSet_Name": testsetName,
            "Add_Folders": self.addMissingFoldersCheckBox.isChecked(),
            "Add_TestSet": self.addTestsetCheckBox.isChecked(),
            "Add_TestInstance": self.addTestinstanceCheckBox.isChecked()
        }
        for cfg in self.core().settings().cfg()["custom-testset-fields"]:
            config.update({cfg["key"]: cfg["value"]})

        self.disableExport()
        self.ExportResults.emit(testcases, config)

    def logStatus(self, status):
        """
        """
        self.exportStatusLabel.setText(status)

    def enableExport(self):
        """
        """
        self.exportButton.setEnabled(True)

    def disableExport(self):
        """
        """
        self.exportButton.setEnabled(False)

    def onCheckboxesChanged(self, toggled):
        """
        """
        if self.ignoreUncomplete.isChecked() or self.ignoreTestcases.isChecked(
        ):
            self.testcasesTable.setEnabled(False)
            self.testcasesTable.clear()
            self.stepsTable.setEnabled(False)
            self.stepsTable.clear()

        if not self.ignoreTestcases.isChecked():
            self.testcasesTable.setEnabled(True)
            self.stepsTable.setEnabled(True)

        # reload data
        if self.__debugMode:
            self.readXmlAndCSV(rawXml=VERDICT_EXAMPLE)
        else:
            self.readXmlAndCSV(rawXml=self.__rawXml, listCsv=self.__listCsv)
            # self.readXml(rawXml=self.__rawXml)

    def clearTables(self):
        """
        Clear all tables
        """
        self.stepsTable.clear()
        self.testcasesTable.clear()
        self.testsTable.clear()

    def onLoadSteps(self, steps):
        """
        """
        self.stepsTable.loadTable(data=steps)

    def onLoadTestcases(self, testcases):
        """
        """
        # if self.ignoreTestcases.isChecked():
        #     return

        self.stepsTable.clear()
        self.testcasesTable.loadTable(data=testcases)

    def onLoadTests(self, data):
        """
        """
        # clear the table before to start
        self.clearTables()

        # load tables according to the data provided
        self.testsTable.loadTable(data=data)

    def convertResult(self, result):
        """
        """
        if result == "PASS":
            return QC_PASSED
        elif result == "FAIL":
            return QC_FAILED
        else:
            return QC_UNCOMPLETED

    def readXmlAndCSV(self, rawXml, listCsv=None):
        """
        """
        # init and save the xml provided
        self.__rawXml = rawXml
        try:
            root = ET.fromstring(rawXml)
        except Exception as e:
            self.core().debug().addLogError("Unable to read xml: %s" % e)
        else:
            tests = []
            testsVerdict = root.find(".")

            testPath = testsVerdict.attrib["path"]
            testProject = testsVerdict.attrib["project"]
            testName = testsVerdict.attrib["name"]
            self.testSetPath.setText(testPath)
            self.testSetName.setText(testName)

            # read all tests
            testsName = {}
            for ts in testsVerdict:
                if ts.attrib["status"] in ["not-executed", "disabled"]:
                    continue

                tcs = ts.findall("testcase")
                if len(tcs) and self.ignoreTestcases.isChecked():
                    continue

                tsName = ts.attrib["name"]
                tsName = tsName.strip()

                if tsName not in testsName:
                    testsName[tsName] = 1
                else:
                    testsName[tsName] += 1
                ts_result = self.convertResult(ts.attrib["result"])
                if self.ignoreUncomplete.isChecked():
                    if ts_result == QC_UNCOMPLETED:
                        continue

                testname_instance = "[%s]%s" % (testsName[tsName], tsName)
                if self.core().settings().cfg()["qc-server"]["use-rest"]:
                    testname_instance = "%s [%s]" % (tsName, testsName[tsName])
                test = {
                    "name": testname_instance,
                    "result": ts_result,
                    "testpath": ts.attrib["path"],
                    "testname": tsName
                }
                # read all testcases
                testcases = []
                tcsName = {}
                for tc in tcs:
                    tcName = tc.attrib["name"]

                    # read all steps
                    stepsVerdict = tc.findall("step")
                    steps = []
                    for stp in stepsVerdict:
                        steps.append({
                            "result":
                            self.convertResult(stp.attrib["result"]),
                            "actual":
                            stp.attrib["actual"]
                        })

                    if tcName not in tcsName:
                        tcsName[tcName] = 1
                    else:
                        tcsName[tcName] += 1
                    tc_result = self.convertResult(tc.attrib["result"])
                    testcases.append({
                        "name":
                        "[%s]%s" % (tcsName[tcName], tcName),
                        "result":
                        tc_result,
                        "steps":
                        steps
                    })

                test.update({"testcases": testcases})
                tests.append(test)
            self.core().debug().addLogSuccess("Export results detected: %s" %
                                              len(tests))
            if len(tests) == 0:
                if listCsv is not None:
                    self.__listCsv = listCsv

                    testsincsv = listCsv.splitlines()
                    testcaseCSV = testsincsv[1].split(',')

                    test = {
                        "name": testcaseCSV[1],
                        "result": self.convertResult(testcaseCSV[4]),
                        "testpath": testPath,
                        "testname": testcaseCSV[1],
                        "testcases": []
                    }
                    tests.append(test)

            # finally loading all tests in table model
            self.core().debug().addLogSuccess("first test in csv: %s" % test)
            if len(tests): self.onLoadTests(data=tests)
示例#40
0
 def setTabText(self, index, text):
     QTabWidget.setTabText(self, index, text)
     if text in self.titles and not self.dontLoopInExpandTitle:
         self.expand_tab_name(text)
示例#41
0
class PluginsManagerWidget(QDialog):

    def __init__(self, parent):
        QDialog.__init__(self, parent, Qt.Dialog)
        self.setWindowTitle(self.tr("Plugins Manager"))
        self.resize(700, 600)

        vbox = QVBoxLayout(self)
        self._tabs = QTabWidget()
        vbox.addWidget(self._tabs)
        self._txt_data = QTextBrowser()
        self._txt_data.setOpenLinks(False)
        vbox.addWidget(QLabel(self.tr("Description:")))
        vbox.addWidget(self._txt_data)
        # Footer
        hbox = QHBoxLayout()
        btn_close = QPushButton(self.tr('Close'))
        btnReload = QPushButton(self.tr("Reload"))
        hbox.addWidget(btn_close)
        hbox.addSpacerItem(QSpacerItem(1, 0, QSizePolicy.Expanding))
        hbox.addWidget(btnReload)
        vbox.addLayout(hbox)
        self.overlay = ui_tools.Overlay(self)
        self.overlay.hide()

        self._oficial_available = []
        self._community_available = []
        self._locals = []
        self._updates = []
        self._loading = True
        self._requirements = {}

        self.connect(btnReload, SIGNAL("clicked()"), self._reload_plugins)
        self.thread = ThreadLoadPlugins(self)
        self.connect(self.thread, SIGNAL("finished()"),
            self._load_plugins_data)
        self.connect(self.thread, SIGNAL("plugin_downloaded(PyQt_PyObject)"),
            self._after_download_plugin)
        self.connect(self.thread, SIGNAL("plugin_uninstalled(PyQt_PyObject)"),
            self._after_uninstall_plugin)
        self.connect(self._txt_data, SIGNAL("anchorClicked(const QUrl&)"),
            self._open_link)
        self.connect(btn_close, SIGNAL('clicked()'), self.close)
        self.overlay.show()
        self._reload_plugins()

    def show_plugin_info(self, data):
        plugin_description = data[2].replace('\n', '<br>')
        html = HTML_STYLE.format(name=data[0],
            version=data[1], description=plugin_description,
            author=data[3], link=data[4])
        self._txt_data.setHtml(html)

    def _open_link(self, url):
        link = url.toString()
        if link.startswith('/plugins/'):
            link = 'http://ninja-ide.org' + link
        webbrowser.open(link)

    def _reload_plugins(self):
        self.overlay.show()
        self._loading = True
        self.thread.runnable = self.thread.collect_data_thread
        self.thread.start()

    def _after_download_plugin(self, plugin):
        oficial_plugin = _get_plugin(plugin[0], self._oficial_available)
        community_plugin = _get_plugin(plugin[0], self._community_available)
        if oficial_plugin:
            self._installedWidget.add_table_items([oficial_plugin])
            self._availableOficialWidget.remove_item(plugin[0])
        elif community_plugin:
            self._installedWidget.add_table_items([community_plugin])
            self._availableCommunityWidget.remove_item(plugin[0])

    def _after_uninstall_plugin(self, plugin):
        #make available the plugin corresponding to the type
        oficial_plugin = _get_plugin(plugin[0], self._oficial_available)
        community_plugin = _get_plugin(plugin[0], self._community_available)
        if oficial_plugin:
            self._availableOficialWidget.add_table_items([oficial_plugin])
            self._installedWidget.remove_item(plugin[0])
        elif community_plugin:
            self._availableCommunityWidget.add_table_items([community_plugin])
            self._installedWidget.remove_item(plugin[0])

    def _load_plugins_data(self):
        if self._loading:
            self._tabs.clear()
            self._updatesWidget = UpdatesWidget(self, copy(self._updates))
            self._availableOficialWidget = AvailableWidget(self,
                copy(self._oficial_available))
            self._availableCommunityWidget = AvailableWidget(self,
                copy(self._community_available))
            self._installedWidget = InstalledWidget(self, copy(self._locals))
            self._tabs.addTab(self._availableOficialWidget,
                self.tr("Official Available"))
            self._tabs.addTab(self._availableCommunityWidget,
                self.tr("Community Available"))
            self._tabs.addTab(self._updatesWidget, self.tr("Updates"))
            self._tabs.addTab(self._installedWidget, self.tr("Installed"))
            self._loading = False
        self.overlay.hide()

    def download_plugins(self, plugs):
        """
        Install
        """
        self.overlay.show()
        self.thread.plug = plugs
        #set the function to run in the thread
        self.thread.runnable = self.thread.download_plugins_thread
        self.thread.start()

    def mark_as_available(self, plugs):
        """
        Uninstall
        """
        self.overlay.show()
        self.thread.plug = plugs
        #set the function to run in the thread
        self.thread.runnable = self.thread.uninstall_plugins_thread
        self.thread.start()

    def update_plugin(self, plugs):
        """
        Update
        """
        self.overlay.show()
        self.thread.plug = plugs
        #set the function to run in the thread
        self.thread.runnable = self.thread.update_plugin_thread
        self.thread.start()

    def reset_installed_plugins(self):
        local_plugins = plugin_manager.local_plugins()
        plugins = _format_for_table(local_plugins)
        self._installedWidget.reset_table(plugins)

    def resizeEvent(self, event):
        self.overlay.resize(event.size())
        event.accept()
示例#42
0
class ThemesManagerWidget(QDialog):
    def __init__(self, parent):
        QDialog.__init__(self, parent, Qt.Dialog)
        self.setWindowTitle(self.tr("Themes Manager"))
        self.resize(700, 500)

        vbox = QVBoxLayout(self)
        self._tabs = QTabWidget()
        vbox.addWidget(self._tabs)
        # Footer
        hbox = QHBoxLayout()
        btn_close = QPushButton(self.tr('Close'))
        btnReload = QPushButton(self.tr("Reload"))
        hbox.addWidget(btn_close)
        hbox.addSpacerItem(QSpacerItem(1, 0, QSizePolicy.Expanding))
        hbox.addWidget(btnReload)
        vbox.addLayout(hbox)
        self.overlay = ui_tools.Overlay(self)
        self.overlay.show()

        self._schemes = []
        self._loading = True
        self.downloadItems = []

        #Load Themes with Thread
        self.connect(btnReload, SIGNAL("clicked()"), self._reload_themes)
        self._thread = ui_tools.ThreadExecution(self.execute_thread)
        self.connect(self._thread, SIGNAL("finished()"), self.load_skins_data)
        self.connect(btn_close, SIGNAL('clicked()'), self.close)
        self._reload_themes()

    def _reload_themes(self):
        self.overlay.show()
        self._loading = True
        self._thread.execute = self.execute_thread
        self._thread.start()

    def load_skins_data(self):
        if self._loading:
            self._tabs.clear()
            self._schemeWidget = SchemeWidget(self, self._schemes)
            self._tabs.addTab(self._schemeWidget, self.tr("Editor Schemes"))
            self._loading = False
        self.overlay.hide()
        self._thread.wait()

    def download_scheme(self, scheme):
        self.overlay.show()
        self.downloadItems = scheme
        self._thread.execute = self._download_scheme_thread
        self._thread.start()

    def resizeEvent(self, event):
        self.overlay.resize(event.size())
        event.accept()

    def execute_thread(self):
        try:
            descriptor_schemes = urlopen(resources.SCHEMES_URL)
            schemes = json_manager.parse(descriptor_schemes)
            schemes = [(d['name'], d['download']) for d in schemes]
            local_schemes = self.get_local_schemes()
            schemes = [
                schemes[i] for i in range(len(schemes))
                if os.path.basename(schemes[i][1]) not in local_schemes
            ]
            self._schemes = schemes
        except URLError:
            self._schemes = []

    def get_local_schemes(self):
        if not file_manager.folder_exists(resources.EDITOR_SKINS):
            file_manager.create_tree_folders(resources.EDITOR_SKINS)
        schemes = os.listdir(resources.EDITOR_SKINS)
        schemes = [s for s in schemes if s.endswith('.color')]
        return schemes

    def _download_scheme_thread(self):
        for d in self.downloadItems:
            self.download(d[1], resources.EDITOR_SKINS)

    def download(self, url, folder):
        fileName = os.path.join(folder, os.path.basename(url))
        try:
            content = urlopen(url)
            f = open(fileName, 'w')
            f.write(content.read())
            f.close()
        except URLError:
            return
示例#43
0
class options(QWidget):
    def __init__(self, parent):
        QWidget.__init__(self)
        self.init(parent)
        self.initShape()

    def init(self, parent):
        self.heditor = parent

    def initShape(self):
        self.vbox = QVBoxLayout()
        self.optab = QTabWidget()

        self.fill = QWidget()

        self.createHexOptions()
        #        self.createPageOptions()
        self.createPixelOptions()
        self.vbox.addWidget(self.optab)

        self.createButtons()
        self.vbox.addWidget(self.fill)

        self.setLayout(self.vbox)

    def createPageOptions(self):
        self.pagegrid = QGridLayout()
        self.pagegroup = QWidget()

        pagelabel = QLabel("Page size : ")
        self.sizeEdit = QFFSpinBox(self)
        self.sizeEdit.setMaximum(self.heditor.filesize)
        self.sizeEdit.setValue(self.heditor.pageSize)
        #        psize = QString("%.2d" % self.heditor.pageSize)
        #        self.sizeEdit.insert(psize)

        headerlabel = QLabel("Header size : ")
        self.headEdit = QFFSpinBox(self)
        self.headEdit.setMaximum(self.heditor.filesize)
        self.headEdit.setValue(self.heditor.pageHead)
        #        phead = QString("%.2d" % self.heditor.pageHead)
        #        self.headEdit.insert(phead)

        sparelabel = QLabel("Spare size : ")
        self.spareEdit = QFFSpinBox(self)
        self.spareEdit.setMaximum(self.heditor.filesize)
        self.spareEdit.setValue(self.heditor.pageSpare)
        #        pspare = QString("%.2d" % self.heditor.pageSpare)
        #        self.spareEdit.insert(pspare)

        ppb = QLabel("Pages per block:")
        self.pagesperblock = QComboBox()
        self.pagesperblock.addItem("8")
        self.pagesperblock.addItem("16")
        self.pagesperblock.addItem("32")
        self.pagesperblock.addItem("64")
        self.pagesperblock.addItem("128")
        self.pagesperblock.addItem("256")
        self.pagesperblock.addItem("512")
        self.pagesperblock.setCurrentIndex(2)

        lview = QLabel("Left indication: ")
        self.indic = QComboBox()
        self.indic.addItem("Offset")
        self.indic.addItem("Block")

        #        self.pagesperlineEdit = QLineEdit()
        #        ppl = QString("%.2d" % self.heditor.pagesPerBlock)
        #        self.pagesperlineEdit.insert(ppl)

        self.pagegrid.addWidget(pagelabel, 0, 0)
        self.pagegrid.addWidget(self.sizeEdit, 0, 1)

        self.pagegrid.addWidget(headerlabel, 1, 0)
        self.pagegrid.addWidget(self.headEdit, 1, 1)

        self.pagegrid.addWidget(sparelabel, 2, 0)
        self.pagegrid.addWidget(self.spareEdit, 2, 1)

        self.pagegrid.addWidget(ppb, 3, 0)
        self.pagegrid.addWidget(self.pagesperblock, 3, 1)

        self.pagegrid.addWidget(lview, 4, 0)
        self.pagegrid.addWidget(self.indic, 4, 1)

        self.pagegrid.addWidget(self.fill, 5, 0)
        self.pagegrid.setRowStretch(5, 1)
        #        self.pagegrid.addWidget(self.fill, 6, 0)

        #        self.pagegrid.addWidget(pagesperline, 6, 0)
        #        self.pagegrid.addWidget(self.pagesperlineEdit, 7, 0)

        self.pagegroup.setLayout(self.pagegrid)
        self.vvbox.addWidget(self.pagegroup)

#        self.optab.insertTab(1, self.pagegroup, "Pages" )

#        self.vbox.addWidget(self.pagegroup)

    def createHexOptions(self):
        self.vvbox = QVBoxLayout()
        self.vcontainer = QWidget()

        self.hexgroup = QWidget()

        self.hexgrid = QGridLayout()

        groupebylabel = QLabel("Groupe by:")
        self.groupeby = QComboBox()
        self.groupeby.addItem("1")
        self.groupeby.addItem("2")
        self.groupeby.addItem("4")

        offsetlabel = QLabel("Offset as")
        self.offsetas = QComboBox()
        self.offsetas.addItem("Hexadecimal")
        self.offsetas.addItem("Decimal")

        #        self.hexgrid.addWidget(groupebylabel, 0, 0)
        #        self.hexgrid.addWidget(self.groupeby, 1, 0)
        self.hexgrid.addWidget(offsetlabel, 0, 0)
        self.hexgrid.addWidget(self.offsetas, 0, 1)
        #        self.hexgrid.addWidget(self.fill, 2, 0)
        #        self.hexgrid.setRowStretch(2, 1)

        self.hexgroup.setLayout(self.hexgrid)

        self.vvbox.addWidget(self.hexgroup)

        self.createPageOptions()

        self.vcontainer.setLayout(self.vvbox)

        self.optab.insertTab(0, self.vcontainer, "General")

#        self.vbox.addWidget(self.hexgroup)

#Offset as decimal / hexadecimal

    def createPixelOptions(self):
        self.pixgroup = QWidget()

        self.pixgrid = QGridLayout()

        formatlabel = QLabel("Format :")
        self.format = QComboBox()
        self.format.addItem("RGB")
        self.format.addItem("Alpha RGB")
        self.format.addItem("Indexed 8bit")
        self.format.addItem("Mono")
        self.connect(self.format, SIGNAL("currentIndexChanged(const QString)"),
                     self.formatChanged)

        colorlabel = QLabel("Indexed Color :")
        self.icolor = QComboBox()
        self.icolor.addItem("Green")
        self.icolor.addItem("Red")
        self.icolor.addItem("Blue")
        self.icolor.addItem("Ascii")
        self.icolor.addItem("256")
        self.icolor.setEnabled(False)

        slidelabel = QLabel("Resolution : ")

        self.sliderspin = QSpinBox(self)
        self.sliderspin.setMinimum(64)
        self.sliderspin.setMaximum(1024)
        self.sliderspin.setValue(self.heditor.wpixel.view.w)
        self.connect(self.sliderspin, SIGNAL("valueChanged(int)"),
                     self.slidermoved)

        self.slider = QSlider(Qt.Horizontal)
        self.slider.setMinimum(64)
        self.slider.setMaximum(1024)
        self.slider.setValue(self.heditor.wpixel.view.w)
        self.slider.setSingleStep(1)

        self.zoomlabel = QLabel("Scale factor : 1")
        self.zoom = QSlider(Qt.Horizontal)
        self.zoom.setMinimum(1)
        self.zoom.setMaximum(5)
        self.zoom.setValue(1)
        self.zoom.setSingleStep(1)
        self.zoom.setTickInterval(1)
        self.zoom.setTickPosition(QSlider.TicksBelow)

        self.connect(self.slider, SIGNAL("sliderMoved(int)"), self.slidermoved)
        self.connect(self.zoom, SIGNAL("sliderMoved(int)"), self.scale)

        self.pixgrid.addWidget(formatlabel, 0, 0)
        self.pixgrid.addWidget(self.format, 0, 1)
        self.pixgrid.addWidget(colorlabel, 1, 0)
        self.pixgrid.addWidget(self.icolor, 1, 1)

        self.pixgrid.addWidget(slidelabel, 2, 0)
        self.pixgrid.addWidget(self.sliderspin, 2, 1, Qt.AlignLeft)

        self.pixgrid.addWidget(self.slider, 3, 0)
        self.pixgrid.addWidget(self.zoomlabel, 4, 0, Qt.AlignLeft)
        self.pixgrid.addWidget(self.zoom, 5, 0)

        self.pixgrid.addWidget(self.fill, 6, 0)
        self.pixgrid.setRowStretch(6, 1)

        self.pixgroup.setLayout(self.pixgrid)

        self.optab.insertTab(1, self.pixgroup, "Pixel")

    def setSliderLabel(self, value):
        cvalue = QString()
        cvalue = "%2.d" % value
        self.sliderlabel.setText(cvalue)

    def setZoomLabel(self, value):
        zvalue = QString("Scale factor : ")
        zvalue += "%2.d" % value
        self.zoomlabel.setText(zvalue)

    def createButtons(self):
        self.applyB = QPushButton("Apply")
        self.connect(self.applyB, SIGNAL('clicked()'), self.apply)

        self.vbox.addWidget(self.applyB)

    def checkValue(self, value):
        try:
            n = int(value)
            return n
        except ValueError:
            return -1

    def apply(self):
        #PAGE CHECK
        pagesize = self.sizeEdit.value()
        headsize = self.headEdit.value()
        sparesize = self.spareEdit.value()
        pagesperblock = self.checkValue(self.pagesperblock.currentText())

        if (pagesize < 0) or (headsize < 0) or (sparesize <
                                                0) or (pagesperblock < 0):
            print "Wrong values"
        else:
            offas = self.offsetas.currentText()
            if offas == "Decimal":
                self.heditor.decimalview = True
            elif offas == "Hexadecimal":
                self.heditor.decimalview = False
            #Hexview refresh
            self.heditor.readOffset(self.heditor.currentOffset)
            #Pageview refresh
            if self.indic.currentText() == "Offset":
                self.heditor.pageOffView = True
            else:
                self.heditor.pageOffView = False

            self.heditor.refreshPageValues(headsize, pagesize, sparesize,
                                           pagesperblock)
            if self.heditor.wpage.scroll:
                self.heditor.wpage.scroll.refreshValues(
                    self.heditor.pagesPerBlock, self.heditor.pageSize)
            self.heditor.wpage.view.refreshAllContent()
            #PageView scrollbar refres
            #Pixel View refresh
            format = self.format.currentText()
            if format == "Indexed 8bit":
                self.heditor.wpixel.view.format = 0
            elif format == "Mono":
                self.heditor.wpixel.view.format = 1
            elif format == "RGB":
                self.heditor.wpixel.view.format = 2
            elif format == "Alpha RGB":
                self.heditor.wpixel.view.format = 3

            if self.heditor.wpixel.scroll:
                self.heditor.wpixel.scroll.refreshValues()
            #Color
            icolor = self.icolor.currentText()
            if icolor == "Red":
                self.heditor.wpixel.view.icolor = 0
            elif icolor == "Green":
                self.heditor.wpixel.view.icolor = 1
            elif icolor == "Blue":
                self.heditor.wpixel.view.icolor = 2
            elif icolor == "Ascii":
                self.heditor.wpixel.view.icolor = 3
            elif icolor == "256":
                self.heditor.wpixel.view.icolor = 4

            pixoffset = self.heditor.wpixel.view.currentOffset
            self.heditor.wpixel.view.read_image(pixoffset)

    def slidermoved(self, value):
        pixoffset = self.heditor.wpixel.view.currentOffset
        self.heditor.wpixel.view.w = value
        self.sliderspin.setValue(value)
        #        self.setSliderLabel(value)
        self.heditor.wpixel.view.read_image(pixoffset)
        if self.heditor.wpixel.scroll:
            self.heditor.wpixel.scroll.refreshValues()
#        print value

    def scale(self, value):
        self.setZoomLabel(value)
        self.heditor.wpixel.view.scale = value
        pixoffset = self.heditor.wpixel.view.currentOffset
        self.heditor.wpixel.view.read_image(pixoffset)

    def formatChanged(self, format):
        if format == "Indexed 8bit":
            self.icolor.setEnabled(True)
        else:
            self.icolor.setEnabled(False)

    def keyPressEvent(self, kEvent):
        key = kEvent.key()
        if key == Qt.Key_Return or key == Qt.Key_Enter:
            self.apply()
示例#44
0
    def __init__(self, argv):
        QMainWindow.__init__(self)
        self.setWindowTitle("SimSo: Real-Time Scheduling Simulator")

        # Possible actions:
        style = qApp.style()

        # New
        self._newAction = QAction(
            style.standardIcon(QStyle.SP_FileDialogNewFolder), '&New', None)
        self._newAction.setShortcut(Qt.CTRL + Qt.Key_N)
        self._newAction.triggered.connect(self.fileNew)

        # Open
        self._openAction = QAction(
            style.standardIcon(QStyle.SP_DialogOpenButton), '&Open', None)
        self._openAction.setShortcut(Qt.CTRL + Qt.Key_O)
        self._openAction.triggered.connect(self.fileOpen)

        # Save
        self._saveAction = QAction(
            style.standardIcon(QStyle.SP_DialogSaveButton), '&Save', None)
        self._saveAction.setShortcut(Qt.CTRL + Qt.Key_S)
        self._saveAction.triggered.connect(self.fileSave)

        # Save As
        self._saveAsAction = QAction(
            style.standardIcon(QStyle.SP_DialogSaveButton), 'Save &As', None)
        self._saveAsAction.setShortcut(Qt.CTRL + Qt.SHIFT + Qt.Key_S)
        self._saveAsAction.triggered.connect(self.fileSaveAs)

        # Run
        self._runAction = QAction(style.standardIcon(QStyle.SP_MediaPlay),
                                  '&Run', None)
        self._runAction.setShortcut(Qt.CTRL + Qt.Key_R)
        self._runAction.triggered.connect(self.fileRun)

        # Show Model data
        self._modelAction = QAction('&Model data', None)
        self._modelAction.setShortcut(Qt.CTRL + Qt.Key_M)
        #self._ganttAction.setCheckable(True)
        self._modelAction.triggered.connect(self.showModelWindow)

        # Show Gantt
        self._ganttAction = QAction('&Gantt', None)
        self._ganttAction.setShortcut(Qt.CTRL + Qt.Key_G)
        self._ganttAction.setEnabled(False)
        #self._ganttAction.setCheckable(True)
        self._ganttAction.triggered.connect(self.showGantt)

        # Show Results
        self._metricsAction = QAction('&Results', None)
        self._metricsAction.setShortcut(Qt.CTRL + Qt.Key_I)
        self._metricsAction.setEnabled(False)
        #self._metricsAction.setCheckable(True)
        self._metricsAction.triggered.connect(self.showResults)

        # Show Doc
        self._docAction = QAction('&Documentation', None)
        self._docAction.triggered.connect(self.showDocumentation)

        self._aboutAction = QAction('&About SimSo', None)
        self._aboutAction.triggered.connect(self.showAbout)

        # Recent files
        self._recentFileActions = []
        for i in range(5):
            act = QAction(self)
            act.setVisible(False)
            act.triggered.connect(self.openRecentFile)
            self._recentFileActions.append(act)

        # File Menu:
        file_menu = QMenu('&File', self)
        file_menu.addAction(self._newAction)
        file_menu.addAction(self._openAction)
        file_menu.addAction(self._saveAction)
        file_menu.addAction(self._saveAsAction)
        file_menu.addAction(self._runAction)
        file_menu.addSeparator()
        for act in self._recentFileActions:
            file_menu.addAction(act)
        file_menu.addSeparator()
        file_menu.addAction('&Quit', self.fileQuit, Qt.CTRL + Qt.Key_Q)
        self.updateRecentFileActions()

        # View Menu:
        view_menu = QMenu('&View', self)
        view_menu.addAction(self._modelAction)
        view_menu.addAction(self._ganttAction)
        view_menu.addAction(self._metricsAction)

        # Help Menu:
        help_menu = QMenu('&Help', self)
        help_menu.addAction(self._docAction)
        help_menu.addAction(self._aboutAction)

        # Add menus to menuBar:
        self.menuBar().addMenu(file_menu)
        self.menuBar().addMenu(view_menu)
        self.menuBar().addMenu(help_menu)

        # ToolBar:
        self.toolBar = QToolBar("Main ToolBar")
        self.addToolBar(self.toolBar)
        self.toolBar.addAction(self._newAction)
        self.toolBar.addAction(self._openAction)
        self.toolBar.addAction(self._saveAction)
        self.toolBar.addAction(self._runAction)
        self.toolBar.addAction(self._ganttAction)
        self.toolBar.addAction(self._metricsAction)

        # Tab:
        self.main_tab = QTabWidget()
        self.main_tab.setTabsClosable(True)
        self.main_tab.setMovable(True)
        self.main_tab.tabCloseRequested.connect(self.tabCloseRequested)
        self.main_tab.currentChanged.connect(self.tabChanged)
        self.setCentralWidget(self.main_tab)

        # Init statusBar:
        self.statusBar().showMessage("", 2000)

        self._documentation = None

        if argv:
            for arg in argv:
                try:
                    self.open_file(arg)
                except Exception as e:
                    print(e)
        else:
            self.fileNew()
    def createWidgets(self):
        """
        """
        self.listingTab = QTabWidget()
        self.listingTab.setMinimumWidth(650)

        layoutGrid = QGridLayout()

        self.testSetPath = QLineEdit()
        self.testSetName = QLineEdit()

        self.testsTable = TestsTableView(self, core=self.core())
        self.testcasesTable = TestcasesTableView(self, core=self.core())

        self.stepsTable = StepsTableView(self, core=self.core())

        self.listingTab.addTab(self.testsTable, "Test(s)")
        self.listingTab.addTab(self.testcasesTable, "Testcase(s)")
        self.listingTab.addTab(self.stepsTable, "Steps(s)")

        self.ignoreTestcases = QCheckBox("Ignore testcase(s)")
        if self.core().settings().cfg()["export-results"]["ignore-testcase"]:
            self.ignoreTestcases.setCheckState(Qt.Checked)

        self.ignoreUncomplete = QCheckBox("Ignore uncomplete result(s)")
        if self.core().settings().cfg()["export-results"]["ignore-uncomplete"]:
            self.ignoreUncomplete.setCheckState(Qt.Checked)

        self.addMissingFoldersCheckBox = QCheckBox(
            self.tr("Create missing folders"))
        if self.core().settings().cfg()["export-results"]["add-folders"]:
            self.addMissingFoldersCheckBox.setCheckState(Qt.Checked)

        self.addTestsetCheckBox = QCheckBox(self.tr("Create testset"))
        if self.core().settings().cfg()["export-results"]["add-testset"]:
            self.addTestsetCheckBox.setCheckState(Qt.Checked)

        self.addTestinstanceCheckBox = QCheckBox(
            self.tr("Add test instance in testset"))
        if self.core().settings().cfg()["export-results"]["add-testinstance"]:
            self.addTestinstanceCheckBox.setCheckState(Qt.Checked)

        optionsLayout = QHBoxLayout()
        optionsLayout.addWidget(self.ignoreTestcases)
        optionsLayout.addWidget(self.ignoreUncomplete)
        optionsLayout.addStretch(1)

        # optionsTsLayout = QHBoxLayout()
        # optionsTsLayout.addWidget(self.addTestsetCheckBox)
        # optionsTsLayout.addWidget(self.addTestinstanceCheckBox)
        # optionsTsLayout.addStretch(1)

        layoutGrid.addWidget(QLabel("Remote Test Set Path:"), 0, 0)
        layoutGrid.addWidget(self.testSetPath, 0, 1)
        # layoutGrid.addWidget(self.addMissingFoldersCheckBox, 1, 1)
        layoutGrid.addWidget(QLabel("Remote Test Set Name:"), 2, 0)
        layoutGrid.addWidget(self.testSetName, 2, 1)
        # layoutGrid.addLayout(optionsTsLayout, 3, 1)
        layoutGrid.addWidget(QLabel("Local result(s):"), 4, 0)
        layoutGrid.addLayout(optionsLayout, 4, 1)
        layoutGrid.addWidget(QLabel("Test(s) Verdict:"), 5, 0)
        layoutGrid.addWidget(self.listingTab, 5, 1)

        self.exportStatusLabel = QLabel("Status: Disconnected", self)
        self.exportButton = QPushButton(self.tr("Export Result"), self)
        self.exportButton.setMinimumWidth(300)

        layoutRight = QHBoxLayout()
        layoutRight.addWidget(self.exportButton)
        layoutRight.addWidget(self.exportStatusLabel)
        layoutRight.addStretch(1)

        layoutGrid.addWidget(QLabel("Controls:"), 6, 0)
        layoutGrid.addLayout(layoutRight, 6, 1)

        layoutMain = QHBoxLayout()
        layoutMain.addLayout(layoutGrid)

        self.setLayout(layoutMain)
class ModelerParametersDialog(QDialog):

    ENTER_NAME = '[Enter name if this is a final result]'
    NOT_SELECTED = '[Not selected]'
    USE_MIN_COVERING_EXTENT = '[Use min covering extent]'

    def __init__(self, alg, model, algName=None):
        QDialog.__init__(self)
        self.setModal(True)
        #The algorithm to define in this dialog. It is an instance of GeoAlgorithm
        self._alg = alg
        #The resulting algorithm after the user clicks on OK. it is an instance of the container Algorithm class
        self.alg = None
        #The model this algorithm is going to be added to
        self.model = model
        #The name of the algorithm in the model, in case we are editing it and not defining it for the first time
        self._algName = algName
        self.setupUi()
        self.params = None

    def setupUi(self):
        self.labels = {}
        self.widgets = {}
        self.checkBoxes = {}
        self.showAdvanced = False
        self.valueItems = {}
        self.dependentItems = {}
        self.resize(650, 450)
        self.buttonBox = QDialogButtonBox()
        self.buttonBox.setOrientation(Qt.Horizontal)
        self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel
                                          | QDialogButtonBox.Ok)
        tooltips = self._alg.getParameterDescriptions()
        self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.verticalLayout = QVBoxLayout()
        self.verticalLayout.setSpacing(5)
        self.verticalLayout.setMargin(20)

        hLayout = QHBoxLayout()
        hLayout.setSpacing(5)
        hLayout.setMargin(0)
        descriptionLabel = QLabel(self.tr("Description"))
        self.descriptionBox = QLineEdit()
        self.descriptionBox.setText(self._alg.name)
        hLayout.addWidget(descriptionLabel)
        hLayout.addWidget(self.descriptionBox)
        self.verticalLayout.addLayout(hLayout)
        line = QFrame()
        line.setFrameShape(QFrame.HLine)
        line.setFrameShadow(QFrame.Sunken)
        self.verticalLayout.addWidget(line)

        for param in self._alg.parameters:
            if param.isAdvanced:
                self.advancedButton = QPushButton()
                self.advancedButton.setText(
                    self.tr('Show advanced parameters'))
                self.advancedButton.setMaximumWidth(150)
                self.advancedButton.clicked.connect(
                    self.showAdvancedParametersClicked)
                self.verticalLayout.addWidget(self.advancedButton)
                break
        for param in self._alg.parameters:
            if param.hidden:
                continue
            desc = param.description
            if isinstance(param, ParameterExtent):
                desc += '(xmin, xmax, ymin, ymax)'
            label = QLabel(desc)
            self.labels[param.name] = label
            widget = self.getWidgetFromParameter(param)
            self.valueItems[param.name] = widget
            if param.name in tooltips.keys():
                tooltip = tooltips[param.name]
            else:
                tooltip = param.description
            label.setToolTip(tooltip)
            widget.setToolTip(tooltip)
            if param.isAdvanced:
                label.setVisible(self.showAdvanced)
                widget.setVisible(self.showAdvanced)
                self.widgets[param.name] = widget
            self.verticalLayout.addWidget(label)
            self.verticalLayout.addWidget(widget)

        for output in self._alg.outputs:
            if output.hidden:
                continue
            if isinstance(output, (OutputRaster, OutputVector, OutputTable,
                                   OutputHTML, OutputFile, OutputDirectory)):
                label = QLabel(output.description + '<' +
                               output.__class__.__name__ + '>')
                item = QLineEdit()
                if hasattr(item, 'setPlaceholderText'):
                    item.setPlaceholderText(ModelerParametersDialog.ENTER_NAME)
                self.verticalLayout.addWidget(label)
                self.verticalLayout.addWidget(item)
                self.valueItems[output.name] = item

        label = QLabel(' ')
        self.verticalLayout.addWidget(label)
        label = QLabel(self.tr('Parent algorithms'))
        self.dependenciesPanel = self.getDependenciesPanel()
        self.verticalLayout.addWidget(label)
        self.verticalLayout.addWidget(self.dependenciesPanel)

        self.verticalLayout.addStretch(1000)
        self.setLayout(self.verticalLayout)

        self.setPreviousValues()
        self.setWindowTitle(self._alg.name)
        self.verticalLayout2 = QVBoxLayout()
        self.verticalLayout2.setSpacing(2)
        self.verticalLayout2.setMargin(0)
        self.tabWidget = QTabWidget()
        self.tabWidget.setMinimumWidth(300)
        self.paramPanel = QWidget()
        self.paramPanel.setLayout(self.verticalLayout)
        self.scrollArea = QScrollArea()
        self.scrollArea.setWidget(self.paramPanel)
        self.scrollArea.setWidgetResizable(True)
        self.tabWidget.addTab(self.scrollArea, self.tr('Parameters'))
        self.webView = QWebView()

        html = None
        url = None
        isText, help = self._alg.help()
        if help is not None:
            if isText:
                html = help
            else:
                url = QUrl(help)
        else:
            html = self.tr('<h2>Sorry, no help is available for this '
                           'algorithm.</h2>')
        try:
            if html:
                self.webView.setHtml(html)
            elif url:
                self.webView.load(url)
        except:
            self.webView.setHtml(
                self.tr('<h2>Could not open help file :-( </h2>'))
        self.tabWidget.addTab(self.webView, 'Help')
        self.verticalLayout2.addWidget(self.tabWidget)
        self.verticalLayout2.addWidget(self.buttonBox)
        self.setLayout(self.verticalLayout2)
        self.buttonBox.accepted.connect(self.okPressed)
        self.buttonBox.rejected.connect(self.cancelPressed)
        QMetaObject.connectSlotsByName(self)

    def getAvailableDependencies(self):
        if self._algName is None:
            dependent = []
        else:
            dependent = self.model.getDependentAlgorithms(self._algName)
        opts = []
        for alg in self.model.algs.values():
            if alg.name not in dependent:
                opts.append(alg)
        return opts

    def getDependenciesPanel(self):
        return MultipleInputPanel(
            [alg.algorithm.name for alg in self.getAvailableDependencies()])

    def showAdvancedParametersClicked(self):
        self.showAdvanced = not self.showAdvanced
        if self.showAdvanced:
            self.advancedButton.setText(self.tr('Hide advanced parameters'))
        else:
            self.advancedButton.setText(self.tr('Show advanced parameters'))
        for param in self._alg.parameters:
            if param.isAdvanced:
                self.labels[param.name].setVisible(self.showAdvanced)
                self.widgets[param.name].setVisible(self.showAdvanced)

    def getAvailableValuesOfType(self, paramType, outType=None):
        values = []
        inputs = self.model.inputs
        for i in inputs.values():
            param = i.param
            if isinstance(param, paramType):
                values.append(ValueFromInput(param.name))
        if outType is None:
            return values
        if self._algName is None:
            dependent = []
        else:
            dependent = self.model.getDependentAlgorithms(self._algName)
        for alg in self.model.algs.values():
            if alg.name not in dependent:
                for out in alg.algorithm.outputs:
                    if isinstance(out, outType):
                        values.append(ValueFromOutput(alg.name, out.name))

        return values

    def resolveValueDescription(self, value):
        if isinstance(value, ValueFromInput):
            return self.model.inputs[value.name].param.description
        else:
            alg = self.model.algs[value.alg]
            return self.tr("'%s' from algorithm '%s'") % (
                alg.algorithm.getOutputFromName(
                    value.output).description, alg.description)

    def getWidgetFromParameter(self, param):
        if isinstance(param, ParameterRaster):
            item = QComboBox()
            layers = self.getAvailableValuesOfType(ParameterRaster,
                                                   OutputRaster)
            if param.optional:
                item.addItem(self.NOT_SELECTED, None)
            for layer in layers:
                item.addItem(self.resolveValueDescription(layer), layer)
        elif isinstance(param, ParameterVector):
            item = QComboBox()
            layers = self.getAvailableValuesOfType(ParameterVector,
                                                   OutputVector)
            if param.optional:
                item.addItem(self.NOT_SELECTED, None)
            for layer in layers:
                item.addItem(self.resolveValueDescription(layer), layer)
        elif isinstance(param, ParameterTable):
            item = QComboBox()
            tables = self.getAvailableValuesOfType(ParameterTable, OutputTable)
            layers = self.getAvailableValuesOfType(ParameterVector,
                                                   OutputVector)
            if param.optional:
                item.addItem(self.NOT_SELECTED, None)
            for table in tables:
                item.addItem(self.resolveValueDescription(table), table)
            for layer in layers:
                item.addItem(self.resolveValueDescription(layer), layer)
        elif isinstance(param, ParameterBoolean):
            item = QComboBox()
            item.addItem('Yes')
            item.addItem('No')
            bools = self.getAvailableValuesOfType(ParameterBoolean, None)
            for b in bools:
                item.addItem(self.resolveValueDescription(b), b)
        elif isinstance(param, ParameterSelection):
            item = QComboBox()
            item.addItems(param.options)
        elif isinstance(param, ParameterFixedTable):
            item = FixedTablePanel(param)
        elif isinstance(param, ParameterRange):
            item = RangePanel(param)
        elif isinstance(param, ParameterMultipleInput):
            if param.datatype == ParameterMultipleInput.TYPE_VECTOR_ANY:
                options = self.getAvailableValuesOfType(
                    ParameterVector, OutputVector)
            else:
                options = self.getAvailableValuesOfType(
                    ParameterRaster, OutputRaster)
            opts = []
            for opt in options:
                opts.append(self.resolveValueDescription(opt))
            item = MultipleInputPanel(opts)
        elif isinstance(param, ParameterString):
            strings = self.getAvailableValuesOfType(ParameterString,
                                                    OutputString)
            options = [(self.resolveValueDescription(s), s) for s in strings]
            if param.multiline:
                item = MultilineTextPanel(options)
                item.setText(unicode(param.default))
            else:
                item = QComboBox()
                item.setEditable(True)
                for desc, val in options:
                    item.addItem(desc, val)
                item.setEditText(unicode(param.default))
        elif isinstance(param, ParameterTableField):
            item = QComboBox()
            item.setEditable(True)
            fields = self.getAvailableValuesOfType(ParameterTableField, None)
            for f in fields:
                item.addItem(self.resolveValueDescription(f), f)
        elif isinstance(param, ParameterNumber):
            item = QComboBox()
            item.setEditable(True)
            numbers = self.getAvailableValuesOfType(ParameterNumber,
                                                    OutputNumber)
            for n in numbers:
                item.addItem(self.resolveValueDescription(n), n)
            item.setEditText(str(param.default))
        elif isinstance(param, ParameterCrs):
            item = CrsSelectionPanel(param.default)
        elif isinstance(param, ParameterExtent):
            item = QComboBox()
            item.setEditable(True)
            extents = self.getAvailableValuesOfType(ParameterExtent,
                                                    OutputExtent)
            if self.canUseAutoExtent():
                item.addItem(self.USE_MIN_COVERING_EXTENT, None)
            for ex in extents:
                item.addItem(self.resolveValueDescription(ex), ex)
            if not self.canUseAutoExtent():
                item.setEditText(str(param.default))
        elif isinstance(param, ParameterFile):
            item = QComboBox()
            item.setEditable(True)
            files = self.getAvailableValuesOfType(ParameterFile, OutputFile)
            for f in files:
                item.addItem(self.resolveValueDescription(f), f)
        elif isinstance(param, ParameterGeometryPredicate):
            item = GeometryPredicateSelectionPanel(param.enabledPredicates)
        else:
            item = QLineEdit()
            try:
                item.setText(str(param.default))
            except:
                pass
        return item

    def canUseAutoExtent(self):
        for param in self._alg.parameters:
            if isinstance(
                    param,
                (ParameterRaster, ParameterVector, ParameterMultipleInput)):
                return True
        return False

    def setTableContent(self):
        params = self._alg.parameters
        outputs = self._alg.outputs
        visibleParams = [p for p in params if not p.hidden]
        visibleOutputs = [p for o in outputs if not o.hidden]
        self.tableWidget.setRowCount(len(visibleParams) + len(visibleOutputs))

        for i, param in visibleParams:
            item = QTableWidgetItem(param.description)
            item.setFlags(Qt.ItemIsEnabled)
            self.tableWidget.setItem(i, 0, item)
            item = self.getWidgetFromParameter(param)
            self.valueItems[param.name] = item
            self.tableWidget.setCellWidget(i, 1, item)
            self.tableWidget.setRowHeight(i, 22)

        for i, output in visibleOutputs:
            item = QTableWidgetItem(output.description + '<' +
                                    output.__module__.split('.')[-1] + '>')
            item.setFlags(Qt.ItemIsEnabled)
            self.tableWidget.setItem(i, 0, item)
            item = QLineEdit()
            if hasattr(item, 'setPlaceholderText'):
                item.setPlaceholderText(ModelerParametersDialog.ENTER_NAME)
            self.valueItems[output.name] = item
            self.tableWidget.setCellWidget(i, 1, item)
            self.tableWidget.setRowHeight(i, 22)

    def setComboBoxValue(self, combo, value, param):
        if isinstance(value, list):
            value = value[0]
        items = [combo.itemData(i) for i in range(combo.count())]
        try:
            idx = items.index(value)
            combo.setCurrentIndex(idx)
            return
        except ValueError:
            pass
        if combo.isEditable():
            if value is not None:
                combo.setEditText(unicode(value))
        elif isinstance(param, ParameterSelection):
            combo.setCurrentIndex(int(value))
        elif isinstance(param, ParameterBoolean):
            if value:
                combo.setCurrentIndex(0)
            else:
                combo.setCurrentIndex(1)

    def setPreviousValues(self):
        if self._algName is not None:
            alg = self.model.algs[self._algName]
            self.descriptionBox.setText(alg.description)
            for param in alg.algorithm.parameters:
                if param.hidden:
                    continue
                widget = self.valueItems[param.name]
                value = alg.params[param.name]
                if isinstance(
                        param,
                    (ParameterRaster, ParameterVector, ParameterTable,
                     ParameterTableField, ParameterSelection, ParameterNumber,
                     ParameterBoolean, ParameterExtent, ParameterFile)):
                    self.setComboBoxValue(widget, value, param)
                elif isinstance(param, ParameterString):
                    if param.multiline:
                        widget.setValue(value)
                    else:
                        self.setComboBoxValue(widget, value, param)
                elif isinstance(param, ParameterCrs):
                    widget.setAuthId(value)
                elif isinstance(param, ParameterFixedTable):
                    pass  # TODO!
                elif isinstance(param, ParameterMultipleInput):
                    if param.datatype == ParameterMultipleInput.TYPE_VECTOR_ANY:
                        options = self.getAvailableValuesOfType(
                            ParameterVector, OutputVector)
                    else:
                        options = self.getAvailableValuesOfType(
                            ParameterRaster, OutputRaster)
                    selected = []
                    for i, opt in enumerate(options):
                        if opt in value:
                            selected.append(i)
                    widget.setSelectedItems(selected)
                elif isinstance(param, ParameterGeometryPredicate):
                    widget.setValue(value)

            for name, out in alg.outputs.iteritems():
                widget = self.valueItems[name].setText(out.description)

            selected = []
            dependencies = self.getAvailableDependencies()
            for idx, dependency in enumerate(dependencies):
                if dependency in alg.dependencies:
                    selected.append(idx)

            self.dependenciesPanel.setSelectedItems(selected)

    def createAlgorithm(self):
        alg = Algorithm(self._alg.commandLineName())
        alg.setName(self.model)
        alg.description = self.descriptionBox.text()
        params = self._alg.parameters
        outputs = self._alg.outputs
        for param in params:
            if param.hidden:
                continue
            if not self.setParamValue(alg, param, self.valueItems[param.name]):
                return None
        for output in outputs:
            if not output.hidden:
                name = unicode(self.valueItems[output.name].text())
                if name.strip(
                ) != '' and name != ModelerParametersDialog.ENTER_NAME:
                    alg.outputs[output.name] = ModelerOutput(name)

        selectedOptions = self.dependenciesPanel.selectedoptions
        availableDependencies = self.getAvailableDependencies()
        for selected in selectedOptions:
            alg.dependencies.append(availableDependencies[selected].name)

        return alg

    def setParamValueLayerOrTable(self, alg, param, widget):
        idx = widget.currentIndex()
        if idx < 0:
            return False
        else:
            value = widget.itemData(widget.currentIndex())
            alg.params[param.name] = value
            return True

    def setParamTableFieldValue(self, alg, param, widget):
        idx = widget.findText(widget.currentText())
        if idx < 0:
            s = str(widget.currentText()).strip()
            if s == '':
                if param.optional:
                    alg.params[param.name] = None
                    return True
                else:
                    return False
            else:
                alg.params[param.name] = s
                return True
        else:
            alg.params[param.name] = widget.itemData(widget.currentIndex())
        return True

    def setParamStringValue(self, alg, param, widget):
        if param.multiline:
            value = widget.getValue()
            option = widget.getOption()
            if option == MultilineTextPanel.USE_TEXT:
                if value == '':
                    if param.optional:
                        alg.params[param.name] = None
                        return True
                    else:
                        return False
                else:
                    alg.params[param.name] = value
            else:
                alg.params[param.name] = value
        else:
            idx = widget.findText(widget.currentText())
            if idx < 0:
                value = widget.currentText().strip()
                if value == '':
                    if param.optional:
                        alg.params[param.name] = None
                        return True
                    else:
                        return False
                else:
                    alg.params[param.name] = value
            else:
                alg.params[param.name] = widget.itemData(widget.currentIndex())
        return True

    def setParamFileValue(self, alg, param, widget):
        idx = widget.findText(widget.currentText())
        if idx < 0:
            value = widget.currentText()
        else:
            value = widget.itemData(widget.currentIndex())
        alg.params[param.name] = value
        return True

    def setParamNumberValue(self, alg, param, widget):
        idx = widget.findText(widget.currentText())
        if idx < 0:
            s = widget.currentText()
            try:
                value = float(s)
            except:
                return False
        else:
            value = widget.itemData(widget.currentIndex())
        alg.params[param.name] = value
        return True

    def setParamExtentValue(self, alg, param, widget):
        idx = widget.findText(widget.currentText())
        if idx < 0:
            s = str(widget.currentText())
            try:
                tokens = s.split(',')
                if len(tokens) != 4:
                    return False
                for token in tokens:
                    float(token)
            except:
                return False
            alg.params[param.name] = [s]
        else:
            value = widget.itemData(widget.currentIndex())
            alg.params[param.name] = value
        return True

    def setParamValue(self, alg, param, widget):
        if isinstance(param,
                      (ParameterRaster, ParameterVector, ParameterTable)):
            return self.setParamValueLayerOrTable(alg, param, widget)
        elif isinstance(param, ParameterBoolean):
            if widget.currentIndex() < 2:
                value = widget.currentIndex() == 0
            else:
                value = widget.itemData(widget.currentIndex())
            alg.params[param.name] = value
            return True
        elif isinstance(param, ParameterString):
            return self.setParamStringValue(alg, param, widget)
        elif isinstance(param, ParameterNumber):
            return self.setParamNumberValue(alg, param, widget)
        elif isinstance(param, ParameterExtent):
            return self.setParamExtentValue(alg, param, widget)
        elif isinstance(param, ParameterFile):
            return self.setParamFileValue(alg, param, widget)
        elif isinstance(param, ParameterSelection):
            alg.params[param.name] = widget.currentIndex()
            return True
        elif isinstance(param, ParameterRange):
            alg.params[param.name] = widget.getValue()
            return True
        elif isinstance(param, ParameterCrs):
            authid = widget.getValue()
            if authid is None:
                alg.params[param.name] = None
            else:
                alg.params[param.name] = authid
            return True
        elif isinstance(param, ParameterFixedTable):
            alg.params[param.name] = ParameterFixedTable.tableToString(
                widget.table)
            return True
        elif isinstance(param, ParameterTableField):
            return self.setParamTableFieldValue(alg, param, widget)
        elif isinstance(param, ParameterMultipleInput):
            if param.datatype == ParameterMultipleInput.TYPE_VECTOR_ANY:
                options = self.getAvailableValuesOfType(
                    ParameterVector, OutputVector)
            else:
                options = self.getAvailableValuesOfType(
                    ParameterRaster, OutputRaster)
            values = [options[i] for i in widget.selectedoptions]
            if len(values) == 0 and not param.optional:
                return False
            alg.params[param.name] = values
            return True
        elif isinstance(param, ParameterGeometryPredicate):
            alg.params[param.name] = widget.value()
            return True
        else:
            alg.params[param.name] = unicode(widget.text())
            return True

    def okPressed(self):
        self.alg = self.createAlgorithm()
        if self.alg is not None:
            self.close()
        else:
            QMessageBox.warning(self, self.tr('Unable to add algorithm'),
                                self.tr('Wrong or missing parameter values'))

    def cancelPressed(self):
        self.alg = None
        self.close()
示例#47
0
文件: apbba.py 项目: huyong1979/aphla
class ApBbaDlg(QDialog):
    def __init__(self, parent = None, **kwargs):
        super(ApBbaDlg, self).__init__(parent)

        self.bpms  = []
        self.quads = []
        self.corrs  = []
        self.quad_dkicks = []
        self.cor_dkicks = []

        self.bba = ap.bba.BbaBowtie()

        self.table = QTableWidget(0, 5)
        self.table.setMinimumHeight(120)
        self.table.setMinimumWidth(500)
        self.table.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        hdview = QHeaderView(Qt.Horizontal)
        self.table.setHorizontalHeaderLabels(
            ['QUAD', 'BPM.field', 'BPM center', "Corr", "Kick"])

        fmbox = QFormLayout()
        self.subprogress = QProgressBar()
        self.subprogress.setTextVisible(True)
        self.subprogress.setSizePolicy(QSizePolicy.MinimumExpanding,
                                       QSizePolicy.Fixed)
        self.progress    = QProgressBar()
        self.progress.setTextVisible(True)
        self.progress.setSizePolicy(QSizePolicy.MinimumExpanding,
                                    QSizePolicy.Fixed)
        fmbox.setFieldGrowthPolicy(QFormLayout.ExpandingFieldsGrow)
        fmbox.addRow("Current BPM", self.subprogress)
        fmbox.addRow("All Alignment", self.progress)
        #self.progress.setMaximum(self.repeatbox.value())
        vbox = QVBoxLayout()
        vbox.addWidget(self.table)
        vbox.addLayout(fmbox)

        #hbox.addStretch()
        self.widtab = QTabWidget()

        vbox.addWidget(self.widtab)

        self.setLayout(vbox)

        self.connect(self.widtab, SIGNAL("currentChanged(int)"),
                     self.activateResult)
        self.connect(self.table, SIGNAL("cellClicked(int, int)"),
                     self.activateResult)
        #self.bbathread = ApBbaThread()
        #self.connect(self.bbathread,
        #             SIGNAL("aligned(QString, QString, float, float)"),
        #             self.setResult)
        #self.connect(self.bbathread,
        #             SIGNAL("startAlign(QString, QString, QString)"),
        #             self.appendRecord)

        #self.connect(self.bbathread,
        #             SIGNAL("aligned(QString, QString, float, float)"),
        #             self.bbadlg.appendResult)

    def setInput(self, **kwargs):
        self.bpms = kwargs.get('bpms', [])
        self.quads = kwargs.get('quads', [])
        self.cors  = kwargs.get('cors', [])
        self.quad_dkicks = kwargs.get('quad_dkicks', [])
        self.cor_dkicks = kwargs.get('cor_dkicks', [])

    def runAlignment(self, **kwargs):
        self.setInput(**kwargs)
        #self.bbathread.start()
        print("Starting %d measurements" % len(self.bpms))
        self.progress.setMaximum(len(self.bpms))
        self.subprogress.setMaximum(100)
        from cothread.catools import caget, caput
        print(__file__, "BBA align", caget('V:2-SR:C30-BI:G2{PH1:11}SA:X'))
        self.table.setRowCount(len(self.bpms))
        for i,bpmrec in enumerate(self.bpms):
            print(i, bpmrec[0].name, self.quads[i][0].name)
            self.bba.setInput(bpmrec, self.quads[i], self.cors[i],
                              self.quad_dkicks[i], self.cor_dkicks[i])
            #self.emit(SIGNAL("startAlign(QString, QString, QString)"),
            #          self.quads[i][0].name, bpmrec[0].name, bpmrec[1])
            self.setNames(i, self.quads[i][0].name, bpmrec[0].name,
                          bpmrec[1], self.cors[i][0].name)
            self.bba.align(verbose=2, guihook = QApplication.processEvents,
                           logger = None, progress = self.subprogress)

            cv1 = BbaMplCanvas()
            cv2 = BbaMplCanvas()
            self.bba.plot(cv1.axes, cv2.axes, factor=(1e6, 1e6))
            cv1.draw()
            cv2.draw()

            wid = QWidget(self)
            hbox = QHBoxLayout()
            hbox.addWidget(cv1)
            hbox.addWidget(cv2)
            wid.setLayout(hbox)
            self.widtab.addTab(wid, "%s.%s" % (bpmrec[0].name, bpmrec[1]))
            self.widtab.setCurrentIndex(i)

            #time.sleep(.1)

            #self.emit(SIGNAL("aligned(QString, QString, float, float)"),
            #          bpmrec[0].name, bpmrec[1], 0.0, 0.0)
            self.setResult(i, bpmrec[0].name, bpmrec[1],
                           self.bba.bpm_fitted, self.bba.cor_fitted)
            self.progress.setValue(i + 1)

    def activateResult(self, i = 0, j = 0):
        if i < self.widtab.count() and i != self.widtab.currentIndex():
            self.widtab.setCurrentIndex(i)
        if i < self.table.rowCount() and i != self.table.currentRow():
            self.table.setCurrentCell(i, 1)

    def setNames(self, i, quadname, bpmname, fld, corname):
        self.table.setItem(i, 0, QTableWidgetItem(quadname))
        self.table.setItem(i, 1,
                           QTableWidgetItem("{0}.{1}".format(bpmname, fld)))
        self.table.setItem(i, 3, QTableWidgetItem(corname))

    def setResult(self, i, bpmname, fld, bpmval, corval):
        #self.table.setItem(n, 1, QTableWidgetItem(bpmname))
        #self.table.setItem(n, 2, QTableWidgetItem(fld))
        self.table.setItem(i, 2, QTableWidgetItem("%g" % bpmval))
        self.table.setItem(i, 4, QTableWidgetItem("%g" % corval))
        self.table.setCurrentCell(i, 1)
示例#48
0
class MainWidget(QMainWindow):
    def __init__(self, parent=None):
        super(MainWidget,
              self).__init__(parent,
                             windowTitle='GithubRemote',
                             windowIcon=QIcon(image_path('git.png')),
                             geometry=QRect(300, 300, 600, 372))

        self.repo_pixmap = QPixmap(image_path('book_16.png'))
        self.big_repo_pixmap = QPixmap(image_path('book_32.png'))
        self.repo_fork_pixmap = QPixmap(image_path('book_fork_16.png'))
        self.star_pixmap = QPixmap(image_path('star_16.png'))
        self.big_star_pixmap = QPixmap(image_path('star_32.png'))
        self.fork_pixmap = QPixmap(image_path('fork_16.png'))
        self.eye_pixmap = QPixmap(image_path('eye_16.png'))

        self.github = None

        # Actions

        self.repoAddAction = QAction(QIcon(image_path('plus_48.png')),
                                     '&Add Repo',
                                     self,
                                     statusTip='Add a new repo')
        self.repoAddAction.triggered.connect(self.repoAdd)

        self.repoRemoveAction = QAction(QIcon(image_path('minus.png')),
                                        '&Remove Repo',
                                        self,
                                        statusTip='Remove repo')
        self.repoRemoveAction.triggered.connect(self.repoRemove)

        self.repoRefreshAction = QAction(QIcon(image_path('refresh.png')),
                                         'Refresh',
                                         self,
                                         statusTip='Refresh list of repos')
        self.repoRefreshAction.triggered.connect(self.reposRefresh)
        self.repoRefreshAction.triggered.connect(self.starsRefresh)

        self.addAccountAction = QAction('Add Account',
                                        self,
                                        statusTip='Add Account')
        self.addAccountAction.triggered.connect(self.addAccount)

        # userPushButton - Displays the current active username and
        # image on the top right of the toolbar.

        self.userButtonMenu = UserButtonMenu(32, 32)

        # ToolBar

        self.toolBar = self.addToolBar('Main')
        self.toolBar.setMovable(False)
        self.toolBar.setFloatable(False)
        spacer = QWidget()
        spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.toolBar.addAction(self.repoAddAction)
        self.toolBar.addAction(self.repoRemoveAction)
        self.toolBar.addAction(self.repoRefreshAction)
        self.toolBar.addWidget(spacer)
        self.toolBar.addWidget(self.userButtonMenu)

        # Menu

        menuBar = self.menuBar()
        fileMenu = menuBar.addMenu('&File')
        actionMenu = menuBar.addMenu('&Action')
        fileMenu.addAction(self.addAccountAction)
        actionMenu.addAction(self.repoAddAction)
        actionMenu.addAction(self.repoRemoveAction)
        actionMenu.addAction(self.repoRefreshAction)

        # StatusBar

        statusBar = self.statusBar()
        self.setStatusBar(statusBar)

        # reposTableWidget - Displays a list of the users repositories

        self.reposTableWidget = QTableWidget(
            0,
            5,
            selectionBehavior=QAbstractItemView.SelectRows,
            selectionMode=QAbstractItemView.SingleSelection,
            editTriggers=QAbstractItemView.NoEditTriggers,
            itemSelectionChanged=self.actionsUpdate)
        self.reposTableWidget.horizontalHeader().setResizeMode(
            QHeaderView.ResizeToContents)
        self.reposTableWidget.horizontalHeader().setResizeMode(
            1, QHeaderView.Stretch)
        self.reposTableWidget.horizontalHeader().setVisible(False)
        self.reposTableWidget.verticalHeader().setVisible(False)
        self.reposTableWidget.setShowGrid(False)
        self.reposTableWidget.verticalHeader().setMinimumSectionSize(25)

        # repoTab - Layout
        reposTab = QWidget()
        reposTabLayout = QVBoxLayout(reposTab)
        reposTabLayout.addWidget(self.reposTableWidget)
        reposTab.setLayout(reposTabLayout)

        # starsTableWidget - Displays a list of the users repositories

        self.starsTableWidget = QTableWidget(
            0,
            5,
            selectionBehavior=QAbstractItemView.SelectRows,
            selectionMode=QAbstractItemView.SingleSelection,
            editTriggers=QAbstractItemView.NoEditTriggers,
            itemSelectionChanged=self.actionsUpdate)
        self.starsTableWidget.horizontalHeader().setResizeMode(
            QHeaderView.ResizeToContents)
        self.starsTableWidget.horizontalHeader().setResizeMode(
            1, QHeaderView.Stretch)
        self.starsTableWidget.horizontalHeader().setVisible(False)
        self.starsTableWidget.verticalHeader().setVisible(False)
        self.starsTableWidget.setShowGrid(False)
        self.starsTableWidget.verticalHeader().setMinimumSectionSize(25)

        # repoTab - Layout
        starsTab = QWidget()
        starsTabLayout = QVBoxLayout(starsTab)
        starsTabLayout.addWidget(self.starsTableWidget)
        starsTab.setLayout(starsTabLayout)

        # Tab Widget
        self.tabs = QTabWidget()
        self.tabs.setTabBar(FlippedTabBar(self))
        self.tabs.addTab(reposTab, QIcon(self.big_repo_pixmap), "repos")
        self.tabs.addTab(starsTab, QIcon(self.big_star_pixmap), "stars")
        self.tabs.setTabPosition(QTabWidget.West)

        # Layout

        self.setCentralWidget(self.tabs)
        self.actionsUpdate()
        self.show()

        # Update

        self.loadUserMenu()
        if self.activeUserAction:
            self.activeUserAction.setVisible(False)
        self.authenticate()
        self.actionsUpdate()
        self.reposRefresh()
        self.starsRefresh()
        self.updateImage()

    @waiting_effects
    def updateImage(self):

        try:
            url = self.github.get_user().avatar_url
        except (GithubException, AttributeError):
            return
        data = urllib.urlopen(url).read()
        pixmap = QPixmap()
        pixmap.loadFromData(data)
        self.activeUserAction.setIcon(QIcon(pixmap))
        self.userButtonMenu.setPixmap(pixmap)
        self.userButtonMenu.setText(self.github.get_user().login)

    @waiting_effects
    def loadUserMenu(self):

        action = None
        for _, username, token in generate_tokens(CONFIG_PATH, 'github'):

            try:
                url = Github(token).get_user().avatar_url
            except (GithubException, AttributeError):
                action = QAction(username, self, triggered=self.changeActive)
                self.userButtonMenu.addAction(action)
                continue
            data = urllib.urlopen(url).read()
            pixmap = QPixmap()
            pixmap.loadFromData(data)
            action = QAction(QIcon(pixmap),
                             username,
                             self,
                             triggered=self.changeActive)
            action.setIconVisibleInMenu(True)
            self.userButtonMenu.addAction(action)

        self.activeUserAction = action

    def changeActive(self):

        sender = self.sender()

        self.activeUserAction.setVisible(True)
        self.activeUserAction = sender
        self.activeUserAction.setVisible(False)
        self.authenticate()
        self.actionsUpdate()
        self.reposRefresh()
        self.starsRefresh()
        self.updateImage()

    @waiting_effects
    def reposRefresh(self):

        self.reposTableWidget.clearContents()

        try:
            repos = self.github.get_user().get_repos()
            self.reposTableWidget.setRowCount(
                self.github.get_user().public_repos)
        except (GithubException, AttributeError):
            return
        for row, repo in enumerate(repos):
            imageLabel = QLabel()
            if repo.fork:
                imageLabel.setPixmap(self.repo_fork_pixmap)
            else:
                imageLabel.setPixmap(self.repo_pixmap)
            imageLabel.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
            imageLabel.setMargin(5)

            self.reposTableWidget.setCellWidget(row, 0, imageLabel)
            label = QLabel('<b>{}</b><br />{}'.format(str(repo.name),
                                                      str(repo.description)))
            label.setAlignment(Qt.AlignVCenter)
            label.setMargin(5)
            label.setWordWrap(True)
            self.reposTableWidget.setCellWidget(row, 1, label)
            self.reposTableWidget.setItem(
                row, 2,
                QTableWidgetItem(QIcon(self.star_pixmap),
                                 str(repo.stargazers_count)))
            self.reposTableWidget.setItem(
                row, 3,
                QTableWidgetItem(QIcon(self.eye_pixmap),
                                 str(repo.watchers_count)))
            self.reposTableWidget.setItem(
                row, 4,
                QTableWidgetItem(QIcon(self.fork_pixmap),
                                 str(repo.forks_count)))

        self.reposTableWidget.resizeRowsToContents()

    @waiting_effects
    def starsRefresh(self):

        self.starsTableWidget.clearContents()

        try:
            starred = self.github.get_user().get_starred()
            self.starsTableWidget.setRowCount(
                self.github.get_user().public_repos)
        except (GithubException, AttributeError):
            return
        for row, repo in enumerate(starred):
            imageLabel = QLabel()
            if repo.fork:
                imageLabel.setPixmap(self.repo_fork_pixmap)
            else:
                imageLabel.setPixmap(self.repo_pixmap)
            imageLabel.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
            imageLabel.setMargin(5)

            self.starsTableWidget.setCellWidget(row, 0, imageLabel)
            label = QLabel(u'<b>{}/{}</b><br />{}'.format(
                unicode(repo.owner.login), unicode(repo.name),
                unicode(repo.description)))
            label.setAlignment(Qt.AlignVCenter)
            label.setMargin(5)
            label.setWordWrap(True)
            self.starsTableWidget.setCellWidget(row, 1, label)
            self.starsTableWidget.setItem(
                row, 2, QTableWidgetItem(QIcon(self.star_pixmap), '0'))
            self.starsTableWidget.setItem(
                row, 3,
                QTableWidgetItem(QIcon(self.eye_pixmap),
                                 str(repo.watchers_count)))
            self.starsTableWidget.setItem(
                row, 4,
                QTableWidgetItem(QIcon(self.fork_pixmap),
                                 str(repo.forks_count)))

        self.starsTableWidget.resizeRowsToContents()

    @waiting_effects
    def authenticate(self):

        if self.activeUserAction:
            username = str(self.activeUserAction.text())
            token = load_token(CONFIG_PATH, 'github', username)
            self.github = Github(token)
        else:
            self.github = None

    def actionsUpdate(self):
        # TODO disable if no user is logged in
        if self.github is None:
            self.repoAddAction.setEnabled(False)
            self.repoRemoveAction.setEnabled(False)
            self.repoRefreshAction.setEnabled(False)
        else:
            self.repoAddAction.setEnabled(True)
            self.repoRefreshAction.setEnabled(True)
            if self._isARepoSelected():
                self.repoRemoveAction.setEnabled(True)
            else:
                self.repoRemoveAction.setEnabled(False)

    def addAccount(self):
        wizard = AddAccountWizard(self)
        if wizard.exec_():
            username = str(wizard.field('username').toString())
            token = str(wizard.field('token').toString())
            store_token(CONFIG_PATH, 'github', username, token)
            self.authenticate()
            self.reposRefresh()
            self.updateImage()
            self.actionsUpdate()

    def repoAdd(self):
        wizard = AddRepoWizard(self.github, self)
        if wizard.exec_():
            self.github.get_user().create_repo(
                str(wizard.field('name').toString()),
                description=str(wizard.field('description').toString()),
                private=bool(wizard.field('private').toBool()),
                auto_init=bool(wizard.field('auto_init').toBool()),
                gitignore_template=str(wizard.field('gitignore').toString()),
                homepage=str(wizard.field('homepage').toString()),
                has_wiki=bool(wizard.field('has_wiki').toBool()),
                has_downloads=bool(wizard.field('has_downloads').toBool()),
                has_issues=bool(wizard.field('has_issues').toBool()))
            self.reposRefresh()

    def repoRemove(self):

        row = self._selectedRepoRow()
        name = self.reposTableWidget.item(row, 0).text()
        dialog = RepoRemoveDialog(self.github, name)
        if dialog.exec_():
            self.github.get_user().get_repo(str(name)).delete()
            self.reposRefresh()

    def _isARepoSelected(self):
        """ Return True if a repo is selected else False """
        if len(self.reposTableWidget.selectedItems()) > 0:
            return True
        else:
            return False

    def _selectedRepoRow(self):
        """ Return the currently select repo """
        # TODO - figure out what happens if no repo is selected
        selectedModelIndexes = \
            self.reposTableWidget.selectionModel().selectedRows()
        for index in selectedModelIndexes:
            return index.row()
示例#49
0
class SimulatorWindow(QMainWindow):
    def __init__(self, argv):
        QMainWindow.__init__(self)
        self.setWindowTitle("SimSo: Real-Time Scheduling Simulator")

        # Possible actions:
        style = qApp.style()

        # New
        self._newAction = QAction(
            style.standardIcon(QStyle.SP_FileDialogNewFolder), '&New', None)
        self._newAction.setShortcut(Qt.CTRL + Qt.Key_N)
        self._newAction.triggered.connect(self.fileNew)

        # Open
        self._openAction = QAction(
            style.standardIcon(QStyle.SP_DialogOpenButton), '&Open', None)
        self._openAction.setShortcut(Qt.CTRL + Qt.Key_O)
        self._openAction.triggered.connect(self.fileOpen)

        # Save
        self._saveAction = QAction(
            style.standardIcon(QStyle.SP_DialogSaveButton), '&Save', None)
        self._saveAction.setShortcut(Qt.CTRL + Qt.Key_S)
        self._saveAction.triggered.connect(self.fileSave)

        # Save As
        self._saveAsAction = QAction(
            style.standardIcon(QStyle.SP_DialogSaveButton), 'Save &As', None)
        self._saveAsAction.setShortcut(Qt.CTRL + Qt.SHIFT + Qt.Key_S)
        self._saveAsAction.triggered.connect(self.fileSaveAs)

        # Run
        self._runAction = QAction(style.standardIcon(QStyle.SP_MediaPlay),
                                  '&Run', None)
        self._runAction.setShortcut(Qt.CTRL + Qt.Key_R)
        self._runAction.triggered.connect(self.fileRun)

        # Show Model data
        self._modelAction = QAction('&Model data', None)
        self._modelAction.setShortcut(Qt.CTRL + Qt.Key_M)
        #self._ganttAction.setCheckable(True)
        self._modelAction.triggered.connect(self.showModelWindow)

        # Show Gantt
        self._ganttAction = QAction('&Gantt', None)
        self._ganttAction.setShortcut(Qt.CTRL + Qt.Key_G)
        self._ganttAction.setEnabled(False)
        #self._ganttAction.setCheckable(True)
        self._ganttAction.triggered.connect(self.showGantt)

        # Show Results
        self._metricsAction = QAction('&Results', None)
        self._metricsAction.setShortcut(Qt.CTRL + Qt.Key_I)
        self._metricsAction.setEnabled(False)
        #self._metricsAction.setCheckable(True)
        self._metricsAction.triggered.connect(self.showResults)

        # Show Doc
        self._docAction = QAction('&Documentation', None)
        self._docAction.triggered.connect(self.showDocumentation)

        self._aboutAction = QAction('&About SimSo', None)
        self._aboutAction.triggered.connect(self.showAbout)

        # Recent files
        self._recentFileActions = []
        for i in range(5):
            act = QAction(self)
            act.setVisible(False)
            act.triggered.connect(self.openRecentFile)
            self._recentFileActions.append(act)

        # File Menu:
        file_menu = QMenu('&File', self)
        file_menu.addAction(self._newAction)
        file_menu.addAction(self._openAction)
        file_menu.addAction(self._saveAction)
        file_menu.addAction(self._saveAsAction)
        file_menu.addAction(self._runAction)
        file_menu.addSeparator()
        for act in self._recentFileActions:
            file_menu.addAction(act)
        file_menu.addSeparator()
        file_menu.addAction('&Quit', self.fileQuit, Qt.CTRL + Qt.Key_Q)
        self.updateRecentFileActions()

        # View Menu:
        view_menu = QMenu('&View', self)
        view_menu.addAction(self._modelAction)
        view_menu.addAction(self._ganttAction)
        view_menu.addAction(self._metricsAction)

        # Help Menu:
        help_menu = QMenu('&Help', self)
        help_menu.addAction(self._docAction)
        help_menu.addAction(self._aboutAction)

        # Add menus to menuBar:
        self.menuBar().addMenu(file_menu)
        self.menuBar().addMenu(view_menu)
        self.menuBar().addMenu(help_menu)

        # ToolBar:
        self.toolBar = QToolBar("Main ToolBar")
        self.addToolBar(self.toolBar)
        self.toolBar.addAction(self._newAction)
        self.toolBar.addAction(self._openAction)
        self.toolBar.addAction(self._saveAction)
        self.toolBar.addAction(self._runAction)
        self.toolBar.addAction(self._ganttAction)
        self.toolBar.addAction(self._metricsAction)

        # Tab:
        self.main_tab = QTabWidget()
        self.main_tab.setTabsClosable(True)
        self.main_tab.setMovable(True)
        self.main_tab.tabCloseRequested.connect(self.tabCloseRequested)
        self.main_tab.currentChanged.connect(self.tabChanged)
        self.setCentralWidget(self.main_tab)

        # Init statusBar:
        self.statusBar().showMessage("", 2000)

        self._documentation = None

        if argv:
            for arg in argv:
                try:
                    self.open_file(arg)
                except Exception as e:
                    print(e)
        else:
            self.fileNew()

    def openRecentFile(self):
        try:
            self.open_file(self.sender().data().toString())
        except AttributeError:
            self.open_file(self.sender().data())

    def updateRecentFileActions(self):
        settings = QSettings()
        files = settings.value("recentFileList",
                               defaultValue=[],
                               type='QString')
        for i in range(5):
            if i < len(files):
                text = "&{} {}".format(i + 1, QFileInfo(files[i]).fileName())
                self._recentFileActions[i].setText(text)
                self._recentFileActions[i].setData(files[i])
                self._recentFileActions[i].setVisible(True)
            else:
                self._recentFileActions[i].setVisible(False)

    def setCurrentFile(self, filename):
        filename = QFileInfo(filename).absoluteFilePath()
        settings = QSettings()
        files = settings.value("recentFileList",
                               defaultValue=[],
                               type='QString')

        if filename in files:
            files.remove(filename)
        files.insert(0, filename)
        while len(files) > 5:
            del files[-1]

        settings.setValue("recentFileList", files)
        self.updateRecentFileActions()

    def showAbout(self):
        QMessageBox.about(
            self, "About SimSo",
            "<b>SimSo - Simulation of Multiprocessor Scheduling with Overheads</b><br/><br/>"
            "Version: SimSo {}, Graphical User Interface {}<br/><br/>"
            "SimSo is a free software developed by Maxime Cheramy (LAAS-CNRS).<br/>"
            "This software is distributed under the <a href='http://www.cecill.info'>CECILL license</a>, "
            "compatible with the GNU GPL.<br/><br/>"
            "Contact: <a href='mailto:[email protected]'>[email protected]</a>"
            .format(simso.__version__, simsogui.__version__)
            #            "<br/><hr/><br/>"
            #            "The Code Editor, copyright the <a href='http://www.iep-project.org/'>IEP development team</a>, "
            #            "was reproduced and integrated into SimSo in respect of the (new) BSD license."
        )

    def showDocumentation(self):
        if self._documentation is None:
            doc = QWebView(self)
            doc.load(QUrl("doc/html/index.html"))
            self._documentation = QDockWidget("Documentation", self)
            self._documentation.setWidget(doc)
            self._documentation.closeEvent = lambda _: self.hide_documentation(
            )

        self.addDockWidget(Qt.LeftDockWidgetArea, self._documentation)

    def showGantt(self):
        self.main_tab.currentWidget().showGantt()

    def showModelWindow(self):
        self.main_tab.currentWidget().showModelWindow()

    def showResults(self):
        self.main_tab.currentWidget().showResults()

    def hide_documentation(self):
        self._documentation = None

    def fileNew(self):
        self.main_tab.addTab(SimulationTab(self), 'Unsaved')

    def fileOpen(self):
        simulation_file = QFileDialog.getOpenFileName(
            filter="*.xml", caption="Open XML simulation file.")
        if simulation_file:
            self.open_file(simulation_file)

    def open_file(self, simulation_file):
        try:
            simulation_file = unicode(simulation_file)
        except NameError:
            pass

        try:
            self.setCurrentFile(simulation_file)
            sim = SimulationTab(self, simulation_file)
            if (self.main_tab.currentWidget()
                    and not self.main_tab.currentWidget().simulation_file
                    and self.main_tab.currentWidget().configuration.is_saved()
                    and self.main_tab.count() == 1):
                self.main_tab.removeTab(0)
            self.main_tab.addTab(sim, os.path.split(simulation_file)[1])
            self.main_tab.setCurrentWidget(sim)
            self.updateMenus()
        except Exception:
            QMessageBox.critical(
                self, "Could not open file",
                "The file {} could not be opened.".format(simulation_file))
            print(traceback.format_exc())

    def fileSave(self):
        try:
            self.main_tab.currentWidget().save()
        except:
            self.fileSaveAs()

    def fileSaveAs(self):
        simulation_file = QFileDialog.getSaveFileName(
            filter="*.xml", caption="Save XML simulation file.")
        try:
            simulation_file = unicode(simulation_file)
        except NameError:
            pass
        if simulation_file:
            if simulation_file[-4:] != '.xml':
                simulation_file += '.xml'
            self.main_tab.currentWidget().save_as(simulation_file)
            self.setCurrentFile(simulation_file)

    def fileRun(self):
        self._runAction.setEnabled(False)
        self.main_tab.currentWidget().run()

    def fileQuit(self):
        self.close()

    def setTabText(self, tab, text):
        self.main_tab.setTabText(self.main_tab.indexOf(tab), text)

    def tabChanged(self, index):
        self.updateMenus()

    def tabCloseRequested(self, index):
        if self.main_tab.widget(index).close():
            self.main_tab.removeTab(index)
            self.updateMenus()

    def closeEvent(self, event):
        while self.main_tab.count() > 0:
            if self.main_tab.widget(0).close():
                self.main_tab.removeTab(0)
            else:
                event.ignore()
                return

    def updateMenus(self):
        if self.main_tab.count() > 0:
            widget = self.main_tab.currentWidget()
            self._runAction.setEnabled(True)
            self._modelAction.setEnabled(True)
            self._ganttAction.setEnabled(widget._model is not None)
            self._metricsAction.setEnabled(widget._model is not None)
        else:
            self._runAction.setEnabled(False)
            self._modelAction.setEnabled(False)
            self._ganttAction.setEnabled(False)
            self._metricsAction.setEnabled(False)
示例#50
0
    def __init__(self, parent=None):
        super(MainWidget,
              self).__init__(parent,
                             windowTitle='GithubRemote',
                             windowIcon=QIcon(image_path('git.png')),
                             geometry=QRect(300, 300, 600, 372))

        self.repo_pixmap = QPixmap(image_path('book_16.png'))
        self.big_repo_pixmap = QPixmap(image_path('book_32.png'))
        self.repo_fork_pixmap = QPixmap(image_path('book_fork_16.png'))
        self.star_pixmap = QPixmap(image_path('star_16.png'))
        self.big_star_pixmap = QPixmap(image_path('star_32.png'))
        self.fork_pixmap = QPixmap(image_path('fork_16.png'))
        self.eye_pixmap = QPixmap(image_path('eye_16.png'))

        self.github = None

        # Actions

        self.repoAddAction = QAction(QIcon(image_path('plus_48.png')),
                                     '&Add Repo',
                                     self,
                                     statusTip='Add a new repo')
        self.repoAddAction.triggered.connect(self.repoAdd)

        self.repoRemoveAction = QAction(QIcon(image_path('minus.png')),
                                        '&Remove Repo',
                                        self,
                                        statusTip='Remove repo')
        self.repoRemoveAction.triggered.connect(self.repoRemove)

        self.repoRefreshAction = QAction(QIcon(image_path('refresh.png')),
                                         'Refresh',
                                         self,
                                         statusTip='Refresh list of repos')
        self.repoRefreshAction.triggered.connect(self.reposRefresh)
        self.repoRefreshAction.triggered.connect(self.starsRefresh)

        self.addAccountAction = QAction('Add Account',
                                        self,
                                        statusTip='Add Account')
        self.addAccountAction.triggered.connect(self.addAccount)

        # userPushButton - Displays the current active username and
        # image on the top right of the toolbar.

        self.userButtonMenu = UserButtonMenu(32, 32)

        # ToolBar

        self.toolBar = self.addToolBar('Main')
        self.toolBar.setMovable(False)
        self.toolBar.setFloatable(False)
        spacer = QWidget()
        spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.toolBar.addAction(self.repoAddAction)
        self.toolBar.addAction(self.repoRemoveAction)
        self.toolBar.addAction(self.repoRefreshAction)
        self.toolBar.addWidget(spacer)
        self.toolBar.addWidget(self.userButtonMenu)

        # Menu

        menuBar = self.menuBar()
        fileMenu = menuBar.addMenu('&File')
        actionMenu = menuBar.addMenu('&Action')
        fileMenu.addAction(self.addAccountAction)
        actionMenu.addAction(self.repoAddAction)
        actionMenu.addAction(self.repoRemoveAction)
        actionMenu.addAction(self.repoRefreshAction)

        # StatusBar

        statusBar = self.statusBar()
        self.setStatusBar(statusBar)

        # reposTableWidget - Displays a list of the users repositories

        self.reposTableWidget = QTableWidget(
            0,
            5,
            selectionBehavior=QAbstractItemView.SelectRows,
            selectionMode=QAbstractItemView.SingleSelection,
            editTriggers=QAbstractItemView.NoEditTriggers,
            itemSelectionChanged=self.actionsUpdate)
        self.reposTableWidget.horizontalHeader().setResizeMode(
            QHeaderView.ResizeToContents)
        self.reposTableWidget.horizontalHeader().setResizeMode(
            1, QHeaderView.Stretch)
        self.reposTableWidget.horizontalHeader().setVisible(False)
        self.reposTableWidget.verticalHeader().setVisible(False)
        self.reposTableWidget.setShowGrid(False)
        self.reposTableWidget.verticalHeader().setMinimumSectionSize(25)

        # repoTab - Layout
        reposTab = QWidget()
        reposTabLayout = QVBoxLayout(reposTab)
        reposTabLayout.addWidget(self.reposTableWidget)
        reposTab.setLayout(reposTabLayout)

        # starsTableWidget - Displays a list of the users repositories

        self.starsTableWidget = QTableWidget(
            0,
            5,
            selectionBehavior=QAbstractItemView.SelectRows,
            selectionMode=QAbstractItemView.SingleSelection,
            editTriggers=QAbstractItemView.NoEditTriggers,
            itemSelectionChanged=self.actionsUpdate)
        self.starsTableWidget.horizontalHeader().setResizeMode(
            QHeaderView.ResizeToContents)
        self.starsTableWidget.horizontalHeader().setResizeMode(
            1, QHeaderView.Stretch)
        self.starsTableWidget.horizontalHeader().setVisible(False)
        self.starsTableWidget.verticalHeader().setVisible(False)
        self.starsTableWidget.setShowGrid(False)
        self.starsTableWidget.verticalHeader().setMinimumSectionSize(25)

        # repoTab - Layout
        starsTab = QWidget()
        starsTabLayout = QVBoxLayout(starsTab)
        starsTabLayout.addWidget(self.starsTableWidget)
        starsTab.setLayout(starsTabLayout)

        # Tab Widget
        self.tabs = QTabWidget()
        self.tabs.setTabBar(FlippedTabBar(self))
        self.tabs.addTab(reposTab, QIcon(self.big_repo_pixmap), "repos")
        self.tabs.addTab(starsTab, QIcon(self.big_star_pixmap), "stars")
        self.tabs.setTabPosition(QTabWidget.West)

        # Layout

        self.setCentralWidget(self.tabs)
        self.actionsUpdate()
        self.show()

        # Update

        self.loadUserMenu()
        if self.activeUserAction:
            self.activeUserAction.setVisible(False)
        self.authenticate()
        self.actionsUpdate()
        self.reposRefresh()
        self.starsRefresh()
        self.updateImage()
示例#51
0
class WTestManager(QWidget, Logger.ClassLogger):
    """
    Widget to display all tests in the scheduler
    """
    def __init__(self, parent):
        """
        Constructs WTestManager widget

        @param parent: 
        @type parent:
        """
        QWidget.__init__(self, parent)
        self.parent = parent
        self.name = self.tr("Task Manager")
        self.ascendingOrder = False
        self.ascendingOrderHistory = False
        self.ascendingOrderWaiting = False
        
        self.itemCurrent = None
        self.projects = []
        self.createWidgets()
        self.createActions()
        self.createConnections()
        self.createActions()
        self.createToolbar()
        self.deactivate()

    def createWidgets (self):
        """
        QtWidgets creation
        
        QTreeWidget (Id, Name, Init at, Sched at, Start at, Stop at, User, Duration)
         _______________
        |    QToolBar   |
        |---------------|
         _______________
        |               |
        |---------------|
        |               |
        |               |
        |_______________|
        """

        #self.mainTab = QTabWidget()


        layout = QVBoxLayout()

        topLayout = QHBoxLayout()

        # waiting tree widget
        self.tabWaiting = QTabWidget()

        #self.waitingBox = QGroupBox("Waiting")
        self.waitingBox = QFrame(self)
        self.testWaiting = QTreeWidget(self)
        self.testWaiting.setSelectionMode(QAbstractItemView.ExtendedSelection)
        self.waitingToolbar = QToolBar(self)
        self.labelsWaiting = [ self.tr("No.") , self.tr("Group"), self.tr("Schedulation Type"),
                              self.tr("Project"), self.tr("Name") , self.tr("Next run"), 
                              self.tr("Repeat"), self.tr("Probes"), self.tr("Notifications") , 
                              self.tr("Tests result"), self.tr("Author")  ]
        self.testWaiting.setHeaderLabels(self.labelsWaiting)
        self.testWaiting.setIndentation(10)
        self.testWaiting.setContextMenuPolicy(Qt.CustomContextMenu)
        layoutWaiting = QVBoxLayout()
        layoutWaiting.addWidget(self.waitingToolbar)
        layoutWaiting.addWidget(self.testWaiting)
        self.waitingBox.setLayout(layoutWaiting)

        self.tabWaiting.addTab( self.waitingBox, "Scheduled" )

        self.enqueuedBox = QFrame(self)
        layoutEnqueued = QVBoxLayout()

        self.testEnqueued = QTreeWidget(self)
        self.labelsEnqueued = [ self.tr("Group of tests")  ] 
        self.testEnqueued.setHeaderLabels(self.labelsEnqueued)
        self.testEnqueued.setIndentation(10)

        layoutEnqueued.addWidget(self.testEnqueued)
        self.enqueuedBox.setLayout(layoutEnqueued)
        self.tabWaiting.addTab( self.enqueuedBox, "Waiting" )


        # current tree widget
        self.currentBox = QGroupBox("Running")
        self.testManager = QTreeWidget(self)
        self.testManager.setSelectionMode(QAbstractItemView.ExtendedSelection)
        self.dockToolbar = QToolBar(self)
        self.labels  = [ self.tr("No."), self.tr("Project"), self.tr("Name"), self.tr("Started at"),
                         self.tr("Author"), self.tr("Recursive") ]
        self.testManager.setHeaderLabels(self.labels)
        self.testManager.setIndentation(10)
        self.testManager.setContextMenuPolicy(Qt.CustomContextMenu)
        layoutCurrent = QVBoxLayout()
        layoutCurrent.addWidget(self.dockToolbar)
        layoutCurrent.addWidget(self.testManager)
        self.currentBox.setLayout(layoutCurrent)
        
        v_splitter = QSplitter(self)      
        v_splitter.addWidget( self.tabWaiting )
        v_splitter.addWidget( self.currentBox ) 
        topLayout.addWidget(v_splitter)

        # history tree widget
        self.historyBox = QGroupBox("History")
        self.testHistory = QTreeWidget(self)
        self.historyToolbar = QToolBar(self)
        self.labels2 = [ self.tr("Id"),  self.tr("Schedulation Type"),  self.tr("Project") , self.tr("Name"), 
                         self.tr("Sched at"), self.tr("Run start"), self.tr("Run end"), self.tr("Author"), 
                         self.tr("Duration (in sec.)"), self.tr("Run Result") ]
        self.testHistory.setHeaderLabels(self.labels2)
        
        self.statsBox = QGroupBox("Summary")
        self.nbRunningLabel = QLabel("0")
        self.nbWaitingLabel = QLabel("0")
        self.nbHistoryLabel = QLabel("0")
        self.nbCompleteHistoryLabel = QLabel("0")
        self.nbErrorHistoryLabel = QLabel("0")
        self.nbKilledHistoryLabel = QLabel("0")
        self.nbCancelledHistoryLabel = QLabel("0")
        layout2 = QFormLayout()
        layout2.addRow(QLabel("Running"), self.nbRunningLabel )
        layout2.addRow(QLabel("Waiting"), self.nbWaitingLabel )
        layout2.addRow( QLabel(""), QLabel("") )
        layout2.addRow(QLabel("History"), self.nbHistoryLabel )
        layout2.addRow(QLabel(" - COMPLETE"), self.nbCompleteHistoryLabel )
        layout2.addRow(QLabel(" - ERROR"), self.nbErrorHistoryLabel )
        layout2.addRow(QLabel(" - KILLED"), self.nbKilledHistoryLabel )
        layout2.addRow(QLabel(" - CANCELLED"), self.nbCancelledHistoryLabel )
        self.statsBox.setLayout(layout2)

        layoutHistory = QVBoxLayout()
        layoutHistory.addWidget(self.historyToolbar)
        layoutHistory.addWidget(self.testHistory)
        self.historyBox.setLayout(layoutHistory)
        
        subLayout = QHBoxLayout()
        subLayout.addWidget(self.historyBox)
        subLayout.addWidget(self.statsBox)

        frame_left = QFrame(self)
        frame_left.setFrameShape(QFrame.NoFrame)
        frame_left.setLayout(topLayout)

        frame_right = QFrame(self)
        frame_right.setFrameShape(QFrame.NoFrame)
        frame_right.setLayout(subLayout)

        topLayout.setContentsMargins(0,0,0,0)
        subLayout.setContentsMargins(0,0,0,0)

        splitter1 = QSplitter(Qt.Vertical)
        splitter1.addWidget(frame_left)
        splitter1.addWidget(frame_right)

        layout.addWidget(splitter1)
        self.setLayout(layout)

    def createConnections(self):
        """
        Create Qt Connections
        """
        self.testWaiting.customContextMenuRequested.connect(self.onPopupMenuWaiting)
        self.testWaiting.currentItemChanged.connect(self.onCurrentWaitingItemChanged)

        self.testManager.customContextMenuRequested.connect(self.onPopupMenu)
        self.testManager.currentItemChanged.connect(self.onCurrentItemChanged)

        self.testWaiting.itemDoubleClicked.connect(self.onItemDoubleClicked)

    def createActions (self):
        """
        Actions defined:
         * sort running task
         * sort waiting task
         * sort history task
         * kill one task
         * kill all tasks
         * cancel one task
         * cancel all task
         * clear the history
         * edit a waiting task
         * refresh waiting tasks
         * refresh running tasks
         * partial refresh of the history
         * complete refresh of the history
         * disable a waiting task
         * enable a waiting task
        """
        self.sortAction = QtHelper.createAction(self, "Ascending Order", self.toggleSort, toggled = True, 
                                icon = QIcon(":/ascending.png") )
        self.sortHistoryAction = QtHelper.createAction(self, "Ascending Order", self.toggleSortHistory, toggled = True, 
                                icon = QIcon(":/ascending.png") )
        self.sortWaitingAction = QtHelper.createAction(self, "Ascending Order", self.toggleSortWaiting, toggled = True, 
                                icon = QIcon(":/ascending.png") )
        self.killAction = QtHelper.createAction(self, "&Kill", self.killTask, tip = 'Kill selected test', 
                                icon = QIcon(":/process-kill.png") )
        self.killAllAction = QtHelper.createAction(self, "&Kill All", self.killAllTasks, tip = 'Kill all running tests', 
                                icon = QIcon(":/process-killall.png") )
        self.cancelAction = QtHelper.createAction(self, "&Cancel", self.cancelTask, tip = 'Cancel selected test', 
                                icon = QIcon(":/process-cancel.png") )
        self.cancelAllAction = QtHelper.createAction(self, "&Cancel All", self.cancelAllTasks, tip = 'Cancel all waiting tests', 
                                icon = QIcon(":/processes-cancelall.png") )
        
        self.clearHistoryAction = QtHelper.createAction(self, "&Clear history", self.clearHistory, tip = 'Clear history', 
                                icon = QIcon(":/trash.png"))
        self.editWaitingAction = QtHelper.createAction(self, "&Edit", self.editWaiting, tip = 'Edit the selected task', 
                                icon = QIcon(":/reschedule.png"))

        self.refreshWaitingAction = QtHelper.createAction(self, "Waiting tasks", self.refreshWaitingList, 
                                icon = QIcon(":/act-refresh.png"), tip="Refresh waiting tasks" )
        self.refreshRunningAction = QtHelper.createAction(self, "Running tasks", self.refreshRunningList, 
                                icon = QIcon(":/act-refresh.png"), tip="Refresh running tasks" )
        self.partialRefreshHistoryAction = QtHelper.createAction(self, "Partial history", self.partialRefreshHistoryList, 
                                icon = QIcon(":/act-half-refresh.png"), tip="Refresh partial history" )
        self.refreshHistoryAction = QtHelper.createAction(self, "Full history", self.refreshHistoryList, 
                                icon = QIcon(":/act-refresh.png"), tip="Refresh full history" )

        self.disableAction = QtHelper.createAction(self, "&Disable", self.disableTask, tip = 'Disable task', 
                                icon = QIcon(":/process-pause-icon.png") )
        self.enableAction = QtHelper.createAction(self, "&Enable", self.enableTask, tip = 'Enable task', 
                                icon = None)

    def createToolbar(self):
        """
        Toolbar creation
            
        ||----------||
        || Kill all ||
        ||----------||
        """
        self.dockToolbar.setObjectName("Test Manager toolbar")
        self.dockToolbar.addAction(self.sortAction)
        self.dockToolbar.addAction(self.refreshRunningAction)
        self.dockToolbar.addSeparator()
        self.dockToolbar.addAction(self.killAction)
        self.dockToolbar.addAction(self.killAllAction)
        self.dockToolbar.addSeparator()
        self.dockToolbar.setIconSize(QSize(16, 16))
        #
        self.historyToolbar.setObjectName("Test Manager History toolbar")
        self.historyToolbar.addAction(self.sortHistoryAction)
        self.historyToolbar.addAction(self.partialRefreshHistoryAction)
        self.historyToolbar.addAction(self.refreshHistoryAction)
        self.historyToolbar.addSeparator()
        self.historyToolbar.addAction(self.clearHistoryAction)
        self.historyToolbar.setIconSize(QSize(16, 16))
        #
        self.waitingToolbar.setObjectName("Test Manager Waiting toolbar")
        self.waitingToolbar.addAction(self.sortWaitingAction)
        self.waitingToolbar.addAction(self.refreshWaitingAction)
        self.waitingToolbar.addSeparator()
        self.waitingToolbar.addAction(self.editWaitingAction)
        self.waitingToolbar.addAction(self.disableAction)
        self.waitingToolbar.addAction(self.cancelAction)
        self.waitingToolbar.addAction(self.cancelAllAction)
        self.waitingToolbar.addSeparator()
        self.waitingToolbar.setIconSize(QSize(16, 16))

    def onItemDoubleClicked(self, item):
        """
        On item double clicked in waiting task
        """
        if item.taskEventType in [ UCI.SCHED_QUEUE_AT, UCI.SCHED_QUEUE ]:
            pass
        else:
            self.editWaiting()
        
    def getProjectName(self, prjId):
        """
        Return the project name
        """
        pname = "UNKNOWN"
        
        if prjId == 0:
            return "UNDEFINED"

        for p in self.projects:
            if int(p['project_id']) == int(prjId):
                pname = p['name']
                break

        return pname

    def refreshWaitingList(self):
        """
        Refresh the waiting task list
        """
        RCI.instance().waitingTasks()
        
    def refreshRunningList(self):
        """
        Refresh the running task list
        """
        RCI.instance().runningTasks()
        
    def partialRefreshHistoryList(self):
        """
        Partial refresh of the history task list
        """
        RCI.instance().historyTasks()
        
    def refreshHistoryList(self):
        """
        Refresh the history task list
        """
        RCI.instance().historyTasksAll()
        
    def onCurrentItemChanged(self, witem1, witem2):
        """
        On current item changed 

        @param witem1: 
        @type witem1:

        @param witem2: 
        @type witem2:
        """
        # kill task available just for admin and tester
        if UCI.RIGHTS_ADMIN in RCI.instance().userRights  or UCI.RIGHTS_TESTER in RCI.instance().userRights :
            if witem1 is not None:
                if witem1.taskState == STATE_RUNNING :
                    self.itemCurrent = witem1
                    self.killAction.setEnabled(True)
                else:
                    self.killAction.setEnabled(False)

    def onCurrentWaitingItemChanged(self, witem1, witem2):
        """
        On current waiting task item changed

        @param witem1: 
        @type witem1:

        @param witem2: 
        @type witem2:
        """
        # kill task available just for admin and tester
        if UCI.RIGHTS_ADMIN in RCI.instance().userRights or UCI.RIGHTS_TESTER in RCI.instance().userRights :
            if witem1 is not None:
                self.itemCurrent = witem1
                self.cancelAction.setEnabled(True)
                self.editWaitingAction.setEnabled(True)
                self.disableAction.setEnabled(True)
            else:
                self.cancelAction.setEnabled(False)
                self.editWaitingAction.setEnabled(False)
                self.disableAction.setEnabled(False)

    def disableTask(self):
        """
        Disable a waiting task
        """
        # if self.itemCurrent is not None:
        for currentItem in self.testWaiting.selectedItems():
            RCI.instance().rescheduleTask(taskId=currentItem.taskId, taskEnabled=False, 
                                            scheduleType=currentItem.taskEventType,
                                            scheduleAt=currentItem.taskEventArgs, 
                                            scheduleRepeat=currentItem.taskEventNb, 
                                            probesEnabled=currentItem.taskWithoutProbes, 
                                            notificationsEnabled=currentItem.taskWithoutNotif, 
                                            debugEnabled=False, logsEnabled=currentItem.taskNoKeepTr, 
                                            fromTime=currentItem.taskEventFrom, toTime=currentItem.taskEventTo )
                                            
    def enableTask(self):
        """
        Enable a waiting task
        """
        # if self.itemCurrent is not None:
        for currentItem in self.testWaiting.selectedItems():
            RCI.instance().rescheduleTask(taskId=currentItem.taskId, taskEnabled=True, 
                                            scheduleType=currentItem.taskEventType,
                                            scheduleAt=currentItem.taskEventArgs, 
                                            scheduleRepeat=currentItem.taskEventNb, 
                                            probesEnabled=currentItem.taskWithoutProbes, 
                                            notificationsEnabled=currentItem.taskWithoutNotif, 
                                            debugEnabled=False, logsEnabled=currentItem.taskNoKeepTr, 
                                            fromTime=currentItem.taskEventFrom, toTime=currentItem.taskEventTo )
    
    def editWaiting(self):
        """
        Edit a waiting task
        """
        if self.itemCurrent is not None:
            if self.itemCurrent.taskEventType in [ UCI.SCHED_QUEUE_AT, UCI.SCHED_QUEUE ]:
                pass
            else:
                dSched = ScheduleDialog.SchedDialog( self )
                dSched.fillFields( schedType=self.itemCurrent.taskEventType, schedArgs=self.itemCurrent.taskEventArgs,
                                    taskName=self.itemCurrent.taskEventName, taskId=self.itemCurrent.taskId, 
                                    schedNb=self.itemCurrent.taskEventNb, withoutProbes=self.itemCurrent.taskWithoutProbes,
                                    enabled=self.itemCurrent.taskEventEnabled,
                                    withoutNotifs=self.itemCurrent.taskWithoutNotif, noKeepTr=self.itemCurrent.taskNoKeepTr,
                                    schedFrom=self.itemCurrent.taskEventFrom, schedTo=self.itemCurrent.taskEventTo )
                if dSched.exec_() == QDialog.Accepted:
                    runAt, runType, runNb, withoutProbes, runEnabled, noTr, withoutNotifs, runFrom, runTo = dSched.getSchedtime()

                    RCI.instance().rescheduleTask(taskId=self.itemCurrent.taskId, taskEnabled=runEnabled, scheduleType=runType,
                                                    scheduleAt=runAt, scheduleRepeat=runNb, 
                                                    probesEnabled=withoutProbes, notificationsEnabled=withoutNotifs, 
                                                    debugEnabled=False, logsEnabled=noTr, 
                                                    fromTime=runFrom, toTime=runTo )
    def clearHistory(self):
        """
        Call the server to clear the history
        """
        reply = QMessageBox.question(self, "Clear tasks history", "Are you sure ?",
                        QMessageBox.Yes | QMessageBox.No )
        if reply == QMessageBox.Yes:
            RCI.instance().clearHistory()
            
    def testKilled(self):
        """
        Test kiled
        """
        self.itemCurrent = None
        self.killAction.setEnabled(False)

    def testCancelled(self):
        """
        Test cancelled
        """
        self.itemCurrent = None
        self.cancelAction.setEnabled(False)

    def active (self):
        """
        Enables QTreeWidget 
        """
        self.waitingBox.setEnabled(True)
        self.currentBox.setEnabled(True)
        self.historyBox.setEnabled(True)
        self.statsBox.setEnabled(True)
        #
        self.testManager.setEnabled(True)
        self.testHistory.setEnabled(True)
        self.testWaiting.setEnabled(True)
        #
        self.sortAction.setEnabled(True)
        self.sortHistoryAction.setEnabled(True)
        self.sortWaitingAction.setEnabled(True)
        
        self.refreshWaitingAction.setEnabled(True)
        self.refreshRunningAction.setEnabled(True)
        self.refreshHistoryAction.setEnabled(True)
        self.partialRefreshHistoryAction.setEnabled(True)

        self.killAction.setEnabled(False)
        self.cancelAction.setEnabled(False)
        self.editWaitingAction.setEnabled(False)
        if UCI.RIGHTS_ADMIN in RCI.instance().userRights:
            self.killAllAction.setEnabled(True)
            self.cancelAllAction.setEnabled(True)
            self.clearHistoryAction.setEnabled(True)

        self.disableAction.setEnabled(False)
        self.enableAction.setEnabled(True)

    def deactivate (self):
        """
        Clears QTreeWidget and disables it
        """
        self.waitingBox.setEnabled(False)
        self.currentBox.setEnabled(False)
        self.historyBox.setEnabled(False)
        self.statsBox.setEnabled(False)
        
        self.testWaiting.clear()
        self.testWaiting.setEnabled(False)
        self.testManager.clear()
        self.testManager.setEnabled(False)
        self.testHistory.clear()
        self.testHistory.setEnabled(False)
        self.testEnqueued.clear()
        self.testHistory.setEnabled(False)

        self.nbRunningLabel.setText("0")
        self.nbWaitingLabel.setText("0")
        self.nbHistoryLabel.setText("0")
        self.nbCompleteHistoryLabel.setText("0")
        self.nbErrorHistoryLabel.setText("0")
        self.nbKilledHistoryLabel.setText("0")
        self.nbCancelledHistoryLabel.setText("0")
        self.itemCurrent = None
        
        self.setDefaultActionsValues()
    
    def setDefaultActionsValues (self):
        """
        Set default values for qt actions
        """
        self.sortAction.setEnabled(False)
        self.sortHistoryAction.setEnabled(False)
        self.sortWaitingAction.setEnabled(False)

        self.killAction.setEnabled(False)
        self.killAllAction.setEnabled(False)

        self.cancelAction.setEnabled(False)
        self.cancelAllAction.setEnabled(False)
        self.editWaitingAction.setEnabled(False)
        self.clearHistoryAction.setEnabled(False)

        self.refreshWaitingAction.setEnabled(False)
        self.refreshRunningAction.setEnabled(False)
        self.refreshHistoryAction.setEnabled(False)
        self.partialRefreshHistoryAction.setEnabled(False)

        self.disableAction.setEnabled(False)
        self.enableAction.setEnabled(False)

    def loadProjects(self, data):
        """
        Load all projects
        """
        self.projects = data

    def loadRunning (self, data):
        """
        Loads running tasks

        @param data: 
        @type data: dict
        """
        self.nbRunningLabel.setText( str( len(data) ) )
        for task in data:
            if self.getProjectName(task['project-id']) == "UNKNOWN":
                continue
            taskItem = TaskRunningItem(  task = task, parent= self.testManager )
        
        # resize cols
        for i in xrange(len(self.labels2) - 1):
            self.testManager.resizeColumnToContents(i)
        
        # change sort order
        if self.ascendingOrder:
            self.testWaiting.sortItems(2, Qt.AscendingOrder)     # sort by sched time
        self.testManager.sortItems(2, Qt.DescendingOrder)

    def updateRunning(self, data):
        """
        Update running tasks

        @param data: 
        @type data: 
        """
        self.testManager.clear()
        self.loadRunning( data=data )

    def loadWaiting (self, data):
        """
        Loads waiting tasks

        @param data: 
        @type data: dict
        """
        self.nbWaitingLabel.setText( str(len(data)) )
        for task in data:
            eventid, eventtype, eventargs, eventtime, eventname, author, realruntime, duration, result, eventnb, \
            eventnbcur, eventenabled, withoutprobes, withoutnotif, nokeeptr, userid, projectid, eventfrom, eventto, groupid  = task
            if self.getProjectName(projectid) == "UNKNOWN":
                continue
            taskItem = TaskWaitingItem(  task = task, parent= self.testWaiting )
        
        # resize cols
        for i in xrange(len(self.labels2) - 1):
            self.testWaiting.resizeColumnToContents(i)
        
        # change sort order
        if self.ascendingOrderHistory:
            self.testWaiting.sortItems(3, Qt.AscendingOrder)     
        self.testWaiting.sortItems(3, Qt.DescendingOrder)

    def updateWaiting(self, data):
        """
        Update waiting tasks

        @param data: 
        @type data: 
        """
        self.testWaiting.clear()
        self.loadWaiting( data=data )

    def loadEnqueued (self, data):
        """
        Loads enqueued tasks

        @param data: 
        @type data: dict
        """
        for (groupId, groupData) in data.items():
            groupName, groupsTests = groupData

            pluriel = ''
            if len(groupsTests) > 1:
                pluriel = ''
            groupTask = TaskEnqueuedItem( parent=self.testEnqueued, text="%s - %s - (%s test%s)" % (groupId, groupName, len(groupsTests), pluriel) )
            groupTask.setExpanded(True)
            for gTest in groupsTests:
                tDict = eval(gTest)
                tst = "%s:%s.%s" % ( self.getProjectName(tDict['prj-id']), tDict['test-path'], tDict['test-extension'])
                
                # set the icon according to the type of test
                if tDict['test-extension'] == 'tux':
                    testIcon = QIcon(":/tux.png")
                if tDict['test-extension'] == 'tax':
                    testIcon = QIcon(":/tax.png")
                if tDict['test-extension'] == 'tsx':
                    testIcon = QIcon(":/tsx.png")
                if tDict['test-extension'] == 'tpx':
                    testIcon = QIcon(":/tpx.png")
                if tDict['test-extension'] == 'tgx':
                    testIcon = QIcon(":/tgx.png")
                subTask = TaskEnqueuedItem(parent=groupTask, text=tst, icon=testIcon)

    def updateEnqueued(self, data):
        """
        Update enqueued tasks

        @param data: 
        @type data: 
        """
        self.testEnqueued.clear()
        self.loadEnqueued( data=data )

    def loadHistory (self, data):
        """
        Loads history tasks

        @param data: 
        @type data: dict
        """
        # Init counters
        nbComplete = int(self.nbCompleteHistoryLabel.text())
        nbError = int(self.nbErrorHistoryLabel.text())
        nbKilled = int(self.nbKilledHistoryLabel.text())
        nbCancelled = int(self.nbCancelledHistoryLabel.text())

        for task in data:
            dbid, eventtype, eventargs, eventtime, eventname, author, realruntime, duration, result, projectid  = task
            if self.getProjectName(projectid) == "UNKNOWN":
                continue
            taskItem = TaskHistoryItem(  task = task, parent= self.testHistory )
            if taskItem.taskEventResult == STATE_COMPLETE:
                nbComplete += 1
            if taskItem.taskEventResult == STATE_ERROR:
                nbError += 1
            if taskItem.taskEventResult == STATE_KILLED:
                nbKilled += 1
            if taskItem.taskEventResult == STATE_CANCELLED:
                nbCancelled += 1

        # resize cols
        for i in xrange(len(self.labels2) - 1):
            self.testHistory.resizeColumnToContents(i)
        
        # change sort order by sched at
        if self.ascendingOrderHistory:
            self.testHistory.sortItems(0, Qt.AscendingOrder)     
        self.testHistory.sortItems(0, Qt.DescendingOrder)
        
        # Update summary
        nbHistory = int(self.nbHistoryLabel.text())
        self.nbHistoryLabel.setText( str( len(data) + nbHistory ) )
        self.nbCompleteHistoryLabel.setText( str(nbComplete) )
        self.nbErrorHistoryLabel.setText( str(nbError) )
        self.nbKilledHistoryLabel.setText( str(nbKilled) )
        self.nbCancelledHistoryLabel.setText( str(nbCancelled) )

    def updateHistory(self, data):
        """
        Update history tasks

        @param data: 
        @type data: 
        """
        # reset counters
        self.nbHistoryLabel.setText("0")
        self.nbCompleteHistoryLabel.setText("0")
        self.nbErrorHistoryLabel.setText("0")
        self.nbKilledHistoryLabel.setText("0")
        self.nbCancelledHistoryLabel.setText("0")
        #
        self.testHistory.clear()
        self.loadHistory( data=data )
    
    def refreshRunningTask(self, data, action):
        """
        Refresh running task

        @param data: 
        @type data: 

        @param action: 
        @type action: 
        """
        if action == "add":
            self.loadRunning(data=data)
        elif action == "update":
            self.updateRunning(data=data)
        else:
            pass # error

    def refreshWaitingTask(self, data, action):
        """
        Refresh waiting task

        @param data: 
        @type data: 

        @param action: 
        @type action: 
        """
        if action == "update":
            self.updateWaiting(data=data)
        else:
            pass # error

    def refreshEnqueuedTask(self, data, action):
        """
        Refresh enqueued task

        @param data: 
        @type data: 

        @param action: 
        @type action: 
        """
        if action == "update":
            self.updateEnqueued(data=data)
        else:
            pass # error

    def refreshHistoryTask(self, data, action):
        """
        Refresh history task

        @param data: 
        @type data: 

        @param action: 
        @type action: 
        """
        if action == "add":
            self.loadHistory(data=data)
        elif action == "update":
            self.updateHistory(data=data)
        else:
            pass # error

    def onPopupMenu(self, pos):
        """
        Display menu on right click

        @param pos: 
        @type pos:
        """
        self.menu = QMenu()
        item = self.testManager.itemAt(pos)
        if item:
            self.itemCurrent = item
            # kill task available just for admin and tester
            if UCI.RIGHTS_ADMIN in RCI.instance().userRights or UCI.RIGHTS_TESTER in RCI.instance().userRights :
                if item.taskState == STATE_RUNNING :
                    self.menu.addAction( self.killAction )
                self.menu.popup(self.testManager.mapToGlobal(pos))

    def onPopupMenuWaiting(self, pos):
        """
        Display menu on right click

        @param pos: 
        @type pos:
        """
        self.menu = QMenu()
        item = self.testWaiting.itemAt(pos)
        if item:
            self.itemCurrent = item
            # kill task available just for admin and tester
            if UCI.RIGHTS_ADMIN in RCI.instance().userRights or UCI.RIGHTS_TESTER in RCI.instance().userRights :
                self.menu.addAction( self.editWaitingAction )
                self.menu.addAction( self.cancelAction )
                self.menu.addSeparator()
                self.menu.addAction( self.disableAction )
                self.menu.addAction( self.enableAction )
                self.menu.popup(self.testWaiting.mapToGlobal(pos))

    def cancelTask(self):
        """
        Cancel the selected task
        """
        items = self.testWaiting.selectedItems()
        taskIds = []
        for itm in items:
            taskIds.append( itm.taskId )
        
        reply = QMessageBox.question(self, "Cancel test(s)", "Are you sure ?",
                        QMessageBox.Yes | QMessageBox.No )
        if reply == QMessageBox.Yes:
            RCI.instance().cancelTasks(taskIds=taskIds)
            
    def cancelAllTasks(self):
        """
        Cancel all tasks
        """
        reply = QMessageBox.question(self, "Cancel all tests", "Are you sure ?",
                        QMessageBox.Yes | QMessageBox.No )
        if reply == QMessageBox.Yes:
            RCI.instance().cancelTasksAll()
            
    def killTask(self):
        """
        Kill the selected task
        """
        items = self.testManager.selectedItems()
        taskIds = []
        for itm in items:
            taskIds.append( itm.taskId )
            
        reply = QMessageBox.question(self, "Kill test", "Are you sure ?",
                        QMessageBox.Yes | QMessageBox.No )
        if reply == QMessageBox.Yes:
            RCI.instance().killTasks(taskIds=taskIds)
            
    def killAllTasks(self):
        """
        Kill all tasks
        """
        reply = QMessageBox.question(self, "Kill all tests", "Are you sure ?",
                        QMessageBox.Yes | QMessageBox.No )
        if reply == QMessageBox.Yes:
            RCI.instance().killTasksAll()
    
    def toggleSort(self):
        """
        Toggle sort of running task
        """
        if not self.ascendingOrder:
            self.testManager.sortItems(2, Qt.AscendingOrder)
            self.ascendingOrder = True
        else:
            self.testManager.sortItems(2, Qt.DescendingOrder)
            self.ascendingOrder = False

    def toggleSortHistory(self):
        """
        Toggle sort of the history
        """
        if not self.ascendingOrderHistory:
            self.testHistory.sortItems(0, Qt.AscendingOrder)
            self.ascendingOrderHistory = True
        else:
            self.testHistory.sortItems(0, Qt.DescendingOrder)
            self.ascendingOrderHistory = False

    def toggleSortWaiting(self):
        """
        Toggle sort of the waiting 
        """
        if not self.ascendingOrderWaiting:
            self.testWaiting.sortItems(3, Qt.AscendingOrder)
            self.ascendingOrderWaiting = True
        else:
            self.testWaiting.sortItems(3, Qt.DescendingOrder)
            self.ascendingOrderWaiting = False
示例#52
0
 def __init__(self, parent):
     QTabWidget.__init__(self)
     self.init(parent)
     self.initShape()
示例#53
0
    def __init__(self, parent=None):
        super(Dialog, self).__init__(parent)

        self._info = None
        self._text = ''
        self._convertedtext = ''
        self._encoding = None
        self.mainwindow = parent

        self.fromVersionLabel = QLabel()
        self.fromVersion = QLineEdit()
        self.reason = QLabel()
        self.toVersionLabel = QLabel()
        self.toVersion = QLineEdit()
        self.lilyChooser = lilychooser.LilyChooser()
        self.messages = QTextBrowser()
        self.diff = QTextBrowser(lineWrapMode=QTextBrowser.NoWrap)
        self.uni_diff = QTextBrowser(lineWrapMode=QTextBrowser.NoWrap)
        self.copyCheck = QCheckBox(
            checked=QSettings().value('convert_ly/copy_messages', True, bool))
        self.tabw = QTabWidget()

        self.tabw.addTab(self.messages, '')
        self.tabw.addTab(self.diff, '')
        self.tabw.addTab(self.uni_diff, '')

        self.buttons = QDialogButtonBox(QDialogButtonBox.Reset
                                        | QDialogButtonBox.Save
                                        | QDialogButtonBox.Ok
                                        | QDialogButtonBox.Cancel)
        self.buttons.button(QDialogButtonBox.Ok).clicked.connect(self.accept)
        self.buttons.rejected.connect(self.reject)
        self.buttons.button(QDialogButtonBox.Reset).clicked.connect(self.run)
        self.buttons.button(QDialogButtonBox.Save).clicked.connect(
            self.saveFile)

        layout = QVBoxLayout()
        self.setLayout(layout)

        grid = QGridLayout()
        grid.addWidget(self.fromVersionLabel, 0, 0)
        grid.addWidget(self.fromVersion, 0, 1)
        grid.addWidget(self.reason, 0, 2, 1, 3)
        grid.addWidget(self.toVersionLabel, 1, 0)
        grid.addWidget(self.toVersion, 1, 1)
        grid.addWidget(self.lilyChooser, 1, 3, 1, 2)

        layout.addLayout(grid)
        layout.addWidget(self.tabw)
        layout.addWidget(self.copyCheck)
        layout.addWidget(widgets.Separator())
        layout.addWidget(self.buttons)

        app.translateUI(self)
        qutil.saveDialogSize(self, 'convert_ly/dialog/size', QSize(600, 300))
        app.settingsChanged.connect(self.readSettings)
        self.readSettings()
        self.finished.connect(self.saveCopyCheckSetting)
        self.lilyChooser.currentIndexChanged.connect(
            self.slotLilyPondVersionChanged)
        self.slotLilyPondVersionChanged()
示例#54
0
class preferencesDialog(QDialog):
    def __init__(self, parent):
        QDialog.__init__(self, parent)
        self.tmpPref = {}
        self.tmpPref['pref'] = copy.deepcopy(self.parent().prm['pref'])
        self.currLocale = self.parent().prm['data']['currentLocale']
        self.currLocale.setNumberOptions(self.currLocale.OmitGroupSeparator | self.currLocale.RejectGroupSeparator)
        
        self.tabWidget = QTabWidget()
        self.tabWidget.currentChanged.connect(self.tabChanged)
        self.appPrefWidget = QWidget()
        self.plotPrefWidget = QWidget()
        self.signalPrefWidget = QWidget()
        self.soundPrefWidget = QWidget()

        
        #APP PREF
        appPrefGrid = QGridLayout()
        n = 0
        self.languageChooserLabel = QLabel(self.tr('Language (requires restart):'))
        appPrefGrid.addWidget(self.languageChooserLabel, n, 0)
        self.languageChooser = QComboBox()
        self.languageChooser.addItems(self.parent().prm['data']['available_languages'])
        self.languageChooser.setCurrentIndex(self.languageChooser.findText(self.tmpPref['pref']['language']))
        self.languageChooser.currentIndexChanged[int].connect(self.onLanguageChooserChange)
        appPrefGrid.addWidget(self.languageChooser, n, 1)
        n = n+1
        self.countryChooserLabel = QLabel(self.tr('Country (requires restart):'))
        appPrefGrid.addWidget(self.countryChooserLabel, n, 0)
        self.countryChooser = QComboBox()
        self.countryChooser.addItems(self.parent().prm['data']['available_countries'][self.tmpPref['pref']['language']])
        self.countryChooser.setCurrentIndex(self.countryChooser.findText(self.tmpPref['pref']['country']))
        appPrefGrid.addWidget(self.countryChooser, n, 1)

        self.appPrefWidget.setLayout(appPrefGrid)
        
        #PLOT PREF
        plotPrefGrid = QGridLayout()
        n = 0


        #LINE COLOUR
        self.lineColor1 = self.tmpPref['pref']['lineColor1']
        self.lineColorButton = QPushButton(self.tr("Line Color"), self)
        self.lineColorButton.clicked.connect(self.onChangeLineColor)
        plotPrefGrid.addWidget(self.lineColorButton, n, 0)

        self.lineColorSquare = QWidget(self)
        self.lineColorSquare.setStyleSheet("QWidget { background-color: %s }" % self.lineColor1.name())
        plotPrefGrid.addWidget(self.lineColorSquare, n, 1)
       
        n = n+1
        
        self.backgroundColor = self.tmpPref['pref']['backgroundColor']
        self.backgroundColorButton = QPushButton(self.tr("Background Color"), self)
        self.backgroundColorButton.clicked.connect(self.onChangeBackgroundColor)
        plotPrefGrid.addWidget(self.backgroundColorButton, n, 0)

        self.backgroundColorSquare = QWidget(self)
        self.backgroundColorSquare.setStyleSheet("QWidget { background-color: %s }" % self.backgroundColor.name())
        plotPrefGrid.addWidget(self.backgroundColorSquare, n, 1)

        n = n+1
        self.canvasColor = self.tmpPref['pref']['canvasColor']
        self.canvasColorButton = QPushButton(self.tr("Canvas Color"), self)
        self.canvasColorButton.clicked.connect(self.onChangeCanvasColor)
        plotPrefGrid.addWidget(self.canvasColorButton, n, 0)

        self.canvasColorSquare = QWidget(self)
        self.canvasColorSquare.setStyleSheet("QWidget { background-color: %s }" % self.canvasColor.name())
        plotPrefGrid.addWidget(self.canvasColorSquare, n, 1)
        
        n = n+1
        self.dpiLabel = QLabel(self.tr('DPI - Resolution:'))
        plotPrefGrid.addWidget(self.dpiLabel, n, 0)
        self.dpiWidget = QLineEdit(str(self.tmpPref['pref']['dpi']))
        plotPrefGrid.addWidget(self.dpiWidget, n, 1)
        self.dpiWidget.setValidator(QIntValidator(self))
        self.dpiWidget.editingFinished.connect(self.ondpiChange)
        
        n = n+1
        self.cmapChooserLabel = QLabel(self.tr('Color Map:'))
        plotPrefGrid.addWidget(self.cmapChooserLabel, n, 0)
        self.cmapChooser = QComboBox()
        self.cmapChooser.addItems(self.parent().prm['data']['available_colormaps'])
        self.cmapChooser.setCurrentIndex(self.cmapChooser.findText(self.tmpPref['pref']['colormap']))
        plotPrefGrid.addWidget(self.cmapChooser, n, 1)
        n = n+1
        
        self.gridOn = QCheckBox(self.tr('Grid'))
        self.gridOn.setChecked(self.tmpPref['pref']['grid'])
        plotPrefGrid.addWidget(self.gridOn, n, 1)

        self.plotPrefWidget.setLayout(plotPrefGrid)
        
        #SIGNAL PREF
        signalPrefGrid = QGridLayout()
        n = 0
        self.windowChooser = QComboBox()
        self.windowChooser.addItems(self.parent().prm['data']['available_windows'])
        self.windowChooser.setCurrentIndex(self.windowChooser.findText(self.tmpPref['pref']['smoothingWindow']))
        self.windowChooserLabel = QLabel(self.tr('Window:'))
        signalPrefGrid.addWidget(self.windowChooserLabel, 0, 0)
        signalPrefGrid.addWidget(self.windowChooser, 0, 1)

        n = n+1
        self.signalPrefWidget.setLayout(signalPrefGrid)
        
        #SOUND PREF
        soundPrefGrid = QGridLayout()
        n = 0
        self.wavmanagerLabel = QLabel(self.tr('Wav Manager (requires restart):'))
        self.wavmanagerChooser = QComboBox()
        self.wavmanagerChooser.addItems(["scipy"])
        self.wavmanagerChooser.setCurrentIndex(self.wavmanagerChooser.findText(self.tmpPref['pref']['wavmanager']))
        soundPrefGrid.addWidget(self.wavmanagerLabel, n, 0)
        soundPrefGrid.addWidget(self.wavmanagerChooser, n, 1)

        n = n+1
        
        self.playChooser = QComboBox()
        self.playChooser.addItems(self.parent().prm['data']['available_play_commands'])
        self.playChooser.setCurrentIndex(self.playChooser.findText(self.tmpPref['pref']['playCommandType']))
        self.playChooser.currentIndexChanged[int].connect(self.onPlayChooserChange)
        self.playChooserLabel = QLabel(self.tr('Play Command:'))
        soundPrefGrid.addWidget(self.playChooserLabel, n, 0)
        soundPrefGrid.addWidget(self.playChooser, n, 1)

        n = n+1
        self.playCommandLabel = QLabel(self.tr('Command:'))
        soundPrefGrid.addWidget(self.playCommandLabel, n, 0)
        self.playCommandWidget = QLineEdit(str(self.tmpPref['pref']['playCommand']))
        self.playCommandWidget.setReadOnly(True)
        soundPrefGrid.addWidget(self.playCommandWidget, n, 1)

        n = n+1
        self.maxLevelLabel = QLabel(self.tr('Max Level:'))
        soundPrefGrid.addWidget(self.maxLevelLabel, n, 0)
        self.maxLevelWidget = QLineEdit(self.currLocale.toString(self.tmpPref['pref']['maxLevel']))
        self.maxLevelWidget.setValidator(QDoubleValidator(self))
        soundPrefGrid.addWidget(self.maxLevelWidget, n, 1)

        
        self.soundPrefWidget.setLayout(soundPrefGrid)

        self.tabWidget.addTab(self.appPrefWidget, self.tr("Applicatio&n"))
        self.tabWidget.addTab(self.plotPrefWidget, self.tr("Plot&s"))
        self.tabWidget.addTab(self.signalPrefWidget, self.tr("Signa&l"))
        self.tabWidget.addTab(self.soundPrefWidget, self.tr("Soun&d"))

        buttonBox = QDialogButtonBox(QDialogButtonBox.Apply|QDialogButtonBox.Ok|QDialogButtonBox.Cancel)
        buttonBox.accepted.connect(self.accept)
        buttonBox.rejected.connect(self.reject)
        buttonBox.button(QDialogButtonBox.Apply).clicked.connect(self.permanentApply)
        
        layout = QVBoxLayout()
        layout.addWidget(self.tabWidget)
        layout.addWidget(buttonBox)
        self.setLayout(layout)
      

    def ondpiChange(self):
        try:
            val = int(self.dpiWidget.text())
        except ValueError:
            QMessageBox.warning(self, self.tr('Warning'), self.tr('dpi value not valid'))
            self.dpiWidget.setText(str(self.tmpPref['pref']['dpi']))

        val = int(self.dpiWidget.text())
        if val < 10:
            QMessageBox.warning(self, self.tr('Warning'), self.tr('dpi value too small'))
            self.dpiWidget.setText(str(10))

    def onChangeLineColor(self):
        col = QColorDialog.getColor()
        if col.isValid():
            self.lineColor1 = col
        self.lineColorSquare.setStyleSheet("QWidget { background-color: %s }" % self.lineColor1.name())
    def onChangeCanvasColor(self):
        col = QColorDialog.getColor()
        if col.isValid():
            self.canvasColor = col
        self.canvasColorSquare.setStyleSheet("QWidget { background-color: %s }" % self.canvasColor.name())
    def onChangeBackgroundColor(self):
        col = QColorDialog.getColor()
        if col.isValid():
            self.backgroundColor = col
        self.backgroundColorSquare.setStyleSheet("QWidget { background-color: %s }" % self.backgroundColor.name())
    def onLanguageChooserChange(self):
        for i in range(self.countryChooser.count()):
            self.countryChooser.removeItem(0)
        self.countryChooser.addItems(self.parent().prm['data']['available_countries'][self.languageChooser.currentText()])
    def onPlayChooserChange(self):
        foo = self.playChooser.currentText()
        if foo != self.tr('custom'):
            self.playCommandWidget.setText(foo)
            self.playCommandWidget.setReadOnly(True)
        else:
            self.playCommandWidget.setReadOnly(False)

            

    def tryApply(self):
        self.tmpPref['pref']['colormap'] = str(self.cmapChooser.currentText())
        self.tmpPref['pref']['dpi'] = int(self.dpiWidget.text())
        self.tmpPref['pref']['lineColor1'] = self.lineColor1
        self.tmpPref['pref']['canvasColor'] = self.canvasColor
        self.tmpPref['pref']['backgroundColor'] = self.backgroundColor
        self.tmpPref['pref']['language'] = self.languageChooser.currentText()
        self.tmpPref['pref']['country'] = self.countryChooser.currentText()
        self.tmpPref['pref']['wavmanager'] = str(self.wavmanagerChooser.currentText())
        self.tmpPref['pref']['playCommand'] = self.playCommandWidget.text()
        self.tmpPref['pref']['playCommandType'] = self.playChooser.currentText()
        self.tmpPref['pref']['maxLevel'] = self.currLocale.toDouble(self.maxLevelWidget.text())[0]
        if self.gridOn.isChecked():
            self.tmpPref['pref']['grid'] = True
        else:
            self.tmpPref['pref']['grid'] = False
        self.tmpPref['pref']['smoothingWindow'] = str(self.windowChooser.currentText())

    def revertChanges(self):
        self.cmapChooser.setCurrentIndex(self.cmapChooser.findText(self.tmpPref['pref']['colormap']))
        self.dpiWidget.setText(str(self.tmpPref['pref']['dpi']))
        self.languageChooser.setCurrentIndex(self.languageChooser.findText(self.tmpPref['pref']['language']))
        self.countryChooser.setCurrentIndex(self.countryChooser.findText(self.tmpPref['pref']['country']))
        self.wavmanagerChooser.setCurrentIndex(self.wavmanagerChooser.findText(self.tmpPref['pref']['sound']['wavmanager']))
        self.playChooser.setCurrentIndex(self.playChooser.findText(self.tmpPref['pref']['playCommandType']))
        self.playCommandWidget.setText(self.tmpPref['pref']['playCommand'])
        if self.playChooser.currentText() != self.tr('custom'):
            self.playCommandWidget.setReadOnly(True)
        self.maxLevelWidget.setText(str(self.tmpPref['pref']['maxLevel']))
        self.gridOn.setChecked(self.tmpPref['pref']['grid'])
        self.windowChooser.setCurrentIndex(self.windowChooser.findText(self.tmpPref['pref']['smoothingWindow']))
        self.lineColor1 = self.tmpPref['pref']['lineColor1']
        self.lineColorSquare.setStyleSheet("QWidget { background-color: %s }" % self.lineColor1.name())
        self.canvasColor = self.tmpPref['pref']['canvasColor']
        self.backgroundColor = self.tmpPref['pref']['backgroundColor']
        self.backgroundColorSquare.setStyleSheet("QWidget { background-color: %s }" % self.backgroundColor.name())
        self.canvasColorSquare.setStyleSheet("QWidget { background-color: %s }" % self.canvasColor.name())
       
        
       
    def permanentApply(self):
        self.tryApply()
        self.parent().prm['pref'] = copy.deepcopy(self.tmpPref['pref'])
        f = open(self.parent().prm['prefFile'], 'wb')
        pickle.dump(self.parent().prm['pref'], f)
        f.close()

    def tabChanged(self):
        self.tryApply()
        if self.tmpPref['pref'] != self.parent().prm['pref']:
            conf = applyChanges(self)
            if conf.exec_():
                self.permanentApply()
            else:
                self.tmpPref['pref'] = copy.deepcopy(self.parent().prm['pref'])
                self.revertChanges()
示例#55
0
class RowPanel(QWidget):
    def __init__(self, name):
        QWidget.__init__(self)
        self.__name = name
        self.__layout_queue = []
        self.setMinimumWidth(500)
        self.__layout = QGridLayout()
        """ @type: QGridLayout """
        self.setLayout(self.__layout)
        self.__row = 0
        self.__widgets = {}

        self.__layout.setColumnMinimumWidth(0, 20)
        self.__layout.setColumnMinimumWidth(6, 20)

        self.__popups = []

    def getName(self):
        return self.__name

    def __startNewRow(self):
        self.__layout.setRowStretch(self.__row, 0)

    def __rowFinished(self):
        self.__row += 2
        self.__layout.setRowStretch(self.__row, 1)

    def addRow(self,
               row_widget,
               configurator=None,
               configuration_title="Configure"):
        """
        Add a new row on a configuration page. Returns the row widget.
        If the row does not have a getLabel() function the row spans both columns.

        @rtype: QWidget
        """
        assert hasattr(row_widget,
                       "getLabel"), "Widget must have a getLabel() method"

        self.__startNewRow()

        if row_widget.getLabel() is None or row_widget.getLabel() == "":
            self.__layout.addWidget(row_widget, self.__row, 1, 1, 3)
        else:
            self.__layout.addWidget(QLabel(row_widget.getLabel()), self.__row,
                                    1, Qt.AlignLeft | Qt.AlignTop)
            self.__layout.addWidget(row_widget, self.__row, 3)

        if not configurator is None:
            self.__layout.setColumnMinimumWidth(4, 20)
            button = self.__addConfigurationButton(configurator,
                                                   configuration_title)
            self.__layout.addWidget(button, self.__row, 5)

        self.__widgets[row_widget] = self.__row

        self.__rowFinished()

    def startTabs(self, name_of_first_tab):
        self.__tab_widget = QTabWidget()
        self.__layout_queue.append(self.__layout)
        self.__layout = None
        self.addTab(name_of_first_tab)

    def addTab(self, name):
        self.__layout = QGridLayout()
        widget = QWidget()
        widget.setLayout(self.__layout)
        self.__tab_widget.addTab(widget, name)

    def endTabs(self):
        self.__layout = self.__layout_queue.pop()
        """ @type: QGridLayout """
        self.__startNewRow()
        self.__layout.addWidget(self.__tab_widget, self.__row, 1, 1, 5)
        self.__rowFinished()
        self.__tab_widget = None

    def startGroup(self, group_title):
        """Start a titled sub group on the page."""
        self.__group_box = QGroupBox(group_title)
        self.__layout_queue.append(self.__layout)
        self.__layout = QGridLayout()

    def endGroup(self):
        """Finish the titled sub group"""
        self.__group_box.setLayout(self.__layout)
        self.__layout = self.__layout_queue.pop()
        """ @type: QGridLayout """
        self.__layout.addRow(self.__group_box)
        self.__group_box = None

    def addLabeledSeparator(self, label):
        """Adds a labeled separator line to the panel."""
        widget = QWidget()
        layout = QVBoxLayout()
        widget.setLayout(layout)

        h_layout = QHBoxLayout()

        frame = QFrame()
        frame.setFrameShape(QFrame.HLine)
        frame.setFrameShadow(QFrame.Sunken)

        h_layout.addWidget(QLabel(label))
        h_layout.addWidget(frame, 1, Qt.AlignBottom)

        layout.addSpacing(2)
        layout.addLayout(h_layout)
        layout.addSpacing(0)

        # widget.setStyleSheet("background-color: #ffff00")

        self.__startNewRow()
        self.__layout.addWidget(widget, self.__row, 0, 1, 7)
        self.__rowFinished()

    def addSeparator(self):
        widget = QWidget()
        layout = QVBoxLayout()
        widget.setLayout(layout)

        frame = QFrame()
        frame.setFrameShape(QFrame.HLine)
        frame.setFrameShadow(QFrame.Sunken)

        layout.addSpacing(5)
        layout.addWidget(frame)
        layout.addSpacing(5)

        self.__startNewRow()
        self.__layout.addWidget(widget, self.__row, 1, 1, 5)
        self.__rowFinished()

    def __addConfigurationButton(self, configurator, configuration_title):
        popup = PopupDialog(configurator.getName(), configurator, self)
        button = popup.getButton()
        button.setText(configuration_title)
        self.__popups.append(popup)
        return button

    def addSpace(self, size=5):
        """Creates a widget that can be used as spacing on  a panel."""
        space = QWidget()
        space.setMinimumSize(QSize(size, size))
        self.__startNewRow()
        self.__layout.addWidget(space, self.__row, 1, 1, 5)
        self.__rowFinished()
示例#56
0
def buildfromauto(formconfig, base):
    widgetsconfig = copy.deepcopy(formconfig['widgets'])

    try:
        widgetsconfig = base.get_widgets(widgetsconfig)
    except AttributeError:
        pass

    newstyle = formconfig.get("newstyle", False)
    hassections = any(config['widget'] == "Section" for config in widgetsconfig)

    def make_layout():
        if newstyle:
            return QVBoxLayout()
        else:
            layout = QFormLayout()
            layout.setFieldGrowthPolicy(QFormLayout.AllNonFixedFieldsGrow)
            return layout

    def make_tab(tabwidget, name):
        widget = QWidget()
        widget.setLayout(make_layout())
        tabwidget.addTab(widget, name)
        return widget, widget.layout()

    if hassections:
        outwidget = QTabWidget(base)
        outlayout = None
        base.setLayout(QVBoxLayout())
        base.layout().setContentsMargins(0,0,0,0)
        base.layout().addWidget(outwidget)
    else:
        outwidget = base
        outlayout = make_layout()
        outwidget.setLayout(outlayout)

    if roam.config.settings.get("form_geom_edit", False):
        geomwidget = GeomWidget()
        geomwidget.setObjectName("__geomwidget")
        outlayout.addRow("Geometry", geomwidget)

    insection = False
    for config in widgetsconfig:
        widgettype = config['widget']

        ## Make the first tab if one isn't defined already and we have other sections in the config
        if not insection and hassections and not widgettype == "Section":
            name = formconfig['label']
            tabwidget, outlayout = make_tab(outwidget, name)
            insection = True

        if widgettype == 'Section':
            # Add a spacer to the last widget
            if outlayout:
                spacer = QWidget()
                spacer.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Expanding)
                outlayout.addItem(QSpacerItem(10, 500))
                outlayout.addWidget(spacer)

            name = config['name']
            tabwidget, outlayout = make_tab(outwidget, name)
            installflickcharm(tabwidget)
            insection = True
            continue

        field = config['field']
        name = config.get('name', field)
        if not field:
            utils.warning("Field can't be null for {}".format(name))
            utils.warning("Skipping widget")
            continue

        label = QLabel(name)
        label.setObjectName(field + "_label")
        labelwidget = QWidget()
        labelwidget.setLayout(QBoxLayout(QBoxLayout.LeftToRight))
        labelwidget.layout().addWidget(label)
        labelwidget.layout().setContentsMargins(0,0,0,0)

        widget = roam.editorwidgets.core.createwidget(widgettype, parent=base)
        widget.setObjectName(field)
        layoutwidget = QWidget()
        layoutwidget.setLayout(QBoxLayout(QBoxLayout.LeftToRight))
        layoutwidget.layout().addWidget(widget)
        layoutwidget.layout().setContentsMargins(0,0,0,10)

        if config.get('rememberlastvalue', False):
            savebutton = QToolButton()
            savebutton.setObjectName('{}_save'.format(field))
            if newstyle:
                spacer = QWidget()
                spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
                labelwidget.layout().addWidget(spacer)
                labelwidget.layout().addWidget(savebutton)
            else:
                layoutwidget.layout().addWidget(savebutton)

        if newstyle:
            outlayout.addWidget(labelwidget)
            outlayout.addWidget(layoutwidget)
        else:
            outlayout.addRow(labelwidget, layoutwidget)

    spacer = QWidget()
    spacer.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Expanding)
    outlayout.addWidget(spacer)
    if not hassections:
        outlayout.addItem(QSpacerItem(10, 500))
        installflickcharm(outwidget)
    return base
示例#57
0
文件: db_manager.py 项目: jarped/QGIS
class DBManager(QMainWindow):
    def __init__(self, iface, parent=None):
        QMainWindow.__init__(self, parent)
        self.setAttribute(Qt.WA_DeleteOnClose)
        self.setupUi()
        self.iface = iface

        # restore the window state
        settings = QSettings()
        self.restoreGeometry(
            settings.value("/DB_Manager/mainWindow/geometry",
                           QByteArray(),
                           type=QByteArray))
        self.restoreState(
            settings.value("/DB_Manager/mainWindow/windowState",
                           QByteArray(),
                           type=QByteArray))

        self.connect(self.tabs, SIGNAL("currentChanged(int)"), self.tabChanged)
        self.connect(self.tree, SIGNAL("selectedItemChanged"),
                     self.itemChanged)
        self.itemChanged(None)

    def closeEvent(self, e):
        self.unregisterAllActions()

        # save the window state
        settings = QSettings()
        settings.setValue("/DB_Manager/mainWindow/windowState",
                          self.saveState())
        settings.setValue("/DB_Manager/mainWindow/geometry",
                          self.saveGeometry())

        QMainWindow.closeEvent(self, e)

    def refreshItem(self, item=None):
        QApplication.setOverrideCursor(Qt.WaitCursor)
        try:
            if item is None:
                item = self.tree.currentItem()
            self.tree.refreshItem(item)  # refresh item children in the db tree
        except BaseError as e:
            DlgDbError.showError(e, self)
            return
        finally:
            QApplication.restoreOverrideCursor()

    def itemChanged(self, item):
        QApplication.setOverrideCursor(Qt.WaitCursor)
        try:
            self.reloadButtons()
            self.refreshTabs()
        except BaseError as e:
            DlgDbError.showError(e, self)
            return
        finally:
            QApplication.restoreOverrideCursor()

    def reloadButtons(self):
        db = self.tree.currentDatabase()
        if not hasattr(self, '_lastDb'):
            self._lastDb = db

        elif db == self._lastDb:
            return

        # remove old actions
        if self._lastDb is not None:
            self.unregisterAllActions()

        # add actions of the selected database
        self._lastDb = db
        if self._lastDb is not None:
            self._lastDb.registerAllActions(self)

    def tabChanged(self, index):
        QApplication.setOverrideCursor(Qt.WaitCursor)
        try:
            self.refreshTabs()
        except BaseError as e:
            DlgDbError.showError(e, self)
            return
        finally:
            QApplication.restoreOverrideCursor()

    def refreshTabs(self):
        index = self.tabs.currentIndex()
        item = self.tree.currentItem()
        table = self.tree.currentTable()

        # enable/disable tabs
        self.tabs.setTabEnabled(self.tabs.indexOf(self.table), table
                                is not None)
        self.tabs.setTabEnabled(
            self.tabs.indexOf(self.preview), table is not None
            and table.type in [table.VectorType, table.RasterType]
            and table.geomColumn is not None)
        # show the info tab if the current tab is disabled
        if not self.tabs.isTabEnabled(index):
            self.tabs.setCurrentWidget(self.info)

        current_tab = self.tabs.currentWidget()
        if current_tab == self.info:
            self.info.showInfo(item)
        elif current_tab == self.table:
            self.table.loadData(item)
        elif current_tab == self.preview:
            self.preview.loadPreview(item)

    def refreshActionSlot(self):
        self.info.setDirty()
        self.table.setDirty()
        self.preview.setDirty()
        self.refreshItem()

    def importActionSlot(self):
        db = self.tree.currentDatabase()
        if db is None:
            self.infoBar.pushMessage(
                self.tr(
                    "No database selected or you are not connected to it."),
                QgsMessageBar.INFO, self.iface.messageTimeout())
            return

        outUri = db.uri()
        schema = self.tree.currentSchema()
        if schema:
            outUri.setDataSource(schema.name, "", "", "")

        from .dlg_import_vector import DlgImportVector

        dlg = DlgImportVector(None, db, outUri, self)
        dlg.exec_()

    def exportActionSlot(self):
        table = self.tree.currentTable()
        if table is None:
            self.infoBar.pushMessage(
                self.tr("Select the table you want export to file."),
                QgsMessageBar.INFO, self.iface.messageTimeout())
            return

        inLayer = table.toMapLayer()

        from .dlg_export_vector import DlgExportVector

        dlg = DlgExportVector(inLayer, table.database(), self)
        dlg.exec_()

        inLayer.deleteLater()

    def runSqlWindow(self):
        db = self.tree.currentDatabase()
        if db is None:
            self.infoBar.pushMessage(
                self.tr(
                    "No database selected or you are not connected to it."),
                QgsMessageBar.INFO, self.iface.messageTimeout())
            # force displaying of the message, it appears on the first tab (i.e. Info)
            self.tabs.setCurrentIndex(0)
            return

        from dlg_sql_window import DlgSqlWindow

        query = DlgSqlWindow(self.iface, db, self)
        dbname = db.connection().connectionName()
        tabname = self.tr("Query") + u" (%s)" % dbname
        index = self.tabs.addTab(query, tabname)
        self.tabs.setTabIcon(index, db.connection().icon())
        self.tabs.setCurrentIndex(index)
        query.nameChanged.connect(
            functools.partial(self.update_query_tab_name, index, dbname))

    def update_query_tab_name(self, index, dbname, queryname):
        if not queryname:
            queryname = self.tr("Query")
        tabname = u"%s (%s)" % (queryname, dbname)
        self.tabs.setTabText(index, tabname)

    def showSystemTables(self):
        self.tree.showSystemTables(self.actionShowSystemTables.isChecked())

    def registerAction(self, action, menuName, callback=None):
        """ register an action to the manager's main menu """
        if not hasattr(self, '_registeredDbActions'):
            self._registeredDbActions = {}

        if callback is not None:
            invoke_callback = lambda x: self.invokeCallback(callback)

        if menuName is None or menuName == "":
            self.addAction(action)

            if menuName not in self._registeredDbActions:
                self._registeredDbActions[menuName] = list()
            self._registeredDbActions[menuName].append(action)

            if callback is not None:
                QObject.connect(action, SIGNAL("triggered(bool)"),
                                invoke_callback)
            return True

        # search for the menu
        actionMenu = None
        helpMenuAction = None
        for a in self.menuBar.actions():
            if not a.menu() or a.menu().title() != menuName:
                continue
            if a.menu() != self.menuHelp:
                helpMenuAction = a

            actionMenu = a
            break

        # not found, add a new menu before the help menu
        if actionMenu is None:
            menu = QMenu(menuName, self)
            if helpMenuAction is not None:
                actionMenu = self.menuBar.insertMenu(helpMenuAction, menu)
            else:
                actionMenu = self.menuBar.addMenu(menu)

        menu = actionMenu.menu()
        menuActions = menu.actions()

        # get the placeholder's position to insert before it
        pos = 0
        for pos in range(len(menuActions)):
            if menuActions[pos].isSeparator() and menuActions[pos].objectName(
            ).endswith("_placeholder"):
                menuActions[pos].setVisible(True)
                break

        if pos < len(menuActions):
            before = menuActions[pos]
            menu.insertAction(before, action)
        else:
            menu.addAction(action)

        actionMenu.setVisible(True)  # show the menu

        if menuName not in self._registeredDbActions:
            self._registeredDbActions[menuName] = list()
        self._registeredDbActions[menuName].append(action)

        if callback is not None:
            QObject.connect(action, SIGNAL("triggered(bool)"), invoke_callback)

        return True

    def invokeCallback(self, callback, *params):
        """ Call a method passing the selected item in the database tree,
                the sender (usually a QAction), the plugin mainWindow and
                optionally additional parameters.

                This method takes care to override and restore the cursor,
                but also catches exceptions and displays the error dialog.
        """
        QApplication.setOverrideCursor(Qt.WaitCursor)
        try:
            callback(self.tree.currentItem(), self.sender(), self, *params)

        except BaseError as e:
            # catch database errors and display the error dialog
            DlgDbError.showError(e, self)
            return

        finally:
            QApplication.restoreOverrideCursor()

    def unregisterAction(self, action, menuName):
        if not hasattr(self, '_registeredDbActions'):
            return

        if menuName is None or menuName == "":
            self.removeAction(action)

            if menuName in self._registeredDbActions:
                if self._registeredDbActions[menuName].count(action) > 0:
                    self._registeredDbActions[menuName].remove(action)

            action.deleteLater()
            return True

        for a in self.menuBar.actions():
            if not a.menu() or a.menu().title() != menuName:
                continue

            menu = a.menu()
            menuActions = menu.actions()

            menu.removeAction(action)
            if menu.isEmpty():  # hide the menu
                a.setVisible(False)

            if menuName in self._registeredDbActions:
                if self._registeredDbActions[menuName].count(action) > 0:
                    self._registeredDbActions[menuName].remove(action)

                # hide the placeholder if there're no other registered actions
                if len(self._registeredDbActions[menuName]) <= 0:
                    for i in range(len(menuActions)):
                        if menuActions[i].isSeparator() and menuActions[
                                i].objectName().endswith("_placeholder"):
                            menuActions[i].setVisible(False)
                            break

            action.deleteLater()
            return True

        return False

    def unregisterAllActions(self):
        if not hasattr(self, '_registeredDbActions'):
            return

        for menuName in self._registeredDbActions:
            for action in list(self._registeredDbActions[menuName]):
                self.unregisterAction(action, menuName)
        del self._registeredDbActions

    def close_tab(self, index):
        widget = self.tabs.widget(index)
        if widget not in [self.info, self.table, self.preview]:
            self.tabs.removeTab(index)
            widget.deleteLater()

    def setupUi(self):
        self.setWindowTitle(self.tr("DB Manager"))
        self.setWindowIcon(QIcon(":/db_manager/icon"))
        self.resize(QSize(700, 500).expandedTo(self.minimumSizeHint()))

        # create central tab widget and add the first 3 tabs: info, table and preview
        self.tabs = QTabWidget()
        self.info = InfoViewer(self)
        self.tabs.addTab(self.info, self.tr("Info"))
        self.table = TableViewer(self)
        self.tabs.addTab(self.table, self.tr("Table"))
        self.preview = LayerPreview(self)
        self.tabs.addTab(self.preview, self.tr("Preview"))
        self.setCentralWidget(self.tabs)

        # display close button for all tabs but the first 3 ones, i.e.
        # HACK: just hide the close button where not needed (GS)
        self.tabs.setTabsClosable(True)
        self.tabs.tabCloseRequested.connect(self.close_tab)
        tabbar = self.tabs.tabBar()
        for i in range(3):
            btn = tabbar.tabButton(i, QTabBar.RightSide) if tabbar.tabButton(
                i, QTabBar.RightSide) else tabbar.tabButton(
                    i, QTabBar.LeftSide)
            btn.resize(0, 0)
            btn.hide()

        # Creates layout for message bar
        self.layout = QGridLayout(self.info)
        self.layout.setContentsMargins(0, 0, 0, 0)
        spacerItem = QSpacerItem(20, 40, QSizePolicy.Minimum,
                                 QSizePolicy.Expanding)
        self.layout.addItem(spacerItem, 1, 0, 1, 1)
        # init messageBar instance
        self.infoBar = QgsMessageBar(self.info)
        sizePolicy = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed)
        self.infoBar.setSizePolicy(sizePolicy)
        self.layout.addWidget(self.infoBar, 0, 0, 1, 1)

        # create database tree
        self.dock = QDockWidget("Tree", self)
        self.dock.setObjectName("DB_Manager_DBView")
        self.dock.setFeatures(QDockWidget.DockWidgetMovable)
        self.tree = DBTree(self)
        self.dock.setWidget(self.tree)
        self.addDockWidget(Qt.LeftDockWidgetArea, self.dock)

        # create status bar
        self.statusBar = QStatusBar(self)
        self.setStatusBar(self.statusBar)

        # create menus
        self.menuBar = QMenuBar(self)
        self.menuDb = QMenu(self.tr("&Database"), self)
        self.menuBar.addMenu(self.menuDb)
        self.menuSchema = QMenu(self.tr("&Schema"), self)
        actionMenuSchema = self.menuBar.addMenu(self.menuSchema)
        self.menuTable = QMenu(self.tr("&Table"), self)
        actionMenuTable = self.menuBar.addMenu(self.menuTable)
        self.menuHelp = None  # QMenu(self.tr("&Help"), self)
        # actionMenuHelp = self.menuBar.addMenu(self.menuHelp)

        self.setMenuBar(self.menuBar)

        # create toolbar
        self.toolBar = QToolBar("Default", self)
        self.toolBar.setObjectName("DB_Manager_ToolBar")
        self.addToolBar(self.toolBar)

        # create menus' actions

        # menu DATABASE
        sep = self.menuDb.addSeparator()
        sep.setObjectName("DB_Manager_DbMenu_placeholder")
        sep.setVisible(False)

        self.actionRefresh = self.menuDb.addAction(
            QIcon(":/db_manager/actions/refresh"), self.tr("&Refresh"),
            self.refreshActionSlot, QKeySequence("F5"))
        self.actionSqlWindow = self.menuDb.addAction(
            QIcon(":/db_manager/actions/sql_window"), self.tr("&SQL window"),
            self.runSqlWindow, QKeySequence("F2"))
        self.menuDb.addSeparator()
        self.actionClose = self.menuDb.addAction(QIcon(), self.tr("&Exit"),
                                                 self.close,
                                                 QKeySequence("CTRL+Q"))

        # menu SCHEMA
        sep = self.menuSchema.addSeparator()
        sep.setObjectName("DB_Manager_SchemaMenu_placeholder")
        sep.setVisible(False)

        actionMenuSchema.setVisible(False)

        # menu TABLE
        sep = self.menuTable.addSeparator()
        sep.setObjectName("DB_Manager_TableMenu_placeholder")
        sep.setVisible(False)

        self.actionImport = self.menuTable.addAction(
            QIcon(":/db_manager/actions/import"),
            self.tr("&Import layer/file"), self.importActionSlot)
        self.actionExport = self.menuTable.addAction(
            QIcon(":/db_manager/actions/export"), self.tr("&Export to file"),
            self.exportActionSlot)
        self.menuTable.addSeparator()
        #self.actionShowSystemTables = self.menuTable.addAction(self.tr("Show system tables/views"), self.showSystemTables)
        #self.actionShowSystemTables.setCheckable(True)
        #self.actionShowSystemTables.setChecked(True)
        actionMenuTable.setVisible(False)

        # add actions to the toolbar
        self.toolBar.addAction(self.actionRefresh)
        self.toolBar.addAction(self.actionSqlWindow)
        self.toolBar.addAction(self.actionImport)
        self.toolBar.addAction(self.actionExport)
示例#58
0
class PanelManager(QWidget):
    def __init__(self, parent, devmgr):
        QWidget.__init__(self, parent)
        self.devmgr = devmgr
        self.devmgr.registerPreUpdateCallback(self.devlistPreUpdate)
        self.devmgr.registerPostUpdateCallback(self.devlistPostUpdate)
        self.devmgr.registerUpdateCallback(self.devlistUpdate)
        self.devmgr.registerDestroyedCallback(self.devmgrDestroyed)

        # maps a device GUID to a QT panel
        self.panels = {}

        # a layout for ourselves
        self.layout = QVBoxLayout(self)

        # the tabs
        self.tabs = QTabWidget(self)
        self.tabs.hide()
        self.layout.addWidget(self.tabs)

        # a dialog that is shown during update
        self.status = PanelManagerStatus(self)
        self.status.lblMessage.setText("Initializing...")
        self.layout.addWidget(self.status)
        self.status.show()

        # live check timer
        self.alivetimer = QTimer()
        QObject.connect(self.alivetimer, SIGNAL('timeout()'), self.commCheck)
        self.alivetimer.start(2000)

    def count(self):
        return self.tabs.count()

    def pollPanels(self):
        # only when not modifying the tabs
        if self.tabs.isEnabled():
            for guid in self.panels.keys():
                w = self.panels[guid]
                for child in w.children():
                    #log.debug("poll child %s,%s" % (guid,child))
                    if 'polledUpdate' in dir(child):
                        try:
                            child.polledUpdate()
                        except:
                            log.error("error in polled update")
                            raise

    def devlistPreUpdate(self):
        log.debug("devlistPreUpdate")
        self.tabs.setEnabled(False)
        self.tabs.hide()
        self.status.lblMessage.setText(
            "Bus reconfiguration in progress, please wait...")
        self.status.show()

    def devlistPostUpdate(self):
        log.debug("devlistPostUpdate")
        # this can fail if multiple busresets happen in fast succession
        ntries = 10
        while ntries > 0:
            try:
                self.updatePanels()
                return
            except:
                log.debug("devlistPostUpdate failed (%d)" % ntries)
                for guid in self.panels.keys():
                    w = self.panels[guid]
                    del self.panels[guid]  # remove from the list
                    idx = self.tabs.indexOf(w)
                    self.tabs.removeTab(idx)
                    del w  # GC might also take care of that

                ntries = ntries - 1
                time.sleep(2)  # sleep a few seconds

        log.debug("devlistPostUpdate failed completely")
        self.tabs.setEnabled(False)
        self.tabs.hide()
        self.status.lblMessage.setText(
            "Error while reconfiguring. Please restart ffadomixer.")
        self.status.show()

    def devlistUpdate(self):
        log.debug("devlistUpdate")

    def devmgrDestroyed(self):
        log.debug("devmgrDestroyed")
        self.alivetimer.stop()
        self.tabs.setEnabled(False)
        self.tabs.hide()
        self.status.lblMessage.setText(
            "DBUS server was shut down, please restart it and restart ffadomixer..."
        )
        self.status.show()

    def commCheck(self):
        try:
            nbDevices = self.devmgr.getNbDevices()
        except:
            log.debug("comms lost")
            self.tabs.setEnabled(False)
            self.tabs.hide()
            self.status.lblMessage.setText(
                "Failed to communicate with DBUS server. Please restart it and restart ffadomixer..."
            )
            self.status.show()
            self.alivetimer.stop()

    def updatePanels(self):
        nbDevices = self.devmgr.getNbDevices()

        # list of panels present
        guids_with_tabs = self.panels.keys()

        # build list of guids on the bus now
        guids_present = []
        guid_indexes = {}
        for idx in range(nbDevices):
            path = self.devmgr.getDeviceName(idx)
            cfgrom = ConfigRomInterface(
                FFADO_DBUS_SERVER,
                FFADO_DBUS_BASEPATH + '/DeviceManager/' + path)
            guid = cfgrom.getGUID()
            guids_present.append(guid)
            guid_indexes[guid] = idx

        # figure out what to remove
        # the special panel (generic)
        # that has (pseudo-)GUID 0
        # is also automatically removed
        to_remove = []
        for guid in guids_with_tabs:
            if not guid in guids_present:
                to_remove.append(guid)
                log.debug("going to remove %s" % str(guid))
            else:
                log.debug("going to keep %s" % str(guid))

        # figure out what to add
        to_add = []
        for guid in guids_present:
            if not guid in guids_with_tabs:
                to_add.append(guid)
                log.debug("going to add %s" % str(guid))

        # update the widget
        for guid in to_remove:
            w = self.panels[guid]
            del self.panels[guid]  # remove from the list
            idx = self.tabs.indexOf(w)
            self.tabs.removeTab(idx)
            del w  # GC might also take care of that

        for guid in to_add:
            # retrieve the device manager index
            idx = guid_indexes[guid]
            path = self.devmgr.getDeviceName(idx)
            log.debug("Adding device %d: %s" % (idx, path))

            cfgrom = ConfigRomInterface(
                FFADO_DBUS_SERVER,
                FFADO_DBUS_BASEPATH + '/DeviceManager/' + path)
            vendorId = cfgrom.getVendorId()
            modelId = cfgrom.getModelId()
            unitVersion = cfgrom.getUnitVersion()
            guid = cfgrom.getGUID()
            vendorName = cfgrom.getVendorName()
            modelName = cfgrom.getModelName()
            log.debug(" Found (%s, %X, %X) %s %s" %
                      (str(guid), vendorId, modelId, vendorName, modelName))

            # check whether this has already been registered at ffado.org
            reg = ffado_registration(FFADO_VERSION, int(guid, 16), vendorId,
                                     modelId, vendorName, modelName)
            reg.check_for_registration()

            thisdev = (vendorId, modelId)
            # The MOTU devices use unitVersion to differentiate models.  For the
            # moment thought we don't need to know precisely which model we're
            # using.
            if vendorId == 0x1f2:
                thisdev = (vendorId, 0x00000000)

            dev = None
            for d in SupportedDevices:
                if d[0] == thisdev:
                    dev = d

            w = QWidget()
            l = QVBoxLayout(w)

            # create a control object
            hw = ControlInterface(
                FFADO_DBUS_SERVER,
                FFADO_DBUS_BASEPATH + '/DeviceManager/' + path)
            clockselect = ClockSelectInterface(
                FFADO_DBUS_SERVER,
                FFADO_DBUS_BASEPATH + "/DeviceManager/" + path)
            samplerateselect = SamplerateSelectInterface(
                FFADO_DBUS_SERVER,
                FFADO_DBUS_BASEPATH + "/DeviceManager/" + path)
            nickname = TextInterface(
                FFADO_DBUS_SERVER, FFADO_DBUS_BASEPATH + "/DeviceManager/" +
                path + "/Generic/Nickname")

            #
            # Generic elements for all mixers follow here:
            #
            tmp = GlobalMixer(w)
            tmp.configrom = cfgrom
            tmp.clockselect = clockselect
            tmp.samplerateselect = samplerateselect
            tmp.nickname = nickname
            tmp.hw = hw
            tmp.initValues()
            l.addWidget(tmp, 1)

            #
            # Line to separate
            #
            l.addWidget(HLine(w))

            #
            # Specific (or dummy) mixer widgets get loaded in the following
            #
            if dev != None:
                mixerapp = dev[1]
                exec("mixerwidget = " + mixerapp + "( w )")
            else:
                mixerwidget = DummyMixer(w)
                mixerapp = modelName + " (Dummy)"

            #
            # The same for all mixers
            #
            l.addWidget(mixerwidget, 10)
            mixerwidget.configrom = cfgrom
            mixerwidget.clockselect = clockselect
            mixerwidget.samplerateselect = samplerateselect
            mixerwidget.nickname = nickname
            mixerwidget.hw = hw
            if 'buildMixer' in dir(mixerwidget):
                mixerwidget.buildMixer()
            if 'initValues' in dir(mixerwidget):
                mixerwidget.initValues()
            if 'getDisplayTitle' in dir(mixerwidget):
                title = mixerwidget.getDisplayTitle()
            else:
                title = mixerapp

            self.tabs.addTab(w, title)
            self.panels[guid] = w

        # if there is no panel, add the no-device message
        # else make sure it is not present
        if self.count() == 0:
            self.tabs.hide()
            self.tabs.setEnabled(False)
            self.status.lblMessage.setText("No supported device found.")
            self.status.show()
        else:
            self.tabs.show()
            self.tabs.setEnabled(True)
            self.status.hide()
            if use_generic:
                #
                # Show the generic (development) mixer if it is available
                #
                w = GenericMixer(devmgr.bus, FFADO_DBUS_SERVER, mw)
                self.tabs.addTab(w, "Generic Mixer")
                self.panels[GUID_GENERIC_MIXER] = w
    def setupUi(self):
        self.labels = {}
        self.widgets = {}
        self.checkBoxes = {}
        self.showAdvanced = False
        self.valueItems = {}
        self.dependentItems = {}
        self.resize(650, 450)
        self.buttonBox = QDialogButtonBox()
        self.buttonBox.setOrientation(Qt.Horizontal)
        self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel
                                          | QDialogButtonBox.Ok)
        tooltips = self._alg.getParameterDescriptions()
        self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.verticalLayout = QVBoxLayout()
        self.verticalLayout.setSpacing(5)
        self.verticalLayout.setMargin(20)

        hLayout = QHBoxLayout()
        hLayout.setSpacing(5)
        hLayout.setMargin(0)
        descriptionLabel = QLabel(self.tr("Description"))
        self.descriptionBox = QLineEdit()
        self.descriptionBox.setText(self._alg.name)
        hLayout.addWidget(descriptionLabel)
        hLayout.addWidget(self.descriptionBox)
        self.verticalLayout.addLayout(hLayout)
        line = QFrame()
        line.setFrameShape(QFrame.HLine)
        line.setFrameShadow(QFrame.Sunken)
        self.verticalLayout.addWidget(line)

        for param in self._alg.parameters:
            if param.isAdvanced:
                self.advancedButton = QPushButton()
                self.advancedButton.setText(
                    self.tr('Show advanced parameters'))
                self.advancedButton.setMaximumWidth(150)
                self.advancedButton.clicked.connect(
                    self.showAdvancedParametersClicked)
                self.verticalLayout.addWidget(self.advancedButton)
                break
        for param in self._alg.parameters:
            if param.hidden:
                continue
            desc = param.description
            if isinstance(param, ParameterExtent):
                desc += '(xmin, xmax, ymin, ymax)'
            label = QLabel(desc)
            self.labels[param.name] = label
            widget = self.getWidgetFromParameter(param)
            self.valueItems[param.name] = widget
            if param.name in tooltips.keys():
                tooltip = tooltips[param.name]
            else:
                tooltip = param.description
            label.setToolTip(tooltip)
            widget.setToolTip(tooltip)
            if param.isAdvanced:
                label.setVisible(self.showAdvanced)
                widget.setVisible(self.showAdvanced)
                self.widgets[param.name] = widget
            self.verticalLayout.addWidget(label)
            self.verticalLayout.addWidget(widget)

        for output in self._alg.outputs:
            if output.hidden:
                continue
            if isinstance(output, (OutputRaster, OutputVector, OutputTable,
                                   OutputHTML, OutputFile, OutputDirectory)):
                label = QLabel(output.description + '<' +
                               output.__class__.__name__ + '>')
                item = QLineEdit()
                if hasattr(item, 'setPlaceholderText'):
                    item.setPlaceholderText(ModelerParametersDialog.ENTER_NAME)
                self.verticalLayout.addWidget(label)
                self.verticalLayout.addWidget(item)
                self.valueItems[output.name] = item

        label = QLabel(' ')
        self.verticalLayout.addWidget(label)
        label = QLabel(self.tr('Parent algorithms'))
        self.dependenciesPanel = self.getDependenciesPanel()
        self.verticalLayout.addWidget(label)
        self.verticalLayout.addWidget(self.dependenciesPanel)

        self.verticalLayout.addStretch(1000)
        self.setLayout(self.verticalLayout)

        self.setPreviousValues()
        self.setWindowTitle(self._alg.name)
        self.verticalLayout2 = QVBoxLayout()
        self.verticalLayout2.setSpacing(2)
        self.verticalLayout2.setMargin(0)
        self.tabWidget = QTabWidget()
        self.tabWidget.setMinimumWidth(300)
        self.paramPanel = QWidget()
        self.paramPanel.setLayout(self.verticalLayout)
        self.scrollArea = QScrollArea()
        self.scrollArea.setWidget(self.paramPanel)
        self.scrollArea.setWidgetResizable(True)
        self.tabWidget.addTab(self.scrollArea, self.tr('Parameters'))
        self.webView = QWebView()

        html = None
        url = None
        isText, help = self._alg.help()
        if help is not None:
            if isText:
                html = help
            else:
                url = QUrl(help)
        else:
            html = self.tr('<h2>Sorry, no help is available for this '
                           'algorithm.</h2>')
        try:
            if html:
                self.webView.setHtml(html)
            elif url:
                self.webView.load(url)
        except:
            self.webView.setHtml(
                self.tr('<h2>Could not open help file :-( </h2>'))
        self.tabWidget.addTab(self.webView, 'Help')
        self.verticalLayout2.addWidget(self.tabWidget)
        self.verticalLayout2.addWidget(self.buttonBox)
        self.setLayout(self.verticalLayout2)
        self.buttonBox.accepted.connect(self.okPressed)
        self.buttonBox.rejected.connect(self.cancelPressed)
        QMetaObject.connectSlotsByName(self)
class ProjectProperties(QDialog):
    """Project Properties widget class"""
    def __init__(self, project, parent=None):
        super(ProjectProperties, self).__init__(parent, Qt.Dialog)
        self.parent = parent
        self.project = project
        self.setWindowTitle(translations.TR_PROJECT_PROPERTIES)
        self.resize(600, 500)
        vbox = QVBoxLayout(self)
        self.tab_widget = QTabWidget()
        self.projectData = ProjectData(self)
        self.projectExecution = ProjectExecution(self)
        self.projectMetadata = ProjectMetadata(self)
        self.tab_widget.addTab(self.projectData, translations.TR_PROJECT_DATA)
        self.tab_widget.addTab(self.projectExecution,
                               translations.TR_PROJECT_EXECUTION)
        self.tab_widget.addTab(self.projectMetadata,
                               translations.TR_PROJECT_METADATA)

        vbox.addWidget(self.tab_widget)
        self.btnSave = QPushButton(translations.TR_SAVE)
        self.btnCancel = QPushButton(translations.TR_CANCEL)
        hbox = QHBoxLayout()
        hbox.addWidget(self.btnCancel)
        hbox.addWidget(self.btnSave)

        vbox.addLayout(hbox)

        self.connect(self.btnCancel, SIGNAL("clicked()"), self.close)
        self.connect(self.btnSave, SIGNAL("clicked()"), self.save_properties)

    def save_properties(self):
        """Show warning message if Project Name is empty"""
        if not len(self.projectData.name.text().strip()):
            QMessageBox.critical(self, translations.TR_PROJECT_SAVE_INVALID,
                                 translations.TR_PROJECT_INVALID_MESSAGE)
            return

        self.project.name = self.projectData.name.text()
        self.project.description = self.projectData.description.toPlainText()
        self.project.license = self.projectData.cboLicense.currentText()
        self.project.main_file = self.projectExecution.path.text()
        self.project.url = self.projectData.url.text()
        self.project.project_type = self.projectData.txtType.text()
        # FIXME
        self.project.python_exec = \
            self.projectExecution.txtPythonInterpreter.text()
        self.project.python_path = \
            self.projectExecution.txtPythonPath.toPlainText()
        self.project.additional_builtins = [
            e for e in self.projectExecution.additional_builtins.text().split(
                ' ') if e
        ]
        self.project.pre_exec_script = self.projectExecution.txtPreExec.text()
        self.project.post_exec_script = self.projectExecution.txtPostExec.text(
        )
        self.project.program_params = self.projectExecution.txtParams.text()
        self.project.venv = self.projectExecution.txtVenvPath.text()
        extensions = self.projectData.txtExtensions.text().split(', ')
        self.project.extensions = tuple(extensions)
        self.project.indentation = self.projectData.spinIndentation.value()
        self.project.use_tabs = bool(
            self.projectData.checkUseTabs.currentIndex())
        related = self.projectMetadata.txt_projects.toPlainText()
        related = [
            _path for _path in related.split('\n') if len(_path.strip())
        ]
        self.project.related_projects = related
        self.project.save_project_properties()

        self.parent.refresh_file_filters()

        self.close()