Coverage for plugin/edit.py: 78.1%

248 statements  

« prev     ^ index     » next       coverage.py v7.17.5, created at 2026-11-28 02:31 +0000

1import aqt 

2import aqt.editor 

3import aqt.browser.previewer 

4from aqt import gui_hooks 

5from aqt.qt import Qt, QKeySequence, QShortcut, QCloseEvent, QMainWindow 

6from aqt.utils import restoreGeom, saveGeom, tooltip 

7from anki.errors import NotFoundError 

8from anki.consts import QUEUE_TYPE_SUSPENDED 

9from anki.utils import ids2str 

10 

11 

12# Edit dialog. Like Edit Current, but: 

13# * has a Preview button to preview the cards for the note 

14# * has Previous/Back buttons to navigate the history of the dialog 

15# * has a Browse button to open the history in the Browser 

16# * has no bar with the Close button 

17# 

18# To register in Anki's dialog system: 

19# > from .edit import Edit 

20# > Edit.register_with_anki() 

21# 

22# To (re)open (note_id is an integer): 

23# > Edit.open_dialog_and_show_note_with_id(note_id) 

24 

25 

26DOMAIN_PREFIX = "foosoft.ankiconnect." 

27 

28 

29def get_note_by_note_id(note_id): 

30 return aqt.mw.col.get_note(note_id) 

31 

32def is_card_suspended(card): 

33 return card.queue == QUEUE_TYPE_SUSPENDED 

34 

35def filter_valid_note_ids(note_ids): 

36 return aqt.mw.col.db.list( 

37 "select id from notes where id in " + ids2str(note_ids) 

38 ) 

39 

40 

41############################################################################## 

42 

43 

44class DecentPreviewer(aqt.browser.previewer.MultiCardPreviewer): 

45 class Adapter: 

46 def get_current_card(self): raise NotImplementedError 46 ↛ exitline 46 didn't except from function 'get_current_card' because the raise on line 46 wasn't executed

47 def can_select_previous_card(self): raise NotImplementedError 47 ↛ exitline 47 didn't except from function 'can_select_previous_card' because the raise on line 47 wasn't executed

48 def can_select_next_card(self): raise NotImplementedError 48 ↛ exitline 48 didn't except from function 'can_select_next_card' because the raise on line 48 wasn't executed

49 def select_previous_card(self): raise NotImplementedError 49 ↛ exitline 49 didn't except from function 'select_previous_card' because the raise on line 49 wasn't executed

50 def select_next_card(self): raise NotImplementedError 50 ↛ exitline 50 didn't except from function 'select_next_card' because the raise on line 50 wasn't executed

51 

52 def __init__(self, adapter: Adapter): 

53 super().__init__(parent=None, mw=aqt.mw, on_close=lambda: None) # noqa 

54 self.adapter = adapter 

55 self.last_card_id = 0 

56 gui_hooks.operation_did_execute.append(self.on_operation_did_execute) 

57 

58 # Unlike the Browser's previewer, no host refreshes this one; close it rather 

59 # than render a card deleted elsewhere, e.g. through the API. 

60 def on_operation_did_execute(self, changes, handler): 

61 if not self._open or not (changes.card or changes.note_text): 

62 return 

63 ids = [card.id for card in getattr(self.adapter, "cards", [self.card()])] 

64 if self.mw.col.db.scalar( 64 ↛ exitline 64 didn't return from function 'on_operation_did_execute' because the condition on line 64 was always true

65 "select count() from cards where id in " + ids2str(ids)) != len(ids): 

66 self.close() 

67 

68 def _on_close(self): 

69 gui_hooks.operation_did_execute.remove(self.on_operation_did_execute) 

70 super()._on_close() 

71 

72 def card(self): 

73 return self.adapter.get_current_card() 

74 

75 def card_changed(self): 

76 current_card_id = self.adapter.get_current_card().id 

77 changed = self.last_card_id != current_card_id 

78 self.last_card_id = current_card_id 

79 return changed 

80 

81 # the check if we can select next/previous card is needed because 

