Exemplo n.º 1
0
				def load(check_string):
					line = self.p.jekyll_process.stdout.readline()
					if check_string in line:
						loadPreview()
					else:
						self.previewBox.setHtml(str(line))
						QTimer.singleShot(20, lambda: load(check_string))
Exemplo n.º 2
0
    def shutdown(self, status=0):
        """Try to shutdown everything cleanly.

        For some reason lastWindowClosing sometimes seem to get emitted twice,
        so we make sure we only run once here.

        Args:
            status: The status code to exit with.
        """
        if self._shutting_down:
            return
        self._shutting_down = True
        log.destroy.debug("Shutting down with status {}...".format(status))
        deferrer = False
        for win_id in objreg.window_registry:
            prompter = objreg.get('prompter', None, scope='window',
                                  window=win_id)
            if prompter is not None and prompter.shutdown():
                deferrer = True
        if deferrer:
            # If shutdown was called while we were asking a question, we're in
            # a still sub-eventloop (which gets quitted now) and not in the
            # main one.
            # This means we need to defer the real shutdown to when we're back
            # in the real main event loop, or we'll get a segfault.
            log.destroy.debug("Deferring real shutdown because question was "
                              "active.")
            QTimer.singleShot(0, functools.partial(self._shutdown, status))
        else:
            # If we have no questions to shut down, we are already in the real
            # event loop, so we can shut down immediately.
            self._shutdown(status)
Exemplo n.º 3
0
 def test_normal_exec(self):
     """Test exec_ without double-executing."""
     self.loop = qtutils.EventLoop()
     QTimer.singleShot(100, self._assert_executing)
     QTimer.singleShot(200, self.loop.quit)
     self.loop.exec_()
     assert not self.loop._executing
Exemplo n.º 4
0
    def exceptionCaught(self, message, package = '', block = False):
        self.runPreExceptionMethods()

        if any(warning in message for warning in ('urlopen error','Socket Error', 'PYCURL ERROR')):
            errorTitle = i18n("Network Error")
            errorMessage = i18n("Please check your network connections and try again.")
        elif "Access denied" in message or "tr.org.pardus.comar.Comar.PolicyKit" in message:
            errorTitle = i18n("Authorization Error")
            errorMessage = i18n("You are not authorized for this operation.")
        elif "HTTP Error 404" in message and not package == '':
            errorTitle = i18n("Pisi Error")
            errorMessage = unicode(i18n("Package <b>%s</b> not found in repositories.<br>"\
                                        "It may be upgraded or removed from the repository.<br>"\
                                        "Please try upgrading repository informations.")) % package
        elif "MIXING PACKAGES" in message:
            errorTitle = i18n("Pisi Error")
            errorMessage = i18n("Mixing file names and package names not supported yet.")
        elif "FILE NOT EXISTS" in message:
            errorTitle = i18n("Pisi Error")
            errorMessage = unicode(i18n("File <b>%s</b> doesn't exists.")) % package
        elif "ALREADY RUNNING" in message:
            errorTitle = i18n("Pisi Error")
            errorMessage = i18n("Another instance of PiSi is running. Only one instance is allowed.")
        else:
            errorTitle = i18n("Pisi Error")
            errorMessage = message

        self.messageBox = QMessageBox(errorTitle, errorMessage, QMessageBox.Critical, QMessageBox.Ok, 0, 0)

        if block:
            self.messageBox.exec_()
            self.runPostExceptionMethods()
        else:
            QTimer.singleShot(0, self.messageBox.exec_)
            self.messageBox.buttonClicked.connect(self.runPostExceptionMethods)
Exemplo n.º 5
0
    def _call_cb(self, callback, found, text, flags, caller):
        """Call the given callback if it's non-None.

        Delays the call via a QTimer so the website is re-rendered in between.

        Args:
            callback: What to call
            found: If the text was found
            text: The text searched for
            flags: The flags searched with
            caller: Name of the caller.
        """
        found_text = 'found' if found else "didn't find"
        # Removing FindWrapsAroundDocument to get the same logging as with
        # QtWebEngine
        debug_flags = debug.qflags_key(
            QWebPage, flags & ~QWebPage.FindWrapsAroundDocument,
            klass=QWebPage.FindFlag)
        if debug_flags != '0x0000':
            flag_text = 'with flags {}'.format(debug_flags)
        else:
            flag_text = ''
        log.webview.debug(' '.join([caller, found_text, text, flag_text])
                          .strip())
        if callback is not None:
            QTimer.singleShot(0, functools.partial(callback, found))
Exemplo n.º 6
0
 def __send(self, fx, lang, fn, data):
     """
     Private method to send a job request to one of the clients.
     
     @param fx remote function name to execute (str)
     @param lang language to connect to (str)
     @param fn filename for identification (str)
     @param data function argument(s) (any basic datatype)
     """
     connection = self.connections.get(lang)
     if connection is None:
         if fx != 'INIT':
             # Avoid growing recursion deep which could itself result in an
             # exception
             QTimer.singleShot(
                 0,
                 lambda: self.serviceNotAvailable.emit(
                     fx, lang, fn, self.tr(
                         '{0} not configured.').format(lang)))
         # Reset flag and continue processing queue
         self.isWorking = None
         self.__processQueue()
     else:
         packedData = json.dumps([fx, fn, data])
         if sys.version_info[0] == 3:
             packedData = bytes(packedData, 'utf-8')
         header = struct.pack(
             b'!II', len(packedData), adler32(packedData) & 0xffffffff)
         connection.write(header)
         connection.write(packedData)
Exemplo n.º 7
0
 def on_newConnection(self):
     """
     Private slot for new incomming connections from the clients.
     """
     connection = self.nextPendingConnection()
     if not connection.waitForReadyRead(1000):
         return
     lang = connection.read(64)
     if sys.version_info[0] == 3:
         lang = lang.decode('utf-8')
     # Avoid hanging of eric on shutdown
     if self.connections.get(lang):
         self.connections[lang].close()
     if self.isWorking == lang:
         self.isWorking = None
     self.connections[lang] = connection
     connection.readyRead.connect(
         lambda x=lang: self.__receive(x))
     connection.disconnected.connect(
         lambda x=lang: self.on_disconnectSocket(x))
         
     for (fx, lng), args in self.services.items():
         if lng == lang:
             # Register service with modulepath and module
             self.enqueueRequest('INIT', lng, fx, args[:2])
     
     # Syntax check the open editors again
     try:
         vm = e5App().getObject("ViewManager")
     except KeyError:
         return
     for editor in vm.getOpenEditors():
         if editor.getLanguage() == lang:
             QTimer.singleShot(0, editor.checkSyntax)
Exemplo n.º 8
0
 def mouseMoveEvent(self, evt):
     """
     Protected method to handle mouse move events.
     
     @param evt reference to the mouse move event (QMouseEvent)
     """
     if self.count() == 1:
         return
     
     E5WheelTabBar.mouseMoveEvent(self, evt)
     
     if Preferences.getHelp("ShowPreview"):
         # Find the tab under the mouse
         i = 0
         tabIndex = -1
         while i < self.count() and tabIndex == -1:
             if self.tabRect(i).contains(evt.pos()):
                 tabIndex = i
             i += 1
         
         # If found and not the current tab then show tab preview
         if tabIndex != -1 and \
            tabIndex != self.currentIndex() and \
            self.__currentTabPreviewIndex != tabIndex and \
            evt.buttons() == Qt.NoButton:
             self.__currentTabPreviewIndex = tabIndex
             QTimer.singleShot(200, self.__showTabPreview)
         
         # If current tab or not found then hide previous tab preview
         if tabIndex == self.currentIndex() or \
            tabIndex == -1:
             if self.__previewPopup is not None:
                 self.__previewPopup.hide()
             self.__currentTabPreviewIndex = -1
Exemplo n.º 9
0
    def search(self, text, flags):
        """Search for text in the current page.

        Args:
            text: The text to search for.
            flags: The QWebPage::FindFlags.
        """
        log.webview.debug("Searching with text '{}' and flags "
                          "0x{:04x}.".format(text, int(flags)))
        widget = self.currentWidget()
        old_scroll_pos = widget.scroll_pos
        found = widget.findText(text, flags)
        if not found and not flags & QWebPage.HighlightAllOccurrences and text:
            message.error(self._win_id, "Text '{}' not found on "
                          "page!".format(text), immediately=True)
        else:
            backward = int(flags) & QWebPage.FindBackward

            def check_scroll_pos():
                """Check if the scroll position got smaller and show info."""
                if not backward and widget.scroll_pos < old_scroll_pos:
                    message.info(self._win_id, "Search hit BOTTOM, continuing "
                                 "at TOP", immediately=True)
                elif backward and widget.scroll_pos > old_scroll_pos:
                    message.info(self._win_id, "Search hit TOP, continuing at "
                                 "BOTTOM", immediately=True)
            # We first want QWebPage to refresh.
            QTimer.singleShot(0, check_scroll_pos)
