def fieldsAreBlank(self):
    for (field, widget) in self.fields.values():
        value = tidyHTML(unicode(widget.toHtml()))
        if (self.addMode and value != self.sticky_value.get(field.name, '')):
            if value:
                return False
    return True
Beispiel #2
0
 def loadFields(self, check=True, font=True):
     "Update field text (if changed) and font/colours."
     # text
     for field in self.fact.fields:
         w = self.fields[field.name][1]
         self.fields[field.name] = (field, w)
         self.widgets[w] = field
         new = self.fact[field.name]
         old = tidyHTML(unicode(w.toHtml()))
         # only update if something has changed
         if new != old:
             cur = w.textCursor()
             w.setHtml('<meta name="qrichtext" content="1"/>' + new)
             w.setTextCursor(cur)
         if font:
             # apply fonts
             font = QFont()
             # family
             family = field.fieldModel.editFontFamily or field.fieldModel.quizFontFamily
             if family:
                 font.setFamily(family)
             # size
             size = field.fieldModel.editFontSize or field.fieldModel.quizFontSize
             if size:
                 font.setPixelSize(size)
             w.setFont(font)
     self.tags.blockSignals(True)
     self.tags.setText(self.fact.tags)
     self.tags.blockSignals(False)
     if check:
         self.checkValid()
Beispiel #3
0
def doAddURL():
    # get URL from clipboard
    url = str(QApplication.clipboard().mimeData().text())
    try:
        # download HTML file with urllib
        html = opener.open(url).read()
    except ValueError:
        utils.showInfo("Please copy a URL to clipboard first.")
        return
    # parse HTML and find images
    xml = libxml2.htmlParseDoc(html, 'utf-8')
    context = xml.xpathNewContext()
    # find correct nodes via XPath
    count = 0
    for img in context.xpathEval('//img'):
        # get src attribute
        attr = img.get_properties()
        imgurl = None
        while attr:
            if attr.name == 'src':
                _replaceImageSrc(url, attr)
                count += 1
                break
            attr = attr.get_next()

    # add new fact
    fact = Fact(mw.deck.currentModel)
    val = tidyHTML(xml.serialize(encoding='utf-8').decode('utf-8', 'replace'))
    fact.fields[0].value = val
    mw.deck.addFact(fact, reset=True)
    utils.showInfo(
        "URL successfully added as new fact (%d pictures downloaded)" % count)
Beispiel #4
0
def doAddURL():
    # get URL from clipboard
    url = str(QApplication.clipboard().mimeData().text())
    try:
        # download HTML file with urllib
        html = opener.open(url).read()
    except ValueError:
       utils.showInfo("Please copy a URL to clipboard first.")
       return
    # parse HTML and find images
    xml = libxml2.htmlParseDoc(html, 'utf-8')
    context = xml.xpathNewContext()
    # find correct nodes via XPath
    count = 0
    for img in context.xpathEval('//img'):
        # get src attribute
        attr = img.get_properties()
        imgurl = None
        while attr:
            if attr.name == 'src':
                _replaceImageSrc(url, attr)
                count += 1
                break
            attr = attr.get_next()

    # add new fact
    fact = Fact(mw.deck.currentModel)
    val = tidyHTML(xml.serialize(encoding='utf-8').decode('utf-8', 'replace'))
    fact.fields[0].value = val
    mw.deck.addFact(fact, reset = True)
    utils.showInfo("URL successfully added as new fact (%d pictures downloaded)" % count)
Beispiel #5
0
def _onExtract():
    mw.deck.setUndoStart('Extract')
    # mark selection, get selected content
    html = _markSelection()
    mw.deck.setUndoEnd('Extract')
    # open add cards dialog
    addDialog = ui.dialogs.get("AddCards", mw)
    # add selected content to first field (Front) and
    # update editor display
    addDialog.editor.fact.fields[0].value = tidyHTML(html.decode('utf-8', 'replace'))
    addDialog.editor.drawFields(check=True)
