Coverage for plugin/compat.py: 45.8%

841 statements  

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

1"""Differences between Anki releases, kept out of the API services. 

2 

3Prefer feature detection; release numbers only order prereleases and gate 

4behavior that cannot be detected without side effects. 

5""" 

6from collections import namedtuple 

7from types import SimpleNamespace 

8import functools 

9import importlib 

10import inspect 

11import re 

12import sys 

13 

14import aqt 

15 

16PRERELEASES = {'a': -3, 'b': -2, 'rc': -1} 

17 

18 

19def parse_version(text): 

20 """Order releases so that 26.5b1 < 26.5 < 26.5.1; ignore fork labels such as +fsrs7.""" 

21 found = re.match(r'(\d+(?:\.\d+)*)(?:(a|b|rc)(\d+))?', text.split('+')[0].strip()) 

22 if not found: 22 ↛ 23line 22 didn't jump to line 23 because the condition on line 22 was never true

23 raise ValueError('Unrecognized Anki version: ' + text) 

24 release = [int(part) for part in found.group(1).split('.')] 

25 release += [0] * (3 - len(release)) 

26 stage = (PRERELEASES[found.group(2)], int(found.group(3))) if found.group(2) else (0, 0) 

27 return tuple(release[:3]) + stage 

28 

29 

30VERSION = parse_version(aqt.appVersion) 

31 

32 

33def at_least(*release): 

34 return VERSION >= tuple(release) + (0,) * (3 - len(release)) + (0, 0) 

35 

36 

37def lookup(root, path): 

38 value = root 

39 for part in path.split('.'): 

40 value = getattr(value, part, None) 

41 if value is None: 

42 return None 

43 return value 

44 

45 

46def has(root, path): 

47 return lookup(root, path) is not None 

48 

49 

50def editor_dialog_available(): 

51 """The custom editor dialog uses the editor modes and browser table of Anki 2.1.50.""" 

52 import aqt.editor 

53 return has(aqt.editor, 'EditorMode') and has(aqt.gui_hooks, 'operation_did_execute') 

54 

55 

56def macos_helper(): 

57 try: 

58 from aqt._macos_helper import macos_helper as helper 

59 except ImportError: 

60 # Anki 2.1.49 and earlier have no App Nap helper. 

61 return None 

62 return helper 

63 

64 

65def on_op_finished(mw, changes, initiator=None): 

66 """Notify Anki's GUI of a native operation, as CollectionOp does.""" 

67 try: 

68 from aqt.operations import on_op_finished as finished 

69 except ImportError: 

70 finished = None 

71 if finished: 71 ↛ 74line 71 didn't jump to line 74 because the condition on line 71 was always true

72 finished(mw, changes, initiator) 

73 return 

74 if isinstance(changes, LegacyChanges): 

75 # Releases before 2.1.45 have no change tracking; refresh every screen. 

76 mw.reset() 

77 return 

78 # Anki 2.1.45-2.1.65 inline the same steps in CollectionOp._finish_op. 

79 mw.update_undo_actions() 

80 mw.autosave() 

81 aqt.gui_hooks.operation_did_execute(changes, initiator) 

82 if mw.col.op_made_changes(changes): 

83 aqt.gui_hooks.state_did_reset() 

84 

85 

86class _LegacyHook: 

87 """A runHook-style hook with the append/remove/call shape of a GUI hook.""" 

88 

89 def __init__(self, name): 

90 self.name = name 

91 

92 def append(self, callback): 

93 from anki.hooks import addHook 

94 addHook(self.name, callback) 

95 

96 def remove(self, callback): 

97 from anki.hooks import remHook 

98 remHook(self.name, callback) 

99 

100 def __call__(self, *args): 

101 from anki.hooks import runHook 

102 runHook(self.name, *args) 

103 

104 

105# GUI hooks that releases before 2.1.20 ran by name through anki.hooks. 

106LEGACY_GUI_HOOKS = {'profile_will_close': 'unloadProfile'} 

107 

108 

109def gui_hook(name): 

110 """The named GUI hook, or None when the running release has no equivalent.""" 

111 hook = getattr(getattr(aqt, 'gui_hooks', None), name, None) 

112 if hook is None and name in LEGACY_GUI_HOOKS: 112 ↛ 113line 112 didn't jump to line 113 because the condition on line 112 was never true

113 return _LegacyHook(LEGACY_GUI_HOOKS[name]) 

114 return hook 

115 

116 

117def register_collection_close(callback): 

118 hook = gui_hook('collection_will_temporarily_close') 

119 if hook is not None: 119 ↛ exitline 119 didn't return from function 'register_collection_close' because the condition on line 119 was always true

120 # Anki 2.1.50 and earlier close collections only by unloading the profile. 

121 hook.append(callback) 

122 

123 

124# Releases before 2.1.45 do not count background operations; count this add-on's own. 

125_background_ops = [0] 

126 

127 

128def background_op_count(mw): 

129 if hasattr(mw, '_increase_background_ops'): 129 ↛ 131line 129 didn't jump to line 131 because the condition on line 129 was always true

130 return mw._background_op_count 

131 return _background_ops[0] 

132 

133 

134def increase_background_ops(mw): 

135 if hasattr(mw, '_increase_background_ops'): 135 ↛ 138line 135 didn't jump to line 138 because the condition on line 135 was always true

136 mw._increase_background_ops() 

137 else: 

138 _background_ops[0] += 1 

139 

140 

141def decrease_background_ops(mw): 

142 if hasattr(mw, '_decrease_background_ops'): 142 ↛ 145line 142 didn't jump to line 145 because the condition on line 142 was always true

143 mw._decrease_background_ops() 

144 else: 

145 _background_ops[0] -= 1 

146 

147 

148def collection_thread_bound(): 

149 """Whether collections use a Python sqlite3 connection bound to the main thread (before 2.1.24).""" 

150 import importlib.util 

151 return importlib.util.find_spec('anki.dbproxy') is None 

152 

153 

154def run_in_background(mw, task, on_done, uses_collection=True): 

155 """Run task through Anki's task manager, calling on_done(future) on the main thread. 

156 

157 Where collections are bound to the main thread, collection work runs there later 

158 instead, preserving asynchronous completion. Releases before 23.10 cannot mark 

159 work as independent of the collection. 

160 """ 

161 import concurrent.futures 

162 taskman = getattr(mw, 'taskman', None) 

163 if taskman is None or (uses_collection and collection_thread_bound()): 163 ↛ 164line 163 didn't jump to line 164 because the condition on line 163 was never true

164 def run(): 

165 future = concurrent.futures.Future() 

166 try: 

167 future.set_result(task()) 

168 except BaseException as error: 

169 future.set_exception(error) 

170 on_done(future) 

171 if taskman is not None: 

172 taskman.run_on_main(run) 

173 else: 

174 # Anki 2.1.15 has no task manager. 

175 from aqt.qt import QTimer 

176 QTimer.singleShot(0, run) 

177 return 

178 parameters = inspect.signature(taskman.run_in_background).parameters 

179 if 'uses_collection' in parameters or any(p.kind == p.VAR_KEYWORD for p in parameters.values()): 

180 taskman.run_in_background(task, on_done, uses_collection=uses_collection) 

181 elif uses_collection: 181 ↛ 184line 181 didn't jump to line 184 because the condition on line 181 was always true

182 _run_collection_task(taskman, task, on_done) 

183 else: 

184 taskman.run_in_background(task, on_done) 

185 

186 

187# Collection tasks waiting for the one in progress; the first entry is running. 

188_collection_tasks = [] 

189 

190 

191def _run_collection_task(taskman, task, on_done): 

192 """Before 23.10 the task manager runs tasks on several threads at once. Queue 

193 collection work so one request's reads and writes do not interleave with another's.""" 

194 def finished(future): 

195 try: 

196 on_done(future) 

197 finally: 

198 _collection_tasks.pop(0) 

199 if _collection_tasks: 

200 _start_collection_task(taskman) 

201 _collection_tasks.append((task, finished)) 

202 if len(_collection_tasks) == 1: 

203 _start_collection_task(taskman) 

204 

205 

206def _start_collection_task(taskman): 

207 import concurrent.futures 

208 task, finished = _collection_tasks[0] 

209 try: 

210 taskman.run_in_background(task, finished) 

211 except BaseException as error: 

212 # A task that cannot start must still release the queue. 

213 future = concurrent.futures.Future() 

214 future.set_exception(error) 

215 finished(future) 

216 

217 

218# Qt dialogs. These run on the main thread. 

219 

220def svelte_editor_enabled(col): 

221 """Whether Add opens the experimental Svelte editor of Anki 26.08 and later.""" 