Exemplo n.º 10
0
 def __finish(self):
     """
     Private slot called when the process finished or the user pressed
     the button.
     """
     if self.process is not None and \
        self.process.state() != QProcess.NotRunning:
         self.process.terminate()
         QTimer.singleShot(2000, self.process.kill)
         self.process.waitForFinished(3000)
     
     self.buttonBox.button(QDialogButtonBox.Close).setEnabled(True)
     self.buttonBox.button(QDialogButtonBox.Cancel).setEnabled(False)
     self.buttonBox.button(QDialogButtonBox.Close).setDefault(True)
     
     self.inputGroup.setEnabled(False)
     self.inputGroup.hide()
     
     if len(self.changeListsDict) == 0:
         self.changeLists.addItem(self.tr("No changelists found"))
         self.buttonBox.button(QDialogButtonBox.Close).setFocus(
             Qt.OtherFocusReason)
     else:
         self.changeLists.addItems(sorted(self.changeListsDict.keys()))
         self.changeLists.setCurrentRow(0)
         self.changeLists.setFocus(Qt.OtherFocusReason)
Exemplo n.º 11
0
    def __init__(self, filepath=None):
        QObject.__init__(self)
        QTimer.singleShot(0, self.__launchTimerTimedOut)
        self.prefs = Preferences()
        self.prefs.load()
        global APP_PREFS
        APP_PREFS = self.prefs
        locale = QLocale.system()
        dateFormat = self.prefs.dateFormat
        decimalSep = locale.decimalPoint()
        groupingSep = locale.groupSeparator()
        cachePath = QStandardPaths.standardLocations(QStandardPaths.CacheLocation)[0]
        DateEdit.DATE_FORMAT = dateFormat
        self.model = MoneyGuruModel(
            view=self, date_format=dateFormat, decimal_sep=decimalSep,
            grouping_sep=groupingSep, cache_path=cachePath
        )
        self.mainWindow = MainWindow(app=self)
        self.preferencesPanel = PreferencesPanel(self.mainWindow, app=self)
        self.aboutBox = AboutBox(self.mainWindow, self)
        self.initialFilePath = None
        if filepath and op.exists(filepath):
            self.initialFilePath = filepath
        elif self.prefs.recentDocuments:
            self.initialFilePath = self.prefs.recentDocuments[0]

        self.finishedLaunching.connect(self.applicationFinishedLaunching)
        QCoreApplication.instance().aboutToQuit.connect(self.applicationWillTerminate)
Exemplo n.º 12
0
    def load(self, name, temp=False):
        """Load a named session.

        Args:
            name: The name of the session to load.
            temp: If given, don't set the current session.
        """
        path = self._get_session_path(name, check_exists=True)
        try:
            with open(path, encoding='utf-8') as f:
                data = yaml.load(f, Loader=YamlLoader)
        except (OSError, UnicodeDecodeError, yaml.YAMLError) as e:
            raise SessionError(e)
        log.sessions.debug("Loading session {} from {}...".format(name, path))
        for win in data['windows']:
            window = mainwindow.MainWindow(geometry=win['geometry'])
            window.show()
            tabbed_browser = objreg.get('tabbed-browser', scope='window',
                                        window=window.win_id)
            tab_to_focus = None
            for i, tab in enumerate(win['tabs']):
                new_tab = tabbed_browser.tabopen()
                self._load_tab(new_tab, tab)
                if tab.get('active', False):
                    tab_to_focus = i
            if tab_to_focus is not None:
                tabbed_browser.setCurrentIndex(tab_to_focus)
            if win.get('active', False):
                QTimer.singleShot(0, tabbed_browser.activateWindow)
        self.did_load = True
        if not name.startswith('_') and not temp:
            self._current = name
Exemplo n.º 13
0
    def newScreenshot(self):
        if self.hideThisWindowCheckBox.isChecked():
            self.hide()
        self.newScreenshotButton.setDisabled(True)

        QTimer.singleShot(self.delaySpinBox.value() * 1000,
                self.shootScreen)
Exemplo n.º 14
0
 def __init__(self):
     """
     Constructor
     """
     super(SnapshotFreehandGrabber, self).__init__(
         None,
         Qt.X11BypassWindowManagerHint | Qt.WindowStaysOnTopHint |
         Qt.FramelessWindowHint | Qt.Tool)
     
     self.__selection = QPolygon()
     self.__mouseDown = False
     self.__newSelection = False
     self.__handleSize = 10
     self.__showHelp = True
     self.__grabbing = False
     self.__dragStartPoint = QPoint()
     self.__selectionBeforeDrag = QPolygon()
     self.__locale = QLocale()
     
     self.__helpTextRect = QRect()
     self.__helpText = self.tr(
         "Select a region using the mouse. To take the snapshot,"
         " press the Enter key or double click. Press Esc to quit.")
     
     self.__pixmap = QPixmap()
     self.__pBefore = QPoint()
     
     self.setMouseTracking(True)
     
     QTimer.singleShot(200, self.__initialize)
Exemplo n.º 15
0
 def __finish(self):
     """
     Private slot called when the process finished or the user pressed
     the button.
     """
     if self.process is not None and \
        self.process.state() != QProcess.NotRunning:
         self.process.terminate()
         QTimer.singleShot(2000, self.process.kill)
         self.process.waitForFinished(3000)
     
     self.inputGroup.setEnabled(False)
     self.inputGroup.hide()
     
     self.buttonBox.button(QDialogButtonBox.Close).setEnabled(True)
     self.buttonBox.button(QDialogButtonBox.Cancel).setEnabled(False)
     self.buttonBox.button(QDialogButtonBox.Close).setDefault(True)
     self.buttonBox.button(QDialogButtonBox.Close).setFocus(
         Qt.OtherFocusReason)
     
     if self.patchesList.topLevelItemCount() == 0:
         # no patches present
         self.__generateItem(
             0, "", self.tr("no patches found"), "", True)
     self.__resizeColumns()
     self.__resort()
Exemplo n.º 16
0
    def _setup(self):
        core.pe.photo.PLAT_SPECIFIC_PHOTO_CLASS = PlatSpecificPhoto
        self._setupActions()
        self._update_options()
        self.recentResults = Recent(self, 'recentResults')
        self.recentResults.mustOpenItem.connect(self.model.load_from)
        self.resultWindow = None
        self.details_dialog = None
        self.directories_dialog = DirectoriesDialog(self)
        self.progress_window = ProgressWindow(self.directories_dialog, self.model.progress_window)
        self.problemDialog = ProblemDialog(parent=self.directories_dialog, model=self.model.problem_dialog)
        self.ignoreListDialog = IgnoreListDialog(parent=self.directories_dialog, model=self.model.ignore_list_dialog)
        self.deletionOptions = DeletionOptions(parent=self.directories_dialog, model=self.model.deletion_options)
        self.about_box = AboutBox(self.directories_dialog, self)

        self.directories_dialog.show()
        self.model.load()

        self.SIGTERM.connect(self.handleSIGTERM)

        # The timer scheme is because if the nag is not shown before the application is
        # completely initialized, the nag will be shown before the app shows up in the task bar
        # In some circumstances, the nag is hidden by other window, which may make the user think
        # that the application haven't launched.
        QTimer.singleShot(0, self.finishedLaunching)
Exemplo n.º 17
0
    def execute(self):
        if not self.timer.isActive() or self.is_date_changed:
            QTimer.singleShot(500, self.setTime)
            self.timer.stop()

        index = self.ui.countryList.currentIndex()
        ctx.installData.timezone = self.ui.countryList.itemData(index)
        ctx.logger.debug("Time zone selected as %s " % ctx.installData.timezone)

        if ctx.flags.install_type == ctx.STEP_BASE:
            #FIXME:Refactor hacky code
            ctx.installData.rootPassword = ctx.consts.default_password
            ctx.installData.hostName = yali.util.product_release()
            if ctx.storageInitialized:
                disks = filter(lambda d: not d.format.hidden, ctx.storage.disks)
                if len(disks) == 1:
                    ctx.storage.clearPartDisks = [disks[0].name]
                    ctx.mainScreen.step_increment = 2
                else:
                    ctx.mainScreen.step_increment = 1
                return True
            else:
                self.pds_messagebox.setMessage(_("Storage Devices initialising..."))
                self.pds_messagebox.animate(start=MIDCENTER, stop=MIDCENTER)
                ctx.mainScreen.step_increment = 0
                self.pthread.start()
                QTimer.singleShot(2, self.startStorageInitialize)
                return False

        return True
