Esempio n. 1
0
 def test_executable(self) -> None:
     "Check to see if the TiddlyWiki executable provided can be called from Anki."
     # pylint: disable=no-member
     QApplication.setOverrideCursor(QCursor(Qt.CursorShape.WaitCursor))
     try:
         args = [self.form.tiddlywikiBinary_.text(), "--version"]
         proc = subprocess.run(args,
                               check=True,
                               stderr=subprocess.STDOUT,
                               stdout=subprocess.PIPE,
                               startupinfo=nowin_startupinfo())
     except FileNotFoundError:
         QApplication.restoreOverrideCursor()
         showCritical(
             "It doesn't look like that file exists on your computer. "
             "Try using the full path to 'tiddlywiki'.")
     except subprocess.CalledProcessError as e:
         QApplication.restoreOverrideCursor()
         showCritical(
             f"It's not quite working yet. Try seeing if you can run TiddlyWiki "
             f"from the command line and copy your command in here.\n\n"
             f"{e.output}")
     except Exception:
         QApplication.restoreOverrideCursor()
         raise
     else:
         QApplication.restoreOverrideCursor()
         showInfo(
             f"Successfully called TiddlyWiki {proc.stdout.decode().strip()}! "
             f"You're all set.")
Esempio n. 2
0
 def _copyDebuglog(self):
     log = getLatestLog()
     if log is False:
         tooltip("No debug log has been recorded, yet")
         return False
     QApplication.clipboard().setText(log)
     tooltip("Copied to clipboard")
    def _on_app_focus_changed(self, old_widget: Optional[QWidget],
                              new_widget: Optional[QWidget]):
        focus_behavior = self._settings.focus_behavior
        focus_exceptions = self._settings.focus_behavior_exceptions
        parent_window = self.parent().window()
        old_window = old_widget.window() if old_widget else None
        new_window = new_widget.window() if new_widget else None

        if focus_exceptions and any(
                isinstance(old_window, wtype) for wtype in focus_exceptions):
            # switching back from an excluded window should not cause notif closing
            pass
        elif new_window is None and QApplication.widgetAt(
                QCursor.pos()) == self:
            # clicking on self should not dismiss notification when not configured as
            # such (Windows bug)
            pass
        elif new_window is None:
            # switched focus away from application
            self.close()
        elif new_window != parent_window and (not focus_exceptions or (all(
                not isinstance(new_window, wtype)
                for wtype in focus_exceptions))):
            # switched to other window within same application that's not excluded
            if focus_behavior == FocusBehavior.close_on_window_focus_lost:
                self.close()
            elif focus_behavior == FocusBehavior.lower_on_window_focus_lost:
                self.setWindowFlag(Qt.WindowType.ToolTip, on=False)
        elif (new_window == parent_window
              and focus_behavior == FocusBehavior.lower_on_window_focus_lost):
            self.setWindowFlag(Qt.WindowType.ToolTip, on=True)
            self.show()
Esempio n. 4
0
 def __init__(self, mw):
     self.mw = mw
     self.app = QApplication.instance()
     self.inDB = False
     self.blockUpdates = False
     self._win = None
     self._levels = 0
Esempio n. 5
0
    def paint(self, painter, option, index):
        options = QStyleOptionViewItemV4(option)
        self.initStyleOption(options, index)

        # Choose appropriate style
        style = QApplication.style(
        ) if options.widget is None else options.widget.style()

        # Convert text into HTML
        doc = QTextDocument()
        doc.setHtml(options.text)
        doc.setTextWidth(option.rect.width())

        options.text = ""
        style.drawControl(QStyle.CE_ItemViewItem, options, painter)

        ctx = QAbstractTextDocumentLayout.PaintContext()

        textRect = style.subElementRect(QStyle.SE_ItemViewItemText, options)
        painter.save()
        painter.translate(textRect.topLeft())
        painter.setClipRect(textRect.translated(-textRect.topLeft()))
        doc.documentLayout().draw(painter, ctx)

        painter.restore()
    def __init__(
        self,
        text: str,
        settings: NotificationSettings = NotificationSettings(),
        parent: Optional[QWidget] = None,
        **kwargs,
    ):
        super().__init__(text, parent=parent, **kwargs)
        self._settings = settings

        self.setFrameStyle(QFrame.Shape.Panel)
        self.setLineWidth(2)
        self.setWindowFlags(Qt.WindowType.ToolTip)
        self.setContentsMargins(10, 10, 10, 10)

        palette = QPalette()
        palette.setColor(QPalette.ColorRole.Window,
                         QColor(self._settings.bg_color))
        palette.setColor(QPalette.ColorRole.WindowText,
                         QColor(self._settings.fg_color))
        self.setPalette(palette)

        if parent and self._settings.focus_behavior != FocusBehavior.always_on_top:
            app: "AnkiApp" = QApplication.instance(
            )  # type: ignore[assignment]
            app.focusChanged.connect(self._on_app_focus_changed)