222 try: 

223 from anki.collection import ExperimentFlag 

224 except ImportError: 

225 return False 

226 return col.experiment_enabled(ExperimentFlag.SVELTE_EDITOR) 

227 

228 

229def add_dialog_deck_id(dialog): 

230 chooser = getattr(dialog, 'deck_chooser', None) 

231 # Before 2.1.45 the deck chooser stored a deck name. 

232 return chooser.selected_deck_id if chooser is not None else dialog.deckChooser.selectedId() 

233 

234 

235def add_dialog_set_note(dialog, note, deck_id): 

236 """AddCards.set_note of 2.1.50: select the note type and deck, then load fields and tags.""" 

237 if hasattr(dialog, 'set_note'): 237 ↛ 240line 237 didn't jump to line 240 because the condition on line 237 was always true

238 dialog.set_note(note, deck_id) 

239 return 

240 if hasattr(dialog, 'notetype_chooser'): 

241 dialog.notetype_chooser.selected_notetype_id = note.mid 

242 dialog.deck_chooser.selected_deck_id = deck_id 

243 draft = dialog._new_note() 

244 else: 

245 # Before 2.1.45 Add drafts used the collection's current note type. 

246 col = dialog.mw.col 

247 col.models.setCurrent(note.note_type()) 

248 dialog.modelChooser.updateModels() 

249 dialog.deckChooser.setDeckName(col.decks.name(deck_id)) 

250 draft = col.newNote() 

251 draft.fields = list(note.fields) 

252 draft.tags = list(note.tags) 

253 dialog.setAndFocusNote(draft) 

254 # Before 2.1.50 Add mode keeps the tag box text, which saving copies to the note. 

255 dialog.editor.tags.setText(' '.join(draft.tags)) 

256 

257 

258def browser_opens_with_search(): 

259 """Whether a new browser applies an initial search before loading its editor (2.1.41).""" 

260 from aqt.browser import Browser 

261 opens = inspect.signature(aqt.dialogs.open).parameters.values() 

262 return ('search' in inspect.signature(Browser.__init__).parameters 

263 and any(parameter.kind == parameter.VAR_KEYWORD for parameter in opens)) 

264 

265 

266def browser_card_row(browser, card_id): 

267 table = getattr(browser, 'table', None) 

268 if table is not None: 268 ↛ 272line 268 didn't jump to line 272 because the condition on line 268 was always true

269 return table._model.get_card_row(card_id) 

270 # Before 2.1.45 the browser listed only cards, in search order; 2.1.28-2.1.44 

271 # keep the backend's repeated field, which has no index method. 

272 try: 

273 return list(browser.model.cards).index(card_id) 

274 except ValueError: 

275 return None 

276 

277 

278def browser_select_rows(browser, rows): 

279 from aqt.qt import QItemSelection, QItemSelectionModel 

280 table = getattr(browser, 'table', None) 

281 view = browser.form.tableView 

282 if table is not None: 282 ↛ 285line 282 didn't jump to line 285 because the condition on line 282 was always true

283 table.clear_selection() 

284 else: 

285 view.selectionModel().clear() 

286 model = view.model() 

287 selection = QItemSelection() 

288 for row in rows: 

289 # The Rows flag extends each index across its row. 

290 selection.select(model.index(row, 0), model.index(row, 0)) 

291 if rows: 

292 # Before 2.1.45 the browser shows the card at the current index. 

293 view.selectionModel().setCurrentIndex(model.index(rows[0], 0), QItemSelectionModel.SelectionFlag.NoUpdate) 

294 view.selectionModel().select( 

295 selection, QItemSelectionModel.SelectionFlag.Select | QItemSelectionModel.SelectionFlag.Rows) 

296 

297 

298def browser_column_exists(col, column): 

299 if hasattr(col, 'get_browser_column'): 299 ↛ 302line 299 didn't jump to line 302 because the condition on line 299 was always true

300 return col.get_browser_column(column) is not None 

301 # Before 2.1.45 the browser defined these card columns. 

302 return column in ('question', 'answer', 'template', 'deck', 'noteFld', 'noteCrt', 'noteMod', 'cardMod', 

303 'cardDue', 'cardIvl', 'cardEase', 'cardReps', 'cardLapses', 'noteTags', 'note') 

304 

305 

306def browser_sort(browser, column, descending): 

307 """Sort by an active browser column; returns False when the column is not shown. 

308 

309 Applies the column, then the direction, so that a column's default direction 

310 on first selection does not decide the result. 

311 """ 

312 table = getattr(browser, 'table', None) 

313 if table is not None: 313 ↛ 322line 313 didn't jump to line 322 because the condition on line 313 was always true

314 from aqt.qt import Qt 

315 index = table._model.active_column_index(column) 

316 if index is None: 316 ↛ 317line 316 didn't jump to line 317 because the condition on line 316 was never true

317 return False 

318 order = Qt.SortOrder.DescendingOrder if descending else Qt.SortOrder.AscendingOrder 

319 table._on_sort_column_changed(index, order) 

320 table._on_sort_column_changed(index, order) 

321 return True 

322 columns = browser.model.activeCols 

323 if column not in columns: 

324 return False 

325 # Before 2.1.45 unsortable columns open a modal notice; before 2.1.28 there were more. 

326 unsortable = ('question', 'answer') + (() if at_least(2, 1, 28) else ('template', 'deck', 'note', 'noteTags')) 

327 if column in unsortable: 

328 from .protocol import ApiError 

329 raise ApiError('invalidParams', 'This Anki release cannot sort the browser by ' + column + '.') 

330 # The native handler reverses rows after an asynchronous editor save; the 

331 # caller has saved the editor, so set the order and search synchronously. 

332 col = browser.col 

333 col.conf['sortType'] = column 

334 col.conf['sortBackwards'] = descending 

335 col.setMod() 

336 browser.search() 

337 browser.setSortIndicator() 

338 return True 

339 

340 

341def editor_save(editor, callback, keepFocus=False): 

342 """Save the shown note, then call back; 2.1.45 renamed saveNow.""" 

343 (getattr(editor, 'call_after_note_saved', None) or editor.saveNow)(callback, keepFocus=keepFocus) 

344 

345 

346def saves_editor(editor): 

347 return callable(getattr(editor, 'call_after_note_saved', None) or getattr(editor, 'saveNow', None)) 

348 

349 

350def reloads_changed_notes(editor, method): 

351 """Whether a saved editor shows the result of a note write afterwards. 

352 

353 Browser, Edit Current, and custom editor hosts reload a classic editor's Python 

354 note from change notifications (from the reset hook before 2.1.45) and drop 

355 deleted notes. The web editors of 26.08 keep only a note ID; outside Add mode 

356 their page reloads field and tag changes from the same notifications, but a 

357 deleted or converted note fails to load there.""" 

358 if getattr(editor, 'note', None) is not None: 

359 return True 

360 return (method in ('notes.update', 'tags.add', 'tags.remove', 'tags.replace') 

361 and hasattr(editor, 'reload_note') and not getattr(editor, 'addMode', False)) 

362 

363 

364def binding_error(error, function): 

365 """Name methods by their qualified name in argument errors, as Python 3.10+ does.""" 

366 message = str(error) 

367 if sys.version_info < (3, 10) and message.startswith(function.__name__ + '('): 367 ↛ 368line 367 didn't jump to line 368 because the condition on line 367 was never true

368 return TypeError(function.__qualname__ + message[len(function.__name__):]) 

369 return error 

370 

371 

372def repeated(field): 

373 """Whether a protobuf field descriptor is a repeated field, for every protobuf release.""" 

374 if hasattr(field, 'is_repeated'): 374 ↛ 376line 374 didn't jump to line 376 because the condition on line 374 was always true

375 return field.is_repeated 

376 return field.label == field.LABEL_REPEATED 

377 

378 

379def deck_config_descriptor(): 

380 """The native preset descriptor, or None before 2.1.28. 

381 

382 2.1.45 introduced DeckConfig.Config (its module was renamed in 2.1.66); 

383 2.1.28-2.1.44 describe the same options as backend DeckConfigInner. 

384 """ 

385 try: 

386 from anki.deck_config_pb2 import DeckConfig 

387 except ImportError: 

388 try: 

389 from anki.deckconfig_pb2 import DeckConfig 

390 except ImportError: 

391 DeckConfig = None 

392 if DeckConfig is not None: 392 ↛ 394line 392 didn't jump to line 394 because the condition on line 392 was always true

393 return DeckConfig.Config.DESCRIPTOR 

394 for module in ('anki._backend.backend_pb2', 'anki.backend_pb2'): 