Exemplo n.º 18
0
    def _click(self, elem, context):
        """Click an element.

        Args:
            elem: The QWebElement to click.
            context: The HintContext to use.
        """
        target_mapping = {
            Target.normal: usertypes.ClickTarget.normal,
            Target.current: usertypes.ClickTarget.normal,
            Target.tab_fg: usertypes.ClickTarget.tab,
            Target.tab_bg: usertypes.ClickTarget.tab_bg,
            Target.window: usertypes.ClickTarget.window,
            Target.hover: usertypes.ClickTarget.normal,
        }
        if config.get('tabs', 'background-tabs'):
            target_mapping[Target.tab] = usertypes.ClickTarget.tab_bg
        else:
            target_mapping[Target.tab] = usertypes.ClickTarget.tab
        # FIXME Instead of clicking the center, we could have nicer heuristics.
        # e.g. parse (-webkit-)border-radius correctly and click text fields at
        # the bottom right, and everything else on the top left or so.
        # https://github.com/The-Compiler/qutebrowser/issues/70
        pos = elem.rect_on_view().center()
        action = "Hovering" if context.target == Target.hover else "Clicking"
        log.hints.debug("{} on '{}' at {}/{}".format(
            action, elem, pos.x(), pos.y()))
        self.start_hinting.emit(target_mapping[context.target])
        if context.target in [Target.tab, Target.tab_fg, Target.tab_bg,
                              Target.window]:
            modifiers = Qt.ControlModifier
        else:
            modifiers = Qt.NoModifier
        events = [
            QMouseEvent(QEvent.MouseMove, pos, Qt.NoButton, Qt.NoButton,
                        Qt.NoModifier),
        ]
        if context.target != Target.hover:
            events += [
                QMouseEvent(QEvent.MouseButtonPress, pos, Qt.LeftButton,
                            Qt.LeftButton, modifiers),
                QMouseEvent(QEvent.MouseButtonRelease, pos, Qt.LeftButton,
                            Qt.NoButton, modifiers),
            ]

        if context.target in [Target.normal, Target.current]:
            # Set the pre-jump mark ', so we can jump back here after following
            tabbed_browser = objreg.get('tabbed-browser', scope='window',
                                        window=self._win_id)
            tabbed_browser.set_mark("'")

        if context.target == Target.current:
            elem.remove_blank_target()
        for evt in events:
            self.mouse_event.emit(evt)
        if elem.is_text_input() and elem.is_editable():
            QTimer.singleShot(0, functools.partial(
                elem.webFrame().page().triggerAction,
                QWebPage.MoveToEndOfDocument))
        QTimer.singleShot(0, self.stop_hinting.emit)
Exemplo n.º 19
0
def startShellGui(workflow_cmdline_args, preinit_funcs, postinit_funcs):
    """
    Create an application and launch the shell in it.
    """

    """
    The next two lines fix the following xcb error on Ubuntu by calling X11InitThreads before loading the QApplication:
       [xcb] Unknown request in queue while dequeuing
       [xcb] Most likely this is a multi-threaded client and XInitThreads has not been called
       [xcb] Aborting, sorry about that.
       python: ../../src/xcb_io.c:178: dequeue_pending_request: Assertion !xcb_xlib_unknown_req_in_deq failed.
    """
    platform_str = platform.platform().lower()
    if 'ubuntu' in platform_str or 'fedora' in platform_str or 'debian' in platform_str:
        QApplication.setAttribute(Qt.AA_X11InitThreads, True)

    if ilastik.config.cfg.getboolean("ilastik", "debug"):
        QApplication.setAttribute(Qt.AA_DontUseNativeMenuBar, True)

    app = QApplication([])
    _applyStyleSheet(app)

    splashScreen.showSplashScreen()
    app.processEvents()
    QTimer.singleShot( 0, functools.partial(launchShell, workflow_cmdline_args, preinit_funcs, postinit_funcs ) )
    QTimer.singleShot( 0, splashScreen.hideSplashScreen)

    return app.exec_()
Exemplo n.º 20
0
    def slot_handlePatchbayClientAddedCallback(self, clientId, clientIcon, pluginId, clientName):
        pcSplit = patchcanvas.SPLIT_UNDEF
        pcIcon  = patchcanvas.ICON_APPLICATION

        if clientIcon == PATCHBAY_ICON_PLUGIN:
            pcIcon = patchcanvas.ICON_PLUGIN
        if clientIcon == PATCHBAY_ICON_HARDWARE:
            pcIcon = patchcanvas.ICON_HARDWARE
        elif clientIcon == PATCHBAY_ICON_CARLA:
            pass
        elif clientIcon == PATCHBAY_ICON_DISTRHO:
            pcIcon = patchcanvas.ICON_DISTRHO
        elif clientIcon == PATCHBAY_ICON_FILE:
            pcIcon = patchcanvas.ICON_FILE

        patchcanvas.addGroup(clientId, clientName, pcSplit, pcIcon)

        QTimer.singleShot(0, self.fMiniCanvasPreview.update)

        if pluginId < 0:
            return
        if pluginId >= self.fPluginCount:
            print("sorry, can't map this plugin to canvas client", pluginId, self.fPluginCount)
            return

        patchcanvas.setGroupAsPlugin(clientId, pluginId, bool(self.host.get_plugin_info(pluginId)['hints'] & PLUGIN_HAS_CUSTOM_UI))
Exemplo n.º 21
0
    def loadSettings(self, firstTime):
        qsettings   = QSettings()
        websettings = self.ui.webview.settings()

        self.fSavedSettings = {
            # WebView
            MOD_KEY_WEBVIEW_INSPECTOR:      qsettings.value(MOD_KEY_WEBVIEW_INSPECTOR,      MOD_DEFAULT_WEBVIEW_INSPECTOR,      type=bool),
            MOD_KEY_WEBVIEW_SHOW_INSPECTOR: qsettings.value(MOD_KEY_WEBVIEW_SHOW_INSPECTOR, MOD_DEFAULT_WEBVIEW_SHOW_INSPECTOR, type=bool)
        }

        inspectorEnabled = self.fSavedSettings[MOD_KEY_WEBVIEW_INSPECTOR] and not USING_LIVE_ISO

        websettings.setAttribute(QWebSettings.DeveloperExtrasEnabled, inspectorEnabled)

        if firstTime:
            self.restoreGeometry(qsettings.value("Geometry", ""))

            if inspectorEnabled and self.fSavedSettings[MOD_KEY_WEBVIEW_SHOW_INSPECTOR]:
                QTimer.singleShot(1000, self.ui.webinspector.show)

        self.ui.act_file_inspect.setVisible(inspectorEnabled)

        if self.fIdleTimerId != 0:
            self.killTimer(self.fIdleTimerId)

        self.fIdleTimerId = self.startTimer(MOD_DEFAULT_MAIN_REFRESH_INTERVAL)
            def cb_import_extract(result):
                script_instance = script_instance_ref[0]

                if script_instance != None:
                    aborted = script_instance.abort
                else:
                    aborted = False

                script_instance_ref[0] = None

                if aborted:
                    return

                if not report_script_result(result, 'Import Error', 'Could not extract archive',
                                            before_message_box=self.progress.close):
                    return

                def cb_restart_reboot_shutdown(result):
                    self.progress.close()

                    report_script_result(result, 'Import Error', 'Could not reboot RED Brick to finish program import')

                # step 4/4: reboot
                self.progress.setLabelText('Step 4 of 4: Rebooting RED Brick')
                self.progress.setRange(0, 0)

                self.script_manager.execute_script('restart_reboot_shutdown_systemd',
                                                   cb_restart_reboot_shutdown, ['1'])

                def close_progress():
                    # use a closure to capture self and ansure that it's safe
                    # to call this even if the tab was official destroyed already
                    self.progress.close()

                QTimer.singleShot(1500, close_progress)
Exemplo n.º 23
0
    def play(self, fromStart=True, force=False):
        item = self.targetObject()

        # If the item that this animation controls in currently under the
        # control of another animation, stop that animation first.
        if item.currentAnimation is not None:
            item.currentAnimation.stop()

        item.currentAnimation = self

        if Colors.noAnimations and not force:
            # If animations are disabled just move to the end position.
            item.setPos(self.endValue())
        else:
            if self.isVisible():
                # If the item is already visible, start the animation from the
                # item's current position rather than from the start.
                self.setStartValue(item.pos())

            if fromStart:
                self.setCurrentTime(0)
                item.setPos(self.startValue())

        if self._inOrOut == DemoItemAnimation.ANIM_IN:
            item.setRecursiveVisible(True)

        if not Colors.noAnimations or force:
            if self._startDelay:
                QTimer.singleShot(self._startDelay, self.start)
            else:
                self.start()
Exemplo n.º 24
0
    def show_alert(self, title, text, urgency = None, force = False,
                   buttons = None):

        # NOTE: there is no support for buttons via QSystemTrayIcon.

        if ((title, text) == self.last_alert) and not force:
            return

        def _action_activate_cb(action_num):
            if not buttons:
                return

            try:
                action_info = buttons[action_num - 1]
            except IndexError:
                return

            _action_id, _button_name, button_callback = action_info
            button_callback()

        def do_show():
            if not self._window.supportsMessages():
                const_debug_write("show_alert", "messages not supported.")
                return

            icon_id = QSystemTrayIcon.Information
            if urgency == "critical":
                icon_id = QSystemTrayIcon.Critical

            self._window.showMessage(title, text, icon_id)
            self.last_alert = (title, text)

        QTimer.singleShot(0, do_show)
Exemplo n.º 25
0
    def extract(self, location: Location, directory_watcher, stdio) -> Optional[ArchiveExtractor]:
        extractor = self._extractors.get(location, None)
        if extractor is not None:
            return extractor  # extraction already running or queued

        outdir = self._make_extractor_outdir(location)

        if not os.path.isdir(outdir):
            extractor = ArchiveExtractor(stdio.get_stdio_name(location.origin()), outdir)
            self._extractors[location] = extractor
            extractor.sig_started.connect(lambda extractor:
                                          self._on_archive_extractor_started(extractor))
            extractor.sig_finished.connect(lambda extractor, d=directory_watcher:
                                           self._on_archive_extractor_finished(extractor, d))

            if self.get_running_extractor_count() < self._max_extractors:
                extractor.start()
            else:
                self._queued_extractors.append(extractor)

            return extractor
        else:
            status_file = os.path.join(outdir, "status.json")
            status = ExtractorStatus.from_file(status_file)

            if status.status() == ExtractorResult.FAILURE:
                def send_message(dw=directory_watcher, message=status.message()):
                    dw.sig_message.emit(status.message())

                # FIXME: this is a bit of a crude hack to
                # communicate the message to the user
                QTimer.singleShot(0, send_message)
                logger.error("%s: archive exist, but is broken: %s", location, status.message())

            return None
