class BaseFenetrePrinc(QMainWindow):
    """ Classe BaseFenetrePrinc

    Cette classe définit les widgets contenus dans la fenetre principale de
    PyFt. Elle est héritée par fen.FenetrePrinc.
    """

    def __init__(self, parent=None):
        """ Fait des initialisations """
        super(BaseFenetrePrinc, self).__init__(parent)
        self.resize(800, 600)
        self.setWindowTitle('PyFt - 0.1')

        # barre de menu
        self.menuBar = QMenuBar()
        self.mFic = QMenu('Fichier')

        self.a_quit = QAction('Quitter', self)

        self.menuBar.addMenu(self.mFic)
        self.setMenuBar(self.menuBar)

        # zone centrale
        self.mdi = QMdiArea()
        self.setCentralWidget(self.mdi)
Esempio n. 2
0
    def menuUi(self):
        extractQuit = QAction(self) 
        extractQuit.setStatusTip('File')
          
        mainMenu = QMenuBar()
        
        fileMenu = mainMenu.addMenu('&File')
        exitMenu = QAction('&Exit', self)
        exitMenu.setShortcut('CTRL+Q')
        exitMenu.setStatusTip('Close Dialog')
        #exitMenu.triggered.connect(self.lunchUnitForm)
        fileMenu.addAction(exitMenu)
    
        printMenu = mainMenu.addMenu('&Print')
        printPrevMenu = QAction('&Print Preview', self)
        printPrevMenu.setShortcut('CTRL+P')
        printPrevMenu.setStatusTip('Print Preview')
        printPrevMenu.triggered.connect(self.lunchPrintForm)
        printMenu.addAction(printPrevMenu)
    
        printPDF = QAction('&Print PDF', self)
        printPDF.setShortcut('CTRL+D')
        printPDF.setStatusTip('PDF')
        printPDF.triggered.connect(self.lunchPrintPdf)
        printMenu.addAction(printPDF)

        printEXCEL = QAction('&Print EXCEL', self)
        printEXCEL.setShortcut('CTRL+E')
        printEXCEL.setStatusTip('EXCEL')
        printEXCEL.triggered.connect(self.lunchPrintExcel)
        printMenu.addAction(printEXCEL)
        
        printCSV = QAction('&Print CSV', self)
        printCSV.setShortcut('CTRL+C')
        printCSV.setStatusTip('PDF')
        printCSV.triggered.connect(self.lunchPrintCsv)
        printMenu.addAction(printCSV)
        
        selMenu = mainMenu.addMenu('Column Visibility')
        self.hold = {}
        for a in self.header:
            d =  QAction(self.header[a], self, checkable = True)
            d.changed.connect(lambda:self.loadPage())
            self.hold[a] = d
            if a in self.columns:
               d.setChecked(True)
            selMenu.addAction(d)
            
        return mainMenu
Esempio n. 3
0
def menubar():
    """Return a newly created parent-less menu bar that's used when there is no main window."""
    m = QMenuBar()
    m.addMenu(menu_file(m))
    m.addMenu(menu_edit(m))
    m.addMenu(menu_window(m))
    m.addMenu(menu_sessions(m))
    m.addMenu(menu_help(m))
    return m
Esempio n. 4
0
def menubar():
    """Return a newly created parent-less menu bar that's used when there is no main window."""
    m = QMenuBar()
    m.addMenu(menu_file(m))
    m.addMenu(menu_edit(m))
    m.addMenu(menu_window(m))
    m.addMenu(menu_sessions(m))
    m.addMenu(menu_help(m))
    return m
Esempio n. 5
0
    def __init__(self, config):
        # Initialize the object as a QWidget and
        # set its title and minimum width

        QWidget.__init__(self)

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

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

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

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

        layout = QVBoxLayout()
        layout.setContentsMargins(QMargins(0, 0, 0, 0))
        self.setLayout(layout)
        
        statusBar = QStatusBar()
        statusBar.showMessage('Ready')
        
        layout.addWidget(menubar)
        layout.addWidget(self.peerList)
        layout.addWidget(statusBar)
Esempio n. 6
0
    def create_menu_bar ( self, parent, controller = None ):
        """ Creates a menu bar representation of the manager.
        """
        # If a controller is required it can either be set as a facet on the
        # menu bar manager (the facet is part of the 'ActionManager' API), or
        # passed in here (if one is passed in here it takes precedence over the
        # facet).
        if controller is None:
            controller = self.controller

        menu_bar = QMenuBar( parent )

        # Every item in every group must be a menu manager:
        for group in self.groups:
            for item in group.items:
                menu = item.create_menu( parent, controller )
                menu.menuAction().setText( item.name )
                menu_bar.addMenu( menu )

        return menu_bar

#-- EOF ------------------------------------------------------------------------
Esempio n. 7
0
 def initMenuBar(self):
     menuBar = QMenuBar()
     file = menuBar.addMenu("&File")
     quit = file.addAction("&Quit", QApplication.instance().quit)
     quit.setShortcutContext(Qt.ApplicationShortcut)
     quit.setShortcut(QKeySequence.Quit)
     self.changeName = QAction("Change Name", self, triggered=self.__changeName)
     self.changeColor = QAction("Change Color", self, triggered=self.__changeColor)
     self.cashCards = QAction("Cash in Cards", self, enabled=False, triggered=self.__cashCards)
     self.endAttack = QAction("End Attack", self, enabled=False, triggered=self.endAttackReleased)
     self.endTurn = QAction("End Turn", self, enabled=False, triggered=self.endTurnReleased)
     menuBar.addAction(self.changeName)
     menuBar.addAction(self.changeColor)
     menuBar.addAction(self.cashCards)
     menuBar.addAction(self.endAttack)
     menuBar.addAction(self.endTurn)
     self.setMenuBar(menuBar)
Esempio n. 8
0
class MainWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        
        self.menubar = QMenuBar()
        file_ = self.menubar.addMenu(u"&Fichier")
        exit = QAction(u"Quitter", self)
        exit.setShortcut("Ctrl+Q")
        exit.setToolTip("Quitter l'application")
        self.menubar.connect(exit, SIGNAL("triggered()"), \
                                         self, \
                                         SLOT("close()"))

        file_.addAction(exit)
        self.setMenuBar(self.menubar)
        self.web = QWebView()
        self.web.load(QUrl(APP_URL))
        self.setCentralWidget(self.web)
    
    def goto(self, url):
        self.web.load(QUrl(url))
Esempio n. 9
0
class LoginView(QDialog,View):
	_mainLayout_ = None

	#We put all widgets in container widgets,
	#If we add all of them to layouts by themselves we get Bus error
	#when doing mainLayout.addLayout()
	_usernameWidget_ = None
	_passWidget_ = None
	_rememberWidget_ = None
	_buttonsWidget_ = None
	
	_logoLabel_ = None
	_usernameLabel_ = None
	_passwordLabel_ = None
	_usernameLineEdit_ = None
	_passwordLineEdit_ = None
	_rememberCheckbox_ = None
	_registerButton_ = None
	_loginButton_ = None
	_myBloopSiteLink_ = None #QLabel
	_movieWaiting_ = None #Gotta keep a refernce to the .GIF, otherwise it won't send signals to the QLabel
	
	_controller_ = None
	_menuBar_ = None
		
	def __init__(self, parent=None):
		'''
		Initializes all components in the dialog.
		Whoever uses this view, and its controller,
		must letter bind the controller and the view
		using view.setController(c)
		
		The controller then will be able to access
		all the view elements with the getters
		defined in this dummy view class.
		
		The controller can also connect to events
		triggered by this dialog.
		'''
		QDialog.__init__(self)
		View.__init__(self)
		#self.createMenubar()
		#set up the fields
		
		self.setWindowTitle(i18n.LABEL_WINDOW_LOGIN_TITLE)
		imagePath = os.path.join("i18n","images","us_en") 
		self.setWindowIcon(QIcon(os.path.join(imagePath,"bloop.png")))		
		
		#Blooploader Logo
		pixmap = QPixmap(os.path.join('i18n','images','us_en','login_logo.png'))
		assert(not pixmap.isNull())
		self._logoLabel_ = QLabel()
		self._logoLabel_.setPixmap(pixmap)
		
		#login row
		self._usernameLabel_ = QLabel(i18n.LABEL_USERNAME)
		self._usernameLineEdit_ = QLineEdit()
		self._usernameWidget_ = PairedWidget(self._usernameLabel_, self._usernameLineEdit_)

		#password row
		self._passwordLabel_ = QLabel(i18n.LABEL_PASSWORD)
		self._passwordLineEdit_ = QLineEdit()
		self._passwordLineEdit_.setEchoMode(QLineEdit.Password)
		self._passWidget_ = PairedWidget(self._passwordLabel_, self._passwordLineEdit_)
		
		#remember me row
		self._rememberCheckbox_ = QCheckBox(i18n.LABEL_REMEMBER_ME)
		self._rememberWidget_= QWidget() 
		rememberLayout = QHBoxLayout()
		rememberLayout.addStretch()
		rememberLayout.addWidget(self._rememberCheckbox_)
		self._rememberWidget_.setLayout(rememberLayout)
		
		#buttons
		self._loginButton_ = QPushButton(i18n.LABEL_LOGIN)
		self._buttonsWidget_ = QHBoxLayout()
		self._buttonsWidget_.addStretch()
		self._buttonsWidget_.addWidget(self._loginButton_)

		#MyBloop.com Link at the end
		self._myBloopSiteLink_ = QLabel('<a href="http://www.mybloop.com">www.mybloop.com</a>')
		myBloopSiteLinkLayout = QHBoxLayout()
		myBloopSiteLinkLayout.addStretch()
		myBloopSiteLinkLayout.addWidget(self._myBloopSiteLink_)
		myBloopSiteLinkLayout.addStretch()
		
		#Stack em up vertically
		self._mainLayout_ = QVBoxLayout()
		self._mainLayout_.addStretch()
		self._mainLayout_.addWidget(self._logoLabel_,0,Qt.AlignCenter)
		self._mainLayout_.addWidget(self._usernameWidget_)
		self._mainLayout_.addWidget(self._passWidget_)
		self._mainLayout_.addWidget(self._rememberWidget_)
		self._mainLayout_.addLayout(self._buttonsWidget_)
		self._mainLayout_.addLayout(myBloopSiteLinkLayout)
		self._mainLayout_.addStretch()
		
		#Add another layout to show while we wait
		#put all this on a QStackedLayout
		self._passwordLineEdit_.setStyleSheet("border-style: outset; border-width: 1px; border-radius: 3px; border-color: gray; padding: 3px;")
		self._usernameLineEdit_.setStyleSheet("border-style: outset; border-width: 1px; border-radius: 3px; border-color: gray; padding: 3px;")
		self._waitLayout_ = QVBoxLayout()
		self._waitLayout_.setAlignment(Qt.AlignHCenter)

		self._waitLabel_ = QLabel()
		pixmap = QPixmap(os.path.join('i18n','images','us_en','loading.png'))
		self._waitLabel_.setPixmap(pixmap)
		self._waitLayout_.addWidget(self._waitLabel_)
		self._waitLayout_.addStretch()

		self._stackedLayout_ = QStackedLayout()

		waitWidget = QWidget()
		waitWidget.setLayout(self._waitLayout_)

		mainWidget = QWidget()
		mainWidget.setLayout(self._mainLayout_)

		self._stackedLayout_.addWidget(mainWidget)
		self._stackedLayout_.addWidget(waitWidget)

		self._stackedLayout_.setCurrentIndex(0) #main layout

		self.fillBackground()
		loginLayout = QVBoxLayout()
		loginLayout.addLayout(self._stackedLayout_)
		self.setLayout(loginLayout)

	def getLineEditUsername(self):
		return self._usernameLineEdit_
	
	def getLineEditPassword(self):
		return self._passwordLineEdit_

	def getUsernameLabel(self):
		return self._usernameLabel_

	def getPasswordLabel(self):
		return self._passwordLabel_
	
	def getButtonLogin(self):
		return self._loginButton_
	
	def getButtonRegister(self):
		return self._registerButton_
	
	def getLabelMyBloopSiteLink(self):
		'''Returns a QLabel object. 
		This QLabel contains one or more links to MyBloop.com pages.
		It's the responsability of the controller to catch the linkActivated(QString)
		signal to open a browser for the user. The String passed contains the URL'''
		return self._myBloopSiteLink_
	
	def getRememberCheckbox(self):
		return self._rememberCheckbox_
	
	def wantsToBeRemembered(self):
		return self._rememberCheckbox_.checkState() == Qt.Checked
	
	def fillBackground(self):
		"""Fills the background with a solid white"""
		self.palette().setColor(QPalette.Background, QColor(255,255,255))
		self.setAutoFillBackground(True)
		
	def showForm(self):
		self._stackedLayout_.setCurrentIndex(0)
		
	def showWaiting(self):
		self._stackedLayout_.setCurrentIndex(1)

	def createMenubar(self):
		self._menuBar_ = QMenuBar(None)
		
		#Create File Menu
		self._fileMenu_ = QMenu(self)
		am = ActionManager.getInstance()
        #todo add actions from ActionManager
		for action in am.getBloopFileMenuActions():
		    print "MainView.createMenuBar() adding action to file menu", action
		    print self._fileMenu_.addAction(action)
        
		#Create Help Menu
		self._menuBar_.addMenu(self._fileMenu_)
		
		#self.setMenuWidget(self._menuBar_)
		#self._menuBar_.setVisible(True)