395 try: 

396 return importlib.import_module(module).DeckConfigInner.DESCRIPTOR 

397 except (ImportError, AttributeError): 

398 pass 

399 return None 

400 

401 

402def message(cls, **values): 

403 """Build a protobuf message, omitting fields this release does not define.""" 

404 known = cls.DESCRIPTOR.fields_by_name 

405 return cls(**{name: value for name, value in values.items() if name in known and value is not None}) 

406 

407 

408def field(value, name, default=None): 

409 """Read a protobuf field this release may not define.""" 

410 if not hasattr(value, 'DESCRIPTOR'): 410 ↛ 411line 410 didn't jump to line 411 because the condition on line 410 was never true

411 return getattr(value, name, default) 

412 return getattr(value, name) if name in value.DESCRIPTOR.fields_by_name else default 

413 

414 

415# Before 25.07, native rendering marked an empty front only by appending a 

416# notice that links to one of these help pages and repeating it as the answer. 

417EMPTY_FRONT_LINKS = ('#front-of-card-is-blank', '#no-cloze-filter-on-cloze-note-type', 

418 '/the-front-of-this-card-is-blank', '/no-cloze-found-on-card') 

419 

420 

421def rendered_empty(output): 

422 """Whether a partial render has an empty front, as Anki decides when adding cards.""" 

423 if 'is_empty' in output.DESCRIPTOR.fields_by_name: 423 ↛ 425line 423 didn't jump to line 425 because the condition on line 423 was always true

424 return output.is_empty 

425 answer, question = output.answer_nodes, output.question_nodes 

426 if not question or question[-1].WhichOneof('value') != 'text': 

427 return False 

428 front = question[-1] 

429 # 2.1.41-2.1.44 replace both sides with the message; earlier releases append it to the question. 

430 return ((len(answer) == 1 and answer[0] == front 

431 or re.fullmatch("<div>[^<]*<br><a href='[^']*'>[^<]*</a></div>", front.text) is not None) 

432 and any(link + "'>" in front.text for link in EMPTY_FRONT_LINKS)) 

433 

434 

435def import_package(col, path): 

436 """Import an .apkg with notetype merging, scheduling and presets where the release offers options (23.10+).""" 

437 if not hasattr(col, 'import_anki_package'): 437 ↛ 439line 437 didn't jump to line 439 because the condition on line 437 was never true

438 # Before 2.1.52 Anki imported packages with its Python importer, which clears undo. 

439 from anki.importing.apkg import AnkiPackageImporter 

440 import zipfile 

441 importer = AnkiPackageImporter(col, path) 

442 try: 

443 importer.run() 

444 except zipfile.BadZipFile as error: 

445 # Report it as the Rust importer does. 

446 raise OSError('invalid Zip archive: ' + str(error)) from error 

447 finally: 

448 if hasattr(importer, 'close'): 

449 importer.close() 

450 elif getattr(importer, 'zip', None): 

451 # Before 2.1.50 the importer left its archive open. 

452 importer.zip.close() 

453 try: 

454 from anki.collection import OpChanges 

455 except ImportError: 

456 return LegacyChanges() 

457 return message(OpChanges, card=True, note=True, deck=True, deck_config=True, notetype=True, 

458 tag=True, note_text=True, browser_table=True, study_queues=True, mtime=True) 

459 from anki import import_export_pb2 

460 if not hasattr(import_export_pb2, 'ImportAnkiPackageOptions'): 460 ↛ 462line 460 didn't jump to line 462 because the condition on line 460 was never true

461 # 2.1.52-2.1.66 import scheduling and presets and keep conflicting notetypes separate. 

462 return col.import_anki_package(path) 

463 options = message(import_export_pb2.ImportAnkiPackageOptions, 

464 merge_notetypes=True, with_scheduling=True, with_deck_configs=True) 

465 return col.import_anki_package(import_export_pb2.ImportAnkiPackageRequest(package_path=path, options=options)) 

466 

467 

468def export_package(col, path, deck_id, scheduling): 

469 if not hasattr(col, 'export_anki_package'): 469 ↛ 471line 469 didn't jump to line 471 because the condition on line 469 was never true

470 # Before 2.1.52 Anki exported packages with its Python exporter. 

471 from anki.exporting import AnkiPackageExporter 

472 exporter = AnkiPackageExporter(col) 

473 exporter.did, exporter.includeSched, exporter.includeMedia = deck_id, scheduling, True 

474 exporter.exportInto(path) 

475 return 

476 from anki import import_export_pb2 

477 from anki.collection import DeckIdLimit 

478 limit = DeckIdLimit(deck_id=deck_id) 

479 if hasattr(import_export_pb2, 'ExportAnkiPackageOptions'): 479 ↛ 482line 479 didn't jump to line 482 because the condition on line 479 was always true

480 options = import_export_pb2.ExportAnkiPackageOptions(with_scheduling=scheduling, with_media=True, legacy=True) 

481 return col.export_anki_package(out_path=path, options=options, limit=limit) 

482 return col.export_anki_package(out_path=path, limit=limit, with_scheduling=scheduling, 

483 with_media=True, legacy_support=True) 

484 

485 

486try: 

487 from anki.collection import AddNoteRequest 

488except ImportError: 

489 # Collection.add_notes and its request arrived in 23.10. 

490 AddNoteRequest = namedtuple('AddNoteRequest', 'note deck_id') 

491 

492 

493def column_sorting(column, kind): 

494 """A browser column's sort mode for notes or cards; 23.10 split the single mode by kind.""" 

495 name = 'sorting_notes' if kind == 'notes' else 'sorting_cards' 

496 return getattr(column, name) if name in column.DESCRIPTOR.fields_by_name else column.sorting 

497 

498 

499def transact(col, op): 

500 """Apply op atomically; before 23.10 the collection is always inside an open transaction.""" 

501 if hasattr(col.db, 'transact'): 501 ↛ 503line 501 didn't jump to line 503 because the condition on line 501 was always true

502 return col.db.transact(op) 

503 col.save() 

504 try: 

505 op() 

506 except BaseException: 

507 col.db.rollback() 

508 col.db.begin() 

509 raise 

510 col.save() 

511 

512 

513def which(message): 

514 """The set member of a message's main oneof, which 2.1.66 renamed from value to kind.""" 

515 return message.WhichOneof('kind' if 'kind' in message.DESCRIPTOR.oneofs_by_name else 'value') 

516 

517 

518def backend_errors(): 

519 """Exception classes raised by the Rust backend; 2.1.55 gave them the BackendError base.""" 

520 import anki.errors 

521 if hasattr(anki.errors, 'BackendError'): 521 ↛ 523line 521 didn't jump to line 523 because the condition on line 521 was always true

522 return (anki.errors.BackendError,) 

523 names = ('LocalizedError', 'NotFoundError', 'ExistsError', 'Interrupted', 'UndoEmpty', 'StringError') 

524 return tuple(getattr(anki.errors, name) for name in names if hasattr(anki.errors, name)) 

525 

526 

527def is_not_found(error): 

528 """Whether Anki raised its NotFoundError, which install_backports provides on every release.""" 

529 import anki.errors 

530 return isinstance(error, anki.errors.NotFoundError) 

531 

532 

533def renders_uncommitted(col): 

534 """Whether the backend renders unsaved notes; from 2.1.28.""" 

535 return has(col._backend, 'render_uncommitted_card_legacy') or has(col._backend, 'render_uncommitted_card') 

536 

537 

538def render_uncommitted(col, note, card_ord, template, fill_empty): 

539 """Render a template against an unsaved note; partial_render (2.1.61+) leaves Python filters unapplied.""" 

540 # Before 2.1.45 the unsuffixed method took the template as JSON bytes. 

541 render = getattr(col._backend, 'render_uncommitted_card_legacy', None) or col._backend.render_uncommitted_card 

542 options = {'note': note, 'card_ord': card_ord, 'template': template, 'fill_empty': fill_empty} 

543 if 'partial_render' in inspect.signature(render).parameters: 543 ↛ 545line 543 didn't jump to line 545 because the condition on line 543 was always true

544 options['partial_render'] = True 

545 return render(**options) 

546 

547 

548def _import_dialog_available(): 

549 try: 

550 from aqt.import_export import import_dialog, importing 

551 except ImportError: 

552 return False 

553 return (all(hasattr(import_dialog, name) for name in ('ImportDialog', 'AnkiPackageArgs', 'CsvArgs', 'JsonFileArgs')) 

554 and all(hasattr(importing, name) for name in ('ColpkgImporter', 'import_collection_package_op'))) 

555 

556 

