def test_removeMapLayersByLayer(self):
        """ test removing map layers by layer"""
        QgsMapLayerRegistry.instance().removeAllMapLayers()

        # test no crash with empty registry
        QgsMapLayerRegistry.instance().removeMapLayers([None])

        l1 = createLayer('test')
        l2 = createLayer('test2')
        l3 = createLayer('test3')

        QgsMapLayerRegistry.instance().addMapLayers([l1, l2, l3])
        self.assertEqual(QgsMapLayerRegistry.instance().count(), 3)

        #remove bad layers
        QgsMapLayerRegistry.instance().removeMapLayers([None])
        self.assertEqual(QgsMapLayerRegistry.instance().count(), 3)

        # remove valid layers
        QgsMapLayerRegistry.instance().removeMapLayers([l1])
        self.assertEqual(QgsMapLayerRegistry.instance().count(), 2)

        # test that layer has been deleted
        self.assertTrue(sip.isdeleted(l1))

        # remove multiple
        QgsMapLayerRegistry.instance().removeMapLayers([l2, l3])
        self.assertEqual(QgsMapLayerRegistry.instance().count(), 0)
        self.assertTrue(sip.isdeleted(l2))
        self.assertTrue(sip.isdeleted(l3))
Beispiel #2
0
    def test_removeMapLayersByLayer(self):
        """ test removing map layers by layer"""
        store = QgsMapLayerStore()

        # test no crash with empty store
        store.removeMapLayers([None])

        l1 = createLayer('test')
        l2 = createLayer('test2')
        l3 = createLayer('test3')

        store.addMapLayers([l1, l2, l3])
        self.assertEqual(store.count(), 3)

        #remove bad layers
        store.removeMapLayers([None])
        self.assertEqual(store.count(), 3)

        # remove valid layers
        store.removeMapLayers([l1])
        self.assertEqual(store.count(), 2)

        # test that layer has been deleted
        self.assertTrue(sip.isdeleted(l1))

        # remove multiple
        store.removeMapLayers([l2, l3])
        self.assertEqual(store.count(), 0)
        self.assertTrue(sip.isdeleted(l2))
        self.assertTrue(sip.isdeleted(l3))
Beispiel #3
0
    def slotFlashTimeout(self):
        '''Handle flashing of UI components.'''

        # because we're flashing random UI components, the C++ object
        # might be deleted, so we have to check before doing things to
        # it: hence the sip.isdeleted

        if ( self.flash is not self.oldflash and self.oldflash is not None
             and not sip.isdeleted(self.oldflash) ):
            # clear any flashing on previous widget
            self.oldflash.setStyleSheet('')
            self.oldflash = None

        if self.flash is not None and not sip.isdeleted(self.flash):
            # set flash state and toggle variable
            if self.flashon:
                self.flash.setStyleSheet('background: yellow;')
            else:
                self.flash.setStyleSheet('')
            self.flashon = not self.flashon
            self.oldflash = self.flash

            # stop flashing after N iterations
            self.flashct -= 1
            if self.flashct == 0:
                self.flash = None
Beispiel #4
0
    def testTakePage(self):
        p = QgsProject()
        l = QgsLayout(p)
        collection = l.pageCollection()

        # add some pages
        page = QgsLayoutItemPage(l)
        page.setPageSize('A4')
        collection.addPage(page)
        page2 = QgsLayoutItemPage(l)
        page2.setPageSize('A5')
        collection.addPage(page2)

        self.assertEqual(collection.pageCount(), 2)

        self.assertFalse(collection.takePage(None))

        self.assertEqual(collection.takePage(page), page)
        self.assertFalse(sip.isdeleted(page))

        self.assertEqual(collection.pageCount(), 1)
        self.assertEqual(collection.pages(), [page2])
        self.assertEqual(collection.page(0), page2)

        self.assertEqual(collection.takePage(page2), page2)
        self.assertFalse(sip.isdeleted(page2))

        self.assertEqual(collection.pageCount(), 0)
        self.assertEqual(collection.pages(), [])
        self.assertFalse(collection.page(0))
Beispiel #5
0
    def testClear(self):
        """
        Test clearing the collection
        """
        p = QgsProject()
        l = QgsLayout(p)
        collection = l.pageCollection()

        collection.clear()

        # add a page
        page = QgsLayoutItemPage(l)
        page.setPageSize('A4')
        collection.addPage(page)
        # add a second page
        page2 = QgsLayoutItemPage(l)
        page2.setPageSize('A5')
        collection.addPage(page2)

        page_about_to_be_removed_spy = QSignalSpy(collection.pageAboutToBeRemoved)

        # clear
        collection.clear()
        self.assertEqual(collection.pageCount(), 0)
        self.assertEqual(len(page_about_to_be_removed_spy), 2)

        QCoreApplication.sendPostedEvents(None, QEvent.DeferredDelete)
        self.assertTrue(sip.isdeleted(page))
        self.assertTrue(sip.isdeleted(page2))