Esempio n. 10
0
class MainWindow(QMainWindow):
    """
    class MainWindow for the gui
    """

    def __init__(self, config, parent=None):
        """
        Constructor for class MainWindow
        :rtype : object
        :param parent: 
        @param config: iHike configuration
        """
        QMainWindow.__init__(self)
        self.config = config
        self.setGeometry(
            self.config.settings['app_x'],
            self.config.settings['app_y'],
            self.config.settings['app_w'],
            self.config.settings['app_h']
        )
        self.setWindowTitle(
            self.config.settings['appname'] +
            ' - Version: ' +
            self.config.settings['appversion']
        )
        globalFont = QFont(
            self.config.settings['fontfamily'],
            self.config.settings['pointsize']
        )
        self.statusbar = self.statusBar()
        self.center()

        self.exit = QAction('Quit iHike', self)
        self.menuLoadFile = QAction('Load File...', self)

        self.menubar = QMenuBar(None)
        self.file = self.menubar.addMenu('&File')
        self.file.addAction(self.exit)
        self.file.addAction(self.menuLoadFile)
        self.setMenuBar(self.menubar)

        self.save = QAction(QIcon('rsc/icons/fileSave.png'),
            'Save current page', self)
        self.save.setShortcut('Ctrl+S')
        self.save.setDisabled(True)
        self.search = QAction(QIcon('rsc/icons/magfit.png'), 'Search for',
            self)

        self.toolbar = self.addToolBar('Toolbar')
        self.toolbar.addAction(self.save)
        self.toolbar.addSeparator()
        self.toolbar.addAction(self.search)
        self.toolbar.setMaximumHeight(24)

        self.trackListView = TrackListView()
        self.trackListView.setAllowedAreas(Qt.TopDockWidgetArea |
                                           Qt.BottomDockWidgetArea)
        self.addDockWidget(Qt.TopDockWidgetArea, self.trackListView)
        detailView = DetailView()
        detailView.setAllowedAreas(
            Qt.LeftDockWidgetArea | Qt.RightDockWidgetArea)
        self.addDockWidget(Qt.RightDockWidgetArea, detailView)

        self.mainWidget = QWidget(self)
        # self.mainWidget.setLayout(self.gridLayout)
        self.setCentralWidget(self.mainWidget)

    def center(self):
        screen = QDesktopWidget().screenGeometry()
        size = self.geometry()
        self.move((screen.width() - size.width()) / 2,
            (screen.height() - size.height()) / 2)
Esempio n. 11
0
class MainWindow(QMainWindow):
    subWindows = []
    def __init__(self, parent=None):
        QMainWindow.__init__(self, parent)

        self.setWindowTitle("Seabiscuit2")

        self.menuBar = QMenuBar()
        self.setMenuBar(self.menuBar)

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

        self.newWindowAction = QAction("&New Window", self)
        self.newWindowAction.setShortcut("Ctrl+N")
        self.newWindowAction.triggered.connect(self.newWindow)
        self.fileMenu.addAction(self.newWindowAction)

        self.editMenu = QMenu("&Edit")
        self.menuBar.addMenu(self.editMenu)

        self.toolsMenu = QMenu("&Tools")
        self.menuBar.addMenu(self.toolsMenu)

        self.historyAction = QAction("View &History", self)
        self.historyAction.setShortcut("Ctrl+H")
        self.historyAction.triggered.connect(self.loadHistory)
        self.toolsMenu.addAction(self.historyAction)

        self.clearHistoryAction = QAction("&Clear History", self)
        self.clearHistoryAction.setShortcut("Ctrl+Shift+Del")
        self.clearHistoryAction.triggered.connect(self.clearHistory)
        self.toolsMenu.addAction(self.clearHistoryAction)

        self.helpMenu = QMenu("&Help")
        self.menuBar.addMenu(self.helpMenu)

        self.readmeAction = QAction("View &README", self)
        self.readmeAction.setShortcut("F1")
        self.readmeAction.triggered.connect(self.loadReadme)
        self.helpMenu.addAction(self.readmeAction)

        self.aboutAction = QAction("&About Seabiscuit2", self)
        self.aboutAction.setShortcut("F2")
        self.aboutAction.triggered.connect(lambda: self.render("Seabiscuit version " + version + " (running on " + platform + ")"))
        self.helpMenu.addAction(self.aboutAction)

        self.toolBar = QToolBar()
        self.toolBar.setMovable(False)
        self.toolBar.setContextMenuPolicy(Qt.CustomContextMenu)
        self.addToolBar(self.toolBar)

        self.wv = QWebView()

        self.backAction = self.wv.pageAction(QWebPage.Back)
        self.backAction.setEnabled(True)
        self.backAction.setShortcut("Alt+Left")
        self.backAction.triggered.connect(lambda: self.mdiArea.currentSubWindow().widget().back())
        self.toolBar.addAction(self.backAction)

        self.forwardAction = self.wv.pageAction(QWebPage.Forward)
        self.forwardAction.setEnabled(True)
        self.forwardAction.setShortcut("Alt+Right")
        self.forwardAction.triggered.connect(lambda: self.mdiArea.currentSubWindow().widget().forward())
        self.toolBar.addAction(self.forwardAction)

        self.reloadAction = self.wv.pageAction(QWebPage.Reload)
        self.reloadAction.setShortcuts(["F5", "Ctrl+R"])
        self.reloadAction.triggered.connect(lambda: self.mdiArea.currentSubWindow().widget().reload())
        self.toolBar.addAction(self.reloadAction)

        self.locationBar = QLineEdit()
        self.locationBar.returnPressed.connect(self.loadCommand)
        self.toolBar.addWidget(self.locationBar)

        self.focusLocationBarAction = QAction(self)
        self.focusLocationBarAction.setShortcuts(["Ctrl+L", "Alt+D"])
        self.focusLocationBarAction.triggered.connect(self.locationBar.setFocus)
        self.focusLocationBarAction.triggered.connect(self.locationBar.selectAll)
        self.addAction(self.focusLocationBarAction)

        self.mdiArea = QMdiArea()
        self.setCentralWidget(self.mdiArea)

    def newWindow(self):
        s = SWebView(self)
        self.subWindows.append(s)
        self.mdiArea.addSubWindow(s)
        s.activateWindow()
        s.show()
        return s

    def loadHistory(self):
        self.newWindow()
        self.updateWeb(os.path.join(seabiscuit_home, "history.html"))

    def loadReadme(self):
        self.newWindow()
        self.updateWeb("file://" + os.path.join(sys.path[0], "README.html"))

    def closeEvent(self, ev):
        confirm = yes_no_question("Query", "Are you sure you want to quit?")
        if confirm:
            ev.accept()
            sys.exit()
        else:
            ev.ignore()

    def render(self, text):
        QMessageBox.question(None, "Seabiscuit2 says...", text.replace("\n", "<br>"))

    def updateWeb(self, url=None):
        if url != None:
            self.mdiArea.currentSubWindow().widget().load(QUrl.fromUserInput(url))

    def clearHistory(self):
        confirm = yes_no_question("Query", "Are you sure you want to clear the browser history?")
        if confirm:
            historyfile = open(os.path.join(seabiscuit_home, "history.html"), "w")
            historyfile.write("<html><head><script type='text/javascript'>function breakPage(url) {top.location = url}</script></head><body style=\"color: black; background: white;\"><h2>Browsing History</h2>\n")
            historyfile.close()

    def loadCommand(self):
        command = unicode(self.locationBar.text())
        if command.lower().startswith("browser:"):
            command = command.replace("browser:", "")
            webbrowser.open(command)
            self.render("The page has been loaded in your default Web browser.")
        elif command.lower().startswith("download:"):
            command = command.replace("download:", "")
            location = ""
            while not os.path.exists(location):
                location = unicode(QInputDialog.getText("Query", "Enter a valid folder to save your file under."))
                if not os.path.exists(location):
                    render("Invalid path!")
            os.chdir(location)
            os.system("wget '" + command + "'")
            os.chdir(path[0])
        else:
            self.updateWeb(command)
Esempio n. 12
0
    def menuUi(self):
        extractQuit = QAction(self)
        extractQuit.setStatusTip('File')

        mainMenu = QMenuBar()

        fileMenu = mainMenu.addMenu('&File')
        exitMenu = QAction('&Exit', self)
        exitMenu.setShortcut('CTRL+Q')
        exitMenu.setStatusTip('Close Dialog')
        exitMenu.triggered.connect(self.lunchUnitForm)
        fileMenu.addAction(exitMenu)

        #settings menu
        ViewMenu = mainMenu.addMenu('&Veiws')
        ## student menu static items
        bioMenu = QAction('Biodata', self)
        bioMenu.setStatusTip('Bio and Contact data')
        bioMenu.triggered.connect(
            lambda state, x=1, y='k': self.lunchReport(x, y))
        ViewMenu.addAction(bioMenu)

        academicMenu = ViewMenu.addMenu('Academic')
        dumpClass1 = {}
        for k in self.myterms:
            act = str(list(self.myterms[k])[0])
            getResult = self.pullResults(k)
            studs = academicMenu.addMenu(act)
            for w in getResult:
                getRes = w['name'].split(',')
                getDat = w['description'].split(':::')
                if list(self.myterms[k])[1] in getRes:
                    stud = QAction(getDat[0], studs)
                    dumpClass1[k] = stud
                    stud.triggered.connect(lambda state, x=2, term=k, rep=w[
                        'id']: self.lunchReport(x, term, rep))
                    studs.addAction(stud)

        affectiveMenu = ViewMenu.addMenu('Affective')
        dumpClass2 = {}
        for k in self.myterms:
            act = str(self.myterms[k])
            stud = QAction(act, self)
            dumpClass2[k] = stud
            stud.triggered.connect(
                lambda state, x=3, y=k: self.lunchReport(x, y))
            affectiveMenu.addAction(stud)

        psychomotorMenu = ViewMenu.addMenu('Psychomotor')
        dumpClass3 = {}
        for k in self.myterms:
            act = str(self.myterms[k])
            stud = QAction(act, self)
            dumpClass3[k] = stud
            stud.triggered.connect(
                lambda state, x=4, y=k: self.lunchReport(x, y))
            psychomotorMenu.addAction(stud)

        feeMenu = ViewMenu.addMenu('Fees')
        dumpClass4 = {}
        for k in self.myterms:
            act = str(self.myterms[k])
            stud = QAction(act, self)
            dumpClass4[k] = stud
            stud.triggered.connect(
                lambda state, x=5, y=k: self.lunchReport(x, y))
            feeMenu.addAction(stud)

        printMenu = mainMenu.addMenu('&Print')
        exitMenu1 = QAction('&Exit', self)
        exitMenu1.setShortcut('CTRL+Q')
        exitMenu1.setStatusTip('Close Dialog')
        exitMenu1.triggered.connect(lambda state, x=1: self.lunchPrintForm(x))
        printMenu.addAction(exitMenu1)
        #printMenu.triggered.connect(lambda state, x = 1:self.lunchPrintForm(x))

        return mainMenu