82 # the buttons sometimes get disabled a tad too late 

83 # and can still be pressed by user. 

84 # this is likely due to Anki sometimes delaying rendering of cards 

85 # in order to avoid rendering them too fast? 

86 def _on_prev_card(self): 

87 if self.adapter.can_select_previous_card(): 

88 self.adapter.select_previous_card() 

89 self.render_card() 

90 

91 def _on_next_card(self): 

92 if self.adapter.can_select_next_card(): 

93 self.adapter.select_next_card() 

94 self.render_card() 

95 

96 def _should_enable_prev(self): 

97 return self.showing_answer_and_can_show_question() or \ 

98 self.adapter.can_select_previous_card() 

99 

100 def _should_enable_next(self): 

101 return self.showing_question_and_can_show_answer() or \ 

102 self.adapter.can_select_next_card() 

103 

104 def _render_scheduled(self): 

105 super()._render_scheduled() # noqa 

106 self._updateButtons() 

107 

108 def showing_answer_and_can_show_question(self): 

109 return self._state == "answer" and not self._show_both_sides 

110 

111 def showing_question_and_can_show_answer(self): 

112 return self._state == "question" 

113 

114 

115class ReadyCardsAdapter(DecentPreviewer.Adapter): 

116 def __init__(self, cards): 

117 self.cards = cards 

118 self.current = 0 

119 

120 def get_current_card(self): 

121 return self.cards[self.current] 

122 

123 def can_select_previous_card(self): 

124 return self.current > 0 

125 

126 def can_select_next_card(self): 

127 return self.current < len(self.cards) - 1 

128 

129 def select_previous_card(self): 

130 self.current -= 1 

131 

132 def select_next_card(self): 

133 self.current += 1 

134 

135 

136############################################################################## 

137 

138 

139# store note ids instead of notes, as note objects don't implement __eq__ etc 

140class History: 

141 number_of_notes_to_keep_in_history = 25 

142 

143 def __init__(self): 

144 self.note_ids = [] 

145 

146 def append(self, note): 

147 if note.id in self.note_ids: 

148 self.note_ids.remove(note.id) 

149 self.note_ids.append(note.id) 

150 self.note_ids = self.note_ids[-self.number_of_notes_to_keep_in_history:] 

151 

152 def has_note_to_left_of(self, note): 

153 return note.id in self.note_ids and note.id != self.note_ids[0] 

154 

155 def has_note_to_right_of(self, note): 

156 return note.id in self.note_ids and note.id != self.note_ids[-1] 

157 

158 def get_note_to_left_of(self, note): 

159 note_id = self.note_ids[self.note_ids.index(note.id) - 1] 

160 return get_note_by_note_id(note_id) 

161 

162 def get_note_to_right_of(self, note): 

163 note_id = self.note_ids[self.note_ids.index(note.id) + 1] 

164 return get_note_by_note_id(note_id) 

165 

166 def get_last_note(self): # throws IndexError if history empty 

167 return get_note_by_note_id(self.note_ids[-1]) 

168 

169 def remove_invalid_notes(self): 

170 self.note_ids = filter_valid_note_ids(self.note_ids) 

171 

172history = History() 

173 

174 

175# see method `find_cards` of `collection.py` 

176def trigger_search_for_dialog_history_notes(search_context, use_history_order): 

177 search_context.search = " or ".join( 

178 f"nid:{note_id}" for note_id in history.note_ids 

179 ) 

180 

181 if use_history_order: 

182 search_context.order = f"""case c.nid { 

183 " ".join( 

184 f"when {note_id} then {n}" 

185 for (n, note_id) in enumerate(reversed(history.note_ids)) 

186 ) 

187 } end asc""" 

188 

189 

190############################################################################## 

191 

192 

193# noinspection PyAttributeOutsideInit 

194class Edit(aqt.editcurrent.EditCurrent): 

195 dialog_geometry_tag = DOMAIN_PREFIX + "edit" 

196 dialog_registry_tag = DOMAIN_PREFIX + "Edit" 

