From ee473c30a013713965dbda18a04d0145602f2ada Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=81=8D=E5=85=AE=E6=83=9A=E5=85=AE?= <101191390+HIllya51@users.noreply.github.com> Date: Thu, 23 May 2024 21:49:18 +0800 Subject: [PATCH] perf --- .../LunaTranslator/gui/selecthook.py | 2 - .../LunaTranslator/gui/textbrowser.py | 194 +++++++++--------- .../network/libcurl/requests.py | 68 ++---- .../LunaTranslator/textsource/texthook.py | 2 - .../LunaTranslator/translator/deepl_dev.py | 2 +- .../LunaTranslator/translator/dev_youdao.py | 6 +- .../LunaTranslator/translator/lingva.py | 6 +- .../LunaTranslator/translator/tx_dev.py | 6 +- plugins/CMakeLists.txt | 2 +- 9 files changed, 133 insertions(+), 155 deletions(-) diff --git a/LunaTranslator/LunaTranslator/gui/selecthook.py b/LunaTranslator/LunaTranslator/gui/selecthook.py index de66abcf..8c0101e6 100644 --- a/LunaTranslator/LunaTranslator/gui/selecthook.py +++ b/LunaTranslator/LunaTranslator/gui/selecthook.py @@ -821,7 +821,6 @@ class hookselect(closeashidewindow): return if gobject.baseobject.textsource: - print(hookcode) gobject.baseobject.textsource.inserthook(hookcode) self.tabwidget.setCurrentIndex(1) else: @@ -897,7 +896,6 @@ class hookselect(closeashidewindow): if select: gobject.baseobject.textsource.selectedhook.append(key) - print(key) if key[-2][:8] == "UserHook": needinserthookcode = savehook_new_data[ gobject.baseobject.textsource.pname diff --git a/LunaTranslator/LunaTranslator/gui/textbrowser.py b/LunaTranslator/LunaTranslator/gui/textbrowser.py index 914c8c71..daf3a707 100644 --- a/LunaTranslator/LunaTranslator/gui/textbrowser.py +++ b/LunaTranslator/LunaTranslator/gui/textbrowser.py @@ -76,21 +76,22 @@ class QGraphicsDropShadowEffect_multi(QGraphicsDropShadowEffect): super().draw(painter) -class PlainLabel(QLabel): - def __init__(self, parent=None): - super().__init__(parent) - self.setTextFormat(Qt.PlainText) - +class BorderedLabel(QLabel): def move(self, point: QPoint): text = self.text() isarabic = any((ord(char) >= 0x0600 and ord(char) <= 0x06E0) for char in text) if isarabic: point.setX(point.x() - self.width()) + + point.setX(int(point.x() - self.m_fontOutLineWidth)) + point.setY(int(point.y() - self.m_fontOutLineWidth)) super().move(point) + def clearShadow(self): + self.setGraphicsEffect(None) + + def setShadow(self, colorshadow, width=1, deepth=1, trace=False): -class ShadowLabel(PlainLabel): - def setShadow(self, colorshadow, width, deepth, trace=False): shadow2 = QGraphicsDropShadowEffect_multi(deepth) if trace: shadow2.setBlurRadius(width) @@ -101,9 +102,6 @@ class ShadowLabel(PlainLabel): shadow2.setColor(QColor(colorshadow)) self.setGraphicsEffect(shadow2) - -class BorderedLabel(ShadowLabel): - def __init__(self, parent=None): super().__init__(parent) self.m_outLineColor = QColor() @@ -120,17 +118,14 @@ class BorderedLabel(ShadowLabel): self._m_text = text def setColorWidth(self, outLineColor, contentColor, width, _type=0): + self.m_outLineColor = QColor(outLineColor) self.m_contentColor = QColor(contentColor) self.m_fontOutLineWidth = width self._type = _type - def move(self, point: QPoint): - point.setX(int(point.x() - self.m_fontOutLineWidth)) - point.setY(int(point.y() - self.m_fontOutLineWidth)) - super().move(point) - def adjustSize(self): + self._pix = None font = self.font() text = self.text() font_m = QFontMetrics(font) @@ -139,6 +134,30 @@ class BorderedLabel(ShadowLabel): int(font_m.height() + 2 * self.m_fontOutLineWidth), ) + def labelresetcolor(self, color, rate=1): + c1 = color + c2 = globalconfig["miaobiancolor"] + if globalconfig["zitiyangshi2"] == 2: + self.setColorWidth(c1, c2, rate * globalconfig["miaobianwidth2"]) + self.clearShadow() + elif globalconfig["zitiyangshi2"] == 3: + self.setColorWidth(c2, c1, rate * globalconfig["miaobianwidth2"]) + self.clearShadow() + elif globalconfig["zitiyangshi2"] == 1: + self.setColorWidth(c1, c2, rate * globalconfig["miaobianwidth"], 1) + self.clearShadow() + elif globalconfig["zitiyangshi2"] == 4: + self.setColorWidth(c2, c1, rate * globalconfig["miaobianwidth2"]) + self.setShadow(c2, rate * globalconfig["traceoffset"], 1, True) + elif globalconfig["zitiyangshi2"] == 0: + self.setColorWidth(None, c1, 0, 2) + self.clearShadow() + elif globalconfig["zitiyangshi2"] == 5: + self.setColorWidth(None, c2, 0, 2) + self.setShadow( + c1, rate * globalconfig["fontsize"], globalconfig["shadowforce"] + ) + def paintEvent(self, event): if not self._pix: rate = self.devicePixelRatioF() @@ -150,30 +169,39 @@ class BorderedLabel(ShadowLabel): font_m = QFontMetrics(font) painter = QPainter(self._pix) - path = QPainterPath() - path.addText( - self.m_fontOutLineWidth, - self.m_fontOutLineWidth + font_m.ascent(), - font, - text, - ) - - pen = QPen( - self.m_outLineColor, - self.m_fontOutLineWidth, - Qt.SolidLine, - Qt.RoundCap, - Qt.RoundJoin, - ) - painter.setRenderHint(QPainter.Antialiasing) - if self._type == 0: - painter.strokePath(path, pen) - painter.fillPath(path, QBrush(self.m_contentColor)) - elif self._type == 1: - painter.fillPath(path, QBrush(self.m_contentColor)) - painter.strokePath(path, pen) + path = QPainterPath() + if self._type == 2: + path.addText( + 0, + font_m.ascent(), + font, + text, + ) + painter.fillPath(path, QBrush(self.m_contentColor)) + else: + path.addText( + self.m_fontOutLineWidth, + self.m_fontOutLineWidth + font_m.ascent(), + font, + text, + ) + + pen = QPen( + self.m_outLineColor, + self.m_fontOutLineWidth, + Qt.SolidLine, + Qt.RoundCap, + Qt.RoundJoin, + ) + + if self._type == 0: + painter.strokePath(path, pen) + painter.fillPath(path, QBrush(self.m_contentColor)) + elif self._type == 1: + painter.fillPath(path, QBrush(self.m_contentColor)) + painter.strokePath(path, pen) painter = QPainter(self) painter.drawPixmap(0, 0, self._pix) @@ -235,6 +263,7 @@ class Textbrowser(QLabel): self.backcolorlabels = [] self.yinyinglabels = [] + self.yinyinglabels_idx = 0 self.yinyingpos = 0 self.yinyingposline = 0 @@ -308,10 +337,10 @@ class Textbrowser(QLabel): def showyinyingtext2(self, color, iter_context_class, pos, text): if iter_context_class not in self.iteryinyinglabelsave: - self.iteryinyinglabelsave[iter_context_class] = [] + self.iteryinyinglabelsave[iter_context_class] = [[], 0] maxh = 0 maxh2 = 9999999 - for label in self.iteryinyinglabelsave[iter_context_class]: + for label in self.iteryinyinglabelsave[iter_context_class][0]: maxh2 = min(label.pos().y(), maxh2) if label.isVisible() == False: continue @@ -334,14 +363,23 @@ class Textbrowser(QLabel): maxnewh = 0 for i in range(len(subtext)): + if self.iteryinyinglabelsave[iter_context_class][1] >= len( + self.iteryinyinglabelsave[iter_context_class][0] + ): + self.iteryinyinglabelsave[iter_context_class][0].append( + BorderedLabel(self.toplabel2) + ) maxnewh = max(maxnewh, subpos[i].y()) - _ = self.guesscreatelabel(self.toplabel2, color) + _ = self.iteryinyinglabelsave[iter_context_class][0][ + self.iteryinyinglabelsave[iter_context_class][1] + ] + _.labelresetcolor(color) _.setText(subtext[i]) _.setFont(self.font) _.adjustSize() _.move(subpos[i]) _.show() - self.iteryinyinglabelsave[iter_context_class].append(_) + self.iteryinyinglabelsave[iter_context_class][1] += 1 if maxh: if maxnewh == 0: maxnewh = maxh2 @@ -353,7 +391,7 @@ class Textbrowser(QLabel): for klass in self.iteryinyinglabelsave: if klass == iter_context_class: continue - for label in self.iteryinyinglabelsave[klass]: + for label in self.iteryinyinglabelsave[klass][0]: if label.isVisible() == False: continue if label.pos().y() > maxh: @@ -379,13 +417,16 @@ class Textbrowser(QLabel): self.textbrowser.setTextCursor(self.textcursor) tl1 = self.textbrowser.cursorRect(self.textcursor).topLeft() - _ = self.guesscreatelabel(self.toplabel2, color) + if self.yinyinglabels_idx >= len(self.yinyinglabels): + self.yinyinglabels.append(BorderedLabel(self.toplabel2)) + _ = self.yinyinglabels[self.yinyinglabels_idx] + self.yinyinglabels_idx += 1 + _.labelresetcolor(color) _.setText(block.text()[s : s + l]) _.setFont(self.font) _.adjustSize() _.move(tl1) _.show() - self.yinyinglabels.append(_) linei += 1 self.yinyingposline = linei @@ -575,6 +616,7 @@ class Textbrowser(QLabel): self.textbrowser.setTextCursor(self.textcursor) x = self.nearmerge(x, pos, fonthira, fontorig) self.settextposcursor(pos) + savetaglabels_idx = 0 for word in x: l = len(word["orig"]) @@ -589,9 +631,12 @@ class Textbrowser(QLabel): # print(tl1,tl2,word['hira'],self.textbrowser.textCursor().position()) if word["orig"] == " ": continue - self.savetaglabels.append( - self.solvejiaminglabel(word, fonthira, tl1, tl2, fascent) + if savetaglabels_idx >= len(self.savetaglabels): + self.savetaglabels.append(BorderedLabel(self.atback2)) + self.solvejiaminglabel( + self.savetaglabels[savetaglabels_idx], word, fonthira, tl1, tl2, fascent ) + savetaglabels_idx += 1 def settextposcursor(self, pos): self.textcursor.setPosition(pos) @@ -663,39 +708,8 @@ class Textbrowser(QLabel): self.settextposcursor(startpos) return res - def guesscreatelabel(self, p, color, rate=1): - c1 = color - c2 = globalconfig["miaobiancolor"] - if globalconfig["zitiyangshi2"] == 2: - label = BorderedLabel(p) - label.setColorWidth(c1, c2, rate * globalconfig["miaobianwidth2"]) - - elif globalconfig["zitiyangshi2"] == 3: - label = BorderedLabel(p) - label.setColorWidth(c2, c1, rate * globalconfig["miaobianwidth2"]) - elif globalconfig["zitiyangshi2"] == 1: - - label = BorderedLabel(p) - label.setColorWidth(c1, c2, rate * globalconfig["miaobianwidth"], 1) - elif globalconfig["zitiyangshi2"] == 4: - label = BorderedLabel(p) - label.setColorWidth(c2, c1, rate * globalconfig["miaobianwidth2"]) - label.setShadow(c2, rate * globalconfig["traceoffset"], 1, True) - elif globalconfig["zitiyangshi2"] == 0: - label = PlainLabel(p) - label.setStyleSheet("color:{}; background-color:(0,0,0,0)".format(c1)) - elif globalconfig["zitiyangshi2"] == 5: - label = ShadowLabel(p) - label.setStyleSheet("color:{}; background-color:(0,0,0,0)".format(c2)) - label.setShadow( - c1, rate * globalconfig["fontsize"], globalconfig["shadowforce"] - ) - return label - - def solvejiaminglabel(self, word, font, tl1, tl2, fh): - _ = self.guesscreatelabel( - self.atback2, globalconfig["jiamingcolor"], rate=globalconfig["kanarate"] - ) + def solvejiaminglabel(self, _: BorderedLabel, word, font, tl1, tl2, fh): + _.labelresetcolor(globalconfig["jiamingcolor"], rate=globalconfig["kanarate"]) _.setText(word["hira"]) _.setFont(font) _.adjustSize() @@ -725,22 +739,16 @@ class Textbrowser(QLabel): for label in self.searchmasklabels_clicked: label.hide() for label in self.savetaglabels: - label.deleteLater() - del label - self.savetaglabels.clear() + label.hide() + + self.yinyinglabels_idx = 0 for label in self.yinyinglabels: - label.deleteLater() - del label - self.yinyinglabels.clear() + label.hide() for klass, labels in self.iteryinyinglabelsave.items(): - for label in labels: - label.deleteLater() - del label - self.iteryinyinglabelsave.clear() + for label in labels[0]: + label.hide() + labels[1] = 0 self.yinyingpos = 0 self.yinyingposline = 0 self.cleared = True - self.textbrowser.setText("") - - # self.shadowlabel.setText('') - # self.shadowlabel.savetext='' + self.textbrowser.clear() diff --git a/LunaTranslator/LunaTranslator/network/libcurl/requests.py b/LunaTranslator/LunaTranslator/network/libcurl/requests.py index d7477167..765fd9d9 100644 --- a/LunaTranslator/LunaTranslator/network/libcurl/requests.py +++ b/LunaTranslator/LunaTranslator/network/libcurl/requests.py @@ -5,19 +5,12 @@ from network.requests_common import * from traceback import print_exc -class autostatus: - def __init__(self, ref) -> None: - self.ref = ref - ref._status = 1 - - def __del__(self): - self.ref._status = 0 - - class Response(ResponseBase): def __init__(self): super().__init__() self.last_error = 0 + self.keeprefs = [] + self.queue = queue.Queue() def iter_content_impl(self, chunk_size=1): @@ -62,15 +55,6 @@ def ExceptionFilter(func): class Session(Sessionbase): - def __init__(self) -> None: - super().__init__() - self._status = 0 - self.curl = AutoCURLHandle(curl_easy_init()) - curl_easy_setopt(self.curl, CURLoption.CURLOPT_COOKIEJAR, "") - curl_easy_setopt( - self.curl, CURLoption.CURLOPT_USERAGENT, self.UA.encode("utf8") - ) - def raise_for_status(self): if self.last_error: raise CURLException(self.last_error) @@ -120,18 +104,14 @@ class Session(Sessionbase): verify, timeout, ): - - if self._status == 0: - curl = self.curl - __ = autostatus(self) + curl = AutoCURLHandle(curl_easy_init()) + curl_easy_setopt(curl, CURLoption.CURLOPT_COOKIEJAR, "") + curl_easy_setopt(curl, CURLoption.CURLOPT_USERAGENT, self.UA.encode("utf8")) + if cookies: + cookies.update(self.cookies) else: - # 不能多线程同时复用同一个curl对象 - curl = AutoCURLHandle(curl_easy_duphandle(self.curl)) - if cookies: - cookies.update(self.cookies) - else: - cookies = self.cookies - curl_easy_reset(curl) + cookies = self.cookies + if cookies: cookie = self._parsecookie(cookies) curl_easy_setopt(curl, CURLoption.CURLOPT_COOKIE, cookie.encode("utf8")) @@ -171,7 +151,7 @@ class Session(Sessionbase): curl_easy_setopt(curl, CURLoption.CURLOPT_POSTFIELDSIZE, datalen) resp = Response() - + resp.keeprefs.append(curl) if stream: def WriteMemoryCallback(queue, contents, size, nmemb, userp): @@ -181,25 +161,23 @@ class Session(Sessionbase): _content = [] _headers = [] - resp.queue = queue.Queue() headerqueue = queue.Queue() - resp.keepref1 = WRITEFUNCTION( - functools.partial(WriteMemoryCallback, resp.queue) - ) - resp.keepref2 = WRITEFUNCTION( + keepref1 = WRITEFUNCTION(functools.partial(WriteMemoryCallback, resp.queue)) + keepref2 = WRITEFUNCTION( functools.partial(WriteMemoryCallback, headerqueue) ) curl_easy_setopt( curl, CURLoption.CURLOPT_WRITEFUNCTION, - cast(resp.keepref1, c_void_p).value, + cast(keepref1, c_void_p).value, ) curl_easy_setopt( curl, CURLoption.CURLOPT_HEADERFUNCTION, - cast(resp.keepref2, c_void_p).value, + cast(keepref2, c_void_p).value, ) + resp.keeprefs += [keepref1, keepref2] def ___perform(): error = False @@ -250,29 +228,25 @@ class Session(Sessionbase): _content = [] _headers = [] - resp.keepref1 = WRITEFUNCTION( - functools.partial(WriteMemoryCallback, _content) - ) - resp.keepref2 = WRITEFUNCTION( - functools.partial(WriteMemoryCallback, _headers) - ) + keepref1 = WRITEFUNCTION(functools.partial(WriteMemoryCallback, _content)) + keepref2 = WRITEFUNCTION(functools.partial(WriteMemoryCallback, _headers)) curl_easy_setopt( curl, CURLoption.CURLOPT_WRITEFUNCTION, - cast(resp.keepref1, c_void_p).value, + cast(keepref1, c_void_p).value, ) curl_easy_setopt( curl, CURLoption.CURLOPT_HEADERFUNCTION, - cast(resp.keepref2, c_void_p).value, + cast(keepref2, c_void_p).value, ) - + resp.keeprefs += [keepref1, keepref2] self._perform(curl) resp.content = b"".join(_content) resp.headers = self._update_header_cookie(b"".join(_headers).decode("utf8")) resp.status_code = self._getStatusCode(curl) - + resp.last_error = self.last_error resp.cookies = self.cookies return resp diff --git a/LunaTranslator/LunaTranslator/textsource/texthook.py b/LunaTranslator/LunaTranslator/textsource/texthook.py index e3570203..003dcae2 100644 --- a/LunaTranslator/LunaTranslator/textsource/texthook.py +++ b/LunaTranslator/LunaTranslator/textsource/texthook.py @@ -234,8 +234,6 @@ class texthook(basetext): dll = os.path.abspath( "./files/plugins/LunaHook/LunaHook{}.dll".format(arch) ) - print(injecter, os.path.exists(injecter)) - print(dll, os.path.exists(dll)) # subprocess.Popen('"{}" dllinject {} "{}"'.format(injecter,pid,dll)) injectdll(injectpids, injecter, dll) diff --git a/LunaTranslator/LunaTranslator/translator/deepl_dev.py b/LunaTranslator/LunaTranslator/translator/deepl_dev.py index 685d56dd..30766f20 100644 --- a/LunaTranslator/LunaTranslator/translator/deepl_dev.py +++ b/LunaTranslator/LunaTranslator/translator/deepl_dev.py @@ -12,5 +12,5 @@ class TS(basetransdev): ) ) return self.wait_for_result( - r"""document.evaluate('//*[@id="headlessui-tabs-panel-7"]/div/div[1]/section/div/div[2]/div[3]/section/div[1]/d-textarea/div',document).iterateNext().textContent""" + r"""document.querySelector("#textareasContainer > div.rounded-ee-inherit.relative.min-h-\\[240px\\].min-w-0.md\\:min-h-\\[clamp\\(250px\\,50vh\\,557px\\)\\].mobile\\:min-h-0.mobile\\:flex-1.max-\\[768px\\]\\:min-h-\\[375px\\] > section > div.rounded-inherit.mobile\\:min-h-0.relative.flex.flex-1.flex-col > d-textarea").textContent""" ) diff --git a/LunaTranslator/LunaTranslator/translator/dev_youdao.py b/LunaTranslator/LunaTranslator/translator/dev_youdao.py index daffaab9..44b80fbe 100644 --- a/LunaTranslator/LunaTranslator/translator/dev_youdao.py +++ b/LunaTranslator/LunaTranslator/translator/dev_youdao.py @@ -5,9 +5,11 @@ class TS(basetransdev): target_url = "https://fanyi.youdao.com/" def translate(self, content): - self.Runtime_evaluate( - '(a=document.querySelector("#TextTranslate > div.source > a"))?a.click():"";i=document.querySelector("#js_fanyi_input");i.innerText=`{}`;event = new Event("input", {{bubbles: true, cancelable: true }});i.dispatchEvent(event);'.format( + 'document.querySelector("#TextTranslate > div.source > div.text-translate-top-right > a").click()' + ) + self.Runtime_evaluate( + 'i=document.querySelector("#js_fanyi_input");i.innerText=`{}`;event = new Event("input", {{bubbles: true, cancelable: true }});i.dispatchEvent(event);'.format( content ) ) diff --git a/LunaTranslator/LunaTranslator/translator/lingva.py b/LunaTranslator/LunaTranslator/translator/lingva.py index 77cf2eb6..dae3b1c7 100644 --- a/LunaTranslator/LunaTranslator/translator/lingva.py +++ b/LunaTranslator/LunaTranslator/translator/lingva.py @@ -21,11 +21,7 @@ class TS(basetrans): # self.url=self.config['host']+'_next/data/{}/%s/%s/%s.json'.format(_id) def translate(self, content): # print(self.url%(self.srclang,self.tgtlang,urllib.parse.quote(content))) - print( - "https://" - + self.config["host"] - + "/api/v1/%s/%s/%s" % (self.srclang, self.tgtlang, quote_plus(content)) - ) + x = self.session.get( "https://" + self.config["host"] diff --git a/LunaTranslator/LunaTranslator/translator/tx_dev.py b/LunaTranslator/LunaTranslator/translator/tx_dev.py index a5a4dc46..6fcb76d6 100644 --- a/LunaTranslator/LunaTranslator/translator/tx_dev.py +++ b/LunaTranslator/LunaTranslator/translator/tx_dev.py @@ -29,8 +29,10 @@ class TS(basetransdev): else: tgtidx = 1 self.Runtime_evaluate( - """document.querySelector('div.textpanel-tool.tool-close').click(); - document.querySelector("#language-button-group-source > div.language-button-dropdown.language-source > ul > li:nth-child(1) > span").click(); + 'document.querySelector("div.textpanel-tool.tool-close").click()' + ) + self.Runtime_evaluate( + """document.querySelector("#language-button-group-source > div.language-button-dropdown.language-source > ul > li:nth-child(1) > span").click(); document.querySelector("#language-button-group-target > div.language-button-dropdown.language-target > ul > li:nth-child({}) > span"); document.getElementsByClassName('textinput')[0].value=`{}`; document.getElementsByClassName('language-translate-button')[0].click(); diff --git a/plugins/CMakeLists.txt b/plugins/CMakeLists.txt index 5883fb45..a3552822 100644 --- a/plugins/CMakeLists.txt +++ b/plugins/CMakeLists.txt @@ -29,7 +29,7 @@ include(generate_product_version) set(VERSION_MAJOR 2) set(VERSION_MINOR 52) -set(VERSION_PATCH 5) +set(VERSION_PATCH 6) add_library(pch pch.cpp) target_precompile_headers(pch PUBLIC pch.h)