Esempio n. 13
0
class RoadnetToolbar(object):
    """
    Toolbar for roadnet
    """
    sb_btn = None
    street_sel_btn = None
    sb_icon = None
    ss_off_icon = None
    ss_on_icon = None

    rn_menu = None
    exp_menu = None
    admin_menu = None
    ramp_menu = None

    mcl_auto_number_btn = None
    mcl_auto_number_on_icon = None
    mcl_auto_number_off_icon = None
    mcl_select_btn = None
    mcl_select_on_icon = None
    mcl_select_off_icon = None
    rdpoly_select_btn = None
    rdpoly_select_on_icon = None
    rdpoly_select_off_icon = None

    start_rn = None
    stop_rn = None
    change_db_path = None
    settings = None
    create_restore = None
    change_pwd = None
    help = None
    exp_lgs = None
    exp_srwr = None
    exp_lsg_shp = None
    exp_maintain_poly = None
    exp_list_roads = None
    meta_menu = None
    edit_lsg_lu = None
    edit_srwr_lu = None
    validation_rpt = None
    street_rpt = None
    clean_rdpoly = None

    load_layers = None
    road_length = None
    export_wdm = None
    ramp_validation = None
    about = None

    def __init__(self, iface, plugin_dir, with_ramp):
        """
        Initial setup of toolbar (pre-login)
        """
        self.iface = iface
        self.plugin_dir = plugin_dir
        self.with_ramp = with_ramp
        self.canvas = self.iface.mapCanvas()
        # Create toolbar
        self.toolbar = self.iface.addToolBar(u'Roadnet')
        self.toolbar.setObjectName(u'Roadnet')

        # Create menubar
        self.menubar = QMenuBar()
        self.define_button_icons_and_actions()
        self.populate_menubar()

        # Add menubar to toolbar
        self.toolbar.addWidget(self.menubar)
        self.toolbar.setIconSize(QSize(100, 100))

        # Set initial state
        self.set_state('init')

    def define_button_icons_and_actions(self):
        # Top level buttons
        # Street Browser button
        self.sb_icon = QIcon(os.path.join(self.plugin_dir, "image", "sb_icon.png"))
        self.sb_btn = QAction(self.sb_icon, "w", self.iface.mainWindow())
        self.sb_btn.setToolTip("Street Browser")
        self.sb_btn.hovered.connect(lambda: self._actionHovered(self.sb_btn))
        # Street selector button
        self.ss_off_icon = QIcon(
                os.path.join(self.plugin_dir, "image", "ss_off_icon.png"))
        self.ss_on_icon = QIcon(
                os.path.join(self.plugin_dir, "image", "ss_on_icon.png"))
        self.street_sel_btn = QAction(self.ss_off_icon, "OFF", self.menubar)
        self.street_sel_btn.setToolTip("Street Selector")
        self.street_sel_btn.hovered.connect(lambda: self._actionHovered(self.street_sel_btn))

        # Setup RAMP buttons if required
        if self.with_ramp:
            self.define_ramp_button_icons_and_actions()

    def define_ramp_button_icons_and_actions(self):
        # Select MCL section button
        self.mcl_select_on_icon = QIcon(os.path.join(self.plugin_dir,
                                                     "image", "edit_mcl_on_icon.png"))
        self.mcl_select_off_icon = QIcon(os.path.join(self.plugin_dir,
                                                      "image", "edit_mcl_off_icon.png"))
        self.mcl_select_btn = QAction(self.mcl_select_off_icon, "",
                                      self.iface.mainWindow())
        self.mcl_select_btn.setToolTip("Select MCL section")
        self.mcl_select_btn.hovered.connect(
            lambda: self._actionHovered(self.mcl_select_btn))

        # MCL auto numbering tool button
        self.mcl_auto_number_on_icon = QIcon(os.path.join(self.plugin_dir,
                                                          "image", "number_mcls_on_icon.png"))
        self.mcl_auto_number_off_icon = QIcon(os.path.join(self.plugin_dir,
                                                           "image", "number_mcls_off_icon.png"))
        self.mcl_auto_number_btn = QAction(self.mcl_auto_number_off_icon, "",
                                           self.iface.mainWindow())
        self.mcl_auto_number_btn.setToolTip("Auto number MCL sections")
        self.mcl_auto_number_btn.hovered.connect(
            lambda: self._actionHovered(self.mcl_auto_number_btn))

        # Select feature button
        self.rdpoly_select_on_icon = QIcon(os.path.join(self.plugin_dir,
                                                   "image", "edit_poly_on_icon.png"))
        self.rdpoly_select_off_icon = QIcon(os.path.join(self.plugin_dir,
                                                      "image", "edit_poly_off_icon.png"))
        self.rdpoly_select_btn = QAction(self.rdpoly_select_off_icon, "",
                                       self.iface.mainWindow())
        self.rdpoly_select_btn.setToolTip("Select RAMP polygon")
        self.rdpoly_select_btn.hovered.connect(
            lambda: self._actionHovered(self.rdpoly_select_btn))

    def populate_menubar(self):
        # Top level menu items + add buttons
        self.rn_menu = self.menubar.addMenu("roadNet")
        self.add_roadnet_menu_items()
        self.menubar.addActions([self.street_sel_btn, self.sb_btn])
        self.exp_menu = self.menubar.addMenu("Export")
        self.add_export_menu_items()
        self.admin_menu = self.menubar.addMenu("Admin")
        self.add_admin_menu_items()
        if self.with_ramp:
            self.ramp_menu = self.menubar.addMenu("RAMP")
            self.add_ramp_menu_items()
            self.menubar.addActions([self.mcl_select_btn,
                                     self.mcl_auto_number_btn,
                                     self.rdpoly_select_btn])

    def add_roadnet_menu_items(self):
        # Add actions to Roadnet menu
        self.start_rn = self.rn_menu.addAction("Start roadNet")
        self.stop_rn = self.rn_menu.addAction("Stop roadNet")
        self.rn_menu.addSeparator()
        self.change_db_path = self.rn_menu.addAction("Change Database Location")
        self.settings = self.rn_menu.addAction("Settings")
        self.rn_menu.addSeparator()
        self.create_restore = self.rn_menu.addAction("Create Restore Point")
        self.change_pwd = self.rn_menu.addAction("Change Password")
        self.rn_menu.addSeparator()
        self.help = self.rn_menu.addAction("Help")
        self.about = self.rn_menu.addAction("About")

    def add_export_menu_items(self):
        # Add actions to Export menu
        self.exp_lgs = self.exp_menu.addAction("Export LSG")
        self.exp_srwr = self.exp_menu.addAction("Export SRWR")
        self.exp_menu.addSeparator()
        self.exp_lsg_shp = self.exp_menu.addAction("Export LSG Shapes")
        self.exp_maintain_poly = self.exp_menu.addAction(
            "Export Maintenance Polygons")
        self.exp_menu.addSeparator()
        self.exp_list_roads = self.exp_menu.addAction("List of Roads")

    def add_admin_menu_items(self):
        """
        Add actions to the admin menu.
        """
        self.meta_menu = self.admin_menu.addAction("Metadata")
        self.admin_menu.addSeparator()
        self.edit_lsg_lu = self.admin_menu.addAction("Edit LSG Lookups")
        self.edit_srwr_lu = self.admin_menu.addAction("Edit SRWR Lookups")
        self.admin_menu.addSeparator()
        self.validation_rpt = self.admin_menu.addAction("Validation Report")
        self.street_rpt = self.admin_menu.addAction("Street Reports")
        self.admin_menu.addSeparator()
        self.clean_rdpoly = self.admin_menu.addAction("Update Symbology")
        self.sb_btn.setEnabled(True)

    def add_ramp_menu_items(self):
        """
        Create actions that appear as items in RAMP menu
        """
        self.load_layers = self.ramp_menu.addAction("Load RAMP/MCL layers")
        self.ramp_menu.addSeparator()
        self.road_length = self.ramp_menu.addAction("Road length report")
        self.export_wdm = self.ramp_menu.addAction("Export for WDM")

    def set_state(self, role):
        """
        Set toolbar state, i.e. which buttons are enabled, based on user
        role.

        :param role: String from ['init', 'editor', 'readonly']
        """
        # Define buttons used in each mode
        roadnet_buttons = [self.start_rn, self.stop_rn, self.create_restore,
                           self.change_db_path, self.change_pwd, self.settings,
                           self.street_sel_btn, self.sb_btn, self.exp_menu,
                           self.admin_menu, self.meta_menu, self.edit_lsg_lu,
                           self.edit_srwr_lu, self.validation_rpt,
                           self.street_rpt, self.help, self.about]
        ramp_buttons = [self.ramp_menu, self.mcl_select_btn,
                        self.mcl_auto_number_btn, self.rdpoly_select_btn]

        init = [self.start_rn, self.change_db_path, self.about, self.help]
        readonly = [self.stop_rn, self.street_sel_btn, self.sb_btn,
                    self.exp_menu, self.admin_menu, self.meta_menu,
                    self.validation_rpt, self.street_rpt, self.settings,
                    self.create_restore, self.help, self.about]

        if self.with_ramp:
            roadnet_buttons += ramp_buttons
            readonly += ramp_buttons

        editor = readonly + [self.create_restore, self.change_pwd,
                             self.edit_lsg_lu, self.edit_srwr_lu]

        # Disable all buttons
        for button in roadnet_buttons:
            button.setEnabled(False)
        # Enable required buttons
        if role == 'init':
            for button in init:
                button.setEnabled(True)
        if role == 'readonly':
            for button in readonly:
                button.setEnabled(True)
        if role == 'editor':
            for button in editor:
                button.setEnabled(True)

    def street_sel_icon_state(self, state):
        """
        Change the text/icon of the street selector button to reflect state
        """
        if state == 'on':
            self.street_sel_btn.setText('on')
            self.street_sel_btn.setIcon(self.ss_on_icon)
        if state == 'off':
            self.street_sel_btn.setText('off')
            self.street_sel_btn.setIcon(self.ss_off_icon)

    def mcl_selector_icon_state(self, state):
        """
        Change the text/icon of the street selector button to reflect state
        """
        if state == 'on':
            self.mcl_select_btn.setText('on')
            self.mcl_select_btn.setIcon(self.mcl_select_on_icon)
        if state == 'off':
            self.mcl_select_btn.setText('off')
            self.mcl_select_btn.setIcon(self.mcl_select_off_icon)

    def rdpoly_selector_icon_state(self, state):
        """
        Change the text/icon of the street selector button to reflect state
        """
        if state == 'on':
            self.rdpoly_select_btn.setText('on')
            self.rdpoly_select_btn.setIcon(self.rdpoly_select_on_icon)
        if state == 'off':
            self.rdpoly_select_btn.setText('off')
            self.rdpoly_select_btn.setIcon(self.rdpoly_select_off_icon)

    def _actionHovered(self, action):
        tip = action.toolTip()
        QToolTip.showText(QCursor.pos(), tip)
# coding: utf-8
from PyQt4.QtGui import QDialog, QMenu, QMenuBar, QVBoxLayout
from qgis.core import QgsColorSchemeRegistry, QgsCustomColorScheme
from qgis.gui import QgsColorSwatchGridAction

new_dialog = QDialog()
main_layout = QVBoxLayout()
menu_bar = QMenuBar()
menu = QMenu(u"Test")

color_scheme_registry = QgsColorSchemeRegistry.instance()
schemes = color_scheme_registry.schemes()
project_scheme = [s for s in schemes if isinstance(s, QgsCustomColorScheme)][0]

color_swatch_grid_action = QgsColorSwatchGridAction(project_scheme, menu)

menu.addAction(color_swatch_grid_action)

menu_bar.addMenu(menu)
main_layout.setMenuBar(menu_bar)
new_dialog.setLayout(main_layout)

new_dialog.show()
Esempio n. 15
0
    def setupMainWindow(self):
        self.resize(800, 600)
        screen = QDesktopWidget().screenGeometry()
        size = self.geometry()
        self.move((screen.width() - size.width()) / 2,
                  (screen.height() - size.height()) / 2)
        self.setWindowTitle('{} - {}'.format(self.settings.notebookName,
                                             __appname__))

        self.viewedList.setFixedHeight(25)
        self.noteSplitter.addWidget(self.notesEdit)
        self.noteSplitter.addWidget(self.notesView)
        mainSplitter = QSplitter(Qt.Vertical)
        mainSplitter.setChildrenCollapsible(False)
        mainSplitter.addWidget(self.viewedList)
        mainSplitter.addWidget(self.noteSplitter)
        mainSplitter.addWidget(self.findBar)
        self.setCentralWidget(mainSplitter)

        self.searchEdit.returnPressed.connect(self.searchNote)
        self.quickNoteNav.returnPressed.connect(self.openFuncWrapper)
        searchLayout = QVBoxLayout()
        searchLayout.addWidget(self.searchEdit)
        searchLayout.addWidget(self.searchView)
        self.searchTab.setLayout(searchLayout)

        indexLayout = QVBoxLayout(self.notesTab)
        indexLayout.addWidget(self.quickNoteNav)
        indexLayout.addWidget(self.notesTree)

        self.dockIndex.setObjectName("Index")
        self.dockIndex.setWidget(self.notesTab)
        self.dockSearch.setObjectName("Search")
        self.dockSearch.setWidget(self.searchTab)
        self.dockToc.setObjectName("TOC")
        self.dockToc.setWidget(self.tocTree)
        self.dockAttachment.setObjectName("Attachment")
        self.dockAttachment.setWidget(self.attachmentView)

        self.setDockOptions(QMainWindow.VerticalTabs)
        self.addDockWidget(Qt.LeftDockWidgetArea, self.dockIndex)
        self.addDockWidget(Qt.LeftDockWidgetArea, self.dockSearch)
        self.addDockWidget(Qt.LeftDockWidgetArea, self.dockToc)
        self.addDockWidget(Qt.LeftDockWidgetArea, self.dockAttachment)
        self.tabifyDockWidget(self.dockIndex, self.dockSearch)
        self.tabifyDockWidget(self.dockSearch, self.dockToc)
        self.tabifyDockWidget(self.dockToc, self.dockAttachment)
        self.setTabPosition(Qt.LeftDockWidgetArea, QTabWidget.North)
        self.dockIndex.raise_()  # Put dockIndex on top of the tab stack

        menuBar = QMenuBar(self)
        self.setMenuBar(menuBar)
        menuFile = menuBar.addMenu(self.tr('&File'))
        menuEdit = menuBar.addMenu(self.tr('&Edit'))
        menuView = menuBar.addMenu(self.tr('&View'))
        menuHelp = menuBar.addMenu(self.tr('&Help'))
        # menuFile
        menuFile.addAction(self.actions['newPage'])
        menuFile.addAction(self.actions['newSubpage'])
        menuFile.addAction(self.actions['NBSettings'])
        menuFile.addAction(self.actions['MDSettings'])
        menuFile.addAction(self.actions['importPage'])
        menuFile.addAction(self.actions['openNotebook'])
        menuFile.addAction(self.actions['reIndex'])
        menuFile.addSeparator()
        menuFile.addAction(self.actions['save'])
        menuFile.addAction(self.actions['saveAs'])
        menuFile.addAction(self.actions['print_'])
        menuExport = menuFile.addMenu(self.tr('&Export'))
        menuExport.addAction(self.actions['html'])
        menuFile.addSeparator()
        menuFile.addAction(self.actions['renamePage'])
        menuFile.addAction(self.actions['delPage'])
        menuFile.addSeparator()
        menuFile.addAction(self.actions['quit'])
        # menuEdit
        menuEdit.addAction(self.actions['undo'])
        menuEdit.addAction(self.actions['redo'])
        menuEdit.addAction(self.actions['findText'])
        menuEdit.addAction(self.actions['findRepl'])
        menuEdit.addSeparator()
        menuEdit.addAction(self.actions['sortLines'])
        menuEdit.addAction(self.actions['insertImage'])
        # menuView
        menuView.addAction(self.actions['edit'])
        menuView.addAction(self.actions['split'])
        menuView.addAction(self.actions['flipEditAndView'])
        menuShowHide = menuView.addMenu(self.tr('Show/Hide'))
        menuShowHide.addAction(self.dockIndex.toggleViewAction())
        menuShowHide.addAction(self.dockSearch.toggleViewAction())
        menuShowHide.addAction(self.dockToc.toggleViewAction())
        menuShowHide.addAction(self.dockAttachment.toggleViewAction())
        #menuMode = menuView.addMenu(self.tr('Mode'))
        #menuMode.addAction(self.actionLeftAndRight)
        #menuMode.addAction(self.actionUpAndDown)
        # menuHelp
        menuHelp.addAction(self.actions['readme'])
        menuHelp.addAction(self.actions['changelog'])
        menuHelp.addAction(self.actions['aboutQt'])

        toolBar = QToolBar(self.tr("toolbar"), self)
        toolBar.setObjectName("toolbar")  # needed in saveState()
        #toolBar.setIconSize(QSize(16, 16))
        toolBar.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)
        self.addToolBar(Qt.TopToolBarArea, toolBar)
        toolBar.addAction(self.actions['edit'])
        toolBar.addAction(self.actions['split'])
        self.findEdit.returnPressed.connect(self.findText)
        self.findBar.addWidget(self.findEdit)
        self.findBar.addWidget(self.checkBox)
        self.findBar.addAction(self.actions['findPrev'])
        self.findBar.addAction(self.actions['find'])
        self.findBar.setVisible(False)
        self.findBar.visibilityChanged.connect(self.findBarVisibilityChanged)

        self.setStatusBar(self.statusBar)
        self.statusBar.addWidget(self.statusLabel, 1)

        self.notesTree.currentItemChanged.connect(
            self.currentItemChangedWrapper)
        self.notesTree.nvwCallback = self.newNoteDisplay
        self.notesTree.nvwtCallback = self.newPlainTextNoteDisplay
        self.tocTree.itemClicked.connect(self.tocNavigate)
        self.notesEdit.textChanged.connect(self.noteEditted)

        self.notesEdit.document().modificationChanged.connect(
            self.modificationChanged)

        self.updateRecentViewedNotes()
        notes = self.settings.recentViewedNotes()
        if len(notes) != 0:
            item = self.notesTree.pageToItem(notes[0])
            self.notesTree.setCurrentItem(item)