197 dialog_search_tag = DOMAIN_PREFIX + "edit.history" 

198 

199 # depending on whether the dialog already exists,  

200 # upon a request to open the dialog via `aqt.dialogs.open()`, 

201 # the manager will call either the constructor or the `reopen` method 

202 def __init__(self, note): 

203 QMainWindow.__init__(self, None, Qt.WindowType.Window) 

204 self.mw = aqt.mw 

205 self._cleaned_up = False 

206 self.form = aqt.forms.editcurrent.Ui_Dialog() 

207 self.form.setupUi(self) 

208 self.setWindowTitle("Edit") 

209 self.setMinimumWidth(250) 

210 self.setMinimumHeight(400) 

211 restoreGeom(self, self.dialog_geometry_tag) 

212 

213 self.setup_editor_buttons() 

214 

215 self.show() 

216 self.bring_to_foreground() 

217 

218 history.remove_invalid_notes() 

219 history.append(note) 

220 self.show_note(note) 

221 

222 gui_hooks.operation_did_execute.append(self.on_operation_did_execute) 

223 gui_hooks.editor_did_load_note.append(self.editor_did_load_note) 

224 

225 def reopen(self, note): 

226 history.append(note) 

227 self.show_note(note) 

228 self.bring_to_foreground() 

229 

230 def cleanup(self): 

231 if self._cleaned_up: 231 ↛ 232line 231 didn't jump to line 232 because the condition on line 231 was never true

232 return 

233 self._cleaned_up = True 

234 gui_hooks.editor_did_load_note.remove(self.editor_did_load_note) 

235 gui_hooks.operation_did_execute.remove(self.on_operation_did_execute) 

236 

237 self.editor.cleanup() 

238 saveGeom(self, self.dialog_geometry_tag) 

239 aqt.dialogs.markClosed(self.dialog_registry_tag) 

240 

241 def closeEvent(self, evt: QCloseEvent) -> None: 

242 if self._cleaned_up: 242 ↛ 245line 242 didn't jump to line 245 because the condition on line 242 was always true

243 evt.accept() 

244 return 

245 self.editor.call_after_note_saved(self.cleanup) 

246 

247 # Before 23.10, EditCurrent's versions close the reviewer's dialog registration 

248 # and call QDialog.reject on this QMainWindow. 

249 def _saveAndClose(self): 

250 self.cleanup() 

251 self.close() 

252 

253 def closeWithCallback(self, onsuccess): 

254 def callback(): 

255 self._saveAndClose() 

256 onsuccess() 

257 self.editor.call_after_note_saved(callback) 

258 

259 # This method (mostly) solves (at least on my Windows 10 machine) three issues 

260 # with window activation. Without this not even too hacky a fix, 

261 # * When dialog is opened from Yomichan *for the first time* since app start, 

262 # the dialog opens in background (just like Browser does), 

263 # but does not flash in taskbar (unlike Browser); 

264 # * When dialog is opened, closed, *then main window is focused by clicking in it*, 

265 # then dialog is opened from Yomichan again, same issue as above arises; 

266 # * When dialog is restored from minimized state *and main window isn't minimized*, 

267 # opening the dialog from Yomichan does not reliably focus it; 

268 # sometimes it opens in foreground, sometimes in background. 

269 # With this fix, windows nearly always appear in foreground in all three cases. 

270 # In the case of the first two issues, strictly speaking, the fix is not ideal: 

271 # the window appears in background first, and then quickly pops into foreground. 

272 # It is not *too* unsightly, probably, no-one will notice this; 

273 # still, a better solution must be possible. TODO find one! 

274 # 

275 # Note that operation systems, notably Windows, and desktop managers, may restrict 

276 # background applications from raising windows to prevent them from interrupting 

277 # what the user is currently doing. For details, see: 

278 # https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-setforegroundwindow#remarks 

279 # https://doc.qt.io/qt-5/qwidget.html#activateWindow 

280 # https://wiki.qt.io/Technical_FAQ#QWidget_::activateWindow.28.29_-_behavior_under_windows 

