Beispiel #1
0
 def _initWeb(self):
     base = getBase(self.mw.col)
     self.web.stdHtml(self._revHtml,
                      self._styles(),
                      bodyClass="card",
                      loadCB=lambda x: self._showQuestion(),
                      head=base)
Beispiel #2
0
    def renderPreview(self):
        c = self.card
        html = """<html><head>%s</head><body class=card>
<style>%s</style>%s</body></html>"""
        ti = self.maybeTextInput
        base = getBase(self.mw.col)
        self.tab["pform"].front.setHtml(html % (base, "", ti(mungeQA(c.q(reload=True)))))
        self.tab["pform"].back.setHtml(html % (base, "", ti(mungeQA(c.a()), "a")))
Beispiel #3
0
def colorize_notes(self, note, hide=True, focus=False):
    css_colors = ""
    if note:
        for l in note.model()["css"].split("\n"):
            if l.startswith(".tone"):
                css_colors += l + "\n"
        myHtml = _html % (getBase(self.mw.col), anki.js.jquery, _("Show Duplicates"))
        myHtml = myHtml.replace("<style>", "<style\n>" + css_colors)
        self.web.setHtml(myHtml, loadCB=self._loadFinished)
Beispiel #4
0
    def renderPreview(self):
        c = self.card
        html = '''<html><head>%s</head><body class=card>
<style>%s</style>%s</body></html>'''
        ti = self.maybeTextInput
        base = getBase(self.mw.col)
        self.tab['pform'].front.setHtml(
            html % (base, "", ti(mungeQA(c.q(reload=True)))))
        self.tab['pform'].back.setHtml(
            html % (base, "", ti(mungeQA(c.a()), 'a')))
Beispiel #5
0
 def showCards(self):
     global chapters
     for chap in chapters:
         self.cards[chap] = AnkiWebView()
         self.cards[chap].setLinkHandler(self.linkHandler)
         base = getBase(mw.col)
         self.cards[chap].stdHtml(self._cardHTML % chap, head=base)
         self.nextTodo(chap)
         self.ui.form.chapters.addItem(self.cards[chap], chap)
         self.cards[chap].show()
Beispiel #6
0
def colorize_notes(self, note, hide=True, focus=False):
    css_colors = ""
    if note:
        for l in note.model()["css"].split("\n"):
            if l.startswith(".tone"):
                css_colors += l+"\n"
        myHtml = _html % (
            getBase(self.mw.col), anki.js.jquery,
            _("Show Duplicates"))
        myHtml = myHtml.replace("<style>", "<style\n>"+css_colors)
        self.web.setHtml(myHtml, loadCB=self._loadFinished)
Beispiel #7
0
 def _initWeb(self):
     self._reps = 0
     self._bottomReady = False
     base = getBase(self.mw.col)
     # main window
     self.web.stdHtml(self._revHtml, self._styles(), loadCB=lambda x: self._showQuestion(), head=base)
     # show answer / ease buttons
     self.bottom.web.show()
     self.bottom.web.stdHtml(
         self._bottomHTML(), self.bottom._css + self._bottomCSS, loadCB=lambda x: self._showAnswerButton()
     )
Beispiel #8
0
 def setNote(self, note, hide=True):
     "Make NOTE the current note."
     self.note = note
     # change timer
     if self.note:
         self.web.setHtml(_html % (getBase(self.mw.col), anki.js.all,
                               _("Show Duplicates")),
                          loadCB=self._loadFinished)
         self.updateTagsAndDeck()
         self.updateKeyboard()
     elif hide:
         self.widget.hide()
Beispiel #9
0
 def setFact(self, fact, hide=True):
     "Make FACT the current fact."
     self.fact = fact
     # change timer
     if self.fact:
         self.web.setHtml(_html % (getBase(self.mw.deck), anki.js.all,
                               _("Show Duplicates")),
                          loadCB=self._loadFinished)
         self.updateTagsAndGroup()
         self.updateKeyboard()
     elif hide:
         self.widget.hide()
Beispiel #10
0
 def setFact(self, fact, hide=True):
     "Make FACT the current fact."
     self.fact = fact
     # change timer
     if self.fact:
         self.web.setHtml(
             _html %
             (getBase(self.mw.deck), anki.js.all, _("Show Duplicates")),
             loadCB=self._loadFinished)
         self.updateTagsAndGroup()
         self.updateKeyboard()
     elif hide:
         self.widget.hide()