557class _ClosedWebView: 

558 def setFocus(self): 

559 pass 

560 

561 def cleanup(self): 

562 pass 

563 

564 

565def import_dialog(mw, args): 

566 """Open Anki's import dialog, tolerating 23.10-24.04's late setup focus callback.""" 

567 from aqt.import_export.import_dialog import ImportDialog 

568 if at_least(24, 6): 568 ↛ 571line 568 didn't jump to line 571 because the condition on line 568 was always true

569 return ImportDialog(mw, args) 

570 

571 class Dialog(ImportDialog): 

572 def reject(self): 

573 ImportDialog.reject(self) 

574 # The setup callback focuses self.web and can run after an early close. 

575 self.web = _ClosedWebView() 

576 

577 return Dialog(mw, args) 

578 

579 

580FEATURES = { 

581 'editorDialog': (lambda: editor_dialog_available(), 'Requires the note editor modes of Anki 2.1.50.'), 

582 # Earlier importers report through modal dialogs and offer no completion signal. 

583 'importDialog': (_import_dialog_available, 'Requires the import dialog of Anki 23.10 or later.'), 

584} 

585 

586 

587def missing_feature(name): 

588 """The reason a release feature is unavailable, or None.""" 

589 available, reason = FEATURES[name] 

590 return None if available() else reason 

591 

592 

593def scheduling_states(col, card_id): 

594 """A card's current and next v3 states; 2.1.55 renamed get_next_card_states.""" 

595 backend = col._backend 

596 if hasattr(backend, 'get_scheduling_states'): 596 ↛ 598line 596 didn't jump to line 598 because the condition on line 596 was always true

597 return backend.get_scheduling_states(card_id) 

598 return backend.get_next_card_states(card_id) 

599 

600 

601def reviewer_states(info): 

602 """The reviewer's v3 card states; 2.1.55 renamed next_states.""" 

603 return info.states if hasattr(info, 'states') else info.next_states 

604 

605 

606def reviewer_leech(reviewer, suspended): 

607 """Report a leech; before 25.07 onLeech took an optional card and read its queue.""" 

608 if 'suspended' in inspect.signature(reviewer.onLeech).parameters: 

609 reviewer.onLeech(suspended) 

610 else: 

611 reviewer.onLeech() 

612 

613 

614def learning_seconds(col, card): 

615 """The current (re)learning step delay, as rslib reports it in the card's state.""" 

616 backend = col._backend 

617 if not has(backend, 'get_scheduling_states') and not has(backend, 'get_next_card_states'): 617 ↛ 618line 617 didn't jump to line 618 because the condition on line 617 was never true

618 return _learning_seconds(col, card) 

619 states = scheduling_states(col, card.id) 

620 native = states.current.normal 

621 if which(states.current) == 'filtered' and which(states.current.filtered) == 'rescheduling': 

622 native = states.current.filtered.rescheduling.original_state 

623 kind = which(native) 

624 if kind == 'learning': 

625 return native.learning.scheduled_secs 

626 if kind == 'relearning': 626 ↛ 628line 626 didn't jump to line 628 because the condition on line 626 was always true

627 return native.relearning.learning.scheduled_secs 

628 return None 

629 

630 

631def _learning_seconds(col, card): 

632 """Port of rslib 2.1.44 current_card_state for releases without native card states.""" 

633 if card.odid and not col.decks.get(card.did).get('resched', True): 

634 # Previewing filtered decks report a preview state. 

635 return None 

636 config = col.decks.confForDid(card.odid or card.did) 

637 steps = config['new' if card.type == 1 else 'lapse']['delays'] 

638 index = min(max(len(steps) - card.left % 1000, 0), max(len(steps) - 1, 0)) 

639 return int(steps[index] * 60) if steps else 0 

640 

641 

642def collection_syncs_media(col): 

643 """Anki 23.10 syncs media with the collection and reports media status itself.""" 

644 return hasattr(col, 'media_sync_status') 

645 

646 

647def sync_collection(col, auth, media): 

648 if collection_syncs_media(col): 648 ↛ 650line 648 didn't jump to line 650 because the condition on line 648 was always true

649 return col.sync_collection(auth, media) 

650 return col.sync_collection(auth) 

651 

652 

653def release_sync_lock(col): 

654 """Before 23.10 Python holds a write transaction that native sync commits first.""" 

655 if 'trx' not in inspect.signature(col.save).parameters: 655 ↛ 657line 655 didn't jump to line 657 because the condition on line 655 was always true

656 return lambda: None 

657 col.save(trx=False) 

658 return col.db.begin 

659 

660 

661def full_sync(mw, col, auth, upload, server_usn): 

662 """Back up, close, and replace one side; runs in the background like Anki's own sync.""" 

663 if not upload and hasattr(mw, '_close_for_full_download'): 

664 # 2.1.45-2.1.54 back up by closing and reopening for the download. 

665 mw._close_for_full_download() 

666 else: 

667 if not upload and hasattr(mw, 'create_backup_now'): 

668 mw.create_backup_now() 

669 # Before 2.1.40 Anki's own full download took no backup first. 

670 col.close_for_full_sync() 

671 if hasattr(col, 'full_upload_or_download'): 

672 col.full_upload_or_download(auth=auth, server_usn=server_usn, upload=upload) 

673 else: 

674 (col.full_upload if upload else col.full_download)(auth) 

675 

676 

677def reopen_after_full_sync(mw): 

678 if 'after_full_sync' in inspect.signature(mw.reopen).parameters: 

679 mw.reopen(after_full_sync=True) 

680 else: 

681 mw.col.reopen(after_full_sync=True) 

682 

683 

684def refresh_after_sync(mw): 

685 """Redraw the toolbar's sync state; 2.1.41 named this step.""" 

686 if hasattr(mw, '_refresh_after_sync'): 686 ↛ 689line 686 didn't jump to line 689 because the condition on line 686 was always true

687 mw._refresh_after_sync() 

688 else: 

689 mw.toolbar.redraw() 

690 

691 

692def start_media_sync(mw, col): 

693 """23.10 only monitors the media sync that the collection sync started.""" 

694 if collection_syncs_media(col): 694 ↛ 697line 694 didn't jump to line 697 because the condition on line 694 was always true

695 mw.media_syncer.start_monitoring() 

696 else: 

697 mw.media_syncer.start() 

698 

699 

700def watch_media_sync(syncer): 

701 """Before 23.10 the media syncer only logs failures and cancellation. Observe its 

702 next completion; the returned function gives that run's exception, or None.""" 

703 outcome = [] 

704 finished = syncer._on_finished 

705 native = syncer.__dict__.get('_on_finished', outcome) 

706 def restore(): 

707 if native is outcome: 

708 syncer.__dict__.pop('_on_finished', None) 

709 else: 

710 syncer._on_finished = native 

711 def observed(future): 

712 restore() 

713 outcome.append(future.exception()) 

714 finished(future) 

715 syncer._on_finished = observed 

716 def result(): 

717 restore() 

718 return outcome[0] if outcome else None 

719 return result 

720 

721 

722def collection_will_temporarily_close(col): 

723 hook = gui_hook('collection_will_temporarily_close') 

724 if hook is not None: 

725 hook(col) 

726 

727 

728def ask_user(text, callback, buttons, default_button, parent): 

729 """A non-modal button choice; ask_user_dialog exists from 2.1.55.""" 

730 try: 

731 from aqt.utils import ask_user_dialog 

732 except ImportError: 

733 ask_user_dialog = None 

734 if ask_user_dialog is not None: 

735 return ask_user_dialog(text, callback=callback, buttons=buttons, default_button=default_button, parent=parent) 

736 from aqt.qt import QMessageBox 

737 box = QMessageBox(parent) 

738 box.setText(text) 

739 role = getattr(QMessageBox, 'ActionRole', None) 

740 if role is None: 

741 role = QMessageBox.ButtonRole.ActionRole 

742 added = [box.addButton(label, role) for label in buttons] 

743 box.setDefaultButton(added[default_button]) 

744 box.setEscapeButton(added[default_button]) 

745 box.buttonClicked.connect(lambda button: callback(added.index(button))) 

746 box.open() 

747 return box 

748 

749 

750def _graph_rows(col, search): 

751 """The searched cards and their reviews, as the 2.1.28 graphs backend returned them.""" 

752 from anki.utils import ids2str 

753 cids = ids2str(col.find_cards(search)) 

754 revlog = [SimpleNamespace(id=id, review_kind=kind, last_interval=last, taken_millis=taken) for id, kind, last, taken 

755 in col.db.execute('select id, type, lastIvl, time from revlog where cid in %s order by id' % cids)] 