Beispiel #6
0
    def search(self, text):
        logging.debug('Doing search.')
        thread = QThread()

        worker = SearchWorker(text, time.time())
        worker.moveToThread(thread)

        thread.started.connect(worker.process)
        worker.finished.connect(thread.quit)
        worker.finished.connect(worker.deleteLater)
        worker.new_items.connect(functools.partial(self.repopulate, worker))
        thread.finished.connect(thread.deleteLater)

        self._threads.append(thread)
        self.workers.append(worker)
        thread.start()

        # Revert search bar color.
        palette = main_window.palette()
        brush = palette.brush(QPalette.Highlight).color()
        palette.setBrush(QPalette.Base, QBrush(brush))
        search_bar.setPalette(palette)

        # Clean up old threads.
        self._threads = [thread for thread in self._threads
                         if not sip.isdeleted(thread)]
        self.workers = [worker for worker in self.workers
                        if not sip.isdeleted(worker)]
    def test_removeMapLayerByLayer(self):
        """ test removing a map layer by layer """
        QgsMapLayerRegistry.instance().removeAllMapLayers()

        # test no crash with empty registry
        QgsMapLayerRegistry.instance().removeMapLayer('bad')
        QgsMapLayerRegistry.instance().removeMapLayer(None)

        l1 = createLayer('test')
        l2 = createLayer('test2')

        QgsMapLayerRegistry.instance().addMapLayers([l1, l2])
        self.assertEqual(QgsMapLayerRegistry.instance().count(), 2)

        #remove bad layers
        QgsMapLayerRegistry.instance().removeMapLayer(None)
        self.assertEqual(QgsMapLayerRegistry.instance().count(), 2)
        l3 = createLayer('test3')
        QgsMapLayerRegistry.instance().removeMapLayer(l3)
        self.assertEqual(QgsMapLayerRegistry.instance().count(), 2)

        # remove valid layers
        QgsMapLayerRegistry.instance().removeMapLayer(l1)
        self.assertEqual(QgsMapLayerRegistry.instance().count(), 1)

        # test that layer has been deleted
        self.assertTrue(sip.isdeleted(l1))

        # remove second layer
        QgsMapLayerRegistry.instance().removeMapLayer(l2)
        self.assertEqual(QgsMapLayerRegistry.instance().count(), 0)
        self.assertTrue(sip.isdeleted(l2))
Beispiel #8
0
 def onclose(e):
     print 'destroying frame', f
     print 'BEFORE: isdeleted?', sip.isdeleted(f)
     print sip.dump(f)
     f.Destroy()
     #sip.setdeleted(f)
     print 'AFTER: isdeleted?', sip.isdeleted(f)
     print sip.dump(f)
Beispiel #9
0
    def _cleanup(self):
        """
        Delete the thread.
        """

        if self._thread:
            if not sip.isdeleted(self) and not sip.isdeleted(self._thread):
                if self._thread.isRunning():
                    self._thread.quit()
                    if not self._thread.wait(3000):
                        self._thread.terminate()
                        self._thread.wait()
                self._thread.deleteLater()
Beispiel #10
0
    def threadCleanup(self):
        if (self.mesh_thread is not None):
            if (sip.isdeleted(self.mesh_thread) == False):
                if (isinstance(self.mesh_thread,MeshThread)):
                    self.mesh_thread.deleteLater()
                    self.mesh_thread = None

        if (self.thread is not None):
            if (sip.isdeleted(self.thread) == False):
                if (isinstance(self.thread,QThread)):
                    self.thread.quit()
                    self.thread.wait()
                    self.thread.deleteLater()
                    self.thread = None
Beispiel #11
0
    def purgeDeletedWidgets():
        """Finds old references to stashed fields and deletes them"""
        toremove = []
        for field in AbstractEditorWidget.funit_fields:
            if sip.isdeleted(field):
                toremove.append(field)
        for field in toremove:
            AbstractEditorWidget.funit_fields.remove(field)

        toremove = []
        for field in AbstractEditorWidget.tunit_fields:
            if sip.isdeleted(field):
                toremove.append(field)
        for field in toremove:
            AbstractEditorWidget.tunit_fields.remove(field)
Beispiel #12
0
 def g_proxy(self, *args, **kwargs):
     g = func(self, *args, **kwargs)
     result = None
     while not sip.isdeleted(self):
         result = g.send(result)
         try:
             result = yield result
         except (GeneratorExit, StopIteration):
             break
         except Exception:
             if not sip.isdeleted(self):
                 g.throw(*sys.exc_info()) # NB: can raise anything and we'll propagate it
             else:
                 log.debug("Ignored exception on deleted object", exc_info=True)
     g.close()
Beispiel #13
0
def sip_is_deleted(obj):
    """
    :return: True if object no longer exists
    """
    if obj is None or (isinstance(obj, sip.simplewrapper) and sip.isdeleted(obj)):
        return True
    return False
    def __init__(self,layer,style,renderer,controller):
        QgsRendererV2Widget.__init__(self, layer, style)

        self._controller=controller

        if renderer is not None and renderer.type() != VectorFieldRenderer.rendererName:
            renderer=None

        import sip
        if renderer is not None and sip.isdeleted(renderer):
            renderer=None

        if renderer is not None and not isinstance(renderer,VectorFieldRenderer):
            renderer=self._controller.findLayerRenderer(layer)

        self.r = VectorFieldRenderer() if renderer is None else renderer

        self._layer=layer
        self.validLayer = True
        if layer is None or layer.type() != QgsMapLayer.VectorLayer or layer.geometryType() != QGis.Point:
           self.setupBlankUi(layer)
           self.validLayer = False
           return

        self._mode = VectorFieldRenderer.Cartesian
        self._ellipsemode = VectorFieldRenderer.NoEllipse
        self.buildWidget()
        self.setupLayer(layer)
        self.loadFromRenderer()
        # Try creating a new renderer to save to ...
        self.r=VectorFieldRenderer()