Esempio n. 16
0
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)
Esempio n. 17
0
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)
Esempio n. 18
0
class PeakMapExplorer(EmzedDialog):

    def __init__(self, ok_rows_container=[], parent=None):
        super(PeakMapExplorer, self).__init__(parent)
        self.setWindowFlags(Qt.Window)
        # Destroying the C++ object right after closing the dialog box,
        # otherwise it may be garbage-collected in another QThread
        # (e.g. the editor's analysis thread in Spyder), thus leading to
        # a segmentation fault on UNIX or an application crash on Windows
        self.ok_rows = ok_rows_container

        self.setAttribute(Qt.WA_DeleteOnClose)
        self.setWindowFlags(Qt.Window)

        self.gamma = 3.0

        self.last_used_directory_for_load = None
        self.last_used_directory_for_save = None

        self.history = History()

    def keyPressEvent(self, e):
        # avoid closing of dialog when Esc key pressed:
        if e.key() != Qt.Key_Escape:
            return super(PeakMapExplorer, self).keyPressEvent(e)

    def setWindowTitle(self):
        if self.peakmap2 is None:
            title = os.path.basename(self.peakmap.meta.get("source", ""))
        else:
            p1 = os.path.basename(self.peakmap.meta.get("source", ""))
            p2 = os.path.basename(self.peakmap2.meta.get("source", ""))
            title = "yellow=%s, blue=%s" % (p1, p2)
        super(PeakMapExplorer, self).setWindowTitle(title)

    def setup(self, peakmap, peakmap2=None, table=None):
        self.table = table

        def collect_precursor_mz(pm):
            for s in pm:
                if s.precursors:
                    if s.msLevel > 1:
                        yield s.precursors[0][0]

        self.ms_levels = set(peakmap.getMsLevels())
        self.precursor_mz = set(collect_precursor_mz(peakmap))
        if peakmap2 is not None:
            self.ms_levels &= set(peakmap2.getMsLevels())
            self.precursor_mz &= set(collect_precursor_mz(peakmap2))

        self.ms_levels = sorted(self.ms_levels)
        self.precursor_mz = sorted(self.precursor_mz)

        self.setup_table_widgets()
        self.setup_input_widgets()
        self.history_list = QComboBox(self)

        self.setup_ms2_widgets()
        self.full_pm = peakmap
        self.full_pm2 = peakmap2
        self.dual_mode = self.full_pm2 is not None

        self.current_ms_level = self.ms_levels[0]
        self.process_peakmap(self.current_ms_level)
        self.rtmin, self.rtmax, self.mzmin, self.mzmax = get_range(self.peakmap, self.peakmap2)

        self.setup_plot_widgets()
        self.setup_menu_bar()
        self.setup_layout()
        self.connect_signals_and_slots()
        self.setup_initial_values()
        self.plot_peakmap()

    def setup_ms2_widgets(self):
        self.spectra_selector_widget.set_data(self.ms_levels, self.precursor_mz)

    def setup_table_widgets(self):
        if self.table is not None:
            self.table_widget = create_table_widget(self.table, self)
            self.select_all_peaks = QPushButton("Select all peaks", self)
            self.unselect_all_peaks = QPushButton("Unselect all peaks", self)
            self.done_button = QPushButton("Done", self)

    def setup_menu_bar(self):
        self.menu_bar = QMenuBar(self)
        menu = QMenu("Peakmap Explorer", self.menu_bar)
        self.menu_bar.addMenu(menu)
        if not self.dual_mode:
            self.load_action = QAction("Load Peakmap", self)
            self.load_action.setShortcut(QKeySequence("Ctrl+L"))
            self.load_action2 = None
            menu.addAction(self.load_action)
        else:
            self.load_action = QAction("Load Yellow Peakmap", self)
            self.load_action2 = QAction("Load Blue Peakmap", self)
            menu.addAction(self.load_action)
            menu.addAction(self.load_action2)

        self.save_action = QAction("Save selected range as image", self)
        self.save_action.setShortcut(QKeySequence("Ctrl+S"))
        menu.addAction(self.save_action)

        menu = QMenu("Help", self.menu_bar)
        self.help_action = QAction("Help", self)
        self.help_action.setShortcut(QKeySequence("F1"))
        menu.addAction(self.help_action)
        self.menu_bar.addMenu(menu)

    def process_peakmap(self, ms_level, pre_mz_min=None, pre_mz_max=None):

        peakmap = self.full_pm.filter(lambda s: s.msLevel == ms_level)
        if ms_level > 1 and pre_mz_min is not None:
            peakmap = peakmap.filter(lambda s: s.precursors[0][0] >= pre_mz_min)
        if ms_level > 1 and pre_mz_max is not None:
            peakmap = peakmap.filter(lambda s: s.precursors[0][0] <= pre_mz_max)

        if self.full_pm2 is not None:
            peakmap2 = self.full_pm2.filter(lambda s: s.msLevel == ms_level)

        self.peakmap = peakmap
        if self.dual_mode:
            self.peakmap2 = peakmap2
        else:
            self.peakmap2 = None

        for i, msl in enumerate(self.ms_levels):
            if msl == ms_level:
                pass # TODO self.ms_level.setCurrentIndex(i)

        self.setWindowTitle()

    def setup_initial_values(self):

        imax = self.peakmap_plotter.get_total_imax()
        self.image_scaling_widget.set_max_intensity(imax)
        self.image_scaling_widget.set_gamma(self.gamma)

        self.view_range_widget.set_view_range(self.rtmin, self.rtmax, self.mzmin, self.mzmax)

    def setup_input_widgets(self):
        self.image_scaling_widget = ImageScalingWidget(self)
        self.spectra_selector_widget = SpectraSelectorWidget(self)
        self.view_range_widget = ViewRangeWidget(self)

    def setup_plot_widgets(self):
        self.peakmap_plotter = PeakMapPlottingWidget()
        self.peakmap_plotter.set_peakmaps(self.peakmap, self.peakmap2)
        self.eic_plotter = EicPlottingWidget(with_range=False)
        self.mz_plotter = MzPlottingWidget()

        self.peakmap_plotter.set_logarithmic_scale(1)
        self.peakmap_plotter.set_gamma(self.gamma)

        self.eic_plotter.set_overall_range(self.rtmin, self.rtmax)
        self.mz_plotter.set_overall_range(self.mzmin, self.mzmax)


    def setup_layout(self):
        outer_layout = QVBoxLayout()
        outer_layout.addWidget(self.menu_bar)
        outer_layout.setStretch(0, 1)

        h_splitter = QSplitter(self)
        h_splitter.setOrientation(Qt.Horizontal)

        # FIRST COLUMN of h_splitter is chromatogram + peakmap:  ############################

        v_splitter1 = QSplitter(self)
        v_splitter1.setOrientation(Qt.Vertical)
        v_splitter1.addWidget(self.eic_plotter)
        v_splitter1.addWidget(self.peakmap_plotter)
        self.peakmap_plotter.setMinimumSize(250, 200)
        v_splitter1.setStretchFactor(0, 1)
        v_splitter1.setStretchFactor(1, 3)

        h_splitter.addWidget(v_splitter1)
        h_splitter.setStretchFactor(0, 2)

        # SECOND COLUMN of h_splittier holds controlx boxes + mz plot #######################

        v_splitter2 = QSplitter(self)
        v_splitter2.setOrientation(Qt.Vertical)

        v_splitter2.addWidget(self.image_scaling_widget)
        v_splitter2.addWidget(self.spectra_selector_widget)
        v_splitter2.addWidget(self.view_range_widget)
        v_splitter2.addWidget(self.history_list)
        v_splitter2.addWidget(self.mz_plotter)

        v_splitter2.setStretchFactor(0, 0)
        v_splitter2.setStretchFactor(1, 0)
        v_splitter2.setStretchFactor(2, 0)
        v_splitter2.setStretchFactor(3, 0)
        v_splitter2.setStretchFactor(4, 1)

        h_splitter.addWidget(v_splitter2)
        h_splitter.setStretchFactor(1, 1)

        # THIRD COLUMN of h_splittier holds control table + buttons ##########################
        if self.table:
            frame = QFrame(self)
            layout = QVBoxLayout(frame)
            frame.setLayout(layout)
            layout.addWidget(self.table_widget)

            button_row_layout = QHBoxLayout(frame)
            button_row_layout.addWidget(self.select_all_peaks)
            button_row_layout.addWidget(self.unselect_all_peaks)
            button_row_layout.addWidget(self.done_button)

            layout.addLayout(button_row_layout)
            h_splitter.addWidget(frame)
            h_splitter.setStretchFactor(2, 2)

        outer_layout.addWidget(h_splitter)
        self.setLayout(outer_layout)
        outer_layout.setStretch(1, 99)

    def connect_signals_and_slots(self):
        self.image_scaling_widget.USE_LOG_SCALE.connect(self.use_logscale)
        self.image_scaling_widget.GAMMA_CHANGED.connect(self.gamma_changed)

        self.image_scaling_widget.IMIN_CHANGED.connect(self.set_image_min)
        self.image_scaling_widget.IMAX_CHANGED.connect(self.set_image_max)

        self.spectra_selector_widget.MS_LEVEL_CHOSEN.connect(self.ms_level_chosen)
        self.spectra_selector_widget.PRECURSOR_RANGE_CHANGED.connect(self.set_precursor_range)

        self.view_range_widget.RANGE_CHANGED.connect(self.update_image_range)

        self.connect(self.history_list, SIGNAL("activated(int)"), self.history_item_selected)

        if self.dual_mode:
            self.connect(self.load_action, SIGNAL("triggered()"), self.do_load_yellow)
            self.connect(self.load_action2, SIGNAL("triggered()"), self.do_load_blue)
        else:
            self.connect(self.load_action, SIGNAL("triggered()"), self.do_load)
        self.connect(self.save_action, SIGNAL("triggered()"), self.do_save)
        self.connect(self.help_action, SIGNAL("triggered()"), self.show_help)

        self.peakmap_plotter.NEW_IMAGE_LIMITS.connect(self.image_limits_upated_by_user)

        self.peakmap_plotter.KEY_LEFT.connect(self.user_pressed_left_key_in_plot)
        self.peakmap_plotter.KEY_RIGHT.connect(self.user_pressed_right_key_in_plot)
        self.peakmap_plotter.KEY_BACKSPACE.connect(self.user_pressed_backspace_key_in_plot)
        self.peakmap_plotter.KEY_END.connect(self.user_pressed_end_key_in_plot)
        self.peakmap_plotter.CURSOR_MOVED.connect(self.cursor_moved_in_plot)
        self.eic_plotter.CURSOR_MOVED.connect(self.eic_cursor_moved)
        self.eic_plotter.VIEW_RANGE_CHANGED.connect(self.eic_view_range_changed)
        self.mz_plotter.CURSOR_MOVED.connect(self.mz_cursor_moved)
        self.mz_plotter.VIEW_RANGE_CHANGED.connect(self.mz_view_range_changed)

        if self.table is not None:
            self.connect(self.table_widget.verticalHeader(), SIGNAL("sectionClicked(int)"),
                         self.row_selected)
            self.connect(self.table_widget, SIGNAL("itemClicked(QTableWidgetItem*)"),
                         self.cell_clicked)
            self.connect(self.select_all_peaks, SIGNAL("pressed()"),
                         self.select_all_peaks_button_pressed)
            self.connect(self.unselect_all_peaks, SIGNAL("pressed()"),
                         self.unselect_all_peaks_button_pressed)
            self.connect(self.done_button, SIGNAL("pressed()"),
                         self.done_button_pressed)

            def key_release_handler(evt):
                tw = self.table_widget
                active_rows = set(ix.row() for ix in tw.selectionModel().selection().indexes())
                if active_rows:
                    row = active_rows.pop()
                    if evt.key() in (Qt.Key_Up, Qt.Key_Down):
                        tw.selectRow(row)
                        tw.verticalHeader().emit(SIGNAL("sectionClicked(int)"), row)
                        return
                return QTableWidget.keyPressEvent(tw, evt)

            self.table_widget.keyReleaseEvent = key_release_handler

    def cursor_moved_in_plot(self, rt, mz):
        self.eic_plotter.set_cursor_pos(rt)
        self.mz_plotter.set_cursor_pos(mz)

    def eic_cursor_moved(self, rt):
        self.peakmap_plotter.set_cursor_rt(rt)

    def eic_view_range_changed(self, rtmin, rtmax):
        """
        we want to avoid the loop   EIC_RANGE_CHANGED -> VIEW_RANGE_CHANGED -> EIC_RANGE_CHANGED
        and we do not want to fully block emitting of VIEW_RANGE_CHANGED.
        so self.peakmap_plotter.blockSignals() does not work here, instead we "cut" the last
        connection here:
        """
        self.eic_plotter.VIEW_RANGE_CHANGED.disconnect()
        self.peakmap_plotter.blockSignals(True)
        self.peakmap_plotter.set_rt_limits(rtmin, rtmax)
        self.peakmap_plotter.blockSignals(False)
        self.peakmap_plotter.replot()
        self.eic_plotter.VIEW_RANGE_CHANGED.connect(self.eic_view_range_changed)

    def mz_view_range_changed(self, mzmin, mzmax):
        """
        we want to avoid the loop  MZ_RANGE_CHANGED -> VIEW_RANGE_CHANGED -> MZ_RANGE_CHANGED
        and we do not want to fully block emitting of VIEW_RANGE_CHANGED.
        so self.peakmap_plotter.blockSignals() does not work here, instead we "cut" the last
        connection here:
        """
        self.mz_plotter.VIEW_RANGE_CHANGED.disconnect()
        self.peakmap_plotter.blockSignals(True)
        self.peakmap_plotter.set_mz_limits(mzmin, mzmax)
        self.peakmap_plotter.blockSignals(False)
        self.peakmap_plotter.replot()
        self.mz_plotter.VIEW_RANGE_CHANGED.connect(self.mz_view_range_changed)

    def mz_cursor_moved(self, mz):
        self.peakmap_plotter.set_cursor_mz(mz)

    def image_limits_upated_by_user(self, rtmin, rtmax, mzmin, mzmax):
        self.update_peakmap_projection_views(rtmin, rtmax, mzmin, mzmax)
        self.history.new_head((rtmin, rtmax, mzmin, mzmax))
        self.update_history_entries()

    def set_image_min(self, value):
        self.peakmap_plotter.set_imin(value)
        self.peakmap_plotter.replot()

    def set_image_max(self, value):
        self.peakmap_plotter.set_imax(value)
        self.peakmap_plotter.replot()

    def update_peakmap_projection_views(self, rtmin, rtmax, mzmin, mzmax):

        rts, chroma = self.peakmap.chromatogram(mzmin, mzmax)
        self.eic_plotter.del_all_items()
        if self.dual_mode:
            rts2, chroma2 = self.peakmap2.chromatogram(mzmin, mzmax, rtmin, rtmax)
            self.eic_plotter.add_eics([(rts, chroma), (rts2, chroma2)], configs=[blue_line, yellow_line])
        else:
            self.eic_plotter.add_eics([(rts, chroma)], configs=[grey_line])

        self.eic_plotter.shrink_and_replot(rtmin, rtmax)

        if self.dual_mode:
            data = [(self.peakmap, rtmin, rtmax, mzmin, mzmax, 3000),
                    (self.peakmap2, rtmin, rtmax, mzmin, mzmax, 3000)]
            configs = [dict(color="#aaaa00"), dict(color="#0000aa")]
            self.mz_plotter.plot_peakmaps(data, configs)
        else:
            self.mz_plotter.plot_peakmaps([(self.peakmap, rtmin, rtmax, mzmin, mzmax, 3000)])

        self.mz_plotter.shrink_and_replot(mzmin, mzmax)
        self.view_range_widget.set_view_range(rtmin, rtmax, mzmin, mzmax)

    def _handle_history_action(self, action):
        item = action()
        if item is not None:
            self.peakmap_plotter.set_limits_no_sig(*item)
            self.update_peakmap_projection_views(*item)
            self.update_history_entries()

    def user_pressed_left_key_in_plot(self):
        self._handle_history_action(self.history.go_back)

    def user_pressed_right_key_in_plot(self):
        self._handle_history_action(self.history.go_forward)

    def user_pressed_backspace_key_in_plot(self):
        self._handle_history_action(self.history.go_to_beginning)

    def user_pressed_end_key_in_plot(self):
        self._handle_history_action(self.history.go_to_end)

    def history_item_selected(self, index):
        self._handle_history_action(lambda index=index: self.history.set_position(index))

    @protect_signal_handler
    def do_save(self):
        pix = self.peakmap_plotter.paint_pixmap()
        while True:
            path = askForSave(self.last_used_directory_for_save,
                              caption="Save Image",
                              extensions=("png", "PNG")
                              )
            if path is None:
                break
            __, ext = os.path.splitext(path)
            if ext not in (".png", ".PNG"):
                QMessageBox.warning(self, "Warning", "wrong/missing extension '.png'")
            else:
                self.last_used_directory_for_save = os.path.dirname(path)
                pix.save(path)
                break
        return

    def _do_load(self, title, attribute):
        path = askForSingleFile(self.last_used_directory_for_load,
                                caption=title,
                                extensions=("mzML", "mzData", "mzXML")
                                )
        if path is not None:
            setattr(self, attribute, loadPeakMap(path))
            self.process_peakmap()
            self.peakmap_plotter.set_peakmaps(self.peakmap, self.peakmap2)
            self.setup_initial_values()
            self.setWindowTitle()
            self.peakmap_plotter.replot()
            self.plot_peakmap()
            self.last_used_directory_for_load = os.path.dirname(path)

    @protect_signal_handler
    def do_load(self):
        self._do_load("Load Peakmap", "peakmap")

    @protect_signal_handler
    def do_load_yellow(self):
        self._do_load("Load Yellow Peakmap", "peakmap")

    @protect_signal_handler
    def do_load_blue(self):
        self._do_load("Load Blue Peakmap", "peakmap2")

    @protect_signal_handler
    def select_all_peaks_button_pressed(self):
        for row in range(self.table_widget.rowCount()):
            item = self.table_widget.item(row, 0)
            item.setCheckState(Qt.Checked)

    @protect_signal_handler
    def unselect_all_peaks_button_pressed(self):
        for row in range(self.table_widget.rowCount()):
            item = self.table_widget.item(row, 0)
            item.setCheckState(Qt.Unchecked)

    @protect_signal_handler
    def done_button_pressed(self):
        self.ok_rows[:] = [i for i in range(len(self.table))
                           if self.table_widget.item(i, 0).checkState() == Qt.Checked]
        self.accept()

    @protect_signal_handler
    def row_selected(self, row_idx):
        row = self.table.getValues(self.table.rows[row_idx])
        needed = ["rtmin", "rtmax", "mzmin", "mzmax"]
        if all(n in row for n in needed):
            rtmin, rtmax, mzmin, mzmax = [row.get(ni) for ni in needed]
            self.peakmap_plotter.set_limits(rtmin, rtmax, mzmin, mzmax)
        else:
            needed = ["mzmin", "mzmax"]
            if all(n in row for n in needed):
                mzmin, mzmax = [row.get(ni) for ni in needed]
                self.peakmap_plotter.set_limits(self.rtmin, self.rtmax, mzmin, mzmax)

    @protect_signal_handler
    def cell_clicked(self, item):
        row = item.row()
        self.table_widget.selectRow(row)
        self.table_widget.verticalHeader().emit(SIGNAL("sectionClicked(int)"), row)

    @protect_signal_handler
    def show_help(self):
        html = resource_string("emzed.core.explorers", "help_peakmapexplorer.html")
        QWebSettings.globalSettings().setFontFamily(QWebSettings.StandardFont, 'Courier')
        QWebSettings.globalSettings().setFontSize(QWebSettings.DefaultFontSize, 12)
        v = QWebView(self)
        v.setHtml(html)
        dlg = QDialog(self, Qt.Window)
        dlg.setMinimumSize(300, 300)
        l = QVBoxLayout(dlg)
        l.addWidget(v)
        dlg.setLayout(l)
        dlg.show()

    def update_history_entries(self):
        self.history_list.clear()
        for item in self.history.items:
            rtmin, rtmax, mzmin, mzmax = item
            str_item = "%10.5f .. %10.5f %6.2fm...%6.2fm " % (mzmin, mzmax, rtmin / 60.0,
                                                              rtmax / 60.0)
            self.history_list.addItem(str_item)

        self.history_list.setCurrentIndex(self.history.position)

    @protect_signal_handler
    def use_logscale(self, is_log):
        self.peakmap_plotter.set_logarithmic_scale(is_log)
        self.peakmap_plotter.replot()

    @protect_signal_handler
    def ms_level_chosen(self, ms_level):
        if ms_level != self.current_ms_level:
            self.current_ms_level = ms_level
            self.process_peakmap(ms_level)
            self.peakmap_plotter.set_peakmaps(self.peakmap, self.peakmap2)
            self.peakmap_plotter.replot()
            self.plot_peakmap()

    @protect_signal_handler
    def set_precursor_range(self, pre_mz_min, pre_mz_max):
        self.process_peakmap(self.current_ms_level, pre_mz_min, pre_mz_max)
        self.peakmap_plotter.set_peakmaps(self.peakmap, self.peakmap2)
        self.peakmap_plotter.replot()
        self.plot_peakmap()

    @protect_signal_handler
    def gamma_changed(self, value):
        self.peakmap_plotter.set_gamma(value)
        self.peakmap_plotter.replot()

    @protect_signal_handler
    def update_image_range(self, rtmin, rtmax, mzmin, mzmax):

        rtmin *= 60.0
        rtmax *= 60.0

        if rtmin < self.rtmin:
            rtmin = self.rtmin
        if rtmax > self.rtmax:
            rtmax = self.rtmax
        if mzmin < self.mzmin:
            mzmin = self.mzmin
        if mzmax > self.mzmax:
            mzmax = self.mzmax
        rtmin, rtmax = sorted((rtmin, rtmax))
        mzmin, mzmax = sorted((mzmin, mzmax))

        self.peakmap_plotter.set_limits(rtmin, rtmax, mzmin, mzmax)

    def plot_peakmap(self):
        self.peakmap_plotter.set_limits(self.rtmin, self.rtmax, self.mzmin, self.mzmax)
