Skip to content
This repository has been archived by the owner on Mar 24, 2024. It is now read-only.

Commit

Permalink
Merge branch 'release_1.0.4'
Browse files Browse the repository at this point in the history
  • Loading branch information
fonol committed Jun 18, 2020
2 parents 540c862 + 072b069 commit 77481f2
Show file tree
Hide file tree
Showing 25 changed files with 210 additions and 195 deletions.
1 change: 1 addition & 0 deletions config.json
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,7 @@
"pdf.onOpen.autoFillTagsWithPDFsTags" : true,
"pdf.onOpen.autoFillFieldsWithPDFName": [],
"pdf.import.folders_to_search" : [],
"pdf.shortcuts.toggle_search_on_select": "CTRL+S",
"notes.queue.priorityScaleFactor": 5,
"notes.queue.missedNotesHandling": "remove-schedule",
"notes.queue.scheduleDialogOnDoneUnscheduledNotes": false,
Expand Down
6 changes: 5 additions & 1 deletion src/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -292,7 +292,7 @@ def reset_state(shortcuts: List[Tuple], editor: Editor):
def cb(night_mode: bool):
state.night_mode = night_mode

editor.web.evalWithCallback("() => { return document.body.classList.contains('nightMode'); }", cb)
editor.web.evalWithCallback("(() => { return document.body.classList.contains('nightMode'); })();", cb)

def register_shortcuts(shortcuts: List[Tuple], editor: Editor):
""" Register shortcuts used by the add-on. """
Expand All @@ -306,6 +306,10 @@ def register_shortcuts(shortcuts: List[Tuple], editor: Editor):
QShortcut(QKeySequence(config["notes.editor.shortcut"]), editor.widget, activated=show_note_modal)
except:
pass
try:
QShortcut(QKeySequence(config["pdf.shortcuts.toggle_search_on_select"]), editor.widget, activated=lambda: editor.web.eval("togglePDFSelect()"))
except:
pass

def show_note_modal():
if not state.note_editor_shown:
Expand Down
37 changes: 36 additions & 1 deletion src/command_parsing.py
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,14 @@ def expanded_on_bridge_cmd(handled: Tuple[bool, Any], cmd: str, self: Any) -> Tu
#this renders the popup
display_tag_info(self, cmd.split()[1], " ".join(cmd.split()[2:]), index)

elif cmd.startswith("siac-copy-to-cb "):
# copy to clipboard
try:
QApplication.clipboard().setText(cmd[16:])
tooltip("Copied to Clipboard!")
except:
tooltip("Failed to copy to clipboard!")