Beispiel #15
0
    def exit(self):
        """Destroy the Qt main event loop.

        """
        GRobot.exit_lock.acquire()
        if not self._deleted:
            if self.inspector:
                self.inspector.close()
                sip.delete(self.inspector)

            if self.display:
                self.webview.close()
                sip.delete(self.webview)

            if self.page and not sip.isdeleted(self.page):
                sip.delete(self.page)

            GRobot._liveRobot -= 1

            if GRobot._liveRobot == 0 and GRobot._loop is not None:
                GRobot._kill_loop = gevent.spawn_later(20, self.kill_loop)

            self._deleted = True

        GRobot.exit_lock.release()
Beispiel #16
0
 def captureEvent(self, watched, event):
     if self._shouldSaveEvent(event):
         try:
             eventstr = event_to_string(event)
         except KeyError:
             logger.warn("Don't know how to record event: {}".format( str(event) ))
             print "Don't know how to record", str(event)
         else:
             # Perform a full garbage collection before determining the name of this widget
             gc.collect()
             if sip.isdeleted(watched):
                 return
             timestamp_in_seconds = self._timer.seconds()
             objname = str(get_fully_qualified_name(watched))
             if not ( self._ignore_parent_events and objname.startswith(self._parent_name) ):
                 # Special case: If this is a MouseRelease and we somehow missed the MousePress,
                 #               then create a "synthetic" MousePress and insert it immediately before the release
                 if event.type() == QEvent.MouseButtonPress or event.type() == QEvent.MouseButtonDblClick:
                     self._current_observed_mouse_presses.add( event.button() )
                 elif event.type() == QEvent.MouseButtonRelease:
                     try:
                         self._current_observed_mouse_presses.remove( event.button() )
                     except KeyError:
                         synthetic_press_event = QMouseEvent( QEvent.MouseButtonPress, event.pos(), event.globalPos(), event.button(), event.buttons(), event.modifiers() )
                         synthetic_eventstr = event_to_string(synthetic_press_event)
                         self._captured_events.append( (synthetic_eventstr, objname, timestamp_in_seconds) )
                 self._captured_events.append( (eventstr, objname, timestamp_in_seconds) )
     return
Beispiel #17
0
    def _focus_changed(self, old, new):
        """ Handle a change in focus that affects the current tab. """

        # It is possible for the C++ layer of this object to be deleted between
        # the time when the focus change signal is emitted and time when the
        # slots are dispatched by the Qt event loop. This may be a bug in PyQt4.
        if sip.isdeleted(self):
            return

        if self._repeat_focus_changes:
            self.emit(QtCore.SIGNAL('focusChanged(QWidget *,QWidget *)'), old, new)

        if isinstance(new, _DragableTabBar):
            ntw = new.parent()
            ntidx = ntw.currentIndex()
        else:
            ntw, ntidx = self._tab_widget_of(new)

        if ntw is not None:
            self._set_current_tab(ntw, ntidx)
            
        # See if the widget that has lost the focus is ours.
        otw, _ = self._tab_widget_of(old)

        if otw is not None or ntw is not None:
            if ntw is None:
                nw = None
            else:
                nw = ntw.widget(ntidx)
    
            self.emit(QtCore.SIGNAL('hasFocus'), nw)
    def call_QuickTools(self):
        import QuickTools

        if not hasattr(self.parent, "QuickToolsClsObj") or sip.isdeleted(self.parent.QuickToolsClsObj):
            self.parent.QuickToolsClsObj = QuickTools.QuickToolsCls(self.parent)
        self.parent.QuickToolsClsObj.show()
        self.parent.QuickToolsClsObj.raise_()
Beispiel #19
0
 def __del__(self):
     import sip
     if not sip.isdeleted(self.__process):
         log.debug("X11CommandWidget: __del__ terminates x11...")
         self.terminate()
     else:
         log.debug("X11CommandWidget: __del__ does nothing...")
Beispiel #20
0
    def _save_all(self, *, only_window=None, with_private=False):
        """Get a dict with data for all windows/tabs."""
        data = {'windows': []}
        if only_window is not None:
            winlist = [only_window]
        else:
            winlist = objreg.window_registry

        for win_id in sorted(winlist):
            tabbed_browser = objreg.get('tabbed-browser', scope='window',
                                        window=win_id)
            main_window = objreg.get('main-window', scope='window',
                                     window=win_id)

            # We could be in the middle of destroying a window here
            if sip.isdeleted(main_window):
                continue

            if tabbed_browser.private and not with_private:
                continue

            win_data = {}
            active_window = QApplication.instance().activeWindow()
            if getattr(active_window, 'win_id', None) == win_id:
                win_data['active'] = True
            win_data['geometry'] = bytes(main_window.saveGeometry())
            win_data['tabs'] = []
            if tabbed_browser.private:
                win_data['private'] = True
            for i, tab in enumerate(tabbed_browser.widgets()):
                active = i == tabbed_browser.currentIndex()
                win_data['tabs'].append(self._save_tab(tab, active))
            data['windows'].append(win_data)
        return data