Esempio n. 19
0
File: gui.py Progetto: Zaidos/Pyxie
    def init_widgets(self):

        tabs = QTabWidget(self)
        tab1 = QWidget(self)
        tab2 = QWidget(self)

        menu_bar = QMenuBar(self)
        file_menu = menu_bar.addMenu('&File')

        open = QAction("Exit", self) 
        save = QAction("Save", self) 
        exit = QAction("Quit", self) 

        file_menu.addAction(open)
        file_menu.addAction(save)
        file_menu.addAction(exit)

        stream_labels = ['client ip', 'client port', 
                         'server ip', 'server port',
                         'protocol', 'created']

        # set up the stream tab
        self.streammodel = QStandardItemModel()
        self.streammodel.setHorizontalHeaderLabels(stream_labels)
        
        self.streamtable = StreamTableView(self)
        self.streamtable.setModel(self.streammodel)
        self.streamtable.setSelectionBehavior(QAbstractItemView.SelectRows)
        
        # create textedit area where traffic goes
        self.stream_dump = QTextEdit(self)

        # create buttons
        self.proxy_btn = QPushButton('Proxy Stopped')
        self.proxy_btn.setCheckable(True)
        self.proxy_btn.clicked[bool].connect(self.toggle_proxy)
        
        # add widgets to stream tab
        stream_tab = QVBoxLayout(tab1)
        stream_tab.addWidget(self.proxy_btn)
        stream_tab.addWidget(self.streamtable)
        stream_tab.addWidget(self.stream_dump)

        # create buttons and add them to hbox widget
        intercept_btn = QPushButton('Intercept', self)
        intercept_btn.setCheckable(True)
        intercept_btn.clicked[bool].connect(self.toggle_intercept)

        forward_btn = QPushButton('Forward', self)
        forward_btn.clicked[bool].connect(self.forward_traffic)

        drop_btn = QPushButton('Drop', self)
        drop_btn.clicked[bool].connect(self.drop_traffic)

        intercept_buttons = QHBoxLayout()
        intercept_buttons.addWidget(intercept_btn)
        intercept_buttons.addWidget(forward_btn)
        intercept_buttons.addWidget(drop_btn)

        # create textedit area where traffic goes
        self.intercept_dump = QTextEdit(self)

        # add widgets to stream tab
        intercept_tab = QVBoxLayout(tab2)
        intercept_tab.addLayout(intercept_buttons)
        intercept_tab.addWidget(self.intercept_dump)

        # add tabs to the tabs widget
        tabs.addTab(tab1, "Streams")
        tabs.addTab(tab2, "Intercept")

        main_layout = QVBoxLayout(self)
        main_layout.addWidget(menu_bar)
        main_layout.addWidget(tabs)

        self.setLayout(main_layout)
