File size: 73,110 Bytes
b2fbb41 |
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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 |
import os.path as osp
import os, re, traceback, sys
from typing import List, Union
from pathlib import Path
import subprocess
from functools import partial
import time
import cv2
from tqdm import tqdm
from qtpy.QtWidgets import QAction, QFileDialog, QMenu, QHBoxLayout, QVBoxLayout, QApplication, QStackedWidget, QSplitter, QListWidget, QShortcut, QListWidgetItem, QMessageBox, QTextEdit, QPlainTextEdit
from qtpy.QtCore import Qt, QPoint, QSize, QEvent, Signal
from qtpy.QtGui import QContextMenuEvent, QTextCursor, QGuiApplication, QIcon, QCloseEvent, QKeySequence, QKeyEvent, QPainter, QClipboard, QImage
from utils.logger import logger as LOGGER
from utils.text_processing import is_cjk, full_len, half_len
from utils.textblock import TextBlock, TextAlignment
from utils import shared
from utils.message import create_error_dialog, create_info_dialog
from modules.translators.trans_chatgpt import GPTTranslator
from modules import GET_VALID_TEXTDETECTORS, GET_VALID_INPAINTERS, GET_VALID_TRANSLATORS, GET_VALID_OCR
from .misc import parse_stylesheet, set_html_family, QKEY
from utils.config import ProgramConfig, pcfg, save_config, text_styles, save_text_styles, load_textstyle_from, FontFormat
from utils.proj_imgtrans import ProjImgTrans
from .canvas import Canvas
from .configpanel import ConfigPanel
from .module_manager import ModuleManager
from .textedit_area import SourceTextEdit, SelectTextMiniMenu, TransTextEdit
from .drawingpanel import DrawingPanel
from .scenetext_manager import SceneTextManager, TextPanel, PasteSrcItemsCommand
from .mainwindowbars import TitleBar, LeftBar, BottomBar
from .io_thread import ImgSaveThread, ImportDocThread, ExportDocThread
from .custom_widget import Widget, ViewWidget
from .global_search_widget import GlobalSearchWidget
from .textedit_commands import GlobalRepalceAllCommand
from .framelesswindow import FramelessWindow, FramelessMoveResize
from .drawing_commands import RunBlkTransCommand
from .keywordsubwidget import KeywordSubWidget
from . import shared_widget as SW
from .custom_widget import MessageBox, FrameLessMessageBox, ImgtransProgressMessageBox
class PageListView(QListWidget):
reveal_file = Signal()
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self.setIconSize(QSize(shared.PAGELIST_THUMBNAIL_SIZE, shared.PAGELIST_THUMBNAIL_SIZE))
def contextMenuEvent(self, e: QContextMenuEvent):
menu = QMenu()
reveal_act = menu.addAction(self.tr('Reveal in File Explorer'))
rst = menu.exec_(e.globalPos())
if rst == reveal_act:
self.reveal_file.emit()
return super().contextMenuEvent(e)
mainwindow_cls = Widget if shared.HEADLESS else FramelessWindow
class MainWindow(mainwindow_cls):
imgtrans_proj: ProjImgTrans = ProjImgTrans()
save_on_page_changed = True
opening_dir = False
page_changing = False
postprocess_mt_toggle = True
translator = None
restart_signal = Signal()
create_errdialog = Signal(str, str, str)
create_infodialog = Signal(dict)
def __init__(self, app: QApplication, config: ProgramConfig, open_dir='', **exec_args) -> None:
super().__init__()
shared.create_errdialog_in_mainthread = self.create_errdialog.emit
self.create_errdialog.connect(self.on_create_errdialog)
shared.create_infodialog_in_mainthread = self.create_infodialog.emit
self.create_infodialog.connect(self.on_create_infodialog)
shared.register_view_widget = self.register_view_widget
self.app = app
self.backup_blkstyles = []
self._run_imgtrans_wo_textstyle_update = False
self.setupThread()
self.setupUi()
self.setupConfig()
self.setupShortcuts()
self.setupRegisterWidget()
# self.showMaximized()
FramelessMoveResize.toggleMaxState(self)
self.setAcceptDrops(True)
if open_dir != '' and osp.exists(open_dir):
self.OpenProj(open_dir)
elif pcfg.open_recent_on_startup:
if len(self.leftBar.recent_proj_list) > 0:
proj_dir = self.leftBar.recent_proj_list[0]
if osp.exists(proj_dir):
self.OpenProj(proj_dir)
if shared.HEADLESS:
self.run_batch(**exec_args)
if shared.ON_MACOS:
# https://bugreports.qt.io/browse/QTBUG-133215
self.hideSystemTitleBar()
self.showMaximized()
def setStyleSheet(self, styleSheet: str) -> None:
self.imgtrans_progress_msgbox.setStyleSheet(styleSheet)
self.export_doc_thread.progress_bar.setStyleSheet(styleSheet)
self.import_doc_thread.progress_bar.setStyleSheet(styleSheet)
return super().setStyleSheet(styleSheet)
def setupThread(self):
self.imsave_thread = ImgSaveThread()
self.export_doc_thread = ExportDocThread()
self.export_doc_thread.fin_io.connect(self.on_fin_export_doc)
self.import_doc_thread = ImportDocThread(self)
self.import_doc_thread.fin_io.connect(self.on_fin_import_doc)
def resetStyleSheet(self, reverse_icon: bool = False):
theme = 'eva-dark' if pcfg.darkmode else 'eva-light'
self.setStyleSheet(parse_stylesheet(theme, reverse_icon))
def setupUi(self):
screen_size = QGuiApplication.primaryScreen().geometry().size()
self.setMinimumWidth(screen_size.width() // 2)
self.configPanel = ConfigPanel(self)
self.configPanel.trans_config_panel.show_pre_MT_keyword_window.connect(self.show_pre_MT_keyword_window)
self.configPanel.trans_config_panel.show_MT_keyword_window.connect(self.show_MT_keyword_window)
self.configPanel.trans_config_panel.show_OCR_keyword_window.connect(self.show_OCR_keyword_window)
self.leftBar = LeftBar(self)
self.leftBar.showPageListLabel.clicked.connect(self.pageLabelStateChanged)
self.leftBar.imgTransChecked.connect(self.setupImgTransUI)
self.leftBar.configChecked.connect(self.setupConfigUI)
self.leftBar.globalSearchChecker.clicked.connect(self.on_set_gsearch_widget)
self.leftBar.open_dir.connect(self.OpenProj)
self.leftBar.open_json_proj.connect(self.openJsonProj)
self.leftBar.save_proj.connect(self.manual_save)
self.leftBar.export_doc.connect(self.on_export_doc)
self.leftBar.import_doc.connect(self.on_import_doc)
self.leftBar.export_src_txt.connect(lambda : self.on_export_txt(dump_target='source'))
self.leftBar.export_trans_txt.connect(lambda : self.on_export_txt(dump_target='translation'))
self.leftBar.export_src_md.connect(lambda : self.on_export_txt(dump_target='source', suffix='.md'))
self.leftBar.export_trans_md.connect(lambda : self.on_export_txt(dump_target='translation', suffix='.md'))
self.leftBar.import_trans_txt.connect(self.on_import_trans_txt)
self.pageList = PageListView()
self.pageList.reveal_file.connect(self.on_reveal_file)
self.pageList.setHidden(True)
self.pageList.currentItemChanged.connect(self.pageListCurrentItemChanged)
self.leftStackWidget = QStackedWidget(self)
self.leftStackWidget.addWidget(self.pageList)
self.global_search_widget = GlobalSearchWidget(self.leftStackWidget)
self.global_search_widget.req_update_pagetext.connect(self.on_req_update_pagetext)
self.global_search_widget.req_move_page.connect(self.on_req_move_page)
self.imsave_thread.img_writed.connect(self.global_search_widget.on_img_writed)
self.global_search_widget.search_tree.result_item_clicked.connect(self.on_search_result_item_clicked)
self.leftStackWidget.addWidget(self.global_search_widget)
self.centralStackWidget = QStackedWidget(self)
self.titleBar = TitleBar(self)
self.titleBar.closebtn_clicked.connect(self.on_closebtn_clicked)
self.titleBar.display_lang_changed.connect(self.on_display_lang_changed)
self.bottomBar = BottomBar(self)
self.bottomBar.textedit_checkchanged.connect(self.setTextEditMode)
self.bottomBar.paintmode_checkchanged.connect(self.setPaintMode)
self.bottomBar.textblock_checkchanged.connect(self.setTextBlockMode)
mainHLayout = QHBoxLayout()
mainHLayout.addWidget(self.leftBar)
mainHLayout.addWidget(self.centralStackWidget)
mainHLayout.setContentsMargins(0, 0, 0, 0)
mainHLayout.setSpacing(0)
# set up canvas
SW.canvas = self.canvas = Canvas()
self.canvas.imgtrans_proj = self.imgtrans_proj
self.canvas.gv.hide_canvas.connect(self.onHideCanvas)
self.canvas.proj_savestate_changed.connect(self.on_savestate_changed)
self.canvas.textstack_changed.connect(self.on_textstack_changed)
self.canvas.run_blktrans.connect(self.on_run_blktrans)
self.canvas.drop_open_folder.connect(self.dropOpenDir)
self.canvas.originallayer_trans_slider = self.bottomBar.originalSlider
self.canvas.textlayer_trans_slider = self.bottomBar.textlayerSlider
self.canvas.copy_src_signal.connect(self.on_copy_src)
self.canvas.paste_src_signal.connect(self.on_paste_src)
self.bottomBar.originalSlider.valueChanged.connect(self.canvas.setOriginalTransparencyBySlider)
self.bottomBar.textlayerSlider.valueChanged.connect(self.canvas.setTextLayerTransparencyBySlider)
self.drawingPanel = DrawingPanel(self.canvas, self.configPanel.inpaint_config_panel)
self.textPanel = TextPanel(self.app)
self.textPanel.formatpanel.foldTextBtn.checkStateChanged.connect(self.fold_textarea)
self.textPanel.formatpanel.sourceBtn.checkStateChanged.connect(self.show_source_text)
self.textPanel.formatpanel.transBtn.checkStateChanged.connect(self.show_trans_text)
self.textPanel.formatpanel.textstyle_panel.export_style.connect(self.export_tstyles)
self.textPanel.formatpanel.textstyle_panel.import_style.connect(self.import_tstyles)
self.ocrSubWidget = KeywordSubWidget(self.tr("Keyword substitution for source text"))
self.ocrSubWidget.setParent(self)
self.ocrSubWidget.setWindowFlags(Qt.WindowType.Window)
self.ocrSubWidget.hide()
self.mtPreSubWidget = KeywordSubWidget(self.tr("Keyword substitution for machine translation source text"))
self.mtPreSubWidget.setParent(self)
self.mtPreSubWidget.setWindowFlags(Qt.WindowType.Window)
self.mtPreSubWidget.hide()
self.mtSubWidget = KeywordSubWidget(self.tr("Keyword substitution for machine translation"))
self.mtSubWidget.setParent(self)
self.mtSubWidget.setWindowFlags(Qt.WindowType.Window)
self.mtSubWidget.hide()
SW.st_manager = self.st_manager = SceneTextManager(self.app, self, self.canvas, self.textPanel)
self.st_manager.new_textblk.connect(self.canvas.search_widget.on_new_textblk)
self.canvas.search_widget.pairwidget_list = self.st_manager.pairwidget_list
self.canvas.search_widget.textblk_item_list = self.st_manager.textblk_item_list
self.canvas.search_widget.replace_one.connect(self.st_manager.on_page_replace_one)
self.canvas.search_widget.replace_all.connect(self.st_manager.on_page_replace_all)
# comic trans pannel
self.rightComicTransStackPanel = QStackedWidget(self)
self.rightComicTransStackPanel.addWidget(self.drawingPanel)
self.rightComicTransStackPanel.addWidget(self.textPanel)
self.rightComicTransStackPanel.currentChanged.connect(self.on_transpanel_changed)
self.comicTransSplitter = QSplitter(Qt.Orientation.Horizontal)
self.comicTransSplitter.addWidget(self.leftStackWidget)
self.comicTransSplitter.addWidget(self.canvas.gv)
self.comicTransSplitter.addWidget(self.rightComicTransStackPanel)
self.centralStackWidget.addWidget(self.comicTransSplitter)
self.centralStackWidget.addWidget(self.configPanel)
self.selectext_minimenu = self.st_manager.selectext_minimenu = SelectTextMiniMenu(self.app, self)
self.selectext_minimenu.block_current_editor.connect(self.st_manager.on_block_current_editor)
self.selectext_minimenu.hide()
mainVBoxLayout = QVBoxLayout(self)
mainVBoxLayout.addWidget(self.titleBar)
mainVBoxLayout.addLayout(mainHLayout)
mainVBoxLayout.addWidget(self.bottomBar)
margin = mainVBoxLayout.contentsMargins()
self.main_margin = margin
mainVBoxLayout.setContentsMargins(0, 0, 0, 0)
mainVBoxLayout.setSpacing(0)
self.mainvlayout = mainVBoxLayout
self.comicTransSplitter.setStretchFactor(0, 1)
self.comicTransSplitter.setStretchFactor(1, 10)
self.comicTransSplitter.setStretchFactor(2, 1)
self.imgtrans_progress_msgbox = ImgtransProgressMessageBox()
self.resetStyleSheet()
def on_finish_setdetector(self):
module_manager = self.module_manager
if module_manager.textdetector is not None:
name = module_manager.textdetector.name
pcfg.module.textdetector = name
self.configPanel.detect_config_panel.setDetector(name)
self.bottomBar.textdet_selector.setSelectedValue(name)
LOGGER.info('Text detector set to {}'.format(name))
def on_finish_setocr(self):
module_manager = self.module_manager
if module_manager.ocr is not None:
name = module_manager.ocr.name
pcfg.module.ocr = name
self.configPanel.ocr_config_panel.setOCR(name)
self.bottomBar.ocr_selector.setSelectedValue(name)
LOGGER.info('OCR set to {}'.format(name))
def on_finish_setinpainter(self):
module_manager = self.module_manager
if module_manager.inpainter is not None:
name = module_manager.inpainter.name
pcfg.module.inpainter = name
self.configPanel.inpaint_config_panel.setInpainter(name)
self.bottomBar.inpaint_selector.setSelectedValue(name)
LOGGER.info('Inpainter set to {}'.format(name))
def on_finish_settranslator(self):
module_manager = self.module_manager
translator = module_manager.translator
if translator is not None:
name = translator.name
pcfg.module.translator = name
self.bottomBar.trans_selector.finishSetTranslator(translator)
self.configPanel.trans_config_panel.finishSetTranslator(translator)
LOGGER.info('Translator set to {}'.format(name))
else:
LOGGER.error('invalid translator')
def on_enable_module(self, idx, checked):
if idx == 0:
pcfg.module.enable_detect = checked
self.bottomBar.textdet_selector.setVisible(checked)
elif idx == 1:
pcfg.module.enable_ocr = checked
self.bottomBar.ocr_selector.setVisible(checked)
elif idx == 2:
pcfg.module.enable_translate = checked
self.bottomBar.trans_selector.setVisible(checked)
elif idx == 3:
pcfg.module.enable_inpaint = checked
self.bottomBar.inpaint_selector.setVisible(checked)
def setupConfig(self):
self.bottomBar.originalSlider.setValue(int(pcfg.original_transparency * 100))
self.bottomBar.trans_selector.selector.addItems(GET_VALID_TRANSLATORS())
self.bottomBar.ocr_selector.selector.addItems(GET_VALID_OCR())
self.bottomBar.textdet_selector.selector.addItems(GET_VALID_TEXTDETECTORS())
self.bottomBar.textdet_selector.selector.currentTextChanged.connect(self.on_textdet_changed)
self.bottomBar.inpaint_selector.selector.addItems(GET_VALID_INPAINTERS())
self.bottomBar.inpaint_selector.selector.currentTextChanged.connect(self.on_inpaint_changed)
self.bottomBar.trans_selector.cfg_clicked.connect(self.to_trans_config)
self.bottomBar.trans_selector.selector.currentTextChanged.connect(self.on_trans_changed)
self.bottomBar.trans_selector.tgt_selector.currentTextChanged.connect(self.on_trans_tgt_changed)
self.bottomBar.trans_selector.src_selector.currentTextChanged.connect(self.on_trans_src_changed)
self.bottomBar.textdet_selector.cfg_clicked.connect(self.to_detect_config)
self.bottomBar.inpaint_selector.cfg_clicked.connect(self.to_inpaint_config)
self.bottomBar.ocr_selector.cfg_clicked.connect(self.to_ocr_config)
self.bottomBar.ocr_selector.selector.currentTextChanged.connect(self.on_ocr_changed)
self.bottomBar.textdet_selector.setVisible(pcfg.module.enable_detect)
self.bottomBar.ocr_selector.setVisible(pcfg.module.enable_ocr)
self.bottomBar.trans_selector.setVisible(pcfg.module.enable_translate)
self.bottomBar.inpaint_selector.setVisible(pcfg.module.enable_inpaint)
self.configPanel.trans_config_panel.target_combobox.currentTextChanged.connect(self.on_trans_tgt_changed)
self.configPanel.trans_config_panel.source_combobox.currentTextChanged.connect(self.on_trans_src_changed)
self.drawingPanel.maskTransperancySlider.setValue(int(pcfg.mask_transparency * 100))
self.leftBar.initRecentProjMenu(pcfg.recent_proj_list)
self.leftBar.showPageListLabel.setChecked(pcfg.show_page_list)
self.updatePageList()
self.leftBar.save_config.connect(self.save_config)
self.leftBar.imgTransChecker.setChecked(True)
self.st_manager.formatpanel.global_format = pcfg.global_fontformat
self.st_manager.formatpanel.set_active_format(pcfg.global_fontformat)
self.rightComicTransStackPanel.setHidden(True)
self.st_manager.setTextEditMode(False)
self.st_manager.formatpanel.foldTextBtn.setChecked(pcfg.fold_textarea)
self.st_manager.formatpanel.transBtn.setCheckState(pcfg.show_trans_text)
self.st_manager.formatpanel.sourceBtn.setCheckState(pcfg.show_source_text)
self.fold_textarea(pcfg.fold_textarea)
self.show_trans_text(pcfg.show_trans_text)
self.show_source_text(pcfg.show_source_text)
self.module_manager = module_manager = ModuleManager(self.imgtrans_proj)
module_manager.finish_translate_page.connect(self.finishTranslatePage)
module_manager.imgtrans_pipeline_finished.connect(self.on_imgtrans_pipeline_finished)
module_manager.page_trans_finished.connect(self.on_pagtrans_finished)
module_manager.setupThread(self.configPanel, self.imgtrans_progress_msgbox, self.ocr_postprocess, self.translate_preprocess, self.translate_postprocess)
module_manager.progress_msgbox.showed.connect(self.on_imgtrans_progressbox_showed)
module_manager.blktrans_pipeline_finished.connect(self.on_blktrans_finished)
module_manager.imgtrans_thread.post_process_mask = self.drawingPanel.rectPanel.post_process_mask
module_manager.inpaint_thread.finish_set_module.connect(self.on_finish_setinpainter)
module_manager.translate_thread.finish_set_module.connect(self.on_finish_settranslator)
module_manager.textdetect_thread.finish_set_module.connect(self.on_finish_setdetector)
module_manager.ocr_thread.finish_set_module.connect(self.on_finish_setocr)
module_manager.setTextDetector()
module_manager.setOCR()
module_manager.setTranslator()
module_manager.setInpainter()
self.leftBar.run_imgtrans_clicked.connect(self.run_imgtrans)
self.titleBar.darkModeAction.setChecked(pcfg.darkmode)
self.drawingPanel.set_config(pcfg.drawpanel)
self.drawingPanel.initDLModule(module_manager)
self.global_search_widget.imgtrans_proj = self.imgtrans_proj
self.global_search_widget.setupReplaceThread(self.st_manager.pairwidget_list, self.st_manager.textblk_item_list)
self.global_search_widget.replace_thread.finished.connect(self.on_global_replace_finished)
self.configPanel.setupConfig()
self.configPanel.save_config.connect(self.save_config)
self.configPanel.reload_textstyle.connect(self.load_textstyle_from_proj_dir)
self.configPanel.show_only_custom_font.connect(self.on_show_only_custom_font)
if pcfg.let_show_only_custom_fonts_flag:
self.on_show_only_custom_font(True)
textblock_mode = pcfg.imgtrans_textblock
if pcfg.imgtrans_textedit:
if textblock_mode:
self.bottomBar.textblockChecker.setChecked(True)
self.bottomBar.texteditChecker.click()
elif pcfg.imgtrans_paintmode:
self.bottomBar.paintChecker.click()
self.textPanel.formatpanel.textstyle_panel.initStyles(text_styles)
self.canvas.search_widget.whole_word_toggle.setChecked(pcfg.fsearch_whole_word)
self.canvas.search_widget.case_sensitive_toggle.setChecked(pcfg.fsearch_case)
self.canvas.search_widget.regex_toggle.setChecked(pcfg.fsearch_regex)
self.canvas.search_widget.range_combobox.setCurrentIndex(pcfg.fsearch_range)
self.global_search_widget.whole_word_toggle.setChecked(pcfg.gsearch_whole_word)
self.global_search_widget.case_sensitive_toggle.setChecked(pcfg.gsearch_case)
self.global_search_widget.regex_toggle.setChecked(pcfg.gsearch_regex)
self.global_search_widget.range_combobox.setCurrentIndex(pcfg.gsearch_range)
if self.rightComicTransStackPanel.isHidden():
self.setPaintMode()
try:
self.ocrSubWidget.loadCfgSublist(pcfg.ocr_sublist)
except Exception as e:
LOGGER.error(traceback.format_exc())
pcfg.ocr_sublist = []
self.ocrSubWidget.loadCfgSublist(pcfg.ocr_sublist)
try:
self.mtPreSubWidget.loadCfgSublist(pcfg.pre_mt_sublist)
except Exception as e:
LOGGER.error(traceback.format_exc())
pcfg.pre_mt_sublist = []
self.mtPreSubWidget.loadCfgSublist(pcfg.pre_mt_sublist)
try:
self.mtSubWidget.loadCfgSublist(pcfg.mt_sublist)
except Exception as e:
LOGGER.error(traceback.format_exc())
pcfg.mt_sublist = []
self.mtSubWidget.loadCfgSublist(pcfg.mt_sublist)
def setupImgTransUI(self):
self.centralStackWidget.setCurrentIndex(0)
if self.leftBar.needleftStackWidget():
self.leftStackWidget.show()
else:
self.leftStackWidget.hide()
def setupConfigUI(self):
self.centralStackWidget.setCurrentIndex(1)
def set_display_lang(self, lang: str):
self.retranslateUI()
def OpenProj(self, proj_path: str):
if osp.isdir(proj_path):
self.openDir(proj_path)
else:
self.openJsonProj(proj_path)
if pcfg.let_textstyle_indep_flag and not shared.HEADLESS:
self.load_textstyle_from_proj_dir(from_proj=True)
def load_textstyle_from_proj_dir(self, from_proj=False):
if from_proj:
text_style_path = osp.join(self.imgtrans_proj.directory, 'textstyles.json')
else:
text_style_path = 'config/textstyles/default.json'
if osp.exists(text_style_path):
load_textstyle_from(text_style_path)
self.textPanel.formatpanel.textstyle_panel.setStyles(text_styles)
else:
pcfg.text_styles_path = text_style_path
save_text_styles()
def on_show_only_custom_font(self, only_custom: bool):
if only_custom:
font_list = shared.CUSTOM_FONTS
else:
font_list = shared.FONT_FAMILIES
self.textPanel.formatpanel.familybox.update_font_list(font_list)
def openDir(self, directory: str):
try:
self.opening_dir = True
self.imgtrans_proj.load(directory)
self.st_manager.clearSceneTextitems()
self.titleBar.setTitleContent(osp.basename(directory))
self.updatePageList()
self.opening_dir = False
except Exception as e:
self.opening_dir = False
create_error_dialog(e, self.tr('Failed to load project ') + directory)
return
def dropOpenDir(self, directory: str):
if isinstance(directory, str) and osp.exists(directory):
self.leftBar.updateRecentProjList(directory)
self.OpenProj(directory)
def openJsonProj(self, json_path: str):
try:
self.opening_dir = True
self.imgtrans_proj.load_from_json(json_path)
self.st_manager.clearSceneTextitems()
self.leftBar.updateRecentProjList(self.imgtrans_proj.proj_path)
self.updatePageList()
self.titleBar.setTitleContent(osp.basename(self.imgtrans_proj.proj_path))
self.opening_dir = False
except Exception as e:
self.opening_dir = False
create_error_dialog(e, self.tr('Failed to load project from') + json_path)
def updatePageList(self):
if self.pageList.count() != 0:
self.pageList.clear()
if len(self.imgtrans_proj.pages) >= shared.PAGELIST_THUMBNAIL_MAXNUM:
item_func = lambda imgname: QListWidgetItem(imgname)
else:
item_func = lambda imgname:\
QListWidgetItem(QIcon(osp.join(self.imgtrans_proj.directory, imgname)), imgname)
for imgname in self.imgtrans_proj.pages:
lstitem = item_func(imgname)
self.pageList.addItem(lstitem)
if imgname == self.imgtrans_proj.current_img:
self.pageList.setCurrentItem(lstitem)
def pageLabelStateChanged(self):
setup = self.leftBar.showPageListLabel.isChecked()
if setup:
if self.leftStackWidget.isHidden():
self.leftStackWidget.show()
if self.leftBar.globalSearchChecker.isChecked():
self.leftBar.globalSearchChecker.setChecked(False)
self.leftStackWidget.setCurrentWidget(self.pageList)
else:
self.leftStackWidget.hide()
pcfg.show_page_list = setup
save_config()
def closeEvent(self, event: QCloseEvent) -> None:
if not self.imgtrans_proj.is_empty:
self.conditional_save(keep_exist_as_backup=True)
while True:
if not self.imsave_thread.isRunning():
break
time.sleep(0.1)
self.st_manager.hovering_transwidget = None
self.st_manager.blockSignals(True)
self.canvas.prepareClose()
self.save_config()
return super().closeEvent(event)
def changeEvent(self, event: QEvent):
if event.type() == QEvent.Type.WindowStateChange:
if self.windowState() & Qt.WindowState.WindowMaximized:
if not shared.ON_MACOS:
self.titleBar.maxBtn.setChecked(True)
elif event.type() == QEvent.Type.ActivationChange:
self.canvas.on_activation_changed()
super().changeEvent(event)
def retranslateUI(self):
# according to https://stackoverflow.com/questions/27635068/how-to-retranslate-dynamically-created-widgets
# we got to do it manually ... I'd rather restart the program
msg = QMessageBox()
msg.setText(self.tr('Restart to apply changes? \n'))
msg.setStandardButtons(QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No)
ret = msg.exec_()
if ret == QMessageBox.StandardButton.Yes:
self.restart_signal.emit()
def save_config(self):
save_config()
def onHideCanvas(self):
self.canvas.clearToolStates()
def conditional_save(self, keep_exist_as_backup=False):
if self.canvas.projstate_unsaved and not self.opening_dir:
update_scene_text = save_proj = self.canvas.text_change_unsaved()
save_rst_only = not self.canvas.draw_change_unsaved()
if not save_rst_only:
save_proj = True
self.saveCurrentPage(update_scene_text, save_proj, restore_interface=True, save_rst_only=save_rst_only, keep_exist_as_backup=keep_exist_as_backup)
def pageListCurrentItemChanged(self):
item = self.pageList.currentItem()
self.page_changing = True
if item is not None:
if self.save_on_page_changed:
self.conditional_save()
self.imgtrans_proj.set_current_img(item.text())
self.canvas.clear_undostack(update_saved_step=True)
self.canvas.updateCanvas()
self.st_manager.updateSceneTextitems()
self.titleBar.setTitleContent(page_name=self.imgtrans_proj.current_img)
self.module_manager.handle_page_changed()
self.drawingPanel.handle_page_changed()
self.page_changing = False
def setupShortcuts(self):
self.titleBar.nextpage_trigger.connect(self.shortcutNext)
self.titleBar.prevpage_trigger.connect(self.shortcutBefore)
self.titleBar.textedit_trigger.connect(self.shortcutTextedit)
self.titleBar.drawboard_trigger.connect(self.shortcutDrawboard)
self.titleBar.redo_trigger.connect(self.on_redo)
self.titleBar.undo_trigger.connect(self.on_undo)
self.titleBar.page_search_trigger.connect(self.on_page_search)
self.titleBar.global_search_trigger.connect(self.on_global_search)
self.titleBar.replacePreMTkeyword_trigger.connect(self.show_pre_MT_keyword_window)
self.titleBar.replaceMTkeyword_trigger.connect(self.show_MT_keyword_window)
self.titleBar.replaceOCRkeyword_trigger.connect(self.show_OCR_keyword_window)
self.titleBar.run_trigger.connect(self.leftBar.runImgtransBtn.click)
self.titleBar.run_woupdate_textstyle_trigger.connect(self.run_imgtrans_wo_textstyle_update)
self.titleBar.translate_page_trigger.connect(self.on_transpagebtn_pressed)
self.titleBar.enable_module.connect(self.on_enable_module)
self.titleBar.importtstyle_trigger.connect(self.import_tstyles)
self.titleBar.exporttstyle_trigger.connect(self.export_tstyles)
self.titleBar.darkmode_trigger.connect(self.on_darkmode_triggered)
shortcutA = QShortcut(QKeySequence("A"), self)
shortcutA.activated.connect(self.shortcutBefore)
shortcutPageUp = QShortcut(QKeySequence(QKeySequence.StandardKey.MoveToPreviousPage), self)
shortcutPageUp.activated.connect(self.shortcutBefore)
shortcutD = QShortcut(QKeySequence("D"), self)
shortcutD.activated.connect(self.shortcutNext)
shortcutPageDown = QShortcut(QKeySequence(QKeySequence.StandardKey.MoveToNextPage), self)
shortcutPageDown.activated.connect(self.shortcutNext)
shortcutTextblock = QShortcut(QKeySequence("W"), self)
shortcutTextblock.activated.connect(self.shortcutTextblock)
shortcutZoomIn = QShortcut(QKeySequence.StandardKey.ZoomIn, self)
shortcutZoomIn.activated.connect(self.canvas.gv.scale_up_signal)
shortcutZoomOut = QShortcut(QKeySequence.StandardKey.ZoomOut, self)
shortcutZoomOut.activated.connect(self.canvas.gv.scale_down_signal)
shortcutCtrlD = QShortcut(QKeySequence("Ctrl+D"), self)
shortcutCtrlD.activated.connect(self.shortcutCtrlD)
shortcutSpace = QShortcut(QKeySequence("Space"), self)
shortcutSpace.activated.connect(self.shortcutSpace)
shortcutSelectAll = QShortcut(QKeySequence.StandardKey.SelectAll, self)
shortcutSelectAll.activated.connect(self.shortcutSelectAll)
shortcutEscape = QShortcut(QKeySequence("Escape"), self)
shortcutEscape.activated.connect(self.shortcutEscape)
shortcutBold = QShortcut(QKeySequence.StandardKey.Bold, self)
shortcutBold.activated.connect(self.shortcutBold)
shortcutItalic = QShortcut(QKeySequence.StandardKey.Italic, self)
shortcutItalic.activated.connect(self.shortcutItalic)
shortcutUnderline = QShortcut(QKeySequence.StandardKey.Underline, self)
shortcutUnderline.activated.connect(self.shortcutUnderline)
shortcutDelete = QShortcut(QKeySequence.StandardKey.Delete, self)
shortcutDelete.activated.connect(self.shortcutDelete)
drawpanel_shortcuts = {'hand': 'H', 'rect': 'R', 'inpaint': 'J', 'pen': 'B'}
for tool_name, shortcut_key in drawpanel_shortcuts.items():
shortcut = QShortcut(QKeySequence(shortcut_key), self)
shortcut.activated.connect(partial(self.drawingPanel.shortcutSetCurrentToolByName, tool_name))
self.drawingPanel.setShortcutTip(tool_name, shortcut_key)
def shortcutNext(self):
sender: QShortcut = self.sender()
if isinstance(sender, QShortcut):
if sender.key() == QKEY.Key_D:
if self.canvas.editing_textblkitem is not None:
return
if self.centralStackWidget.currentIndex() == 0:
focus_widget = self.app.focusWidget()
if self.st_manager.is_editting():
self.st_manager.on_switch_textitem(1)
elif isinstance(focus_widget, (SourceTextEdit, TransTextEdit)):
self.st_manager.on_switch_textitem(1, current_editing_widget=focus_widget)
else:
index = self.pageList.currentIndex()
page_count = self.pageList.count()
if index.isValid():
row = index.row()
row = (row + 1) % page_count
self.pageList.setCurrentRow(row)
def shortcutBefore(self):
sender: QShortcut = self.sender()
if isinstance(sender, QShortcut):
if sender.key() == QKEY.Key_A:
if self.canvas.editing_textblkitem is not None:
return
if self.centralStackWidget.currentIndex() == 0:
focus_widget = self.app.focusWidget()
if self.st_manager.is_editting():
self.st_manager.on_switch_textitem(-1)
elif isinstance(focus_widget, (SourceTextEdit, TransTextEdit)):
self.st_manager.on_switch_textitem(-1, current_editing_widget=focus_widget)
else:
index = self.pageList.currentIndex()
page_count = self.pageList.count()
if index.isValid():
row = index.row()
row = (row - 1 + page_count) % page_count
self.pageList.setCurrentRow(row)
def shortcutTextedit(self):
if self.centralStackWidget.currentIndex() == 0:
self.bottomBar.texteditChecker.click()
def shortcutTextblock(self):
if self.centralStackWidget.currentIndex() == 0:
if self.bottomBar.texteditChecker.isChecked():
self.bottomBar.textblockChecker.click()
def shortcutDrawboard(self):
if self.centralStackWidget.currentIndex() == 0:
self.bottomBar.paintChecker.click()
def shortcutCtrlD(self):
if self.centralStackWidget.currentIndex() == 0:
if self.drawingPanel.isVisible():
if self.drawingPanel.currentTool == self.drawingPanel.rectTool:
self.drawingPanel.rectPanel.delete_btn.click()
elif self.canvas.textEditMode():
self.canvas.delete_textblks.emit(0)
def shortcutSelectAll(self):
if self.centralStackWidget.currentIndex() == 0:
if self.textPanel.isVisible():
self.st_manager.set_blkitems_selection(True)
def shortcutSpace(self):
if self.centralStackWidget.currentIndex() == 0:
if self.drawingPanel.isVisible():
if self.drawingPanel.currentTool == self.drawingPanel.rectTool:
self.drawingPanel.rectPanel.inpaint_btn.click()
def shortcutBold(self):
if self.textPanel.formatpanel.isVisible():
self.textPanel.formatpanel.formatBtnGroup.boldBtn.click()
def shortcutDelete(self):
if self.canvas.gv.isVisible():
self.canvas.delete_textblks.emit(1)
def shortcutItalic(self):
if self.textPanel.formatpanel.isVisible():
self.textPanel.formatpanel.formatBtnGroup.italicBtn.click()
def shortcutUnderline(self):
if self.textPanel.formatpanel.isVisible():
self.textPanel.formatpanel.formatBtnGroup.underlineBtn.click()
def on_redo(self):
self.canvas.redo()
def on_undo(self):
self.canvas.undo()
def on_page_search(self):
if self.canvas.gv.isVisible():
fo = self.app.focusObject()
sel_text = ''
tgt_edit = None
blkitem = self.canvas.editing_textblkitem
if fo == self.canvas.gv and blkitem is not None:
sel_text = blkitem.textCursor().selectedText()
tgt_edit = self.st_manager.pairwidget_list[blkitem.idx].e_trans
elif isinstance(fo, QTextEdit) or isinstance(fo, QPlainTextEdit):
sel_text = fo.textCursor().selectedText()
if isinstance(fo, SourceTextEdit):
tgt_edit = fo
se = self.canvas.search_widget.search_editor
se.setFocus()
if sel_text != '':
se.setPlainText(sel_text)
cursor = se.textCursor()
cursor.select(QTextCursor.SelectionType.Document)
se.setTextCursor(cursor)
if self.canvas.search_widget.isHidden():
self.canvas.search_widget.show()
self.canvas.search_widget.setCurrentEditor(tgt_edit)
def on_global_search(self):
if self.canvas.gv.isVisible():
if not self.leftBar.globalSearchChecker.isChecked():
self.leftBar.globalSearchChecker.click()
fo = self.app.focusObject()
sel_text = ''
blkitem = self.canvas.editing_textblkitem
if fo == self.canvas.gv and blkitem is not None:
sel_text = blkitem.textCursor().selectedText()
elif isinstance(fo, QTextEdit) or isinstance(fo, QPlainTextEdit):
sel_text = fo.textCursor().selectedText()
se = self.global_search_widget.search_editor
se.setFocus()
if sel_text != '':
se.setPlainText(sel_text)
cursor = se.textCursor()
cursor.select(QTextCursor.SelectionType.Document)
se.setTextCursor(cursor)
self.global_search_widget.commit_search()
def show_pre_MT_keyword_window(self):
self.mtPreSubWidget.show()
def show_MT_keyword_window(self):
self.mtSubWidget.show()
def show_OCR_keyword_window(self):
self.ocrSubWidget.show()
def on_req_update_pagetext(self):
if self.canvas.text_change_unsaved():
self.st_manager.updateTextBlkList()
def on_req_move_page(self, page_name: str, force_save=False):
ori_save = self.save_on_page_changed
self.save_on_page_changed = False
current_img = self.imgtrans_proj.current_img
if current_img == page_name and not force_save:
return
if current_img not in self.global_search_widget.page_set:
if self.canvas.projstate_unsaved:
self.saveCurrentPage()
else:
self.saveCurrentPage(save_rst_only=True)
self.pageList.setCurrentRow(self.imgtrans_proj.pagename2idx(page_name))
self.save_on_page_changed = ori_save
def on_search_result_item_clicked(self, pagename: str, blk_idx: int, is_src: bool, start: int, end: int):
idx = self.imgtrans_proj.pagename2idx(pagename)
self.pageList.setCurrentRow(idx)
pw = self.st_manager.pairwidget_list[blk_idx]
edit = pw.e_source if is_src else pw.e_trans
edit.setFocus()
edit.ensure_scene_visible.emit()
cursor = QTextCursor(edit.document())
cursor.setPosition(start)
cursor.setPosition(end, QTextCursor.MoveMode.KeepAnchor)
edit.setTextCursor(cursor)
def shortcutEscape(self):
if self.canvas.search_widget.isVisible():
self.canvas.search_widget.hide()
elif self.canvas.editing_textblkitem is not None and self.canvas.editing_textblkitem.isEditing():
self.canvas.editing_textblkitem.endEdit()
def setPaintMode(self):
if self.bottomBar.paintChecker.isChecked():
if self.rightComicTransStackPanel.isHidden():
self.rightComicTransStackPanel.show()
self.rightComicTransStackPanel.setCurrentIndex(0)
self.canvas.setPaintMode(True)
self.bottomBar.originalSlider.show()
self.bottomBar.textlayerSlider.show()
self.bottomBar.textblockChecker.hide()
else:
self.canvas.setPaintMode(False)
self.rightComicTransStackPanel.setHidden(True)
self.st_manager.setTextEditMode(False)
def setTextEditMode(self):
if self.bottomBar.texteditChecker.isChecked():
if self.rightComicTransStackPanel.isHidden():
self.rightComicTransStackPanel.show()
self.bottomBar.textblockChecker.show()
self.rightComicTransStackPanel.setCurrentIndex(1)
self.st_manager.setTextEditMode(True)
self.setTextBlockMode()
else:
self.bottomBar.textblockChecker.hide()
self.rightComicTransStackPanel.setHidden(True)
self.st_manager.setTextEditMode(False)
self.canvas.setPaintMode(False)
def setTextBlockMode(self):
mode = self.bottomBar.textblockChecker.isChecked()
self.canvas.setTextBlockMode(mode)
pcfg.imgtrans_textblock = mode
self.st_manager.showTextblkItemRect(mode)
def manual_save(self):
if self.leftBar.imgTransChecker.isChecked()\
and self.imgtrans_proj.directory is not None:
LOGGER.debug('Manually saving...')
self.saveCurrentPage(update_scene_text=True, save_proj=True, restore_interface=True, save_rst_only=False)
def saveCurrentPage(self, update_scene_text=True, save_proj=True, restore_interface=False, save_rst_only=False, keep_exist_as_backup=False):
if not self.imgtrans_proj.img_valid:
return
if restore_interface:
set_canvas_focus = self.canvas.hasFocus()
sel_textitem = self.canvas.selected_text_items()
n_sel_textitems = len(sel_textitem)
editing_textitem = None
if n_sel_textitems == 1 and sel_textitem[0].isEditing():
editing_textitem = sel_textitem[0]
if update_scene_text:
self.st_manager.updateTextBlkList()
if self.rightComicTransStackPanel.isHidden():
self.bottomBar.texteditChecker.click()
restore_textblock_mode = False
if pcfg.imgtrans_textblock:
restore_textblock_mode = True
self.bottomBar.textblockChecker.click()
hide_tsc = False
if self.st_manager.txtblkShapeControl.isVisible():
hide_tsc = True
self.st_manager.txtblkShapeControl.hide()
if not osp.exists(self.imgtrans_proj.result_dir()):
os.makedirs(self.imgtrans_proj.result_dir())
if save_proj:
try:
self.imgtrans_proj.save(keep_exist_as_backup=keep_exist_as_backup)
if not save_rst_only:
mask_path = self.imgtrans_proj.get_mask_path()
mask_array = self.imgtrans_proj.mask_array
if mask_array is not None:
self.imsave_thread.saveImg(mask_path, mask_array, save_params={'ext': pcfg.intermediate_imgsave_ext})
inpainted_path = self.imgtrans_proj.get_inpainted_path()
if self.canvas.drawingLayer.drawed():
inpainted = self.canvas.base_pixmap.copy()
painter = QPainter(inpainted)
painter.drawPixmap(0, 0, self.canvas.drawingLayer.get_drawed_pixmap())
painter.end()
else:
inpainted = self.imgtrans_proj.inpainted_array
if inpainted is not None:
self.imsave_thread.saveImg(inpainted_path, inpainted, save_params={'ext': pcfg.intermediate_imgsave_ext}, keep_alpha=self.imgtrans_proj.current_has_alpha())
except Exception as e:
LOGGER.error(f"Failed to save project files: {e}")
# Render the final result image properly
try:
img = self.canvas.render_result_img()
imsave_path = self.imgtrans_proj.get_result_path(self.imgtrans_proj.current_img)
self.imsave_thread.saveImg(imsave_path, img, self.imgtrans_proj.current_img, save_params={'ext': pcfg.imgsave_ext, 'quality': pcfg.imgsave_quality}, keep_alpha=self.imgtrans_proj.current_has_alpha())
except Exception as e:
LOGGER.error(f"Failed to render and save result image: {e}")
self.canvas.setProjSaveState(False)
self.canvas.update_saved_undostep()
if restore_interface:
if restore_textblock_mode:
self.bottomBar.textblockChecker.click()
if hide_tsc:
self.st_manager.txtblkShapeControl.show()
if set_canvas_focus:
self.canvas.setFocus()
if n_sel_textitems > 0:
self.canvas.block_selection_signal = True
for blk in sel_textitem:
blk.setSelected(True)
self.st_manager.on_incanvas_selection_changed()
self.canvas.block_selection_signal = False
if editing_textitem is not None:
editing_textitem.startEdit()
def to_trans_config(self):
self.leftBar.configChecker.setChecked(True)
self.configPanel.focusOnTranslator()
def to_inpaint_config(self):
self.leftBar.configChecker.setChecked(True)
self.configPanel.focusOnInpaint()
def to_ocr_config(self):
self.leftBar.configChecker.setChecked(True)
self.configPanel.focusOnOCR()
def to_detect_config(self):
self.leftBar.configChecker.setChecked(True)
self.configPanel.focusOnDetect()
def on_textdet_changed(self):
module = self.bottomBar.textdet_selector.selector.currentText()
tgt_selector = self.configPanel.detect_config_panel.module_combobox
if tgt_selector.currentText() != module and module in GET_VALID_TEXTDETECTORS():
tgt_selector.setCurrentText(module)
def on_ocr_changed(self):
module = self.bottomBar.ocr_selector.selector.currentText()
tgt_selector = self.configPanel.ocr_config_panel.module_combobox
if tgt_selector.currentText() != module and module in GET_VALID_OCR():
tgt_selector.setCurrentText(module)
def on_trans_changed(self):
module = self.bottomBar.trans_selector.selector.currentText()
tgt_selector = self.configPanel.trans_config_panel.module_combobox
if tgt_selector.currentText() != module and module in GET_VALID_TRANSLATORS():
tgt_selector.setCurrentText(module)
def on_trans_src_changed(self):
sender = self.sender()
text = sender.currentText()
translator = self.module_manager.translator
if translator is not None:
translator.set_source(text)
pcfg.module.translate_source = text
combobox = self.configPanel.trans_config_panel.source_combobox
if sender != combobox:
combobox.blockSignals(True)
combobox.setCurrentText(text)
combobox.blockSignals(False)
combobox = self.bottomBar.trans_selector.src_selector
if sender != combobox:
combobox.blockSignals(True)
combobox.setCurrentText(text)
combobox.blockSignals(False)
def on_trans_tgt_changed(self):
sender = self.sender()
text = sender.currentText()
translator = self.module_manager.translator
if translator is not None:
translator.set_target(text)
pcfg.module.translate_target = text
combobox = self.configPanel.trans_config_panel.target_combobox
if sender != combobox:
combobox.blockSignals(True)
combobox.setCurrentText(text)
combobox.blockSignals(False)
combobox = self.bottomBar.trans_selector.tgt_selector
if sender != combobox:
combobox.blockSignals(True)
combobox.setCurrentText(text)
combobox.blockSignals(False)
def on_inpaint_changed(self):
module = self.bottomBar.inpaint_selector.selector.currentText()
tgt_selector = self.configPanel.inpaint_config_panel.module_combobox
if tgt_selector.currentText() != module and module in GET_VALID_INPAINTERS():
tgt_selector.setCurrentText(module)
def on_transpagebtn_pressed(self, run_target: bool):
page_key = self.imgtrans_proj.current_img
if page_key is None:
return
blkitem_list = self.st_manager.textblk_item_list
if len(blkitem_list) < 1:
return
self.translateBlkitemList(blkitem_list, -1)
def translateBlkitemList(self, blkitem_list: List, mode: int) -> bool:
tgt_img = self.imgtrans_proj.img_array
if tgt_img is None:
return False
tgt_mask = self.imgtrans_proj.mask_array
if len(blkitem_list) < 1:
return False
self.global_search_widget.set_document_edited()
im_h, im_w = tgt_img.shape[:2]
blk_list, blk_ids = [], []
for blkitem in blkitem_list:
blk: TextBlock = blkitem.blk
blk._bounding_rect = blkitem.absBoundingRect()
blk.text = self.st_manager.pairwidget_list[blkitem.idx].e_source.toPlainText()
blk_ids.append(blkitem.idx)
blk.set_lines_by_xywh(blk._bounding_rect, angle=-blk.angle, x_range=[0, im_w-1], y_range=[0, im_h-1], adjust_bbox=True)
blk_list.append(blk)
self.module_manager.runBlktransPipeline(blk_list, tgt_img, mode, blk_ids, tgt_mask = tgt_mask)
return True
def finishTranslatePage(self, page_key):
if page_key == self.imgtrans_proj.current_img:
self.st_manager.updateTranslation()
def on_imgtrans_pipeline_finished(self):
self.backup_blkstyles.clear()
self._run_imgtrans_wo_textstyle_update = False
self.postprocess_mt_toggle = True
if pcfg.module.empty_runcache and not shared.HEADLESS:
self.module_manager.unload_all_models()
if shared.args.export_translation_txt:
self.on_export_txt('translation')
if shared.args.export_source_txt:
self.on_export_txt('source')
if shared.HEADLESS:
self.run_next_dir()
def postprocess_translations(self, blk_list: List[TextBlock]) -> None:
src_is_cjk = is_cjk(pcfg.module.translate_source)
tgt_is_cjk = is_cjk(pcfg.module.translate_target)
if tgt_is_cjk:
for blk in blk_list:
if src_is_cjk:
blk.translation = full_len(blk.translation)
else:
blk.translation = half_len(blk.translation)
blk.translation = re.sub(r'([?.!"])\s+', r'\1', blk.translation) # remove spaces following punctuations
else:
for blk in blk_list:
if blk.vertical:
blk.alignment = TextAlignment.Center
blk.translation = half_len(blk.translation)
blk.vertical = False
for blk in blk_list:
blk.translation = self.mtSubWidget.sub_text(blk.translation)
if pcfg.let_uppercase_flag:
blk.translation = blk.translation.upper()
def on_pagtrans_finished(self, page_index: int):
blk_list = self.imgtrans_proj.get_blklist_byidx(page_index)
ffmt_list = None
if len(self.backup_blkstyles) == self.imgtrans_proj.num_pages and len(self.backup_blkstyles[page_index]) == len(blk_list):
ffmt_list: List[FontFormat] = self.backup_blkstyles[page_index]
self.postprocess_translations(blk_list)
# override font format if necessary
override_fnt_size = pcfg.let_fntsize_flag == 1
override_fnt_stroke = pcfg.let_fntstroke_flag == 1
override_fnt_color = pcfg.let_fntcolor_flag == 1
override_fnt_scolor = pcfg.let_fnt_scolor_flag == 1
override_alignment = pcfg.let_alignment_flag == 1
override_effect = pcfg.let_fnteffect_flag == 1
override_writing_mode = pcfg.let_writing_mode_flag == 1
override_font_family = pcfg.let_family_flag == 1
gf = self.textPanel.formatpanel.global_format
inpaint_only = pcfg.module.enable_inpaint
inpaint_only = inpaint_only and not (pcfg.module.enable_detect or pcfg.module.enable_ocr or pcfg.module.enable_translate)
if not inpaint_only:
for ii, blk in enumerate(blk_list):
if self._run_imgtrans_wo_textstyle_update and ffmt_list is not None:
blk.fontformat.merge(ffmt_list[ii])
else:
if override_fnt_size or \
blk.font_size < 0: # fall back to global font size if font size is not valid, it will be set to -1 for detected blocks
blk.font_size = gf.font_size
elif blk._detected_font_size > 0 and not pcfg.module.enable_detect:
blk.font_size = blk._detected_font_size
if override_fnt_stroke:
blk.stroke_width = gf.stroke_width
elif pcfg.module.enable_ocr:
blk.recalulate_stroke_width()
if override_fnt_color:
blk.set_font_colors(fg_colors=gf.frgb)
if override_fnt_scolor:
blk.set_font_colors(bg_colors=gf.srgb)
if override_alignment:
blk.alignment = gf.alignment
elif pcfg.module.enable_detect and not blk.src_is_vertical:
blk.recalulate_alignment()
if override_effect:
blk.opacity = gf.opacity
blk.shadow_color = gf.shadow_color
blk.shadow_radius = gf.shadow_radius
blk.shadow_strength = gf.shadow_strength
blk.shadow_offset = gf.shadow_offset
if override_writing_mode:
blk.vertical = gf.vertical
if override_font_family or blk.font_family is None:
blk.font_family = gf.font_family
if blk.rich_text:
blk.rich_text = set_html_family(blk.rich_text, gf.font_family)
blk.line_spacing = gf.line_spacing
blk.letter_spacing = gf.letter_spacing
blk.italic = gf.italic
blk.bold = gf.bold
blk.underline = gf.underline
sw = blk.stroke_width
if sw > 0 and pcfg.module.enable_ocr and pcfg.module.enable_detect and not override_fnt_size:
blk.font_size = blk.font_size / (1 + sw)
self.st_manager.auto_textlayout_flag = pcfg.let_autolayout_flag and \
(pcfg.module.enable_detect or pcfg.module.enable_translate)
if page_index != self.pageList.currentIndex().row():
self.pageList.setCurrentRow(page_index)
else:
self.imgtrans_proj.set_current_img_byidx(page_index)
self.canvas.updateCanvas()
self.st_manager.updateSceneTextitems()
if not pcfg.module.enable_detect and pcfg.module.enable_translate:
for blkitem in self.st_manager.textblk_item_list:
blkitem.squeezeBoundingRect()
if page_index + 1 == self.imgtrans_proj.num_pages:
self.st_manager.auto_textlayout_flag = False
# save proj file on page trans finished
self.imgtrans_proj.save()
self.saveCurrentPage(False, False)
def on_savestate_changed(self, unsaved: bool):
save_state = self.tr('unsaved') if unsaved else self.tr('saved')
self.titleBar.setTitleContent(save_state=save_state)
def on_textstack_changed(self):
if not self.page_changing:
self.global_search_widget.set_document_edited()
def on_run_blktrans(self, mode: int):
blkitem_list = self.canvas.selected_text_items()
self.translateBlkitemList(blkitem_list, mode)
def on_blktrans_finished(self, mode: int, blk_ids: List[int]):
if len(blk_ids) < 1:
return
blkitem_list = [self.st_manager.textblk_item_list[idx] for idx in blk_ids]
pairw_list = []
for blk in blkitem_list:
pairw_list.append(self.st_manager.pairwidget_list[blk.idx])
self.canvas.push_undo_command(RunBlkTransCommand(self.canvas, blkitem_list, pairw_list, mode))
def on_imgtrans_progressbox_showed(self):
msg_size = self.module_manager.progress_msgbox.size()
size = self.size()
p = self.mapToGlobal(QPoint(size.width() - msg_size.width(),
size.height() - msg_size.height()))
self.module_manager.progress_msgbox.move(p)
def on_closebtn_clicked(self):
if self.imsave_thread.isRunning():
self.imsave_thread.finished.connect(self.close)
mb = FrameLessMessageBox()
mb.setText(self.tr('Saving image...'))
self.imsave_thread.finished.connect(mb.close)
mb.exec()
return
self.close()
def on_display_lang_changed(self, lang: str):
if lang != pcfg.display_lang:
pcfg.display_lang = lang
self.set_display_lang(lang)
def run_imgtrans(self):
if not self.imgtrans_proj.is_all_pages_no_text and not pcfg.module.keep_exist_textlines:
reply = QMessageBox.question(self, self.tr('Confirmation'),
self.tr('Are you sure to run image translation again?\nAll existing translation results will be cleared!'),
QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
if reply != QMessageBox.Yes:
return
self.on_run_imgtrans()
def run_imgtrans_wo_textstyle_update(self):
self._run_imgtrans_wo_textstyle_update = True
self.run_imgtrans()
def on_run_imgtrans(self):
self.backup_blkstyles.clear()
if self.bottomBar.textblockChecker.isChecked():
self.bottomBar.textblockChecker.click()
self.postprocess_mt_toggle = False
all_disabled = pcfg.module.all_stages_disabled()
if pcfg.module.enable_detect:
for page in self.imgtrans_proj.pages:
if not pcfg.module.keep_exist_textlines:
self.imgtrans_proj.pages[page].clear()
else:
self.st_manager.updateTextBlkList()
textblk: TextBlock = None
for blklist in self.imgtrans_proj.pages.values():
ffmt_list = []
self.backup_blkstyles.append(ffmt_list)
for textblk in blklist:
if not pcfg.module.enable_detect:
ffmt_list.append(textblk.fontformat.deepcopy())
if pcfg.module.enable_ocr:
textblk.text = []
textblk.set_font_colors((0, 0, 0), (0, 0, 0))
if pcfg.module.enable_translate or (all_disabled and not self._run_imgtrans_wo_textstyle_update) or pcfg.module.enable_ocr:
textblk.rich_text = ''
textblk.vertical = textblk.src_is_vertical
self.module_manager.runImgtransPipeline()
def on_transpanel_changed(self):
self.canvas.editor_index = self.rightComicTransStackPanel.currentIndex()
if not self.canvas.textEditMode() and self.canvas.search_widget.isVisible():
self.canvas.search_widget.hide()
self.canvas.updateLayers()
def import_tstyles(self):
ddir = osp.dirname(pcfg.text_styles_path)
p = QFileDialog.getOpenFileName(self, self.tr("Import Text Styles"), ddir, None, "(.json)")
if not isinstance(p, str):
p = p[0]
if p == '':
return
try:
load_textstyle_from(p, raise_exception=True)
save_config()
self.textPanel.formatpanel.textstyle_panel.setStyles(text_styles)
except Exception as e:
create_error_dialog(e, self.tr(f'Failed to load from {p}'))
def export_tstyles(self):
ddir = osp.dirname(pcfg.text_styles_path)
savep = QFileDialog.getSaveFileName(self, self.tr("Save Text Styles"), ddir, None, "(.json)")
if not isinstance(savep, str):
savep = savep[0]
if savep == '':
return
suffix = Path(savep).suffix
if suffix != '.json':
if suffix == '':
savep = savep + '.json'
else:
savep = savep.replace(suffix, '.json')
oldp = pcfg.text_styles_path
try:
pcfg.text_styles_path = savep
save_text_styles(raise_exception=True)
save_config()
except Exception as e:
create_error_dialog(e, self.tr(f'Failed save to {savep}'))
pcfg.text_styles_path = oldp
def fold_textarea(self, fold: bool):
pcfg.fold_textarea = fold
self.textPanel.textEditList.setFoldTextarea(fold)
def show_source_text(self, show: bool):
pcfg.show_source_text = show
self.textPanel.textEditList.setSourceVisible(show)
def show_trans_text(self, show: bool):
pcfg.show_trans_text = show
self.textPanel.textEditList.setTransVisible(show)
def on_export_doc(self):
if self.canvas.text_change_unsaved():
self.st_manager.updateTextBlkList()
self.export_doc_thread.exportAsDoc(self.imgtrans_proj)
def on_import_doc(self):
self.import_doc_thread.importDoc(self.imgtrans_proj)
def on_export_txt(self, dump_target, suffix='.txt'):
try:
self.imgtrans_proj.dump_txt(dump_target=dump_target, suffix=suffix)
create_info_dialog(self.tr('Text file exported to ') + self.imgtrans_proj.dump_txt_path(dump_target, suffix))
except Exception as e:
create_error_dialog(e, self.tr('Failed to export as TEXT file'))
def on_import_trans_txt(self):
try:
selected_file = ''
dialog = QFileDialog()
selected_file = str(dialog.getOpenFileUrl(self.parent(), self.tr('Import *.md/*.txt'), filter="*.txt *.md *.TXT *.MD")[0].toLocalFile())
if not osp.exists(selected_file):
return
all_matched, match_rst = self.imgtrans_proj.load_translation_from_txt(selected_file)
matched_pages = match_rst['matched_pages']
if self.imgtrans_proj.current_img in matched_pages:
self.canvas.clear_undostack(update_saved_step=True)
self.st_manager.updateSceneTextitems()
if all_matched:
msg = self.tr('Translation imported and matched successfully.')
else:
msg = self.tr('Imported txt file not fully matched with current project, please make sure source txt file structured like results from \"export TXT/markdown\"')
if len(match_rst['missing_pages']) > 0:
msg += '\n' + self.tr('Missing pages: ') + '\n'
msg += '\n'.join(match_rst['missing_pages'])
if len(match_rst['unexpected_pages']) > 0:
msg += '\n' + self.tr('Unexpected pages: ') + '\n'
msg += '\n'.join(match_rst['unexpected_pages'])
if len(match_rst['unmatched_pages']) > 0:
msg += '\n' + self.tr('Unmatched pages: ') + '\n'
msg += '\n'.join(match_rst['unmatched_pages'])
msg = msg.strip()
for pagename in matched_pages:
for blk in self.imgtrans_proj.pages[pagename]:
blk.translation = self.mtSubWidget.sub_text(blk.translation)
create_info_dialog(msg)
except Exception as e:
create_error_dialog(e, self.tr('Failed to import translation from ') + selected_file)
def on_reveal_file(self):
current_img_path = self.imgtrans_proj.current_img_path()
if sys.platform == 'win32':
# qprocess seems to fuck up with "\""
p = "\""+str(Path(current_img_path))+"\""
subprocess.Popen("explorer.exe /select,"+p, shell=True)
elif sys.platform == 'darwin':
p = "\""+current_img_path+"\""
subprocess.Popen("open -R "+p, shell=True)
def on_set_gsearch_widget(self):
setup = self.leftBar.globalSearchChecker.isChecked()
if setup:
if self.leftStackWidget.isHidden():
self.leftStackWidget.show()
self.leftBar.showPageListLabel.setChecked(False)
self.leftStackWidget.setCurrentWidget(self.global_search_widget)
else:
self.leftStackWidget.hide()
def on_fin_export_doc(self):
msg = QMessageBox()
msg.setText(self.tr('Export to ') + self.imgtrans_proj.doc_path())
msg.exec_()
def on_fin_import_doc(self):
self.st_manager.updateSceneTextitems()
def on_global_replace_finished(self):
rt = self.global_search_widget.replace_thread
self.canvas.push_text_command(
GlobalRepalceAllCommand(rt.sceneitem_list, rt.background_list, rt.target_text, self.imgtrans_proj)
)
rt.sceneitem_list = None
rt.background_list = None
def on_darkmode_triggered(self):
pcfg.darkmode = self.titleBar.darkModeAction.isChecked()
self.resetStyleSheet(reverse_icon=True)
self.save_config()
def ocr_postprocess(self, textblocks: List[TextBlock], img, ocr_module=None, **kwargs):
for blk in textblocks:
text = blk.get_text()
blk.text = self.ocrSubWidget.sub_text(text)
def translate_preprocess(self, translations: List[str] = None, textblocks: List[TextBlock] = None, translator = None, source_text:list = []):
for i in range(len(source_text)):
source_text[i] = self.mtPreSubWidget.sub_text(source_text[i])
def translate_postprocess(self, translations: List[str] = None, textblocks: List[TextBlock] = None, translator = None):
if not self.postprocess_mt_toggle:
return
for ii, tr in enumerate(translations):
translations[ii] = self.mtSubWidget.sub_text(tr)
def on_copy_src(self):
blks = self.canvas.selected_text_items()
if len(blks) == 0:
return
if isinstance(self.module_manager.translator, GPTTranslator):
src_list = [self.st_manager.pairwidget_list[blk.idx].e_source.toPlainText() for blk in blks]
src_txt = ''
for (prompt, num_src) in self.module_manager.translator._assemble_prompts(src_list, max_tokens=4294967295):
src_txt += prompt
src_txt = src_txt.strip()
else:
src_list = [self.st_manager.pairwidget_list[blk.idx].e_source.toPlainText().strip().replace('\n', ' ') for blk in blks]
src_txt = '\n'.join(src_list)
self.st_manager.app_clipborad.setText(src_txt, QClipboard.Mode.Clipboard)
def on_paste_src(self):
blks = self.canvas.selected_text_items()
if len(blks) == 0:
return
src_widget_list = [self.st_manager.pairwidget_list[blk.idx].e_source for blk in blks]
text_list = self.st_manager.app_clipborad.text().split('\n')
n_paragraph = min(len(src_widget_list), len(text_list))
if n_paragraph < 1:
return
src_widget_list = src_widget_list[:n_paragraph]
text_list = text_list[:n_paragraph]
self.canvas.push_undo_command(PasteSrcItemsCommand(src_widget_list, text_list))
def run_batch(self, exec_dirs: Union[List, str], **kwargs):
if not isinstance(exec_dirs, List):
exec_dirs = exec_dirs.split(',')
valid_dirs = []
for d in exec_dirs:
if osp.exists(d):
valid_dirs.append(d)
else:
LOGGER.warning(f'target directory {d} does not exist.')
self.exec_dirs = valid_dirs
self.run_next_dir()
def run_next_dir(self):
if len(self.exec_dirs) == 0:
while self.imsave_thread.isRunning():
time.sleep(0.1)
LOGGER.info(f'finished translating all dirs, quit app...')
self.app.quit()
return
d = self.exec_dirs.pop(0)
LOGGER.info(f'translating {d} ...')
self.openDir(d)
shared.pbar = {}
npages = len(self.imgtrans_proj.pages)
if npages > 0:
if pcfg.module.enable_detect:
shared.pbar['detect'] = tqdm(range(npages), desc="Text Detection")
if pcfg.module.enable_ocr:
shared.pbar['ocr'] = tqdm(range(npages), desc="OCR")
if pcfg.module.enable_translate:
shared.pbar['translate'] = tqdm(range(npages), desc="Translation")
if pcfg.module.enable_inpaint:
shared.pbar['inpaint'] = tqdm(range(npages), desc="Inpaint")
self.on_run_imgtrans()
def on_create_errdialog(self, error_msg: str, detail_traceback: str = '', exception_type: str = ''):
try:
if exception_type != '':
shared.showed_exception.add(exception_type)
err = QMessageBox()
err.setText(error_msg)
err.setDetailedText(detail_traceback)
err.exec()
if exception_type != '':
shared.showed_exception.remove(exception_type)
except:
if exception_type in shared.showed_exception:
shared.showed_exception.remove(exception_type)
LOGGER.error('Failed to create error dialog')
LOGGER.error(traceback.format_exc())
def on_create_infodialog(self, info_dict: dict):
QMessageBox.StandardButton.NoButton
dialog = MessageBox(**info_dict)
dialog.show() # exec_ will block main thread
def setupRegisterWidget(self):
self.titleBar.viewMenu.addSeparator()
for cfg_name in shared.config_name_to_view_widget:
d = shared.config_name_to_view_widget[cfg_name]
widget: ViewWidget = d['widget']
action = QAction(widget.action_name, self.titleBar)
action.setCheckable(True)
visible = getattr(pcfg, cfg_name)
action.setChecked(visible)
action.triggered.connect(self.action_set_view_visible)
self.titleBar.viewMenu.addAction(action)
d['action'] = action
shared.action_to_view_config_name[action] = cfg_name
widget.set_expend_area(expend=getattr(pcfg, widget.config_expand_name), set_config=False)
widget.view_hide_btn_clicked.connect(self.on_hide_view_widget)
widget.setVisible(visible)
def register_view_widget(self, widget: ViewWidget):
assert widget.config_name not in shared.config_name_to_view_widget
d = {'widget': widget}
shared.config_name_to_view_widget[widget.config_name] = d
def action_set_view_visible(self):
action: QAction = self.sender()
show = action.isChecked()
cfg_name = shared.action_to_view_config_name[action]
widget: ViewWidget = shared.config_name_to_view_widget[cfg_name]['widget']
widget.setVisible(show)
setattr(pcfg, cfg_name, show)
def on_hide_view_widget(self, cfg_name: str):
d = shared.config_name_to_view_widget[cfg_name]
widget: ViewWidget = d['widget']
widget.setVisible(False)
action: QAction = d['action']
action.setChecked(False)
setattr(pcfg, cfg_name, False) |