Esempio n. 7
0
 def _setHtml(self, html):
     app = QApplication.instance()
     oldFocus = app.focusWidget()
     self._domDone = False
     self._page.setHtml(html)
     # work around webengine stealing focus on setHtml()
     if oldFocus:
         oldFocus.setFocus()
Esempio n. 8
0
    def gotoLocalFile(self, rootHtmlPath):
        rootHtmlPath = getResourcePath(rootHtmlPath)

        # Code from AnkiWebView::_setHtml
        app = QApplication.instance()

        # work around webengine stealing focus on setHtml()
        oldFocus = app.focusWidget()
        self.web._page.setUrl(QUrl.fromLocalFile(rootHtmlPath))
        if oldFocus:
            oldFocus.setFocus()
Esempio n. 9
0
    def _setupUI(self):
        super(RevHmContrib, self)._setupUI()

        # manually adjust title label font sizes on Windows
        # gap between default windows font sizes and sizes that work well
        # on Linux and macOS is simply too big
        # TODO: find a better solution
        if PLATFORM == "win":
            default_size = QApplication.font().pointSize()
            for label in [self.form.fmtLabContrib]:
                font = label.font()
                font.setPointSize(int(default_size * 1.4))
                label.setFont(font)
Esempio n. 10
0
def getAudio(parent, encode=True):
    "Record and return filename"
    # record first
    if not Recorder:
        showWarning("pyaudio not installed")
        return

    r = Recorder()
    mb = QMessageBox(parent)
    restoreGeom(mb, "audioRecorder")
    mb.setWindowTitle("Anki")
    mb.setIconPixmap(QPixmap(":/icons/media-record.png"))
    but = QPushButton(_("Save"))
    mb.addButton(but, QMessageBox.AcceptRole)
    but = QPushButton(_("Cancel"))
    mb.addButton(but, QMessageBox.RejectRole)
    mb.setEscapeButton(but)
    t = time.time()
    r.start()
    time.sleep(r.startupDelay)
    QApplication.instance().processEvents()
    while not mb.clickedButton():
        txt = _("Recording...<br>Time: %0.1f")
        mb.setText(txt % (time.time() - t))
        mb.show()
        QApplication.instance().processEvents()
    if mb.clickedButton() == mb.escapeButton():
        r.stop()
        return
    saveGeom(mb, "audioRecorder")
    # ensure at least a second captured
    while time.time() - t < 1:
        time.sleep(0.1)
    r.stop()
    # process
    r.postprocess(encode)
    return r.file()
Esempio n. 11
0
    def zoomFactor(self):
        # overridden scale factor?
        webscale = os.environ.get("ANKI_WEBSCALE")
        if webscale:
            return float(webscale)

        if isMac:
            return 1
        screen = QApplication.desktop().screen()
        dpi = screen.logicalDpiX()
        factor = dpi / 96.0
        if isLin:
            factor = max(1, factor)
            return factor
        # compensate for qt's integer scaling on windows
        qtIntScale = self._getQtIntScale(screen)
        desiredScale = factor * qtIntScale
        newFactor = desiredScale / qtIntScale
        return max(1, newFactor)
    def paint(self, painter, option, index):
        """Overrided. Paint content."""
        text = index.data(Qt.DisplayRole)
        style = QApplication.style(
        ) if option.styleObject is None else option.styleObject.style()

        self._setupTextDocument(text, option.rect.width())

        option.text = ""
        option.backgroundBrush = index.data(
            Qt.BackgroundRole) or option.backgroundBrush
        style.drawControl(QStyle.CE_ItemViewItem, option, painter)

        ctx = QAbstractTextDocumentLayout.PaintContext()

        textRect = style.subElementRect(QStyle.SE_ItemViewItemText, option)
        painter.save()
        painter.translate(textRect.topLeft())
        painter.setClipRect(textRect.translated(-textRect.topLeft()))
        self.textDocument.documentLayout().draw(painter, ctx)

        painter.restore()