281 def bring_to_foreground(self): 

282 aqt.mw.app.processEvents() 

283 self.activateWindow() 

284 self.raise_() 

285 

286 #################################### hooks enabled during dialog lifecycle 

287 

288 def on_operation_did_execute(self, changes, handler): 

289 if changes.note_text and handler is not self.editor: 

290 self.reload_notes_after_user_action_elsewhere() 

291 

292 def editor_did_load_note(self, _editor): 

293 self.enable_disable_next_and_previous_buttons() 

294 

295 ###################################################### load & reload notes 

296 

297 # setting editor.card is required for the "Cards…" button to work properly 

298 def show_note(self, note): 

299 self.note = note 

300 cards = note.cards() 

301 

302 self.editor.set_note(note) 

303 self.editor.card = cards[0] if cards else None 

304 

305 if any(is_card_suspended(card) for card in cards): 305 ↛ 306line 305 didn't jump to line 306 because the condition on line 305 was never true

306 tooltip("Some of the cards associated with this note " 

307 "have been suspended", parent=self) 

308 

309 def reload_notes_after_user_action_elsewhere(self): 

310 history.remove_invalid_notes() 

311 

312 try: 

313 self.note.load() # this also updates the fields 

314 except NotFoundError: 

315 try: 

316 self.note = history.get_last_note() 

317 except IndexError: 

318 self.cleanup() 

319 return 

320 

321 self.show_note(self.note) 

322 

323 ################################################################## actions 

324 

325 # search two times, one is to select the current note or its cards, 

326 # and another to show the whole history, while keeping the above selection 

327 # set sort column to our search tag, which: 

328 # * prevents the column sort indicator from being shown 

329 # * serves as a hint for us to show notes or cards in history order 

330 # (user can then click on any of the column names 

331 # to show history cards in the order of their choosing) 

332 def show_browser(self, *_): 

333 def search_input_select_all(hook_browser, *_): 

334 hook_browser.form.searchEdit.lineEdit().selectAll() 

335 gui_hooks.browser_did_change_row.remove(search_input_select_all) 

336 gui_hooks.browser_did_change_row.append(search_input_select_all) 

337 

338 try: 

339 browser = aqt.dialogs.open("Browser", aqt.mw) 

340 browser.table._state.sort_column = self.dialog_search_tag # noqa 

341 browser.table._set_sort_indicator() # noqa 

342 

343 browser.search_for(f"nid:{self.note.id}") 

344 browser.table.select_all() 

345 browser.search_for(self.dialog_search_tag) 

346 finally: 

347 # Row changes are synchronous; never leave the one-shot hook behind. 

348 gui_hooks.browser_did_change_row.remove(search_input_select_all) 

349 

350 def show_preview(self, *_): 

351 cards = self.note.cards() 

352 if cards: 352 ↛ 357line 352 didn't jump to line 357 because the condition on line 352 was always true

353 previewer = DecentPreviewer(ReadyCardsAdapter(cards)) 

354 previewer.open() 

355 return previewer 

356 else: 

357 tooltip("No cards found", parent=self) 

358 return None 

359 

360 def show_previous(self, *_): 

361 if history.has_note_to_left_of(self.note): 

362 self.show_note(history.get_note_to_left_of(self.note)) 

363 

364 def show_next(self, *_): 

365 if history.has_note_to_right_of(self.note): 

366 self.show_note(history.get_note_to_right_of(self.note)) 

367 

368 ################################################## button and hotkey setup 

369 

370 def setup_editor_buttons(self): 

371 gui_hooks.editor_did_init.append(self.add_preview_button) 

372 gui_hooks.editor_did_init_buttons.append(self.add_right_hand_side_buttons) 

373 

374 # Browser mode makes the Preview button visible. 

375 self.editor = aqt.editor.Editor(aqt.mw, self.form.fieldsArea, self, 

376 editor_mode=aqt.editor.EditorMode.BROWSER) 

377 