Exemplo n.º 26
0
    def handlelink(self, url):
        urlstr = url.toString()
        log("handling link : %s" % urlstr)
        #check if url is for the current page
        if url.matches(self.url(), QUrl.RemoveFragment):
            #do nothing, probably a JS link
            return True

        #check other windows to see if url is loaded there
        for window in self.parent.windows:
            if url.matches(window.url(), QUrl.RemoveFragment):
                window.raise_()
                window.activateWindow()
                #if this is a tree window and not the main one, close it
                if self.url().toString().startswith(self.parent.homepage + "/tree") and not self.main:
                    QTimer.singleShot(0, self.close) #calling self.close() is no good
                return True

        if "/files/" in urlstr:
            #save, don't load new page
            self.parent.savefile(url)
        elif "/tree/" in urlstr or urlstr.startswith(self.parent.homepage + "/tree"):
            #keep in same window
            self.load(url)
        else:
            #open in new window
            newwindow = self.createWindow(QWebPage.WebBrowserWindow, js=False)
            newwindow.load(url)

            #if this is a tree window and not the main one, close it
        if self.url().toString().startswith(self.parent.homepage + "/tree") and not self.main:
            QTimer.singleShot(0, self.close) #calling self.close() is no good
        return True
Exemplo n.º 27
0
def main() -> None:
    signal.signal(signal.SIGINT, signal.SIG_DFL)
    app = QCoreApplication([])

    testo = Testo()

    # This is causing the problem
    def a() -> None:
        # Using 'app' in a local function seems to be what requires
        # the manual 'del app' call, otherwise the garbage collector
        # needs to do the cleanup and probably comes to late, as
        # another QCoreApplication instance might have already been
        # created.
        print(app)

    # As long as the function isn't using 'app' everything seems to be
    # ok.
    def b() -> None:
        print("nothing")

    # If 'b' is used instead of 'a' the problem goes away
    testo.sig_test.connect(a)

    QTimer.singleShot(1000, app.quit)

    print("exec")
    app.exec()
    print("exec:done")
Exemplo n.º 28
0
    def test_collector(self):
        app = QApplication([])

        try:
            vfs = StdioFilesystem("/tmp")
            metadata_collector = MetaDataCollector(vfs)

            def on_metadata(filename, metadata):
                print(filename)
                print(metadata)
                print()

            metadata_collector.sig_metadata_ready.connect(on_metadata)

            metadata_collector.request_metadata(Location.from_path("dirtools/fileview/icons/noun_409399_cc.png"))

            QTimer.singleShot(500, metadata_collector.close)
            QTimer.singleShot(1500, app.quit)

            app.exec()
        except Exception as err:
            print(err)
        finally:
            metadata_collector.close()
            vfs.close()
Exemplo n.º 29
0
 def on_current_changed(self, idx):
     """Set last-focused-tab and leave hinting mode when focus changed."""
     if idx == -1 or self._shutting_down:
         # closing the last tab (before quitting) or shutting down
         return
     tab = self.widget(idx)
     log.modes.debug("Current tab changed, focusing {!r}".format(tab))
     tab.setFocus()
     for mode in (usertypes.KeyMode.hint, usertypes.KeyMode.insert,
                  usertypes.KeyMode.caret, usertypes.KeyMode.passthrough):
         modeman.maybe_leave(self._win_id, mode, 'tab changed')
     if self._now_focused is not None:
         objreg.register('last-focused-tab', self._now_focused, update=True,
                         scope='window', window=self._win_id)
     ai = False
     for r in pt_masks:
         if re.match(r, tab.url().host()) is not None:
             ai = True
             break
     if ai:
         modeman.enter(self._win_id, usertypes.KeyMode.passthrough,
                       'load finished', only_if_normal=True)
     self._now_focused = tab
     self.current_tab_changed.emit(tab)
     QTimer.singleShot(0, self.update_window_title)
     self._tab_insert_idx_left = self.currentIndex()
     self._tab_insert_idx_right = self.currentIndex() + 1
Exemplo n.º 30
0
    def cancel(self):
        self.widget.hide()
        self.busy.show()

        self.actionLabel.setText(i18n("<b>Cancelling operation...</b>"))
        self.disableCancel()
        QTimer.singleShot(100, self.iface.cancel)
Exemplo n.º 31
0
    def __init__(self, win_id, parent=None):
        super().__init__(parent)
        objreg.register('statusbar', self, scope='window', window=win_id)
        self.setObjectName(self.__class__.__name__)
        self.setAttribute(Qt.WA_StyledBackground)
        style.set_register_stylesheet(self)

        self.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Fixed)

        self._win_id = win_id
        self._option = None
        self._stopwatch = QTime()

        self._hbox = QHBoxLayout(self)
        self.set_hbox_padding()
        objreg.get('config').changed.connect(self.set_hbox_padding)
        self._hbox.setSpacing(5)

        self._stack = QStackedLayout()
        self._hbox.addLayout(self._stack)
        self._stack.setContentsMargins(0, 0, 0, 0)

        self.cmd = command.Command(win_id)
        self._stack.addWidget(self.cmd)
        objreg.register('status-command',
                        self.cmd,
                        scope='window',
                        window=win_id)

        self.txt = textwidget.Text()
        self._stack.addWidget(self.txt)
        self._timer_was_active = False
        self._text_queue = collections.deque()
        self._text_pop_timer = usertypes.Timer(self, 'statusbar_text_pop')
        self._text_pop_timer.timeout.connect(self._pop_text)
        self.set_pop_timer_interval()
        objreg.get('config').changed.connect(self.set_pop_timer_interval)

        self.prompt = prompt.Prompt(win_id)
        self._stack.addWidget(self.prompt)
        self._previous_widget = PreviousWidget.none

        self.cmd.show_cmd.connect(self._show_cmd_widget)
        self.cmd.hide_cmd.connect(self._hide_cmd_widget)
        self._hide_cmd_widget()
        prompter = objreg.get('prompter', scope='window', window=self._win_id)
        prompter.show_prompt.connect(self._show_prompt_widget)
        prompter.hide_prompt.connect(self._hide_prompt_widget)
        self._hide_prompt_widget()

        self.keystring = keystring.KeyString()
        self._hbox.addWidget(self.keystring)

        self.url = url.UrlText()
        self._hbox.addWidget(self.url)

        self.percentage = percentage.Percentage()
        self._hbox.addWidget(self.percentage)

        self.tabindex = tabindex.TabIndex()
        self._hbox.addWidget(self.tabindex)

        # We add a parent to Progress here because it calls self.show() based
        # on some signals, and if that happens before it's added to the layout,
        # it will quickly blink up as independent window.
        self.prog = progress.Progress(self)
        self._hbox.addWidget(self.prog)

        objreg.get('config').changed.connect(self.maybe_hide)
        QTimer.singleShot(0, self.maybe_hide)
Exemplo n.º 32
0
    def __init__(self):
        super(MainWindow, self).__init__()
        self.ui = loadUi(join(execPath, "../share/imblproc/imbl-bct.ui"), self)
        self.ui.tabWidget.tabBar().setExpanding(True)
        for errLabel in self.ui.findChildren(QtWidgets.QLabel, QtCore.QRegExp("^err\\w+")):
            self.showWdg(errLabel, False)
        self.ui.distanceR.addItems(list(distances))
        self.ui.energyR.addItems(list(energies))
        self.proc.setProgram("/bin/bash")

        if isdir(dataPath) :
            selection = self.ui.expSelect
            selection.setEnabled(False)
            selection.clear()
            selection.addItem("Loading...")
            self.update()
            QtCore.QCoreApplication.processEvents()
            for name in sorted(os.listdir(dataPath)) :
                expPath = join(dataPath, name)
                if isdir(join(expPath, "input")):
                    selection.addItem(name, expPath)
            selection.removeItem(0) # Loading...
            if selection.count() :
                selection.setEnabled(True)
            else :
                selection.addItem("<none>")

        self.configObjects = (
            self.ui.outAuto,
            self.ui.expPath,
            self.ui.inPath,
            self.ui.outPath,
            self.ui.trimL,
            self.ui.trimR,
            self.ui.trimT,
            self.ui.trimB,
            self.ui.energyR,
            self.ui.distanceR,
            self.ui.ring,
            self.ui.autoCor,
            self.ui.cor,
            self.ui.set1,
            self.ui.set2,
            self.ui.set4 )
        for swdg in self.configObjects:
            if isinstance(swdg, QtWidgets.QLineEdit):
                swdg.textChanged.connect(self.saveConfiguration)
            elif isinstance(swdg, QtWidgets.QCheckBox):
                swdg.toggled.connect(self.saveConfiguration)
            elif isinstance(swdg, QtWidgets.QAbstractSpinBox):
                swdg.valueChanged.connect(self.saveConfiguration)
            elif isinstance(swdg, QtWidgets.QComboBox):
                swdg.currentTextChanged.connect(self.saveConfiguration)

        def onBrowse(target, lineEdit):
            newPath = QFileDialog.getExistingDirectory(self, target + " directory", lineEdit.text())
            setVText(lineEdit, newPath, str)
        def onSelect(lineEdit):
            newPath = self.sender().currentData()
            setVText(lineEdit, newPath, str)
        self.ui.expBrowse.clicked.connect(lambda: onBrowse("Experiment", self.ui.expPath))
        self.ui.expSelect.activated.connect(lambda: onSelect(self.ui.expPath))
        self.ui.expPath.textChanged.connect(self.onNewExperiment)
        self.ui.inBrowse.clicked.connect(lambda: onBrowse("Sample input", self.ui.inPath))
        self.ui.inSelect.activated.connect(lambda: onSelect(self.ui.inPath))
        self.ui.inPath.textChanged.connect(lambda: (self.onNewSample(), self.setOutPath()))
        self.ui.outBrowse.clicked.connect(lambda: onBrowse("Sample output", self.ui.outPath))
        self.ui.outAuto.toggled.connect(self.setOutPath)
        self.ui.outPath.textChanged.connect(lambda: self.setOutPath(False))
        self.ui.ring.valueChanged[int].connect(lambda val:
            self.ui.ring.setStyleSheet("" if not val or val % 2 else badStyle))
        self.ui.goStitch.clicked.connect(self.onStitch)
        self.ui.testMe.clicked.connect(self.onRec)
        self.ui.goRec.clicked.connect(self.onRec)

        QtCore.QTimer.singleShot(100, self.loadConfiguration)
        QTimer.singleShot(0, (lambda: self.resize(self.minimumSizeHint())))