elif cmd.startswith("siac-rerender "):
ix = int(cmd.split()[1])
if check_index() and ix < len(index.ui.previous_calls):
Expand Down Expand Up @@ -1449,6 +1457,7 @@ def get_index_info():
<tr><td>Confirm new note and keep open</td><td> <b>Ctrl+Shift+Enter</b></td></tr>
<tr><td>PDF: Quick Open</td><td> <b>Ctrl+O</b></td></tr>
<tr><td>PDF: Toggle Top & Bottom Bar</td><td> <b>F11</b></td></tr>
<tr><td>PDF: Toggle Search on Select</td><td> <b>%s</b></td></tr>
</table>
""" % (index.type, sqlite3.sqlite_version,
Expand All @@ -1465,9 +1474,35 @@ def get_index_info():
config["toggleShortcut"],
"None" if len(excluded_fields) == 0 else "<b>%s</b> field(s) among <b>%s</b> note type(s)" % (field_c, len(excluded_fields)),
("%ssiac-notes.db" % config["addonNoteDBFolderPath"]) if config["addonNoteDBFolderPath"] is not None and len(config["addonNoteDBFolderPath"]) > 0 else utility.misc.get_user_files_folder_path() + "siac-notes.db",
config["notes.editor.shortcut"]
config["notes.editor.shortcut"],
config["pdf.shortcuts.toggle_search_on_select"]
)

changes = changelog()

if changes:
html += "<br/><br/><b>Changelog:</b><hr>"
for ix, c in enumerate(changes):
html += f"<br>{ix + 1}. {c}"

issues = known_issues()

if issues:
html += "<br/><br/><b>Known Issues:</b><hr>"
for ix, i in enumerate(issues):
html += f"<br>{ix + 1}. {i}"

html += """
<br><br>
<b>Contact:</b>
<hr>
<br>
For bug reports, feedback or suggestions: <a href='https://github.com/fonol/anki-search-inside-add-card'>Github Repository</a>
<br>
If you want to support this project: <a href='https://www.patreon.com/tomtomtom'>Patreon Site</a>
"""

return html

@requires_index_loaded
Expand Down
43 changes: 2 additions & 41 deletions src/dialogs/editor.py
Original file line number Diff line number Diff line change
Expand Up @@ -175,45 +175,6 @@ def setup_ui(self):
layout_main.addWidget(self.tabs)
self.setLayout(layout_main)

styles = ""
if self.dark_mode_used:
styles += """
QTabBar {
background: #222;
color: #666;
border-radius: 0;
border: 2px solid #222;
}
QTabWidget::pane {
border-color: black;
color: #666;
border-radius: 0;
border: 2px solid #222;
}
QTabBar::tab:top {
margin: 1px 1px 0 0;
padding: 4px 8px;
border-bottom: 3px solid transparent;
}
QTabBar::tab:selected {
color: white;
border: 0;
}
QTabBar::tab:top:hover {
border-bottom: 3px solid #444;
}
QTabBar::tab:top:selected {
border-bottom: 3px solid #1086e2;
}
QTabBar::tab:hover,
QTabBar::tab:focus {
}
"""
self.setStyleSheet(styles)
self.create_tab.title.setFocus()

# self.exec_()
Expand Down Expand Up @@ -311,7 +272,7 @@ def on_update_clicked(self):

NoteEditor.last_tags = tags
update_note(self.note_id, title, text, source, tags, specific_schedule, priority)
run_hooks("user-note-edited")
run_hooks("user-note-edited", self.note_id)

self.reject()

Expand Down Expand Up @@ -1011,7 +972,7 @@ def set_remove_btns(self, priority_list):
if self.parent.dark_mode_used:
rem_btn.setStyleSheet("border: 1px solid darkgrey; border-style: outset; font-size: 10px; background: #313233; color: white; margin: 0px; padding: 3px;")
else:
rem_btn.setStyleSheet("border: 1px solid black; border-style: outset; font-size: 10px; background: white; margin: 0px; padding: 3px;")
rem_btn.setStyleSheet("border: 1px solid black; border-style: outset; font-size: 10px; background: white; color: black; margin: 0px; padding: 3px;")
rem_btn.setCursor(Qt.PointingHandCursor)
rem_btn.setMinimumHeight(18)
rem_btn.clicked.connect(functools.partial(self.on_remove_clicked, priority_list[r].id))
Expand Down
2 changes: 1 addition & 1 deletion src/dialogs/queue_picker.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ def __init__(self, parent, note_list, note_list_right):
self.parent = parent

try:
self.dark_mode_used = utility.misc.dark_mode_is_used(aqt.mw.addonManager.getConfig(__name__))
self.dark_mode_used = state.night_mode
except:
self.dark_mode_used = False

Expand Down
12 changes: 9 additions & 3 deletions src/hooks.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>.

import typing
from typing import Callable, Dict
from typing import Callable, Dict, Optional, Any

hooks: Dict[str, Callable] = dict()

Expand All @@ -27,8 +27,14 @@ def add_hook(name: str, fn: Callable):
hooks[name] = [fn]


def run_hooks(name: str):
def run_hooks(name: str, arg: Optional[Any] = None):
name = name.lower()
if name in hooks:
for fn in hooks[name]:
fn()
if arg:
try:
fn(arg)
except:
fn()
else:
fn()
42 changes: 21 additions & 21 deletions src/output.py
Original file line number Diff line number Diff line change
Expand Up @@ -248,29 +248,29 @@ def print_search_results(self, notes, stamp, editor=None, logging=False, printTi
# use either the template for addon's notes or the normal
if res.note_type == "user":
newNote = noteTemplateUserNote.format(
grid_class=gridclass,
counter=counter+1,
nid=nid,
creation="&nbsp;&#128336; " + timeDiffString,
edited="" if str(nid) not in self.edited else "&nbsp;&#128336; " + self._buildEditedInfo(self.edited[str(nid)]),
mouseup= "getSelectionText()" if not is_queue else "",
text=text,
tags=utility.tags.build_tag_string(res.tags, self.gridView),
queue=": Q-%s&nbsp;" % (res.position + 1) if res.is_in_queue() else "",
progress=progress,
pdf_class=pdf_class,
ret=retInfo)
grid_class = gridclass,
counter = counter + 1,
nid = nid,
creation = "&nbsp;&#128336; " + timeDiffString,
edited = "" if str(nid) not in self.edited else "&nbsp;&#128336; " + self._buildEditedInfo(self.edited[str(nid)]),
mouseup = "getSelectionText()" if not is_queue else "",
text = text,
tags = utility.tags.build_tag_string(res.tags, self.gridView),
queue = ": Q-%s&nbsp;" % (res.position + 1) if res.is_in_queue() else "",
progress = progress,
pdf_class = pdf_class,
ret = retInfo)
else:
newNote = noteTemplate.format(
grid_class=gridclass,
counter=counter+1,
nid=nid,
creation="&nbsp;&#128336; " + timeDiffString,
edited="" if str(nid) not in self.edited else "&nbsp;&#128336; " + self._buildEditedInfo(self.edited[str(nid)]),
mouseup= "getSelectionText()" if not is_queue else "",
text=text,
tags=utility.tags.build_tag_string(res.tags, self.gridView),
ret=retInfo)
grid_class = gridclass,
counter = counter + 1,
nid = nid,
creation = "&nbsp;&#128336; " + timeDiffString,
edited = "" if str(nid) not in self.edited else "&nbsp;&#128336; " + self._buildEditedInfo(self.edited[str(nid)]),
mouseup = "getSelectionText()" if not is_queue else "",
text = text,
tags = utility.tags.build_tag_string(res.tags, self.gridView),
ret = retInfo)

html = f"{html}{newNote}"
tags = self._addToTags(tags, res.tags)
Expand Down
31 changes: 17 additions & 14 deletions src/stats.py
Original file line number Diff line number Diff line change
Expand Up @@ -268,26 +268,26 @@ def _getScore(cards, onlyRet=False):
def calculateStats(nid, gridView):

tables = {
"Note": [],
"Cards": [],
"Stats": []
"Note" : [],
"Cards" : [],
"Stats" : []
}
infoTable = {}
infoTable["Note ID"] = nid
infoTable["Note ID"] = f"""{nid} &nbsp;<span class='keyword' onclick='pycmd("siac-copy-to-cb {nid}")'>[Copy to Clipboard]</span>"""

note = mw.col.getNote(nid)
note = mw.col.getNote(int(nid))
model = mw.col.models.get(note.mid)
templates = mw.col.findTemplates(note)

try:
infoTable["Created Date"] = time.strftime("%Y-%m-%d", time.localtime(int(nid)/1000)) + " &nbsp;&nbsp;<a class='keyword' href='#' style='float: right;' onclick='pycmd(\"siac-added-same-day %s\"); $(\"#a-modal\").hide(); return false;'>Added Same Day</a>" % nid
infoTable["Last Modified"] = time.strftime(
"%Y-%m-%d", time.localtime(note.mod))
infoTable["Last Modified"] = time.strftime("%Y-%m-%d", time.localtime(note.mod))

except:
pass
if model is not None:
infoTable["Note Type"] = model["name"]

infoTable["Tags"] = " ".join(note.tags) if note.tags else "-"

# get card ids for note
cards = mw.col.db.all("select * from cards where nid = %s" % (nid))
Expand Down Expand Up @@ -322,7 +322,8 @@ def calculateStats(nid, gridView):

cardNameById = {}
for k, v in cardOrdById.items():
for temp in templates:
tmpls = mw.col.getCard(k).model()["tmpls"]
for temp in tmpls:
if temp['ord'] == v:
cardNameById[k] = temp['name']

Expand All @@ -341,8 +342,10 @@ def calculateStats(nid, gridView):
timePlotData = {}
similar_res_by_cid = {}

infoTable["Card ID(s)"] = ", ".join([str(c[0]) + f" ({_cardTypeStr(c[6])}) <span class='keyword' onclick='pycmd(\"siac-copy-to-cb {c[0]}\")'>[Copy]</span>" for c in cards])

if not entries or not hasReview:
infoTable["Result"] = "No cards have been reviewed yet for this note"
infoTable["[Stats]"] = "Not enough reviews to compute statistics"
tables["Note"].append(infoTable)
else:
cnt = 0
Expand Down Expand Up @@ -665,11 +668,11 @@ def _calcPerformanceScore(retention, time, goodAndEasy, hard):

def _cardTypeStr(typeNumber):
if typeNumber == 0:
return "new"
return "New"
if typeNumber == 1:
return "learning"
return "Learning"
if typeNumber == 2:
return "due"
return "Due"
if typeNumber == 3:
return "filtered"
return "Filtered"
return "?"
6 changes: 4 additions & 2 deletions src/web/html.py
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,7 @@ def right_side_html(indexIsLoaded: bool = False) -> str:

rightSideWidth = 100 - leftSideWidth
hideSidebar = conf_or_def("hideSidebar", False)
search_bar_mode = "Add-on" if not get_index() else get_index().searchbar_mode

if conf_or_def("switchLeftRight", False):
insert_code = """
Expand Down Expand Up @@ -322,7 +323,7 @@ def right_side_html(indexIsLoaded: bool = False) -> str:
</fieldset>
<fieldset id="searchMaskCol" style="flex: 1 1 auto; font-size: 0.85em;">
<legend id="siac-search-inp-mode-lbl" onclick='toggleSearchbarMode(this);'>Mode: Add-on</legend>
<legend id="siac-search-inp-mode-lbl" onclick='toggleSearchbarMode(this);'>Mode: %s</legend>
<span class='siac-search-icn' style='width: 16px; height: 16px; background-size: 16px 16px;'></span>
<input id='siac-browser-search-inp' placeholder='' onkeyup='searchMaskKeypress(event)'></input>
</fieldset>
Expand Down Expand Up @@ -376,6 +377,7 @@ def right_side_html(indexIsLoaded: bool = False) -> str:
$(`.siac-col`).wrapAll('<div id="outerWr" style="width: 100%%; display: flex; overflow: hidden; height: 100%%;"></div>');
updatePinned();
var there = false;
onWindowResize();
} else {
var there = true;
Expand All @@ -386,7 +388,6 @@ def right_side_html(indexIsLoaded: bool = False) -> str:
$('.field').attr('onmouseup', 'getSelectionText()');
window.$fields = $('.field');
window.$searchInfo = $('#searchInfo');
onWindowResize();
window.addEventListener('resize', onWindowResize, true);
$('.cal-block-outer').on('mouseenter', function(event) { calBlockMouseEnter(event, this);});
$('.cal-block-outer').on('click', function(event) { displayCalInfo(this);});
Expand All @@ -404,6 +405,7 @@ def right_side_html(indexIsLoaded: bool = False) -> str:
"display: none;" if indexIsLoaded else "",
"hidden" if hideSidebar else "",
getCalendarHtml() if conf_or_def("showTimeline", True) else "",
search_bar_mode,
insert_code
)