def clip_copy(filename):
    _, fileabspath, _, _ = process_path(filename)
    QApplication.clipboard().setText(fileabspath)
Esempio n. 14
0
 def onCopy():
     addmgr = mw.addonManager
     addons = "\n".join(addmgr.annotatedName(d) for d in addmgr.allAddons())
     info = "\n".join((supportText(), "Add-ons:\n\n{}".format(addons)))
     QApplication.clipboard().setText(info)
     tooltip(_("Copied to clipboard"), parent=dialog)
Esempio n. 15
0
 def darrowTool(self):
     QApplication.setOverrideCursor(Qt.ArrowCursor)
     self.changeMode(ToolMode.Darrow)
Esempio n. 16
0
 def lineTool(self):
     QApplication.setOverrideCursor(Qt.ArrowCursor)
     self.changeMode(ToolMode.Line)
Esempio n. 17
0
 def polygonTool(self):
     QApplication.setOverrideCursor(Qt.ArrowCursor)
     self.changeMode(ToolMode.Polygon)
Esempio n. 18
0
        self.parent = parent
        self.fieldWidgets = {}
        
        self.controls = pinyin.forms.generated.builddb.Ui_BuildDB()
        self.controls.setupUi(self)

if __name__ == "__main__":
    import sys
    import time
    import pinyin.forms.builddbcontroller
    import pinyin.mocks
    
    class MockDBBuilder(object):
        def build(self):
            print "Building!"
            time.sleep(5)
            print "Building done"
    
    app = QApplication(sys.argv)

    parent = QWidget()
    parent.resize(250, 150)
    parent.setWindowTitle('simple')
    
    builddb = BuildDB(parent)
    _controller = pinyin.forms.builddbcontroller.BuildDBController(builddb, pinyin.mocks.NullNotifier(), MockDBBuilder(), True)
    
    builddb.show()
    
    sys.exit(app.exec_())
Esempio n. 19
0
def set_clip(v, u):
    QApplication.clipboard().setText(u.url())
def nidcopy(nid):
    prefix = ""
    if gc("browser_table_add_prefix_when_copying", True):
        prefix += gc("prefix_nid", "nidd")
    QApplication.clipboard().setText(prefix + str(nid))
Esempio n. 21
0
 def __init__(self, argv):
     QApplication.__init__(self, argv)
     self._argv = argv
Esempio n. 22
0
 def ellipseTool(self):
     QApplication.setOverrideCursor(Qt.ArrowCursor)
     self.changeMode(ToolMode.Ellipse)
Esempio n. 23
0
 def moveTool(self):
     QApplication.setOverrideCursor(Qt.SizeAllCursor)
     self.changeMode(ToolMode.Move)
Esempio n. 24
0
 def event(self, evt):
     if evt.type() == QEvent.FileOpen:
         self.appMsg.emit(evt.file() or "raise")
         return True
     return QApplication.event(self, evt)
Esempio n. 25
0
        self.controls = pinyin.forms.generated.builddb.Ui_BuildDB()
        self.controls.setupUi(self)


if __name__ == "__main__":
    import sys
    import time
    import pinyin.forms.builddbcontroller
    import pinyin.mocks

    class MockDBBuilder(object):
        def build(self):
            print "Building!"
            time.sleep(5)
            print "Building done"

    app = QApplication(sys.argv)

    parent = QWidget()
    parent.resize(250, 150)
    parent.setWindowTitle('simple')

    builddb = BuildDB(parent)
    _controller = pinyin.forms.builddbcontroller.BuildDBController(
        builddb, pinyin.mocks.NullNotifier(), MockDBBuilder(), True)

    builddb.show()

    sys.exit(app.exec_())
Esempio n. 26
0
 def zoomTool(self):
     QApplication.setOverrideCursor(Qt.ArrowCursor)
     self.changeMode(ToolMode.Zoom)
Esempio n. 27
0
 def onCopy():
     QApplication.clipboard().setText(text.toPlainText())
Esempio n. 28
0
 def rectTool(self):
     QApplication.setOverrideCursor(Qt.ArrowCursor)
     self.changeMode(ToolMode.Rect)