Beispiel #6
0
def _onExtract():
    mw.deck.setUndoStart('Extract')
    # mark selection, get selected content
    html = _markSelection()
    mw.deck.setUndoEnd('Extract')
    # open add cards dialog
    addDialog = ui.dialogs.get("AddCards", mw)
    # add selected content to first field (Front) and
    # update editor display
    addDialog.editor.fact.fields[0].value = tidyHTML(
        html.decode('utf-8', 'replace'))
    addDialog.editor.drawFields(check=True)
Beispiel #7
0
 def saveFields(self):
     "Save field text into fact."
     modified = False
     n = _("Edit")
     self.deck.setUndoStart(n, merge=True)
     for (w, f) in self.widgets.items():
         v = tidyHTML(unicode(w.toHtml()))
         if self.fact[f.name] != v:
             self.fact[f.name] = v
             modified = True
     if modified:
         self.fact.setModified(textChanged=True)
         self.deck.setModified()
     self.deck.setUndoEnd(n)
Beispiel #8
0
 def fieldsAreBlank(self):
     for (field, widget) in self.fields.values():
         value = tidyHTML(unicode(widget.toHtml()))
         if value:
             return False
     return True
Beispiel #9
0
def onClozeRepl(self):
    src = self.focusedEdit()
    if not src:
        return
    re1 = "\[(?:<.+?>)?.+?(:(.+?))?\](?:</.+?>)?"
    re2 = "\[(?:<.+?>)?(.+?)(:.+?)?\](?:</.+?>)?"
    # add brackets because selected?
    cursor = src.textCursor()
    oldSrc = None
    if cursor.hasSelection():
        oldSrc = src.toHtml()
        s = cursor.selectionStart()
        e = cursor.selectionEnd()
        cursor.setPosition(e)
        cursor.insertText("]]")
        cursor.setPosition(s)
        cursor.insertText("[[")
        re1 = "\[" + re1 + "\]"
        re2 = "\[" + re2 + "\]"
    dst = None
    for field in self.fact.fields:
        w = self.fields[field.name][1]
        if w.hasFocus():
            dst = False
            continue
        if dst is False:
            dst = w
            break
    if not dst:
        dst = self.fields[self.fact.fields[0].name][1]
        if dst == w:
            return
    # check if there's alredy something there
    if not oldSrc:
        oldSrc = src.toHtml()
    oldDst = dst.toHtml()
    if unicode(dst.toPlainText()):
        if (self.lastCloze and self.lastCloze[1] == oldSrc
                and self.lastCloze[2] == oldDst):
            src.setHtml(self.lastCloze[0])
            dst.setHtml("")
            self.lastCloze = None
            self.saveFields()
            return
        else:
            ui.utils.showInfo(_("Next field must be blank."),
                              help="ClozeDeletion",
                              parent=self.parent)
            return
    # escape known
    oldtxt = unicode(src.toPlainText())
    html = unicode(src.toHtml())
    reg = "\[(/?(latex|\$|\$\$))\]"
    repl = "{\\1}"
    txt = re.sub(reg, repl, oldtxt)
    html = re.sub(reg, repl, html)
    haveLatex = txt != oldtxt
    # check if there's anything to change
    if not re.search("\[.+?\]", txt):
        ui.utils.showInfo(_("You didn't specify anything to occlude."),
                          help="ClozeDeletion",
                          parent=self.parent)
        return
    # create
    ses = tidyHTML(html).split("<br>")
    news = []
    olds = []
    for s in ses:
        haveLatex = ("latex" in s or "{$}" in s or "{$$}" in s)

        def repl(match):
            exp = ""
            if match.group(2):
                exp = match.group(2)
            if haveLatex:
                return "\\textbf{[...%s]}" % (exp)
            else:
                return '<font color="%s"><b>[...%s]</b></font>' % (clozeColour,
                                                                   exp)

        new = re.sub(re1, repl, s)
        if haveLatex:
            old = re.sub(re2, "{\\\\bf{}\\1\\\\rm{}}", s)
        else:
            old = re.sub(re2,
                         '<font color="%s"><b>\\1</b></font>' % clozeColour, s)
        reg = "\{(/?(latex|\$|\$\$))\}"
        repl = "[\\1]"
        new = re.sub(reg, repl, new)
        old = re.sub(reg, repl, old)
        news.append(new)
        olds.append(old)
    src.setHtml("<br>".join(news))
    dst.setHtml("<br>".join(olds))
    self.lastCloze = (oldSrc, unicode(src.toHtml()), unicode(dst.toHtml()))
    self.saveFields()