Beispiel #11
0
def generate_html_block(style_text, processed_cards):
    """Iterates through all cards to generate the html table layout."""

    #html header
    header = ("<html>\n"
              "<head>\n"
              "\t<meta charset=\"utf-8\">\n"
              "\t{0}\n"
              "</head>\n"
              "<style type=\"text/css\">\n"
              "{1}\n"
              "</style>\n").format(getBase(mw.col), style_text.encode("utf8"))

    html_block = [header]

    #loop through all cards and add to html block
    for i, (question, answer, front_images,
            back_images) in enumerate(processed_cards):

        #front side table section
        html_block.append("<table>\n" + "<tr class=\"front\">\n")
        if question:
            html_block.append("\t<td>\n\t\t{0}\n\t</td>\n".format(question))
        if front_images:
            for front_image in front_images:
                html_block.append(
                    "\t<td>\n\t\t{0}\n\t</td>\n".format(front_image))
        html_block.append("</tr>\n" + "</table>\n")

        #back_side table section
        if i + 1 < len(processed_cards):
            html_block.append("<table>\n")
        else:
            #avoid line break on last page
            html_block.append("<table style=\"page-break-after: avoid\">\n")
        html_block.append("<tr class=\"back\">\n")
        if answer:
            html_block.append("\t<td>\n\t\t{0}\n\t</td>\n".format(answer))
        if back_images:
            for back_image in back_images:
                html_block.append(
                    "\t<td>\n\t\t{0}\n\t</td>\n".format(back_image))
        html_block.append("</tr>\n" + "</table>\n")

        #progress bar update
        mw.progress.update("Cards formatted to html: {0}".format(i + 1))

    html_block.append("</body>\n" + "</html>")

    return "".join(html_block)
Beispiel #12
0
def doGrid():
    
    if not GridDlg.gridOn(): return False

    rev = mw.reviewer
    
    if not rev.state == "question":  # did the user just click to get a new question?
        return False # No
    # Probably Yes
    
    if staleCard(rev.card):
        return False # No, actually. We already just showed this card

    # print 'show grid'

    #import time
    #time.sleep(2)

    w = GridDlg(rev)
    w.setGeo()
    
    width = w.size().width()
    height = w.size().height()
    
    v = w.ui.gridView  # note: we expect type of v to be: QtWebKit.QWebView or its AnkiWebView subclass

    # would prefer Qt.ScrollBarAsNeeded but somehow this object thinks it's always needed
    v.page().mainFrame().setScrollBarPolicy(Qt.Horizontal, Qt.ScrollBarAlwaysOff)
    v.page().mainFrame().setScrollBarPolicy(Qt.Vertical, Qt.ScrollBarAsNeeded)  

    #see also: Reviewer._initWeb()
    base = getBase(rev.mw.col)  # this is necessary, or the images won't display; however, it complicates links  

    klass = "card card%d" % (rev.card.ord+1)
    width = int(0.96 * width)
    height = int(0.96 * height)
    buffer = 60 # e.g. for the window's title bar, and a bottom 'margin'
    html = gridHtml(rev._css, base, klass, width, height - buffer) #... we insert this once for the whole grid

    callback = lambda x: w.showAnswerGrid(rev.card, rev)

    v.setHtml(html, callback)  # pass in the 'empty' container, plus the function that'll fill it in

    v.show()
    w.show() 

    if w.exec_():
        # show the next flashcard
        return True
    return False