Exemplo n.º 33
0
 def showWdg(self, wdg, showme=True):
     wdg.setVisible(showme)
     QTimer.singleShot(0, (lambda: self.resize(self.minimumSizeHint())))
Exemplo n.º 34
0
    def __init__(self, parent=None):
        QDialog.__init__(self, parent)
        self.setWindowTitle('show_gif')
        self.setWindowIcon(QIcon('image/Capture_64px.png'))
        self.setWindowFlags(self.windowFlags() | Qt.WindowMinMaxButtonsHint)
        # self.resize(400,400)
        self.setFixedSize(800, 600)
        mainl = QVBoxLayout(self)
        self.labelShow = QLabel()
        self.labelShow.setContentsMargins(0, 0, 0, 0)
        pat = self.labelShow.palette()
        pat.setBrush(QPalette.Background, Qt.darkGray)
        self.labelShow.setAutoFillBackground(True)
        self.labelShow.setPalette(pat)
        self.labelShow.setAlignment(Qt.AlignCenter)
        # self.labelShow.setScaledContents(True)
        mainl.addWidget(self.labelShow, 1)
        line = QFrame()
        line.setFrameShape(QFrame.HLine)
        line.setFrameShadow(QFrame.Sunken)
        mainl.addWidget(line)
        btnLay = QHBoxLayout()

        frmLay = QFormLayout()
        self._spinBox = QSpinBox()
        frmLay.addRow('跳转:', self._spinBox)
        btnGo = QPushButton('Go', self)

        btnPrev = QPushButton('上一张', self)
        self.btnNext = QPushButton('下一张', self)
        btnPrev.clicked.connect(self.on_prev)
        self.btnNext.clicked.connect(self.on_next)
        btnGo.clicked.connect(lambda: self.flashMovie(self._spinBox.value()))
        self._spinBox.valueChanged.connect(lambda n: self.flashMovie(n))
        btnLay.addStretch()
        btnLay.addLayout(frmLay)
        btnLay.addWidget(btnGo)
        btnLay.addWidget(btnPrev)
        btnLay.addWidget(self.btnNext)
        btnLay.addStretch()
        mainl.addLayout(btnLay)

        labLay = QHBoxLayout()
        labLay.setSpacing(10)
        self._label = QLabel()
        frm1 = QFormLayout()
        frm1.addRow('共:', self._label)
        frm1.setRowWrapPolicy(QFormLayout.WrapLongRows)
        labLay.addStretch()
        labLay.addLayout(frm1)
        frm1 = QFormLayout()
        self._labInfo = QLabel()
        # self._labInfo.setWordWrap(True)
        frm1.addRow('当前:', self._labInfo)
        # frm1.setFieldGrowthPolicy(QFormLayout.ExpandingFieldsGrow)
        frm1.setRowWrapPolicy(QFormLayout.WrapLongRows)
        labLay.addLayout(frm1)
        frm1 = QFormLayout()
        self._labPlay = QLabel()
        frm1.addRow('播放帧号:', self._labPlay)
        labLay.addLayout(frm1)
        frm1.setRowWrapPolicy(QFormLayout.WrapLongRows)

        labLay.addStretch()
        labLay.setSpacing(10)
        line = QFrame()
        line.setFrameShape(QFrame.HLine)
        line.setFrameShadow(QFrame.Sunken)
        mainl.addWidget(line)
        mainl.addLayout(labLay)
        self._gifs = []
        self._movie = QMovie()
        self.labelShow.setMovie(self._movie)
        QTimer.singleShot(0, self.on_firstShow)
        self._picIndex = 0
        self._movie.frameChanged.connect(self.on_frameChange)
Exemplo n.º 35
0
    def __init__(self, parent, view1, view2, view3, view4=None):
        QWidget.__init__(self, parent)

        self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)

        self.installEventFilter(self)

        self.dockableContainer = []

        self.layout = QVBoxLayout()
        self.setLayout(self.layout)
        self.layout.setContentsMargins(0, 0, 0, 0)
        self.layout.setSpacing(0)

        self.splitVertical = QSplitter(Qt.Vertical, self)
        self.layout.addWidget(self.splitVertical)
        self.splitHorizontal1 = QSplitter(Qt.Horizontal, self.splitVertical)
        self.splitHorizontal1.setObjectName("splitter1")
        self.splitHorizontal2 = QSplitter(Qt.Horizontal, self.splitVertical)
        self.splitHorizontal2.setObjectName("splitter2")
        self.splitHorizontal1.splitterMoved.connect(
            self.horizontalSplitterMoved)
        self.splitHorizontal2.splitterMoved.connect(
            self.horizontalSplitterMoved)

        self.imageView2D_1 = view1

        self.imageView2D_2 = view2

        self.imageView2D_3 = view3

        self.dock1_ofSplitHorizontal1 = ImageView2DDockWidget(
            self.imageView2D_1)
        self.dock1_ofSplitHorizontal1.connectHud()
        self.dockableContainer.append(self.dock1_ofSplitHorizontal1)
        self.dock1_ofSplitHorizontal1.onDockButtonClicked.connect(
            lambda arg=self.dock1_ofSplitHorizontal1: self.on_dock(arg))
        self.dock1_ofSplitHorizontal1.onMaxButtonClicked.connect(
            lambda arg=self.dock1_ofSplitHorizontal1: self.on_max(arg))
        self.dock1_ofSplitHorizontal1.onMinButtonClicked.connect(
            lambda arg=self.dock1_ofSplitHorizontal1: self.on_min(arg))
        self.splitHorizontal1.addWidget(self.dock1_ofSplitHorizontal1)

        self.dock2_ofSplitHorizontal1 = ImageView2DDockWidget(
            self.imageView2D_2)
        self.dock2_ofSplitHorizontal1.onDockButtonClicked.connect(
            lambda arg=self.dock2_ofSplitHorizontal1: self.on_dock(arg))
        self.dock2_ofSplitHorizontal1.onMaxButtonClicked.connect(
            lambda arg=self.dock2_ofSplitHorizontal1: self.on_max(arg))
        self.dock2_ofSplitHorizontal1.onMinButtonClicked.connect(
            lambda arg=self.dock2_ofSplitHorizontal1: self.on_min(arg))
        self.dock2_ofSplitHorizontal1.connectHud()
        self.dockableContainer.append(self.dock2_ofSplitHorizontal1)
        self.splitHorizontal1.addWidget(self.dock2_ofSplitHorizontal1)

        self.dock1_ofSplitHorizontal2 = ImageView2DDockWidget(
            self.imageView2D_3)
        self.dock1_ofSplitHorizontal2.onDockButtonClicked.connect(
            lambda arg=self.dock1_ofSplitHorizontal2: self.on_dock(arg))
        self.dock1_ofSplitHorizontal2.onMaxButtonClicked.connect(
            lambda arg=self.dock1_ofSplitHorizontal2: self.on_max(arg))
        self.dock1_ofSplitHorizontal2.onMinButtonClicked.connect(
            lambda arg=self.dock1_ofSplitHorizontal2: self.on_min(arg))
        self.dock1_ofSplitHorizontal2.connectHud()
        self.dockableContainer.append(self.dock1_ofSplitHorizontal2)
        self.splitHorizontal2.addWidget(self.dock1_ofSplitHorizontal2)

        self.dock2_ofSplitHorizontal2 = ImageView2DDockWidget(view4)
        self.dockableContainer.append(self.dock2_ofSplitHorizontal2)
        self.splitHorizontal2.addWidget(self.dock2_ofSplitHorizontal2)

        # this is a hack: with 0 ms it does not work...
        QTimer.singleShot(250, self._resizeEqual)
