Ejemplo n.º 1
0
def run():
    try:
        _run()
    except Exception as e:
        traceback.print_exc()
        QMessageBox.critical(
            None, "Startup Error", "Please notify support of this error:\n\n" +
            traceback.format_exc())
Ejemplo n.º 2
0
 def openProfile(self, profile):
     if profile:
         if profile not in self.profiles():
             QMessageBox.critical(None, "Error", "Requested profile does not exist.")
             sys.exit(1)
         try:
             self.load(profile)
         except TypeError:
             raise Exception("Provided profile does not exist.")
Ejemplo n.º 3
0
 def msgHandler(type, ctx, msg):
     if "Failed to create OpenGL context" in msg:
         QMessageBox.critical(
             None, "Error",
             "Error loading '%s' graphics driver. Please start Anki again to try next driver."
             % mode)
         pm.nextGlMode()
         return
     else:
         print("qt:", msg)
Ejemplo n.º 4
0
    def ensureBaseExists(self):
        try:
            self._ensureExists(self.base)
        except:
            # can't translate, as lang not initialized
            QMessageBox.critical(
                None, "Error", """\
Anki could not create the folder %s. Please ensure that location is not \
read-only and you have permission to write to it. If you cannot fix this \
issue, please see the documentation for information on running Anki from \
a flash drive.""" % self.base)
            raise
Ejemplo n.º 5
0
        def recover():
            # if we can't load profile, start with a new one
            if self.db:
                try:
                    self.db.close()
                except:
                    pass
            for suffix in ("", "-journal"):
                fpath = path + suffix
                if os.path.exists(fpath):
                    os.unlink(fpath)
            QMessageBox.warning(
                None, "Preferences Corrupt", """\
Anki's prefs21.db file was corrupt and has been recreated. If you were using multiple \
profiles, please add them back using the same names to recover your cards.""")
Ejemplo n.º 6
0
    def load(self, name):
        assert name != "_global"
        data = self.db.scalar("select cast(data as blob) from profiles where name = ?", name)
        self.name = name
        try:
            self.profile = self._unpickle(data)
        except:
            QMessageBox.warning(
                None, _("Profile Corrupt"), _("""\
Anki could not read your profile data. Window sizes and your sync login \
details have been forgotten."""))

            print("resetting corrupt profile")
            self.profile = profileConf.copy()
            self.save()
        return True
Ejemplo n.º 7
0
    def unlockPopup(self, countryName, cityName):
        msgBox = QMessageBox()
        city = self.buildingAuthority.getCity(countryName, cityName)
        msgBox.setText("Do you want to unlock %s for %s Gold?" %
                       (city.getName(), city.getPrice()))
        msgBox.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)
        msgBox.setDefaultButton(QMessageBox.Ok)
        choice = msgBox.exec_()

        if choice == QMessageBox.Ok:

            if self.buildingAuthority.unlockCity(city) is False:
                self.constructionView(countryName, cityName)
Ejemplo n.º 8
0
    def sendMsg(self, txt):
        sock = QLocalSocket(self)
        sock.connectToServer(self.KEY, QIODevice.WriteOnly)
        if not sock.waitForConnected(self.TMOUT):
            # first instance or previous instance dead
            return False
        sock.write(txt.encode("utf8"))
        if not sock.waitForBytesWritten(self.TMOUT):
            # existing instance running but hung
            QMessageBox.warning(
                None, "Anki Already Running",
                "If the existing instance of Anki is not responding, please close it using your task manager, or restart your computer."
            )

            sys.exit(1)
        sock.disconnectFromServer()
        return True
