This commit is contained in:
恍兮惚兮 2024-06-21 02:08:41 +08:00
parent cb64beb810
commit 89de08bea9
9 changed files with 94 additions and 32 deletions

View File

@ -29,9 +29,7 @@ if __name__ == "__main__":
) # 中文字符下不能自动加载 ) # 中文字符下不能自动加载
QApplication.setAttribute(Qt.ApplicationAttribute.AA_EnableHighDpiScaling) QApplication.setAttribute(Qt.ApplicationAttribute.AA_EnableHighDpiScaling)
QApplication.setAttribute(Qt.ApplicationAttribute.AA_UseHighDpiPixmaps) QApplication.setAttribute(Qt.ApplicationAttribute.AA_UseHighDpiPixmaps)
if os.path.exists( if gobject.testuseqwebengine():
"./LunaTranslator/runtime/PyQt5/Qt5/bin/Qt5WebEngineCore.dll"
):
QApplication.setAttribute( QApplication.setAttribute(
Qt.ApplicationAttribute.AA_ShareOpenGLContexts Qt.ApplicationAttribute.AA_ShareOpenGLContexts
) # maybe use qwebengine ) # maybe use qwebengine

View File

@ -29,3 +29,9 @@ def dopathexists(file):
def overridepathexists(): def overridepathexists():
# win7上如果假如没有D盘然后os.path.exists("D:/...")就会弹窗说不存在D盘 # win7上如果假如没有D盘然后os.path.exists("D:/...")就会弹窗说不存在D盘
os.path.exists = dopathexists os.path.exists = dopathexists
def testuseqwebengine():
return os.path.exists(
"./LunaTranslator/runtime/PyQt5/Qt5/bin/Qt5WebEngineCore.dll"
) or (len(sys.argv) and sys.argv[-1] == "test")

View File

@ -1,6 +1,6 @@
from qtsymbols import * from qtsymbols import *
import platform, functools, sys, os import platform, functools, sys, os
import winsharedutils import winsharedutils, gobject
from myutils.config import globalconfig, _TR, static_data, _TRL from myutils.config import globalconfig, _TR, static_data, _TRL
from myutils.wrapper import threader from myutils.wrapper import threader
from myutils.utils import makehtml, getimageformatlist from myutils.utils import makehtml, getimageformatlist
@ -141,7 +141,7 @@ def createimageview(self):
def setTab_aboutlazy(self, basel): def setTab_aboutlazy(self, basel):
webviews = ["IEFrame", "WebView2"] webviews = ["IEFrame", "WebView2"]
if os.path.exists("./LunaTranslator/runtime/PyQt5/Qt5/bin/Qt5WebEngineCore.dll"): if gobject.testuseqwebengine():
webviews.append("QWebEngine") webviews.append("QWebEngine")
grid2 = [ grid2 = [
[ [

View File

@ -176,7 +176,8 @@ def createinternalfontsettings(self, group, _type):
def resetgroudswitchcallback(self, group): def resetgroudswitchcallback(self, group):
if group == "QWebEngine":
group = "webview"
try: try:
self.goodfontgroupswitch.currentIndexChanged.disconnect() self.goodfontgroupswitch.currentIndexChanged.disconnect()
except: except:
@ -220,7 +221,11 @@ def creategoodfontwid(self):
def xianshigrid(self): def xianshigrid(self):
visengine = ["Webview2", "Qt"]
visengine_internal = ["webview", "textbrowser"]
if gobject.testuseqwebengine():
visengine.append("QWebEngine")
visengine_internal.append("QWebEngine")
textgrid = [ textgrid = [
[ [
( (
@ -280,10 +285,10 @@ def xianshigrid(self):
("显示引擎_重启生效", 3), ("显示引擎_重启生效", 3),
( (
D_getsimplecombobox( D_getsimplecombobox(
["Webview2", "Qt"], visengine,
globalconfig, globalconfig,
"rendertext_using", "rendertext_using",
internallist=["webview", "textbrowser"], internallist=visengine_internal,
callback=functools.partial( callback=functools.partial(
resetgroudswitchcallback, self resetgroudswitchcallback, self
), ),

View File

@ -729,7 +729,8 @@ class searchwordW(closeashidewindow):
if self.current != timestamp: if self.current != timestamp:
return return
if res is None: if res is None:
self.cache_results[k] = res return
self.cache_results[k] = res
thisp = globalconfig["cishu"][k]["args"]["priority"] thisp = globalconfig["cishu"][k]["args"]["priority"]
idx = 0 idx = 0

View File

@ -32,9 +32,10 @@ class Textbrowser(QLabel):
self.contentsChanged.emit(QSize(size.width(), size.height())) self.contentsChanged.emit(QSize(size.width(), size.height()))
def loadinternal(self): def loadinternal(self):
tb = importlib.import_module( __ = globalconfig["rendertext_using"]
f'rendertext.{globalconfig["rendertext_using"]}' if __ == "QWebEngine":
).TextBrowser __ = "webview"
tb = importlib.import_module(f"rendertext.{__}").TextBrowser
try: try:
self.textbrowser = tb(self) self.textbrowser = tb(self)
except webview_exception: except webview_exception:

View File

@ -907,6 +907,15 @@ class abstractwebview(QWidget):
def set_zoom(self, zoom): def set_zoom(self, zoom):
pass pass
def get_zoom(self):
return 1
def bind(self, fname, func):
pass
def eval(self, js, retsaver=None):
pass
def set_transparent_background(self): def set_transparent_background(self):
pass pass
@ -970,6 +979,12 @@ class WebivewWidget(abstractwebview):
self.__token, self.__token,
) )
def bind(self, fname, func):
self.webview.bind(fname, func)
def eval(self, js):
self.webview.eval(js)
def get_controller(self): def get_controller(self):
return self.webview.get_native_handle( return self.webview.get_native_handle(
webview_native_handle_kind_t.WEBVIEW_NATIVE_HANDLE_KIND_BROWSER_CONTROLLER webview_native_handle_kind_t.WEBVIEW_NATIVE_HANDLE_KIND_BROWSER_CONTROLLER
@ -1013,14 +1028,11 @@ class WebivewWidget(abstractwebview):
winsharedutils.put_PreferredColorScheme(self.get_controller(), dl) winsharedutils.put_PreferredColorScheme(self.get_controller(), dl)
def set_zoom(self, zoom): def set_zoom(self, zoom):
self.put_ZoomFactor(zoom)
def get_ZoomFactor(self):
return winsharedutils.get_ZoomFactor(self.get_controller())
def put_ZoomFactor(self, zoom):
winsharedutils.put_ZoomFactor(self.get_controller(), zoom) winsharedutils.put_ZoomFactor(self.get_controller(), zoom)
def get_zoom(self):
return winsharedutils.get_ZoomFactor(self.get_controller())
def _on_load(self, href): def _on_load(self, href):
self.on_load.emit(href) self.on_load.emit(href)
@ -1044,14 +1056,15 @@ class WebivewWidget(abstractwebview):
class QWebWrap(abstractwebview): class QWebWrap(abstractwebview):
def __init__(self) -> None: def __init__(self, p=None) -> None:
super().__init__() super().__init__(p)
from PyQt5.QtWebEngineWidgets import QWebEngineView from PyQt5.QtWebEngineWidgets import QWebEngineView
self.internal = QWebEngineView(self) self.internal = QWebEngineView(self)
self.internal.page().urlChanged.connect( # self.internal.page().urlChanged.connect(
lambda qurl: self.on_load.emit(qurl.url()) # lambda qurl: self.on_load.emit(qurl.url())
) # )
self.internal.loadFinished.connect(self._loadFinish)
self.internal_zoom = 1 self.internal_zoom = 1
t = QTimer(self) t = QTimer(self)
t.setInterval(100) t.setInterval(100)
@ -1059,10 +1072,24 @@ class QWebWrap(abstractwebview):
t.timeout.emit() t.timeout.emit()
t.start() t.start()
def _loadFinish(self):
self.on_load.emit(self.internal.url().url())
def eval(self, js, retsaver=None):
if not retsaver:
retsaver = lambda _: 1
self.internal.page().runJavaScript(js, retsaver)
def set_transparent_background(self):
self.internal.page().setBackgroundColor(Qt.GlobalColor.transparent)
def set_zoom(self, zoom): def set_zoom(self, zoom):
self.internal_zoom = zoom self.internal_zoom = zoom
self.internal.setZoomFactor(zoom) self.internal.setZoomFactor(zoom)
def get_zoom(self):
return self.internal.zoomFactor()
def __getzoomfactor(self): def __getzoomfactor(self):
z = self.internal.zoomFactor() z = self.internal.zoomFactor()
if z != self.internal_zoom: if z != self.internal_zoom:

View File

@ -4,7 +4,7 @@ from rendertext.somefunctions import dataget
import gobject, uuid, json, os import gobject, uuid, json, os
from urllib.parse import quote from urllib.parse import quote
from myutils.config import globalconfig from myutils.config import globalconfig
from gui.usefulwidget import WebivewWidget from gui.usefulwidget import WebivewWidget, QWebWrap
testsavejs = False testsavejs = False
@ -18,21 +18,28 @@ class TextBrowser(QWidget, dataget):
def __init__(self, parent) -> None: def __init__(self, parent) -> None:
gobject.refwebview = self gobject.refwebview = self
super().__init__(parent) super().__init__(parent)
self.webivewwidget = WebivewWidget(self) if globalconfig["rendertext_using"] == "QWebEngine":
self.webivewwidget = QWebWrap(self)
else:
self.webivewwidget = WebivewWidget(self)
if isinstance(self.webivewwidget, QWebWrap):
# webview2当会执行alert之类的弹窗js时若qt窗口不可视会卡住
self.webivewwidget.on_load.connect(self.__loadextra)
self.webivewwidget.navigate( self.webivewwidget.navigate(
os.path.abspath(r"LunaTranslator\rendertext\webview.html") os.path.abspath(r"LunaTranslator\rendertext\webview.html")
) )
self.webivewwidget.set_transparent_background() self.webivewwidget.set_transparent_background()
self.webivewwidget.webview.bind("calllunaclickedword", self.calllunaclickedword) self.webivewwidget.bind("calllunaclickedword", self.calllunaclickedword)
self.webivewwidget.webview.bind( self.webivewwidget.bind("calllunaheightchange", self.calllunaheightchange)
"calllunaheightchange", self.calllunaheightchange
)
self.saveiterclasspointer = {} self.saveiterclasspointer = {}
self.isfirst = True self.isfirst = True
def showEvent(self, e): def showEvent(self, e):
if not self.isfirst: if not self.isfirst:
return return
if not isinstance(self.webivewwidget, WebivewWidget):
return
self.isfirst = False self.isfirst = False
self.__loadextra(0) self.__loadextra(0)
self.webivewwidget.on_load.connect(self.__loadextra) self.webivewwidget.on_load.connect(self.__loadextra)
@ -44,7 +51,7 @@ class TextBrowser(QWidget, dataget):
def debugeval(self, js): def debugeval(self, js):
# print(js) # print(js)
self.webivewwidget.webview.eval(js) self.webivewwidget.eval(js)
# js api # js api
@ -65,6 +72,18 @@ class TextBrowser(QWidget, dataget):
self.debugeval( self.debugeval(
f'create_internal_text("{style}","{styleargs}","{_id}","{text}","{args}");' f'create_internal_text("{style}","{styleargs}","{_id}","{text}","{args}");'
) )
self._qweb_proactive_queryheigh()
def _qweb_proactive_queryheigh(self):
if not isinstance(self.webivewwidget, QWebWrap):
return
def __xxx(h):
self.calllunaheightchange(h)
self.webivewwidget.eval(
'document.getElementById("luna_root_div").offsetHeight', __xxx
)
def create_internal_rubytext(self, style, styleargs, _id, tag, args): def create_internal_rubytext(self, style, styleargs, _id, tag, args):
tag = quote(json.dumps(tag)) tag = quote(json.dumps(tag))
@ -74,12 +93,14 @@ class TextBrowser(QWidget, dataget):
f'create_internal_rubytext("{style}","{styleargs}","{_id}","{tag}","{args}");' f'create_internal_rubytext("{style}","{styleargs}","{_id}","{tag}","{args}");'
) )
self._qweb_proactive_queryheigh()
# js api end # js api end
# native api # native api
def calllunaheightchange(self, h): def calllunaheightchange(self, h):
self.contentsChanged.emit( self.contentsChanged.emit(
QSize(self.width(), int(h * self.webivewwidget.get_ZoomFactor())) QSize(self.width(), int(h * self.webivewwidget.get_zoom()))
) )
def calllunaclickedword(self, packedwordinfo): def calllunaclickedword(self, packedwordinfo):

View File

@ -0,0 +1,3 @@
@echo off
%LOCALAPPDATA%\Programs\Python\Python37\python.exe -B LunaTranslator\LunaTranslator_main.py test
pause