Beispiel #21
0
    def _inject_userjs(self, frame):
        """Inject user JavaScripts into the page.

        Args:
            frame: The QWebFrame to inject the user scripts into.
        """
        if sip.isdeleted(frame):
            log.greasemonkey.debug("_inject_userjs called for deleted frame!")
            return

        url = frame.url()
        if url.isEmpty():
            url = frame.requestedUrl()

        log.greasemonkey.debug("_inject_userjs called for {} ({})"
                               .format(frame, url.toDisplayString()))

        greasemonkey = objreg.get('greasemonkey')
        scripts = greasemonkey.scripts_for(url)
        # QtWebKit has trouble providing us with signals representing
        # page load progress at reasonable times, so we just load all
        # scripts on the same event.
        toload = scripts.start + scripts.end + scripts.idle

        if url.isEmpty():
            # This happens during normal usage like with view source but may
            # also indicate a bug.
            log.greasemonkey.debug("Not running scripts for frame with no "
                                   "url: {}".format(frame))
            assert not toload, toload

        for script in toload:
            if frame is self.mainFrame() or script.runs_on_sub_frames:
                log.webview.debug('Running GM script: {}'.format(script.name))
                frame.evaluateJavaScript(script.code())
Beispiel #22
0
 def __del__(self):
     if not sip.isdeleted(self):
         for obs in self.observed():
             # Notify of the subscribed Observables that they have a None
             # reference
             if obs is not None: obs._checkRefs()
     Node.__del__(self)
Beispiel #23
0
 def _cleanupdlgs(self):
     for key, dialogs in self._keytodlgs.items():
         livedialogs = [dlg for dlg in dialogs if not sip.isdeleted(dlg)]
         if livedialogs:
             self._keytodlgs[key] = livedialogs
         else:
             del self._keytodlgs[key]
Beispiel #24
0
 def workaround_broken_under_mouse(ch):
     import sip
     from PyQt5.Qt import QCursor, QToolButton
     # See https://bugreports.qt-project.org/browse/QTBUG-40233
     if isinstance(ch, QToolButton) and not sip.isdeleted(ch):
         ch.setAttribute(Qt.WA_UnderMouse, ch.rect().contains(ch.mapFromGlobal(QCursor.pos())))
         ch.update()
Beispiel #25
0
def test_wrapper():
    "test wrapped objects' __nonzero__"

    f = wx.Frame(None)

    assert not sip.isdeleted(f)
    assert f

    weak_f = ref(f)
    f.Destroy()

    # calling ProcessIdle here forces wxApp::DeletePendingObjects(), which
    # deletes all objects from the wxPendingDelete list
    wx.GetApp().ProcessIdle()

    assert sip.isdeleted(f)
Beispiel #26
0
    def _exit(self):
        """Destroy the Qt main event loop.

        """
        GRobot.exit_lock.acquire()
        if self.inspector:
            self.inspector.close()
            sip.delete(self.inspector)

        if self.display:
            self.webview.close()
            sip.delete(self.webview)

        if self.page and not sip.isdeleted(self.page):
            sip.delete(self.page)

        GRobot._liveRobot -= 1

        if GRobot._liveRobot == 0 and GRobot._loop is not None:

            GRobot._loop.stop()
            GRobot._loop = None
            GRobot._app = None
            if hasattr(self, 'xvfb'):
                GRobot.xvfb.terminate()
        GRobot.exit_lock.release()
Beispiel #27
0
 def setRowCount( self, rows ):
     """Callback method to set the number of rows
     @param rows the new number of rows
     """
     self._rows = rows
     if not sip.isdeleted(self):
         self.layoutChanged.emit()
Beispiel #28
0
 def threadDisconnect(self):
     if (self.mesh_thread is not None):
         if (sip.isdeleted(self.mesh_thread) == False):
             if (isinstance(self.mesh_thread,MeshThread)):
                 self.mesh_thread.finished.disconnect(self.threadFinished)
                 self.mesh_thread.error.disconnect(self.threadError)
                 self.mesh_thread.progress.disconnect(self.threadProgressbar)
Beispiel #29
0
 def _updateLabel(self, label, label_data):
     if not label or sip.isdeleted(label):
         return
     label.setPlainText(label_data["text"])
     label.setPos(label_data["x"], label_data["y"])
     label.setStyle(label_data["style"])
     label.setRotation(label_data["rotation"])
Beispiel #30
0
 def break_cycles(self):
     for tab in self.tabs:
         if not sip.isdeleted(tab):
             self.stack.removeWidget(tab)
             tab.break_cycles()
             tab.deleteLater()
     self.tabs = []
Beispiel #31
0
 def tearDown(self):
     if not sip.isdeleted(self.presenter.container):
         self.presenter.container.close()
         QApplication.sendPostedEvents()