Exemplo n.º 36
0
    def hgLfconvert(self, direction, projectFile):
        """
        Public slot to convert the repository format of the current project.
        
        @param direction direction of the conversion (string, one of
            'largefiles' or 'normal')
        @param projectFile file name of the current project file (string)
        """
        assert direction in ["largefiles", "normal"]

        projectDir = os.path.dirname(projectFile)

        # find the root of the repo
        repodir = projectDir
        while not os.path.isdir(os.path.join(repodir, self.vcs.adminDir)):
            repodir = os.path.dirname(repodir)
            if os.path.splitdrive(repodir)[1] == os.sep:
                return

        from .LfConvertDataDialog import LfConvertDataDialog
        dlg = LfConvertDataDialog(projectDir, direction)
        if dlg.exec_() == QDialog.Accepted:
            newName, minSize, patterns = dlg.getData()
            newProjectFile = os.path.join(newName,
                                          os.path.basename(projectFile))

            # step 1: convert the current project to new project
            args = self.vcs.initCommand("lfconvert")
            if direction == 'normal':
                args.append('--to-normal')
            else:
                args.append("--size")
                args.append(str(minSize))
            args.append(projectDir)
            args.append(newName)
            if direction == 'largefiles' and patterns:
                args.extend(patterns)

            dia = HgDialog(self.tr('Convert Project - Converting'), self.vcs)
            res = dia.startProcess(args, repodir)
            if res:
                dia.exec_()
                res = dia.normalExit() and os.path.isdir(
                    os.path.join(newName, self.vcs.adminDir))

            # step 2: create working directory contents
            if res:
                args = self.vcs.initCommand("update")
                args.append("--verbose")
                dia = HgDialog(self.tr('Convert Project - Extracting'),
                               self.vcs,
                               useClient=False)
                res = dia.startProcess(args, newName)
                if res:
                    dia.exec_()
                    res = dia.normalExit() and os.path.isfile(newProjectFile)

            # step 3: close current project and open new one
            if res:
                if direction == 'largefiles':
                    self.vcs.hgEditConfig(newName,
                                          largefilesData={
                                              "minsize": minSize,
                                              "pattern": patterns
                                          })
                else:
                    self.vcs.hgEditConfig(newName, withLargefiles=False)
                QTimer.singleShot(
                    0, lambda: e5App().getObject("Project").openProject(
                        newProjectFile))
Exemplo n.º 37
0
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)

        self.mdi = QMdiArea()
        self.setCentralWidget(self.mdi)

        fileNewAction = self.createAction("&New", self.fileNew,
                                          QKeySequence.New, "filenew",
                                          "Create a text file")
        fileOpenAction = self.createAction("&Open...", self.fileOpen,
                                           QKeySequence.Open, "fileopen",
                                           "Open an existing text file")
        fileSaveAction = self.createAction("&Save", self.fileSave,
                                           QKeySequence.Save, "filesave",
                                           "Save the text")
        fileSaveAsAction = self.createAction(
            "Save &As...",
            self.fileSaveAs,
            icon="filesaveas",
            tip="Save the text using a new filename")
        fileSaveAllAction = self.createAction("Save A&ll",
                                              self.fileSaveAll,
                                              "filesave",
                                              tip="Save all the files")
        fileQuitAction = self.createAction("&Quit", self.close, "Ctrl+Q",
                                           "filequit", "Close the application")
        editCopyAction = self.createAction("&Copy", self.editCopy,
                                           QKeySequence.Copy, "editcopy",
                                           "Copy text to the clipboard")
        editCutAction = self.createAction("Cu&t", self.editCut,
                                          QKeySequence.Cut, "editcut",
                                          "Cut text to the clipboard")
        editPasteAction = self.createAction("&Paste", self.editPaste,
                                            QKeySequence.Paste, "editpaste",
                                            "Paste in the clipboard's text")
        self.windowNextAction = self.createAction(
            "&Next", self.mdi.activateNextSubWindow, QKeySequence.NextChild)
        self.windowPrevAction = self.createAction(
            "&Previous", self.mdi.activatePreviousSubWindow,
            QKeySequence.PreviousChild)
        self.windowCascadeAction = self.createAction(
            "Casca&de", self.mdi.cascadeSubWindows)
        self.windowTileAction = self.createAction("&Tile",
                                                  self.mdi.tileSubWindows)
        self.windowRestoreAction = self.createAction("&Restore All",
                                                     self.windowRestoreAll)
        self.windowMinimizeAction = self.createAction("&Iconize All",
                                                      self.windowMinimizeAll)
        #self.windowArrangeIconsAction = self.createAction(
        #        "&Arrange Icons", self.mdi.arrangeIcons)
        self.windowArrangeIconsAction = self.createAction(
            "&Arrange Icons", self.windowMinimizeAll)
        self.windowCloseAction = self.createAction(
            "&Close", self.mdi.closeActiveSubWindow, QKeySequence.Close)
        self.windowMapper = QSignalMapper(self)
        self.windowMapper.mapped[QWidget].connect(self.mdi.setActiveSubWindow)
        fileMenu = self.menuBar().addMenu("&File")
        self.addActions(
            fileMenu,
            (fileNewAction, fileOpenAction, fileSaveAction, fileSaveAsAction,
             fileSaveAllAction, None, fileQuitAction))
        editMenu = self.menuBar().addMenu("&Edit")
        self.addActions(editMenu,
                        (editCopyAction, editCutAction, editPasteAction))
        self.windowMenu = self.menuBar().addMenu("&Window")
        self.windowMenu.aboutToShow.connect(self.updateWindowMenu)
        fileToolbar = self.addToolBar("File")
        fileToolbar.setObjectName("FileToolbar")
        self.addActions(fileToolbar,
                        (fileNewAction, fileOpenAction, fileSaveAction))
        editToolbar = self.addToolBar("Edit")
        editToolbar.setObjectName("EditToolbar")
        self.addActions(editToolbar,
                        (editCopyAction, editCutAction, editPasteAction))

        settings = QSettings()
        if settings.value("MainWindow/Geometry") or settings.value(
                "MainWindow/State"):
            self.restoreGeometry(
                QByteArray(settings.value("MainWindow/Geometry")))
            self.restoreState(QByteArray(settings.value("MainWindow/State")))

        status = self.statusBar()
        status.setSizeGripEnabled(False)
        status.showMessage("Ready", 5000)

        self.updateWindowMenu()
        self.setWindowTitle("Text Editor")
        QTimer.singleShot(0, self.loadFiles)
Exemplo n.º 38
0
 def _pop_later(self):
     """Helper to call self._pop as soon as everything else is done."""
     QTimer.singleShot(0, self._pop)
Exemplo n.º 39
0
    def __init__(self, geometry=None, parent=None):
        """Create a new main window.

        Args:
            geometry: The geometry to load, as a bytes-object (or None).
            parent: The parent the window should get.
        """
        super().__init__(parent)
        self.setAttribute(Qt.WA_DeleteOnClose)
        self._commandrunner = None
        self.win_id = next(win_id_gen)
        self.registry = objreg.ObjectRegistry()
        objreg.window_registry[self.win_id] = self
        objreg.register('main-window',
                        self,
                        scope='window',
                        window=self.win_id)
        tab_registry = objreg.ObjectRegistry()
        objreg.register('tab-registry',
                        tab_registry,
                        scope='window',
                        window=self.win_id)

        message_bridge = message.MessageBridge(self)
        objreg.register('message-bridge',
                        message_bridge,
                        scope='window',
                        window=self.win_id)

        self.setWindowTitle('qutebrowser')
        if geometry is not None:
            self._load_geometry(geometry)
        elif self.win_id == 0:
            self._load_state_geometry()
        else:
            self._set_default_geometry()
        log.init.debug("Initial main window geometry: {}".format(
            self.geometry()))
        self._vbox = QVBoxLayout(self)
        self._vbox.setContentsMargins(0, 0, 0, 0)
        self._vbox.setSpacing(0)

        log.init.debug("Initializing downloads...")
        download_manager = downloads.DownloadManager(self.win_id, self)
        objreg.register('download-manager',
                        download_manager,
                        scope='window',
                        window=self.win_id)

        self._downloadview = downloadview.DownloadView(self.win_id)

        self._tabbed_browser = tabbedbrowser.TabbedBrowser(self.win_id)
        objreg.register('tabbed-browser',
                        self._tabbed_browser,
                        scope='window',
                        window=self.win_id)

        # We need to set an explicit parent for StatusBar because it does some
        # show/hide magic immediately which would mean it'd show up as a
        # window.
        self.status = bar.StatusBar(self.win_id, parent=self)

        self._add_widgets()
        self._downloadview.show()

        self._completion = completionwidget.CompletionView(self.win_id, self)

        self._commandrunner = runners.CommandRunner(self.win_id)

        log.init.debug("Initializing modes...")
        modeman.init(self.win_id, self)

        self._connect_signals()

        # When we're here the statusbar might not even really exist yet, so
        # resizing will fail. Therefore, we use singleShot QTimers to make sure
        # we defer this until everything else is initialized.
        QTimer.singleShot(0, self._connect_resize_completion)
        objreg.get('config').changed.connect(self.on_config_changed)

        if config.get('ui', 'hide-mouse-cursor'):
            self.setCursor(Qt.BlankCursor)
