-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path__init__.py
More file actions
5822 lines (4872 loc) · 301 KB
/
Copy path__init__.py
File metadata and controls
5822 lines (4872 loc) · 301 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
# An add-on to the Anki program. For the window with card templates,
# it adds the ability to color the code, insert and auto-complete some words and lines.
# It can save the cursor position when switching templates.
# It is possible to open the code in an external editor.
# The original idea "HTML Buttons in Template" is from the author: https://ankiweb.net/shared/info/2063726776
# This code has been corrected, improved and supplemented with other ideas:
# - the most important thing and could be in Anki is saving the cursor position (selection)
# when switching between the front and back templates, css.
# - the ability to save the code and open it with a third-party application
# (preferably Visual Studio Code). The Anki editor is not blocked
# and if you save in both applications, then even parallel work is possible.
# A copy of the template is also saved (by Ctrl + S) to the temporary folder anki_backup.
# If necessary, such copies can be loaded later.
# - code autocompletion, autoinsert, user code templates.
# - highlighting by code of all words as in the current selection,
# the ability to find the desired word by code (Ctrl+F, and continue F3)
# https://github.com/AndreyKaiu/Anki_Card-Templates---HTML-JavaScript-CSS-code-highlighting
# Version 1.3, date: 2026-05-23
import os
import json
import time
import re
import shlex
import copy
import unicodedata
import logging
import tempfile
import subprocess
import anki.lang
from logging import Logger, FileHandler, Formatter
from pathlib import Path
from datetime import datetime, timedelta
from aqt.utils import showText, askUser, tr
from anki.lang import without_unicode_isolation
from aqt.clayout import CardLayout
from types import MethodType
from aqt import mw
from aqt.qt import *
from aqt.gui_hooks import card_layout_will_show
from aqt.clayout import CardLayout
from aqt.addons import AddonManager
from aqt.utils import tooltip, shortcut, getOnlyText
from aqt.clayout import CardLayout
from aqt.theme import theme_manager
from bs4 import BeautifulSoup, Comment
# ========================= PYQT_VERSION ======================================
try:
from PyQt6.QtWidgets import (
QApplication,
QPushButton,
QHBoxLayout,
QGroupBox,
QColorDialog,
QTextEdit,
QDialog,
QVBoxLayout,
QCompleter,
QFileDialog,
QLabel,
QComboBox,
QLineEdit,
QStyledItemDelegate
)
from PyQt6.QtGui import QTextDocument, QTextOption, QGuiApplication, QTextCharFormat, QColor, QFont, QSyntaxHighlighter, QTextCursor, QPainter, QTextFormat
from PyQt6.QtCore import QRegularExpression, Qt, QSize, QEvent, QTimer, QCoreApplication
pyqt_version = "PyQt6"
except ImportError:
from PyQt5.QtWidgets import (
QApplication,
QPushButton,
QHBoxLayout,
QGroupBox,
QColorDialog,
QTextEdit,
QDialog,
QVBoxLayout,
QCompleter,
QFileDialog,
QLabel,
QComboBox,
QLineEdit,
QStyledItemDelegate
)
from PyQt5.QtGui import QTextDocument, QTextOption, QGuiApplication, QTextCharFormat, QColor, QFont, QSyntaxHighlighter, QTextCursor, QPainter, QTextFormat
from PyQt5.QtCore import QRegExp, Qt, QSize, QEvent, QTimer, QCoreApplication
pyqt_version = "PyQt5"
if pyqt_version == "PyQt6":
KeepAnchor = QTextCursor.MoveMode.KeepAnchor
MoveAnchor = QTextCursor.MoveMode.MoveAnchor
NextCharacter = QTextCursor.MoveOperation.NextCharacter
PreviousCharacter = QTextCursor.MoveOperation.PreviousCharacter
SingleUnderline = QTextCharFormat.UnderlineStyle.SingleUnderline
WA_TransparentForMouseEvents = Qt.WidgetAttribute.WA_TransparentForMouseEvents
WA_NoSystemBackground = Qt.WidgetAttribute.WA_NoSystemBackground
WA_TranslucentBackground = Qt.WidgetAttribute.WA_TranslucentBackground
MetaModifier = Qt.KeyboardModifier.MetaModifier
ControlModifier = Qt.KeyboardModifier.ControlModifier
ShiftModifier = Qt.KeyboardModifier.ShiftModifier
AltModifier = Qt.KeyboardModifier.AltModifier
FindBackward = QTextDocument.FindFlag.FindBackward
FindWholeWords = QTextDocument.FindFlag.FindWholeWords
FindCaseSensitively = QTextDocument.FindFlag.FindCaseSensitively
Start = QTextCursor.MoveOperation.Start
WaitCursor = Qt.CursorShape.WaitCursor
GC_white = Qt.GlobalColor.white
GC_black = Qt.GlobalColor.black
CustomContextMenu = Qt.ContextMenuPolicy.CustomContextMenu
Key_Return = Qt.Key.Key_Return
Key_Space = Qt.Key.Key_Space
Key_Percent = Qt.Key.Key_Percent
Key_Tab = Qt.Key.Key_Tab
Key_Backtab = Qt.Key.Key_Backtab
Key_Enter = Qt.Key.Key_Enter
Key_Escape = Qt.Key.Key_Escape
Key_Up = Qt.Key.Key_Up
Key_Down = Qt.Key.Key_Down
Key_V = Qt.Key.Key_V
Key_Home = Qt.Key.Key_Home
Key_End = Qt.Key.Key_End
Key_F1 = Qt.Key.Key_F1
Key_0 = Qt.Key.Key_0
Key_Slash = Qt.Key.Key_Slash
Key_B = Qt.Key.Key_B
Key_I = Qt.Key.Key_I
Key_U = Qt.Key.Key_U
Key_K = Qt.Key.Key_K
Key_M = Qt.Key.Key_M
Key_Q = Qt.Key.Key_Q
Key_Equal = Qt.Key.Key_Equal
Key_Plus = Qt.Key.Key_Plus
Key_Exclam = Qt.Key.Key_Exclam
Key_At = Qt.Key.Key_At
Key_NumberSign = Qt.Key.Key_NumberSign
Key_Dollar = Qt.Key.Key_Dollar
Key_AsciiCircum = Qt.Key.Key_AsciiCircum
Key_Ampersand = Qt.Key.Key_Ampersand
Key_Asterisk = Qt.Key.Key_Asterisk
Key_D = Qt.Key.Key_D
Key_T = Qt.Key.Key_T
Key_B = Qt.Key.Key_B
Key_BraceLeft = Qt.Key.Key_BraceLeft
Key_BracketLeft = Qt.Key.Key_BracketLeft
Key_ParenLeft = Qt.Key.Key_ParenLeft
Key_QuoteDbl = Qt.Key.Key_QuoteDbl
Key_Apostrophe = Qt.Key.Key_Apostrophe
Key_Minus = Qt.Key.Key_Minus
Key_Greater = Qt.Key.Key_Greater
Key_Left = Qt.Key.Key_Left
Key_Right = Qt.Key.Key_Right
Key_Left = Qt.Key.Key_Left
Key_Insert = Qt.Key.Key_Insert
else:
KeepAnchor = QTextCursor.KeepAnchor
MoveAnchor = QTextCursor.MoveAnchor
NextCharacter = QTextCursor.NextCharacter
PreviousCharacter = QTextCursor.PreviousCharacter
SingleUnderline = QTextCharFormat.SingleUnderline
WA_TransparentForMouseEvents = Qt.WA_TransparentForMouseEvents
WA_NoSystemBackground = Qt.WA_NoSystemBackground
WA_TranslucentBackground = Qt.WA_TranslucentBackground
MetaModifier = Qt.MetaModifier
ControlModifier = Qt.ControlModifier
ShiftModifier = Qt.ShiftModifier
AltModifier = Qt.AltModifier
FindBackward = QTextDocument.FindBackward
FindWholeWords = QTextDocument.FindWholeWords
FindCaseSensitively = QTextDocument.FindCaseSensitively
Start = QTextCursor.Start
WaitCursor = Qt.WaitCursor
GC_white = Qt.white
GC_black = Qt.black
CustomContextMenu = Qt.CustomContextMenu
Key_Return = Qt.Key_Return
Key_Space = Qt.Key_Space
Key_Percent = Qt.Key_Percent
Key_Tab = Qt.Key_Tab
Key_Backtab = Qt.Key_Backtab
Key_Enter = Qt.Key_Enter
Key_Escape = Qt.Key_Escape
Key_Up = Qt.Key_Up
Key_Down = Qt.Key_Down
Key_V = Qt.Key_V
Key_Home = Qt.Key_Home
Key_End = Qt.Key_End
Key_F1 = Qt.Key_F1
Key_0 = Qt.Key_0
Key_Slash = Qt.Key_Slash
Key_B = Qt.Key_B
Key_I = Qt.Key_I
Key_U = Qt.Key_U
Key_K = Qt.Key_K
Key_M = Qt.Key_M
Key_Q = Qt.Key_Q
Key_Equal = Qt.Key_Equal
Key_Plus = Qt.Key_Plus
Key_Exclam = Qt.Key_Exclam
Key_At = Qt.Key_At
Key_NumberSign = Qt.Key_NumberSign
Key_Dollar = Qt.Key_Dollar
Key_AsciiCircum = Qt.Key_AsciiCircum
Key_Ampersand = Qt.Key_Ampersand
Key_Asterisk = Qt.Key_Asterisk
Key_D = Qt.Key_D
Key_T = Qt.Key_T
Key_B = Qt.Key_B
Key_BraceLeft = Qt.Key_BraceLeft
Key_BracketLeft = Qt.Key_BracketLeft
Key_ParenLeft = Qt.Key_ParenLeft
Key_QuoteDbl = Qt.Key_QuoteDbl
Key_Apostrophe = Qt.Key_Apostrophe
Key_Minus = Qt.Key_Minus
Key_Greater = Qt.Key_Greater
Key_Right = Qt.Key_Right
Key_Left = Qt.Key_Left
Key_Insert = Qt.Key_Insert
# ========================= LOGGING ===========================================
log: Logger = logging.getLogger(__name__)
class Logs:
def __init__(self, log_dir: Path, version):
log_dir.mkdir(exist_ok=True, parents=True)
self.__log_file: Path = log_dir.joinpath("Card Templates - HTML JavaScript CSS code highlighting.log")
self.__root_logger: Logger = self.__configure_logging()
self.error_count = 0 # Счетчик ошибок
def root_logger(self) -> Logger:
return self.__root_logger
def set_level(self, log_level: str) -> None:
self.__root_logger.setLevel(log_level)
def get_log_file(self) -> Path:
return self.__log_file
def __configure_logging(self) -> Logger:
logger: Logger = logging.getLogger(__name__.split(".")[0])
handler: FileHandler = FileHandler(self.__log_file, encoding="utf-8", errors="replace")
level: int = logging.DEBUG # (DEBUG, INFO, WARNING, ERROR, CRITICAL)
handler.setLevel(level)
formatter: Formatter = Formatter('%(asctime)s %(levelname)s %(name)s %(funcName)s %(threadName)s %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.setLevel(level)
logger.info(f"\n\n{'#' * 34} {logger.name} {'#' * 34}\nLogger was configured: "
f"logger_name={logger.name}, version={version} level={logging.getLevelName(level)}, "
f"PyQt_version={pyqt_version}\n file={self.__log_file}"
)
return logger
module_dir: Path = Path(__file__).parent
module_name: str = module_dir.stem
addon_manager: AddonManager = mw.addonManager
version: str = addon_manager.addonMeta(module_name).get("human_version", "0.0")
log_dir: Path = addon_manager.logs_folder(module_name)
logs: Logs = Logs(log_dir, version)
logs.set_level("DEBUG")
# ========================= CONFIG ============================================
# Loading the add-on configuration
config = mw.addonManager.getConfig(__name__)
meta = mw.addonManager.addon_meta(__name__)
this_addon_provided_name = meta.provided_name
def configF(par1, par2, default=""):
"""получить данные из конфига"""
try:
ret = config[par1][par2]
return ret
except Exception as e:
logError(e)
return default
# определям темная или светлая тема
theme_night = True if theme_manager.night_mode else False
themeName = configF("GLOBAL_SETTINGS", "theme", "MODERN")
auto_insert = config["GLOBAL_SETTINGS"]["auto_insert"]
auto_completion = config["GLOBAL_SETTINGS"]["auto_completion"]
languageName = configF("GLOBAL_SETTINGS", "language", "en")
current_language = anki.lang.current_lang #en, pr-BR, en-GB, ru и подобное
if not languageName: # если надо автоопределение
languageName = current_language
if languageName not in config["LOCALIZATION"]:
languageName = "en" # Если не поддерживается, откатываемся на английский
try:
localization = config["LOCALIZATION"][languageName]
except Exception as e:
text = f"ERROR in add-on '{this_addon_provided_name}'\n"
text += f"Config[\"GLOBAL_SETTINGS\"][\"language\"] does not contain '{languageName}'"
text += "\nChange the add-on configuration, \"language\": \"en\""
languageName = "en"
config["GLOBAL_SETTINGS"]["language"] = languageName # меняем язык
mw.addonManager.writeConfig(__name__, config) # записываем конфиг с изменениями
showText(text, type="error")
if theme_night:
colors = config["THEMES"][themeName]["DARK_MODE"]
else:
colors = config["THEMES"][themeName]["LIGHT_MODE"]
def localizationF(par1, default=""):
"""получить данные из localization = config["LOCALIZATION"][languageName] """
try:
ret = localization[par1]
return ret
except Exception as e:
logError(e)
return default
# =============================================================================
html_js_highlighting_addon = None
thisCardLayout = None
template_name = None
gl_model_name = None
from aqt.gui_hooks import card_layout_will_show
original_update_current_ordinal_and_redraw = None
def custom_update_current_ordinal_and_redraw(self, idx: int) -> None:
global template_name, gl_model_name, html_js_highlighting_addon, original_update_current_ordinal_and_redraw
if self.ignore_change_signals:
return
# если изменения пройдут и станет self.ord = idx то надо сохранить позицию
html_js_highlighting_addon.save_cursor_position(html_js_highlighting_addon.cur_edit_area)
original_update_current_ordinal_and_redraw(idx) # вызов оригинального
template_name = self.model["name"] + "_card" + str(self.ord+1)
# изменения прошли и вызвать смену позиции
html_js_highlighting_addon.restore_cursor_position(html_js_highlighting_addon.cur_edit_area, html_js_highlighting_addon.current_button)
html_js_highlighting_addon.needs_update_from_external_editor(html_js_highlighting_addon.cur_edit_area)
paste_without_tab_replace = False
def on_card_layout_will_show(card_layout: CardLayout):
global thisCardLayout, gl_model_name, template_name, theme_night, colors, html_js_highlighting_addon, original_update_current_ordinal_and_redraw
if theme_manager.night_mode: # определям темная или светлая тема
theme_night = True
else:
theme_night = False
if theme_night:
colors = config["THEMES"][themeName]["DARK_MODE"]
else:
colors = config["THEMES"][themeName]["LIGHT_MODE"]
thisCardLayout = card_layout
# табуляция 4 символа
thisCardLayout.tform.edit_area.setTabStopDistance(thisCardLayout.tform.edit_area.fontMetrics().horizontalAdvance('0000'))
# Переопределяем метод вставки из буфера обмена
original_insert_from_mime_data = thisCardLayout.tform.edit_area.insertFromMimeData
def custom_insert_from_mime_data(source: QMimeData):
global thisCardLayout, paste_without_tab_replace
text = source.text() # Получаем текст из буфера обмена
if not paste_without_tab_replace:
text = text.replace("\t", " ") # Заменяем табуляции на 4 пробела
cursor = thisCardLayout.tform.edit_area.textCursor() # Вставляем измененный текст
cursor.insertText(text)
# Заменяем оригинальный метод на наш
thisCardLayout.tform.edit_area.insertFromMimeData = custom_insert_from_mime_data
# Изменяем структуру self.cursor_positions для хранения позиции курсора и вертикального скроллинга
html_js_highlighting_addon.cursor_positions = {
i: { # стиль общий и всегда хранится в i==0
"front_button": {"cursor_position": 0, "cursor_position_end": 0, "vertical_scroll": 0, "position_history": [{"cursor_position": 0, "cursor_position_end": 0, "vertical_scroll": 0} for _ in range(7)]},
"back_button": {"cursor_position": 0, "cursor_position_end": 0, "vertical_scroll": 0, "position_history": [{"cursor_position": 0, "cursor_position_end": 0, "vertical_scroll": 0} for _ in range(7)]},
"style_button": {"cursor_position": 0, "cursor_position_end": 0, "vertical_scroll": 0, "position_history": [{"cursor_position": 0, "cursor_position_end": 0, "vertical_scroll": 0} for _ in range(7)]}
}
for i in range(len(thisCardLayout.templates))
}
gl_model_name = card_layout.model["name"]
# print("html_js_highlighting_addon.load_cursor_positions_from_prefs21")
# QTimer.singleShot(100, lambda: html_js_highlighting_addon.load_cursor_positions_from_prefs21(gl_model_name) )
html_js_highlighting_addon.load_cursor_positions_from_prefs21(gl_model_name)
# замена на свой update_current_ordinal_and_redraw
original_update_current_ordinal_and_redraw = card_layout.update_current_ordinal_and_redraw
# Привязываем кастомный метод к экземпляру card_layout
card_layout.update_current_ordinal_and_redraw = MethodType(custom_update_current_ordinal_and_redraw, card_layout)
# Переподключаем сигнал
card_layout.topAreaForm.templatesBox.currentIndexChanged.disconnect()
qconnect(
card_layout.topAreaForm.templatesBox.currentIndexChanged,
card_layout.update_current_ordinal_and_redraw,
)
# подмена on_search_changed чтобы можно было сделать поиск назад по Shift+Enter
def custom_on_search_changed(self, text: str) -> None:
editor = self.tform.edit_area
modifiers = QApplication.keyboardModifiers()
if modifiers == ShiftModifier:
cursor = editor.textCursor()
start_pos = cursor.position() - 1
cursor.movePosition(QTextCursor.MoveOperation.Left) # Перемещаем курсор на одну позицию назад
editor.setTextCursor(cursor) # Устанавливаем курсор
found = editor.find(text, FindBackward)
if not found:
cursor.movePosition(QTextCursor.MoveOperation.End)
editor.setTextCursor(cursor)
found = editor.find(text, FindBackward)
if not found:
tooltip("No matches found.")
else:
if not editor.find(text):
# try again from top
cursor = editor.textCursor()
cursor.movePosition(Start)
editor.setTextCursor(cursor)
if not editor.find(text):
tooltip("No matches found.")
card_layout.tform.search_edit.textChanged.disconnect()
card_layout.tform.search_edit.setPlaceholderText(localizationF("SearchPlaceholder", "Search ('Enter' - next, 'Shift+Enter' - previous)"))
card_layout.topAreaForm.templatesBox.setToolTip("↑ " + shortcut("Ctrl+F3") + ", " + shortcut("Ctrl+F4") + " ↓" )
card_layout.on_search_changed = MethodType(custom_on_search_changed, card_layout)
qconnect(card_layout.tform.search_edit.textChanged, card_layout.on_search_changed)
# подмена удаления, чтобы можно было удалить и в cursor_positions
original_onRemoveInner = card_layout.onRemoveInner
def custom_onRemoveInner(self, template: dict) -> None:
cord = self.ord
# удаляем тут и cursor_positions по индексу cord
if cord in html_js_highlighting_addon.cursor_positions:
if cord==0 and len(self.templates) > 1: # перепишем стиль из 0
html_js_highlighting_addon.cursor_positions[cord+1]["style_button"] = html_js_highlighting_addon.cursor_positions[cord]["style_button"]
del html_js_highlighting_addon.cursor_positions[cord]
# Сдвигаем ключи для оставшихся элементов
keys_to_shift = sorted(k for k in html_js_highlighting_addon.cursor_positions.keys() if k > cord)
for key in keys_to_shift:
html_js_highlighting_addon.cursor_positions[key - 1] = html_js_highlighting_addon.cursor_positions.pop(key)
original_onRemoveInner(template)
card_layout.onRemoveInner = MethodType(custom_onRemoveInner, card_layout)
# подмена добавления, чтобы можно было cursor_positions правильно отработать
originl_onAddCard = card_layout.onAddCard
def custom_onAddCard(self) -> None:
cnt = self.mw.col.models.use_count(self.model)
txt = tr.card_templates_this_will_create_card_proceed(count=cnt)
if cnt and not askUser(txt):
return
if not self.change_tracker.mark_schema():
return
new_index = len(html_js_highlighting_addon.cursor_positions)
html_js_highlighting_addon.cursor_positions[new_index] = {
"front_button": {"cursor_position": 0, "cursor_position_end": 0, "vertical_scroll": 0, "position_history": [{"cursor_position": 0, "cursor_position_end": 0, "vertical_scroll": 0} for _ in range(7)]},
"back_button": {"cursor_position": 0, "cursor_position_end": 0, "vertical_scroll": 0, "position_history": [{"cursor_position": 0, "cursor_position_end": 0, "vertical_scroll": 0} for _ in range(7)]},
"style_button": {"cursor_position": 0, "cursor_position_end": 0, "vertical_scroll": 0, "position_history": [{"cursor_position": 0, "cursor_position_end": 0, "vertical_scroll": 0} for _ in range(7)]}
}
name = self._newCardName()
t = self.mm.new_template(name)
old = self.current_template()
t["qfmt"] = old["qfmt"]
t["afmt"] = old["afmt"]
self.mm.add_template(self.model, t)
self.ord = len(self.templates) - 1
self.redraw_everything()
card_layout.onAddCard = MethodType(custom_onAddCard, card_layout)
# подмена изменения позиции
original_onReorder = card_layout.onReorder
def custom_onReorder(self) -> None:
n = len(self.templates)
template = self.current_template()
current_pos = self.templates.index(template) + 1
pos_txt = getOnlyText(
tr.card_templates_enter_new_card_position_1(val=n),
default=str(current_pos),
)
if not pos_txt:
return
try:
pos = int(pos_txt)
except ValueError:
return
if pos < 1 or pos > n:
return
if pos == current_pos:
return
new_idx = pos - 1
if not self.change_tracker.mark_schema():
return
# Выполняем обмен
tmp_cursor_positions = copy.deepcopy(html_js_highlighting_addon.cursor_positions[self.ord])
html_js_highlighting_addon.cursor_positions[self.ord] = copy.deepcopy(html_js_highlighting_addon.cursor_positions[new_idx])
html_js_highlighting_addon.cursor_positions[new_idx] = tmp_cursor_positions
if self.ord == 0: # если из них был 0, то стили оставляем в нулевом
html_js_highlighting_addon.cursor_positions[0]["style_button"] = html_js_highlighting_addon.cursor_positions[new_idx]["style_button"]
if new_idx == 0:
html_js_highlighting_addon.cursor_positions[0]["style_button"] = html_js_highlighting_addon.cursor_positions[self.ord]["style_button"]
self.mm.reposition_template(self.model, template, new_idx)
self.ord = new_idx
self.redraw_everything()
card_layout.onReorder = MethodType(custom_onReorder, card_layout)
html_js_highlighting_addon.setup_close_event_handler(card_layout)
html_js_highlighting_addon.setup_show_event_handler(card_layout)
html_js_highlighting_addon.setup_hide_event_handler(card_layout)
# Подключаем хук
card_layout_will_show.append(on_card_layout_will_show)
def CtrlF4():
global thisCardLayout
thisCardLayout.topAreaForm.templatesBox.setFocus()
thisCardLayout.update_current_ordinal_and_redraw(thisCardLayout.ord + 1) if thisCardLayout.ord + 1 < len(thisCardLayout.templates) else None
def CtrlF3():
global thisCardLayout
thisCardLayout.topAreaForm.templatesBox.setFocus()
thisCardLayout.update_current_ordinal_and_redraw(thisCardLayout.ord - 1) if thisCardLayout.ord - 1 > -1 else None
# подмена CardLayout.setupShortcuts чтобы заменить F3, F4 на Ctrl+F3, Ctrl+F4
def custom_CardLayout_setupShortcuts(self) -> None:
self.tform.front_button.setToolTip(shortcut("Ctrl+1"))
self.tform.back_button.setToolTip(shortcut("Ctrl+2"))
self.tform.style_button.setToolTip(shortcut("Ctrl+3"))
QShortcut( # type: ignore
QKeySequence("Ctrl+1"),
self,
activated=self.tform.front_button.click,
)
QShortcut( # type: ignore
QKeySequence("Ctrl+2"),
self,
activated=self.tform.back_button.click,
)
QShortcut( # type: ignore
QKeySequence("Ctrl+3"),
self,
activated=self.tform.style_button.click,
)
for i in range(min(len(self.cloze_numbers), 9)):
QShortcut( # type: ignore
QKeySequence(f"Alt+{i+1}"),
self,
activated=lambda n=i: self.pform.cloze_number_combo.setCurrentIndex(n),
)
# Подменяем метод setupShortcuts
CardLayout.setupShortcuts = custom_CardLayout_setupShortcuts
# =============================================================================
def convert_color_to_hex(color: str) -> str:
"""
Конвертирует цвет из форматов rgb(), rgba(), hsl(), hsla() в #RRGGBB или #AARRGGBB.
Если формат не распознан, возвращает исходное значение.
"""
# Регулярные выражения для rgb/rgba
rgb_regex = re.compile(r'rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)')
rgba_regex = re.compile(r'rgba\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(0|1|0?\.\d+)\s*\)')
# Регулярные выражения для hsl/hsla
hsl_regex = re.compile(r'hsl\(\s*(\d{1,3})\s*,\s*(\d{1,3})%\s*,\s*(\d{1,3})%\s*\)')
hsla_regex = re.compile(r'hsla\(\s*(\d{1,3})\s*,\s*(\d{1,3})%\s*,\s*(\d{1,3})%\s*,\s*(0|1|0?\.\d+)\s*\)')
# Проверяем rgb
match = rgb_regex.match(color)
if match:
r, g, b = map(int, match.groups())
return f"#{r:02X}{g:02X}{b:02X}"
# Проверяем rgba
match = rgba_regex.match(color)
if match:
r, g, b = map(int, match.groups()[:3])
a = float(match.group(4))
alpha = int(a * 255)
return f"#{alpha:02X}{r:02X}{g:02X}{b:02X}"
# Проверяем hsl
match = hsl_regex.match(color)
if match:
h, s, l = map(int, match.groups())
r, g, b = hsl_to_rgb(h, s / 100, l / 100)
return f"#{r:02X}{g:02X}{b:02X}"
# Проверяем hsla
match = hsla_regex.match(color)
if match:
h, s, l = map(int, match.groups()[:3])
a = float(match.group(4))
r, g, b = hsl_to_rgb(h, s / 100, l / 100)
alpha = int(a * 255)
return f"#{alpha:02X}{r:02X}{g:02X}{b:02X}"
# Если формат не распознан, возвращаем исходное значение
return color
def hsl_to_rgb(h, s, l):
"""
Преобразует HSL в RGB.
h: Hue (0-360)
s: Saturation (0-1)
l: Lightness (0-1)
Возвращает кортеж (r, g, b) с компонентами в диапазоне 0-255.
"""
c = (1 - abs(2 * l - 1)) * s
x = c * (1 - abs((h / 60) % 2 - 1))
m = l - c / 2
if 0 <= h < 60:
r, g, b = c, x, 0
elif 60 <= h < 120:
r, g, b = x, c, 0
elif 120 <= h < 180:
r, g, b = 0, c, x
elif 180 <= h < 240:
r, g, b = 0, x, c
elif 240 <= h < 300:
r, g, b = x, 0, c
elif 300 <= h < 360:
r, g, b = c, 0, x
else:
r, g, b = 0, 0, 0
r = int((r + m) * 255)
g = int((g + m) * 255)
b = int((b + m) * 255)
return r, g, b
class AppFocusWatcher(QObject): # Наследуемся от QObject
def __init__(self, app):
super().__init__() # Инициализируем базовый класс QObject
self.app = app
self.app.installEventFilter(self)
self.is_active = False # Флаг активности приложения
self.activate_trigger = False # Менялось ли активность и надо обработать её
def eventFilter(self, obj, event):
# Проверяем тип события в зависимости от версии PyQt
event_type = event.type()
if pyqt_version == "PyQt6":
activate_event = QEvent.Type.ApplicationActivate
deactivate_event = QEvent.Type.ApplicationDeactivate
else: # PyQt5
activate_event = QEvent.ApplicationActivate
deactivate_event = QEvent.ApplicationDeactivate
if event_type == activate_event:
self.is_active = True
elif event_type == deactivate_event:
self.is_active = False
self.activate_trigger = True
return super().eventFilter(obj, event)
focus_watcher = AppFocusWatcher(QApplication.instance())
class InputDialogWithHistory:
def __init__(self, nameH="input_dialog_with_history", max_history=20):
self.max_history = max_history
self.nameH = nameH
self.history = {} # Будет хранить историю для разных заголовков/меток
self.load_history() # Загружает историю из настроек
def getText(self, parent, title, label, default_text=""):
"""Показывает диалог ввода с историей"""
# Создаем комбобокс вместо обычного поля ввода
dialog = QDialog(parent)
dialog.setWindowTitle(title)
layout = QVBoxLayout(dialog)
# Метка
layout.addWidget(QLabel(label))
# Комбобокс с историей
combo = QComboBox()
combo.setEditable(True)
combo.setInsertPolicy(QComboBox.InsertPolicy.InsertAtTop)
combo.setMaxCount(self.max_history)
combo.setDuplicatesEnabled(False)
# Загружаем историю
history_key = self.nameH
if history_key in self.history:
for item in self.history[history_key]:
combo.addItem(item)
if default_text:
combo.setCurrentText(default_text)
layout.addWidget(combo)
combo.lineEdit().selectAll()
# Кнопки
button_box = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok |
QDialogButtonBox.StandardButton.Cancel)
button_box.accepted.connect(dialog.accept)
button_box.rejected.connect(dialog.reject)
layout.addWidget(button_box)
# Показываем диалог
result = dialog.exec()
text = combo.currentText().strip()
if result == QDialog.DialogCode.Accepted and text:
# Сохраняем в историю
self._add_to_history(history_key, text)
self.save_history()
return text, True
else:
return "", False
def _add_to_history(self, key, text):
"""Добавляет текст в историю"""
if key not in self.history:
self.history[key] = []
# Удаляем если уже есть
if text in self.history[key]:
self.history[key].remove(text)
# Добавляем в начало
self.history[key].insert(0, text)
# Ограничиваем размер истории
if len(self.history[key]) > self.max_history:
self.history[key] = self.history[key][:self.max_history]
def save_history(self):
"""Сохраняет историю в настройки"""
try:
mw.pm.profile[self.nameH] = self.history
except:
pass
def load_history(self):
"""Загружает историю из настроек"""
try:
self.history = mw.pm.profile.get(self.nameH, {})
except:
self.history = {}
def closeEvent(self, event):
"""Сохраняем историю при закрытии"""
self.save_history()
super().closeEvent(event)
class FindReplaceDialog(QDialog):
def __init__(self, editor):
super().__init__()
self.editor = editor
self.setWindowTitle(localizationF("Find_and_Replace", "Find and Replace"))
layout = QVBoxLayout(self)
cursor = self.editor.textCursor()
self.cursor_hasSelection = cursor.hasSelection()
# Заменяем QLineEdit на QComboBox для истории поиска
self.find_edit = QComboBox()
self.find_edit.setEditable(True) # Разрешаем редактирование
self.find_edit.setInsertPolicy(QComboBox.InsertPolicy.InsertAtTop) # Новые элементы в начало
self.find_edit.setMaxCount(20) # Максимум 20 элементов в истории
self.find_edit.setDuplicatesEnabled(False) # Не допускать дубликаты
self.replace_edit = QComboBox()
self.replace_edit.setEditable(True)
self.replace_edit.setInsertPolicy(QComboBox.InsertPolicy.InsertAtTop)
self.replace_edit.setMaxCount(20)
self.replace_edit.setDuplicatesEnabled(False)
# Загружаем историю из настроек
self.load_history()
# Флаги поиска
self.case_checkbox = QCheckBox(localizationF("Case_sensitive", "Case sensitive"))
self.case_checkbox.setChecked(True)
self.word_checkbox = QCheckBox(localizationF("Whole_words", "Whole words"))
self.word_checkbox.setChecked(False)
self.selection_checkbox = QCheckBox(localizationF("In_selection_only", "In selection only"))
self.selection_checkbox.setChecked(False)
# Кнопки поиска
btn_layout = QHBoxLayout()
self.find_btn_prev = QPushButton(localizationF("Find_previous", "Find previous"))
self.find_btn = QPushButton(localizationF("Find_next", "Find next"))
btn_layout.addWidget(self.find_btn_prev)
btn_layout.addWidget(self.find_btn)
layout.addWidget(QLabel(localizationF("Find_string", "Find string:")))
layout.addWidget(self.find_edit)
layout.addLayout(btn_layout)
if self.cursor_hasSelection: # выбор только в выделении если это выделение было
layout.addWidget(self.selection_checkbox)
txt = cursor.selectedText()
if not any(c in txt for c in {'\n', '\r', '\u2028', '\u2029'}):
self.find_edit.setCurrentText(cursor.selectedText())
layout.addWidget(self.case_checkbox)
layout.addWidget(self.word_checkbox)
layout.addWidget(QLabel(localizationF("Replace_with_string","Replace with string:")))
layout.addWidget(self.replace_edit)
self.replace_btn = QPushButton(localizationF("Replace","Replace"))
self.replace_all_btn = QPushButton(localizationF("Replace_All", "Replace All"))
layout.addWidget(self.replace_btn)
layout.addWidget(self.replace_all_btn)
self.find_btn_prev.clicked.connect(self.find_prev)
self.find_btn.clicked.connect(self.find_next)
self.replace_btn.clicked.connect(self.replace_one)
self.replace_all_btn.clicked.connect(self.replace_all)
self.find_edit.lineEdit().selectAll()
self.replace_edit.lineEdit().selectAll()
self.selection_start = cursor.selectionStart()
self.selection_end = cursor.selectionEnd()
self.find1 = True
self.find_btn.setDefault(True) # Сделать find_btn активной по умолчанию
def load_history(self):
"""Загружает историю поиска и замены из настроек"""
try:
# Загрузка истории поиска
find_history = mw.pm.profile.get('find_replace_find_history', [])
for item in find_history:
self.find_edit.addItem(item)
# Загрузка истории замены
replace_history = mw.pm.profile.get('find_replace_replace_history', [])
for item in replace_history:
self.replace_edit.addItem(item)
except:
pass
def save_history(self):
"""Сохраняет историю поиска и замены в настройки"""
try:
# Сохраняем историю поиска
find_history = []
for i in range(min(self.find_edit.count(), 20)): # Сохраняем до 20 элементов
find_history.append(self.find_edit.itemText(i))
mw.pm.profile['find_replace_find_history'] = find_history
# Сохраняем историю замены
replace_history = []
for i in range(min(self.replace_edit.count(), 20)):
replace_history.append(self.replace_edit.itemText(i))
mw.pm.profile['find_replace_replace_history'] = replace_history
except:
pass
def add_to_history(self, combo_box, text):
"""Добавляет текст в историю комбобокса"""
if text.strip(): # Не добавляем пустые строки
# Удаляем если уже существует
index = combo_box.findText(text)
if index >= 0:
combo_box.removeItem(index)
# Добавляем в начало
combo_box.insertItem(0, text)
combo_box.setCurrentIndex(0)
def get_flags(self):
if pyqt_version == "PyQt6":
flags = QTextDocument.FindFlag(0)
if self.case_checkbox.isChecked():
flags |= QTextDocument.FindFlag.FindCaseSensitively
if self.word_checkbox.isChecked():
flags |= QTextDocument.FindFlag.FindWholeWords
else:
flags = 0
if self.case_checkbox.isChecked():
flags |= QTextDocument.FindCaseSensitively
if self.word_checkbox.isChecked():
flags |= QTextDocument.FindWholeWords
return flags
def find_prev(self) -> bool:
text = self.find_edit.currentText().strip()
if not text:
return False
# Добавляем в историю
self.add_to_history(self.find_edit, text)
flags = self.get_flags() | FindBackward
cursor = self.editor.textCursor()
if self.selection_checkbox.isChecked() and self.cursor_hasSelection: # Поиск только в выделенном
if self.find1 == True:
self.find1 = False
cursor.setPosition(self.selection_end)
self.editor.setTextCursor(cursor)
found = False
while True:
found = self.editor.find(text, flags)
if not found:
break
c = self.editor.textCursor()
if c.selectionStart() < self.selection_start or c.selectionEnd() > self.selection_end:
cursor = self.editor.textCursor()
cursor.setPosition(self.selection_start)
self.editor.setTextCursor(cursor)
break
# Нашли в выделении
return True
msg = localizationF("Not_found_in_selection", "Not found in selection")
tooltip(f"<p style='color: yellow; background-color: black'>{msg}</p>")
return False
else:
found = self.editor.find(text, flags)
if not found:
msg = localizationF("notfound", "Not found")
tooltip(f"<p style='color: yellow; background-color: black'>{msg}</p>")
return False
return True
def find_next(self) -> bool:
text = self.find_edit.currentText().strip()
if not text:
return False
# Добавляем в историю
self.add_to_history(self.find_edit, text)
flags = self.get_flags()
cursor = self.editor.textCursor()
if self.selection_checkbox.isChecked() and self.cursor_hasSelection: # Поиск только в выделенном
if self.find1 == True:
self.find1 = False
cursor.setPosition(self.selection_start)
self.editor.setTextCursor(cursor)
found = False
while True:
found = self.editor.find(text, flags)
if not found:
break
c = self.editor.textCursor()
if c.selectionStart() < self.selection_start or c.selectionEnd() > self.selection_end:
cursor = self.editor.textCursor()
cursor.setPosition(self.selection_end)
self.editor.setTextCursor(cursor)
break
# Нашли в выделении
return True
msg = localizationF("Not_found_in_selection", "Not found in selection")
tooltip(f"<p style='color: yellow; background-color: black'>{msg}</p>")
return False
else:
found = self.editor.find(text, flags)
if not found:
msg = localizationF("notfound", "Not found")
tooltip(f"<p style='color: yellow; background-color: black'>{msg}</p>")
return False
return True
def replace_one(self) -> bool:
self.find1 = False
text = self.find_edit.currentText().strip()
replace = self.replace_edit.currentText()