From bb6c0f7efd2486af3425a92080bf88a3b85bc913 Mon Sep 17 00:00:00 2001 From: test123456654321 <16307130148@fudan.edu.cn> Date: Mon, 28 Oct 2024 10:12:40 +0800 Subject: [PATCH] some --- src/LunaTranslator/gui/inputdialog.py | 36 ++++++--------- src/LunaTranslator/gui/setting_about.py | 1 - src/LunaTranslator/gui/usefulwidget.py | 46 ++++++++++++++++--- src/LunaTranslator/myutils/ocrutil.py | 4 +- .../network/libcurl/requester.py | 7 +-- .../network/winhttp/requester.py | 5 +- src/LunaTranslator/ocrengines/googlelens.py | 4 +- src/LunaTranslator/ocrengines/volcengine.py | 4 -- src/LunaTranslator/qtsymbols.py | 4 +- .../rendertext/textbrowser_imp/yinying.py | 7 ++- src/LunaTranslator/requests.py | 10 ++-- src/LunaTranslator/translator/huoshanapi.py | 4 -- src/LunaTranslator/translator/microsoft.py | 2 +- src/plugins/CMakeLists.txt | 4 +- 14 files changed, 79 insertions(+), 59 deletions(-) diff --git a/src/LunaTranslator/gui/inputdialog.py b/src/LunaTranslator/gui/inputdialog.py index 91dd4b5d..6558d20d 100644 --- a/src/LunaTranslator/gui/inputdialog.py +++ b/src/LunaTranslator/gui/inputdialog.py @@ -32,7 +32,7 @@ from gui.dynalang import ( @Singleton_close class noundictconfigdialog1(LDialog): - def newline(self, row, item): + def newline(self, row, item: dict): self.model.insertRow( row, [ @@ -42,15 +42,9 @@ class noundictconfigdialog1(LDialog): QStandardItem(item["value"]), ], ) - if "regex" not in item: - item["regex"] = False - if "escape" not in item: - item["escape"] = item["regex"] - self.table.setIndexWidget( - self.model.index(row, 0), getsimpleswitch(item, "regex") - ) - self.table.setIndexWidget( - self.model.index(row, 1), getsimpleswitch(item, "escape") + self.table.setindexdata(self.model.index(row, 0), item.get("regex", False)) + self.table.setindexdata( + self.model.index(row, 1), item.get("escape", item.get("regex", False)) ) def __init__(self, parent, reflist, title, label) -> None: @@ -74,8 +68,6 @@ class noundictconfigdialog1(LDialog): ) self.table = table - for row, item in enumerate(reflist): - self.newline(row, item) search = QHBoxLayout() searchcontent = QLineEdit() @@ -100,6 +92,8 @@ class noundictconfigdialog1(LDialog): table.getindexdata = self.__getindexwidgetdata table.setindexdata = self.__setindexwidget self.table = table + for row, item in enumerate(reflist): + self.newline(row, item) button = threebuttons(texts=["添加行", "删除行", "上移", "下移", "立即应用"]) table.insertplainrow = lambda row: self.newline( row, {"key": "", "value": "", "regex": False} @@ -121,10 +115,10 @@ class noundictconfigdialog1(LDialog): def __setindexwidget(self, index: QModelIndex, data): if index.column() == 0: - data = {"regex": data.lower() == "true"} + data = {"regex": self.table.compatiblebool(data)} self.table.setIndexWidget(index, getsimpleswitch(data, "regex")) elif index.column() == 1: - data = {"escape": data.lower() == "true"} + data = {"escape": self.table.compatiblebool(data)} self.table.setIndexWidget(index, getsimpleswitch(data, "escape")) else: self.table.model().setItem(index.row(), index.column(), QStandardItem(data)) @@ -261,12 +255,10 @@ class yuyinzhidingsetting(LDialog): QStandardItem(), ], ) - self.table.setIndexWidget( - self.model.index(row, 0), getsimpleswitch(item, "regex") - ) - com = getsimplecombobox(["首尾", "包含"], item, "condition") - self.table.setIndexWidget(self.model.index(row, 1), com) - self.table.setIndexWidget(self.model.index(row, 3), self.createacombox(item)) + self.table.setindexdata(self.model.index(row, 0), item['regex']) + + self.table.setindexdata(self.model.index(row, 1), item['condition']) + self.table.setindexdata(self.model.index(row, 3), item['target']) def createacombox(self, config): com = LFocusCombo() @@ -384,7 +376,7 @@ class yuyinzhidingsetting(LDialog): def __setindexwidget(self, index: QModelIndex, data): if index.column() == 0: - data = {"regex": data.lower() == "true"} + data = {"regex": self.table.compatiblebool(data)} self.table.setIndexWidget(index, getsimpleswitch(data, "regex")) elif index.column() == 1: try: @@ -400,7 +392,7 @@ class yuyinzhidingsetting(LDialog): pass else: try: - data = json.loads(data) + data = self.table.compatiblejson(data) except: data = "default" self.table.setIndexWidget(index, self.createacombox({"target": data})) diff --git a/src/LunaTranslator/gui/setting_about.py b/src/LunaTranslator/gui/setting_about.py index 873e44f1..fdeff607 100644 --- a/src/LunaTranslator/gui/setting_about.py +++ b/src/LunaTranslator/gui/setting_about.py @@ -120,7 +120,6 @@ def updatemethod(urls, self): stream=True, verify=False, proxies=getproxy(("update", __x)), - timeout=None, ) file_size = 0 for i in r.iter_content(chunk_size=1024): diff --git a/src/LunaTranslator/gui/usefulwidget.py b/src/LunaTranslator/gui/usefulwidget.py index 4374d61d..0d780bf0 100644 --- a/src/LunaTranslator/gui/usefulwidget.py +++ b/src/LunaTranslator/gui/usefulwidget.py @@ -97,8 +97,7 @@ class TableViewW(QTableView): self.customContextMenuRequested.connect(self.showmenu) def showmenu(self, pos): - r = self.currentIndex().row() - if r < 0: + if not self.currentIndex().isValid(): return menu = QMenu(self) up = LAction("上移") @@ -159,8 +158,11 @@ class TableViewW(QTableView): self.model().removeRow(row) def removeselectedrows(self): - row = self.currentIndex().row() - col = self.currentIndex().column() + curr = self.currentIndex() + if not curr.isValid(): + return + row = curr.row() + col = curr.column() skip = [] for index in self.selectedIndexes(): if index.row() in skip: @@ -176,6 +178,8 @@ class TableViewW(QTableView): def moverank(self, dy): curr = self.currentIndex() + if not curr.isValid(): + return row, col = curr.row(), curr.column() model = self.model() @@ -206,6 +210,15 @@ class TableViewW(QTableView): l: QHBoxLayout = w.layout() return l.itemAt(0).widget() + def inputMethodEvent(self, event: QInputMethodEvent): + # setindexwidget之后,会导致谜之循环触发,异常; + # 没有setindexwidget的,会跳转到第一个输入的字母的行,正常,但我不想要。 + pres = event.commitString() + if not pres: + super().inputMethodEvent(event) + else: + event.accept() + def setIndexWidget(self, index: QModelIndex, w: QWidget): if w is None: return @@ -229,6 +242,24 @@ class TableViewW(QTableView): def setindexdata(self, index, data): self.model().setItem(index.row(), index.column(), QStandardItem(data)) + def compatiblebool(self, data): + if isinstance(data, str): + data = data.lower() == "true" + elif isinstance(data, bool): + data = data + else: + raise Exception + return data + + def compatiblejson(self, data): + if isinstance(data, str): + data = json.loads(data) + elif isinstance(data, (list, dict, tuple)): + data = data + else: + raise Exception + return data + def getdata(self, row_or_index, col=None): if col is None: index: QModelIndex = row_or_index @@ -260,8 +291,10 @@ class TableViewW(QTableView): winsharedutils.clipboard_set(csv_str) def pastetable(self): - string = winsharedutils.clipboard_get() current = self.currentIndex() + if not current.isValid(): + return + string = winsharedutils.clipboard_get() try: csv_file = io.StringIO(string) csv_reader = csv.reader(csv_file, delimiter="\t") @@ -1796,8 +1829,7 @@ def makesubtab_lazy( class listediter(LDialog): def showmenu(self, p: QPoint): curr = self.hctable.currentIndex() - r = curr.row() - if r < 0: + if not curr.isValid(): return menu = QMenu(self.hctable) remove = LAction("删除") diff --git a/src/LunaTranslator/myutils/ocrutil.py b/src/LunaTranslator/myutils/ocrutil.py index e5880aa9..4f0a0773 100644 --- a/src/LunaTranslator/myutils/ocrutil.py +++ b/src/LunaTranslator/myutils/ocrutil.py @@ -87,8 +87,10 @@ def ocr_run(qimage: QImage): if not image: return "", None global _nowuseocrx, _ocrengine + thisocrtype = _nowuseocrx try: ocr_init() + thisocrtype = _ocrengine.typename res = _ocrengine._private_ocr(image) if not res: return "", None @@ -105,7 +107,7 @@ def ocr_run(qimage: QImage): print_exc() msg = stringfyerror(e) text = ( - (_TR(globalconfig["ocr"][_nowuseocrx]["name"]) if _nowuseocrx else "") + (_TR(globalconfig["ocr"][thisocrtype]["name"]) if thisocrtype else "") + " " + msg ) diff --git a/src/LunaTranslator/network/libcurl/requester.py b/src/LunaTranslator/network/libcurl/requester.py index ccc098e6..8a6b4738 100644 --- a/src/LunaTranslator/network/libcurl/requester.py +++ b/src/LunaTranslator/network/libcurl/requester.py @@ -158,9 +158,10 @@ class Requester(Requester_common): curl_easy_reset(curl) curl_easy_setopt(curl, CURLoption.COOKIEJAR, "") - if timeout: - curl_easy_setopt(curl, CURLoption.TIMEOUT_MS, timeout) - curl_easy_setopt(curl, CURLoption.CONNECTTIMEOUT_MS, timeout) + if timeout[0]: + curl_easy_setopt(curl, CURLoption.CONNECTTIMEOUT_MS, timeout[0]) + if timeout[1]: + curl_easy_setopt(curl, CURLoption.TIMEOUT_MS, sum(timeout)) curl_easy_setopt( curl, CURLoption.ACCEPT_ENCODING, diff --git a/src/LunaTranslator/network/winhttp/requester.py b/src/LunaTranslator/network/winhttp/requester.py index d6d9a131..874d7812 100644 --- a/src/LunaTranslator/network/winhttp/requester.py +++ b/src/LunaTranslator/network/winhttp/requester.py @@ -160,8 +160,9 @@ class Requester(Requester_common): flag, ) ) - if timeout: - WinHttpSetTimeouts(hRequest, timeout, timeout, timeout, timeout) + tconnect = timeout[0] + tsendrecv = timeout[1] + WinHttpSetTimeouts(hRequest, tconnect, tconnect, tsendrecv, tsendrecv) if hRequest == 0: MaybeRaiseException() self._set_verify(hRequest, verify) diff --git a/src/LunaTranslator/ocrengines/googlelens.py b/src/LunaTranslator/ocrengines/googlelens.py index fb82c92b..ac1c8798 100644 --- a/src/LunaTranslator/ocrengines/googlelens.py +++ b/src/LunaTranslator/ocrengines/googlelens.py @@ -17,9 +17,7 @@ class OCR(baseocr): cookies = {"SOCS": "CAESEwgDEgk0ODE3Nzk3MjQaAmVuIAEaBgiA_LyaBg"} files = {"encoded_image": ("screenshot.png", imagebinary, "image/png")} - res = self.proxysession.post( - url, files=files, headers=headers, cookies=cookies, timeout=20 - ) + res = self.proxysession.post(url, files=files, headers=headers, cookies=cookies) match = regex.search(res.text) if match == None: return diff --git a/src/LunaTranslator/ocrengines/volcengine.py b/src/LunaTranslator/ocrengines/volcengine.py index 1af60910..a1876cf5 100644 --- a/src/LunaTranslator/ocrengines/volcengine.py +++ b/src/LunaTranslator/ocrengines/volcengine.py @@ -433,10 +433,6 @@ class Service(object): url, headers=r.headers, data=r.form, - timeout=( - self.service_info.connection_timeout, - self.service_info.socket_timeout, - ), proxies=proxy, ) if resp.status_code == 200: diff --git a/src/LunaTranslator/qtsymbols.py b/src/LunaTranslator/qtsymbols.py index a0d7c899..da513b5b 100644 --- a/src/LunaTranslator/qtsymbols.py +++ b/src/LunaTranslator/qtsymbols.py @@ -1,7 +1,7 @@ try: from PyQt5 import QtSvg from PyQt5.QtWidgets import QFrame,QListView,QCheckBox,QAbstractItemView,QTextEdit,QTableView,QHeaderView,QColorDialog,QSpinBox,QDoubleSpinBox,QComboBox,QDialogButtonBox,QMainWindow,QMessageBox,QDialog,QGridLayout,QTextBrowser,QGraphicsDropShadowEffect,QWidget,QSizePolicy,QScrollArea,QApplication,QPushButton,QSystemTrayIcon,QPlainTextEdit,QAction,QMenu,QFileDialog,QKeySequenceEdit,QLabel,QSpacerItem,QWidgetItem,QLayout,QTextBrowser,QLineEdit,QFormLayout,QSizePolicy,QTabWidget,QTabBar,QSplitter,QListWidget,QListWidgetItem,QHBoxLayout,QVBoxLayout,QSizeGrip,QFontComboBox,QProgressBar,QRadioButton,QButtonGroup,QSlider,QToolTip,QGroupBox,QGraphicsOpacityEffect,QStackedWidget,QStyledItemDelegate,QStyleOptionViewItem,QFontDialog,QTreeView - from PyQt5.QtGui import QIconEngine,QIntValidator,QStandardItem,QStandardItemModel,QImageWriter,QIcon,QTextCharFormat,QTextBlockFormat,QResizeEvent,QTextCursor,QFontMetricsF,QMouseEvent,QImage,QPainter,QRegion,QCloseEvent,QFontDatabase,QKeySequence,QPixmap,QCursor,QColor,QFont,QPen,QPainterPath,QBrush,QFontMetrics,QShowEvent,QWheelEvent,QPaintEvent,QTextLayout, QTextOption,QDragEnterEvent, QDropEvent,QTransform,QKeyEvent + from PyQt5.QtGui import QIconEngine,QIntValidator,QStandardItem,QStandardItemModel,QImageWriter,QIcon,QTextCharFormat,QTextBlockFormat,QResizeEvent,QTextCursor,QFontMetricsF,QMouseEvent,QImage,QPainter,QRegion,QCloseEvent,QFontDatabase,QKeySequence,QPixmap,QCursor,QColor,QFont,QPen,QPainterPath,QBrush,QFontMetrics,QShowEvent,QWheelEvent,QPaintEvent,QTextLayout, QTextOption,QDragEnterEvent, QDropEvent,QTransform,QKeyEvent,QInputMethodEvent from PyQt5.QtCore import QObject,pyqtSignal,Qt,QSize,QByteArray,QBuffer,QPointF,QPoint,QRect,QEvent,QModelIndex,QTimer,QRectF,QVariantAnimation,QUrl,QPropertyAnimation,QLocale,QSignalBlocker isqt5 = True class LineHeightTypes: @@ -12,7 +12,7 @@ except: #print_exc() from PyQt6 import QtSvg from PyQt6.QtWidgets import QFrame,QListView,QCheckBox,QAbstractItemView,QTextEdit,QTableView,QHeaderView,QColorDialog,QSpinBox,QDoubleSpinBox,QComboBox,QDialogButtonBox,QMainWindow,QMessageBox,QDialog,QGridLayout,QTextBrowser,QGraphicsDropShadowEffect,QWidget,QSizePolicy,QScrollArea,QApplication,QPushButton,QSystemTrayIcon,QPlainTextEdit,QMenu,QFileDialog,QKeySequenceEdit,QLabel,QSpacerItem,QWidgetItem,QLayout,QTextBrowser,QLineEdit,QFormLayout,QSizePolicy,QTabWidget,QTabBar,QSplitter,QListWidget,QListWidgetItem,QHBoxLayout,QVBoxLayout,QSizeGrip,QFontComboBox,QProgressBar,QRadioButton,QButtonGroup,QSlider,QToolTip,QGroupBox,QGraphicsOpacityEffect,QStackedWidget,QTreeView - from PyQt6.QtGui import QIconEngine,QIntValidator,QAction,QStandardItem,QStandardItemModel,QImageWriter,QIcon,QTextCharFormat,QTextBlockFormat,QResizeEvent,QTextCursor,QFontMetricsF,QMouseEvent,QImage,QPainter,QRegion,QCloseEvent,QFontDatabase,QKeySequence,QPixmap,QCursor,QColor,QFont,QPen,QPainterPath,QBrush,QFontMetrics,QShowEvent,QWheelEvent,QPaintEvent,QTextLayout, QTextOption,QKeyEvent + from PyQt6.QtGui import QIconEngine,QIntValidator,QAction,QStandardItem,QStandardItemModel,QImageWriter,QIcon,QTextCharFormat,QTextBlockFormat,QResizeEvent,QTextCursor,QFontMetricsF,QMouseEvent,QImage,QPainter,QRegion,QCloseEvent,QFontDatabase,QKeySequence,QPixmap,QCursor,QColor,QFont,QPen,QPainterPath,QBrush,QFontMetrics,QShowEvent,QWheelEvent,QPaintEvent,QTextLayout, QTextOption,QKeyEvent,QInputMethodEvent from PyQt6.QtCore import QObject,pyqtSignal,Qt,QSize,QByteArray,QBuffer,QPointF,QPoint,QRect,QEvent,QModelIndex,QTimer,QRectF,QVariantAnimation,QUrl,QPropertyAnimation,QLocale isqt5 = False diff --git a/src/LunaTranslator/rendertext/textbrowser_imp/yinying.py b/src/LunaTranslator/rendertext/textbrowser_imp/yinying.py index 8301f67c..f1d65825 100644 --- a/src/LunaTranslator/rendertext/textbrowser_imp/yinying.py +++ b/src/LunaTranslator/rendertext/textbrowser_imp/yinying.py @@ -17,13 +17,12 @@ class CachedQGraphicsDropShadowEffect_multi(QGraphicsDropShadowEffect): super().__init__(parent) self.shadow_pixmap = QPixmap() self.x = x - self.savey = None + self.savey = None # iterappend中被移动而不需重绘 def draw(self, painter): - r = self.parent().devicePixelRatioF() if self.shadow_pixmap.isNull(): - - size = QSize(painter.device().width(), painter.device().height()) * r + r = self.parent().devicePixelRatioF() + size = self.boundingRect().toRect().united(painter.viewport()).size() * r self.shadow_pixmap = QPixmap(size) self.shadow_pixmap.setDevicePixelRatio(r) self.shadow_pixmap.fill(Qt.GlobalColor.transparent) diff --git a/src/LunaTranslator/requests.py b/src/LunaTranslator/requests.py index e662f9b4..f3429532 100644 --- a/src/LunaTranslator/requests.py +++ b/src/LunaTranslator/requests.py @@ -294,13 +294,17 @@ class Requester_common: proxy = None if proxy == "" else proxy if timeout: if isinstance(timeout, (float, int)): - timeout = int(timeout * 1000) # convert to milliseconds + timeout = (int(timeout * 1000), 0) # convert to milliseconds else: try: - timeout = max(int(_ * 1000) for _ in timeout) + timeout = [int(_ * 1000) for _ in timeout[:2]] except: print("Error invalid timeout", timeout) - timeout = None + timeout = [0, 0] + timeout.append(0) + timeout = timeout[:2] + else: + timeout = (0, 0) return self.request_impl( method, scheme, diff --git a/src/LunaTranslator/translator/huoshanapi.py b/src/LunaTranslator/translator/huoshanapi.py index ea01ba02..05459fe7 100644 --- a/src/LunaTranslator/translator/huoshanapi.py +++ b/src/LunaTranslator/translator/huoshanapi.py @@ -327,10 +327,6 @@ class Service(object): url, headers=r.headers, data=r.body.encode("utf8").decode("latin1"), - timeout=( - self.service_info.connection_timeout, - self.service_info.socket_timeout, - ), proxies=proxy, ) if resp.status_code == 200: diff --git a/src/LunaTranslator/translator/microsoft.py b/src/LunaTranslator/translator/microsoft.py index 062d8924..96fb43b4 100644 --- a/src/LunaTranslator/translator/microsoft.py +++ b/src/LunaTranslator/translator/microsoft.py @@ -18,7 +18,7 @@ def translate_async(text, to_language, from_language=None, self=None): url = "{}/translate?api-version={}&to={}".format( _apiEndpoint, _apiVersion, to_language ) - if from_language is not None: + if from_language != "auto": url += "&from={}".format(from_language) _privateKey = [ 0xA2, diff --git a/src/plugins/CMakeLists.txt b/src/plugins/CMakeLists.txt index ad1972ea..e532f430 100644 --- a/src/plugins/CMakeLists.txt +++ b/src/plugins/CMakeLists.txt @@ -28,8 +28,8 @@ set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} ${CMAKE_SOURCE_DIR}/version) include(generate_product_version) set(VERSION_MAJOR 5) -set(VERSION_MINOR 51) -set(VERSION_PATCH 2) +set(VERSION_MINOR 52) +set(VERSION_PATCH 0) add_library(pch pch.cpp) target_precompile_headers(pch PUBLIC pch.h)