756 cards = [SimpleNamespace(queue=queue, ctype=kind, interval=interval) for queue, kind, interval 

757 in col.db.execute('select queue, type, ivl from cards where id in %s' % cids)] 

758 return SimpleNamespace(revlog=revlog, cards=cards, next_day_at_secs=col.sched.dayCutoff) 

759 

760 

761def graphs(col, search): 

762 """Statistics summaries; before 2.1.56 the backend returned raw rows to the frontend. 

763 

764 The fallback ports rslib's 2.1.56 today, reviews, and card_counts summaries.""" 

765 if has(col._backend, 'graphs'): 765 ↛ 770line 765 didn't jump to line 770 because the condition on line 765 was always true

766 raw = graphs_response(col, search) 

767 if 'today' in raw.DESCRIPTOR.fields_by_name: 767 ↛ 771line 767 didn't jump to line 771 because the condition on line 767 was always true

768 return raw 

769 else: 

770 raw = _graph_rows(col, search) 

771 kinds = ('learn', 'young', 'relearn', 'filtered') 

772 def counts(): 

773 return SimpleNamespace(learn=0, relearn=0, young=0, mature=0, filtered=0) 

774 count, time, start_of_today = {}, {}, (raw.next_day_at_secs - 86400) * 1000 

775 today = SimpleNamespace(answer_count=0) 

776 for review in raw.revlog: 

777 if review.review_kind == 4: 

778 continue 

779 elapsed = review.id // 1000 - raw.next_day_at_secs 