Exemplo n.º 40
0
    def newScreenshot(self):
        if self.hideThisWindowCheckBox.isChecked():
            self.hide()
        self.newScreenshotButton.setDisabled(True)

        QTimer.singleShot(self.delaySpinBox.value() * 1000, self.shootScreen)
Exemplo n.º 41
0
 def set_timeout(self, timeout):
     """Hide the widget after the given timeout."""
     QTimer.singleShot(timeout, self._on_timeout)
Exemplo n.º 42
0
def call_later(interval, function, *args, **kw):
    QTimer.singleShot(int(interval * 1000), lambda: function(*args, **kw))
Exemplo n.º 43
0
 def SingleShotEscape(message_box):
     """aux function to close messagebox"""
     close_delay = 0  # [ms]
     QTimer.singleShot(close_delay,
                       lambda: QTest.keyClick(message_box, Qt.Key_Escape))
Exemplo n.º 44
0
    def create_objects(self):
        if not (self.isValid() and self.shareWidget.initialized):
            self.invalid_count += 1
            print(
                'ND: Context not valid in create_objects, or shareWidget not yet initialized'
            )
            QTimer.singleShot(100, self.create_objects)
            return

        # Make the nd widget context current, necessary when create_objects is not called from initializeGL
        self.makeCurrent()

        # Use the same font as the radarwidget
        self.font = self.shareWidget.font.copy()
        self.font.init_shader(self.text_shader)

        edge = np.zeros(120, dtype=np.float32)
        edge[0:120:2] = 1.4 * np.sin(np.radians(np.arange(-60, 60, 2)))
        edge[1:120:2] = 1.4 * np.cos(np.radians(np.arange(-60, 60, 2)))
        self.edge = RenderObject(gl.GL_LINE_STRIP, vertex=edge, color=white)

        arcs = []
        for i in range(1, 4):
            for angle in range(-60, 60, max(2, 6 - 2 * i)):
                arcs.append(float(i) * 0.35 * sin(radians(angle)))
                arcs.append(float(i) * 0.35 * cos(radians(angle)))
                if i == 4:
                    arcs.append(float(i) * 0.35 * sin(radians(angle + 2)))
                    arcs.append(float(i) * 0.35 * cos(radians(angle + 2)))
        arcs = np.array(arcs, dtype=np.float32)
        self.arcs = RenderObject(gl.GL_LINES, vertex=arcs, color=white)

        mask = []
        for angle in range(-60, 60, 2):
            mask.append(1.4 * sin(radians(angle)))
            mask.append(10.0)
            mask.append(1.4 * sin(radians(angle)))
            mask.append(1.4 * cos(radians(angle)))
        mask = np.array(mask, dtype=np.float32)
        self.mask = RenderObject(gl.GL_TRIANGLE_STRIP,
                                 vertex=mask,
                                 color=black)

        ticks = np.zeros(288, dtype=np.float32)
        for i in range(72):
            ticktop = 1.46 if i % 6 == 0 else (1.44 if i % 2 == 0 else 1.42)
            ticks[4 * i:4 * i + 2] = (1.4 * sin(radians(i * 5)),
                                      1.4 * cos(radians(i * 5)))
            ticks[4 * i + 2:4 * i + 4] = (ticktop * sin(radians(i * 5)),
                                          ticktop * cos(radians(i * 5)))
        self.ticks = RenderObject(gl.GL_LINES, vertex=ticks, color=white)

        ticklbls = np.zeros(24 * 36, dtype=np.float32)
        texcoords = np.zeros(36 * 36, dtype=np.float32)

        for i in range(36):
            if i % 3 == 0:
                w, h, y = 0.045, 0.09, 1.48
            else:
                w, h, y = 0.035, 0.07, 1.46
            tmp = [(-w, h + y), (-w, y), (0.0, h + y), (0.0, h + y), (-w, y),
                   (0.0, y), (0.0, h + y), (0.0, y), (w, h + y), (w, h + y),
                   (0.0, y), (w, y)]

            # numerics start at ASCII 48
            c1 = i / 10 + 48
            c2 = i % 10 + 48
            texcoords[36 * i:36 * i + 18] = [
                0, 0, c1, 0, 1, c1, 1, 0, c1, 1, 0, c1, 0, 1, c1, 1, 1, c1
            ]
            texcoords[36 * i + 18:36 * i + 36] = [
                0, 0, c2, 0, 1, c2, 1, 0, c2, 1, 0, c2, 0, 1, c2, 1, 1, c2
            ]
            angle = radians(10 * (36 - i))
            rot = np.array([[cos(angle), -sin(angle)],
                            [sin(angle), cos(angle)]])
            for j in range(12):
                ticklbls[24 * i + 2 * j:24 * i + 2 * j + 2] = rot.dot(tmp[j])

        self.ticklbls = RenderObject(gl.GL_TRIANGLES,
                                     vertex=ticklbls,
                                     color=white,
                                     texcoords=texcoords)

        vown = np.array([
            0.0, 0.0, 0.0, -0.12, 0.065, -0.03, -0.065, -0.03, 0.022, -0.1,
            -0.022, -0.1
        ],
                        dtype=np.float32)
        self.ownship = RenderObject(gl.GL_LINES, vertex=vown, color=yellow)

        self.spdlabel_text = self.font.prepare_text_string(
            'GS    TAS', 0.05, white, (-0.98, 1.6))
        self.spdlabel_val = self.font.prepare_text_string(
            '  000    000', 0.05, green, (-0.97, 1.6))

        self.waypoints = RenderObject.copy(self.shareWidget.waypoints)
        self.wptlabels = RenderObject.copy(self.shareWidget.wptlabels)
        self.airports = RenderObject.copy(self.shareWidget.airports)
        self.aptlabels = RenderObject.copy(self.shareWidget.aptlabels)
        self.protectedzone = RenderObject.copy(self.shareWidget.protectedzone)
        self.ac_symbol = RenderObject.copy(self.shareWidget.ac_symbol)
        self.aclabels = RenderObject.copy(self.shareWidget.aclabels)

        # Unbind VAO, VBO
        RenderObject.unbind_all()

        # Done initializing
        self.initialized = True
Exemplo n.º 45
0
 def delayed_rebuild(self):
     """Fire a rebuild indirectly so widgets get a chance to update."""
     QTimer.singleShot(0, self.rebuild)
Exemplo n.º 46
0
 def call_next(self, fn):
     QTimer.singleShot(0, fn)
Exemplo n.º 47
0
 def load(self):
     if self.Page == -1:
         return
     self.loadStarted.emit(True)
     # 延迟一秒后调用目的在于显示进度条
     QTimer.singleShot(1000, self._load)
Exemplo n.º 48
0
 def SingleShotOkKlick(message_box):
     """aux function to close messagebox"""
     close_delay = 0  # [ms]
     ok_btn = message_box.button(QMessageBox.Ok)
     QTimer.singleShot(close_delay, ok_btn.click)
Exemplo n.º 49
0
 def autoUpdateDevice(self, flag):
     logger.debug('autoUpdateDevice')
     autosetproperty = self.sender().objectName()
     autosetmethod = getattr(self.device, autosetproperty)
     autosetmethod()
     QTimer.singleShot(1000, self.updateUi)
Exemplo n.º 50
0
 def _shutdown(self, status, restart):  # noqa
     """Second stage of shutdown."""
     log.destroy.debug("Stage 2 of shutting down...")
     if qApp is None:
         # No QApplication exists yet, so quit hard.
         sys.exit(status)
     # Remove eventfilter
     try:
         log.destroy.debug("Removing eventfilter...")
         event_filter = objreg.get('event-filter', None)
         if event_filter is not None:
             qApp.removeEventFilter(event_filter)
     except AttributeError:
         pass
     # Close all windows
     QApplication.closeAllWindows()
     # Shut down IPC
     try:
         ipc.server.shutdown()
     except KeyError:
         pass
     # Save everything
     try:
         save_manager = objreg.get('save-manager')
     except KeyError:
         log.destroy.debug("Save manager not initialized yet, so not "
                           "saving anything.")
     else:
         for key in save_manager.saveables:
             try:
                 save_manager.save(key, is_exit=True)
             except OSError as e:
                 error.handle_fatal_exc(
                     e, self._args, "Error while saving!",
                     pre_text="Error while saving {}".format(key))
     # Disable storage so removing tempdir will work
     websettings.shutdown()
     # Disable application proxy factory to fix segfaults with Qt 5.10.1
     proxy.shutdown()
     # Re-enable faulthandler to stdout, then remove crash log
     log.destroy.debug("Deactivating crash log...")
     objreg.get('crash-handler').destroy_crashlogfile()
     # Delete temp basedir
     if ((self._args.temp_basedir or self._args.temp_basedir_restarted) and
             not restart):
         atexit.register(shutil.rmtree, self._args.basedir,
                         ignore_errors=True)
     # Delete temp download dir
     downloads.temp_download_manager.cleanup()
     # If we don't kill our custom handler here we might get segfaults
     log.destroy.debug("Deactivating message handler...")
     qInstallMessageHandler(None)
     # Now we can hopefully quit without segfaults
     log.destroy.debug("Deferring QApplication::exit...")
     objreg.get('signal-handler').deactivate()
     session_manager = objreg.get('session-manager', None)
     if session_manager is not None:
         session_manager.delete_autosave()
     # We use a singleshot timer to exit here to minimize the likelihood of
     # segfaults.
     QTimer.singleShot(0, functools.partial(qApp.exit, status))