Ejemplo n.º 9
0
 def __init__(self, text, buttons, parent=None, help="", title="Anki"):
     QMessageBox.__init__(self, parent)
     self.buttons = []
     self.setWindowTitle(title)
     self.help = help
     self.setIcon(QMessageBox.Warning)
     self.setText(text)
     # v = QVBoxLayout()
     # v.addWidget(QLabel(text))
     # box = QDialogButtonBox()
     # v.addWidget(box)
     for b in buttons:
         self.buttons.append(
             self.addButton(b, QMessageBox.AcceptRole))
     if help:
         self.addButton(_("Help"), QMessageBox.HelpRole)
         buttons.append(_("Help"))
Ejemplo n.º 10
0
def showInfo(message, parent=None, mode="info", title="Anki"):
    if mode == "info":
        icon = QMessageBox.Information
    elif mode == "warning":
        icon = QMessageBox.Warning
    elif mode == "critical":
        icon = QMessageBox.Critical

    return QMessageBox(icon, title, message, parent=parent)
Ejemplo n.º 11
0
 def _onLangSelected(self):
     f = self.langForm
     obj = langs[f.lang.currentRow()]
     code = obj[1]
     name = obj[0]
     en = "Are you sure you wish to display Anki's interface in %s?"
     r = QMessageBox.question(
         None, "Anki", en%name, QMessageBox.Yes | QMessageBox.No,
         QMessageBox.No)
     if r != QMessageBox.Yes:
         return self._setDefaultLang()
     self.setLang(code)
Ejemplo n.º 12
0
def debug(debugText):
    from aqt.qt import QMessageBox
    QMessageBox.information(mw, getPluginName(), str(debugText))
Ejemplo n.º 13
0
def showInfo(text, parent=False, help="", type="info", title="Anki", textFormat=None):
    "Show a small info window with an OK button."
    if parent is False:
        parent = aqt.mw.app.activeWindow() or aqt.mw
    if type == "warning":
        icon = QMessageBox.Warning
    elif type == "critical":
        icon = QMessageBox.Critical
    else:
        icon = QMessageBox.Information
    mb = QMessageBox(parent)
    if textFormat == "plain":
        mb.setTextFormat(Qt.PlainText)
    elif textFormat == "rich":
        mb.setTextFormat(Qt.RichText)
    elif textFormat is not None:
        raise Exception("unexpected textFormat type")
    mb.setText(text)
    mb.setIcon(icon)
    mb.setWindowTitle(title)
    b = mb.addButton(QMessageBox.Ok)
    b.setDefault(True)
    if help:
        b = mb.addButton(QMessageBox.Help)
        b.clicked.connect(lambda: openHelp(help))
        b.setAutoDefault(False)
    return mb.exec_()
Ejemplo n.º 14
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()
Ejemplo n.º 15
0
 def links(self, handled, message, context):
     QMessageBox(self)
     raise Exception("HIDE")
     ret = self.process_request(json.loads(message), context)
     return (True, ret)
Ejemplo n.º 16
0
    def answerCard(self, Reviewer, card, ease):

        if self.__options.getOption("pluginEnabled"):
            self.setQuality(ease)
            cardsAnsweredToday = self.__stats.cardAnswered(self.__lastQuality)
            self.__stats.save()

            # Update the building process
            self.__buildingAuthority.updateBuildingProgress(
                self.__lastQuality, cardsAnsweredToday)
            self.__buildingAuthority.save()

            # Update rank
            self.__ranks.updateRank(
                self.__treasureChest.getTotalGold(),
                self.__buildingAuthority.getActiveCountry().
                getCompletedObjectsPercentage(),
                False,
            )

            # Display popup and perform event action whenever a major event has occured
            event = self.__eventManager.getNextEvent()

            if event:
                msg = QMessageBox()
                msg.setIcon(QMessageBox.NoIcon)
                msg.setWindowTitle(getPluginName())
                msg.setText(event.performEventAndGetText())
                msg.addButton("OK", QMessageBox.AcceptRole)
                msg.exec_()

            # calculate earned gold
            self.__treasureChest.updateGold(card, self.__lastQuality,
                                            cardsAnsweredToday, False)
            self.__treasureChest.save()

            self.open_main()