def onClozeRepl(self):
    src = self.focusedEdit()
    if not src:
        return
    re1 = "\[(?:<.+?>)?.+?(:(.+?))?\](?:</.+?>)?"
    re2 = "\[(?:<.+?>)?(.+?)(:.+?)?\](?:</.+?>)?"
    # add brackets because selected?
    cursor = src.textCursor()
    oldSrc = None
    if cursor.hasSelection():
        oldSrc = src.toHtml()
        s = cursor.selectionStart()
        e = cursor.selectionEnd()
        cursor.setPosition(e)
        cursor.insertText("]]")
        cursor.setPosition(s)
        cursor.insertText("[[")
        re1 = "\[" + re1 + "\]"
        re2 = "\[" + re2 + "\]"
    dst = None
    for field in self.fact.fields:
        w = self.fields[field.name][1]
        if w.hasFocus():
            dst = False
            continue
        if dst is False:
            dst = w
            break
    if not dst:
        dst = self.fields[self.fact.fields[0].name][1]
        if dst == w:
            return
    # check if there's alredy something there
    if not oldSrc:
        oldSrc = src.toHtml()
    oldDst = dst.toHtml()
    if unicode(dst.toPlainText()):
        if (self.lastCloze and
            self.lastCloze[1] == oldSrc and
            self.lastCloze[2] == oldDst):
            src.setHtml(self.lastCloze[0])
            dst.setHtml("")
            self.lastCloze = None
            self.saveFields()
            return
        else:
            ui.utils.showInfo(
                _("Next field must be blank."),
                help="ClozeDeletion",
                parent=self.parent)
            return
    # escape known
    oldtxt = unicode(src.toPlainText())
    html = unicode(src.toHtml())
    reg = "\[(/?(latex|\$|\$\$))\]"
    repl = "{\\1}"
    txt = re.sub(reg, repl, oldtxt)
    html = re.sub(reg, repl, html)
    haveLatex = txt != oldtxt
    # check if there's anything to change
    if not re.search("\[.+?\]", txt):
        ui.utils.showInfo(
            _("You didn't specify anything to occlude."),
            help="ClozeDeletion",
            parent=self.parent)
        return
    # create
    ses = tidyHTML(html).split("<br>")
    news = []
    olds = []
    for s in ses:
        haveLatex = ("latex" in s or "{$}" in s or "{$$}" in s)
        def repl(match):
            exp = ""
            if match.group(2):
                exp = match.group(2)
            if haveLatex:
                return "\\textbf{[...%s]}" % (exp)
            else:
                return '<font color="%s"><b>[...%s]</b></font>' % (
                    clozeColour, exp)
        new = re.sub(re1, repl, s)
        if haveLatex:
            old = re.sub(re2, "{\\\\bf{}\\1\\\\rm{}}", s)
        else:
            old = re.sub(re2, '<font color="%s"><b>\\1</b></font>'
                         % clozeColour, s)
        reg = "\{(/?(latex|\$|\$\$))\}"
        repl = "[\\1]"
        new = re.sub(reg, repl, new)
        old = re.sub(reg, repl, old)
        news.append(new)
        olds.append(old)
    src.setHtml("<br>".join(news))
    dst.setHtml("<br>".join(olds))
    self.lastCloze = (oldSrc, unicode(src.toHtml()),
                      unicode(dst.toHtml()))
    self.saveFields()
Beispiel #11
0
 def parseLine(self, line):
     fields = line.split(self.pattern)
     fields = [tidyHTML(f.strip()) for f in fields]
     return fields