Expand Down
4 changes: 1 addition & 3 deletions src/web/note_templates.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@
<div class='editLbl' onclick='edit({nid})'>Edit</div>
<div class='srchLbl' onclick='searchCard(this)'><div class='siac-search-icn'></div></div>
<div id='pin-{nid}' class='pinLbl unselected' onclick='pinCard(this, {nid})'><span>&#128204;</span></div>
<div class='floatLbl' onclick='addFloatingNote({nid})'>&#10063;</div>
<div id='rem-{nid}' class='remLbl' onclick='removeNote({nid})'><span>&times;</span></div>
</div>
<div class='cardR' onmouseup='getSelectionText()' onmouseenter='cardMouseEnter(this, {nid})' onmouseleave='cardMouseLeave(this, {nid})' id='{nid}' data-nid='{nid}'>{text}</div>
Expand Down Expand Up @@ -62,14 +61,13 @@

noteTemplateUserNote = """<div class='cardWrapper siac-user-note {pdf_class} {grid_class}' id='nWr-{counter}'>
<div class='topLeftWr'>
<div id='cW-{nid}' class='rankingLbl'>{counter} &nbsp;SIAC<div class='rankingLblAddInfo'>{creation}</div><div class='editedStamp'>{edited}</div></div>
<div id='cW-{nid}' class='rankingLbl' onclick='pycmd("siac-copy-to-cb {nid}")'>{counter} &nbsp;SIAC<div class='rankingLblAddInfo'>{creation}</div><div class='editedStamp'>{edited}</div></div>
</div>
<div id='btnBar-{nid}' class='btnBar' onmouseLeave='pinMouseLeave(this)' onmouseenter='pinMouseEnter(this)'>
<div class='deleteLbl' onclick='pycmd("siac-delete-user-note-modal {nid}"); '><div class='siac-trash-icn'></div></div>
<div class='editLbl' onclick='pycmd("siac-edit-user-note {nid}")'>Edit</div>
<div class='srchLbl' onclick='searchCard(this)'><div class='siac-search-icn'></div></div>
<div id='pin-{nid}' class='pinLbl unselected' onclick='pinCard(this, {nid})'><span>&#128204;</span></div>
<div class='floatLbl' onclick='addFloatingNote({nid})'>&#10063;</div>
<div id='rem-{nid}' class='remLbl' onclick='removeNote({nid})'><span>&times;</span></div>
</div>
<div class='cardR siac-user-note' onmouseup='{mouseup}' onmouseenter='cardMouseEnter(this, {nid})' onmouseleave='cardMouseLeave(this, {nid})' id='{nid}' data-nid='{nid}'>{text}</div>
Expand Down
1 change: 1 addition & 0 deletions src/web/reading_modal.py
Original file line number Diff line number Diff line change
Expand Up @@ -286,6 +286,7 @@ def _display_pdf(self, full_path: str, note_id: int):
if (pdfBarsHidden) {
showPDFBottomRightNotification("%s", 4000);
}
setTimeout(refreshCanvas, 50);
if (pagesRead.length === 0) { pycmd('siac-insert-pages-total %s ' + numPagesExtract()); }
fileReader = null;
});
Expand Down
Loading

0 comments on commit 77481f2

Please sign in to comment.