Ejemplo n.º 17
0
def debug(debugText):
    QMessageBox.information(mw, getPluginName(), str(debugText))
Ejemplo n.º 18
0
def showInfo(message, title="Anknotes: Evernote Importer for Anki", textFormat=0, cancelButton=False, richText=False,
             minHeight=None, minWidth=400, styleSheet=None, convertNewLines=True):
    global imgEvernoteWebMsgBox, icoEvernoteArtcore, icoEvernoteWeb
    msgDefaultButton = QPushButton(icoEvernoteArtcore, "Okay!", mw)

    if not styleSheet:
        styleSheet = file(FILES.ANCILLARY.CSS_QMESSAGEBOX, 'r').read()

    if not is_str_type(message):
        message = str(message)

    if richText:
        textFormat = 1
        message = '<style>\n%s</style>\n\n%s' % (styleSheet, message)
    global messageBox
    messageBox = QMessageBox()
    messageBox.addButton(msgDefaultButton, QMessageBox.AcceptRole)
    if cancelButton:
        msgCancelButton = QPushButton(icoTomato, "No Thanks", mw)
        messageBox.addButton(msgCancelButton, QMessageBox.RejectRole)
    messageBox.setDefaultButton(msgDefaultButton)
    messageBox.setIconPixmap(imgEvernoteWebMsgBox)
    messageBox.setTextFormat(textFormat)

    messageBox.setWindowIcon(icoEvernoteWeb)
    messageBox.setWindowIconText("Anknotes")
    messageBox.setText(message)
    messageBox.setWindowTitle(title)
    hSpacer = QSpacerItem(minWidth, 0, QSizePolicy.Minimum, QSizePolicy.Expanding)

    layout = messageBox.layout()
    """:type : QGridLayout """
    layout.addItem(hSpacer, layout.rowCount() + 1, 0, 1, layout.columnCount())
    ret = messageBox.exec_()
    if not cancelButton:
        return True
    if messageBox.clickedButton() == msgCancelButton or messageBox.clickedButton() == 0:
        return False
    return True
Ejemplo n.º 19
0
def _run(argv=None, exec=True):
    """Start AnkiQt application or reuse an existing instance if one exists.

    If the function is invoked with exec=False, the AnkiQt will not enter
    the main event loop - instead the application object will be returned.

    The 'exec' and 'argv' arguments will be useful for testing purposes.

    If no 'argv' is supplied then 'sys.argv' will be used.
    """
    global mw

    if argv is None:
        argv = sys.argv

    # parse args
    opts, args = parseArgs(argv)

    # profile manager
    from aqt.profiles import ProfileManager
    pm = ProfileManager(opts.base)

    # gl workarounds
    setupGL(pm)

    # opt in to full hidpi support?
    if not os.environ.get("ANKI_NOHIGHDPI"):
        QCoreApplication.setAttribute(Qt.AA_EnableHighDpiScaling)

    # create the app
    app = AnkiApp(argv)
    QCoreApplication.setApplicationName("Anki")
    if app.secondInstance():
        # we've signaled the primary instance, so we should close
        return

    # disable icons on mac; this must be done before window created
    if isMac:
        app.setAttribute(Qt.AA_DontShowIconsInMenus)

    # proxy configured?
    from urllib.request import proxy_bypass, getproxies
    if 'http' in getproxies():
        # if it's not set up to bypass localhost, we'll
        # need to disable proxies in the webviews
        if not proxy_bypass("127.0.0.1"):
            print("webview proxy use disabled")
            proxy = QNetworkProxy()
            proxy.setType(QNetworkProxy.NoProxy)
            QNetworkProxy.setApplicationProxy(proxy)

    # we must have a usable temp dir
    try:
        tempfile.gettempdir()
    except:
        QMessageBox.critical(
            None, "Error", """\
No usable temporary folder found. Make sure C:\\temp exists or TEMP in your \
environment points to a valid, writable folder.""")
        return

    pm.setupMeta()

    if opts.profile:
        pm.openProfile(opts.profile)

    # i18n
    setupLang(pm, app, opts.lang)

    if isLin and pm.glMode() == "auto":
        from aqt.utils import gfxDriverIsBroken
        if gfxDriverIsBroken():
            pm.nextGlMode()
            QMessageBox.critical(
                None, "Error",
                "Your video driver is incompatible. Please start Anki again, and Anki will switch to a slower, more compatible mode."
            )
            sys.exit(1)

    # load the main window
    import aqt.main
    mw = aqt.main.AnkiQt(app, pm, opts, args)
    if exec:
        app.exec()
    else:
        return app