Esempio n. 20
0
    def setupMainWindow(self):
        self.resize(800, 600)
        screen = QDesktopWidget().screenGeometry()
        size = self.geometry()
        self.move((
            screen.width()-size.width())/2, (screen.height()-size.height())/2)
        self.setWindowTitle(
            '{} - {}'.format(self.settings.notebookName, __appname__))

        self.viewedList.setFixedHeight(25)
        self.noteSplitter.addWidget(self.notesEdit)
        self.noteSplitter.addWidget(self.notesView)
        mainSplitter = QSplitter(Qt.Vertical)
        mainSplitter.setChildrenCollapsible(False)
        mainSplitter.addWidget(self.viewedList)
        mainSplitter.addWidget(self.noteSplitter)
        mainSplitter.addWidget(self.findBar)
        self.setCentralWidget(mainSplitter)

        self.searchEdit.returnPressed.connect(self.searchNote)
        self.quickNoteNav.returnPressed.connect(self.openFuncWrapper)
        searchLayout = QVBoxLayout()
        searchLayout.addWidget(self.searchEdit)
        searchLayout.addWidget(self.searchView)
        self.searchTab.setLayout(searchLayout)
        self.tocTree.header().close()

        indexLayout = QVBoxLayout(self.notesTab)
        indexLayout.addWidget(self.quickNoteNav)
        indexLayout.addWidget(self.notesTree)

        self.dockIndex.setObjectName("Index")
        self.dockIndex.setWidget(self.notesTab)
        self.dockSearch.setObjectName("Search")
        self.dockSearch.setWidget(self.searchTab)
        self.dockToc.setObjectName("TOC")
        self.dockToc.setWidget(self.tocTree)
        self.dockAttachment.setObjectName("Attachment")
        self.dockAttachment.setWidget(self.attachmentView)

        self.setDockOptions(QMainWindow.VerticalTabs)
        self.addDockWidget(Qt.LeftDockWidgetArea, self.dockIndex)
        self.addDockWidget(Qt.LeftDockWidgetArea, self.dockSearch)
        self.addDockWidget(Qt.LeftDockWidgetArea, self.dockToc)
        self.addDockWidget(Qt.LeftDockWidgetArea, self.dockAttachment)
        self.tabifyDockWidget(self.dockIndex, self.dockSearch)
        self.tabifyDockWidget(self.dockSearch, self.dockToc)
        self.tabifyDockWidget(self.dockToc, self.dockAttachment)
        self.setTabPosition(Qt.LeftDockWidgetArea, QTabWidget.North)
        self.dockIndex.raise_()      # Put dockIndex on top of the tab stack

        menuBar = QMenuBar(self)
        self.setMenuBar(menuBar)
        menuFile = menuBar.addMenu(self.tr('&File'))
        menuEdit = menuBar.addMenu(self.tr('&Edit'))
        menuView = menuBar.addMenu(self.tr('&View'))
        menuHelp = menuBar.addMenu(self.tr('&Help'))
        # menuFile
        menuFile.addAction(self.actions['newPage'])
        menuFile.addAction(self.actions['newSubpage'])
        menuFile.addAction(self.actions['NBSettings'])
        menuFile.addAction(self.actions['MDSettings'])
        menuFile.addAction(self.actions['importPage'])
        menuFile.addAction(self.actions['openNotebook'])
        menuFile.addAction(self.actions['reIndex'])
        menuFile.addSeparator()
        menuFile.addAction(self.actions['save'])
        menuFile.addAction(self.actions['saveAs'])
        menuFile.addAction(self.actions['print_'])
        menuExport = menuFile.addMenu(self.tr('&Export'))
        menuExport.addAction(self.actions['html'])
        menuFile.addSeparator()
        menuFile.addAction(self.actions['renamePage'])
        menuFile.addAction(self.actions['delPage'])
        menuFile.addSeparator()
        menuFile.addAction(self.actions['quit'])
        # menuEdit
        menuEdit.addAction(self.actions['undo'])
        menuEdit.addAction(self.actions['redo'])
        menuEdit.addAction(self.actions['findText'])
        menuEdit.addSeparator()
        menuEdit.addAction(self.actions['sortLines'])
        menuEdit.addAction(self.actions['insertImage'])
        # menuView
        menuView.addAction(self.actions['edit'])
        menuView.addAction(self.actions['split'])
        menuView.addAction(self.actions['flipEditAndView'])
        menuShowHide = menuView.addMenu(self.tr('Show/Hide'))
        menuShowHide.addAction(self.dockIndex.toggleViewAction())
        menuShowHide.addAction(self.dockSearch.toggleViewAction())
        menuShowHide.addAction(self.dockToc.toggleViewAction())
        menuShowHide.addAction(self.dockAttachment.toggleViewAction())
        #menuMode = menuView.addMenu(self.tr('Mode'))
        #menuMode.addAction(self.actionLeftAndRight)
        #menuMode.addAction(self.actionUpAndDown)
        # menuHelp
        menuHelp.addAction(self.actions['readme'])
        menuHelp.addAction(self.actions['changelog'])
        menuHelp.addAction(self.actions['aboutQt'])

        toolBar = QToolBar(self.tr("toolbar"), self)
        toolBar.setObjectName("toolbar")       # needed in saveState()
        toolBar.setIconSize(QSize(16, 16))
        toolBar.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)
        self.addToolBar(Qt.TopToolBarArea, toolBar)
        toolBar.addAction(self.actions['edit'])
        toolBar.addAction(self.actions['split'])
        self.findEdit.returnPressed.connect(self.findText)
        self.findBar.addWidget(self.findEdit)
        self.findBar.addWidget(self.checkBox)
        self.findBar.addAction(self.actions['findPrev'])
        self.findBar.addAction(self.actions['find'])
        self.findBar.setVisible(False)
        self.findBar.visibilityChanged.connect(self.findBarVisibilityChanged)

        self.setStatusBar(self.statusBar)
        self.statusBar.addWidget(self.statusLabel, 1)

        self.notesTree.currentItemChanged.connect(
            self.currentItemChangedWrapper)
        self.tocTree.itemClicked.connect(self.tocNavigate)
        self.notesEdit.textChanged.connect(self.noteEditted)

        self.notesEdit.document(
        ).modificationChanged.connect(self.modificationChanged)

        self.updateRecentViewedNotes()
        notes = self.settings.recentViewedNotes()
        if len(notes) != 0:
            item = self.notesTree.pageToItem(notes[0])
            self.notesTree.setCurrentItem(item)
