class MainWindow(QMainWindow): def __init__(self): super().__init__() self.setMinimumWidth(640) self.setMinimumHeight(480) # Set up QTabWidget as a central widget self.tab_widget = QTabWidget(self) self.tab_widget.setTabsClosable(True) self.tab_widget.tabCloseRequested.connect(self.on_tab_close_clicked) self.setCentralWidget(self.tab_widget) # Create "Connection" menu menu_bar = self.menuBar() connection_menu = menu_bar.addMenu('Connection') # Add "Create" connection button create_connection_action = QAction('Create', self) create_connection_action.triggered.connect(self.add_new_tab) connection_menu.addAction(create_connection_action) # Add "Close" connection button close_connection_action = QAction('Close', self) close_connection_action.triggered.connect(self.close_current_tab) connection_menu.addAction(close_connection_action) # self.tool_bar = self.addToolBar('test bar') # self.connect_action = self.tool_bar.addAction('connect') self.add_new_tab() def add_new_tab(self): connection_widget = ConnectionWidget(self.tab_widget) connection_widget.title_changed.connect(self.on_tab_name_changed) self.tab_widget.addTab(connection_widget, 'Untitled') def close_current_tab(self): idx = self.tab_widget.currentIndex() self.tab_widget.removeTab(idx) def on_tab_close_clicked(self, idx): self.tab_widget.removeTab(idx) def on_tab_name_changed(self, widget, name): idx = self.tab_widget.indexOf(widget) if idx != -1: self.tab_widget.setTabText(idx, name)
class MainWin(QMainWindow): """ It's a window, stores a TabWidget """ def __init__(self, parent=None): super(MainWin, self).__init__(parent) self.setWindowTitle("Eilat Browser") # gc.set_debug(gc.DEBUG_LEAK) self.last_closed = None self.tab_widget = QTabWidget(self) self.tab_widget.setTabBar(MidClickTabBar(self)) self.tab_widget.tabBar().setMovable(True) self.tab_widget.setTabsClosable(True) # the right side of the tab already has the space for # a non-shown close button self.tab_widget.setStyleSheet( 'QTabBar::tab {padding-top: 0px; padding-bottom: 0px; ' 'padding-left: 0.3em;} ' 'QTabBar::tab:selected {color: #00f;}') # tabCloseRequested carries int (index of a tab) self.tab_widget.tabCloseRequested.connect(self.del_tab) self.setCentralWidget(self.tab_widget) self.tooltip = NotifyLabel(parent=self) def restore_last_closed(): """ One-use callback for QShortcut. Opens a fresh new tab with the url address of the last tab closed """ if self.last_closed is not None: url = self.last_closed self.add_tab(url) self.last_closed = None def dump_gc(): """ prints sizes for large memory collectable objects """ objs = gc.get_objects() pairs = [(str(k)[:80], type(k).__name__, sys.getsizeof(k)) for k in objs if sys.getsizeof(k) > 1024*4*5] for pair in pairs: print(pair) def reload_disk_init(): """ transfer options.yaml and the css directory to global maps """ load_options() load_css() notify("reloaded disk config") set_shortcuts([ ("F9", self, dump_gc), # reload configuration ("Ctrl+Shift+R", self, reload_disk_init), # new tabs ("Ctrl+T", self, self.add_tab), ("Ctrl+Shift+T", self, partial(self.add_tab, scripting=True)), ("Y", self, self.new_tab_from_clipboard), # movement ("M", self, self.inc_tab), ("N", self, partial(self.inc_tab, -1)), ("Ctrl+PgUp", self, partial(self.inc_tab, -1)), ("Ctrl+PgDown", self, self.inc_tab), # destroy/undestroy ("U", self, restore_last_closed), ("Ctrl+W", self, self.del_tab), ("Ctrl+Q", self, self.finalize) ]) def new_tab_from_clipboard(self): """ One-use callback for QShortcut. Reads the content of the PRIMARY clipboard and navigates to it on a new tab. """ url = clipboard() if url is not None: self.add_tab(url) # aux. action (en register_actions) def inc_tab(self, incby=1): """ Takes the current tab index, modifies wrapping around, and sets as current. Afterwards the active tab has focus on its webkit area. """ if self.tab_widget.count() < 2: return idx = self.tab_widget.currentIndex() idx += incby if idx < 0: idx = self.tab_widget.count()-1 elif idx >= self.tab_widget.count(): idx = 0 self.tab_widget.setCurrentIndex(idx) self.tab_widget.currentWidget().webkit.setFocus() def finalize(self): """ Just doing self.close() doesn't clean up; for example, closing when the address bar popup is visible doesn't close the popup, and leaves the window hidden and unclosable (except e.g. for KILL 15) Makes a hard app close through os._exit to prevent garbage collection; cleanup has typically done more harm than good. Any state that we may want to preserve we should do ourselves (e.g. cookies through the NAMs) """ idx = self.tab_widget.currentIndex() self.tab_widget.widget(idx).deleteLater() self.tab_widget.removeTab(idx) close_managers() # also does an os._exit # action y connect en llamada en constructor def del_tab(self, idx=None): """ Closes a tab. If 'idx' is set, it was called by a tabCloseRequested signal (maybe mid click). If not, it was called by a keyboard action and closes the currently active tab. Afterwards the active tab has focus on its webkit area. It closes the window when deleting the last active tab. """ if idx is None: idx = self.tab_widget.currentIndex() self.tab_widget.widget(idx).webkit.stop() self.last_closed = self.tab_widget.widget(idx).webkit.url() self.tab_widget.widget(idx).deleteLater() self.tab_widget.removeTab(idx) if len(self.tab_widget) == 0: close_managers() # also does an os.__exit else: self.tab_widget.currentWidget().webkit.setFocus() # action (en register_actions) # only way to create a new tab # called externally in eilat.py to create the first tab def add_tab(self, url=None, scripting=False): """ Creates a new tab, either empty or navegating to the url. Sets itself as the active tab. If navegating to an url it gives focus to the webkit area. Otherwise, the address bar is focused. """ tab = WebTab(parent=self.tab_widget) self.tab_widget.addTab(tab, tab.current['title']) self.tab_widget.setCurrentWidget(tab) tab_idx = self.tab_widget.indexOf(tab) self.tab_widget.tabBar().tabButton(tab_idx, 1).hide() # 1: right align if scripting: tab.toggle_script() if url is not None: qurl = fix_url(url) tab.webkit.navigate(qurl) else: tab.address_bar.setFocus()
class PanelQWidget(QWidget): """ Class who manage Panel with Host and Services QWidgets """ def __init__(self, parent=None): super(PanelQWidget, self).__init__(parent) self.setAcceptDrops(True) # Fields self.tab_widget = QTabWidget() self.layout = QVBoxLayout() self.dashboard_widget = DashboardQWidget() self.synthesis_widget = SynthesisQWidget() self.problems_widget = ProblemsQWidget() self.spy_widget = SpyQWidget() self.hostnames_list = [] def initialize(self): """ Create the QWidget with its items and layout. """ logger.info('Create Panel View...') self.setLayout(self.layout) # Dashboard widget self.dashboard_widget.initialize() self.layout.addWidget(self.dashboard_widget) self.tab_widget.setMovable(True) self.layout.addWidget(self.tab_widget) tab_order = self.get_tab_order() # Set hostnames self.hostnames_list = data_manager.get_all_hostnames() # Synthesis self.synthesis_widget.initialize_synthesis() self.synthesis_widget.host_widget.spy_btn.clicked.connect( self.spy_host) self.synthesis_widget.line_search.returnPressed.connect( self.display_host) self.synthesis_widget.line_search.cursorPositionChanged.connect( self.display_host) self.synthesis_widget.create_line_search(self.hostnames_list) self.tab_widget.insertTab(tab_order.index('h'), self.synthesis_widget, _('Host Synthesis')) self.tab_widget.setTabToolTip( self.tab_widget.indexOf(self.synthesis_widget), _('See a synthesis view of a host')) # Problems self.problems_widget.initialize(self.spy_widget) self.problems_widget.host_btn.clicked.connect(self.display_host) self.problems_widget.problems_table.doubleClicked.connect( self.set_host_from_problems) self.tab_widget.insertTab( tab_order.index('p'), self.problems_widget, _('Problems (%d)') % len(data_manager.get_problems()['problems'])) self.tab_widget.setTabToolTip( self.tab_widget.indexOf(self.problems_widget), _('See the problems found in backend')) # Spied hosts self.spy_widget.initialize() self.tab_widget.insertTab(tab_order.index('s'), self.spy_widget, _('Spy Hosts')) self.tab_widget.setTabToolTip(self.tab_widget.indexOf(self.spy_widget), _('See spy hosts by Alignak-app')) # Hide widget for first display self.dashboard_widget.show() self.synthesis_widget.host_widget.hide() self.synthesis_widget.services_widget.hide() @staticmethod def get_tab_order(): """ Return tab order defined by user, else default order :return: tab order of App :rtype: list """ default_order = ['p', 'h', 's'] tab_order = settings.get_config('Alignak-app', 'tab_order').split(',') try: assert len(tab_order) == len(default_order) for nb in default_order: assert nb in tab_order except AssertionError: logger.error('Wrong "tab_order" value in config file %s', tab_order) tab_order = default_order return tab_order def spy_host(self): """ Spy host who is available in line_search QLineEdit """ if self.synthesis_widget.line_search.text() in self.hostnames_list: # Spy host self.spy_widget.spy_list_widget.add_spy_host( self.synthesis_widget.host_widget.host_item.item_id) # Update QWidgets self.synthesis_widget.host_widget.spy_btn.setEnabled(False) self.tab_widget.setTabText( self.tab_widget.indexOf(self.spy_widget), _("Spied Hosts (%d)") % self.spy_widget.spy_list_widget.count()) def display_host(self): """ Display and update HostQWidget """ # Update and set "line_search" in case hosts have been added or deleted hostnames_list = data_manager.get_all_hostnames() if hostnames_list != self.hostnames_list: self.synthesis_widget.create_line_search(hostnames_list) # If sender is QPushButton from problems, set "line_search" text if isinstance(self.sender(), QPushButton): self.set_host_from_problems() # Display host if exists if self.synthesis_widget.line_search.text().rstrip( ) in self.hostnames_list: # Get Host Item and its services host = self.get_current_host() services = data_manager.get_host_services(host.item_id) if not services: app_backend.query_services(host.item_id) services = data_manager.get_host_services(host.item_id) # Update QWidgets self.tab_widget.setTabText( self.tab_widget.indexOf(self.synthesis_widget), _('Host "%s"') % host.get_display_name()) not_spied = bool(host.item_id not in self.spy_widget.spy_list_widget.spied_hosts) self.synthesis_widget.update_synthesis(host, services, not_spied) self.dashboard_widget.update_dashboard() else: self.synthesis_widget.update_synthesis(None, None, True) self.tab_widget.setTabText( self.tab_widget.indexOf(self.synthesis_widget), _('Host Synthesis')) def set_host_from_problems(self): """ Set line search if ``sender()`` is instance of QPushButton from :class:`Problems <alignak_app.qobjects.alignak.problems.ProblemsQWidget>` QWidget """ item = self.problems_widget.get_current_user_role_item() if item: if 'service' in item.item_type: hostname = data_manager.get_item('host', item.data['host']).name else: hostname = item.name if hostname in self.hostnames_list: self.synthesis_widget.line_search.setText(hostname) self.tab_widget.setCurrentIndex( self.tab_widget.indexOf(self.synthesis_widget)) def get_current_host(self): """ Return current Host item with name in QLineEdit :return: current host :rtype: alignak_app.items.host.Host """ current_host = data_manager.get_item( 'host', self.synthesis_widget.line_search.text().rstrip()) return current_host def dragMoveEvent(self, event): # pragma: no cover """ Override dragMoveEvent. Only accept EventItem() objects who have ``Qt.UserRole`` :param event: event triggered when something move """ if event.source().currentItem().data(Qt.UserRole): event.accept() else: event.ignore() def dropEvent(self, event): # pragma: no cover """ Override dropEvent. Get dropped item data, create a new one, and delete the one who is in EventsQWidget :param event: event triggered when something is dropped """ host = data_manager.get_item( 'host', '_id', event.source().currentItem().data(Qt.UserRole)) logger.debug('Drag and drop host in Panel: %s', host.name) logger.debug('... with current item: %s', event.source().currentItem()) self.synthesis_widget.line_search.setText(host.name) self.tab_widget.setCurrentIndex( self.tab_widget.indexOf(self.synthesis_widget)) self.display_host() def dragEnterEvent(self, event): """ Override dragEnterEvent. :param event: event triggered when something enter """ event.accept() event.acceptProposedAction()
class MainWin(QMainWindow): """ It's a window, stores a TabWidget """ def __init__(self, parent=None): super(MainWin, self).__init__(parent) self.setWindowTitle("Eilat Browser") # gc.set_debug(gc.DEBUG_LEAK) self.last_closed = None self.tab_widget = QTabWidget(self) self.tab_widget.setTabBar(MidClickTabBar(self)) self.tab_widget.tabBar().setMovable(True) self.tab_widget.setTabsClosable(True) # the right side of the tab already has the space for # a non-shown close button self.tab_widget.setStyleSheet( 'QTabBar::tab {padding-top: 0px; padding-bottom: 0px; ' 'padding-left: 0.3em;} ' 'QTabBar::tab:selected {color: #00f;}') # tabCloseRequested carries int (index of a tab) self.tab_widget.tabCloseRequested.connect(self.del_tab) self.setCentralWidget(self.tab_widget) self.tooltip = NotifyLabel(parent=self) def restore_last_closed(): """ One-use callback for QShortcut. Opens a fresh new tab with the url address of the last tab closed """ if self.last_closed is not None: url = self.last_closed self.add_tab(url) self.last_closed = None def dump_gc(): """ prints sizes for large memory collectable objects """ objs = gc.get_objects() pairs = [(str(k)[:80], type(k).__name__, sys.getsizeof(k)) for k in objs if sys.getsizeof(k) > 1024 * 4 * 5] for pair in pairs: print(pair) def reload_disk_init(): """ transfer options.yaml and the css directory to global maps """ load_options() load_css() notify("reloaded disk config") set_shortcuts([ ("F9", self, dump_gc), # reload configuration ("Ctrl+Shift+R", self, reload_disk_init), # new tabs ("Ctrl+T", self, self.add_tab), ("Ctrl+Shift+T", self, partial(self.add_tab, scripting=True)), ("Y", self, self.new_tab_from_clipboard), # movement ("M", self, self.inc_tab), ("N", self, partial(self.inc_tab, -1)), ("Ctrl+PgUp", self, partial(self.inc_tab, -1)), ("Ctrl+PgDown", self, self.inc_tab), # destroy/undestroy ("U", self, restore_last_closed), ("Ctrl+W", self, self.del_tab), ("Ctrl+Q", self, self.finalize) ]) def new_tab_from_clipboard(self): """ One-use callback for QShortcut. Reads the content of the PRIMARY clipboard and navigates to it on a new tab. """ url = clipboard() if url is not None: self.add_tab(url) # aux. action (en register_actions) def inc_tab(self, incby=1): """ Takes the current tab index, modifies wrapping around, and sets as current. Afterwards the active tab has focus on its webkit area. """ if self.tab_widget.count() < 2: return idx = self.tab_widget.currentIndex() idx += incby if idx < 0: idx = self.tab_widget.count() - 1 elif idx >= self.tab_widget.count(): idx = 0 self.tab_widget.setCurrentIndex(idx) self.tab_widget.currentWidget().webkit.setFocus() def finalize(self): """ Just doing self.close() doesn't clean up; for example, closing when the address bar popup is visible doesn't close the popup, and leaves the window hidden and unclosable (except e.g. for KILL 15) Makes a hard app close through os._exit to prevent garbage collection; cleanup has typically done more harm than good. Any state that we may want to preserve we should do ourselves (e.g. cookies through the NAMs) """ idx = self.tab_widget.currentIndex() self.tab_widget.widget(idx).deleteLater() self.tab_widget.removeTab(idx) close_managers() # also does an os._exit # action y connect en llamada en constructor def del_tab(self, idx=None): """ Closes a tab. If 'idx' is set, it was called by a tabCloseRequested signal (maybe mid click). If not, it was called by a keyboard action and closes the currently active tab. Afterwards the active tab has focus on its webkit area. It closes the window when deleting the last active tab. """ if idx is None: idx = self.tab_widget.currentIndex() self.tab_widget.widget(idx).webkit.stop() self.last_closed = self.tab_widget.widget(idx).webkit.url() self.tab_widget.widget(idx).deleteLater() self.tab_widget.removeTab(idx) if len(self.tab_widget) == 0: close_managers() # also does an os.__exit else: self.tab_widget.currentWidget().webkit.setFocus() # action (en register_actions) # only way to create a new tab # called externally in eilat.py to create the first tab def add_tab(self, url=None, scripting=False): """ Creates a new tab, either empty or navegating to the url. Sets itself as the active tab. If navegating to an url it gives focus to the webkit area. Otherwise, the address bar is focused. """ tab = WebTab(parent=self.tab_widget) self.tab_widget.addTab(tab, tab.current['title']) self.tab_widget.setCurrentWidget(tab) tab_idx = self.tab_widget.indexOf(tab) self.tab_widget.tabBar().tabButton(tab_idx, 1).hide() # 1: right align if scripting: tab.toggle_script() if url is not None: qurl = fix_url(url) tab.webkit.navigate(qurl) else: tab.address_bar.setFocus()
class PanelQWidget(QWidget): """ Class who manage Panel with Host and Services QWidgets """ def __init__(self, parent=None): super(PanelQWidget, self).__init__(parent) self.setAcceptDrops(True) # Fields self.tab_widget = QTabWidget() self.layout = QVBoxLayout() self.dashboard_widget = DashboardQWidget() self.synthesis_widget = SynthesisQWidget() self.problems_widget = ProblemsQWidget() self.spy_widget = SpyQWidget() self.hostnames_list = [] def initialize(self): """ Create the QWidget with its items and layout. """ logger.info('Create Panel View...') self.setLayout(self.layout) # Dashboard widget self.dashboard_widget.initialize() self.layout.addWidget(self.dashboard_widget) self.tab_widget.setMovable(True) self.layout.addWidget(self.tab_widget) tab_order = self.get_tab_order() # Set hostnames self.hostnames_list = data_manager.get_all_hostnames() # Synthesis self.synthesis_widget.initialize_synthesis() self.synthesis_widget.host_widget.spy_btn.clicked.connect(self.spy_host) self.synthesis_widget.line_search.returnPressed.connect(self.display_host) self.synthesis_widget.line_search.cursorPositionChanged.connect(self.display_host) self.synthesis_widget.create_line_search(self.hostnames_list) self.tab_widget.insertTab(tab_order.index('h'), self.synthesis_widget, _('Host Synthesis')) self.tab_widget.setTabToolTip( self.tab_widget.indexOf(self.synthesis_widget), _('See a synthesis view of a host') ) # Problems self.problems_widget.initialize(self.spy_widget) self.problems_widget.host_btn.clicked.connect(self.display_host) self.problems_widget.problems_table.doubleClicked.connect(self.set_host_from_problems) self.tab_widget.insertTab( tab_order.index('p'), self.problems_widget, _('Problems (%d)') % len(data_manager.get_problems()['problems']) ) self.tab_widget.setTabToolTip( self.tab_widget.indexOf(self.problems_widget), _('See the problems found in backend') ) # Spied hosts self.spy_widget.initialize() self.tab_widget.insertTab(tab_order.index('s'), self.spy_widget, _('Spy Hosts')) self.tab_widget.setTabToolTip( self.tab_widget.indexOf(self.spy_widget), _('See spy hosts by Alignak-app') ) # Hide widget for first display self.dashboard_widget.show() self.synthesis_widget.host_widget.hide() self.synthesis_widget.services_widget.hide() @staticmethod def get_tab_order(): """ Return tab order defined by user, else default order :return: tab order of App :rtype: list """ default_order = ['p', 'h', 's'] tab_order = settings.get_config('Alignak-app', 'tab_order').split(',') try: assert len(tab_order) == len(default_order) for nb in default_order: assert nb in tab_order except AssertionError: logger.error('Wrong "tab_order" value in config file %s', tab_order) tab_order = default_order return tab_order def spy_host(self): """ Spy host who is available in line_search QLineEdit """ if self.synthesis_widget.line_search.text() in self.hostnames_list: # Spy host self.spy_widget.spy_list_widget.add_spy_host( self.synthesis_widget.host_widget.host_item.item_id ) # Update QWidgets self.synthesis_widget.host_widget.spy_btn.setEnabled(False) self.tab_widget.setTabText( self.tab_widget.indexOf(self.spy_widget), _("Spied Hosts (%d)") % self.spy_widget.spy_list_widget.count() ) def display_host(self): """ Display and update HostQWidget """ # Update and set "line_search" in case hosts have been added or deleted hostnames_list = data_manager.get_all_hostnames() if hostnames_list != self.hostnames_list: self.synthesis_widget.create_line_search(hostnames_list) # If sender is QPushButton from problems, set "line_search" text if isinstance(self.sender(), QPushButton): self.set_host_from_problems() # Display host if exists if self.synthesis_widget.line_search.text().rstrip() in self.hostnames_list: # Get Host Item and its services host = self.get_current_host() services = data_manager.get_host_services(host.item_id) if not services: app_backend.query_services(host.item_id) services = data_manager.get_host_services(host.item_id) # Update QWidgets self.tab_widget.setTabText( self.tab_widget.indexOf(self.synthesis_widget), _('Host "%s"') % host.get_display_name() ) not_spied = bool( host.item_id not in self.spy_widget.spy_list_widget.spied_hosts ) self.synthesis_widget.update_synthesis(host, services, not_spied) self.dashboard_widget.update_dashboard() else: self.synthesis_widget.update_synthesis(None, None, True) self.tab_widget.setTabText( self.tab_widget.indexOf(self.synthesis_widget), _('Host Synthesis') ) def set_host_from_problems(self): """ Set line search if ``sender()`` is instance of QPushButton from :class:`Problems <alignak_app.qobjects.alignak.problems.ProblemsQWidget>` QWidget """ item = self.problems_widget.get_current_user_role_item() if item: if 'service' in item.item_type: hostname = data_manager.get_item('host', item.data['host']).name else: hostname = item.name if hostname in self.hostnames_list: self.synthesis_widget.line_search.setText(hostname) self.tab_widget.setCurrentIndex(self.tab_widget.indexOf(self.synthesis_widget)) def get_current_host(self): """ Return current Host item with name in QLineEdit :return: current host :rtype: alignak_app.items.host.Host """ current_host = data_manager.get_item( 'host', self.synthesis_widget.line_search.text().rstrip() ) return current_host def dragMoveEvent(self, event): # pragma: no cover """ Override dragMoveEvent. Only accept EventItem() objects who have ``Qt.UserRole`` :param event: event triggered when something move """ if event.source().currentItem().data(Qt.UserRole): event.accept() else: event.ignore() def dropEvent(self, event): # pragma: no cover """ Override dropEvent. Get dropped item data, create a new one, and delete the one who is in EventsQWidget :param event: event triggered when something is dropped """ host = data_manager.get_item('host', '_id', event.source().currentItem().data(Qt.UserRole)) logger.debug('Drag and drop host in Panel: %s', host.name) logger.debug('... with current item: %s', event.source().currentItem()) self.synthesis_widget.line_search.setText(host.name) self.tab_widget.setCurrentIndex(self.tab_widget.indexOf(self.synthesis_widget)) self.display_host() def dragEnterEvent(self, event): """ Override dragEnterEvent. :param event: event triggered when something enter """ event.accept() event.acceptProposedAction()