Beispiel #13
0
 def _initWeb(self):
     self._reps = 0
     self._bottomReady = False
     base = getBase(self.mw.col)
     # main window
     self.web.stdHtml(self._revHtml, self._styles(),
         loadCB=lambda x: self._showQuestion(),
         head=base)
     # show answer / ease buttons
     self.bottom.web.show()
     self.bottom.web.stdHtml(
         self._bottomHTML(),
         self.bottom._css + self._bottomCSS,
     loadCB=lambda x: self._showAnswerButton())
    def setCard(self, cid):
        """
        Set title and webview HTML
        """
        try:
            card = self.mw.col.getCard(cid)
        except TypeError:
            tooltip("Could not find linked card with cid:'{}'.".format(cid))
            return False

        # Set previewer title based on note contents
        note = card.note()
        fields = note.fields
        model = note.model()
        fnames = mw.col.models.fieldNames(model)
        idx = 0
        if "Note ID" in note:
            nid_idx = fnames.index("Note ID")
            if nid_idx == idx:
                idx = min(idx+1, len(fields))
        field1 = stripHTML(fields[idx])
        title = self.title.format(cid, field1[:50])
        self.setWindowTitle(title)

        # Set card HTML
        html = card.a()
        html = runFilter("previewerMungeQA", html)

        ti = lambda x: x
        base = getBase(self.mw.col)
        css = self.mw.reviewer._styles()
        if preview_jsbooster:
            # JS Booster available
            baseUrlText = getBaseUrlText(self.mw.col) + "__previewer__.html"
            stdHtmlWithBaseUrl(self.web,
                ti(mungeQA(self.mw.col, html)), baseUrlText, css,
                bodyClass="card card%d" % (card.ord+1), 
                head=base, js=browserSel)
        else:
            # fall back to default
            self.web.stdHtml(
                ti(mungeQA(self.mw.col, html)), css, 
                bodyClass="card card%d" % (card.ord+1), 
                head=base, js=browserSel)

        # Handle audio
        clearAudioQueue()
        if self.mw.reviewer.autoplay(card):
            playFromText(html)
Beispiel #15
0
 def setNote(self, note, hide=True):
     "Make NOTE the current note."
     self.note = note
     # change timer
     if self.note:
         self.web.setHtml(_html % (getBase(self.mw.col), anki.js.jquery,
                                   (isMac or isWin) and 1 or 0,
                               _("Show Duplicates")),
                          loadCB=self._loadFinished)
         self.updateTagsAndDeck()
         self.updateKeyboard()
     else:
         self.hideCompleters()
         if hide:
             self.widget.hide()
Beispiel #16
0
 def setNote(self, note, hide=True, focus=False):
     "Make NOTE the current note."
     self.note = note
     self.currentField = 0
     # change timer
     if self.note:
         self.web.setHtml(_html % (
             getBase(self.mw.col), anki.js.jquery,
             _("Show Duplicates")), loadCB=self._loadFinished)
         self.updateTags()
         self.updateKeyboard()
     else:
         self.hideCompleters()
         if hide:
             self.widget.hide()
Beispiel #17
0
    def renderPreview(self):
        c = self.card
        html = '''<html><head>%s</head><body class=card>
<style>%s</style>%s</body></html>'''
        ti = self.maybeTextInput
        base = getBase(self.mw.col)
        self.tab['pform'].front.setHtml(
            html % (base, "", ti(mungeQA(c.q(reload=True)))))
        self.tab['pform'].back.setHtml(
            html % (base, "", ti(mungeQA(c.a()), 'a')))
        clearAudioQueue()
        if c.id not in self.playedAudio:
            playFromText(c.q())
            playFromText(c.a())
            self.playedAudio[c.id] = True
Beispiel #18
0
 def renderPreview(self):
     c = self.card
     ti = self.maybeTextInput
     base = getBase(self.mw.col)
     self.tab['pform'].frontWeb.stdHtml(
         ti(mungeQA(c.q(reload=True))), self.mw.reviewer._styles(),
         bodyClass="card", head=base)
     self.tab['pform'].backWeb.stdHtml(
         ti(mungeQA(c.a())), self.mw.reviewer._styles(),
         bodyClass="card", head=base)
     clearAudioQueue()
     if c.id not in self.playedAudio:
         playFromText(c.q())
         playFromText(c.a())
         self.playedAudio[c.id] = True