Exemplo n.º 51
0
def update():
    QTimer.singleShot(2,lambda : update_blocking())
Exemplo n.º 52
0
def run():
    app = QApplication(sys.argv)
    ex = Pycomics()
    QTimer.singleShot(1, ex.InitLastScene)
    sys.exit(app.exec_())
Exemplo n.º 53
0
    def setViewScale(self, scale: float):
        self.fScale = scale

        if self.fRealParent is not None:
            QTimer.singleShot(0, self.fRealParent.slot_miniCanvasCheckAll)
Exemplo n.º 54
0
    def run(self, scenario, run_info):
        """
        Run the model on the remote worker using the settings specified in
        model_input.

        The worker will return a job ID corresponding to the row ID of the
        final results stored in the remote database.

        :param Scenario scenario: Scenario for which to run the model
        :param dict run_info: Supplementary info for this run:
           'reference_point': (lat, lon, depth) reference for coord. conversion
           'injection_point': (lat, lon, depth) of current injection point

        """
        forecast = scenario.forecast_input.forecast
        forecast_schema = ForecastSchema()
        serialized = forecast_schema.dump(forecast).data
        data = {
            'forecast': serialized,
            'parameters': self.model_config['parameters'],
            'scenario id': scenario.id
        }

        # Add cartesian coordinates
        ref = forecast.forecast_set.project.reference_point
        try:
            catalog = data['forecast']['input']['input_catalog']
            for e in catalog['seismic_events']:
                x, y, z = geodetic2ned(e['lat'], e['lon'], e['depth'],
                                       ref['lat'], ref['lon'], ref['h'])
                e['x'], e['y'], e['z'] = x, y, z

        except TypeError:
            self.logger.info('No seismic events')

        # Request model run
        self.results = None
        self.logger.info('Starting remote worker for {}'.format(self.model_id))
        notification = ErrorNotification(calc_id=self.model_id)
        try:
            r = requests.post(self.url, json=data, timeout=5)
        except (ConnectionError, Timeout) as ex:
            self.logger.error('Can' 't connect to worker: {}'.format(repr(ex)))
        else:
            notification.response = r
            if r.status_code == requests.codes.accepted:
                notification = RunningNotification(self.model_id, response=r)
                QTimer.singleShot(self.poll_interval, self._get_results)
            elif r.status_code == requests.codes.bad_request:
                self.logger.error(
                    'The worker did not accept our request: {}'.format(
                        r.content))
            elif r.status_code == requests.codes.server_error:
                self.logger.error('The worker reported an error: {}'.format(
                    r.content))
            elif r.status_code == requests.codes.unavailable:
                self.logger.error(
                    'The worker did not accept our job: {}'.format(r.content))
            else:
                self.logger.error(
                    'Unexpected response received: [{}] {}'.format(
                        r.status_code, r.content))
        self.client_notification.emit(notification)
Exemplo n.º 55
0
 def _log_later(self, *lines):
     """Log the given text line-wise with a QTimer."""
     for line in lines:
         QTimer.singleShot(0, functools.partial(log.destroy.info, line))
Exemplo n.º 56
0
 def timer_event():
     try:
         func(*args, **kwargs)
     finally:
         QTimer.singleShot(timeout, timer_event)
Exemplo n.º 57
0
 def unlock_window(self):
 	self.label.setText("Windows unlocked")
 	self.label.adjustSize()
 	QTimer.singleShot(300, self.close) #close window
 	unhide_taskbar()
 	print('test')
Exemplo n.º 58
0
    features["Standard"] = {}
    features["Standard"]["Count"] = {}
    features["Standard"]["Count"]["displaytext"] = "Size in pixels"
    features["Standard"]["Count"][
        "detailtext"] = "Total size of the object in pixels. No correction for anisotropic resolution or anything else."
    features["Standard"]["Count"]["group"] = "Shape"

    features["Standard"]["Count"] = {}
    features["Standard"]["Count"]["displaytext"] = "Size in pixels"
    features["Standard"]["Count"][
        "detailtext"] = "Total size of the object in pixels. No correction for anisotropic resolution or anything else."
    features["Standard"]["Count"]["group"] = "Shape"

    features["Standard"]["Coord<Minimum>"] = {}
    features["Standard"]["Coord<Minimum>"][
        "displaytext"] = "Bounding Box Minimum"
    features["Standard"]["Coord<Minimum>"][
        "detailtext"] = "The coordinates of the lower left corner of the object's bounding box. The first axis is x, then y, then z (if available)."
    features["Standard"]["Coord<Minimum>"]["group"] = "Location"

    features["Standard"]["Coord<Maximum>"] = {}
    features["Standard"]["Coord<Maximum>"][
        "displaytext"] = "Bounding Box Maximum"
    features["Standard"]["Coord<Maximum>"][
        "detailtext"] = "The coordinates of the upper right corner of the object's bounding box. The first axis is x, then y, then z (if available)."
    features["Standard"]["Coord<Maximum>"]["group"] = "Location"

    dlg = FeatureSelectionDialog(featureDict=features)
    QTimer.singleShot(100, dlg.raise_)
    dlg.exec_()
Exemplo n.º 59
0
class MainController:

    # States
    #

    class Idle:
        pass

    @dataclass
    class Preview:
        image: QImage

    @dataclass
    class Printing:
        image: QImage

    @dataclass
    class Error:
        message: str

    def __init__(
        self,
        main_window: MainWindow,
        idle_widget: IdleWidget,
        preview_widget: PreviewWidget,
        printing_widget: PrintingWidget,
        error_widget: ErrorWidget,
        printer: LibCupsPrinter,
        config,
    ):
        super().__init__()
        self._main_window = main_window
        self._idle_widget = idle_widget
        self._preview_widget = preview_widget
        self._printing_widget = printing_widget
        self._error_widget = error_widget
        self._printer = printer
        self._error_timeout_seconds = config.getint("errorTimeoutSeconds")
        self._preview_timeout_seconds = config.getint("previewTimeoutSeconds")

        self._timeout_timer = QTimer()

        # Connect signals
        #

        self._idle_widget.error.connect(self._switch_to_error)
        self._idle_widget.image_captured.connect(
            self._expect_state_then_switch(MainController.Idle,
                                           self._switch_to_preview))

        self._preview_widget.accept.connect(
            self._expect_state_then_switch(MainController.Preview,
                                           self._switch_to_printing))
        self._preview_widget.reject.connect(
            self._expect_state_then_switch(MainController.Preview,
                                           self._switch_to_idle))

        self._printer.error.connect(self._switch_to_error)
        self._printer.success.connect(
            self._expect_state_then_switch(
                MainController.Printing,
                self._switch_to_idle,
            ))

        self._error_widget.accept.connect(
            self._expect_state_then_switch(MainController.Error,
                                           self._switch_to_idle))

        self._main_window.quit.connect(self._main_window.deleteLater)

        # Initialise state
        #

        self._switch_to_idle()

    def _cancel_timeouts(self):
        self._timeout_timer.stop()

    def _expect_state_then_switch(self, expected_state, switch_to):
        def _inner(*args, **kwargs):
            caller = inspect.stack()[1][3]
            if isinstance(self.state, expected_state):
                logger.debug("Caught %s while in %s state", caller, self.state)
                switch_to(*args, **kwargs)
            else:
                logger.warning("Dropping unexpected %s while in %s state",
                               caller, self.state)

        return _inner

    def _switch_to_idle(self):
        self._cancel_timeouts()
        self.state = MainController.Idle()
        self._idle_widget.reload()
        self._main_window.select_idle()

    def _switch_to_preview(self, image):
        self._cancel_timeouts()
        self.state = MainController.Preview(image)
        self.last_captured_image = image
        self._preview_widget.set_image(image)
        self._main_window.select_preview()
        self._timeout_timer.singleShot(
            self._preview_timeout_seconds * 1000,
            self._expect_state_then_switch(MainController.Preview,
                                           self._switch_to_idle),
        )

    def _switch_to_printing(self):
        self._cancel_timeouts()
        self.state = MainController.Printing(self.state.image)
        self._printing_widget.set_image(self.state.image)
        self._main_window.select_printing()
        self._printer.print(self.state.image)

    def _switch_to_error(self, message: str):
        logger.error("_on_error: %s", message)
        self._cancel_timeouts()
        self.state = MainController.Error(message)
        self._main_window.select_error()
        self._error_widget.set_error_message(message)
        self._timeout_timer.singleShot(
            self._error_timeout_seconds * 1000,
            self._expect_state_then_switch(MainController.Error,
                                           self._switch_to_idle),
        )
 def CursorChangedEvent(self, obj, evt):
     """Called when the CursorChangedEvent fires on the render window."""
     # This indirection is needed since when the event fires, the current
     # cursor is not yet set so we defer this by which time the current
     # cursor should have been set.
     QTimer.singleShot(0, self.ShowCursor)