Beispiel #32
0
    def update_controller_widget(cls, controller_widget, control_name,
                                 control_instance):
        """ Update one element of the list controller widget.

        At the end the list controller widget user editable parameter with the
        name 'control_name' will match the controller trait value with the same
        name.

        Parameters
        ----------
        controller_widget: ControllerWidget (mandatory)
            a controller widget that contains the controller we want to update
        control_name: str(mandatory)
            the name of the controller widget control we want to synchronize
            with the controller
        control_instance: QFrame (mandatory)
            the instance of the controller widget control we want to
            synchronize with the controller
        """
        try:
            if control_name not in controller_widget.controller.user_traits():
                return
        except ReferenceError:
            return

        # Get the list widget current connection status
        try:
            was_connected = control_instance.connected
            test = control_instance.control_widget.layout
        except (ReferenceError, RuntimeError):
            # widget deleted in the meantime
            return

        # Disconnect the list controller and the inner list controller
        cls.disconnect(controller_widget, control_name, control_instance)
        control_instance.controller_widget.disconnect()

        widget = control_instance.control_widget
        if sip.isdeleted(widget):
            OffscreenListControlWidget.disconnect(controller_widget,
                                                  control_name,
                                                  control_instance)
            return

        clayout = widget.control_widget.layout()
        owned_widgets = set()
        parent = widget
        for i in range(widget.columnCount()):
            w = widget.cellWidget(0, i)
            if w is not None:
                parent = w.parentWidget()
                owned_widgets.add(w)
        ListControlWidget.update_controller_widget(controller_widget,
                                                   control_name,
                                                   widget.control_widget)
        keys = list(control_instance.controller.user_traits().keys())
        #n = len(control_instance.controller.user_traits())
        parent_value = getattr(controller_widget.controller, control_name)
        if parent_value is traits.Undefined:
            parent_value = []
        elif not isinstance(parent_value, (list, tuple)):
            # in nipype MultiPath, single values are not in a list
            parent_value = [parent_value]
        n = len(parent_value)
        max_items = widget.max_items
        if max_items > 0:
            m = min(max_items, n)
            if n > max_items:
                widget.setColumnCount(m + 1)
            else:
                widget.setColumnCount(n)
        else:
            m = n
            widget.setColumnCount(n)
        for i in range(m):
            try:
                items = widget.control_widget.controller_widget._controls[str(
                    i)]
                item = items[None][2]
                if item not in owned_widgets:
                    widget.setCellWidget(0, i, item)
                if qt_backend.get_qt_backend() == 'PyQt5':
                    widget.horizontalHeader().setSectionResizeMode(
                        i, QtGui.QHeaderView.Stretch)
                else:
                    widget.horizontalHeader().setResizeMode(
                        i, QtGui.QHeaderView.Stretch)
            except KeyError:
                print('KeyError in OffscreenListControlWidget', i)
                print('controls:',
                      widget.control_widget.controller_widget._controls)
        if n > m:
            label = QtGui.QLabel('...')
            width = label.sizeHint().width()
            widget.setCellWidget(0, max_items, QtGui.QLabel('...'))
            if qt_backend.get_qt_backend() == 'PyQt5':
                widget.horizontalHeader().setSectionResizeMode(
                    max_items, QtGui.QHeaderView.Fixed)
            else:
                widget.horizontalHeader().setResizeMode(
                    max_items, QtGui.QHeaderView.Fixed)
            widget.horizontalHeader().resizeSection(max_items, width)

        widget.resizeRowToContents(0)
        height = widget.rowHeight(0) \
            + sum(widget.getContentsMargins()[1:4:2])
        widget.setFixedHeight(height)

        # Restore the previous list controller connection status
        if was_connected:
            cls.connect(controller_widget, control_name, control_instance)
            control_instance.controller_widget.connect()
Beispiel #33
0
 def html(self):
     self.page().toHtml(lambda html: setattr(self, '_html', html))
     wait(until=lambda: self._html is not _NOTSET or sip.isdeleted(self))
     html, self._html = self._html, _NOTSET
     return html
Beispiel #34
0
def _update_stylesheet(obj):
    """Update the stylesheet for obj."""
    get_stylesheet.cache_clear()
    if not sip.isdeleted(obj):
        obj.setStyleSheet(get_stylesheet(obj.STYLESHEET))
Beispiel #35
0
    def eventFilter(self, obj, e):
        'Redirect key presses from the popup to the widget'
        widget = self.completer_widget()
        if widget is None or sip.isdeleted(widget):
            return False
        etype = e.type()
        if obj is not self:
            return QObject.eventFilter(self, obj, e)

        # self.debug_event(e)

        if etype == e.KeyPress:
            key = e.key()
            if key == Qt.Key_Escape:
                self.hide()
                e.accept()
                return True
            if key == Qt.Key_F4 and e.modifiers() & Qt.AltModifier:
                self.hide()
                e.accept()
                return True
            if key in (Qt.Key_Enter, Qt.Key_Return):
                # We handle this explicitly because on OS X activated() is
                # not emitted on pressing Enter.
                idx = self.currentIndex()
                if idx.isValid():
                    self.item_chosen(idx)
                self.hide()
                e.accept()
                return True
            if key == Qt.Key_Tab:
                idx = self.currentIndex()
                if idx.isValid():
                    self.item_chosen(idx)
                    self.hide()
                elif self.model().rowCount() > 0:
                    self.next_match()
                e.accept()
                return True
            if key in (Qt.Key_PageUp, Qt.Key_PageDown):
                # Let the list view handle these keys
                return False
            if key in (Qt.Key_Up, Qt.Key_Down):
                self.next_match(previous=key == Qt.Key_Up)
                e.accept()
                return True
            # Send to widget
            widget.eat_focus_out = False
            widget.keyPressEvent(e)
            widget.eat_focus_out = True
            if not widget.hasFocus():
                # Widget lost focus hide the popup
                self.hide()
            if e.isAccepted():
                return True
        elif isosx and etype == e.InputMethodQuery and e.queries() == (
                Qt.ImHints | Qt.ImEnabled) and self.isVisible():
            # In Qt 5 the Esc key causes this event and the line edit does not
            # handle it, which causes the parent dialog to be closed
            # See https://bugreports.qt-project.org/browse/QTBUG-41806
            e.accept()
            return True
        elif etype == e.MouseButtonPress and not self.rect().contains(
                self.mapFromGlobal(e.globalPos())):
            # A click outside the popup, close it
            if isinstance(widget, QComboBox):
                # This workaround is needed to ensure clicking on the drop down
                # arrow of the combobox closes the popup
                opt = QStyleOptionComboBox()
                widget.initStyleOption(opt)
                sc = widget.style().hitTestComplexControl(
                    QStyle.CC_ComboBox, opt,
                    widget.mapFromGlobal(e.globalPos()), widget)
                if sc == QStyle.SC_ComboBoxArrow:
                    QTimer.singleShot(0, self.hide)
                    e.accept()
                    return True
            self.hide()
            e.accept()
            return True
        elif etype in (e.InputMethod, e.ShortcutOverride):
            QApplication.sendEvent(widget, e)
        return False