Beispiel #19
0
def onPrint():
    path = os.path.join(mw.pm.profileFolder(), "print.html")
    ids = sortFieldOrderCids(mw.col.decks.selected())

    def esc(s):
        # strip off the repeated question in answer if exists
        #s = re.sub("(?si)^.*<hr id=answer>\n*", "", s)
        # remove type answer
        s = re.sub("\[\[type:[^]]+\]\]", "", s)
        return s

    def upath(path):
        if isWin:
            prefix = u"file:///"
        else:
            prefix = u"file://"
        return prefix + unicode(urllib.quote(path.encode("utf-8")), "utf-8")

    buf = open(path, "w")
    buf.write("<html><head>" + '<meta charset="utf-8">' +
              getBase(mw.col).encode("utf8") + "</head><body>")
    buf.write("""<style>
img { max-width: 100%; }
tr { page-break-after:auto; }
td { page-break-after:auto; }
td { border: 1px solid #ccc; padding: 1em; }
</style><table cellspacing=10 width=100%>""")
    first = True

    mw.progress.start(immediate=True)
    for j, cid in enumerate(ids):
        if j % CARDS_PER_ROW == 0:
            if not first:
                buf.write("</tr>")
            else:
                first = False
            buf.write("<tr>")
        c = mw.col.getCard(cid)
        cont = u"<td><center>%s</center></td>" % esc(
            c._getQA(True, False)['a'])
        buf.write(cont.encode("utf8"))
        if j % 50 == 0:
            mw.progress.update("Cards exported: %d" % (j + 1))
    buf.write("</tr>")
    buf.write("</table></body></html>")
    mw.progress.finish()
    buf.close()
    openLink(upath(path))
Beispiel #20
0
 def setNote(self, note, hide=True, focus=False):
     "Make NOTE the current note."
     self.note = note
     self.currentField = 0
     # change timer
     if self.note:
         self.web.setHtml(
             _html %
             (getBase(self.mw.col), anki.js.jquery, _("Show Duplicates")),
             loadCB=self._loadFinished)
         self.updateTags()
         self.updateKeyboard()
     else:
         self.hideCompleters()
         if hide:
             self.widget.hide()
Beispiel #21
0
 def _initWeb(self):
     self._reps = 0
     self._bottomReady = False
     base = getBase(self.mw.col)
     # main window
     self.web.stdHtml(self.revHtml(), self._styles(),
         loadCB=lambda x: self._showQuestion(),
         head=base)
     # show answer / ease buttons
     css = self.bottom.web.bundledCSS("toolbar-bottom.css") #trigger 2.1 addons
     css += self.bottom.web.bundledCSS("reviewer-bottom.css")
     self.bottom.web.show()
     self.bottom.web.stdHtml(
         self._bottomHTML(),
         self.bottom._css + self._bottomCSS + css,
     loadCB=lambda x: self._showAnswerButton())
Beispiel #22
0
def onPrint():
    path = os.path.join(mw.pm.profileFolder(), "print.html")
    ids = sortFieldOrderCids(mw.col.decks.selected())
    def esc(s):
        # strip off the repeated question in answer if exists
        #s = re.sub("(?si)^.*<hr id=answer>\n*", "", s)
        # remove type answer
        s = re.sub("\[\[type:[^]]+\]\]", "", s)
        return s
    def upath(path):
        if isWin:
            prefix = u"file:///"
        else:
            prefix = u"file://"
        return prefix + unicode(
            urllib.quote(path.encode("utf-8")), "utf-8")
    buf = open(path, "w")
    buf.write("<html><head>" +
              '<meta charset="utf-8">'
              + getBase(mw.col).encode("utf8") + "</head><body>")
    buf.write("""<style>
img { max-width: 100%; }
tr { page-break-after:auto; }
td { page-break-after:auto; }
td { border: 1px solid #ccc; padding: 1em; }
</style><table cellspacing=10 width=100%>""")
    first = True

    mw.progress.start(immediate=True)
    for j, cid in enumerate(ids):
        if j % CARDS_PER_ROW == 0:
            if not first:
                buf.write("</tr>")
            else:
                first = False
            buf.write("<tr>")
        c = mw.col.getCard(cid)
        cont = u"<td><center>%s</center></td>" % esc(c._getQA(True, False)['a'])
        buf.write(cont.encode("utf8"))
        if j % 50 == 0:
            mw.progress.update("Cards exported: %d" % (j+1))
    buf.write("</tr>")
    buf.write("</table></body></html>")
    mw.progress.finish()
    buf.close()
    openLink(upath(path))
Beispiel #23
0
 def renderPreview(self):
     c = self.card
     ti = self.maybeTextInput
     base = getBase(self.mw.col)
     self.tab['pform'].frontWeb.stdHtml(
         ti(mungeQA(self.mw.col, c.q(reload=True))), self.mw.reviewer._styles(),
         bodyClass="card card%d" % (c.ord+1), head=base,
         js=anki.js.browserSel)
     self.tab['pform'].backWeb.stdHtml(
         ti(mungeQA(self.mw.col, c.a()), type='a'), self.mw.reviewer._styles(),
         bodyClass="card card%d" % (c.ord+1), head=base,
         js=anki.js.browserSel)
     clearAudioQueue()
     if c.id not in self.playedAudio:
         playFromText(c.q())
         playFromText(c.a())
         self.playedAudio[c.id] = True