Esempio n. 21
0
class PeakMapExplorer(EmzedDialog):
    def __init__(self, ok_rows_container=[], parent=None):
        super(PeakMapExplorer, self).__init__(parent)
        self.setWindowFlags(Qt.Window)
        # Destroying the C++ object right after closing the dialog box,
        # otherwise it may be garbage-collected in another QThread
        # (e.g. the editor's analysis thread in Spyder), thus leading to
        # a segmentation fault on UNIX or an application crash on Windows
        self.ok_rows = ok_rows_container

        self.setAttribute(Qt.WA_DeleteOnClose)
        self.setWindowFlags(Qt.Window)

        self.gamma = 3.0

        self.last_used_directory_for_load = None
        self.last_used_directory_for_save = None

        self.history = History()

    def keyPressEvent(self, e):
        # avoid closing of dialog when Esc key pressed:
        if e.key() != Qt.Key_Escape:
            return super(PeakMapExplorer, self).keyPressEvent(e)

    def setWindowTitle(self):
        if self.peakmap2 is None:
            title = os.path.basename(self.peakmap.meta.get("source", ""))
        else:
            p1 = os.path.basename(self.peakmap.meta.get("source", ""))
            p2 = os.path.basename(self.peakmap2.meta.get("source", ""))
            title = "yellow=%s, blue=%s" % (p1, p2)
        super(PeakMapExplorer, self).setWindowTitle(title)

    def setup(self, peakmap, peakmap2=None, table=None):
        self.table = table

        def collect_precursor_mz(pm):
            for s in pm:
                if s.precursors:
                    if s.msLevel > 1:
                        yield s.precursors[0][0]

        self.ms_levels = set(peakmap.getMsLevels())
        self.precursor_mz = set(collect_precursor_mz(peakmap))
        if peakmap2 is not None:
            self.ms_levels &= set(peakmap2.getMsLevels())
            self.precursor_mz &= set(collect_precursor_mz(peakmap2))

        self.ms_levels = sorted(self.ms_levels)
        self.precursor_mz = sorted(self.precursor_mz)

        self.setup_table_widgets()
        self.setup_input_widgets()
        self.history_list = QComboBox(self)

        self.setup_ms2_widgets()
        self.full_pm = peakmap
        self.full_pm2 = peakmap2
        self.dual_mode = self.full_pm2 is not None

        self.current_ms_level = self.ms_levels[0]
        self.process_peakmap(self.current_ms_level)
        self.rtmin, self.rtmax, self.mzmin, self.mzmax = get_range(
            self.peakmap, self.peakmap2)

        self.setup_plot_widgets()
        self.setup_menu_bar()
        self.setup_layout()
        self.connect_signals_and_slots()
        self.setup_initial_values()
        self.plot_peakmap()

    def setup_ms2_widgets(self):
        self.spectra_selector_widget.set_data(self.ms_levels,
                                              self.precursor_mz)

    def setup_table_widgets(self):
        if self.table is not None:
            self.table_widget = create_table_widget(self.table, self)
            self.select_all_peaks = QPushButton("Select all peaks", self)
            self.unselect_all_peaks = QPushButton("Unselect all peaks", self)
            self.done_button = QPushButton("Done", self)

    def setup_menu_bar(self):
        self.menu_bar = QMenuBar(self)
        menu = QMenu("Peakmap Explorer", self.menu_bar)
        self.menu_bar.addMenu(menu)
        if not self.dual_mode:
            self.load_action = QAction("Load Peakmap", self)
            self.load_action.setShortcut(QKeySequence("Ctrl+L"))
            self.load_action2 = None
            menu.addAction(self.load_action)
        else:
            self.load_action = QAction("Load Yellow Peakmap", self)
            self.load_action2 = QAction("Load Blue Peakmap", self)
            menu.addAction(self.load_action)
            menu.addAction(self.load_action2)

        self.save_action = QAction("Save selected range as image", self)
        self.save_action.setShortcut(QKeySequence("Ctrl+S"))
        menu.addAction(self.save_action)

        menu = QMenu("Help", self.menu_bar)
        self.help_action = QAction("Help", self)
        self.help_action.setShortcut(QKeySequence("F1"))
        menu.addAction(self.help_action)
        self.menu_bar.addMenu(menu)

    def process_peakmap(self, ms_level, pre_mz_min=None, pre_mz_max=None):

        peakmap = self.full_pm.filter(lambda s: s.msLevel == ms_level)
        if ms_level > 1 and pre_mz_min is not None:
            peakmap = peakmap.filter(
                lambda s: s.precursors[0][0] >= pre_mz_min)
        if ms_level > 1 and pre_mz_max is not None:
            peakmap = peakmap.filter(
                lambda s: s.precursors[0][0] <= pre_mz_max)

        if self.full_pm2 is not None:
            peakmap2 = self.full_pm2.filter(lambda s: s.msLevel == ms_level)

        self.peakmap = peakmap
        if self.dual_mode:
            self.peakmap2 = peakmap2
        else:
            self.peakmap2 = None

        for i, msl in enumerate(self.ms_levels):
            if msl == ms_level:
                pass  # TODO self.ms_level.setCurrentIndex(i)

        self.setWindowTitle()

    def setup_initial_values(self):

        imax = self.peakmap_plotter.get_total_imax()
        self.image_scaling_widget.set_max_intensity(imax)
        self.image_scaling_widget.set_gamma(self.gamma)

        self.view_range_widget.set_view_range(self.rtmin, self.rtmax,
                                              self.mzmin, self.mzmax)

    def setup_input_widgets(self):
        self.image_scaling_widget = ImageScalingWidget(self)
        self.spectra_selector_widget = SpectraSelectorWidget(self)
        self.view_range_widget = ViewRangeWidget(self)

    def setup_plot_widgets(self):
        self.peakmap_plotter = PeakMapPlottingWidget()
        self.peakmap_plotter.set_peakmaps(self.peakmap, self.peakmap2)
        self.eic_plotter = EicPlottingWidget(with_range=False)
        self.mz_plotter = MzPlottingWidget()

        self.peakmap_plotter.set_logarithmic_scale(1)
        self.peakmap_plotter.set_gamma(self.gamma)

        self.eic_plotter.set_overall_range(self.rtmin, self.rtmax)
        self.mz_plotter.set_overall_range(self.mzmin, self.mzmax)

    def setup_layout(self):
        outer_layout = QVBoxLayout()
        outer_layout.addWidget(self.menu_bar)
        outer_layout.setStretch(0, 1)

        h_splitter = QSplitter(self)
        h_splitter.setOrientation(Qt.Horizontal)

        # FIRST COLUMN of h_splitter is chromatogram + peakmap:  ############################

        v_splitter1 = QSplitter(self)
        v_splitter1.setOrientation(Qt.Vertical)
        v_splitter1.addWidget(self.eic_plotter)
        v_splitter1.addWidget(self.peakmap_plotter)
        self.peakmap_plotter.setMinimumSize(250, 200)
        v_splitter1.setStretchFactor(0, 1)
        v_splitter1.setStretchFactor(1, 3)

        h_splitter.addWidget(v_splitter1)
        h_splitter.setStretchFactor(0, 2)

        # SECOND COLUMN of h_splittier holds controlx boxes + mz plot #######################

        v_splitter2 = QSplitter(self)
        v_splitter2.setOrientation(Qt.Vertical)

        v_splitter2.addWidget(self.image_scaling_widget)
        v_splitter2.addWidget(self.spectra_selector_widget)
        v_splitter2.addWidget(self.view_range_widget)
        v_splitter2.addWidget(self.history_list)
        v_splitter2.addWidget(self.mz_plotter)

        v_splitter2.setStretchFactor(0, 0)
        v_splitter2.setStretchFactor(1, 0)
        v_splitter2.setStretchFactor(2, 0)
        v_splitter2.setStretchFactor(3, 0)
        v_splitter2.setStretchFactor(4, 1)

        h_splitter.addWidget(v_splitter2)
        h_splitter.setStretchFactor(1, 1)

        # THIRD COLUMN of h_splittier holds control table + buttons ##########################
        if self.table:
            frame = QFrame(self)
            layout = QVBoxLayout(frame)
            frame.setLayout(layout)
            layout.addWidget(self.table_widget)

            button_row_layout = QHBoxLayout(frame)
            button_row_layout.addWidget(self.select_all_peaks)
            button_row_layout.addWidget(self.unselect_all_peaks)
            button_row_layout.addWidget(self.done_button)

            layout.addLayout(button_row_layout)
            h_splitter.addWidget(frame)
            h_splitter.setStretchFactor(2, 2)

        outer_layout.addWidget(h_splitter)
        self.setLayout(outer_layout)
        outer_layout.setStretch(1, 99)

    def connect_signals_and_slots(self):
        self.image_scaling_widget.USE_LOG_SCALE.connect(self.use_logscale)
        self.image_scaling_widget.GAMMA_CHANGED.connect(self.gamma_changed)

        self.image_scaling_widget.IMIN_CHANGED.connect(self.set_image_min)
        self.image_scaling_widget.IMAX_CHANGED.connect(self.set_image_max)

        self.spectra_selector_widget.MS_LEVEL_CHOSEN.connect(
            self.ms_level_chosen)
        self.spectra_selector_widget.PRECURSOR_RANGE_CHANGED.connect(
            self.set_precursor_range)

        self.view_range_widget.RANGE_CHANGED.connect(self.update_image_range)

        self.connect(self.history_list, SIGNAL("activated(int)"),
                     self.history_item_selected)

        if self.dual_mode:
            self.connect(self.load_action, SIGNAL("triggered()"),
                         self.do_load_yellow)
            self.connect(self.load_action2, SIGNAL("triggered()"),
                         self.do_load_blue)
        else:
            self.connect(self.load_action, SIGNAL("triggered()"), self.do_load)
        self.connect(self.save_action, SIGNAL("triggered()"), self.do_save)
        self.connect(self.help_action, SIGNAL("triggered()"), self.show_help)

        self.peakmap_plotter.NEW_IMAGE_LIMITS.connect(
            self.image_limits_upated_by_user)

        self.peakmap_plotter.KEY_LEFT.connect(
            self.user_pressed_left_key_in_plot)
        self.peakmap_plotter.KEY_RIGHT.connect(
            self.user_pressed_right_key_in_plot)
        self.peakmap_plotter.KEY_BACKSPACE.connect(
            self.user_pressed_backspace_key_in_plot)
        self.peakmap_plotter.KEY_END.connect(self.user_pressed_end_key_in_plot)
        self.peakmap_plotter.CURSOR_MOVED.connect(self.cursor_moved_in_plot)
        self.eic_plotter.CURSOR_MOVED.connect(self.eic_cursor_moved)
        self.eic_plotter.VIEW_RANGE_CHANGED.connect(
            self.eic_view_range_changed)
        self.mz_plotter.CURSOR_MOVED.connect(self.mz_cursor_moved)
        self.mz_plotter.VIEW_RANGE_CHANGED.connect(self.mz_view_range_changed)

        if self.table is not None:
            self.connect(self.table_widget.verticalHeader(),
                         SIGNAL("sectionClicked(int)"), self.row_selected)
            self.connect(self.table_widget,
                         SIGNAL("itemClicked(QTableWidgetItem*)"),
                         self.cell_clicked)
            self.connect(self.select_all_peaks, SIGNAL("pressed()"),
                         self.select_all_peaks_button_pressed)
            self.connect(self.unselect_all_peaks, SIGNAL("pressed()"),
                         self.unselect_all_peaks_button_pressed)
            self.connect(self.done_button, SIGNAL("pressed()"),
                         self.done_button_pressed)

            def key_release_handler(evt):
                tw = self.table_widget
                active_rows = set(
                    ix.row()
                    for ix in tw.selectionModel().selection().indexes())
                if active_rows:
                    row = active_rows.pop()
                    if evt.key() in (Qt.Key_Up, Qt.Key_Down):
                        tw.selectRow(row)
                        tw.verticalHeader().emit(SIGNAL("sectionClicked(int)"),
                                                 row)
                        return
                return QTableWidget.keyPressEvent(tw, evt)

            self.table_widget.keyReleaseEvent = key_release_handler

    def cursor_moved_in_plot(self, rt, mz):
        self.eic_plotter.set_cursor_pos(rt)
        self.mz_plotter.set_cursor_pos(mz)

    def eic_cursor_moved(self, rt):
        self.peakmap_plotter.set_cursor_rt(rt)

    def eic_view_range_changed(self, rtmin, rtmax):
        """
        we want to avoid the loop   EIC_RANGE_CHANGED -> VIEW_RANGE_CHANGED -> EIC_RANGE_CHANGED
        and we do not want to fully block emitting of VIEW_RANGE_CHANGED.
        so self.peakmap_plotter.blockSignals() does not work here, instead we "cut" the last
        connection here:
        """
        self.eic_plotter.VIEW_RANGE_CHANGED.disconnect()
        self.peakmap_plotter.blockSignals(True)
        self.peakmap_plotter.set_rt_limits(rtmin, rtmax)
        self.peakmap_plotter.blockSignals(False)
        self.peakmap_plotter.replot()
        self.eic_plotter.VIEW_RANGE_CHANGED.connect(
            self.eic_view_range_changed)

    def mz_view_range_changed(self, mzmin, mzmax):
        """
        we want to avoid the loop  MZ_RANGE_CHANGED -> VIEW_RANGE_CHANGED -> MZ_RANGE_CHANGED
        and we do not want to fully block emitting of VIEW_RANGE_CHANGED.
        so self.peakmap_plotter.blockSignals() does not work here, instead we "cut" the last
        connection here:
        """
        self.mz_plotter.VIEW_RANGE_CHANGED.disconnect()
        self.peakmap_plotter.blockSignals(True)
        self.peakmap_plotter.set_mz_limits(mzmin, mzmax)
        self.peakmap_plotter.blockSignals(False)
        self.peakmap_plotter.replot()
        self.mz_plotter.VIEW_RANGE_CHANGED.connect(self.mz_view_range_changed)

    def mz_cursor_moved(self, mz):
        self.peakmap_plotter.set_cursor_mz(mz)

    def image_limits_upated_by_user(self, rtmin, rtmax, mzmin, mzmax):
        self.update_peakmap_projection_views(rtmin, rtmax, mzmin, mzmax)
        self.history.new_head((rtmin, rtmax, mzmin, mzmax))
        self.update_history_entries()

    def set_image_min(self, value):
        self.peakmap_plotter.set_imin(value)
        self.peakmap_plotter.replot()

    def set_image_max(self, value):
        self.peakmap_plotter.set_imax(value)
        self.peakmap_plotter.replot()

    def update_peakmap_projection_views(self, rtmin, rtmax, mzmin, mzmax):

        rts, chroma = self.peakmap.chromatogram(mzmin, mzmax)
        self.eic_plotter.del_all_items()
        if self.dual_mode:
            rts2, chroma2 = self.peakmap2.chromatogram(mzmin, mzmax, rtmin,
                                                       rtmax)
            self.eic_plotter.add_eics([(rts, chroma), (rts2, chroma2)],
                                      configs=[blue_line, yellow_line])
        else:
            self.eic_plotter.add_eics([(rts, chroma)], configs=[grey_line])

        self.eic_plotter.shrink_and_replot(rtmin, rtmax)

        if self.dual_mode:
            data = [(self.peakmap, rtmin, rtmax, mzmin, mzmax, 3000),
                    (self.peakmap2, rtmin, rtmax, mzmin, mzmax, 3000)]
            configs = [dict(color="#aaaa00"), dict(color="#0000aa")]
            self.mz_plotter.plot_peakmaps(data, configs)
        else:
            self.mz_plotter.plot_peakmaps([(self.peakmap, rtmin, rtmax, mzmin,
                                            mzmax, 3000)])

        self.mz_plotter.shrink_and_replot(mzmin, mzmax)
        self.view_range_widget.set_view_range(rtmin, rtmax, mzmin, mzmax)

    def _handle_history_action(self, action):
        item = action()
        if item is not None:
            self.peakmap_plotter.set_limits_no_sig(*item)
            self.update_peakmap_projection_views(*item)
            self.update_history_entries()

    def user_pressed_left_key_in_plot(self):
        self._handle_history_action(self.history.go_back)

    def user_pressed_right_key_in_plot(self):
        self._handle_history_action(self.history.go_forward)

    def user_pressed_backspace_key_in_plot(self):
        self._handle_history_action(self.history.go_to_beginning)

    def user_pressed_end_key_in_plot(self):
        self._handle_history_action(self.history.go_to_end)

    def history_item_selected(self, index):
        self._handle_history_action(
            lambda index=index: self.history.set_position(index))

    @protect_signal_handler
    def do_save(self):
        pix = self.peakmap_plotter.paint_pixmap()
        while True:
            path = askForSave(self.last_used_directory_for_save,
                              caption="Save Image",
                              extensions=("png", "PNG"))
            if path is None:
                break
            __, ext = os.path.splitext(path)
            if ext not in (".png", ".PNG"):
                QMessageBox.warning(self, "Warning",
                                    "wrong/missing extension '.png'")
            else:
                self.last_used_directory_for_save = os.path.dirname(path)
                pix.save(path)
                break
        return

    def _do_load(self, title, attribute):
        path = askForSingleFile(self.last_used_directory_for_load,
                                caption=title,
                                extensions=("mzML", "mzData", "mzXML"))
        if path is not None:
            setattr(self, attribute, loadPeakMap(path))
            self.process_peakmap()
            self.peakmap_plotter.set_peakmaps(self.peakmap, self.peakmap2)
            self.setup_initial_values()
            self.setWindowTitle()
            self.peakmap_plotter.replot()
            self.plot_peakmap()
            self.last_used_directory_for_load = os.path.dirname(path)

    @protect_signal_handler
    def do_load(self):
        self._do_load("Load Peakmap", "peakmap")

    @protect_signal_handler
    def do_load_yellow(self):
        self._do_load("Load Yellow Peakmap", "peakmap")

    @protect_signal_handler
    def do_load_blue(self):
        self._do_load("Load Blue Peakmap", "peakmap2")

    @protect_signal_handler
    def select_all_peaks_button_pressed(self):
        for row in range(self.table_widget.rowCount()):
            item = self.table_widget.item(row, 0)
            item.setCheckState(Qt.Checked)

    @protect_signal_handler
    def unselect_all_peaks_button_pressed(self):
        for row in range(self.table_widget.rowCount()):
            item = self.table_widget.item(row, 0)
            item.setCheckState(Qt.Unchecked)

    @protect_signal_handler
    def done_button_pressed(self):
        self.ok_rows[:] = [
            i for i in range(len(self.table))
            if self.table_widget.item(i, 0).checkState() == Qt.Checked
        ]
        self.accept()

    @protect_signal_handler
    def row_selected(self, row_idx):
        row = self.table.getValues(self.table.rows[row_idx])
        needed = ["rtmin", "rtmax", "mzmin", "mzmax"]
        if all(n in row for n in needed):
            rtmin, rtmax, mzmin, mzmax = [row.get(ni) for ni in needed]
            self.peakmap_plotter.set_limits(rtmin, rtmax, mzmin, mzmax)
        else:
            needed = ["mzmin", "mzmax"]
            if all(n in row for n in needed):
                mzmin, mzmax = [row.get(ni) for ni in needed]
                self.peakmap_plotter.set_limits(self.rtmin, self.rtmax, mzmin,
                                                mzmax)

    @protect_signal_handler
    def cell_clicked(self, item):
        row = item.row()
        self.table_widget.selectRow(row)
        self.table_widget.verticalHeader().emit(SIGNAL("sectionClicked(int)"),
                                                row)

    @protect_signal_handler
    def show_help(self):
        html = resource_string("emzed.core.explorers",
                               "help_peakmapexplorer.html")
        QWebSettings.globalSettings().setFontFamily(QWebSettings.StandardFont,
                                                    'Courier')
        QWebSettings.globalSettings().setFontSize(QWebSettings.DefaultFontSize,
                                                  12)
        v = QWebView(self)
        v.setHtml(html)
        dlg = QDialog(self, Qt.Window)
        dlg.setMinimumSize(300, 300)
        l = QVBoxLayout(dlg)
        l.addWidget(v)
        dlg.setLayout(l)
        dlg.show()

    def update_history_entries(self):
        self.history_list.clear()
        for item in self.history.items:
            rtmin, rtmax, mzmin, mzmax = item
            str_item = "%10.5f .. %10.5f %6.2fm...%6.2fm " % (
                mzmin, mzmax, rtmin / 60.0, rtmax / 60.0)
            self.history_list.addItem(str_item)

        self.history_list.setCurrentIndex(self.history.position)

    @protect_signal_handler
    def use_logscale(self, is_log):
        self.peakmap_plotter.set_logarithmic_scale(is_log)
        self.peakmap_plotter.replot()

    @protect_signal_handler
    def ms_level_chosen(self, ms_level):
        if ms_level != self.current_ms_level:
            self.current_ms_level = ms_level
            self.process_peakmap(ms_level)
            self.peakmap_plotter.set_peakmaps(self.peakmap, self.peakmap2)
            self.peakmap_plotter.replot()
            self.plot_peakmap()

    @protect_signal_handler
    def set_precursor_range(self, pre_mz_min, pre_mz_max):
        self.process_peakmap(self.current_ms_level, pre_mz_min, pre_mz_max)
        self.peakmap_plotter.set_peakmaps(self.peakmap, self.peakmap2)
        self.peakmap_plotter.replot()
        self.plot_peakmap()

    @protect_signal_handler
    def gamma_changed(self, value):
        self.peakmap_plotter.set_gamma(value)
        self.peakmap_plotter.replot()

    @protect_signal_handler
    def update_image_range(self, rtmin, rtmax, mzmin, mzmax):

        rtmin *= 60.0
        rtmax *= 60.0

        if rtmin < self.rtmin:
            rtmin = self.rtmin
        if rtmax > self.rtmax:
            rtmax = self.rtmax
        if mzmin < self.mzmin:
            mzmin = self.mzmin
        if mzmax > self.mzmax:
            mzmax = self.mzmax
        rtmin, rtmax = sorted((rtmin, rtmax))
        mzmin, mzmax = sorted((mzmin, mzmax))

        self.peakmap_plotter.set_limits(rtmin, rtmax, mzmin, mzmax)

    def plot_peakmap(self):
        self.peakmap_plotter.set_limits(self.rtmin, self.rtmax, self.mzmin,
                                        self.mzmax)