Beispiel #36
0
    def eventFilter(self, obj, e):
        'Redirect key presses from the popup to the widget'
        widget = self.completer_widget()
        if widget is None or sip.isdeleted(widget):
            return False
        etype = e.type()
        if obj is not self:
            return QObject.eventFilter(self, obj, e)

        if etype == e.KeyPress:
            key = e.key()
            if key == Qt.Key_Escape:
                self.hide()
                e.accept()
                return True
            if key == Qt.Key_F4 and e.modifiers() & Qt.AltModifier:
                self.hide()
                e.accept()
                return True
            if key in (Qt.Key_Enter, Qt.Key_Return):
                # We handle this explicitly because on OS X activated() is
                # not emitted on pressing Enter.
                idx = self.currentIndex()
                if idx.isValid():
                    self.item_chosen(idx)
                self.hide()
                e.accept()
                return True
            if key == Qt.Key_Tab:
                idx = self.currentIndex()
                if idx.isValid():
                    self.item_chosen(idx)
                    self.hide()
                elif self.model().rowCount() > 0:
                    self.next_match()
                e.accept()
                return True
            if key in (Qt.Key_PageUp, Qt.Key_PageDown):
                # Let the list view handle these keys
                return False
            if key in (Qt.Key_Up, Qt.Key_Down):
                self.next_match(previous=key == Qt.Key_Up)
                e.accept()
                return True
            # Send to widget
            widget.eat_focus_out = False
            widget.keyPressEvent(e)
            widget.eat_focus_out = True
            if not widget.hasFocus():
                # Widget lost focus hide the popup
                self.hide()
            if e.isAccepted():
                return True
        elif etype == e.MouseButtonPress:
            if not self.underMouse():
                self.hide()
                e.accept()
                return True
        elif etype in (e.InputMethod, e.ShortcutOverride):
            QApplication.sendEvent(widget, e)
        return False
Beispiel #37
0
 def onMpvIdle(self):
     w = self._activeWindowOnPlay
     if not self.app.activeWindow() and w and not sip.isdeleted(w) and w.isVisible():
         w.activateWindow()
         w.raise_()
     self._activeWindowOnPlay = None
Beispiel #38
0
def _update_stylesheet(obj, *, generator):
    """Update the stylesheet for obj."""
    if not sip.isdeleted(obj):
        stylesheet = generator() if generator is not None else obj.STYLESHEET
        obj.setStyleSheet(get_stylesheet(stylesheet))
Beispiel #39
0
def rewrap_button(w):
    if not sip.isdeleted(w):
        w.setText(wrap_button_text(w.defaultAction().text()))