Beispiel #24
0
 def renderPreview(self):
     c = self.card
     ti = self.maybeTextInput
     base = getBase(self.mw.col)
     self.tab['pform'].frontWeb.stdHtml(
         ti(mungeQA(self.mw.col, c.q(reload=True))), self.mw.reviewer._styles(),
         bodyClass="card card%d" % (c.ord+1), head=base,
         js=anki.js.browserSel)
     self.tab['pform'].backWeb.stdHtml(
         ti(mungeQA(self.mw.col, c.a()), type='a'), self.mw.reviewer._styles(),
         bodyClass="card card%d" % (c.ord+1), head=base,
         js=anki.js.browserSel)
     clearAudioQueue()
     if c.id not in self.playedAudio:
         playFromText(c.q())
         playFromText(c.a())
         self.playedAudio[c.id] = True
Beispiel #25
0
 def renderPreview(self):
     c = self.card
     styles = self.model.genCSS()
     styles += "\n.cloze { font-weight: bold; color: blue; }"
     self.form.preview.setHtml(
         ('<html><head>%s</head><body class="%s">' %
          (getBase(self.deck), c.cssClass())) +
         "<style>" + styles + "</style>" +
         mungeQA(c.q(reload=True)) +
         self.maybeTextInput() +
         "<hr>" +
         mungeQA(c.a())
         + "</body></html>")
     clearAudioQueue()
     if c.id not in self.playedAudio:
         playFromText(c.q())
         playFromText(c.a())
         self.playedAudio[c.id] = True
Beispiel #26
0
 def _initWeb(self):
     base = getBase(self.mw.col)
     self.web.stdHtml(self._revHtml, self._styles(),
         bodyClass="card", loadCB=lambda x: self._showQuestion(),
         head=base)
Beispiel #27
0
    def renderPreview(self, cardChanged=False):
        """
        Generates the preview window content
        """

        oldfocus = None
        cids = self.b.selectedCards()
        nr = len(cids)
        multiple_selected = nr > 1

        if not cids:
            txt = "Please select one or more cards"
            self.web.stdHtml(txt)
            self.updateButtons()
            return

        if cardChanged and not self.both:
            self.state = "question"

        if self.config["rev"][0]:
            # only show review buttons on answer side:
            if self.config["rev"][3] and self.state != "answer":
                self.revArea.hide()
            else:
                self.updateRevArea(self.b.card)

        if cids[0] in self.cards and not multiple_selected:
            # moved focus to another previously selected card
            oldfocus = cids[0]
            cids = self.cards
            nr = len(cids)
            self.multi = nr > 1
            if cardChanged:
                # focus changed without any edits
                if not self.linkClicked and self.multi:
                    # only scroll when coming from browser and multiple cards shown
                    self.scrollToCard(oldfocus)
                self.linkClicked = False
                return
        elif multiple_selected:
            self.multi = True
        else:
            self.multi = False

        if nr >= 200:
            q = ("Are you sure you want to preview <b>{} cards</b> at once? "
                 "This might take a while to render".format(nr))
            ret = askUser(q)
            if not ret:
                return False

        html, css, js = self.renderCards(cids)

        def ti(x):
            return x

        base = getBase(self.mw.col)
        if preview_jsbooster:
            # JS Booster available
            baseUrlText = getBaseUrlText(self.mw.col) + "__previewer__.html"
            stdHtmlWithBaseUrl(self.web,
                               ti(mungeQA(self.mw.col, html)),
                               baseUrlText,
                               css,
                               head=base,
                               js=browserSel + multi_preview_js)
        else:
            # fall back to default
            self.web.stdHtml(ti(mungeQA(self.mw.col, html)),
                             css,
                             head=base,
                             js=js)

        if oldfocus and self.multi:
            self.scrollToCard(oldfocus)

        self.cards = cids

        self.updateButtons()

        clearAudioQueue()

        if not self.multi and self.mw.reviewer.autoplay(self.b.card):
            playFromText(html)
Beispiel #28
0
 def __init__(self, col):
     GlossaryExporter.__init__(self, col)
     self.base = getBase(mw.col).encode("utf8")