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 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
class MenuManager(QWidget, Ui_nodeActions): def __init__(self, selection, listmodel): super(QWidget, self).__init__() self.__iconView = False self.setupUi(self) self.processusManager = ProcessusManager() self.loader = loader.loader() self.lmodules = self.loader.modules self.taskmanager = TaskManager() self.mainwindow = QApplication.instance().mainWindow self.createActions() self.checkedSelection = selection self.selection = None self.model = listmodel self.bookManager = BookmarkManager(self.model) #self.document = QtWebKit.QWebView() #self.document.loadFinished.connect(self.__print) self.__corrupt = base64.b64encode( str(QtGui.QImage(":file_broken.png").bits())) self.__printer = QtGui.QPrinter(QtGui.QPrinter.ScreenResolution) self.__printer.setOutputFormat(QtGui.QPrinter.PdfFormat) self.__printer.setPaperSize(QtGui.QPrinter.A4) self.__printer.setFullPage(True) def setupUi(self, nodeActions): self.actionScan = QAction(self) icon = QIcon() icon.addPixmap(QPixmap(QString.fromUtf8(":/scan")), QIcon.Normal, QIcon.On) self.actionScan.setIcon(icon) self.actionScan.setObjectName(QString.fromUtf8("actionScan")) self.actionReport_node = QAction(self) icon = QIcon() icon.addPixmap(QPixmap(QString.fromUtf8(":/report")), QIcon.Normal, QIcon.On) self.actionReport_node.setIcon(icon) self.actionReport_node.setObjectName( QString.fromUtf8("actionReport_Node")) Ui_nodeActions.setupUi(self, nodeActions) def retranslateUi(self, nodeActions): Ui_nodeActions.retranslateUi(self, nodeActions) self.actionScan.setText( QApplication.translate("nodeActions", "Scan", None, QApplication.UnicodeUTF8)) self.actionScan.setToolTip( QApplication.translate("nodeActions", "Launch recursive scan", None, QApplication.UnicodeUTF8)) self.actionReport_node.setText( QApplication.translate("nodeActions", "Report", None, QApplication.UnicodeUTF8)) self.actionReport_node.setToolTip( QApplication.translate("nodeActions", "Tag nodes", None, QApplication.UnicodeUTF8)) def setIconView(self, enable): self.__iconView = enable def createActions(self): self.extractor = Extractor(self.mainwindow) self.connect(self.extractor, SIGNAL("filled"), self.launchExtract) self.actionOpen.setParent(self.mainwindow) self.actionOpen_in_new_tab.setParent(self.mainwindow) self.copyToHtmlTable = QAction(self.tr("Export selection to pdf"), self) self.copyToHtmlTable.triggered.connect(self.__exportToPdf) self.connect(self.actionOpen, SIGNAL("triggered()"), self.openDefault) self.connect(self.actionOpen_in_new_tab, SIGNAL("triggered()"), self.openAsNewTab) self.connect(self.actionOpen_parent_folder, SIGNAL("triggered()"), self.openParentFolder) self.connect(self.actionHex_viewer, SIGNAL("triggered()"), self.launchHexedit) self.connect(self.actionExtract, SIGNAL("triggered()"), self.extractNodes) self.connect(self.actionBookmark, SIGNAL("triggered()"), self.bookmark) self.connect(self.actionScan, SIGNAL('triggered()'), self.scan) self.connect(self.actionReport_node, SIGNAL('triggered()'), self.reportNode) def createMenu(self): nodeclicked = self.model.currentNode() self.mainmenu = QMenu(self.mainwindow) self.selection = self.model.currentNode() self.setOpenRelevant() self.setOpenWith() self.mainmenu.addAction(self.actionOpen) self.mainmenu.addAction(self.actionOpen_with) self.mainmenu.addAction(self.actionOpen_in_new_tab) self.mainmenu.addAction(self.actionOpen_parent_folder) if nodeclicked.isDir() or nodeclicked.hasChildren(): self.actionOpen_parent_folder.setVisible(False) self.actionOpen_parent_folder.setEnabled(False) self.actionOpen_in_new_tab.setVisible(True) self.actionOpen_in_new_tab.setEnabled(True) else: self.actionOpen_in_new_tab.setVisible(False) self.actionOpen_in_new_tab.setEnabled(False) self.actionOpen_parent_folder.setVisible(True) self.actionOpen_parent_folder.setEnabled(True) self.mainmenu.addSeparator() selection = selectionMenu(self, self.model) self.mainmenu.addMenu(selection) tags = tagMenu(self, self.mainwindow, self.model) self.actionTags.setMenu(tags) self.mainmenu.addAction(self.actionTags) self.mainmenu.addAction(self.actionBookmark) if nodeclicked.path().find('/Bookmarks/') != -1: self.mainmenu.addAction(QIcon(":trash"), self.tr("Delete bookmark"), self.deleteBookmark) self.bookseparator = self.mainmenu.addSeparator() self.mainmenu.addAction(self.actionHex_viewer) self.mainmenu.addAction(self.actionExtract) if self.__iconView: self.mainmenu.addAction(self.copyToHtmlTable) self.mainmenu.popup(QCursor.pos()) self.mainmenu.insertSeparator(self.actionOpen_parent_folder) self.mainmenu.insertAction(self.actionOpen_parent_folder, self.actionScan) self.mainmenu.addSeparator() self.mainmenu.insertAction(self.bookseparator, self.actionReport_node) self.mainmenu.show() def reportNode(self): ReportNodesAction(self.model) def scan(self): autoWiz = AutoWizard(self, root=self.model.currentNode()) autoWiz.exec_() def deleteBookmark(self): vfs = VFS.Get() try: vfs.unregister(self.model.currentNode()) except Exception as e: print 'TreeMenu.deleteNode exceptions : ', str(e) def setOpenRelevant(self): if self.selection != None: node = self.selection modules = node.compatibleModules() if len(modules): relevant = QMenu() for modname in modules: module = self.loader.modules[modname] relevant.addAction( newAction(self, self.mainwindow, modname, module.tags, module.icon)) self.actionOpen.setMenu(relevant) def __exportToPdf(self): pdfFile = QtGui.QFileDialog.getSaveFileName( self, self.tr("Export to pdf file"), os.path.expanduser("~"), self.tr("Pdf files (*.pdf)")) if not pdfFile.endsWith(".pdf"): pdfFile.append(".pdf") self.__printer.setOutputFileName(pdfFile) self.__createPdf() def __createPdf(self): html = """ <html> <head> <style type="text/css"> img { max-width: 340px; max-height: 340px; width: expression(this.width > 340 ? "340px" : true); height: expression(this.height > 340 ? "340px" : true); } .break { page-break-before: always; } </style> </head> <body> """ start = """<table style="height: 100%; margin: 1px auto; border-spacing: 10px; border-collapse: separate;">""" end = """</table><p class="break"></p>""" count = 1 row = "" for uid in self.checkedSelection._selection: cell = self.__nodeToHtmlCell(uid) if len(cell): row += cell if count == 1: html += start if count % 3 == 0: html += "<tr>\n{}\n</tr>".format(row) row = "" if count == 9: html += end count = 0 row = "" count += 1 if len(row): html += "<tr>{}</tr></table>".format(row) html += "</body></html>" self.document.setHtml(html) def __nodeToHtmlCell(self, uid): imagecell = """<td style="text-align: center;"><img src="data:image/jpg;base64,{}"/><br />{} {} {}</td>""" node = VFS.Get().getNodeById(uid) timestamp = "" device = "" model = "" make = "" b64image = self.__corrupt if node is not None: dtype = node.dataType() try: if dtype.find("image") != -1: vfile = node.open() image = vfile.read() vfile.close() data = node.attributesByName("exif.Model", ABSOLUTE_ATTR_NAME) if len(data): model = data[0].toString() data = node.attributesByName("exif.Make", ABSOLUTE_ATTR_NAME) if len(data): make = data[0].toString() if len(model) or len(make): device = "<br />{} {}".format(model, make) data = node.attributesByName("exif.DateTimeDigitized", ABSOLUTE_ATTR_NAME) if len(data): timestamp = "<br /> {}".format(data[0].toString()) b64image = base64.b64encode(image) except: pass return imagecell.format(b64image, node.name(), device, timestamp) return "" def __print(self, ok): self.document.print_(self.__printer) def setOpenWith(self): owmenu = QMenu() setags = Utils.getSetTags() selist = list(setags) selist.sort() owmenu.addAction(self.mainwindow.actionBrowse_modules) owmenu.addSeparator() for tags in selist: if not tags == "builtins": action = QAction(QString(tags), self.mainwindow) menu = self.getMenuFromModuleTag(tags) action.setMenu(menu) owmenu.addAction(action) self.actionOpen_with.setMenu(owmenu) def getMenuFromModuleTag(self, tagname): menu = QMenu() modules = self.loader.modules for mod in modules: m = modules[mod] try: if m.tags == tagname: menu.addAction( newAction(self, self.mainwindow, mod, tagname, m.icon)) # actions.append(newAction(self, self.__mainWindow, mod, self.tags, m.icon)) except AttributeError, e: pass return menu
class trayIcon(QSystemTrayIcon): #================================================================================================================== # CONSTRUCTOR DE LA CLASE #================================================================================================================== def __init__(self, server, icon, parent=None): #-------------------------------------------------------------------------------------------------------------- # INICIAR Y CONFIGURAR LA INSTANCIA #-------------------------------------------------------------------------------------------------------------- QSystemTrayIcon.__init__(self, icon, parent) # Iniciar la instancia self.parent = parent # Almacenar referencia hacia el padre self.server = server #-------------------------------------------------------------------------------------------------------------- # MENU #-------------------------------------------------------------------------------------------------------------- self.menu = QMenu(self.parent) # Definir menú para el trayIcon self.setContextMenu(self.menu) # Enlazar menú con el trayIcon self.showWindow = QAction("Mostrar", self) # Crear acción para mostrar la aplicación self.showWindow.triggered.connect(self.parent.show) # Conectarla con mostrar la ventana de login self.menu.addAction(self.showWindow) # Añadir la acción al menú self.logout = QAction("Cerrar sesión", self) # Crear acción para logout self.logout.triggered.connect(self.parent.closeSession_pressed) # Conectarla con mostrar la ventana de login self.kill = QAction("Salir", self) # Crear acción para cerrar la aplicación self.kill.triggered.connect(self.killApp) # Conectarla con cerrar el programa self.menu.addAction(self.kill) # Añadir la acción al menú #-------------------------------------------------------------------------------------------------------------- # SEÑALES #-------------------------------------------------------------------------------------------------------------- # Conectar la señal de cerrar la ventana principal y cerrar la sesióm self.parent.sessionClosed.connect(self.sessionClosed) # Conectar la señal de cerrar la ventana principal y NO cerrar la sesióm self.parent.sessionAlive.connect(self.sessionAlive) #================================================================================================================== # MÉTODOS #================================================================================================================== # Método para atrapar la señal de cerrar la ventana principal y cerrar la sesióm def sessionClosed(self): self.showWindow.triggered.disconnect() # Desconectar la acción self.showWindow.triggered.connect(self.parent.show) # Y reconectar con mostrar la ventana de login self.menu.removeAction(self.logout) # Añadir la acción al menú # Método para atrapar la señal de cerrar la ventana principal y NO cerrar la sesióm def sessionAlive(self): self.showWindow.triggered.disconnect() # Desconectar la acción self.showWindow.triggered.connect(self.parent.mainWindow.show) # Y reconectar con mostrar la ventana principal self.menu.insertAction(self.kill, self.logout) # Añadir la acción al menú # Método para terminar el programa def killApp(self): if self.parent.guiExist: # Si existe la ventana principal mainWindow = self.parent.mainWindow # Apuntador hacia la ventana principal if mainWindow.db.isOpenTurn(): # Si hay un turno abierto mainWindow.db.closeTurn(mainWindow.user) # Cerrar turno del usuario de la ventana principal mainWindow.close() # Cerrar la ventana principal self.parent.db.close() # Cerrar la sesión en la base de datos self.parent.close() # Cerrar la ventana de login self.server.close() # Cerrar el servidor de la aplicación exit(0) # Salir del programa