Beispiel #40
0
    def validateCurrentPage(self):
        """
        Validates the settings.
        """

        if self.currentPage() == self.uiFilesWizardPage:
            if self._refreshing:
                return False
            current = self.uiApplianceVersionTreeWidget.currentItem()
            if current is None or sip.isdeleted(current):
                return False
            version = current.data(0, QtCore.Qt.UserRole)
            if version is None:
                return False
            appliance = current.data(2, QtCore.Qt.UserRole)
            if not self._appliance.is_version_installable(version["name"]):
                QtWidgets.QMessageBox.warning(
                    self, "Appliance",
                    "Sorry, you cannot install {} with missing files".format(
                        appliance["name"]))
                return False
            reply = QtWidgets.QMessageBox.question(
                self, "Appliance",
                "Would you like to install {} version {}?".format(
                    appliance["name"], version["name"]),
                QtWidgets.QMessageBox.Yes, QtWidgets.QMessageBox.No)
            if reply == QtWidgets.QMessageBox.No:
                return False
            self._uploadImages(version["name"])

        elif self.currentPage() == self.uiUsageWizardPage:
            if self._image_uploading_count > 0:
                QtWidgets.QMessageBox.critical(
                    self, "Add appliance", "Please wait for image uploading")
                return False

            current = self.uiApplianceVersionTreeWidget.currentItem()
            if current:
                version = current.data(0, QtCore.Qt.UserRole)
                return self._install(version["name"])
            else:
                return self._install(None)

        elif self.currentPage() == self.uiServerWizardPage:
            if self.uiRemoteRadioButton.isChecked():
                if len(ComputeManager.instance().remoteComputes()) == 0:
                    QtWidgets.QMessageBox.critical(
                        self, "Remote server",
                        "There is no remote server registered in your preferences"
                    )
                    return False
                self._compute_id = self.uiRemoteServersComboBox.itemData(
                    self.uiRemoteServersComboBox.currentIndex()).id()
            elif hasattr(
                    self,
                    "uiVMRadioButton") and self.uiVMRadioButton.isChecked():
                self._compute_id = "vm"
            else:
                if ComputeManager.instance().localPlatform():
                    if (ComputeManager.instance().localPlatform().startswith(
                            "darwin") or ComputeManager.instance().
                            localPlatform().startswith("win")):
                        if "qemu" in self._appliance:
                            reply = QtWidgets.QMessageBox.question(
                                self, "Appliance",
                                "Qemu on Windows and MacOSX is not supported by the GNS3 team. Are you sur to continue?",
                                QtWidgets.QMessageBox.Yes,
                                QtWidgets.QMessageBox.No)
                            if reply == QtWidgets.QMessageBox.No:
                                return False

                self._compute_id = "local"

        elif self.currentPage() == self.uiQemuWizardPage:
            if self.uiQemuListComboBox.currentIndex() == -1:
                QtWidgets.QMessageBox.critical(
                    self, "Qemu binary", "No compatible Qemu binary selected")
                return False

        elif self.currentPage() == self.uiCheckServerWizardPage:
            return self._server_check

        return True
Beispiel #41
0
 def isQObjectAlive(obj):
     return not sip.isdeleted(obj)
Beispiel #42
0
 def setEnabledIfAlive(self, widget, enable):
     if not sip.isdeleted(widget):
         widget.setEnabled(enable)
    def testPages(self):
        """
        Test adding/retrieving/deleting pages from the collection
        """
        p = QgsProject()
        l = QgsLayout(p)
        collection = l.pageCollection()

        self.assertEqual(collection.pageCount(), 0)
        self.assertFalse(collection.pages())
        self.assertFalse(collection.page(-1))
        self.assertFalse(collection.page(0))
        self.assertFalse(collection.page(1))

        # add a page
        page = QgsLayoutItemPage(l)
        page.setPageSize('A4')
        self.assertEqual(collection.pageNumber(page), -1)

        collection.addPage(page)

        self.assertTrue(page in l.items())

        self.assertEqual(collection.pageCount(), 1)
        self.assertEqual(collection.pages(), [page])
        self.assertFalse(collection.page(-1))
        self.assertEqual(collection.page(0), page)
        self.assertFalse(collection.page(1))
        self.assertEqual(collection.pageNumber(page), 0)

        # add a second page
        page2 = QgsLayoutItemPage(l)
        page2.setPageSize('A5')
        collection.addPage(page2)

        self.assertEqual(collection.pageCount(), 2)
        self.assertEqual(collection.pages(), [page, page2])
        self.assertFalse(collection.page(-1))
        self.assertEqual(collection.page(0), page)
        self.assertEqual(collection.page(1), page2)
        self.assertEqual(collection.pageNumber(page2), 1)

        # insert a page
        page3 = QgsLayoutItemPage(l)
        page3.setPageSize('A3')
        collection.insertPage(page3, 1)
        self.assertTrue(page3 in l.items())

        self.assertEqual(collection.pageCount(), 3)
        self.assertEqual(collection.pages(), [page, page3, page2])
        self.assertEqual(collection.page(0), page)
        self.assertEqual(collection.page(1), page3)
        self.assertEqual(collection.page(2), page2)
        self.assertEqual(collection.pageNumber(page3), 1)

        # delete page
        collection.deletePage(-1)
        self.assertEqual(collection.pageCount(), 3)
        self.assertEqual(collection.pages(), [page, page3, page2])
        collection.deletePage(100)
        self.assertEqual(collection.pageCount(), 3)
        self.assertEqual(collection.pages(), [page, page3, page2])
        collection.deletePage(1)
        self.assertEqual(collection.pageCount(), 2)
        self.assertEqual(collection.pages(), [page, page2])

        # make sure page was deleted
        QCoreApplication.sendPostedEvents(None, QEvent.DeferredDelete)
        self.assertTrue(sip.isdeleted(page3))

        del l
        QCoreApplication.sendPostedEvents(None, QEvent.DeferredDelete)
        self.assertTrue(sip.isdeleted(page))
        self.assertTrue(sip.isdeleted(page2))