378 gui_hooks.editor_did_init_buttons.remove(self.add_right_hand_side_buttons) 

379 gui_hooks.editor_did_init.remove(self.add_preview_button) 

380 

381 # The button is created by setting editor mode, see above; 

382 # so we only need to add the link. 

383 def add_preview_button(self, editor): 

384 QShortcut(QKeySequence("Ctrl+Shift+P"), self, self.show_preview) 

385 editor._links["preview"] = lambda _editor: self.show_preview() and None 

386 

387 # Buttons have weird font size and are square; 

388 # the style below makes them in line with left-hand side buttons 

389 def add_right_hand_side_buttons(self, buttons, editor): 

390 extra_button_class = "anki-connect-button" 

391 editor.web.eval(""" 

392 (function(){ 

393 const style = document.createElement("style"); 

394 style.innerHTML = ` 

395 .anki-connect-button { 

396 white-space: nowrap; 

397 width: auto; 

398 padding: 0 2px; 

399 font-size: var(--base-font-size); 

400 } 

401 .anki-connect-button:disabled { 

402 pointer-events: none; 

403 opacity: .4; 

404 } 

405 `; 

406 document.head.appendChild(style); 

407 })(); 

408 """) 

409 

410 def add(cmd, function, label, tip, keys): 

411 button_html = editor.addButton( 

412 icon=None, 

413 cmd=DOMAIN_PREFIX + cmd, 

414 id=DOMAIN_PREFIX + cmd, 

415 func=function, 

416 label=f"&nbsp;&nbsp;{label}&nbsp;&nbsp;", 

417 tip=f"{tip} ({keys})", 

418 keys=keys, 

419 ) 

420 

421 button_html = button_html.replace('class="', 

422 f'class="{extra_button_class} ') 

423 buttons.append(button_html) 

424 

425 add("browse", self.show_browser, "Browse", "Browse", "Ctrl+F") 

426 add("previous", self.show_previous, "&lt;", "Previous", "Alt+Left") 

427 add("next", self.show_next, "&gt;", "Next", "Alt+Right") 

428 

429 def run_javascript_after_toolbar_ready(self, js): 

430 js = f"setTimeout(function() {{ {js} }}, 1)" 

431 self.editor.web.eval(f'require("anki/ui").loaded.then(() => {js})') 

432 

433 def enable_disable_next_and_previous_buttons(self): 

434 def to_js(boolean): 

435 return "true" if boolean else "false" 

436 

437 disable_previous = not(history.has_note_to_left_of(self.note)) 

438 disable_next = not(history.has_note_to_right_of(self.note)) 

439 

440 self.run_javascript_after_toolbar_ready(f""" 

441 document.getElementById("{DOMAIN_PREFIX}previous") 

442 .disabled = {to_js(disable_previous)}; 

443 document.getElementById("{DOMAIN_PREFIX}next") 

444 .disabled = {to_js(disable_next)}; 

445 """) 

446 

447 ########################################################################## 

448 

449 @classmethod 

450 def browser_will_search(cls, search_context): 

451 if search_context.search == cls.dialog_search_tag: 451 ↛ 452line 451 didn't jump to line 452 because the condition on line 451 was never true

452 trigger_search_for_dialog_history_notes( 

453 search_context=search_context, 

454 use_history_order=cls.dialog_search_tag == 

455 search_context.browser.table._state.sort_column # noqa 

456 ) 

457 

458 @classmethod 

459 def register_with_anki(cls): 

460 if cls.dialog_registry_tag not in aqt.dialogs._dialogs: # noqa 460 ↛ exitline 460 didn't return from function 'register_with_anki' because the condition on line 460 was always true

461 aqt.dialogs.register_dialog(cls.dialog_registry_tag, cls) 

462 gui_hooks.browser_will_search.append(cls.browser_will_search) 

463 

464 @classmethod 

465 def open_dialog_and_show_note_with_id(cls, note_id): # raises NotFoundError 

466 note = get_note_by_note_id(note_id) 

467 return aqt.dialogs.open(cls.dialog_registry_tag, note)