Ejemplo n.º 20
0
def askAndUpdate(mw, ver):
    baseStr = (
        _('''<h1>Anki Updated</h1>Anki %s has been released.<br><br>''') % ver)
    msg = QMessageBox(mw)
    msg.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
    msg.setIcon(QMessageBox.Information)
    msg.setText(baseStr + _("Would you like to download it now?"))
    button = QPushButton(_("Ignore this update"))
    msg.addButton(button, QMessageBox.RejectRole)
    msg.setDefaultButton(QMessageBox.Yes)
    ret = msg.exec_()
    if msg.clickedButton() == button:
        # ignore this update
        mw.pm.meta['suppressUpdate'] = ver
    elif ret == QMessageBox.Yes:
        openLink(aqt.appWebsite)
Ejemplo n.º 21
0
def showInfo(message,
             title="Anknotes: Evernote Importer for Anki",
             textFormat=0,
             cancelButton=False,
             richText=False,
             minHeight=None,
             minWidth=400,
             styleSheet=None,
             convertNewLines=True):
    global imgEvernoteWebMsgBox, icoEvernoteArtcore, icoEvernoteWeb
    msgDefaultButton = QPushButton(icoEvernoteArtcore, "Okay!", mw)

    if not styleSheet:
        styleSheet = file(FILES.ANCILLARY.CSS_QMESSAGEBOX, 'r').read()

    if not is_str_type(message):
        message = str(message)

    if richText:
        textFormat = 1
        message = '<style>\n%s</style>\n\n%s' % (styleSheet, message)
    global messageBox
    messageBox = QMessageBox()
    messageBox.addButton(msgDefaultButton, QMessageBox.AcceptRole)
    if cancelButton:
        msgCancelButton = QPushButton(icoTomato, "No Thanks", mw)
        messageBox.addButton(msgCancelButton, QMessageBox.RejectRole)
    messageBox.setDefaultButton(msgDefaultButton)
    messageBox.setIconPixmap(imgEvernoteWebMsgBox)
    messageBox.setTextFormat(textFormat)

    messageBox.setWindowIcon(icoEvernoteWeb)
    messageBox.setWindowIconText("Anknotes")
    messageBox.setText(message)
    messageBox.setWindowTitle(title)
    hSpacer = QSpacerItem(minWidth, 0, QSizePolicy.Minimum,
                          QSizePolicy.Expanding)

    layout = messageBox.layout()
    """:type : QGridLayout """
    layout.addItem(hSpacer, layout.rowCount() + 1, 0, 1, layout.columnCount())
    ret = messageBox.exec_()
    if not cancelButton:
        return True
    if messageBox.clickedButton(
    ) == msgCancelButton or messageBox.clickedButton() == 0:
        return False
    return True
Ejemplo n.º 22
0
def debug(debugText):
    from aqt.qt import QMessageBox
    QMessageBox.information(mw, getPluginName(), str(debugText))
Ejemplo n.º 23
0
 def showDescription(self, optionDesc, optionLongDesc):
     QMessageBox.information(mw, "Option: %s" % optionDesc,
                             "%s" % optionLongDesc)