Beispiel #44
0
    def _showSlot(self, *args):

        if self._show_lock:
            return
        self._show_lock = True
        if self._progress_dialog is None or sip.isdeleted(
                self._progress_dialog) or self._progress_dialog.wasCanceled():
            progress_dialog = QtWidgets.QProgressDialog(
                "Waiting for server response", None, 0, 0, self.parent())
            progress_dialog.canceled.connect(self._cancelSlot)
            progress_dialog.rejected.connect(self._rejectSlot)
            progress_dialog.setWindowModality(QtCore.Qt.ApplicationModal)
            progress_dialog.setWindowTitle("Please wait")
            progress_dialog.setAutoReset(False)
            progress_dialog.setMinimumDuration(self._minimum_duration)

            if len(self._cancel_button_text) > 0:
                progress_dialog.setCancelButtonText(self._cancel_button_text)
            else:
                progress_dialog.setCancelButton(None)

            if len(self._queries) > 0:
                text = list(self._queries.values())[0]["explanation"]
                progress_dialog.setLabelText(text)

            self._progress_dialog = progress_dialog
            self._finished_query_during_display = 0
            self._display_start_time = (time.time() * 1000) + self._delay
            self.update()
        else:
            progress_dialog = self._progress_dialog
            if sip.isdeleted(progress_dialog):
                self._show_lock = False
                return

            if len(self._queries) > 0:
                text = list(self._queries.values())[0]["explanation"]
            else:
                text = None

            # If we have multiple queries running progress show progress of the queries
            # otherwise it's the progress of the current query
            if len(self._queries) + self._finished_query_during_display > 1:
                progress_dialog.setMaximum(
                    len(self._queries) + self._finished_query_during_display)
                progress_dialog.setValue(self._finished_query_during_display)
            elif len(self._queries) == 1:
                query = list(self._queries.values())[0]
                if query["maximum"] == query["current"]:
                    # We animate the bar. In theory Qt should be able to do it but
                    # due to all the manipulation of the dialog he is getting lost
                    bar_speed = 8
                    if progress_dialog.maximum() != bar_speed:
                        progress_dialog.setMaximum(bar_speed)
                        progress_dialog.setValue(0)
                    elif progress_dialog.value() == bar_speed:
                        progress_dialog.setValue(0)
                    else:
                        progress_dialog.setValue(progress_dialog.value() + 1)

                else:
                    # Due to Qt limitations for large numbers (above 32bit int) we calculate "progress" ourselves
                    current, maximum = self._normalize(query['current'],
                                                       query['maximum'])
                    progress_dialog.setMaximum(maximum)
                    progress_dialog.setValue(current)

                if text and query["maximum"] > 1000:
                    text += "\n{} / {}".format(
                        human_filesize(query["current"]),
                        human_filesize(query["maximum"]))

            if text:
                progress_dialog.setLabelText(text)
        self._show_lock = False
Beispiel #45
0
 def is_deleted(self):
     return sip.isdeleted(self._widget)
Beispiel #46
0
 def _on_webkit_icon_changed(self):
     """Emit iconChanged with a QIcon like QWebEngineView does."""
     if sip.isdeleted(self._widget):
         log.webview.debug("Got _on_webkit_icon_changed for deleted view!")
         return
     self.icon_changed.emit(self._widget.icon())
Beispiel #47
0
 def _rejectSlot(self, *args):
     if self._progress_dialog is not None and not sip.isdeleted(
             self._progress_dialog) or self._progress_dialog.wasCanceled():
         self._progress_dialog.deleteLater()
         self._progress_dialog = None
     self._cancelSlot()
Beispiel #48
0
 def setProgress(self, value):
     if self.progress is not None and not sip.isdeleted(self.progress):
         self.progress.setValue(value)
Beispiel #49
0
 def reset(self):
     if not sip.isdeleted(self):
         self._queries = {}
         self.hide_signal.emit()
Beispiel #50
0
 def load_finished():
     if not sip.isdeleted(self):
         self.frame.addToJavaScriptWindowObject(
             '__bridge', _QWidgetJavaScriptWrapper(self))
         self._evalJS('setTimeout(function(){'
                      '__bridge.load_really_finished(); }, 100);')
Beispiel #51
0
 def partial(*args, **kwargs):
     if sip.isdeleted(func.__self__):
         return
     return func(*args, **kwargs)
Beispiel #52
0
 def _main_window_exists(self):
     return hasattr(self,
                    'main_window') and not sip.isdeleted(self.main_window)
Beispiel #53
0
 def do_trigger(self, checked=False):
     if not sip.isdeleted(self.clone):
         self.clone.trigger()
Beispiel #54
0
 def update_state(self, *args):
     if sip.isdeleted(self) or sip.isdeleted(self.page_action):
         return
     if self.isCheckable():
         self.setChecked(self.page_action.isChecked())
     self.setEnabled(self.page_action.isEnabled())
Beispiel #55
0
 def set_self_icon(icon):
     if not sip.isdeleted(icon):
         self.setIcon(0, icon)
Beispiel #56
0
 def itemExist(self, item):
     return not sip.isdeleted(item)
Beispiel #57
0
def update_stylesheet(obj):
    """Update the stylesheet for obj."""
    if not sip.isdeleted(obj):
        obj.setStyleSheet(get_stylesheet(obj.STYLESHEET))
Beispiel #58
0
 def _update_geometry():
     """Actually update the geometry if the object still exists."""
     if sip.isdeleted(obj):
         return
     obj.updateGeometry()
Beispiel #59
0
def IsDestroyed(win):
    if win is None:
        raise ValueError('IsDestroyed does not take None')

    return sip.isdeleted(win)
Beispiel #60
0
 def _setItemIcon(self, item, icon):
     if not sip.isdeleted(item):
         item.setIcon(0, icon)