Esempio n. 22
0
class MainWindow(QMainWindow):

    def __init__(self, app, radarwidget):
        super(MainWindow, self).__init__()
        self.app = app
        uic.loadUi("./data/graphics/mainwindow.ui", self)

        # list of buttons to connect to, give icons, and tooltips
        #           the button         the icon      the tooltip    the callback
        buttons = { self.zoomin  :    ['zoomin.svg', 'Zoom in', self.buttonClicked],
                    self.zoomout :    ['zoomout.svg', 'Zoom out', self.buttonClicked],
                    self.panleft :    ['panleft.svg', 'Pan left', self.buttonClicked],
                    self.panright :   ['panright.svg', 'Pan right', self.buttonClicked],
                    self.panup :      ['panup.svg', 'Pan up', self.buttonClicked],
                    self.pandown :    ['pandown.svg', 'Pan down', self.buttonClicked],
                    self.ic :         ['stop.svg', 'Initial condition', self.buttonClicked],
                    self.op :         ['play.svg', 'Operate', self.buttonClicked],
                    self.hold :       ['pause.svg', 'Hold', self.buttonClicked],
                    self.fast :       ['fwd.svg', 'Enable fast-time', self.buttonClicked],
                    self.fast10 :     ['ffwd.svg', 'Fast-forward 10 seconds', self.buttonClicked],
                    self.sameic :     ['frwd.svg', 'Restart same IC', self.buttonClicked],
                    self.showac :     ['AC.svg', 'Show/hide aircraft', self.buttonClicked],
                    self.showpz :     ['PZ.svg', 'Show/hide PZ', self.buttonClicked],
                    self.showapt :    ['apt.svg', 'Show/hide airports', self.buttonClicked],
                    self.showwpt :    ['wpt.svg', 'Show/hide waypoints', self.buttonClicked],
                    self.showlabels : ['lbl.svg', 'Show/hide text labels', self.buttonClicked],
                    self.showmap :    ['geo.svg', 'Show/hide satellite image', self.buttonClicked]}

        for b in buttons.iteritems():
            # Set icon
            if not b[1][0] is None:
                b[0].setIcon(QIcon('data/graphics/icons/' + b[1][0]))
            # Set tooltip
            if not b[1][1] is None:
                b[0].setToolTip(b[1][1])
            # Connect clicked signal
            b[0].clicked.connect(b[1][2])

        self.menubar = QMenuBar(self)

        # File menu
        self.fileMenu = self.menubar.addMenu('&File')
        self.open_action = self.fileMenu.addAction('&Open')
        self.open_action.triggered.connect(self.app.show_file_dialog)
        self.save_action = self.fileMenu.addAction('&Save')

        # View Menu
        self.viewMenu = self.menubar.addMenu('&View')
        self.resetview_action = self.viewMenu.addAction('&Reset view')
        self.fullscreen_action = self.viewMenu.addAction('Fullscreen')

        # Analysis and metrics menu
        self.analysisMenu = self.menubar.addMenu('&Analysis')
        self.SD_action = self.analysisMenu.addAction('Static Density')
        self.DD_action = self.analysisMenu.addAction('Dynamic Density')
        self.SSD_action = self.analysisMenu.addAction('SSD Metric')
        self.lyu_action = self.analysisMenu.addAction('Lyapunov analysis')

        # Connections menu
        self.connectionsMenu = self.menubar.addMenu('Connections')
        self.connectionsMenu.addAction('Connect to ADS-B server')
        self.connectionsMenu.addAction('Enable output to UDP')

        self.setMenuBar(self.menubar)

        self.radarwidget = radarwidget
        radarwidget.setParent(self.centralwidget)
        self.verticalLayout.insertWidget(0, radarwidget, 1)

    @pyqtSlot()
    def buttonClicked(self):
        if self.sender() == self.zoomin:
            self.app.notify(self.app, PanZoomEvent(zoom=1.4142135623730951))
        elif self.sender() == self.zoomout:
            self.app.notify(self.app, PanZoomEvent(zoom=0.70710678118654746))
        elif self.sender() == self.pandown:
            self.app.notify(self.app, PanZoomEvent(pan=(-0.5,  0.0)))
        elif self.sender() == self.panup:
            self.app.notify(self.app, PanZoomEvent(pan=( 0.5,  0.0)))
        elif self.sender() == self.panleft:
            self.app.notify(self.app, PanZoomEvent(pan=( 0.0, -0.5)))
        elif self.sender() == self.panright:
            self.app.notify(self.app, PanZoomEvent(pan=( 0.0,  0.5)))
        elif self.sender() == self.ic:
            self.app.show_file_dialog()
        elif self.sender() == self.sameic:
            self.app.stack('IC IC')
        elif self.sender() == self.hold:
            self.app.stack('HOLD')
        elif self.sender() == self.op:
            self.app.stack('OP')
        elif self.sender() == self.fast:
            print('Fast clicked')
        elif self.sender() == self.fast10:
            self.app.stack('RUNFT')
        elif self.sender() == self.showac:
            self.radarwidget.show_traf = not self.radarwidget.show_traf
        elif self.sender() == self.showpz:
            self.radarwidget.show_pz = not self.radarwidget.show_pz
        elif self.sender() == self.showapt:
            self.radarwidget.show_apt = not self.radarwidget.show_apt
        elif self.sender() == self.showwpt:
            self.radarwidget.show_wpt = not self.radarwidget.show_wpt
        elif self.sender() == self.showlabels:
            self.radarwidget.show_lbl = not self.radarwidget.show_lbl
        elif self.sender() == self.showmap:
            self.radarwidget.show_map = not self.radarwidget.show_map
Esempio n. 23
0
class MainWindow(QMainWindow):
    """
    class MainWindow for the gui of dokueddy
    """
    def __init__(self, config, parent=None):
        """
        Constructor for class MainWindow
        @param config: dokueddy configuration
        """
        QMainWindow.__init__(self)
        self.config = config
        self.setGeometry(
                         self.config.settings['app_x'], 
                         self.config.settings['app_y'], 
                         self.config.settings['app_w'],
                         self.config.settings['app_h']
                         )
        self.setWindowTitle(
                            self.config.settings['appname'] + 
                            ' - Version: ' +
                            self.config.settings['appversion']
                            )
        globalFont = QFont(
                           self.config.settings['fontfamily'], 
                           self.config.settings['pointsize']
                           )
        self.statusbar = self.statusBar()
        self.center()
    
        self.exit = QAction('Quit Dokueddy', self)
        self.menubar = QMenuBar(None)
        self.file = self.menubar.addMenu('&File')
        self.file.addAction(self.exit)
        self.setMenuBar(self.menubar)
        
        self.save = QAction(QIcon('../resources/icons/save_edit.gif'), 'Save current page', self)
        self.save.setShortcut('Ctrl+S')
        self.save.setDisabled(True)
        self.fontBold = QAction(QIcon('../resources/icons/tag_bold.png'), 'Bold text', self)
        self.fontItalic = QAction(QIcon('../resources/icons/tag_i.png'), 'Italic text', self)
        self.fontH1 = QAction(QIcon('../resources/icons/tag_h1.png'), 'Heading 1', self)
        self.fontH2 = QAction(QIcon('../resources/icons/tag_h2.png'), 'Heading 2', self)
        self.fontH3 = QAction(QIcon('../resources/icons/tag_h3.png'), 'Heading 3', self)
        self.fontH4 = QAction(QIcon('../resources/icons/tag_h4.png'), 'Heading 4', self)
        self.fontH5 = QAction(QIcon('../resources/icons/tag_h5.png'), 'Heading 5', self)
        self.search = QAction(QIcon('../resources/icons/magnify.png'), 'Search for', self)
        
        self.toolbar = self.addToolBar('Toolbar')
        self.toolbar.addAction(self.save)
        self.toolbar.addSeparator()
        self.toolbar.addAction(self.fontBold)
        self.toolbar.addAction(self.fontItalic)
        self.toolbar.addAction(self.fontH1)
        self.toolbar.addAction(self.fontH2)
        self.toolbar.addAction(self.fontH3)
        self.toolbar.addAction(self.fontH4)
        self.toolbar.addAction(self.fontH5)
        self.toolbar.addAction(self.search)
        self.toolbar.setMaximumHeight(24)
        
        self.serverLabel = QLabel()
        self.serverLabel.setText('Serveraddress:')
        self.userLabel = QLabel()
        self.userLabel.setText('Username:'******'Password:'******'serverAddress'])        
        self.userLineEdit = QLineEdit()
        self.userLineEdit.setMaximumSize(150, 35)
        self.userLineEdit.setText(self.config.settings['user'])        
        self.passwdLineEdit = QLineEdit()
        self.passwdLineEdit.setMaximumSize(150, 35)
        self.passwdLineEdit.setEchoMode(QLineEdit.Password)
        
        self.connectButton = QPushButton('Connect', self)
        self.connectButton.setMaximumSize(100, 35)
        self.quitButton = QPushButton('Quit', self)
        self.quitButton.setMaximumSize(100, 35)
    
        self.listView = QListView(self)
        self.listView.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.listView.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded)
        self.listView.setMinimumWidth(200)
        self.listView.setMaximumWidth(400)
        self.listView.setFont(globalFont)
        
        self.textEdit = QTextEdit(self)
        self.textEdit.setMinimumWidth(400)
        self.textEdit.setFont(globalFont)
        self.textEdit.setLineWrapMode(QTextEdit.NoWrap)
    
        self.editLayout = QGridLayout()
        self.editLayout.addWidget(self.serverLabel, 0, 0, Qt.AlignLeft)
        self.editLayout.addWidget(self.serverLineEdit, 0, 1)
        self.editLayout.addWidget(self.userLabel, 0, 2, Qt.AlignLeft)
        self.editLayout.addWidget(self.userLineEdit, 0, 3)
        self.editLayout.addWidget(self.passwdLabel, 0, 4, Qt.AlignLeft)
        self.editLayout.addWidget(self.passwdLineEdit, 0, 5)
        
        self.gridLayout = QGridLayout()
        self.gridLayout.addLayout(self.editLayout, 0, 0, 1, 2)
        self.gridLayout.addWidget(self.listView, 1, 0, Qt.AlignLeft)
        self.gridLayout.addWidget(self.textEdit, 1, 1, Qt.AlignLeft)
        self.gridLayout.addWidget(self.connectButton, 2, 0, Qt.AlignLeft)
        self.gridLayout.addWidget(self.quitButton, 2, 1, Qt.AlignRight)
    
        self.mainWidget = QWidget(self)
        self.mainWidget.setLayout(self.gridLayout)
        self.setCentralWidget(self.mainWidget)

    def center(self):
        screen = QDesktopWidget().screenGeometry()
        size = self.geometry()
        self.move((screen.width() - size.width()) / 2,
                  (screen.height() - size.height()) / 2)