780 day = -(-elapsed // 86400) if elapsed < 0 else elapsed // 86400 

781 kind = kinds[review.review_kind] 

782 if kind == 'young' and review.last_interval >= 21: 

783 kind = 'mature' 

784 for totals, value in ((count, 1), (time, review.taken_millis)): 

785 entry = totals.setdefault(day, counts()) 

786 setattr(entry, kind, getattr(entry, kind) + value) 

787 if review.id >= start_of_today: 

788 today.answer_count += 1 

789 active = SimpleNamespace(newCards=0, learn=0, relearn=0, young=0, mature=0, suspended=0, buried=0) 

790 for card in raw.cards: 

791 if card.queue == -1: 

792 active.suspended += 1 

793 elif card.queue in (-2, -3): 

794 active.buried += 1 

795 else: 

796 kind = ('newCards', 'learn', 'young', 'relearn')[card.ctype] 

797 # 2.1.28-2.1.35 name the interval ivl. 

798 if kind == 'young' and getattr(card, 'interval', getattr(card, 'ivl', 0)) >= 21: 

799 kind = 'mature' 

800 setattr(active, kind, getattr(active, kind) + 1) 

801 return SimpleNamespace(today=today, reviews=SimpleNamespace(count=count, time=time), 

802 card_counts=SimpleNamespace(excluding_inactive=active)) 

803 

804 

805def error_message(error): 

806 """A backend error's details; before 2.1.55 errors held only a localized sentence.""" 

807 message = str(error) 

808 # Fluent isolates the details argument, as in "Invalid input: \u2068soon\u2069". 

809 inner = re.fullmatch('[^\u2068]*\u2068(.*)\u2069[^\u2069]*', message, re.S) 

810 if inner: 810 ↛ 811line 810 didn't jump to line 811 because the condition on line 810 was never true

811 return inner.group(1) 

812 if not message and type(error).__name__ == 'NotFoundError': 812 ↛ 813line 812 didn't jump to line 813 because the condition on line 812 was never true

813 return 'Not found.' 

814 return message 

815 

816 

817def _utility(name, legacy): 

818 import anki.utils 

819 function = getattr(anki.utils, name, None) 

820 return function if function is not None else getattr(anki.utils, legacy) 

821 

822 

823def strip_html_media(text): 

824 """Anki's media-preserving HTML stripping; 2.1.50 renamed it and moved it to Rust.""" 

825 return _utility('strip_html_media', 'stripHTMLMedia')(text) 

826 

827 

828def field_checksum(text): 

829 return _utility('field_checksum', 'fieldChecksum')(text) 

830 

831 

832def parsed(value, cls): 

833 """Before 2.1.50 some backend calls returned serialized messages for the web frontend.""" 

834 if isinstance(value, bytes): 834 ↛ 835line 834 didn't jump to line 835 because the condition on line 834 was never true

835 message = cls() 

836 message.ParseFromString(value) 

837 return message 

838 return value 

839 

840 

841def graphs_response(col, search): 

842 try: 

843 from anki.stats_pb2 import GraphsResponse 

844 except ImportError: 

845 # Before 2.1.45 the message lived with the backend; 2.1.41 moved it into anki._backend. 

846 try: 

847 from anki._backend.backend_pb2 import GraphsOut as GraphsResponse 

848 except ImportError: 

849 from anki.backend_pb2 import GraphsOut as GraphsResponse 

850 return parsed(col._backend.graphs(search=search, days=0), GraphsResponse) 

851 

852 

853def _default_map(old, new): 

854 """Port of rslib's default field/template map: names first, then unused sources in order.""" 

855 unused = {item['name']: item['ord'] for item in old} 

856 chosen = [unused.pop(item['name'], None) for item in new] 

857 remaining = iter(sorted(unused.values())) 

858 return [next(remaining, -1) if index is None else index for index in chosen] 

859 

860 

861def change_notetype_info(col, old_id, new_id): 

862 if not has(col.models, 'change_notetype_info'): 862 ↛ 864line 862 didn't jump to line 864 because the condition on line 862 was never true

863 # Before 2.1.45 the plan is built in Python and applied by ModelManager.change. 

864 old, new = col.models.get(old_id), col.models.get(new_id) 

865 cloze = old['type'] == 1 or new['type'] == 1 

866 return SimpleNamespace(input=SimpleNamespace( 

867 old_notetype_id=old_id, new_notetype_id=new_id, note_ids=[], is_cloze=cloze, 

868 new_fields=_default_map(old['flds'], new['flds']), 

869 new_templates=[] if cloze else _default_map(old['tmpls'], new['tmpls']))) 

870 from anki import notetypes_pb2 

871 return parsed(col.models.change_notetype_info(old_notetype_id=old_id, new_notetype_id=new_id), 

872 notetypes_pb2.ChangeNotetypeInfo) 

873 

874 

875def change_notetype_of_notes(col, request): 

876 if has(col.models, 'change_notetype_of_notes'): 876 ↛ 878line 876 didn't jump to line 878 because the condition on line 876 was always true

877 return col.models.change_notetype_of_notes(request) 

878 old, new = col.models.get(request.old_notetype_id), col.models.get(request.new_notetype_id) 

879 fields = {source: target for target, source in enumerate(request.new_fields) if source >= 0} 

880 if request.is_cloze: 

881 # The legacy change keeps cloze card ordinals and drops those beyond a standard target. 

882 cards = {item['ord']: item['ord'] for item in old['tmpls']} 

883 else: 

884 cards = {item['ord']: None for item in old['tmpls']} 

885 cards.update({source: target for target, source in enumerate(request.new_templates) if source >= 0}) 

886 # Like the native change, mark the schema modified rather than asking the user. 

887 col.modSchema(check=False) 

888 col.models.change(old, list(request.note_ids), new, fields or {0: None}, cards) 

889 return LegacyChanges() 

890 

891 

892def day_cutoff(col): 

893 """The next day's start; v3 schedulers before 2.1.50 name it dayCutoff.""" 

894 cutoff = getattr(col.sched, 'day_cutoff', None) 

895 return cutoff if cutoff is not None else col.sched.dayCutoff 

896 

897 

898def deck_total(col, node): 

899 """Cards whose current deck is the node's deck, as native due counts total them from 2.1.47.""" 

900 total = field(node, 'total_in_deck') 

901 if total is not None: 901 ↛ 903line 901 didn't jump to line 903 because the condition on line 901 was always true

902 return total 

903 return col.db.scalar('select count() from cards where did=?', node.deck_id) 

904 

905 

906def resets_counts(): 

907 try: 

908 from anki import scheduler_pb2 

909 except ImportError: 

910 return False 

911 return 'reset_counts' in scheduler_pb2.ScheduleCardsAsNewRequest.DESCRIPTOR.fields_by_name 

912 

913 

914def schedule_cards_as_new(col, card_ids, restore_position, reset_counts, log): 

915 """Forget cards; before 2.1.50 cards record no original position to restore.""" 

916 forget = getattr(col._backend, 'schedule_cards_as_new', None) 

917 parameters = inspect.signature(forget).parameters if forget else {} 

918 if 'card_ids' in parameters: 918 ↛ 920line 918 didn't jump to line 920 because the condition on line 918 was never true

919 # 2.1.39-2.1.49 take keywords; only 2.1.45 and later return OpChanges. 

920 changes = col._backend.schedule_cards_as_new(card_ids=card_ids, log=log) 

921 return changes if reports_changes() else None 

922 if 'message' not in parameters: 922 ↛ 924line 922 didn't jump to line 924 because the condition on line 922 was never true

923 # Before 2.1.39 forgetting writes no review log entry. 

924 col.sched.forgetCards(list(card_ids)) 

925 return None 

926 from anki import scheduler_pb2 

927 request = message(scheduler_pb2.ScheduleCardsAsNewRequest, card_ids=card_ids, 

928 restore_position=restore_position, reset_counts=reset_counts, log=log) 

929 return col._backend.schedule_cards_as_new(request) 

930 

931 

932class LegacyChanges(SimpleNamespace): 

933 """Stands in for OpChanges on releases before 2.1.45, which report no changes.""" 

934 

935 

936def reports_changes(): 

937 import anki.collection 

938 return hasattr(anki.collection, 'OpChanges') 

939 

940 

941def update_card(col, card): 

942 """Save a card with an undo entry and return its changes.""" 

943 if reports_changes() and not hasattr(col, 'update_cards'): 943 ↛ 945line 943 didn't jump to line 945 because the condition on line 943 was never true

944 # Anki 2.1.45's wrapper discards the OpChanges its backend returns. 

945 return col._backend.update_card(card=card._to_backend_card(), skip_undo_entry=False) 

946 return col.update_card(card) 

947 

948 

949def _require_row(col, table, id): 

950 # Before 2.1.28 loading a missing note or card failed while unpacking its row. 

951 if not col.db.scalar('select 1 from %s where id=?' % table, id): 

952 from anki.errors import NotFoundError 

953 raise NotFoundError() 

954 

955 

956def _note(col, note_id): 

957 from anki.notes import Note 

958 _require_row(col, 'notes', note_id) 

959 return Note(col, id=note_id) 

960 

961 

962def _card(col, card_id): 

963 _require_row(col, 'cards', card_id) 

964 return col.getCard(card_id) 

965 

966 

967def _new_note(col, notetype): 

968 from anki.notes import Note 

969 note = Note(col, notetype) 

970 # Python notes of 2.1.24-2.1.26 take an id when created; native notes have none until added. 

971 note.id = 0 

972 return note 

973 

974 

975def _set_deck(col, card_ids, deck_id): 

976 """Move cards as the 2.1.15-2.1.37 browser did: return filtered cards home first.""" 

977 col.sched.remFromDyn(list(card_ids)) 

978 col.decks.setDeck(list(card_ids), deck_id) 

979 

980 

981def _add_note(col, note, deck_id): 

982 """Port of rslib add_note over the Python card generation of 2.1.24-2.1.26.""" 

983 from anki.utils import timestampID 

984 note.id = note.id or timestampID(col.db, 'notes') 

985 templates = col.findTemplates(note) 

986 if not templates: 

987 # rslib adds the first card when no template has a non-empty front. 

988 templates = [dict(note.model()['tmpls'][0], ord=0)] 

989 note.flush() 

990 due = col.nextID('pos') 

991 for template in templates: 

992 col._newCard(note, template, due, did=deck_id) 

993 return LegacyChanges(count=len(templates)) 

994 

995 

996def _remove_notes(col, note_ids): 

997 col.remNotes(list(note_ids)) 

998 return LegacyChanges() 

999 

1000 

1001def _deck_due_tree(sched): 

1002 """The due tree of 2.1.24-2.1.26 as native-shaped nodes under a root.""" 

1003 def node(value): 

1004 name, did, review, learn, new, children = value 

1005 return SimpleNamespace(deck_id=did, name=name, review_count=review, learn_count=learn, new_count=new, 

1006 children=[node(child) for child in children]) 

1007 return SimpleNamespace(deck_id=0, name='', review_count=0, learn_count=0, new_count=0, 

1008 children=[node(value) for value in sched.deckDueTree()]) 

1009 

1010 

1011def _trash_media(media, fnames): 

1012 """Move files to media.trash beside the folder, as the Rust backend does from 2.1.22.""" 

1013 import os 

1014 folder = media.dir() 

1015 trash = os.path.join(os.path.dirname(folder), 'media.trash') 

1016 os.makedirs(trash, exist_ok=True) 

1017 for fname in fnames: 

1018 path = os.path.join(folder, fname) 

1019 if os.path.exists(path): 

1020 os.replace(path, os.path.join(trash, fname)) 

1021 

1022 

1023def _names_and_ids(items): 

1024 return [SimpleNamespace(id=int(item['id']), name=item['name']) 

1025 for item in sorted(items, key=lambda item: item['name'].casefold())] 

1026 

1027 

1028def _remove_notetype(models, notetype_id): 

1029 models.rem(models.get(notetype_id)) 

1030 return LegacyChanges() 

1031 

1032 

1033def clear_notetype_cache(col): 

1034 """Drop cached note types; before 2.1.28 the manager held them all without a cache.""" 

1035 cache = getattr(col.models, '_cache', None) 

1036 if cache is not None: 1036 ↛ exitline 1036 didn't return from function 'clear_notetype_cache' because the condition on line 1036 was always true

1037 cache.clear() 

1038 

1039 

1040def _update_note(col, note, **_): 

1041 note.flush() 

1042 return LegacyChanges() 

1043 

1044 

1045def _update_card(col, card, **_): 

1046 card.flush() 

1047 return LegacyChanges() 

1048 

1049 

1050def _update_notetype(models, notetype): 

1051 if hasattr(models, 'models'): 

1052 # 2.1.24-2.1.26 save only registered dicts and generate cards for new templates on request. 

1053 notetype['id'] = models.get(notetype['id'])['id'] 

1054 nids = _remap_structure(models.col, notetype) 

1055 models.update(notetype) 

1056 models.save(notetype, templates=True) 

1057 if nids: 

1058 models.col.updateFieldCache(nids) 

1059 else: 

1060 models.save(notetype) 

1061 return LegacyChanges() 

1062 

1063 

1064def _remap_structure(col, notetype): 

1065 """Port of rslib update_notetype: entries keep their old ord, new ones have none.""" 

1066 from anki.utils import ids2str, intTime, joinFields, splitFields 

1067 old = col.models.get(notetype['id']) 

1068 nids = col.db.list('select id from notes where mid=?', notetype['id']) 

1069 fields = [field.get('ord') for field in notetype['flds']] 

1070 if fields != list(range(len(old['flds']))): 

1071 col.modSchema(check=False) 

1072 rows = [] 

1073 for id, flds in col.db.execute('select id, flds from notes where mid=?', notetype['id']): 

1074 values = splitFields(flds) 

1075 rows.append((joinFields([values[ord] if ord is not None and ord < len(values) else '' for ord in fields]), 

1076 intTime(), col.usn(), id)) 

1077 col.db.executemany('update notes set flds=?, mod=?, usn=? where id=?', rows) 

1078 templates = [template.get('ord') for template in notetype['tmpls']] 

1079 if notetype['type'] == 0 and templates != list(range(len(old['tmpls']))): 

1080 col.modSchema(check=False) 

1081 moved = {ord: index for index, ord in enumerate(templates) if ord is not None} 

1082 cards = 'nid in ' + ids2str(nids) 

1083 col.remCards(col.db.list('select id from cards where %s and ord not in %s' % (cards, ids2str(moved)))) 

1084 if moved: 

1085 cases = ' '.join('when %d then %d' % pair for pair in moved.items()) 

1086 col.db.execute('update cards set ord=(case ord %s end), mod=?, usn=? where %s' % (cases, cards), intTime(), col.usn()) 

1087 for key in ('flds', 'tmpls'): 

1088 for index, value in enumerate(notetype[key]): 

1089 value['ord'] = index 

1090 notetype['sortf'] = min(notetype['sortf'], len(notetype['flds']) - 1) 

1091 return nids 

1092 

1093 

1094def clear_unused_tags(col): 

1095 """Remove unused tags; before 2.1.45 the count is measured from the tag list.""" 

1096 before = set(col.tags.all()) 

1097 out = col.tags.clear_unused_tags() 

1098 if out is None: 1098 ↛ 1099line 1098 didn't jump to line 1099 because the condition on line 1098 was never true

1099 out = LegacyChanges(count=len(before - set(col.tags.all()))) 

1100 return out 

1101 

1102 

1103class _CardRecord: 

1104 """A stored card with the protobuf surface of 2.1.24's backend Card message, which older backends lack.""" 

1105 FIELDS = ('id', 'note_id', 'deck_id', 'template_idx', 'mtime_secs', 'usn', 'ctype', 'queue', 'due', 'interval', 

1106 'ease_factor', 'reps', 'lapses', 'remaining_steps', 'original_due', 'original_deck_id', 'flags', 'data') 

1107 DESCRIPTOR = SimpleNamespace(fields_by_name=dict.fromkeys(FIELDS)) 

1108 

1109 def __init__(self, col, card_id): 

1110 _require_row(col, 'cards', card_id) 

1111 row = col.db.first('select id, nid, did, ord, mod, usn, type, queue, due, ivl, factor, reps, lapses, ' 

1112 'left, odue, odid, flags, data from cards where id = ?', card_id) 

1113 self.__dict__.update(zip(self.FIELDS, row)) 

1114 

1115 def ClearField(self, name): 

1116 setattr(self, name, type(getattr(self, name))()) 

1117 

1118 def SerializeToString(self): 

1119 return repr([getattr(self, name) for name in self.FIELDS]).encode() 

1120 

1121 def __eq__(self, other): 

1122 return isinstance(other, _CardRecord) and vars(self) == vars(other) 

1123 

1124 

1125def _find_notes(col, query): 

1126 # The Python finder's findNotes returns no notes for an invalid term, where findCards raises. 

1127 import anki.find 

1128 finder = anki.find.Finder(col) 

1129 if finder._where(finder._tokenize(query))[0] is None: 

1130 raise Exception('invalidSearch') 

1131 return col.findNotes(query) 

1132 

1133 

1134def find_ids(col, kind, query, order=False, reverse=False): 

1135 finder = col.find_notes if kind == 'notes' else col.find_cards 

1136 if order is False and not has(col, 'get_browser_column'): 1136 ↛ 1138line 1136 didn't jump to line 1138 because the condition on line 1136 was never true

1137 # Before 2.1.45 find_notes takes no order. 

1138 return finder(query) 

1139 return finder(query, order=order, reverse=reverse) 

1140 

1141 

1142def _remove_decks(decks, deck_ids): 

1143 for deck_id in deck_ids: 

1144 decks.rem(deck_id, cardsToo=True) 

1145 return LegacyChanges() 

1146 

1147 

1148def cloze_numbers(col, note): 

1149 if has(col._backend, 'cloze_numbers_in_note'): 1149 ↛ 1152line 1149 didn't jump to line 1152 because the condition on line 1149 was always true

1150 return col._backend.cloze_numbers_in_note(note._to_backend_note()) 

1151 # Before 2.1.41 cloze numbers are read from the field text. 

1152 return sorted({int(number) for text in note.fields for number in re.findall(r'\{\{c(\d+)::', text)}) 

1153 

1154 

1155def set_due_date(col, card_ids, days): 

1156 # The config key arrived in 2.1.45. 

1157 if 'config_key' in inspect.signature(col.sched.set_due_date).parameters: 1157 ↛ 1159line 1157 didn't jump to line 1159 because the condition on line 1157 was always true

1158 return col.sched.set_due_date(card_ids, days, config_key=None) 

1159 return col.sched.set_due_date(card_ids, days) 

1160 

1161 

1162def deck_search(col, name): 

1163 if has(col, 'build_search_string'): 1163 ↛ 1167line 1163 didn't jump to line 1167 because the condition on line 1163 was always true

1164 from anki.collection import SearchNode 

1165 return col.build_search_string(SearchNode(deck=name)) 

1166 # Before 2.1.41 searches are written by hand. 

1167 return 'deck:"' + re.sub(r'([\\"*_])', r'\\\1', name) + '"' 

1168 

1169 

1170def _add_normal_deck(decks, name): 

1171 return LegacyChanges(id=decks.id(name, create=True)) 

1172 

1173 

1174def _add_notetype(models, notetype): 

1175 models.add(notetype) 

1176 return LegacyChanges(id=notetype['id']) 

1177 

1178 

1179CLOZE = re.compile(r'\{\{c\d+::') 

1180 

1181 

1182def _cloze_fields(notetype): 

1183 """Indexes of fields rendered through a cloze filter in the first template.""" 

1184 names = set() 

1185 for tag in re.findall(r'\{\{([^}]*)\}\}', notetype['tmpls'][0]['qfmt']): 

1186 parts = tag.strip().split(':') 

1187 if 'cloze' in parts[:-1]: 

1188 names.add(parts[-1]) 

1189 return {field['ord'] for field in notetype['flds'] if field['name'] in names} 

1190 

1191 

1192def _fields_check(note): 

1193 """Port of rslib 2.1.45 note_fields_check: empty, then cloze problems, then duplicates.""" 

1194 state = note.dupeOrEmpty() 

1195 if state == 1: 

1196 return 1 

1197 notetype = note.model() 

1198 cloze = notetype['type'] == 1 

1199 fields = _cloze_fields(notetype) if cloze else set() 

1200 has_cloze = False 

1201 for index, text in enumerate(note.fields): 

1202 if CLOZE.search(text): 

1203 if not cloze: 

1204 return 4 

1205 if index not in fields: 

1206 return 5 

1207 has_cloze = True 

1208 if cloze and not has_cloze: 

1209 return 3 

1210 return state 

1211 

1212 

1213@functools.lru_cache(maxsize=None) 

1214def release(): 

1215 """The running Anki release, for rules that no API exposes.""" 

1216 try: 

1217 from anki.buildinfo import version 

1218 except ImportError: 

1219 from anki import version # Before 2.1.20. 

1220 return tuple(int(part) for part in re.findall(r'\d+', version.split('+')[0])[:3]) 

1221 

1222 

1223@functools.lru_cache(maxsize=None) 

1224def field_name_rules(): 

1225 """The characters rslib removes from field names and strips from their start. 

1226 

1227 2.1.36 added '"' to the removed characters and 2.1.41 began stripping leading "#", "^" and "/".""" 

1228 removed = re.compile(r'[:{}"]' if release() >= (2, 1, 36) else r'[:{}]') 

1229 leading = re.compile(r'^[\s#/^]+' if release() >= (2, 1, 41) else r'^\s+') 

1230 return removed, leading 

1231 

1232 

1233def _set_due_date(sched, card_ids, days, config_key=None): 

1234 """Before 2.1.41 Anki rescheduled to a day range, also setting the interval and starting ease.""" 

1235 match = re.fullmatch(r'\s*(\d+)(?:\s*-\s*(\d+))?\s*!?\s*', days) 

1236 if not match: 

1237 from anki.errors import InvalidInput 

1238 raise InvalidInput(days) 

1239 low = int(match.group(1)) 

1240 high = int(match.group(2) or low) 

1241 sched.reschedCards(list(card_ids), min(low, high), max(low, high)) 

1242 

1243 

1244# 2.1.28 made the client a context manager that closes its session. 

1245_HTTP_CLIENT_BACKPORTS = { 

1246 '__enter__': lambda client: client, 

1247 '__exit__': lambda client, *args: client.session.close(), 

1248} 

1249 

1250 

1251_SCHEDULER_BACKPORTS = { 

1252 'set_due_date': _set_due_date, 

1253 'suspend_cards': lambda sched, ids: sched.suspendCards(list(ids)), 

1254 'unsuspend_cards': lambda sched, ids: sched.unsuspendCards(list(ids)), 

1255 'rebuild_filtered_deck': lambda sched, deck_id: sched.rebuildDyn(deck_id), 

1256 'empty_filtered_deck': lambda sched, deck_id: sched.emptyDyn(deck_id), 

1257 'deck_due_tree': _deck_due_tree, 

1258} 

1259 

1260 

1261# Modern names that releases before 2.1.45 expose under older spellings. 

1262BACKPORTS = { 

1263 'anki.collection.Collection': { 

1264 'get_note': _note, 

1265 'get_card': _card, 

1266 'note_count': lambda col: col.noteCount(), 

1267 'card_count': lambda col: col.cardCount(), 

1268 'new_note': _new_note, 

1269 'update_note': _update_note, 

1270 'update_card': _update_card, 

1271 '_load_scheduler': lambda col: col._loadScheduler(), 

1272 'set_user_flag_for_cards': lambda col, flag, card_ids: col.setUserFlag(flag, list(card_ids)), 

1273 'set_deck': _set_deck, 

1274 'fix_integrity': lambda col: col.fixIntegrity(), 

1275 'add_note': _add_note, 

1276 'remove_notes': _remove_notes, 

1277 'get_config': lambda col, key, default=None: col.conf.get(key, default), 

1278 # Before 2.1.24 the Python finder searched and could not reverse its order. 

1279 'find_cards': lambda col, query, order=False, reverse=False: ( 

1280 lambda ids: ids[::-1] if reverse else ids)(col.findCards(query, order)), 

1281 'find_notes': _find_notes, 

1282 # 2.1.28-2.1.40 sync through the backend directly. 

1283 'sync_collection': lambda col, auth: col.backend.sync_collection(auth), 

1284 'full_upload': lambda col, auth: col.backend.full_upload(auth), 

1285 'full_download': lambda col, auth: col.backend.full_download(auth), 

1286 'abort_sync': lambda col: col.backend.abort_sync() and None, 

1287 'abort_media_sync': lambda col: col.backend.abort_media_sync() and None, 

1288 }, 

1289 'anki.notes.Note': { 

1290 'fields_check': _fields_check, 

1291 'note_type': lambda note: note.model(), 

1292 '_to_backend_note': lambda note: note.to_backend_note(), 

1293 '_field_index': lambda note, name: note._fieldOrd(name), 

1294 'has_tag': lambda note, tag: note.hasTag(tag), 

1295 'add_tag': lambda note, tag: note.addTag(tag), 

1296 'remove_tag': lambda note, tag: note.delTag(tag), 

1297 'joined_fields': lambda note: note.joinedFields(), 

1298 'card_ids': lambda note: note.col.db.list('select id from cards where nid=? order by ord', note.id), 

1299 }, 

1300 'anki.cards.Card': { 

1301 # Before 2.1.20 cards rendered through q() and a(), both prefixed with the CSS. 

1302 'question': lambda card, reload=False, browser=False: card.q(reload, browser), 

1303 'answer': lambda card: card.a(), 

1304 'note_type': lambda card: card.model(), 

1305 'start_timer': lambda card: card.startTimer(), 

1306 'time_limit': lambda card: card.timeLimit(), 

1307 'time_taken': lambda card: card.timeTaken(), 

1308 'user_flag': lambda card: card.userFlag(), 

1309 # The stored card; callers compare freshly loaded cards. 

1310 '_to_backend_card': lambda card: (card.col._backend.get_card(card.id) if has(card.col._backend, 'get_card') 

1311 else _CardRecord(card.col, card.id)), 

1312 }, 

1313 'anki.schedv2.Scheduler': _SCHEDULER_BACKPORTS, 

1314 # Before 2.1.21 the v1 scheduler did not subclass the v2 one. 

1315 'anki.sched.Scheduler': _SCHEDULER_BACKPORTS, 

1316 'anki.media.MediaManager': { 

1317 # Before 2.1.22 Python managed the media folder. 

1318 'write_data': lambda media, fname, data: media.writeData(fname, data), 

1319 'trash_files': _trash_media, 

1320 }, 

1321 'anki.httpclient.HttpClient': _HTTP_CLIENT_BACKPORTS, 

1322 'anki.sync.AnkiRequestsClient': _HTTP_CLIENT_BACKPORTS, 

1323 'anki.tags.TagManager': { 

1324 # Registering all notes rebuilds the tag list before 2.1.41. 

1325 'clear_unused_tags': lambda tags: tags.registerNotes(), 

1326 'bulk_add': lambda tags, note_ids, tags_text: tags.bulkAdd(list(note_ids), tags_text), 

1327 }, 

1328 'anki.models.ModelManager': { 

1329 'by_name': lambda models, name: models.byName(name), 

1330 'add_dict': _add_notetype, 

1331 'update_dict': _update_notetype, 

1332 'use_count': lambda models, notetype: models.useCount(notetype), 

1333 'all_names_and_ids': lambda models: _names_and_ids(models.all()), 

1334 'new_field': lambda models, name: models.newField(name), 

1335 'add_field': lambda models, notetype, field: models.addField(notetype, field), 

1336 'rename_field': lambda models, notetype, field, name: models.renameField(notetype, field, name), 

1337 'new_template': lambda models, name: models.newTemplate(name), 

1338 'add_template': lambda models, notetype, template: models.addTemplate(notetype, template), 

1339 'remove': _remove_notetype, 

1340 }, 

1341 'anki.decks.DeckManager': { 

1342 'by_name': lambda decks, name: decks.byName(name), 

1343 'add_normal_deck_with_name': _add_normal_deck, 

1344 'remove': _remove_decks, 

1345 'new_filtered': lambda decks, name: decks.newDyn(name), 

1346 'id_for_name': lambda decks, name: decks.id(name, create=False), 

1347 # Missing presets fall back to Default, as the Rust backend does from 2.1.24. 

1348 'get_config': lambda decks, conf_id: decks.dconf.get(str(conf_id)) or decks.dconf['1'], 

1349 'all_config': lambda decks: decks.allConf(), 

1350 'all_names_and_ids': lambda decks, skip_empty_default=False, include_filtered=True: _names_and_ids( 

1351 deck for deck in decks.all() if include_filtered or not deck['dyn']), 

1352 }, 

1353} 

1354 

1355 

1356def _to_json_bytes(value): 

1357 import json 

1358 return json.dumps(value, separators=(',', ':')).encode('utf8') 

1359 

1360 

1361def _rsbackend(name): 

1362 def load(): 

1363 import importlib.util 

1364 if importlib.util.find_spec('anki.rsbackend') is None: 

1365 return None # Before 2.1.20 Anki had no Rust backend. 

1366 import anki.rsbackend 

1367 return getattr(anki.rsbackend, name, None) 

1368 return load 

1369 

1370 

1371# Module names the plugin imports, with loaders for their earlier homes. 

1372MODULE_BACKPORTS = { 

1373 'anki.errors': { 

1374 'NotFoundError': _rsbackend('NotFoundError'), 

1375 'InvalidInput': _rsbackend('InvalidInput'), 

1376 'Interrupted': _rsbackend('Interrupted'), 

1377 }, 

1378 'anki.sync': { 

1379 'SyncAuth': _rsbackend('SyncAuth'), 

1380 'SyncOutput': _rsbackend('SyncOutput'), 

1381 }, 

1382 'anki.utils': { 

1383 'to_json_bytes': lambda: _to_json_bytes, 

1384 }, 

1385} 

1386 

1387 

1388def http_client(): 

1389 """Anki's HTTP client, which was anki.sync.AnkiRequestsClient before 2.1.20.""" 

1390 try: 

1391 from anki.httpclient import HttpClient 

1392 except ImportError: 

1393 from anki.sync import AnkiRequestsClient as HttpClient 

1394 return HttpClient() 

1395 

1396 

1397def collection_class(): 

1398 """The collection class; before 2.1.28 it was private and opened by anki.storage.Collection().""" 

1399 import anki.collection 

1400 return getattr(anki.collection, 'Collection', None) or anki.collection._Collection 

1401 

1402 

1403def install_backports(): 

1404 """Add modern collection methods to releases that lack them, never replacing native ones.""" 

1405 import importlib.util 

1406 for path, methods in BACKPORTS.items(): 

1407 module, name = path.rsplit('.', 1) 

1408 if importlib.util.find_spec(module) is None: 

1409 continue 

1410 cls = getattr(importlib.import_module(module), name, None) 

1411 if cls is None and path == 'anki.collection.Collection': 1411 ↛ 1412line 1411 didn't jump to line 1412 because the condition on line 1411 was never true

1412 cls = collection_class() 

1413 if cls is None: 1413 ↛ 1414line 1413 didn't jump to line 1414 because the condition on line 1413 was never true

1414 continue 

1415 for method, function in methods.items(): 

1416 if not hasattr(cls, method): 

1417 setattr(cls, method, function) 

1418 for path, names in MODULE_BACKPORTS.items(): 

1419 module = importlib.import_module(path) 

1420 for name, load in names.items(): 

1421 if not hasattr(module, name): 1421 ↛ 1422line 1421 didn't jump to line 1422 because the condition on line 1421 was never true

1422 value = load() 

1423 if value is None and path == 'anki.errors': 

1424 # Nothing native raises it there, but backports may. 

1425 value = type(name, (Exception,), {}) 

1426 if value is not None: 

1427 setattr(module, name, value) 

1428 if importlib.util.find_spec('anki._backend') is None: 1428 ↛ 1432line 1428 didn't jump to line 1432 because the condition on line 1428 was never true

1429 # Before 2.1.41 the collection named its backend col.backend. Later 

1430 # releases assign _backend per instance, so this property must not exist there. 

1431 # Before 2.1.20 there is no backend, and backend capabilities are absent. 

1432 collection_class()._backend = property(lambda col: getattr(col, 'backend', None))