2012-12-21 08:51:59 +01:00
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
# Copyright: Damien Elmes <anki@ichi2.net>
|
|
|
|
# License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
|
2013-11-13 06:56:37 +01:00
|
|
|
import re
|
|
|
|
import os
|
2016-05-12 06:45:35 +02:00
|
|
|
import urllib.request, urllib.error, urllib.parse
|
2013-11-13 06:56:37 +01:00
|
|
|
import ctypes
|
2016-05-12 06:45:35 +02:00
|
|
|
import urllib.request, urllib.parse, urllib.error
|
2016-10-20 00:40:30 +02:00
|
|
|
import warnings
|
2016-12-15 09:14:47 +01:00
|
|
|
import html
|
2017-01-08 13:52:33 +01:00
|
|
|
import mimetypes
|
|
|
|
import base64
|
2017-02-19 03:49:52 +01:00
|
|
|
import unicodedata
|
2012-12-21 08:51:59 +01:00
|
|
|
|
2013-11-13 06:56:37 +01:00
|
|
|
from anki.lang import _
|
2012-12-21 08:51:59 +01:00
|
|
|
from aqt.qt import *
|
2016-12-15 09:14:47 +01:00
|
|
|
from anki.utils import stripHTML, isWin, isMac, namedtmp, json, stripHTMLMedia, \
|
|
|
|
checksum
|
2013-07-11 10:21:16 +02:00
|
|
|
import anki.sound
|
2012-12-21 08:51:59 +01:00
|
|
|
from anki.hooks import runHook, runFilter
|
|
|
|
from aqt.sound import getAudio
|
|
|
|
from aqt.webview import AnkiWebView
|
2016-07-07 15:39:48 +02:00
|
|
|
from aqt.utils import shortcut, showInfo, showWarning, getFile, \
|
2015-09-28 15:09:30 +02:00
|
|
|
openHelp, tooltip, downArrow
|
2012-12-21 08:51:59 +01:00
|
|
|
import aqt
|
2016-05-12 06:45:35 +02:00
|
|
|
from bs4 import BeautifulSoup
|
2017-10-25 11:42:20 +02:00
|
|
|
import requests
|
2012-12-21 08:51:59 +01:00
|
|
|
|
2015-03-14 19:00:00 +01:00
|
|
|
pics = ("jpg", "jpeg", "png", "tif", "tiff", "gif", "svg", "webp")
|
|
|
|
audio = ("wav", "mp3", "ogg", "flac", "mp4", "swf", "mov", "mpeg", "mkv", "m4a", "3gp", "spx", "oga")
|
2012-12-21 08:51:59 +01:00
|
|
|
|
|
|
|
_html = """
|
2017-08-06 05:55:09 +02:00
|
|
|
<style>
|
|
|
|
html { background: %s; }
|
|
|
|
#topbuts { background: %s; }
|
|
|
|
</style>
|
2016-06-22 06:52:17 +02:00
|
|
|
<div id="topbuts">%s</div>
|
2012-12-21 08:51:59 +01:00
|
|
|
<div id="fields"></div>
|
2016-06-06 09:54:39 +02:00
|
|
|
<div id="dupes" style="display:none;"><a href="#" onclick="pycmd('dupes');return false;">%s</a></div>
|
2012-12-21 08:51:59 +01:00
|
|
|
"""
|
|
|
|
|
|
|
|
# caller is responsible for resetting note on reset
|
2017-02-06 23:21:33 +01:00
|
|
|
class Editor:
|
2012-12-21 08:51:59 +01:00
|
|
|
def __init__(self, mw, widget, parentWindow, addMode=False):
|
|
|
|
self.mw = mw
|
|
|
|
self.widget = widget
|
|
|
|
self.parentWindow = parentWindow
|
|
|
|
self.note = None
|
|
|
|
self.addMode = addMode
|
2017-08-05 07:15:19 +02:00
|
|
|
self.currentField = None
|
2012-12-21 08:51:59 +01:00
|
|
|
# current card, for card layout
|
|
|
|
self.card = None
|
|
|
|
self.setupOuter()
|
|
|
|
self.setupWeb()
|
2017-10-11 20:51:26 +02:00
|
|
|
self.setupShortcuts()
|
2012-12-21 08:51:59 +01:00
|
|
|
self.setupTags()
|
|
|
|
|
|
|
|
# Initial setup
|
|
|
|
############################################################
|
|
|
|
|
|
|
|
def setupOuter(self):
|
|
|
|
l = QVBoxLayout()
|
2016-06-06 09:54:39 +02:00
|
|
|
l.setContentsMargins(0,0,0,0)
|
2012-12-21 08:51:59 +01:00
|
|
|
l.setSpacing(0)
|
|
|
|
self.widget.setLayout(l)
|
|
|
|
self.outerLayout = l
|
|
|
|
|
|
|
|
def setupWeb(self):
|
|
|
|
self.web = EditorWebView(self.widget, self)
|
2016-07-07 09:23:13 +02:00
|
|
|
self.web.title = "editor"
|
2012-12-21 08:51:59 +01:00
|
|
|
self.web.allowDrops = True
|
2016-06-06 09:54:39 +02:00
|
|
|
self.web.onBridgeCmd = self.onBridgeCmd
|
2012-12-21 08:51:59 +01:00
|
|
|
self.outerLayout.addWidget(self.web, 1)
|
2016-06-22 06:52:17 +02:00
|
|
|
|
2017-01-06 15:54:55 +01:00
|
|
|
righttopbtns = list()
|
2017-08-17 05:51:54 +02:00
|
|
|
righttopbtns.append(self._addButton('text_bold', 'bold', _("Bold text (Ctrl+B)"), id='bold'))
|
|
|
|
righttopbtns.append(self._addButton('text_italic', 'italic', _("Italic text (Ctrl+I)"), id='italic'))
|
|
|
|
righttopbtns.append(self._addButton('text_under', 'underline', _("Underline text (Ctrl+U)"), id='underline'))
|
|
|
|
righttopbtns.append(self._addButton('text_super', 'super', _("Superscript (Ctrl++)"), id='superscript'))
|
|
|
|
righttopbtns.append(self._addButton('text_sub', 'sub', _("Subscript (Ctrl+=)"), id='subscript'))
|
|
|
|
righttopbtns.append(self._addButton('text_clear', 'clear', _("Remove formatting (Ctrl+R)")))
|
2017-01-06 15:54:55 +01:00
|
|
|
# The color selection buttons do not use an icon so the HTML must be specified manually
|
2017-08-17 05:51:54 +02:00
|
|
|
tip = _("Set foreground colour (F7)")
|
|
|
|
righttopbtns.append(f'''<button tabindex=-1 class=linkb title="{tip}"
|
2017-01-06 15:54:55 +01:00
|
|
|
type="button" onclick="pycmd('colour');return false;">
|
|
|
|
<div id=forecolor style="display:inline-block; background: #000;border-radius: 5px;"
|
|
|
|
class=topbut></div></button>''')
|
2017-08-17 05:51:54 +02:00
|
|
|
tip = _("Change colour (F8)")
|
|
|
|
righttopbtns.append(f'''<button tabindex=-1 class=linkb title="{tip}"
|
2017-01-06 15:54:55 +01:00
|
|
|
type="button" onclick="pycmd('changeCol');return false;">
|
|
|
|
<div style="display:inline-block; border-radius: 5px;"
|
|
|
|
class="topbut rainbow"></div></button>''')
|
2017-08-17 05:51:54 +02:00
|
|
|
righttopbtns.append(self._addButton('text_cloze', 'cloze', _("Cloze deletion (Ctrl+Shift+C)")))
|
|
|
|
righttopbtns.append(self._addButton('paperclip', 'attach', _("Attach pictures/audio/video (F3)")))
|
|
|
|
righttopbtns.append(self._addButton('media-record', 'record', _("Record audio (F5)")))
|
2017-01-06 15:54:55 +01:00
|
|
|
righttopbtns.append(self._addButton('more', 'more'))
|
2017-01-06 16:37:57 +01:00
|
|
|
righttopbtns = runFilter("setupEditorButtons", righttopbtns, self)
|
2016-06-22 06:52:17 +02:00
|
|
|
topbuts = """
|
2017-01-06 15:54:55 +01:00
|
|
|
<div id="topbutsleft" style="float:left;">
|
|
|
|
<button onclick="pycmd('fields')">%(flds)s...</button>
|
|
|
|
<button onclick="pycmd('cards')">%(cards)s...</button>
|
|
|
|
</div>
|
|
|
|
<div id="topbutsright" style="float:right;">
|
|
|
|
%(rightbts)s
|
|
|
|
</div>
|
|
|
|
""" % dict(flds=_("Fields"), cards=_("Cards"), rightbts="".join(righttopbtns))
|
2017-06-22 10:01:47 +02:00
|
|
|
bgcol = self.mw.app.palette().window().color().name()
|
|
|
|
# then load page
|
2017-08-10 11:02:32 +02:00
|
|
|
self.web.stdHtml(_html % (
|
2017-08-06 05:55:09 +02:00
|
|
|
bgcol, bgcol,
|
2016-06-22 06:52:17 +02:00
|
|
|
topbuts,
|
2017-08-11 12:59:15 +02:00
|
|
|
_("Show Duplicates")),
|
2017-08-10 11:02:32 +02:00
|
|
|
css=["editor.css"],
|
2017-07-28 08:19:06 +02:00
|
|
|
js=["jquery.js", "editor.js"])
|
2012-12-21 08:51:59 +01:00
|
|
|
|
|
|
|
# Top buttons
|
|
|
|
######################################################################
|
|
|
|
|
2017-01-08 13:52:33 +01:00
|
|
|
def resourceToData(self, path):
|
|
|
|
"""Convert a file (specified by a path) into a data URI."""
|
2017-01-14 21:16:50 +01:00
|
|
|
if not os.path.exists(path):
|
|
|
|
raise FileNotFoundError
|
2017-01-08 13:52:33 +01:00
|
|
|
mime, _ = mimetypes.guess_type(path)
|
|
|
|
with open(path, 'rb') as fp:
|
|
|
|
data = fp.read()
|
|
|
|
data64 = b''.join(base64.encodestring(data).splitlines())
|
|
|
|
return 'data:%s;base64,%s' % (mime, data64.decode('ascii'))
|
|
|
|
|
2017-08-24 10:26:51 +02:00
|
|
|
|
2017-08-23 23:53:57 +02:00
|
|
|
def addButton(self, icon, cmd, func, tip="", label="",
|
|
|
|
id=None, toggleable=False, keys=None):
|
|
|
|
"""Assign func to bridge cmd, register shortcut, return button"""
|
|
|
|
if cmd not in self._links:
|
|
|
|
self._links[cmd] = func
|
|
|
|
if keys:
|
2017-08-24 00:17:28 +02:00
|
|
|
QShortcut(QKeySequence(keys), self.widget,
|
|
|
|
activated = lambda s=self: func(s))
|
2017-08-23 23:53:57 +02:00
|
|
|
btn = self._addButton(icon, cmd, tip=tip, label=label,
|
|
|
|
id=id, toggleable=toggleable)
|
|
|
|
return btn
|
|
|
|
|
2017-08-23 23:48:08 +02:00
|
|
|
def _addButton(self, icon, cmd, tip="", label="", id=None, toggleable=False):
|
|
|
|
if icon:
|
|
|
|
if os.path.isabs(icon):
|
|
|
|
iconstr = self.resourceToData(icon)
|
|
|
|
else:
|
|
|
|
iconstr = "/_anki/imgs/{}.png".format(icon)
|
|
|
|
imgelm = '''<img class=topbut src="{}">'''.format(iconstr)
|
2012-12-21 08:51:59 +01:00
|
|
|
else:
|
2017-08-23 23:48:08 +02:00
|
|
|
imgelm = ""
|
|
|
|
if label or not imgelm:
|
|
|
|
labelelm = '''<span class=blabel>{}</span>'''.format(label or cmd)
|
2012-12-21 08:51:59 +01:00
|
|
|
else:
|
2017-08-23 23:48:08 +02:00
|
|
|
labelelm = ""
|
2017-01-06 16:40:10 +01:00
|
|
|
if id:
|
|
|
|
idstr = 'id={}'.format(id)
|
|
|
|
else:
|
|
|
|
idstr = ""
|
2017-01-08 14:33:45 +01:00
|
|
|
if toggleable:
|
|
|
|
toggleScript = 'toggleEditorButton(this);'
|
|
|
|
else:
|
|
|
|
toggleScript = ''
|
2017-08-17 05:51:54 +02:00
|
|
|
tip = shortcut(tip)
|
2017-08-23 23:48:08 +02:00
|
|
|
return ('''<button tabindex=-1 {id} class=linkb type="button" title="{tip}"'''
|
|
|
|
''' onclick="pycmd('{cmd}');{togglesc}return false;">'''
|
|
|
|
'''{imgelm}{labelelm}</button>'''.format(
|
|
|
|
imgelm=imgelm, cmd=cmd, tip=tip, labelelm=labelelm, id=idstr,
|
|
|
|
togglesc=toggleScript)
|
|
|
|
)
|
2012-12-21 08:51:59 +01:00
|
|
|
|
2016-06-22 06:52:17 +02:00
|
|
|
def setupShortcuts(self):
|
|
|
|
cuts = [
|
|
|
|
("Ctrl+L", self.onCardLayout),
|
|
|
|
("Ctrl+B", self.toggleBold),
|
|
|
|
("Ctrl+I", self.toggleItalic),
|
|
|
|
("Ctrl+U", self.toggleUnderline),
|
2017-07-22 02:54:45 +02:00
|
|
|
("Ctrl++", self.toggleSuper),
|
2016-06-22 06:52:17 +02:00
|
|
|
("Ctrl+=", self.toggleSub),
|
|
|
|
("Ctrl+R", self.removeFormat),
|
|
|
|
("F7", self.onForeground),
|
|
|
|
("F8", self.onChangeCol),
|
|
|
|
("Ctrl+Shift+C", self.onCloze),
|
|
|
|
("Ctrl+Shift+Alt+C", self.onCloze),
|
|
|
|
("F3", self.onAddMedia),
|
|
|
|
("F5", self.onRecSound),
|
|
|
|
("Ctrl+T, T", self.insertLatex),
|
|
|
|
("Ctrl+T, E", self.insertLatexEqn),
|
|
|
|
("Ctrl+T, M", self.insertLatexMathEnv),
|
2017-09-08 11:20:37 +02:00
|
|
|
("Ctrl+M, M", self.insertMathjaxInline),
|
|
|
|
("Ctrl+M, E", self.insertMathjaxBlock),
|
2016-06-22 06:52:17 +02:00
|
|
|
("Ctrl+Shift+X", self.onHtmlEdit),
|
2017-08-05 07:15:19 +02:00
|
|
|
("Ctrl+Shift+T", self.onFocusTags)
|
2016-06-22 06:52:17 +02:00
|
|
|
]
|
2017-08-26 10:47:45 +02:00
|
|
|
runHook("setupEditorShortcuts", cuts, self)
|
2016-06-22 06:52:17 +02:00
|
|
|
for keys, fn in cuts:
|
|
|
|
QShortcut(QKeySequence(keys), self.widget, activated=fn)
|
|
|
|
|
2012-12-21 08:51:59 +01:00
|
|
|
def onFields(self):
|
2016-07-14 12:23:44 +02:00
|
|
|
self.saveNow(self._onFields)
|
|
|
|
|
|
|
|
def _onFields(self):
|
2012-12-21 08:51:59 +01:00
|
|
|
from aqt.fields import FieldDialog
|
|
|
|
FieldDialog(self.mw, self.note, parent=self.parentWindow)
|
|
|
|
|
|
|
|
def onCardLayout(self):
|
2016-07-14 12:23:44 +02:00
|
|
|
self.saveNow(self._onCardLayout)
|
|
|
|
|
|
|
|
def _onCardLayout(self):
|
2012-12-21 08:51:59 +01:00
|
|
|
from aqt.clayout import CardLayout
|
|
|
|
if self.card:
|
|
|
|
ord = self.card.ord
|
|
|
|
else:
|
|
|
|
ord = 0
|
2016-07-07 04:32:27 +02:00
|
|
|
CardLayout(self.mw, self.note, ord=ord, parent=self.parentWindow,
|
2012-12-21 08:51:59 +01:00
|
|
|
addMode=self.addMode)
|
2013-07-23 15:35:00 +02:00
|
|
|
if isWin:
|
|
|
|
self.parentWindow.activateWindow()
|
2012-12-21 08:51:59 +01:00
|
|
|
|
|
|
|
# JS->Python bridge
|
|
|
|
######################################################################
|
|
|
|
|
2016-06-06 09:54:39 +02:00
|
|
|
def onBridgeCmd(self, cmd):
|
2012-12-21 08:51:59 +01:00
|
|
|
if not self.note or not runHook:
|
|
|
|
# shutdown
|
|
|
|
return
|
|
|
|
# focus lost or key/button pressed?
|
2016-06-06 09:54:39 +02:00
|
|
|
if cmd.startswith("blur") or cmd.startswith("key"):
|
2017-08-05 07:15:19 +02:00
|
|
|
(type, ord, txt) = cmd.split(":", 2)
|
|
|
|
ord = int(ord)
|
2016-06-06 09:54:39 +02:00
|
|
|
txt = urllib.parse.unquote(txt)
|
2017-02-19 03:49:52 +01:00
|
|
|
txt = unicodedata.normalize("NFC", txt)
|
2012-12-21 08:51:59 +01:00
|
|
|
txt = self.mungeHTML(txt)
|
|
|
|
# misbehaving apps may include a null byte in the text
|
|
|
|
txt = txt.replace("\x00", "")
|
2014-08-01 02:37:23 +02:00
|
|
|
# reverse the url quoting we added to get images to display
|
2014-08-01 02:42:28 +02:00
|
|
|
txt = self.mw.col.media.escapeImages(txt, unescape=True)
|
2017-08-05 07:15:19 +02:00
|
|
|
self.note.fields[ord] = txt
|
2012-12-21 08:51:59 +01:00
|
|
|
if not self.addMode:
|
|
|
|
self.note.flush()
|
|
|
|
self.mw.requireReset()
|
|
|
|
if type == "blur":
|
2017-08-05 07:15:19 +02:00
|
|
|
self.currentField = None
|
2012-12-21 08:51:59 +01:00
|
|
|
# run any filters
|
|
|
|
if runFilter(
|
2017-08-05 07:15:19 +02:00
|
|
|
"editFocusLost", False, self.note, ord):
|
|
|
|
# something updated the note; update it after a subsequent focus
|
|
|
|
# event has had time to fire
|
|
|
|
self.mw.progress.timer(100, self.loadNote, False)
|
2012-12-21 08:51:59 +01:00
|
|
|
else:
|
|
|
|
self.checkValid()
|
|
|
|
else:
|
|
|
|
runHook("editTimer", self.note)
|
|
|
|
self.checkValid()
|
|
|
|
# focused into field?
|
2016-06-06 09:54:39 +02:00
|
|
|
elif cmd.startswith("focus"):
|
|
|
|
(type, num) = cmd.split(":", 1)
|
2012-12-21 08:51:59 +01:00
|
|
|
self.currentField = int(num)
|
2013-05-21 00:19:43 +02:00
|
|
|
runHook("editFocusGained", self.note, self.currentField)
|
2016-06-22 06:52:17 +02:00
|
|
|
elif cmd in self._links:
|
|
|
|
self._links[cmd](self)
|
2012-12-21 08:51:59 +01:00
|
|
|
else:
|
2016-06-22 06:52:17 +02:00
|
|
|
print("uncaught cmd", cmd)
|
2012-12-21 08:51:59 +01:00
|
|
|
|
|
|
|
def mungeHTML(self, txt):
|
2017-09-02 05:26:57 +02:00
|
|
|
txt = re.sub(r"<br>$", "", txt)
|
2016-12-15 09:14:47 +01:00
|
|
|
return txt
|
2012-12-21 08:51:59 +01:00
|
|
|
|
|
|
|
# Setting/unsetting the current note
|
|
|
|
######################################################################
|
|
|
|
|
2017-08-05 07:15:19 +02:00
|
|
|
def setNote(self, note, hide=True, focusTo=None):
|
2012-12-21 08:51:59 +01:00
|
|
|
"Make NOTE the current note."
|
|
|
|
self.note = note
|
2017-08-05 07:15:19 +02:00
|
|
|
self.currentField = None
|
2012-12-21 08:51:59 +01:00
|
|
|
if self.note:
|
2017-08-05 07:15:19 +02:00
|
|
|
self.loadNote(focusTo=focusTo)
|
2012-12-21 08:51:59 +01:00
|
|
|
else:
|
|
|
|
self.hideCompleters()
|
|
|
|
if hide:
|
|
|
|
self.widget.hide()
|
|
|
|
|
2017-08-05 07:15:19 +02:00
|
|
|
def loadNote(self, focusTo=None):
|
2012-12-21 08:51:59 +01:00
|
|
|
if not self.note:
|
|
|
|
return
|
2017-08-05 07:15:19 +02:00
|
|
|
|
2012-12-21 08:51:59 +01:00
|
|
|
data = []
|
2016-05-12 06:45:35 +02:00
|
|
|
for fld, val in list(self.note.items()):
|
2012-12-21 08:51:59 +01:00
|
|
|
data.append((fld, self.mw.col.media.escapeImages(val)))
|
|
|
|
self.widget.show()
|
2017-08-05 07:15:19 +02:00
|
|
|
self.updateTags()
|
|
|
|
|
|
|
|
def oncallback(arg):
|
|
|
|
if not self.note:
|
|
|
|
return
|
|
|
|
self.setupForegroundButton()
|
|
|
|
self.checkValid()
|
2017-08-15 03:38:32 +02:00
|
|
|
if focusTo is not None:
|
|
|
|
self.web.setFocus()
|
2017-08-05 07:15:19 +02:00
|
|
|
runHook("loadNote", self)
|
|
|
|
|
2017-10-25 11:18:00 +02:00
|
|
|
self.web.evalWithCallback("setFields(%s); setFonts(%s); focusField(%s)" % (
|
|
|
|
json.dumps(data),
|
2017-08-05 07:15:19 +02:00
|
|
|
json.dumps(self.fonts()), json.dumps(focusTo)),
|
|
|
|
oncallback)
|
2012-12-21 08:51:59 +01:00
|
|
|
|
|
|
|
def fonts(self):
|
|
|
|
return [(f['font'], f['size'], f['rtl'])
|
|
|
|
for f in self.note.model()['flds']]
|
|
|
|
|
2016-07-14 12:23:44 +02:00
|
|
|
def saveNow(self, callback):
|
|
|
|
"Save unsaved edits then call callback()."
|
2012-12-21 08:51:59 +01:00
|
|
|
if not self.note:
|
2017-08-16 03:49:33 +02:00
|
|
|
# calling code may not expect the callback to fire immediately
|
|
|
|
self.mw.progress.timer(10, callback, False)
|
2012-12-21 08:51:59 +01:00
|
|
|
return
|
|
|
|
self.saveTags()
|
2016-07-14 12:23:44 +02:00
|
|
|
self.web.evalWithCallback("saveNow()", lambda res: callback())
|
2012-12-21 08:51:59 +01:00
|
|
|
|
|
|
|
def checkValid(self):
|
|
|
|
cols = []
|
|
|
|
err = None
|
|
|
|
for f in self.note.fields:
|
|
|
|
cols.append("#fff")
|
|
|
|
err = self.note.dupeOrEmpty()
|
|
|
|
if err == 2:
|
|
|
|
cols[0] = "#fcc"
|
|
|
|
self.web.eval("showDupes();")
|
|
|
|
else:
|
|
|
|
self.web.eval("hideDupes();")
|
|
|
|
self.web.eval("setBackgrounds(%s);" % json.dumps(cols))
|
|
|
|
|
|
|
|
def showDupes(self):
|
2013-01-14 22:25:21 +01:00
|
|
|
contents = stripHTMLMedia(self.note.fields[0])
|
2012-12-21 08:51:59 +01:00
|
|
|
browser = aqt.dialogs.open("Browser", self.mw)
|
|
|
|
browser.form.searchEdit.lineEdit().setText(
|
2013-05-16 07:17:07 +02:00
|
|
|
'"dupe:%s,%s"' % (self.note.model()['id'],
|
|
|
|
contents))
|
2016-07-14 12:23:44 +02:00
|
|
|
browser.onSearchActivated()
|
2012-12-21 08:51:59 +01:00
|
|
|
|
|
|
|
def fieldsAreBlank(self):
|
|
|
|
if not self.note:
|
|
|
|
return True
|
2013-05-24 05:04:28 +02:00
|
|
|
m = self.note.model()
|
|
|
|
for c, f in enumerate(self.note.fields):
|
|
|
|
if f and not m['flds'][c]['sticky']:
|
2012-12-21 08:51:59 +01:00
|
|
|
return False
|
|
|
|
return True
|
|
|
|
|
2017-08-16 04:45:33 +02:00
|
|
|
def cleanup(self):
|
|
|
|
self.setNote(None)
|
|
|
|
# prevent any remaining evalWithCallback() events from firing after C++ object deleted
|
|
|
|
self.web = None
|
|
|
|
|
2012-12-21 08:51:59 +01:00
|
|
|
# HTML editing
|
|
|
|
######################################################################
|
|
|
|
|
|
|
|
def onHtmlEdit(self):
|
2017-08-05 07:15:19 +02:00
|
|
|
field = self.currentField
|
|
|
|
self.saveNow(lambda: self._onHtmlEdit(field))
|
2016-07-14 12:23:44 +02:00
|
|
|
|
2017-08-05 07:15:19 +02:00
|
|
|
def _onHtmlEdit(self, field):
|
2012-12-21 08:51:59 +01:00
|
|
|
d = QDialog(self.widget)
|
|
|
|
form = aqt.forms.edithtml.Ui_Dialog()
|
|
|
|
form.setupUi(d)
|
2016-06-06 09:54:39 +02:00
|
|
|
form.buttonBox.helpRequested.connect(lambda: openHelp("editor"))
|
2017-08-05 07:15:19 +02:00
|
|
|
form.textEdit.setPlainText(self.note.fields[field])
|
2012-12-21 08:51:59 +01:00
|
|
|
form.textEdit.moveCursor(QTextCursor.End)
|
|
|
|
d.exec_()
|
|
|
|
html = form.textEdit.toPlainText()
|
|
|
|
# filter html through beautifulsoup so we can strip out things like a
|
|
|
|
# leading </div>
|
2016-10-20 00:40:30 +02:00
|
|
|
with warnings.catch_warnings() as w:
|
|
|
|
warnings.simplefilter('ignore', UserWarning)
|
|
|
|
html = str(BeautifulSoup(html, "html.parser"))
|
2017-08-05 07:15:19 +02:00
|
|
|
self.note.fields[field] = html
|
|
|
|
self.loadNote(focusTo=field)
|
2012-12-21 08:51:59 +01:00
|
|
|
|
|
|
|
# Tag handling
|
|
|
|
######################################################################
|
|
|
|
|
|
|
|
def setupTags(self):
|
|
|
|
import aqt.tagedit
|
|
|
|
g = QGroupBox(self.widget)
|
|
|
|
g.setFlat(True)
|
|
|
|
tb = QGridLayout()
|
|
|
|
tb.setSpacing(12)
|
2016-06-06 09:54:39 +02:00
|
|
|
tb.setContentsMargins(6,6,6,6)
|
2012-12-21 08:51:59 +01:00
|
|
|
# tags
|
|
|
|
l = QLabel(_("Tags"))
|
|
|
|
tb.addWidget(l, 1, 0)
|
|
|
|
self.tags = aqt.tagedit.TagEdit(self.widget)
|
2016-06-06 09:54:39 +02:00
|
|
|
self.tags.lostFocus.connect(self.saveTags)
|
2013-05-17 07:32:50 +02:00
|
|
|
self.tags.setToolTip(shortcut(_("Jump to tags with Ctrl+Shift+T")))
|
2012-12-21 08:51:59 +01:00
|
|
|
tb.addWidget(self.tags, 1, 1)
|
|
|
|
g.setLayout(tb)
|
|
|
|
self.outerLayout.addWidget(g)
|
|
|
|
|
|
|
|
def updateTags(self):
|
|
|
|
if self.tags.col != self.mw.col:
|
|
|
|
self.tags.setCol(self.mw.col)
|
|
|
|
if not self.tags.text() or not self.addMode:
|
|
|
|
self.tags.setText(self.note.stringTags().strip())
|
|
|
|
|
|
|
|
def saveTags(self):
|
|
|
|
if not self.note:
|
|
|
|
return
|
2017-02-19 03:49:52 +01:00
|
|
|
tagsTxt = unicodedata.normalize("NFC", self.tags.text())
|
2013-05-17 06:51:49 +02:00
|
|
|
self.note.tags = self.mw.col.tags.canonify(
|
2017-02-19 03:49:52 +01:00
|
|
|
self.mw.col.tags.split(tagsTxt))
|
2013-05-17 06:51:49 +02:00
|
|
|
self.tags.setText(self.mw.col.tags.join(self.note.tags).strip())
|
2012-12-21 08:51:59 +01:00
|
|
|
if not self.addMode:
|
|
|
|
self.note.flush()
|
|
|
|
runHook("tagsUpdated", self.note)
|
|
|
|
|
|
|
|
def saveAddModeVars(self):
|
|
|
|
if self.addMode:
|
|
|
|
# save tags to model
|
|
|
|
m = self.note.model()
|
|
|
|
m['tags'] = self.note.tags
|
|
|
|
self.mw.col.models.save(m)
|
|
|
|
|
|
|
|
def hideCompleters(self):
|
|
|
|
self.tags.hideCompleter()
|
|
|
|
|
2017-08-05 07:15:19 +02:00
|
|
|
def onFocusTags(self):
|
|
|
|
self.tags.setFocus()
|
|
|
|
|
2012-12-21 08:51:59 +01:00
|
|
|
# Format buttons
|
|
|
|
######################################################################
|
|
|
|
|
2016-06-22 06:52:17 +02:00
|
|
|
def toggleBold(self):
|
2012-12-21 08:51:59 +01:00
|
|
|
self.web.eval("setFormat('bold');")
|
|
|
|
|
2016-06-22 06:52:17 +02:00
|
|
|
def toggleItalic(self):
|
2012-12-21 08:51:59 +01:00
|
|
|
self.web.eval("setFormat('italic');")
|
|
|
|
|
2016-06-22 06:52:17 +02:00
|
|
|
def toggleUnderline(self):
|
2012-12-21 08:51:59 +01:00
|
|
|
self.web.eval("setFormat('underline');")
|
|
|
|
|
2016-06-22 06:52:17 +02:00
|
|
|
def toggleSuper(self):
|
2012-12-21 08:51:59 +01:00
|
|
|
self.web.eval("setFormat('superscript');")
|
|
|
|
|
2016-06-22 06:52:17 +02:00
|
|
|
def toggleSub(self):
|
2012-12-21 08:51:59 +01:00
|
|
|
self.web.eval("setFormat('subscript');")
|
|
|
|
|
|
|
|
def removeFormat(self):
|
|
|
|
self.web.eval("setFormat('removeFormat');")
|
|
|
|
|
|
|
|
def onCloze(self):
|
|
|
|
# check that the model is set up for cloze deletion
|
2014-03-09 19:12:39 +01:00
|
|
|
if not re.search('{{(.*:)*cloze:',self.note.model()['tmpls'][0]['qfmt']):
|
2012-12-21 08:51:59 +01:00
|
|
|
if self.addMode:
|
2013-05-17 08:57:22 +02:00
|
|
|
tooltip(_("Warning, cloze deletions will not work until "
|
|
|
|
"you switch the type at the top to Cloze."))
|
2012-12-21 08:51:59 +01:00
|
|
|
else:
|
|
|
|
showInfo(_("""\
|
|
|
|
To make a cloze deletion on an existing note, you need to change it \
|
|
|
|
to a cloze type first, via Edit>Change Note Type."""))
|
2013-05-17 08:57:22 +02:00
|
|
|
return
|
2012-12-21 08:51:59 +01:00
|
|
|
# find the highest existing cloze
|
|
|
|
highest = 0
|
2016-05-12 06:45:35 +02:00
|
|
|
for name, val in list(self.note.items()):
|
2012-12-21 08:51:59 +01:00
|
|
|
m = re.findall("\{\{c(\d+)::", val)
|
|
|
|
if m:
|
|
|
|
highest = max(highest, sorted([int(x) for x in m])[-1])
|
|
|
|
# reuse last?
|
|
|
|
if not self.mw.app.keyboardModifiers() & Qt.AltModifier:
|
|
|
|
highest += 1
|
|
|
|
# must start at 1
|
|
|
|
highest = max(1, highest)
|
|
|
|
self.web.eval("wrap('{{c%d::', '}}');" % highest)
|
|
|
|
|
|
|
|
# Foreground colour
|
|
|
|
######################################################################
|
|
|
|
|
2016-06-22 06:52:17 +02:00
|
|
|
def setupForegroundButton(self):
|
2012-12-21 08:51:59 +01:00
|
|
|
self.fcolour = self.mw.pm.profile.get("lastColour", "#00f")
|
|
|
|
self.onColourChanged()
|
|
|
|
|
|
|
|
# use last colour
|
|
|
|
def onForeground(self):
|
|
|
|
self._wrapWithColour(self.fcolour)
|
|
|
|
|
|
|
|
# choose new colour
|
|
|
|
def onChangeCol(self):
|
|
|
|
new = QColorDialog.getColor(QColor(self.fcolour), None)
|
|
|
|
# native dialog doesn't refocus us for some reason
|
|
|
|
self.parentWindow.activateWindow()
|
|
|
|
if new.isValid():
|
|
|
|
self.fcolour = new.name()
|
|
|
|
self.onColourChanged()
|
|
|
|
self._wrapWithColour(self.fcolour)
|
|
|
|
|
|
|
|
def _updateForegroundButton(self):
|
2016-06-22 06:52:17 +02:00
|
|
|
self.web.eval("setFGButton('%s')" % self.fcolour)
|
2012-12-21 08:51:59 +01:00
|
|
|
|
|
|
|
def onColourChanged(self):
|
|
|
|
self._updateForegroundButton()
|
|
|
|
self.mw.pm.profile['lastColour'] = self.fcolour
|
|
|
|
|
|
|
|
def _wrapWithColour(self, colour):
|
|
|
|
self.web.eval("setFormat('forecolor', '%s')" % colour)
|
|
|
|
|
|
|
|
# Audio/video/images
|
|
|
|
######################################################################
|
|
|
|
|
|
|
|
def onAddMedia(self):
|
|
|
|
key = (_("Media") +
|
|
|
|
" (*.jpg *.png *.gif *.tiff *.svg *.tif *.jpeg "+
|
|
|
|
"*.mp3 *.ogg *.wav *.avi *.ogv *.mpg *.mpeg *.mov *.mp4 " +
|
2017-03-02 03:10:13 +01:00
|
|
|
"*.mkv *.ogx *.ogv *.oga *.flv *.swf *.flac *.webp *.m4a)")
|
2012-12-21 08:51:59 +01:00
|
|
|
def accept(file):
|
|
|
|
self.addMedia(file, canDelete=True)
|
|
|
|
file = getFile(self.widget, _("Add Media"), accept, key, key="media")
|
|
|
|
self.parentWindow.activateWindow()
|
|
|
|
|
|
|
|
def addMedia(self, path, canDelete=False):
|
|
|
|
html = self._addMedia(path, canDelete)
|
|
|
|
self.web.eval("setFormat('inserthtml', %s);" % json.dumps(html))
|
|
|
|
|
|
|
|
def _addMedia(self, path, canDelete=False):
|
2013-07-11 10:21:16 +02:00
|
|
|
"Add to media folder and return local img or sound tag."
|
2012-12-21 08:51:59 +01:00
|
|
|
# copy to media folder
|
2013-07-11 10:21:16 +02:00
|
|
|
fname = self.mw.col.media.addFile(path)
|
2012-12-21 08:51:59 +01:00
|
|
|
# remove original?
|
|
|
|
if canDelete and self.mw.pm.profile['deleteMedia']:
|
2013-07-11 10:21:16 +02:00
|
|
|
if os.path.abspath(fname) != os.path.abspath(path):
|
2012-12-21 08:51:59 +01:00
|
|
|
try:
|
|
|
|
os.unlink(path)
|
|
|
|
except:
|
|
|
|
pass
|
|
|
|
# return a local html link
|
2013-07-11 10:21:16 +02:00
|
|
|
return self.fnameToLink(fname)
|
2012-12-21 08:51:59 +01:00
|
|
|
|
|
|
|
def onRecSound(self):
|
|
|
|
try:
|
|
|
|
file = getAudio(self.widget)
|
2016-05-12 06:45:35 +02:00
|
|
|
except Exception as e:
|
2012-12-21 08:51:59 +01:00
|
|
|
showWarning(_(
|
|
|
|
"Couldn't record audio. Have you installed lame and sox?") +
|
2013-10-20 03:57:42 +02:00
|
|
|
"\n\n" + repr(str(e)))
|
2012-12-21 08:51:59 +01:00
|
|
|
return
|
2017-06-23 05:04:32 +02:00
|
|
|
if file:
|
|
|
|
self.addMedia(file)
|
2012-12-21 08:51:59 +01:00
|
|
|
|
2013-07-11 10:21:16 +02:00
|
|
|
# Media downloads
|
|
|
|
######################################################################
|
|
|
|
|
|
|
|
def urlToLink(self, url):
|
|
|
|
fname = self.urlToFile(url)
|
|
|
|
if not fname:
|
2017-07-11 06:58:22 +02:00
|
|
|
return url
|
2013-07-11 10:21:16 +02:00
|
|
|
return self.fnameToLink(fname)
|
|
|
|
|
|
|
|
def fnameToLink(self, fname):
|
|
|
|
ext = fname.split(".")[-1].lower()
|
|
|
|
if ext in pics:
|
2016-05-12 06:45:35 +02:00
|
|
|
name = urllib.parse.quote(fname.encode("utf8"))
|
2013-07-11 10:21:16 +02:00
|
|
|
return '<img src="%s">' % name
|
|
|
|
else:
|
2017-10-02 09:21:34 +02:00
|
|
|
anki.sound.clearAudioQueue()
|
2013-07-11 10:21:16 +02:00
|
|
|
anki.sound.play(fname)
|
|
|
|
return '[sound:%s]' % fname
|
|
|
|
|
|
|
|
def urlToFile(self, url):
|
|
|
|
l = url.lower()
|
|
|
|
for suffix in pics+audio:
|
2017-10-18 13:58:36 +02:00
|
|
|
if l.endswith("." + suffix):
|
2013-07-11 10:21:16 +02:00
|
|
|
return self._retrieveURL(url)
|
2013-11-26 09:57:02 +01:00
|
|
|
# not a supported type
|
2013-07-11 10:21:16 +02:00
|
|
|
return
|
|
|
|
|
2013-07-18 13:32:41 +02:00
|
|
|
def isURL(self, s):
|
|
|
|
s = s.lower()
|
|
|
|
return (s.startswith("http://")
|
|
|
|
or s.startswith("https://")
|
2013-09-20 07:41:56 +02:00
|
|
|
or s.startswith("ftp://")
|
|
|
|
or s.startswith("file://"))
|
2013-07-18 13:32:41 +02:00
|
|
|
|
2013-07-11 10:21:16 +02:00
|
|
|
def _retrieveURL(self, url):
|
|
|
|
"Download file into media folder and return local filename or None."
|
2013-09-20 07:41:56 +02:00
|
|
|
# urllib doesn't understand percent-escaped utf8, but requires things like
|
2017-08-06 19:03:00 +02:00
|
|
|
# '#' to be escaped.
|
|
|
|
url = urllib.parse.unquote(url)
|
2013-07-11 10:21:16 +02:00
|
|
|
if url.lower().startswith("file://"):
|
|
|
|
url = url.replace("%", "%25")
|
|
|
|
url = url.replace("#", "%23")
|
2017-10-25 11:42:20 +02:00
|
|
|
local = True
|
|
|
|
else:
|
|
|
|
local = False
|
2013-09-20 07:41:56 +02:00
|
|
|
# fetch it into a temporary folder
|
2013-07-11 10:21:16 +02:00
|
|
|
self.mw.progress.start(
|
|
|
|
immediate=True, parent=self.parentWindow)
|
|
|
|
try:
|
2017-10-25 11:42:20 +02:00
|
|
|
if local:
|
|
|
|
req = urllib.request.Request(url, None, {
|
|
|
|
'User-Agent': 'Mozilla/5.0 (compatible; Anki)'})
|
|
|
|
filecontents = urllib.request.urlopen(req).read()
|
|
|
|
else:
|
|
|
|
r = requests.get(url)
|
|
|
|
if r.status_code != 200:
|
|
|
|
showWarning(_("Unexpected response code: %s") % r.status_code)
|
|
|
|
return
|
|
|
|
filecontents = r.content
|
2016-05-12 06:45:35 +02:00
|
|
|
except urllib.error.URLError as e:
|
2013-07-11 10:21:16 +02:00
|
|
|
showWarning(_("An error occurred while opening %s") % e)
|
|
|
|
return
|
|
|
|
finally:
|
|
|
|
self.mw.progress.finish()
|
2016-05-12 06:45:35 +02:00
|
|
|
path = urllib.parse.unquote(url)
|
2013-07-11 10:21:16 +02:00
|
|
|
return self.mw.col.media.writeData(path, filecontents)
|
|
|
|
|
2016-12-15 09:14:47 +01:00
|
|
|
# Paste/drag&drop
|
2013-07-11 10:21:16 +02:00
|
|
|
######################################################################
|
|
|
|
|
2016-12-15 09:14:47 +01:00
|
|
|
removeTags = ["script", "iframe", "object", "style"]
|
|
|
|
|
2017-11-11 02:51:30 +01:00
|
|
|
def _pastePreFilter(self, html, internal):
|
2016-10-20 00:40:30 +02:00
|
|
|
with warnings.catch_warnings() as w:
|
|
|
|
warnings.simplefilter('ignore', UserWarning)
|
|
|
|
doc = BeautifulSoup(html, "html.parser")
|
2016-12-15 09:14:47 +01:00
|
|
|
|
2017-11-11 02:51:30 +01:00
|
|
|
if not internal:
|
|
|
|
for tag in self.removeTags:
|
|
|
|
for node in doc(tag):
|
|
|
|
node.decompose()
|
2016-12-15 09:14:47 +01:00
|
|
|
|
2017-11-11 02:51:30 +01:00
|
|
|
# convert p tags to divs
|
|
|
|
for node in doc("p"):
|
|
|
|
node.name = "div"
|
2016-12-15 09:14:47 +01:00
|
|
|
|
2013-07-11 10:21:16 +02:00
|
|
|
for tag in doc("img"):
|
|
|
|
try:
|
2017-11-11 02:51:30 +01:00
|
|
|
src = tag['src']
|
2013-07-11 10:21:16 +02:00
|
|
|
except KeyError:
|
|
|
|
# for some bizarre reason, mnemosyne removes src elements
|
|
|
|
# from missing media
|
2017-11-11 02:51:30 +01:00
|
|
|
continue
|
|
|
|
|
|
|
|
# in internal pastes, rewrite mediasrv references to relative
|
|
|
|
if internal:
|
|
|
|
m = re.match("http://127.0.0.1:\d+/(.*)$", src)
|
|
|
|
if m:
|
|
|
|
tag['src'] = m.group(1)
|
|
|
|
else:
|
|
|
|
# in external pastes, download remote media
|
|
|
|
if self.isURL(src):
|
|
|
|
fname = self.urlToFile(src)
|
|
|
|
if fname:
|
|
|
|
tag['src'] = fname
|
2016-12-15 09:14:47 +01:00
|
|
|
|
2016-05-12 06:45:35 +02:00
|
|
|
html = str(doc)
|
2013-07-11 10:21:16 +02:00
|
|
|
return html
|
|
|
|
|
2016-12-15 09:14:47 +01:00
|
|
|
def doPaste(self, html, internal):
|
2017-11-11 02:51:30 +01:00
|
|
|
html = self._pastePreFilter(html, internal)
|
2017-10-25 12:20:28 +02:00
|
|
|
extended = self.mw.app.queryKeyboardModifiers() & Qt.ShiftModifier
|
|
|
|
if extended:
|
|
|
|
extended = "true"
|
|
|
|
else:
|
|
|
|
extended = "false"
|
|
|
|
self.web.eval("pasteHTML(%s, %s, %s);" % (
|
|
|
|
json.dumps(html), json.dumps(internal), extended))
|
2016-12-15 09:14:47 +01:00
|
|
|
|
|
|
|
def doDrop(self, html, internal):
|
2017-08-01 09:40:51 +02:00
|
|
|
self.web.evalWithCallback("makeDropTargetCurrent();",
|
2016-12-15 09:14:47 +01:00
|
|
|
lambda _: self.doPaste(html, internal))
|
|
|
|
|
|
|
|
def onPaste(self):
|
|
|
|
self.web.onPaste()
|
|
|
|
|
2017-09-02 05:48:03 +02:00
|
|
|
def onCutOrCopy(self):
|
|
|
|
self.web.flagAnkiText()
|
|
|
|
|
2012-12-21 08:51:59 +01:00
|
|
|
# Advanced menu
|
|
|
|
######################################################################
|
|
|
|
|
|
|
|
def onAdvanced(self):
|
|
|
|
m = QMenu(self.mw)
|
2017-09-08 11:20:37 +02:00
|
|
|
a = m.addAction(_("MathJax inline"))
|
|
|
|
a.triggered.connect(self.insertMathjaxInline)
|
2017-09-19 09:07:28 +02:00
|
|
|
a.setShortcut(QKeySequence("Ctrl+M, M"))
|
2017-09-08 11:20:37 +02:00
|
|
|
a = m.addAction(_("MathJax block"))
|
|
|
|
a.triggered.connect(self.insertMathjaxBlock)
|
2017-09-19 09:07:28 +02:00
|
|
|
a.setShortcut(QKeySequence("Ctrl+M, E"))
|
2012-12-21 08:51:59 +01:00
|
|
|
a = m.addAction(_("LaTeX"))
|
2016-06-06 09:54:39 +02:00
|
|
|
a.triggered.connect(self.insertLatex)
|
2017-09-19 09:07:28 +02:00
|
|
|
a.setShortcut(QKeySequence("Ctrl+T, T"))
|
2012-12-21 08:51:59 +01:00
|
|
|
a = m.addAction(_("LaTeX equation"))
|
2016-06-06 09:54:39 +02:00
|
|
|
a.triggered.connect(self.insertLatexEqn)
|
2017-09-19 09:07:28 +02:00
|
|
|
a.setShortcut(QKeySequence("Ctrl+T, E"))
|
2012-12-21 08:51:59 +01:00
|
|
|
a = m.addAction(_("LaTeX math env."))
|
2016-06-06 09:54:39 +02:00
|
|
|
a.triggered.connect(self.insertLatexMathEnv)
|
2017-09-19 09:07:28 +02:00
|
|
|
a.setShortcut(QKeySequence("Ctrl+T, M"))
|
2012-12-21 08:51:59 +01:00
|
|
|
a = m.addAction(_("Edit HTML"))
|
2016-06-06 09:54:39 +02:00
|
|
|
a.triggered.connect(self.onHtmlEdit)
|
2017-09-19 09:07:28 +02:00
|
|
|
a.setShortcut(QKeySequence("Ctrl+Shift+X"))
|
2012-12-21 08:51:59 +01:00
|
|
|
m.exec_(QCursor.pos())
|
|
|
|
|
|
|
|
# LaTeX
|
|
|
|
######################################################################
|
|
|
|
|
|
|
|
def insertLatex(self):
|
|
|
|
self.web.eval("wrap('[latex]', '[/latex]');")
|
|
|
|
|
|
|
|
def insertLatexEqn(self):
|
|
|
|
self.web.eval("wrap('[$]', '[/$]');")
|
|
|
|
|
|
|
|
def insertLatexMathEnv(self):
|
|
|
|
self.web.eval("wrap('[$$]', '[/$$]');")
|
2017-09-08 11:20:37 +02:00
|
|
|
|
|
|
|
def insertMathjaxInline(self):
|
|
|
|
self.web.eval("wrap('\\\\(', '\\\\)');")
|
|
|
|
|
|
|
|
def insertMathjaxBlock(self):
|
|
|
|
self.web.eval("wrap('\\\\[', '\\\\]');")
|
2012-12-21 08:51:59 +01:00
|
|
|
|
2016-06-22 06:52:17 +02:00
|
|
|
# Links from HTML
|
|
|
|
######################################################################
|
|
|
|
|
|
|
|
_links = dict(
|
|
|
|
fields=onFields,
|
|
|
|
cards=onCardLayout,
|
|
|
|
bold=toggleBold,
|
|
|
|
italic=toggleItalic,
|
|
|
|
underline=toggleUnderline,
|
|
|
|
super=toggleSuper,
|
|
|
|
sub=toggleSub,
|
|
|
|
clear=removeFormat,
|
|
|
|
colour=onForeground,
|
|
|
|
changeCol=onChangeCol,
|
|
|
|
cloze=onCloze,
|
|
|
|
attach=onAddMedia,
|
|
|
|
record=onRecSound,
|
|
|
|
more=onAdvanced,
|
|
|
|
dupes=showDupes,
|
2016-12-15 09:14:47 +01:00
|
|
|
paste=onPaste,
|
2017-09-02 05:48:03 +02:00
|
|
|
cutOrCopy=onCutOrCopy,
|
2016-06-22 06:52:17 +02:00
|
|
|
)
|
|
|
|
|
2012-12-21 08:51:59 +01:00
|
|
|
# Pasting, drag & drop, and keyboard layouts
|
|
|
|
######################################################################
|
|
|
|
|
|
|
|
class EditorWebView(AnkiWebView):
|
|
|
|
|
|
|
|
def __init__(self, parent, editor):
|
2014-09-15 08:04:14 +02:00
|
|
|
AnkiWebView.__init__(self)
|
2012-12-21 08:51:59 +01:00
|
|
|
self.editor = editor
|
|
|
|
self.strip = self.editor.mw.pm.profile['stripHTML']
|
2016-06-06 09:54:39 +02:00
|
|
|
self.setAcceptDrops(True)
|
2017-08-31 10:10:37 +02:00
|
|
|
self._markInternal = False
|
|
|
|
clip = self.editor.mw.app.clipboard()
|
|
|
|
clip.dataChanged.connect(self._onClipboardChange)
|
|
|
|
|
|
|
|
def _onClipboardChange(self):
|
|
|
|
if self._markInternal:
|
|
|
|
self._markInternal = False
|
|
|
|
self._flagAnkiText()
|
2012-12-21 08:51:59 +01:00
|
|
|
|
|
|
|
def onCut(self):
|
2016-06-06 09:54:39 +02:00
|
|
|
self.triggerPageAction(QWebEnginePage.Cut)
|
2012-12-21 08:51:59 +01:00
|
|
|
|
|
|
|
def onCopy(self):
|
2016-06-06 09:54:39 +02:00
|
|
|
self.triggerPageAction(QWebEnginePage.Copy)
|
2012-12-21 08:51:59 +01:00
|
|
|
|
|
|
|
def onPaste(self):
|
2016-12-15 09:14:47 +01:00
|
|
|
mime = self.editor.mw.app.clipboard().mimeData(mode=QClipboard.Clipboard)
|
|
|
|
html, internal = self._processMime(mime)
|
|
|
|
if not html:
|
|
|
|
return
|
|
|
|
self.editor.doPaste(html, internal)
|
2012-12-21 08:51:59 +01:00
|
|
|
|
2016-12-15 09:14:47 +01:00
|
|
|
def dropEvent(self, evt):
|
|
|
|
mime = evt.mimeData()
|
2012-12-21 08:51:59 +01:00
|
|
|
|
2016-12-15 09:14:47 +01:00
|
|
|
if evt.source() and mime.hasHtml():
|
|
|
|
# don't filter html from other fields
|
|
|
|
html, internal = mime.html(), True
|
2012-12-21 08:51:59 +01:00
|
|
|
else:
|
2016-12-15 09:14:47 +01:00
|
|
|
html, internal = self._processMime(mime)
|
|
|
|
|
|
|
|
if not html:
|
|
|
|
return
|
|
|
|
|
|
|
|
self.editor.doDrop(html, internal)
|
|
|
|
|
|
|
|
# returns (html, isInternal)
|
|
|
|
def _processMime(self, mime):
|
2017-01-25 06:12:48 +01:00
|
|
|
# print("html=%s image=%s urls=%s txt=%s" % (
|
|
|
|
# mime.hasHtml(), mime.hasImage(), mime.hasUrls(), mime.hasText()))
|
|
|
|
# print("html", mime.html())
|
|
|
|
# print("urls", mime.urls())
|
|
|
|
# print("text", mime.text())
|
2016-12-15 09:14:47 +01:00
|
|
|
|
|
|
|
# try various content types in turn
|
|
|
|
html, internal = self._processHtml(mime)
|
|
|
|
if html:
|
|
|
|
return html, internal
|
|
|
|
for fn in (self._processUrls, self._processImage, self._processText):
|
|
|
|
html = fn(mime)
|
|
|
|
if html:
|
|
|
|
return html, False
|
|
|
|
return "", False
|
2012-12-21 08:51:59 +01:00
|
|
|
|
|
|
|
def _processUrls(self, mime):
|
2016-12-15 09:14:47 +01:00
|
|
|
if not mime.hasUrls():
|
|
|
|
return
|
|
|
|
|
2012-12-21 08:51:59 +01:00
|
|
|
url = mime.urls()[0].toString()
|
2013-05-09 08:34:16 +02:00
|
|
|
# chrome likes to give us the URL twice with a \n
|
|
|
|
url = url.splitlines()[0]
|
2016-12-15 09:14:47 +01:00
|
|
|
return self.editor.urlToLink(url)
|
2012-12-21 08:51:59 +01:00
|
|
|
|
|
|
|
def _processText(self, mime):
|
2016-12-15 09:14:47 +01:00
|
|
|
if not mime.hasText():
|
|
|
|
return
|
|
|
|
|
|
|
|
txt = mime.text()
|
|
|
|
|
2012-12-21 08:51:59 +01:00
|
|
|
# if the user is pasting an image or sound link, convert it to local
|
2013-07-18 13:32:41 +02:00
|
|
|
if self.editor.isURL(txt):
|
2012-12-21 08:51:59 +01:00
|
|
|
txt = txt.split("\r\n")[0]
|
2016-12-15 09:14:47 +01:00
|
|
|
return self.editor.urlToLink(txt)
|
|
|
|
|
|
|
|
# normal text; convert it to HTML
|
2017-07-12 02:57:01 +02:00
|
|
|
txt = html.escape(txt)
|
|
|
|
return txt
|
2012-12-21 08:51:59 +01:00
|
|
|
|
|
|
|
def _processHtml(self, mime):
|
2016-12-15 09:14:47 +01:00
|
|
|
if not mime.hasHtml():
|
|
|
|
return None, False
|
2012-12-21 08:51:59 +01:00
|
|
|
html = mime.html()
|
2016-12-15 09:14:47 +01:00
|
|
|
|
|
|
|
# no filtering required for internal pastes
|
|
|
|
if html.startswith("<!--anki-->"):
|
|
|
|
return html[11:], True
|
|
|
|
|
|
|
|
return html, False
|
2012-12-21 08:51:59 +01:00
|
|
|
|
|
|
|
def _processImage(self, mime):
|
|
|
|
im = QImage(mime.imageData())
|
2016-12-15 09:14:47 +01:00
|
|
|
uname = namedtmp("paste")
|
2012-12-21 08:51:59 +01:00
|
|
|
if self.editor.mw.pm.profile.get("pastePNG", False):
|
|
|
|
ext = ".png"
|
|
|
|
im.save(uname+ext, None, 50)
|
|
|
|
else:
|
|
|
|
ext = ".jpg"
|
|
|
|
im.save(uname+ext, None, 80)
|
2016-12-15 09:14:47 +01:00
|
|
|
|
2012-12-21 08:51:59 +01:00
|
|
|
# invalid image?
|
2016-12-15 09:14:47 +01:00
|
|
|
path = uname+ext
|
|
|
|
if not os.path.exists(path):
|
|
|
|
return
|
|
|
|
|
|
|
|
# hash and rename
|
|
|
|
csum = checksum(open(path, "rb").read())
|
|
|
|
newpath = "{}-{}{}".format(uname, csum, ext)
|
|
|
|
os.rename(path, newpath)
|
|
|
|
|
|
|
|
# add to media and return resulting html link
|
|
|
|
return self.editor._addMedia(newpath)
|
2012-12-21 08:51:59 +01:00
|
|
|
|
2017-09-02 05:48:03 +02:00
|
|
|
def flagAnkiText(self):
|
|
|
|
# be ready to adjust when clipboard event fires
|
|
|
|
self._markInternal = True
|
|
|
|
|
2012-12-21 08:51:59 +01:00
|
|
|
def _flagAnkiText(self):
|
|
|
|
# add a comment in the clipboard html so we can tell text is copied
|
|
|
|
# from us and doesn't need to be stripped
|
|
|
|
clip = self.editor.mw.app.clipboard()
|
|
|
|
mime = clip.mimeData()
|
|
|
|
if not mime.hasHtml():
|
|
|
|
return
|
|
|
|
html = mime.html()
|
2017-08-31 10:10:37 +02:00
|
|
|
mime.setHtml("<!--anki-->" + html)
|
|
|
|
clip.setMimeData(mime)
|
2012-12-21 08:51:59 +01:00
|
|
|
|
|
|
|
def contextMenuEvent(self, evt):
|
|
|
|
m = QMenu(self)
|
|
|
|
a = m.addAction(_("Cut"))
|
2016-06-06 09:54:39 +02:00
|
|
|
a.triggered.connect(self.onCut)
|
2012-12-21 08:51:59 +01:00
|
|
|
a = m.addAction(_("Copy"))
|
2016-06-06 09:54:39 +02:00
|
|
|
a.triggered.connect(self.onCopy)
|
2012-12-21 08:51:59 +01:00
|
|
|
a = m.addAction(_("Paste"))
|
2016-06-06 09:54:39 +02:00
|
|
|
a.triggered.connect(self.onPaste)
|
2013-07-16 09:42:50 +02:00
|
|
|
runHook("EditorWebView.contextMenuEvent", self, m)
|
2012-12-21 08:51:59 +01:00
|
|
|
m.popup(QCursor.pos())
|