diff --git a/LunaTranslator/LunaTranslator/LunaTranslator_main.py b/LunaTranslator/LunaTranslator/LunaTranslator_main.py index d4b8619f..0c4b3fb8 100644 --- a/LunaTranslator/LunaTranslator/LunaTranslator_main.py +++ b/LunaTranslator/LunaTranslator/LunaTranslator_main.py @@ -28,6 +28,8 @@ if __name__ == "__main__" : os.mkdir('./cache/screenshot') if os.path.exists('./cache/tts')==False: os.mkdir('./cache/tts') + if os.path.exists('./cache/icon')==False: + os.mkdir('./cache/icon') from myutils.config import _TR,static_data,testpriv,globalconfig diff --git a/LunaTranslator/LunaTranslator/cishu/goo.py b/LunaTranslator/LunaTranslator/cishu/goo.py index 4563248c..05dc08ad 100644 --- a/LunaTranslator/LunaTranslator/cishu/goo.py +++ b/LunaTranslator/LunaTranslator/cishu/goo.py @@ -2,7 +2,7 @@ from myutils.config import globalconfig import requests from urllib.parse import quote import re -from myutils.utils import getproxy +from myutils.proxy import getproxy from traceback import print_exc class goo: diff --git a/LunaTranslator/LunaTranslator/cishu/mojidict.py b/LunaTranslator/LunaTranslator/cishu/mojidict.py index 32454f4d..4f1c4319 100644 --- a/LunaTranslator/LunaTranslator/cishu/mojidict.py +++ b/LunaTranslator/LunaTranslator/cishu/mojidict.py @@ -1,5 +1,5 @@ import requests -from myutils.utils import getproxy +from myutils.proxy import getproxy class mojidict: def search(self, word): diff --git a/LunaTranslator/LunaTranslator/cishu/weblio.py b/LunaTranslator/LunaTranslator/cishu/weblio.py index 2e430950..75468de9 100644 --- a/LunaTranslator/LunaTranslator/cishu/weblio.py +++ b/LunaTranslator/LunaTranslator/cishu/weblio.py @@ -2,7 +2,7 @@ from myutils.config import globalconfig import requests from urllib.parse import quote -from myutils.utils import getproxy +from myutils.proxy import getproxy import re,time from traceback import print_exc class weblio: diff --git a/LunaTranslator/LunaTranslator/cishu/youdao.py b/LunaTranslator/LunaTranslator/cishu/youdao.py index 7a403966..d44e3f61 100644 --- a/LunaTranslator/LunaTranslator/cishu/youdao.py +++ b/LunaTranslator/LunaTranslator/cishu/youdao.py @@ -2,7 +2,7 @@ from myutils.config import globalconfig,static_data import requests from urllib.parse import quote import re -from myutils.utils import getproxy +from myutils.proxy import getproxy from traceback import print_exc class youdao: @property @@ -16,50 +16,5 @@ class youdao: return '' def search(self,word): text=requests.get('https://dict.youdao.com/result?word={}&lang={}'.format(quote(word),self.srclang), proxies= getproxy()).text - - fnd=re.findall('
([\\s\\S]*?)(.*?)
',text) - save=[] - try: - asave=[] - for ares in fnd[0]: - - res=re.findall('>(.*?)<',ares+'<') - for _ in res: - for __ in _: - if __ !='': - - asave.append(__) - save.append(''.join(asave)) - except: - print_exc() - - fnd=re.findall('
([\\s\\S]*?)
',text) - - try: - for _,ares in fnd: - asave=[] - res=re.findall('>(.*?)<',ares+'<') - for __ in res: - - if __ !='': - - asave.append(__) - save.append('
'.join(asave)) - except: - print_exc() - - fnd=re.findall('
  • ([\\s\\S]*?)
  • ',text) - try: - for _,ares in fnd: - asave=[] - res=re.findall('>(.*?)<',ares+'<') - for __ in res: - - if __ !='': - - asave.append(__) - - save.append('
    '.join(asave)) - except: - print_exc() - return '

    '.join(save) \ No newline at end of file + fnd=re.findall('
    ([\\s\\S]*?)
    ',text) + return fnd[0][1] \ No newline at end of file diff --git a/LunaTranslator/LunaTranslator/gui/dialog_savedgame.py b/LunaTranslator/LunaTranslator/gui/dialog_savedgame.py index 3f700baf..e7df8dac 100644 --- a/LunaTranslator/LunaTranslator/gui/dialog_savedgame.py +++ b/LunaTranslator/LunaTranslator/gui/dialog_savedgame.py @@ -7,10 +7,10 @@ from PyQt5.QtWidgets import QHBoxLayout, QTableView, QAbstractItemView, QLabe import importlib import windows from PyQt5.QtCore import QPoint, QRect, QSize, Qt,pyqtSignal,QCoreApplication -import os,subprocess +import os,hashlib from PyQt5 import QtCore, QtGui, QtWidgets -from PyQt5.QtWidgets import QApplication, QLayout, QSizePolicy, QWidget, QGridLayout -from PyQt5.QtGui import QPalette, QColor,QResizeEvent,QIcon,QPixmap +from PyQt5.QtWidgets import QApplication, QLayout, QSizePolicy, QWidget, QGridLayout ,QMenu,QAction,QTabBar +from PyQt5.QtGui import QIntValidator, QColor,QResizeEvent,QIcon,QPixmap from PyQt5.QtCore import Qt from gui.usefulwidget import getsimplecombobox,getspinbox,getcolorbutton,getsimpleswitch,getspinbox,selectcolor from PyQt5.QtCore import QPoint, QRect, QSize, Qt,pyqtSignal @@ -26,7 +26,9 @@ from myutils.config import _TR,_TRL,globalconfig,static_data import winsharedutils from myutils.wrapper import Singleton_close,Singleton,threader from myutils.utils import checkifnewgame ,loadfridascriptslist +from myutils.proxy import getproxy from gui.usefulwidget import yuitsu_switch,saveposwindow,getboxlayout +from myutils.vndb import parsehtmlmethod class ItemWidget(QWidget): focuschanged=pyqtSignal(bool,str) doubleclicked=pyqtSignal(str) @@ -237,30 +239,129 @@ def opendir( k): os.startfile(os.path.dirname(k)) except: pass +class CustomTabBar(QTabBar): + lastclick=pyqtSignal() + def __init__(self, parent=None): + super().__init__(parent) + + def mousePressEvent(self, event): + index = self.tabAt(event.pos()) + if index == self.count() - 1 and event.button() == Qt.LeftButton: + self.lastclick.emit() + else: + super().mousePressEvent(event) @Singleton class browserdialog(QDialog): - def resizeEvent(self, a0: QResizeEvent) -> None: - try: - self.browser.resize(0,0,a0.size().width(),a0.size().height()) - except: - pass + def parsehtml(self,exepath): try: - parsehtmlmethod=importlib.import_module('webresource.'+savehook_new_data[exepath]['infomethod']).parsehtmlmethod - newpath=parsehtmlmethod(savehook_new_data[exepath]['infopath']) + newpath=parsehtmlmethod(savehook_new_data[exepath]['vid'],savehook_new_data[exepath]['infopath']) except: + print_exc() newpath=savehook_new_data[exepath]['infopath'] if newpath[:4].lower()!='http': newpath=os.path.abspath(newpath) return newpath def __init__(self, parent,exepath ) -> None: super().__init__(parent, Qt.WindowMinMaxButtonsHint|Qt.WindowCloseButtonHint) - self.browser=winsharedutils.HTMLBrowser(int(self.winId())) + self.exepath=exepath + vbox=QVBoxLayout() + vbox.setContentsMargins(0,0,0,0) + self.setLayout(vbox) + class QWW(QWidget): + def resizeEvent(self, a0: QResizeEvent) -> None: + try: + self.browser.resize(0,0,a0.size().width(),a0.size().height()) + except: + pass + qww=QWW(self) + self.browser=qww.browser=winsharedutils.HTMLBrowser(int(qww.winId())) self.setWindowTitle(savehook_new_data[exepath]['title']) - self.browser.navigate((self.parsehtml( exepath))) - + self.nettab=QTabWidget() + self.nettab.setFixedHeight(self.nettab.tabBar().height()+10) + tabBar = CustomTabBar(self) + self.nettab.setTabBar(tabBar) + tabBar.lastclick.connect(self.lastclicked) + #self.nettab.setSizePolicy( QSizePolicy.Preferred,QSizePolicy.Fixed) + self.nettab.addTab(QWidget(),"vndb") + for lnk in savehook_new_data[self.exepath]['relationlinks']: + self.nettab.addTab(QWidget(),lnk[0]) + self.nettab.addTab(QWidget(),"+") + self.nettab.currentChanged.connect(self.changetab) + self.nettab.setContextMenuPolicy(Qt.CustomContextMenu) + self.nettab.customContextMenuRequested.connect(self.showmenu) + self.changetab(0) + vbox.addWidget(self.nettab) + vbox.addWidget(qww) self.resize(1300,800) self.show() + def showmenu(self,p): + tab_index = self.nettab.tabBar().tabAt(p) + if tab_index ==0 or tab_index==self.nettab.count()-1: + return + menu=QMenu(self ) + shanchu=QAction(_TR("删除")) + cache=QAction(_TR("缓存")) + menu.addAction(cache) + menu.addAction(shanchu) + action=menu.exec(self.mapToGlobal(p)) + if action==shanchu: + self.nettab.setCurrentIndex(0) + self.nettab.removeTab(tab_index) + savehook_new_data[self.exepath]['relationlinks'].pop(tab_index-1) + elif action==cache: + def cachehtml(exepath,idx): + url=savehook_new_data[exepath]['relationlinks'][idx][1] + import requests + + headers = { + 'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7', + 'accept-language': 'zh-CN,zh;q=0.9,ar;q=0.8,sq;q=0.7', + 'cache-control': 'no-cache', + 'pragma': 'no-cache', + 'sec-ch-ua': '"Not_A Brand";v="8", "Chromium";v="120", "Google Chrome";v="120"', + 'sec-ch-ua-mobile': '?0', + 'sec-ch-ua-platform': '"Windows"', + 'sec-fetch-dest': 'document', + 'sec-fetch-mode': 'navigate', + 'sec-fetch-site': 'same-origin', + 'sec-fetch-user': '?1', + 'upgrade-insecure-requests': '1', + 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36', + } + + response = requests.get(url, headers=headers,proxies=getproxy()) + os.makedirs('./cache/cachehtml',exist_ok=True) + fn='./cache/cachehtml/'+hashlib.md5(url.encode('utf8')).hexdigest()+'.html' + with open(fn,'w',encoding='utf8') as ff: + ff.write(response.text.replace('',''.format(url)).replace('',''.format(url))) + for i in range(len(savehook_new_data[exepath]['relationlinks'])): + if url==savehook_new_data[exepath]['relationlinks'][i][1]: + if len(savehook_new_data[exepath]['relationlinks'][i])==3: + savehook_new_data[exepath]['relationlinks'][i][2]=fn + else: + savehook_new_data[exepath]['relationlinks'][i].append(fn) + threading.Thread(target=cachehtml,args=(self.exepath,tab_index-1)).start() + def lastclicked(self): + def callback(texts): + if len(texts[0].strip()) and len(texts[1].strip()): + savehook_new_data[self.exepath]['relationlinks'].append(texts) + self.nettab.insertTab(self.nettab.count()-1,QWidget(),texts[0]) + gobject.baseobject.Prompt.call.emit(_TR('添加关联页面'),_TR('页面类型_页面链接'),[['vndb/2df/...'],'about:blank'],[callback]) + def changetab(self,idx): + if idx==0: + try: + self.browser.navigate((self.parsehtml( self.exepath))) + except: + self.browser.navigate('about:blank') + else: + lnks=savehook_new_data[self.exepath]['relationlinks'][idx-1] + if len(lnks)==3 and os.path.exists(lnks[2]): + link=os.path.abspath(lnks[2]) + else: + link=lnks[1] + print(link) + self.browser.navigate(link) @Singleton class dialog_setting_game(QDialog): def selectexe(self ): @@ -274,13 +375,13 @@ class dialog_setting_game(QDialog): savehook_new_list[savehook_new_list.index(self.exepath)]=res savehook_new_data[res]=savehook_new_data[self.exepath] savehook_new_data.pop(self.exepath) - _icon=getExeIcon(res) + _icon=getExeIcon(res,cache=True) if self.item: self.item.savetext=res self.table.setIndexWidget(self.model.index(self.model.indexFromItem(self.item).row(), 1),getcolorbutton('','',functools.partial( opendir,res),qicon=_icon )) if self.gametitleitme: if savehook_new_data[res]['imagepath'] is None: - self.gametitleitme.setimg(getExeIcon(res,False)) + self.gametitleitme.setimg(getExeIcon(res,False,cache=True)) self.gametitleitme.connectexepath(res) self.setWindowIcon(_icon) @@ -299,6 +400,7 @@ class dialog_setting_game(QDialog): titleedit=QLineEdit(savehook_new_data[exepath]['title']) def _titlechange(x): savehook_new_data[exepath]['title']=x + savehook_new_data[exepath]['searchnoresulttime']=0 self.setWindowTitle(x) gametitleitme.settitle(x) titleedit.textChanged.connect(_titlechange) @@ -320,12 +422,26 @@ class dialog_setting_game(QDialog): formLayout.addLayout(getboxlayout([ QLabel(_TR("封面")),imgpath, - getcolorbutton('','',selectimg,icon='fa.gear',constcolor="#FF69B4") + getcolorbutton('','',selectimg,icon='fa.gear',constcolor="#FF69B4"), + + ])) - statiswids=[QLabel(_TR("统计信息")),getcolorbutton('','',lambda:dialog_statistic(self,exepath),icon='fa.bar-chart',constcolor="#FF69B4")] - if savehook_new_data[exepath]['infopath']: - statiswids+=[QLabel(_TR("游戏信息")),getcolorbutton('','',lambda:browserdialog(self,exepath),icon='fa.book',constcolor="#FF69B4")] + vndbid=QLineEdit(str(savehook_new_data[exepath]['vid'])) + vndbid.setValidator(QIntValidator()) + vndbid.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed) + + def changevid(exepath,text): + savehook_new_data[exepath]['vid']=int(text) + savehook_new_data[exepath]['infopath']=None + savehook_new_data[exepath]['searchnoresulttime']=0 + #savehook_new_data[exepath]['imagepath']=None + vndbid.textEdited.connect(functools.partial(changevid,exepath)) + + statiswids=[ + QLabel(_TR("统计信息")),getcolorbutton('','',lambda:dialog_statistic(self,exepath),icon='fa.bar-chart',constcolor="#FF69B4"), + QLabel(_TR("vndbid")),vndbid,getcolorbutton('','',lambda: browserdialog(self,exepath),icon='fa.book',constcolor="#FF69B4") + ] formLayout.addLayout(getboxlayout(statiswids)) editpath=QLineEdit(exepath) editpath.setReadOnly(True) @@ -336,7 +452,7 @@ class dialog_setting_game(QDialog): self.editpath=editpath self.setWindowTitle(savehook_new_data[exepath]['title']) self.resize(QSize(600,200)) - self.setWindowIcon(getExeIcon(exepath)) + self.setWindowIcon(getExeIcon(exepath,cache=True)) formLayout.addLayout(getboxlayout([ QLabel(_TR("修改路径")),editpath, getcolorbutton('','',functools.partial(self.selectexe),icon='fa.gear',constcolor="#FF69B4") @@ -649,9 +765,7 @@ class dialog_savedgame_new(saveposwindow): self.idxsave.append(k) if i==0: self.top1focus() - QApplication.processEvents() - def showsettingdialog(self ): idx =self.idxsave.index(self.currentfocuspath) @@ -686,7 +800,7 @@ class dialog_savedgame_new(saveposwindow): def _getpixfunction(kk): _pix=QPixmap(savehook_new_data[kk]['imagepath']) if _pix.isNull(): - _pix=getExeIcon(kk,False) + _pix=getExeIcon(kk,False,cache=True) return _pix gameitem=ItemWidget(functools.partial(_getpixfunction,k),savehook_new_data[k]['title']) gameitem.connectexepath(k) @@ -745,7 +859,7 @@ class dialog_savedgame(QDialog): checkifnewgame(k) self.model.insertRow(row,[QStandardItem( ),QStandardItem( ),keyitem,QStandardItem( (savehook_new_data[k]['title'] ) )]) self.table.setIndexWidget(self.model.index(row, 0),getsimpleswitch(savehook_new_data[k],'leuse')) - self.table.setIndexWidget(self.model.index(row, 1),getcolorbutton('','',functools.partial( opendir,k),qicon=getExeIcon(k) )) + self.table.setIndexWidget(self.model.index(row, 1),getcolorbutton('','',functools.partial( opendir,k),qicon=getExeIcon(k,cache=True) )) self.table.setIndexWidget(self.model.index(row, 2),getcolorbutton('','',functools.partial(self.showsettingdialog,k,keyitem ),icon='fa.gear',constcolor="#FF69B4")) def __init__(self, parent ) -> None: @@ -769,8 +883,7 @@ class dialog_savedgame(QDialog): table.setWordWrap(False) table.setModel(model) self.table=table - for row,k in enumerate(savehook_new_list): # 2 - self.newline(row,k) + button=QPushButton( ) button.setText(_TR('开始游戏')) self.button=button @@ -791,4 +904,6 @@ class dialog_savedgame(QDialog): formLayout.addWidget(button2) self.resize(QSize(800,400)) self.show() - + for row,k in enumerate(savehook_new_list): # 2 + self.newline(row,k) + QApplication.processEvents() diff --git a/LunaTranslator/LunaTranslator/gui/settingpage1.py b/LunaTranslator/LunaTranslator/gui/settingpage1.py index e734e2ce..3547db1a 100644 --- a/LunaTranslator/LunaTranslator/gui/settingpage1.py +++ b/LunaTranslator/LunaTranslator/gui/settingpage1.py @@ -12,7 +12,8 @@ from gui.inputdialog import autoinitdialog from gui.usefulwidget import getsimplecombobox,getspinbox,getcolorbutton,yuitsu_switch,getsimpleswitch,getQMessageBox from gui.codeacceptdialog import codeacceptdialog from textsource.fridahook import fridahook -from myutils.utils import loadfridascriptslist,checkifnewgame,makehtml,getproxy +from myutils.utils import loadfridascriptslist,checkifnewgame,makehtml +from myutils.proxy import getproxy def gethookgrid(self) : grids=[ diff --git a/LunaTranslator/LunaTranslator/gui/settingpage_about.py b/LunaTranslator/LunaTranslator/gui/settingpage_about.py index 9daa5836..d9f88f08 100644 --- a/LunaTranslator/LunaTranslator/gui/settingpage_about.py +++ b/LunaTranslator/LunaTranslator/gui/settingpage_about.py @@ -12,15 +12,11 @@ import time,json,platform,zipfile from myutils.utils import makehtml import importlib from functools import partial - +from myutils.githubupdate import updatemethod,getvesionmethod @threader def getversion(self): self.versiontextsignal.emit(('当前版本')+':'+ static_data["version"]+' '+("最新版本")+':'+ ('获取中'))#,'',url,url)) - methods=globalconfig['getvesionmethod'] - getvesionmethod=importlib.import_module('webresource.'+methods).getvesionmethod _version=getvesionmethod() - methods=globalconfig['updatemethod'] - updatemethod=importlib.import_module('webresource.'+methods).updatemethod if _version is None: sversion=_TR("获取失败") diff --git a/LunaTranslator/LunaTranslator/gui/translatorUI.py b/LunaTranslator/LunaTranslator/gui/translatorUI.py index 2b345f3d..99ad6927 100644 --- a/LunaTranslator/LunaTranslator/gui/translatorUI.py +++ b/LunaTranslator/LunaTranslator/gui/translatorUI.py @@ -26,6 +26,7 @@ from gui.textbrowser import Textbrowser from myutils.fullscreen import fullscreen from gui.rangeselect import moveresizegame ,rangeselct_function from gui.usefulwidget import resizableframeless +from gui.dialog_savedgame import browserdialog class QUnFrameWindow(resizableframeless): displayres = pyqtSignal(str,str,str ,bool) displayraw1 = pyqtSignal(list, str,str,bool ) @@ -274,6 +275,7 @@ class QUnFrameWindow(resizableframeless): ("simulate_key_ctrl",lambda:threading.Thread(target=simulate_key_ctrl).start()), ("simulate_key_enter",lambda:threading.Thread(target=simulate_key_enter).start() ), ("copy_once",lambda:gobject.baseobject.textgetmethod(winsharedutils.clipboard_get(),False) ), + ("open_relative_link",lambda:browserdialog(gobject.baseobject.settin_ui,gobject.baseobject.textsource.pname) ), ("ocr_once",lambda:rangeselct_function(self,ocroncefunction,False,False) ), ("minmize",self.hide_and_disableautohide), diff --git a/LunaTranslator/LunaTranslator/gui/usefulwidget.py b/LunaTranslator/LunaTranslator/gui/usefulwidget.py index 20259f53..dc193224 100644 --- a/LunaTranslator/LunaTranslator/gui/usefulwidget.py +++ b/LunaTranslator/LunaTranslator/gui/usefulwidget.py @@ -263,8 +263,16 @@ class Prompt_dialog(QDialog): _layout=QVBoxLayout() _layout.addWidget(QLabel(info)) - self.text=QLineEdit(default) - _layout.addWidget(self.text) + + self.text=[] + for _ in default: + if isinstance(_,str): + self.text.append(QLineEdit(_)) + else: + le=QLineEdit() + le.setPlaceholderText(_[0]) + self.text.append((le)) + _layout.addWidget(self.text[-1]) button = QDialogButtonBox(QDialogButtonBox.Ok) button.accepted.connect(self.accept) _layout.addWidget(button) @@ -279,7 +287,7 @@ class Prompt_dialog(QDialog): self.move(_rect.width()//2 - self.width() // 2, _rect.height()//3) break class Prompt(QObject): - call=pyqtSignal(str,str,str,list) + call=pyqtSignal(str,str,list,list) def __init__(self ) -> None: super().__init__( ) self.call.connect(self.getinputfunc) @@ -288,7 +296,10 @@ class Prompt(QObject): _dia=Prompt_dialog(gobject.baseobject.settin_ui, title, info,default) _dia.exec() - text=_dia.text.text() + + text=[] + for _t in _dia.text: + text.append(_t.text()) callback[0](text) def callbackwrap(d,k,call,_): d[k]=_ diff --git a/LunaTranslator/LunaTranslator/hiraparse/latin.py b/LunaTranslator/LunaTranslator/hiraparse/latin.py index 5cfbe66d..c2901b83 100644 --- a/LunaTranslator/LunaTranslator/hiraparse/latin.py +++ b/LunaTranslator/LunaTranslator/hiraparse/latin.py @@ -1,8 +1,4 @@ -from myutils.config import globalconfig -from myutils.utils import getproxy -import os,requests -from traceback import print_exc class hira: def __init__(self) -> None: pass diff --git a/LunaTranslator/LunaTranslator/hiraparse/mojinlt.py b/LunaTranslator/LunaTranslator/hiraparse/mojinlt.py index a1d6a9e6..545a8121 100644 --- a/LunaTranslator/LunaTranslator/hiraparse/mojinlt.py +++ b/LunaTranslator/LunaTranslator/hiraparse/mojinlt.py @@ -1,6 +1,6 @@ from myutils.config import globalconfig -from myutils.utils import getproxy +from myutils.proxy import getproxy import os,requests from traceback import print_exc class hira: diff --git a/LunaTranslator/LunaTranslator/myutils/commonbase.py b/LunaTranslator/LunaTranslator/myutils/commonbase.py index faff7453..97482ca3 100644 --- a/LunaTranslator/LunaTranslator/myutils/commonbase.py +++ b/LunaTranslator/LunaTranslator/myutils/commonbase.py @@ -1,4 +1,4 @@ -from myutils.utils import getproxy +from myutils.proxy import getproxy from myutils.config import globalconfig,_TR,static_data from myutils.wrapper import stripwrapper from traceback import print_exc diff --git a/LunaTranslator/LunaTranslator/myutils/config.py b/LunaTranslator/LunaTranslator/myutils/config.py index e055f5ed..fc1608c0 100644 --- a/LunaTranslator/LunaTranslator/myutils/config.py +++ b/LunaTranslator/LunaTranslator/myutils/config.py @@ -54,7 +54,7 @@ def getdefaultsavehook(gamepath): 'embedablehook':[], 'imagepath':None, 'infopath':None, - 'infomethod':None, + 'vid':0, 'statistic_playtime':0, 'statistic_wordcount':0, 'statistic_wordcount_nodump':0, @@ -68,7 +68,9 @@ def getdefaultsavehook(gamepath): "allow_tts_auto_names":'', "hooktypeasname":{}, "use_saved_text_process":False, - "fridahook":{} + "fridahook":{}, + "searchnoresulttime":0, + 'relationlinks':[] } return default diff --git a/LunaTranslator/LunaTranslator/webresource/githubrelease.py b/LunaTranslator/LunaTranslator/myutils/githubupdate.py similarity index 99% rename from LunaTranslator/LunaTranslator/webresource/githubrelease.py rename to LunaTranslator/LunaTranslator/myutils/githubupdate.py index 5b7d6aa0..4390664f 100644 --- a/LunaTranslator/LunaTranslator/webresource/githubrelease.py +++ b/LunaTranslator/LunaTranslator/myutils/githubupdate.py @@ -1,7 +1,7 @@ import platform import requests import shutil -from myutils.utils import getproxy +from myutils.proxy import getproxy from traceback import print_exc import zipfile,os from myutils.config import globalconfig ,_TR ,static_data diff --git a/LunaTranslator/LunaTranslator/myutils/hwnd.py b/LunaTranslator/LunaTranslator/myutils/hwnd.py index aa220c41..71a42b20 100644 --- a/LunaTranslator/LunaTranslator/myutils/hwnd.py +++ b/LunaTranslator/LunaTranslator/myutils/hwnd.py @@ -4,9 +4,10 @@ from PyQt5.QtGui import QPixmap,QColor ,QIcon from PyQt5.QtWidgets import QApplication import gobject import os -import time,winrtutils,winsharedutils +import time,winrtutils,winsharedutils,base64,hashlib from myutils.wrapper import threader from myutils.utils import argsort +from traceback import print_exc def pid_running(pid): try: process =windows.AutoHandle(windows.OpenProcess(windows.SYNCHRONIZE, False, pid)) @@ -155,7 +156,7 @@ def ListProcess(filt=True): xxx.append([kv[exe]['pid'],exe]) return xxx -def getExeIcon( name,icon=True ): +def getExeIcon( name,icon=True,cache=False ): if name.lower()[-4:]=='.lnk': exepath,args,iconpath,dirp=(winsharedutils.GetLnkTargetPath(name)) if os.path.exists(iconpath): @@ -163,12 +164,29 @@ def getExeIcon( name,icon=True ): elif os.path.exists(exepath): name=exepath data=winsharedutils.extracticon2data(name) + if cache: + fn='./cache/icon/{}.bmp'.format(hashlib.md5(name.encode('utf8')).hexdigest()) if data: pixmap=QPixmap() pixmap.loadFromData(data) + if cache: + with open(fn,'wb') as ff: + ff.write(data) else: - pixmap=QPixmap(100,100) - pixmap.fill(QColor.fromRgba(0)) + succ=False + if cache and os.path.exists(fn): + try: + with open(fn,'rb') as ff: + data=ff.read() + pixmap=QPixmap() + pixmap.loadFromData(data) + succ=True + except: + pass + #print_exc() + if succ==False: + pixmap=QPixmap(100,100) + pixmap.fill(QColor.fromRgba(0)) if icon: return QIcon(pixmap) else: diff --git a/LunaTranslator/LunaTranslator/myutils/proxy.py b/LunaTranslator/LunaTranslator/myutils/proxy.py new file mode 100644 index 00000000..fc2ac47f --- /dev/null +++ b/LunaTranslator/LunaTranslator/myutils/proxy.py @@ -0,0 +1,37 @@ +from myutils.config import globalconfig +from urllib.request import getproxies_registry +def getsysproxy(): + proxies=getproxies_registry() + try: + return proxies[list(proxies.keys())[0]].split('//')[1] + except: + return '' + # hkey=RegOpenKeyEx(HKEY_CURRENT_USER,'Software\Microsoft\Windows\CurrentVersion\Internet Settings',0,KEY_ALL_ACCESS) + + # count,MaxValueNameLen,MaxValueLen=(RegQueryInfoKey(hkey)) + # ProxyEnable=False + # ProxyServer='' + # for i in range(count): + # k,v=(RegEnumValue(hkey,i,MaxValueNameLen,MaxValueLen)) + # if k=='ProxyEnable': + # ProxyEnable=(v=='\x01') + # elif k=='ProxyServer': + # ProxyServer=v + # if ProxyEnable: + # return ProxyServer + # else: + # return '' +def _getproxy(): + if globalconfig['useproxy']: + if globalconfig['usesysproxy']: + p=getsysproxy() + else: + p=(globalconfig['proxy']) + else: + p=None + return {'https':p,'http':p} +def getproxy(pair=None): + if pair is None or ('useproxy' not in globalconfig[pair[0]][pair[1]]) or globalconfig[pair[0]][pair[1]]['useproxy']: + return _getproxy() + else: + return {'https':None,'http':None} \ No newline at end of file diff --git a/LunaTranslator/LunaTranslator/myutils/utils.py b/LunaTranslator/LunaTranslator/myutils/utils.py index ce791f2f..c6626000 100644 --- a/LunaTranslator/LunaTranslator/myutils/utils.py +++ b/LunaTranslator/LunaTranslator/myutils/utils.py @@ -4,86 +4,86 @@ import os,time,sys from traceback import print_exc import codecs,hashlib import os,time -import socket,functools +import socket,gobject import ctypes import time import ctypes.wintypes -import gobject +import time from traceback import print_exc from myutils.config import globalconfig,static_data,savehook_new_list,savehook_new_data,getdefaultsavehook,translatorsetting import threading,queue -from urllib.request import getproxies_registry import importlib,re +from myutils.vndb import searchforidimage def checkimage(gamepath): return (savehook_new_data[gamepath]['imagepath'] is None) or (os.path.exists(savehook_new_data[gamepath]['imagepath'])==False) def checkinfo(gamepath): return (savehook_new_data[gamepath]['infopath'] is None) or ((savehook_new_data[gamepath]['infopath'][:4].lower()!='http') and os.path.exists(savehook_new_data[gamepath]['infopath'])==False) +def checkvid(gamepath): + if savehook_new_data[gamepath]['vid']: + return checkimage(gamepath) or checkinfo(gamepath) + else: + return time.time()-savehook_new_data[gamepath]['searchnoresulttime']>3600*24*7 def checkneed(gamepath): return (gamepath in savehook_new_data) and \ - (checkimage(gamepath) or checkinfo(gamepath) ) -methodsqueues=[] + (checkvid(gamepath)) +searchvndbqueue=queue.Queue() -def dispatchnext(gamepath,args,idx): - if idx+10 and (len(t)<10) and (all(ord(c) < 128 for c in t)): - continue - lst.append(t) - dispatchnext(gamepath,lst,-1) + if savehook_new_data[gamepath]['vid']: + searchvndbqueue.put((gamepath,[savehook_new_data[gamepath]['vid']])) + else: + for _ in [savehook_new_data[gamepath]['title'],os.path.basename(os.path.dirname(gamepath)),os.path.basename(gamepath)[:-4]]: + _=_.replace('(同人ゲーム)','').replace('(18禁ゲーム)','') + _=re.sub(r'\[RJ(.*?)\]','',_) + _=re.sub(r'\[\d{4}-?\d{2}\-?\d{2}\]','',_) + __t.append(_) + _=re.sub(r'\[(.*?)\]','',_) + if _ !=__t[-1]: + __t.append(_) + _=re.sub(r'\((.*?)\)','',_) + if _ !=__t[-1]: + __t.append(_) + lst=[] + for i,t in enumerate(__t): + t=t.strip() + if t in lst :continue + if (len(t)<10) and (all(ord(c) < 128 for c in t)): + continue + lst.append(t) + searchvndbqueue.put((gamepath,lst)) -def everymethodsthread(methodsidx): - methods=static_data['searchimgmethods'] - searchdatamethod=importlib.import_module('webresource.'+methods[methodsidx]).searchdatamethod +def everymethodsthread(): while True: - gamepath,searchargs=methodsqueues[methodsidx].get() + gamepath,searchargs=searchvndbqueue.get() if checkneed(gamepath)==False: continue - failed=True + print(gamepath) + succ=False for searcharg in searchargs: try: - data= searchdatamethod(searcharg) + data= searchforidimage(searcharg) except: - data={} + print_exc() + continue saveimg=data.get('imagepath',None) saveinfo=data.get('infopath',None) - if saveimg: - if checkimage(gamepath) : - savehook_new_data[gamepath]['imagepath']=saveimg - - if saveinfo: - if checkinfo(gamepath) : - savehook_new_data[gamepath]['infopath']=saveinfo - savehook_new_data[gamepath]['infomethod']=methods[methodsidx] - if saveinfo is not None and saveimg is not None: - failed=False - break - if failed: - dispatchnext(gamepath,searchargs,methodsidx) -for i in range(len(static_data['searchimgmethods'])): - methodsqueues.append(queue.Queue()) - threading.Thread(target=everymethodsthread,args=(i,)).start() + vid=data.get('vid',None) + print(data) + if not vid: + continue + savehook_new_data[gamepath]['vid']=int(vid[1:]) + if checkimage(gamepath): + savehook_new_data[gamepath]['imagepath']=saveimg + savehook_new_data[gamepath]['infopath']=saveinfo + succ=True + break + if succ==False: + savehook_new_data[gamepath]['searchnoresulttime']=time.time() +threading.Thread(target=everymethodsthread).start() def checkifnewgame(gamepath): if gamepath not in savehook_new_list: savehook_new_list.insert(0,gamepath) @@ -95,41 +95,7 @@ def kanjitrans(k): return k.translate(kanjichs2ja) def stringfyerror(e): return str(type(e))[8:-2]+' '+str(e).replace('\n','').replace('\r','') -def getsysproxy(): - proxies=getproxies_registry() - try: - return proxies[list(proxies.keys())[0]].split('//')[1] - except: - return '' - # hkey=RegOpenKeyEx(HKEY_CURRENT_USER,'Software\Microsoft\Windows\CurrentVersion\Internet Settings',0,KEY_ALL_ACCESS) - # count,MaxValueNameLen,MaxValueLen=(RegQueryInfoKey(hkey)) - # ProxyEnable=False - # ProxyServer='' - # for i in range(count): - # k,v=(RegEnumValue(hkey,i,MaxValueNameLen,MaxValueLen)) - # if k=='ProxyEnable': - # ProxyEnable=(v=='\x01') - # elif k=='ProxyServer': - # ProxyServer=v - # if ProxyEnable: - # return ProxyServer - # else: - # return '' -def _getproxy(): - if globalconfig['useproxy']: - if globalconfig['usesysproxy']: - p=getsysproxy() - else: - p=(globalconfig['proxy']) - else: - p=None - return {'https':p,'http':p} -def getproxy(pair=None): - if pair is None or ('useproxy' not in globalconfig[pair[0]][pair[1]]) or globalconfig[pair[0]][pair[1]]['useproxy']: - return _getproxy() - else: - return {'https':None,'http':None} def checkportavailable(port): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: diff --git a/LunaTranslator/LunaTranslator/myutils/vndb.py b/LunaTranslator/LunaTranslator/myutils/vndb.py new file mode 100644 index 00000000..2c6ccb43 --- /dev/null +++ b/LunaTranslator/LunaTranslator/myutils/vndb.py @@ -0,0 +1,161 @@ + +from urllib.parse import quote +import base64 +import queue,time,requests,re,os,hashlib +from traceback import print_exc +from myutils.proxy import getproxy +from myutils.config import globalconfig +from threading import Thread +def b64string(a): + return hashlib.md5(a.encode('utf8')).hexdigest() + +def vndbdownloadimg(url,wait=True): + savepath='./cache/vndb/'+b64string(url)+'.jpg' + if os.path.exists(savepath): + return savepath + def _(url,savepath): + headers= { + 'sec-ch-ua': '"Microsoft Edge";v="113", "Chromium";v="113", "Not-A.Brand";v="24"', + 'Referer': 'https://vndb.org/', + 'sec-ch-ua-mobile': '?0', + 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36 Edg/113.0.1774.42', + 'sec-ch-ua-platform': '"Windows"', + } + try: + time.sleep(1) + _content=requests.get(url,headers=headers,proxies=getproxy()).content + with open(savepath,'wb') as ff: + ff.write(_content) + return savepath + except: + return None + if wait: + return _(url,savepath) + else: + Thread(target=_,args=(url,savepath)).start() + return None +def vndbdowloadinfo(vid): + cookies = { + 'vndb_samesite': '1', + } + + headers = { + 'authority': 'vndb.org', + 'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7', + 'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6', + 'sec-ch-ua': '"Microsoft Edge";v="113", "Chromium";v="113", "Not-A.Brand";v="24"', + 'sec-ch-ua-mobile': '?0', + 'sec-ch-ua-platform': '"Windows"', + 'sec-fetch-dest': 'document', + 'sec-fetch-mode': 'navigate', + 'sec-fetch-site': 'none', + 'sec-fetch-user': '?1', + 'upgrade-insecure-requests': '1', + 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36 Edg/113.0.1774.42', + } + url='https://vndb.org/'+vid + savepath='./cache/vndb/'+b64string(url)+'.html' + #print(url,savepath) + if not os.path.exists(savepath): + try: + time.sleep(1) + response = requests.get(url, cookies=cookies, headers=headers,proxies=getproxy()) + with open(savepath,'w',encoding='utf8') as ff: + ff.write(response.text) + except: + return None + return savepath + +def searchforidimage(title): + if isinstance(title,str): + if os.path.exists('./cache/vndb')==False: + os.mkdir('./cache/vndb') + js=requests.post('https://api.vndb.org/kana/vn',json={ + "filters": ["search", "=", title], + "fields": "image.url" ,"sort":"searchrank" + },proxies=getproxy()) + try: + results=js.json()['results'] + except: + print(js.text) + return {} + if len(results)==0: + js=requests.post('https://api.vndb.org/kana/release',json={ + "filters": ["search", "=", title], + "fields": "vns.id" ,"sort":"searchrank" + },proxies=getproxy()) + results=js.json()['results'] + if len(results)==0: + return {} + vns=results[0]['vns'] + if len(vns)==0:return {} + vid=vns[0]['id'] + js=requests.post('https://api.vndb.org/kana/vn',json={ + "filters": ["id", "=", vid], + "fields": "image.url" + },proxies=getproxy()) + try: + results=js.json()['results'] + except: + print(js.text) + return {} + img=results[0]['image']['url'] + else: + img=results[0]['image']['url'] + vid=results[0]['id'] + elif isinstance(title,int): + vid='v{}'.format(title) + js=requests.post('https://api.vndb.org/kana/vn',json={ + "filters": ["id", "=", vid], + "fields": "image.url" + },proxies=getproxy()) + try: + results=js.json()['results'] + except: + print(js.text) + return {} + img=results[0]['image']['url'] + return {'vid':vid,'infopath':vndbdowloadinfo(vid),'imagepath':vndbdownloadimg(img)} + +import re +def parsehtmlmethod(vid,infopath): + with open(infopath,'r',encoding='utf8') as ff: + text=ff.read() + ##隐藏横向滚动 + text=text.replace('','') + ##删除header + text=re.sub('
    ([\\s\\S]*?)
    ','',text) + text=re.sub('','',text) + text=re.sub('
    ','',text) + text=re.sub('
    ','',text) + text=re.sub('
    ','',text) + + text=re.sub('','',text) + text=re.sub('

    ([\\s\\S]*?)

    ','',text) + text=re.sub('
    ([\\s\\S]*?)
    ','',text) + text=re.sub('
    ([\\s\\S]*?)
    ','',text) + resavepath=infopath+'parsed.html' + + if globalconfig['languageuse']==0: + text=re.sub('(.*?)','\\2',text) + + + hrefs=re.findall('src="(.*?)" width="(.*?)" height="(.*?)"',text) + #print(hrefs) + for href in hrefs: + if href[0].startswith('https://t.vndb.org/st/'): + href1=href[0].replace('https://t.vndb.org/st/','https://t.vndb.org/sf/') + localimg=vndbdownloadimg(href1,False) + if localimg: + text=text.replace('src="{}" width="{}" height="{}"'.format(href[0],href[1],href[2]),'src="file://{}" width="512"'.format(os.path.abspath(localimg).replace('\\','/'))) + text=text.replace('href="{}"'.format(href1),'href="file://{}"'.format(os.path.abspath(localimg).replace('\\','/'))) + elif href[0].startswith('https://t.vndb.org/cv/'): + localimg=vndbdownloadimg(href[0],False) + if localimg: + text=text.replace('src="{}"'.format(href[0]),'src="file://{}"'.format(os.path.abspath(localimg).replace('\\','/'))) + + with open(resavepath,'w',encoding='utf8') as ff: + ff.write(text) + + + return resavepath \ No newline at end of file diff --git a/LunaTranslator/LunaTranslator/network/winhttp/requests.py b/LunaTranslator/LunaTranslator/network/winhttp/requests.py index 2d73de4f..f2d77434 100644 --- a/LunaTranslator/LunaTranslator/network/winhttp/requests.py +++ b/LunaTranslator/LunaTranslator/network/winhttp/requests.py @@ -56,7 +56,10 @@ class Session(Sessionbase): def _set_proxy(self,hsess,proxy): if proxy: winhttpsetproxy(hsess,proxy) - + def _set_verify(self,curl,verify): + if verify==False: + dwFlags=DWORD(SECURITY_FLAG_IGNORE_ALL_CERT_ERRORS) + WinHttpSetOption(curl,WINHTTP_OPTION_SECURITY_FLAGS, pointer(dwFlags),sizeof(dwFlags)) def request_impl(self, method,scheme,server,port,param,url,headers,cookies,dataptr,datalen,proxy,stream,verify): headers=self._parseheader(headers,cookies) @@ -71,6 +74,7 @@ class Session(Sessionbase): if hRequest==0: raise WinhttpException(GetLastError()) + self._set_verify(hRequest,verify) self._set_proxy(hRequest,proxy) succ=WinHttpSendRequest(hRequest,headers,-1,dataptr,datalen,datalen,None) diff --git a/LunaTranslator/LunaTranslator/network/winhttp/winhttp.py b/LunaTranslator/LunaTranslator/network/winhttp/winhttp.py index bcc00408..8e7374ed 100644 --- a/LunaTranslator/LunaTranslator/network/winhttp/winhttp.py +++ b/LunaTranslator/LunaTranslator/network/winhttp/winhttp.py @@ -100,6 +100,15 @@ WINHTTP_OPTION_PROXY=38 WINHTTP_ACCESS_TYPE_NAMED_PROXY=3 WINHTTP_QUERY_STATUS_CODE=19 WINHTTP_QUERY_FLAG_NUMBER=0x20000000 +WINHTTP_OPTION_SECURITY_FLAGS =31 +SECURITY_FLAG_IGNORE_UNKNOWN_CA =0x00000100 +SECURITY_FLAG_IGNORE_CERT_WRONG_USAGE =0x00000200 +SECURITY_FLAG_IGNORE_CERT_CN_INVALID =0x00001000 # bad common name in X509 Cert. +SECURITY_FLAG_IGNORE_CERT_DATE_INVALID =0x00002000 # expired X509 Cert. +SECURITY_FLAG_IGNORE_ALL_CERT_ERRORS =(SECURITY_FLAG_IGNORE_UNKNOWN_CA | \ + SECURITY_FLAG_IGNORE_CERT_WRONG_USAGE | \ + SECURITY_FLAG_IGNORE_CERT_CN_INVALID | \ + SECURITY_FLAG_IGNORE_CERT_DATE_INVALID) #function kernel32=windll.kernel32 GetLastError=kernel32.GetLastError diff --git a/LunaTranslator/LunaTranslator/textsource/fridahook.py b/LunaTranslator/LunaTranslator/textsource/fridahook.py index fb18aefa..ef810778 100644 --- a/LunaTranslator/LunaTranslator/textsource/fridahook.py +++ b/LunaTranslator/LunaTranslator/textsource/fridahook.py @@ -95,13 +95,14 @@ def buildfridaclass(copycallback,pexe): r= savehook_new_data[pexe]['fridahook']['prompt'][t] except: pass - def callback(text): + def callback(texts): + text=texts[0] self.script.post({'type':payload.key,'result':text}) try: savehook_new_data[pexe]['fridahook']['prompt'].update({t:text}) except: savehook_new_data[pexe]['fridahook'].update({'prompt':{t:text}}) - gobject.baseobject.Prompt.call.emit('prompt',t,r,[callback]) + gobject.baseobject.Prompt.call.emit('prompt',t,[r],[callback]) def on_message(self,raw_message: str, data): diff --git a/LunaTranslator/LunaTranslator/tts/edgetts.py b/LunaTranslator/LunaTranslator/tts/edgetts.py index 5c39cb7e..81416d49 100644 --- a/LunaTranslator/LunaTranslator/tts/edgetts.py +++ b/LunaTranslator/LunaTranslator/tts/edgetts.py @@ -3,7 +3,7 @@ import threading from traceback import print_exc import requests from myutils.config import globalconfig -from myutils.utils import getproxy +from myutils.proxy import getproxy import websocket from datetime import datetime diff --git a/LunaTranslator/LunaTranslator/webresource/2dfgetimg.py b/LunaTranslator/LunaTranslator/webresource/2dfgetimg.py deleted file mode 100644 index 8022471a..00000000 --- a/LunaTranslator/LunaTranslator/webresource/2dfgetimg.py +++ /dev/null @@ -1,165 +0,0 @@ - -from urllib.parse import quote -import hashlib -import queue,time,requests,re,os - -from myutils.utils import getproxy -def b64string(a): - return hashlib.md5(a.encode('utf8')).hexdigest() - - -def vndbdownloadimg(url): - - if url is None: - return None - savepath='./cache/2df/'+b64string(url)+'.jpg' - if os.path.exists(savepath): - return savepath - - headers = { - 'authority': 'img.achost.top', - 'accept': 'image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8', - 'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6', - 'referer': 'https://2dfan.org/', - 'sec-ch-ua': '"Microsoft Edge";v="113", "Chromium";v="113", "Not-A.Brand";v="24"', - 'sec-ch-ua-mobile': '?0', - 'sec-ch-ua-platform': '"Windows"', - 'sec-fetch-dest': 'image', - 'sec-fetch-mode': 'no-cors', - 'sec-fetch-site': 'cross-site', - 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36 Edg/113.0.1774.42', - } - try: - time.sleep(1) - _content=requests.get(url,headers=headers,proxies=getproxy()).content - with open(savepath,'wb') as ff: - ff.write(_content) - return savepath - except: - return None -def vndbsearch(title): - - headers = { - 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7', - 'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6', - 'Cache-Control': 'max-age=0', - 'Proxy-Connection': 'keep-alive', - 'Referer': 'http://bangumi.tv/subject_search/amatutumi?cat=all', - 'Upgrade-Insecure-Requests': '1', - 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36 Edg/113.0.1774.42', - } - url='https://2dfan.org/subjects/search?keyword='+(title) - - savepath='./cache/2df/'+b64string(url)+'.html' - #print(url,savepath) - if not os.path.exists(savepath): - try: - time.sleep(1) - response = requests.get( - url, - headers=headers,proxies=getproxy(), - verify=False, - ) - with open(savepath,'w',encoding='utf8') as ff: - ff.write(response.text) - text=response.text - except: - return None - else: - with open(savepath,'r',encoding='utf8') as ff: - text=ff.read() - - try: - found=re.findall('',text) - except: - #print("??") - return None - #print(found) - if len(found)==0: - return None - found=found[0][1] - if 'normal_' in found: - found=found.replace('normal_','') - return found - else: - return None - -def vndbsearchinfo(title): - - headers = { - 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7', - 'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6', - 'Cache-Control': 'max-age=0', - 'Proxy-Connection': 'keep-alive', - 'Referer': 'http://bangumi.tv/subject_search/amatutumi?cat=all', - 'Upgrade-Insecure-Requests': '1', - 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36 Edg/113.0.1774.42', - } - url='https://2dfan.org/subjects/search?keyword='+(title) - - savepath='./cache/2df/'+b64string(url)+'.html' - #print(url,savepath) - if not os.path.exists(savepath): - try: - time.sleep(1) - response = requests.get( - url, - headers=headers,proxies=getproxy(), - verify=False, - ) - with open(savepath,'w',encoding='utf8') as ff: - ff.write(response.text) - text=response.text - except: - return None - else: - with open(savepath,'r',encoding='utf8') as ff: - text=ff.read() - - try: - found=re.findall('

    (.*?)

    ',text) - except: - #print("??") - return None - #print(found) - if len(found)==0: - return None - - found=found[0] - found=re.findall('href="(.*?)"',found)[0] - - url='https://2dfan.org'+found - return url - savepath='./cache/2df/'+b64string(url)+'.html' - #print(url,savepath) - if not os.path.exists(savepath): - try: - time.sleep(1) - response = requests.get( - url, - headers=headers,proxies=getproxy(), - verify=False, - ) - with open(savepath,'w',encoding='utf8') as ff: - ff.write(response.text) - text=response.text - except: - return None - else: - with open(savepath,'r',encoding='utf8') as ff: - text=ff.read() - return savepath - - -def searchdatamethod(title): - - if os.path.exists('./cache/2df')==False: - os.mkdir('./cache/2df') - imgurl=vndbsearch(title) - #print(imgurl) - savepath= vndbdownloadimg(imgurl) - infosavepath=vndbsearchinfo(title) - return {'imagepath':savepath,'infopath':infosavepath} -import re -def parsehtmlmethod(infopath): - return infopath \ No newline at end of file diff --git a/LunaTranslator/LunaTranslator/webresource/bangumigetimg.py b/LunaTranslator/LunaTranslator/webresource/bangumigetimg.py deleted file mode 100644 index fbe133d4..00000000 --- a/LunaTranslator/LunaTranslator/webresource/bangumigetimg.py +++ /dev/null @@ -1,161 +0,0 @@ - -from urllib.parse import quote -import hashlib -import queue,time,requests,re,os - -from myutils.utils import getproxy -def b64string(a): - return hashlib.md5(a.encode('utf8')).hexdigest() - - -def vndbdownloadimg(url): - if url is None: - return None - savepath='./cache/bangumi/'+b64string(url)+'.jpg' - if os.path.exists(savepath): - return savepath - headers= { - 'sec-ch-ua': '"Microsoft Edge";v="113", "Chromium";v="113", "Not-A.Brand";v="24"', - 'Referer': 'https://vndb.org/', - 'sec-ch-ua-mobile': '?0', - 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36 Edg/113.0.1774.42', - 'sec-ch-ua-platform': '"Windows"', - } - try: - time.sleep(1) - _content=requests.get(url,headers=headers,proxies=getproxy()).content - with open(savepath,'wb') as ff: - ff.write(_content) - return savepath - except: - return None -def vndbsearch(title): - - headers = { - 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7', - 'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6', - 'Cache-Control': 'max-age=0', - 'Proxy-Connection': 'keep-alive', - 'Referer': 'http://bangumi.tv/subject_search/amatutumi?cat=all', - 'Upgrade-Insecure-Requests': '1', - 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36 Edg/113.0.1774.42', - } - - params = { - 'cat': '4', - } - url='http://bangumi.tv/subject_search/'+(title) - - savepath='./cache/bangumi/'+b64string(url)+'.html' - #print(url,savepath) - if not os.path.exists(savepath): - try: - time.sleep(1) - response = requests.get( - url, - params=params, - headers=headers,proxies=getproxy(), - verify=False, - ) - with open(savepath,'w',encoding='utf8') as ff: - ff.write(response.text) - text=response.text - except: - return None - else: - with open(savepath,'r',encoding='utf8') as ff: - text=ff.read() - - try: - found=re.findall('',text) - except: - #print("??") - return None - #print(found) - if len(found)==0: - return None - - url='http://bangumi.tv'+found[0] - savepath='./cache/bangumi/'+b64string(url)+'.html' - #print(url,savepath) - if not os.path.exists(savepath): - try: - time.sleep(1) - response = requests.get(url, headers=headers,proxies=getproxy(),verify=False,) - with open(savepath,'w',encoding='utf8') as ff: - ff.write(response.text) - text=response.text - except: - return None - else: - with open(savepath,'r',encoding='utf8') as ff: - text=ff.read() - try: - imgurl=(re.search('',text) - except: - #print("??") - return None - #print(found) - if len(found)==0: - return None - if found[0]=='/': - return None - url='http://bangumi.tv'+found[0] - return url - - -def searchdatamethod(title): - - if os.path.exists('./cache/bangumi')==False: - os.mkdir('./cache/bangumi') - imgurl=vndbsearch(title) - #print(imgurl) - savepath= vndbdownloadimg(imgurl) - infosavepath=vndbsearchinfo(title) - return {'imagepath':savepath,'infopath':infosavepath} -import re -def parsehtmlmethod(infopath): - - return infopath \ No newline at end of file diff --git a/LunaTranslator/LunaTranslator/webresource/vndbgetimg.py b/LunaTranslator/LunaTranslator/webresource/vndbgetimg.py deleted file mode 100644 index b845f59a..00000000 --- a/LunaTranslator/LunaTranslator/webresource/vndbgetimg.py +++ /dev/null @@ -1,221 +0,0 @@ - -from urllib.parse import quote -import base64 -import queue,time,requests,re,os -from traceback import print_exc -import hashlib -from myutils.utils import getproxy -from myutils.config import globalconfig -def b64string(a): - return hashlib.md5(a.encode('utf8')).hexdigest() - - -def vndbdownloadimg(url): - if url is None: - return None - savepath='./cache/vndb/'+b64string(url)+'.jpg' - if os.path.exists(savepath): - return savepath - headers= { - 'sec-ch-ua': '"Microsoft Edge";v="113", "Chromium";v="113", "Not-A.Brand";v="24"', - 'Referer': 'https://vndb.org/', - 'sec-ch-ua-mobile': '?0', - 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36 Edg/113.0.1774.42', - 'sec-ch-ua-platform': '"Windows"', - } - try: - time.sleep(1) - _content=requests.get(url,headers=headers,proxies=getproxy()).content - with open(savepath,'wb') as ff: - ff.write(_content) - return savepath - except: - return None -def vndbsearch(title):#301直接跳转到目标 - cookies = { - 'vndb_samesite': '1', - } - - headers = { - 'authority': 'vndb.org', - 'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7', - 'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6', - 'sec-ch-ua': '"Microsoft Edge";v="113", "Chromium";v="113", "Not-A.Brand";v="24"', - 'sec-ch-ua-mobile': '?0', - 'sec-ch-ua-platform': '"Windows"', - 'sec-fetch-dest': 'document', - 'sec-fetch-mode': 'navigate', - 'sec-fetch-site': 'none', - 'sec-fetch-user': '?1', - 'upgrade-insecure-requests': '1', - 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36 Edg/113.0.1774.42', - } - url='https://vndb.org/v?sq='+quote(title) - savepath='./cache/vndb/'+b64string(url)+'.html' - #print(url,savepath) - #print(getproxy()) - if not os.path.exists(savepath): - try: - time.sleep(1) - response = requests.get(url, cookies=cookies, headers=headers,proxies=getproxy()) - with open(savepath,'w',encoding='utf8') as ff: - ff.write(response.text) - text=response.text - except: - print_exc() - return None - else: - with open(savepath,'r',encoding='utf8') as ff: - text=ff.read() - try: - #301 - imgurl=(re.search('
    ','') - ##删除header - text=re.sub('
    ([\\s\\S]*?)
    ','',text) - text=re.sub('
    ([\\s\\S]*?)
    ','',text) - text=re.sub('
    ','',text) - text=re.sub('
    ','',text) - text=re.sub('
    ','',text) - - text=re.sub('','',text) - text=re.sub('

    ([\\s\\S]*?)

    ','',text) - text=re.sub('
    ([\\s\\S]*?)
    ','',text) - text=re.sub('
    ([\\s\\S]*?)
    ','',text) - resavepath=infopath+'parsed.html' - - if globalconfig['languageuse']==0: - text=re.sub('
    (.*?)','\\2',text) - - try: - imgurl=(re.search('
    ) set(CMAKE_LIBRARY_OUTPUT_DIRECTORY $<1:${CMAKE_FINAL_OUTPUT_DIRECTORY}>) set(CMAKE_RUNTIME_OUTPUT_DIRECTORY $<1:${CMAKE_FINAL_OUTPUT_DIRECTORY}>) -add_library(winsharedutils MODULE otsu.cpp cinterface.cpp clipboard.cpp lnk.cpp dllmain.cpp levenshtein.cpp muteprocess.cpp sapi_dll.cpp simplemecab.cpp WebBrowser.cpp icon.cpp) +add_library(winsharedutils MODULE otsu.cpp cinterface.cpp clipboard.cpp lnk.cpp dllmain.cpp levenshtein.cpp muteprocess.cpp sapi_dll.cpp simplemecab.cpp SimpleBrowser.cpp MWebBrowser.cpp icon.cpp) if(${CMAKE_SIZEOF_VOID_P} EQUAL 8) set_target_properties(winsharedutils PROPERTIES OUTPUT_NAME "winsharedutils64") diff --git a/plugins/winsharedutils/MWebBrowser.cpp b/plugins/winsharedutils/MWebBrowser.cpp new file mode 100644 index 00000000..7b5be724 --- /dev/null +++ b/plugins/winsharedutils/MWebBrowser.cpp @@ -0,0 +1,989 @@ +// MWebBrowser.cpp --- simple Win32 Web Browser +// Copyright (C) 2019 Katayama Hirofumi MZ +// This file is public domain software. + +#include "MWebBrowser.hpp" +#include +#include +#include +#include +#include +#include +#include + +/*static*/ MWebBrowser * +MWebBrowser::Create(HWND hwndParent) +{ + MWebBrowser *pBrowser = new MWebBrowser(hwndParent); + if (!pBrowser->IsCreated()) + { + pBrowser->Release(); + pBrowser = NULL; + } + return pBrowser; +} + +MWebBrowser::MWebBrowser(HWND hwndParent) : + m_nRefCount(0), + m_hwndParent(NULL), + m_hwndCtrl(NULL), + m_hwndIEServer(NULL), + m_web_browser2(NULL), + m_ole_object(NULL), + m_ole_inplace_object(NULL), + m_pDocHostUIHandler(NULL), + m_hr(S_OK), + m_bAllowInsecure(FALSE), + m_nZoomPercents(100) +{ + ::SetRectEmpty(&m_rc); + + m_hr = CreateBrowser(hwndParent); +} + +BOOL MWebBrowser::IsCreated() const +{ + return m_hr == S_OK; +} + +MWebBrowser::~MWebBrowser() +{ + if (m_pDocHostUIHandler) + { + m_pDocHostUIHandler->Release(); + m_pDocHostUIHandler = NULL; + } + if (m_ole_object) + { + m_ole_object->Release(); + m_ole_object = NULL; + } + if (m_ole_inplace_object) + { + m_ole_inplace_object->Release(); + m_ole_inplace_object = NULL; + } + if (m_web_browser2) + { + m_web_browser2->Release(); + m_web_browser2 = NULL; + } +} + +IWebBrowser2 *MWebBrowser::GetIWebBrowser2() +{ + return m_web_browser2; +} + +IHTMLDocument2 *MWebBrowser::GetIHTMLDocument2() +{ + IDispatch *pDisp; + m_web_browser2->get_Document(&pDisp); + if (pDisp) + { + return static_cast(pDisp); + } + return NULL; +} + +HWND MWebBrowser::GetControlWindow() +{ + if (::IsWindow(m_hwndCtrl)) + return m_hwndCtrl; + + if (!m_ole_inplace_object) + return NULL; + + m_ole_inplace_object->GetWindow(&m_hwndCtrl); + return m_hwndCtrl; +} + +HWND MWebBrowser::GetIEServerWindow() +{ + if (::IsWindow(m_hwndIEServer)) + return m_hwndIEServer; + + HWND hwnd = ::GetWindow(m_hwndParent, GW_CHILD); + while (hwnd) + { + WCHAR szClass[64]; + ::GetClassNameW(hwnd, szClass, 64); + if (lstrcmpiW(szClass, L"Internet Explorer_Server") == 0) + { + m_hwndIEServer = hwnd; + return hwnd; + } + hwnd = ::GetWindow(hwnd, GW_CHILD); + } + + return NULL; +} + +HRESULT MWebBrowser::CreateBrowser(HWND hwndParent) +{ + m_hwndParent = hwndParent; + + HRESULT hr; + hr = ::OleCreate(CLSID_WebBrowser, IID_IOleObject, OLERENDER_DRAW, NULL, + this, this, (void **)&m_ole_object); + if (FAILED(hr)) + { + assert(0); + return hr; + } + + if (m_pDocHostUIHandler) + { + m_pDocHostUIHandler->Release(); + m_pDocHostUIHandler = NULL; + } + m_ole_object->QueryInterface(&m_pDocHostUIHandler); + + hr = m_ole_object->SetClientSite(this); + if (FAILED(hr)) + { + assert(0); + return hr; + } + + hr = ::OleSetContainedObject(m_ole_object, TRUE); + if (FAILED(hr)) + { + assert(0); + return hr; + } + + RECT rc; + ::SetRectEmpty(&rc); + hr = m_ole_object->DoVerb(OLEIVERB_INPLACEACTIVATE, NULL, this, 0, + m_hwndParent, &rc); + if (FAILED(hr)) + { + assert(0); + return hr; + } + + hr = m_ole_object->QueryInterface(&m_web_browser2); + if (FAILED(hr)) + { + assert(0); + return hr; + } + + HWND hwnd = GetControlWindow(); + + DWORD exstyle = GetWindowLong(hwnd, GWL_EXSTYLE); + SetWindowLong(hwnd, GWL_EXSTYLE, exstyle | WS_EX_CLIENTEDGE); + + ShowWindow(hwnd, SW_SHOWNORMAL); + + Release(); + + return S_OK; +} + +void MWebBrowser::Destroy() +{ + if (m_web_browser2) + m_web_browser2->Quit(); + + m_hwndParent = NULL; + m_hwndCtrl = NULL; + m_hwndIEServer = NULL; +} + +RECT MWebBrowser::PixelToHIMETRIC(const RECT& rc) +{ + HDC hDC = ::GetDC(NULL); + INT nPixelsPerInchX = ::GetDeviceCaps(hDC, LOGPIXELSX); + INT nPixelsPerInchY = ::GetDeviceCaps(hDC, LOGPIXELSY); + RECT ret; + ret.left = MulDiv(rc.left, 2540, nPixelsPerInchX); + ret.top = MulDiv(rc.top, 2540, nPixelsPerInchY); + ret.right = MulDiv(rc.right, 2540, nPixelsPerInchX); + ret.bottom = MulDiv(rc.bottom, 2540, nPixelsPerInchY); + ::ReleaseDC(NULL, hDC); + return ret; +} + +void MWebBrowser::MoveWindow(const RECT& rc) +{ + m_rc = rc; + + SIZEL siz; + RECT rcHIMETRIC = PixelToHIMETRIC(rc); + siz.cx = rcHIMETRIC.right - rcHIMETRIC.left; + siz.cy = rcHIMETRIC.bottom - rcHIMETRIC.top; + m_ole_object->SetExtent(DVASPECT_CONTENT, &siz); + + if (m_ole_inplace_object) + { + m_ole_inplace_object->SetObjectRects(&m_rc, &m_rc); + } +} + +void MWebBrowser::GoHome() +{ + if (m_web_browser2) + m_web_browser2->GoHome(); +} + +void MWebBrowser::GoBack() +{ + if (m_web_browser2) + m_web_browser2->GoBack(); +} + +void MWebBrowser::GoForward() +{ + if (m_web_browser2) + m_web_browser2->GoForward(); +} + +void MWebBrowser::Stop() +{ + if (m_web_browser2) + m_web_browser2->Stop(); +} + +void MWebBrowser::StopDownload() +{ + if (!m_web_browser2) + return; + + IDispatch *pDisp; + m_web_browser2->get_Document(&pDisp); + if (pDisp) + { + IOleCommandTarget *pCmdTarget = NULL; + pDisp->QueryInterface(&pCmdTarget); + if (pCmdTarget) + { + OLECMDEXECOPT option = OLECMDEXECOPT_DONTPROMPTUSER; + pCmdTarget->Exec(NULL, OLECMDID_STOPDOWNLOAD, option, NULL, NULL); + pCmdTarget->Release(); + } + pDisp->Release(); + } +} + +void MWebBrowser::Refresh() +{ + if (m_web_browser2) + m_web_browser2->Refresh(); +} + +HRESULT MWebBrowser::Navigate(const WCHAR *url) +{ + HRESULT hr = E_FAIL; + if (m_web_browser2) + { + bstr_t bstrURL(url); + variant_t flags(0); + hr = m_web_browser2->Navigate(bstrURL, &flags, 0, 0, 0); + } + return hr; +} + +HRESULT MWebBrowser::Navigate2(const WCHAR *url, DWORD dwFlags) +{ + HRESULT hr = E_FAIL; + if (!m_web_browser2) + { + return hr; + } + VARIANT var1, var2, varEmpty; + + VariantInit(&var1); + VariantInit(&var2); + VariantInit(&varEmpty); + + V_VT(&var1) = VT_BSTR; + V_BSTR(&var1) = SysAllocString(url); + + V_VT(&var2) = VT_I4; + V_I4(&var2) = dwFlags; + + V_VT(&varEmpty) = VT_EMPTY; + + hr = m_web_browser2->Navigate2(&var1, &var2, &varEmpty, &varEmpty, &varEmpty); + + VariantClear(&var1); + VariantClear(&var2); + VariantClear(&varEmpty); + + return hr; +} + +void MWebBrowser::Print(BOOL bBang) +{ + if (!m_web_browser2) + return; + + IDispatch *pDisp; + m_web_browser2->get_Document(&pDisp); + if (pDisp) + { + IOleCommandTarget *pCmdTarget = NULL; + pDisp->QueryInterface(&pCmdTarget); + if (pCmdTarget) + { + OLECMDEXECOPT option; + if (bBang) + option = OLECMDEXECOPT_DONTPROMPTUSER; + else + option = OLECMDEXECOPT_PROMPTUSER; + pCmdTarget->Exec(NULL, OLECMDID_PRINT, option, NULL, NULL); + pCmdTarget->Release(); + } + pDisp->Release(); + } +} + +void MWebBrowser::PrintPreview() +{ + if (!m_web_browser2) + return; + + IDispatch *pDisp; + m_web_browser2->get_Document(&pDisp); + if (pDisp) + { + IOleCommandTarget *pCmdTarget = NULL; + pDisp->QueryInterface(&pCmdTarget); + if (pCmdTarget) + { + OLECMDEXECOPT option = OLECMDEXECOPT_DONTPROMPTUSER; + pCmdTarget->Exec(NULL, OLECMDID_PRINTPREVIEW, option, NULL, NULL); + pCmdTarget->Release(); + } + pDisp->Release(); + } +} + +void MWebBrowser::PageSetup() +{ + if (!m_web_browser2) + return; + + IDispatch *pDisp; + m_web_browser2->get_Document(&pDisp); + if (pDisp) + { + IOleCommandTarget *pCmdTarget = NULL; + pDisp->QueryInterface(&pCmdTarget); + if (pCmdTarget) + { + OLECMDEXECOPT option = OLECMDEXECOPT_DONTPROMPTUSER; + pCmdTarget->Exec(NULL, OLECMDID_PAGESETUP, option, NULL, NULL); + pCmdTarget->Release(); + } + pDisp->Release(); + } +} + +BOOL MWebBrowser::TranslateAccelerator(LPMSG pMsg) +{ + if (!m_web_browser2) + return FALSE; + + IOleInPlaceActiveObject *pOIPAO = NULL; + HRESULT hr = m_web_browser2->QueryInterface(&pOIPAO); + if (SUCCEEDED(hr)) + { + hr = pOIPAO->TranslateAccelerator(pMsg); + pOIPAO->Release(); + return hr == S_OK; + } + return FALSE; +} + +HRESULT MWebBrowser::get_LocationURL(BSTR *bstrURL) const +{ + if (!m_web_browser2) + { + *bstrURL = NULL; + return E_FAIL; + } + + return m_web_browser2->get_LocationURL(bstrURL); +} + +HRESULT MWebBrowser::get_mimeType(BSTR *bstrMIME) const +{ + if (!m_web_browser2) + { + *bstrMIME = NULL; + return E_FAIL; + } + + HRESULT hr = E_FAIL; + IDispatch *pDisp; + m_web_browser2->get_Document(&pDisp); + if (pDisp) + { + IHTMLDocument2 *pDocument = static_cast(pDisp); + hr = pDocument->get_mimeType(bstrMIME); + pDisp->Release(); + } + + return hr; +} + +BOOL MWebBrowser::is_busy() const +{ + if (!m_web_browser2) + { + return FALSE; + } + + VARIANT_BOOL b = FALSE; + m_web_browser2->get_Busy(&b); + return b; +} + +HRESULT MWebBrowser::get_Application(IDispatch **ppApplication) const +{ + *ppApplication = NULL; + if (!m_web_browser2) + return E_NOINTERFACE; + + return m_web_browser2->get_Application(ppApplication); +} + +void MWebBrowser::AllowInsecure(BOOL bAllow) +{ + m_bAllowInsecure = bAllow; +} + +HRESULT MWebBrowser::put_Silent(VARIANT_BOOL bSilent) +{ + if (!m_web_browser2) + return E_NOINTERFACE; + return m_web_browser2->put_Silent(bSilent); +} + +HRESULT MWebBrowser::ZoomUp() +{ + LONG percents = m_nZoomPercents; + if (percents >= 300) + return E_FAIL; + + if (percents < 100) + { + percents += 10; + } + else + { + percents += 50; + } + + return ZoomPercents(percents); +} + +HRESULT MWebBrowser::ZoomDown() +{ + LONG percents = m_nZoomPercents; + if (percents <= 50) + return E_FAIL; + + if (percents > 100) + { + percents -= 50; + } + else + { + percents -= 10; + } + + return ZoomPercents(percents); +} + +HRESULT MWebBrowser::Zoom100() +{ + return ZoomPercents(100); +} + +HRESULT MWebBrowser::ZoomPercents(LONG percents) +{ + VARIANT zoom; + VariantInit(&zoom); + V_VT(&zoom) = VT_I4; + V_I4(&zoom) = percents; + + OLECMDEXECOPT option = OLECMDEXECOPT_DONTPROMPTUSER; + HRESULT hr = m_web_browser2->ExecWB(OLECMDID_OPTICAL_ZOOM, option, &zoom, NULL); + if (SUCCEEDED(hr)) + { + m_nZoomPercents = percents; + } + return hr; +} + +// IUnknown interface + +STDMETHODIMP MWebBrowser::QueryInterface(REFIID riid, void **ppvObj) +{ + if (riid == __uuidof(IUnknown)) + { + *ppvObj = static_cast(this); + } + else if (riid == __uuidof(IOleInPlaceSite)) + { + *ppvObj = static_cast(this); + } + else if (riid == __uuidof(IServiceProvider)) + { + *ppvObj = static_cast(this); + } + else if (riid == __uuidof(IDocHostUIHandler)) + { + *ppvObj = static_cast(this); + } + else + { + return E_NOINTERFACE; + } + + AddRef(); + return S_OK; +} + +STDMETHODIMP_(ULONG) MWebBrowser::AddRef() +{ + m_nRefCount++; + return m_nRefCount; +} + +STDMETHODIMP_(ULONG) MWebBrowser::Release() +{ + --m_nRefCount; + if (m_nRefCount != 0) + return m_nRefCount; + + delete this; + return 0; +} + +// IOleWindow interface + +STDMETHODIMP MWebBrowser::GetWindow(HWND *phwnd) +{ + *phwnd = m_hwndParent; + return S_OK; +} + +STDMETHODIMP MWebBrowser::ContextSensitiveHelp(BOOL fEnterMode) +{ + return E_NOTIMPL; +} + +// IOleInPlaceSite interface + +STDMETHODIMP MWebBrowser::CanInPlaceActivate() +{ + return S_OK; +} + +STDMETHODIMP MWebBrowser::OnInPlaceActivate() +{ + ::OleLockRunning(m_ole_object, TRUE, FALSE); + m_ole_object->QueryInterface(&m_ole_inplace_object); + m_ole_inplace_object->SetObjectRects(&m_rc, &m_rc); + return S_OK; +} + +STDMETHODIMP MWebBrowser::OnUIActivate() +{ + return S_OK; +} + +STDMETHODIMP MWebBrowser::GetWindowContext( + IOleInPlaceFrame **ppFrame, + IOleInPlaceUIWindow **ppDoc, + LPRECT lprcPosRect, + LPRECT lprcClipRect, + LPOLEINPLACEFRAMEINFO lpFrameInfo) +{ + *ppFrame = NULL; + *ppDoc = NULL; + *lprcPosRect = m_rc; + *lprcClipRect = *lprcPosRect; + + lpFrameInfo->fMDIApp = FALSE; + lpFrameInfo->hwndFrame = m_hwndParent; + lpFrameInfo->haccel = NULL; + lpFrameInfo->cAccelEntries = 0; + + return S_OK; +} + +STDMETHODIMP MWebBrowser::Scroll(SIZE scrollExtant) +{ + return E_NOTIMPL; +} + +STDMETHODIMP MWebBrowser::OnUIDeactivate(BOOL fUndoable) +{ + return S_OK; +} + +STDMETHODIMP MWebBrowser::OnInPlaceDeactivate() +{ + m_hwndCtrl = NULL; + m_ole_inplace_object = NULL; + return S_OK; +} + +STDMETHODIMP MWebBrowser::DiscardUndoState() +{ + return E_NOTIMPL; +} + +STDMETHODIMP MWebBrowser::DeactivateAndUndo() +{ + return E_NOTIMPL; +} + +STDMETHODIMP MWebBrowser::OnPosRectChange(LPCRECT lprcPosRect) +{ + return E_NOTIMPL; +} + +// IOleClientSite interface + +STDMETHODIMP MWebBrowser::SaveObject() +{ + return E_NOTIMPL; +} + +STDMETHODIMP MWebBrowser::GetMoniker( + DWORD dwAssign, + DWORD dwWhichMoniker, + IMoniker **ppmk) +{ + if (dwAssign == OLEGETMONIKER_ONLYIFTHERE && + dwWhichMoniker == OLEWHICHMK_CONTAINER) + { + return E_FAIL; + } + + return E_NOTIMPL; +} + +STDMETHODIMP MWebBrowser::GetContainer(IOleContainer **ppContainer) +{ + return E_NOINTERFACE; +} + +STDMETHODIMP MWebBrowser::ShowObject() +{ + return S_OK; +} + +STDMETHODIMP MWebBrowser::OnShowWindow(BOOL fShow) +{ + return S_OK; +} + +STDMETHODIMP MWebBrowser::RequestNewObjectLayout() +{ + return E_NOTIMPL; +} + +// IStorage interface + +STDMETHODIMP MWebBrowser::CreateStream( + const OLECHAR *pwcsName, + DWORD grfMode, + DWORD reserved1, + DWORD reserved2, + IStream **ppstm) +{ + return E_NOTIMPL; +} + +STDMETHODIMP MWebBrowser::OpenStream( + const OLECHAR *pwcsName, + void *reserved1, + DWORD grfMode, + DWORD reserved2, + IStream **ppstm) +{ + return E_NOTIMPL; +} + +STDMETHODIMP MWebBrowser::CreateStorage( + const OLECHAR *pwcsName, + DWORD grfMode, + DWORD reserved1, + DWORD reserved2, + IStorage **ppstg) +{ + return E_NOTIMPL; +} + +STDMETHODIMP MWebBrowser::OpenStorage( + const OLECHAR *pwcsName, + IStorage *pstgPriority, + DWORD grfMode, + SNB snbExclude, + DWORD reserved, + IStorage **ppstg) +{ + return E_NOTIMPL; +} + +STDMETHODIMP MWebBrowser::CopyTo( + DWORD ciidExclude, + const IID *rgiidExclude, + SNB snbExclude, + IStorage *pstgDest) +{ + return E_NOTIMPL; +} + +STDMETHODIMP MWebBrowser::MoveElementTo( + const OLECHAR *pwcsName, + IStorage *pstgDest, + const OLECHAR *pwcsNewName, + DWORD grfFlags) +{ + return E_NOTIMPL; +} + +STDMETHODIMP MWebBrowser::Commit(DWORD grfCommitFlags) +{ + return E_NOTIMPL; +} + +STDMETHODIMP MWebBrowser::Revert() +{ + return E_NOTIMPL; +} + +STDMETHODIMP MWebBrowser::EnumElements( + DWORD reserved1, + void *reserved2, + DWORD reserved3, + IEnumSTATSTG **ppenum) +{ + return E_NOTIMPL; +} + +STDMETHODIMP MWebBrowser::DestroyElement( + const OLECHAR *pwcsName) +{ + return E_NOTIMPL; +} + +STDMETHODIMP MWebBrowser::RenameElement( + const OLECHAR *pwcsOldName, + const OLECHAR *pwcsNewName) +{ + return E_NOTIMPL; +} + +STDMETHODIMP MWebBrowser::SetElementTimes( + const OLECHAR *pwcsName, + const FILETIME *pctime, + const FILETIME *patime, + const FILETIME *pmtime) +{ + return E_NOTIMPL; +} + +STDMETHODIMP MWebBrowser::SetClass(REFCLSID clsid) +{ + return S_OK; +} + +STDMETHODIMP MWebBrowser::SetStateBits(DWORD grfStateBits, DWORD grfMask) +{ + return E_NOTIMPL; +} + +STDMETHODIMP MWebBrowser::Stat(STATSTG *pstatstg, DWORD grfStatFlag) +{ + return E_NOTIMPL; +} + +// IServiceProvider interface + +STDMETHODIMP MWebBrowser::QueryService( + REFGUID guidService, + REFIID riid, + void **ppvObject) +{ + *ppvObject = NULL; + + if (riid == __uuidof(IWindowForBindingUI) || + riid == __uuidof(IHttpSecurity)) + { + *ppvObject = static_cast(this); + } + else + { + return E_NOTIMPL; + } + + AddRef(); + return S_OK; +} + +// IWindowForBindingUI interface + +STDMETHODIMP MWebBrowser::GetWindow(REFGUID rguidReason, HWND *phwnd) +{ + *phwnd = m_hwndParent; + return S_OK; +} + + +STDMETHODIMP MWebBrowser::OnSecurityProblem(DWORD dwProblem) +{ + printf("MWebBrowser::OnSecurityProblem\n"); + + BSTR url = NULL; + get_LocationURL(&url); + if (url) + { + SysFreeString(url); + } + + + { + return S_OK; + } + + { + return S_OK; + } + + return E_ABORT; +} + +// IDocHostUIHandler interface + +STDMETHODIMP MWebBrowser::ShowContextMenu( + DWORD dwID, + POINT *ppt, + IUnknown *pcmdtReserved, + IDispatch *pdispReserved) +{ + return S_FALSE; +} + +STDMETHODIMP MWebBrowser::GetHostInfo(DOCHOSTUIINFO *pInfo) +{ + if (m_pDocHostUIHandler) + return m_pDocHostUIHandler->GetHostInfo(pInfo); + return E_NOTIMPL; +} + +STDMETHODIMP MWebBrowser::ShowUI( + DWORD dwID, + IOleInPlaceActiveObject *pActiveObject, + IOleCommandTarget *pCommandTarget, + IOleInPlaceFrame *pFrame, + IOleInPlaceUIWindow *pDoc) +{ + if (m_pDocHostUIHandler) + return m_pDocHostUIHandler->ShowUI(dwID, pActiveObject, pCommandTarget, pFrame, pDoc); + return E_NOTIMPL; +} + +STDMETHODIMP MWebBrowser::HideUI() +{ + if (m_pDocHostUIHandler) + return m_pDocHostUIHandler->HideUI(); + return E_NOTIMPL; +} + +STDMETHODIMP MWebBrowser::UpdateUI() +{ + if (m_pDocHostUIHandler) + return m_pDocHostUIHandler->UpdateUI(); + return E_NOTIMPL; +} + +STDMETHODIMP MWebBrowser::EnableModeless(BOOL fEnable) +{ + if (m_pDocHostUIHandler) + return m_pDocHostUIHandler->EnableModeless(fEnable); + return E_NOTIMPL; +} + +STDMETHODIMP MWebBrowser::OnDocWindowActivate(BOOL fActivate) +{ + if (m_pDocHostUIHandler) + return m_pDocHostUIHandler->OnDocWindowActivate(fActivate); + return E_NOTIMPL; +} + +STDMETHODIMP MWebBrowser::OnFrameWindowActivate(BOOL fActivate) +{ + if (m_pDocHostUIHandler) + return m_pDocHostUIHandler->OnFrameWindowActivate(fActivate); + return E_NOTIMPL; +} + +STDMETHODIMP MWebBrowser::ResizeBorder( + LPCRECT prcBorder, + IOleInPlaceUIWindow *pUIWindow, + BOOL fRameWindow) +{ + if (m_pDocHostUIHandler) + return m_pDocHostUIHandler->ResizeBorder(prcBorder, pUIWindow, fRameWindow); + return E_NOTIMPL; +} + +STDMETHODIMP MWebBrowser::TranslateAccelerator( + LPMSG lpMsg, + const GUID *pguidCmdGroup, + DWORD nCmdID) +{ + return S_FALSE; +} + +STDMETHODIMP MWebBrowser::GetOptionKeyPath(LPOLESTR *pchKey, DWORD dw) +{ + return S_FALSE; +} + +STDMETHODIMP MWebBrowser::GetDropTarget( + IDropTarget *pDropTarget, + IDropTarget **ppDropTarget) +{ + *ppDropTarget = NULL; + return E_NOTIMPL; +} + +STDMETHODIMP MWebBrowser::GetExternal(IDispatch **ppDispatch) +{ + *ppDispatch = NULL; + return E_NOTIMPL; +} + +STDMETHODIMP MWebBrowser::TranslateUrl( + DWORD dwTranslate, + OLECHAR *pchURLIn, + OLECHAR **ppchURLOut) +{ + *ppchURLOut = NULL; + return S_FALSE; +} + +STDMETHODIMP MWebBrowser::FilterDataObject(IDataObject *pDO, IDataObject **ppDORet) +{ + *ppDORet = NULL; + return S_FALSE; +} + +HRESULT MWebBrowser::Quit() +{ + if (!m_web_browser2) + return E_NOINTERFACE; + + return m_web_browser2->Quit(); +} diff --git a/plugins/winsharedutils/MWebBrowser.hpp b/plugins/winsharedutils/MWebBrowser.hpp new file mode 100644 index 00000000..1de4e403 --- /dev/null +++ b/plugins/winsharedutils/MWebBrowser.hpp @@ -0,0 +1,225 @@ +// MWebBrowser.cpp --- simple Win32 Web Browser +// Copyright (C) 2019 Katayama Hirofumi MZ +// This file is public domain software. + +#ifndef MWEB_BROWSER_HPP_ +#define MWEB_BROWSER_HPP_ 13 // Version 13 + +#define INITGUID +#include +#include +#include +#include + +class MWebBrowser : + public IOleClientSite, + public IOleInPlaceSite, + public IStorage, + public IServiceProvider, + public IHttpSecurity, + public IDocHostUIHandler +{ +public: + static MWebBrowser *Create(HWND hwndParent); + + RECT PixelToHIMETRIC(const RECT& rc); + HWND GetControlWindow(); + HWND GetIEServerWindow(); + void MoveWindow(const RECT& rc); + + void GoHome(); + void GoBack(); + void GoForward(); + void Stop(); + void StopDownload(); + void Refresh(); + HRESULT Navigate(const WCHAR *url = L"about:blank"); + HRESULT Navigate2(const WCHAR *url, DWORD dwFlags = 0); + void Print(BOOL bBang = FALSE); + void PrintPreview(); + void PageSetup(); + void Destroy(); + BOOL TranslateAccelerator(LPMSG pMsg); + IWebBrowser2 *GetIWebBrowser2(); + IHTMLDocument2 *GetIHTMLDocument2(); + void AllowInsecure(BOOL bAllow); + HRESULT Quit(); + + HRESULT get_Application(IDispatch **ppApplication) const; + HRESULT get_LocationURL(BSTR *bstrURL) const; + HRESULT get_mimeType(BSTR *bstrMIME) const; + HRESULT put_Silent(VARIANT_BOOL bSilent); + BOOL is_busy() const; + HRESULT ZoomUp(); + HRESULT ZoomDown(); + HRESULT Zoom100(); + HRESULT ZoomPercents(LONG percents); + + // IUnknown interface + STDMETHODIMP QueryInterface(REFIID riid, void **ppvObj); + STDMETHODIMP_(ULONG) AddRef(); + STDMETHODIMP_(ULONG) Release(); + + // IOleWindow interface + STDMETHODIMP GetWindow(HWND *phwnd); + STDMETHODIMP ContextSensitiveHelp(BOOL fEnterMode); + + // IOleInPlaceSite interface + STDMETHODIMP CanInPlaceActivate(); + STDMETHODIMP OnInPlaceActivate(); + STDMETHODIMP OnUIActivate(); + STDMETHODIMP GetWindowContext( + IOleInPlaceFrame **ppFrame, + IOleInPlaceUIWindow **ppDoc, + LPRECT lprcPosRect, + LPRECT lprcClipRect, + LPOLEINPLACEFRAMEINFO lpFrameInfo); + STDMETHODIMP Scroll(SIZE scrollExtant); + STDMETHODIMP OnUIDeactivate(BOOL fUndoable); + STDMETHODIMP OnInPlaceDeactivate(); + STDMETHODIMP DiscardUndoState(); + STDMETHODIMP DeactivateAndUndo(); + STDMETHODIMP OnPosRectChange(LPCRECT lprcPosRect); + + // IOleClientSite interface + STDMETHODIMP SaveObject(); + STDMETHODIMP GetMoniker( + DWORD dwAssign, + DWORD dwWhichMoniker, + IMoniker **ppmk); + STDMETHODIMP GetContainer(IOleContainer **ppContainer); + STDMETHODIMP ShowObject(); + STDMETHODIMP OnShowWindow(BOOL fShow); + STDMETHODIMP RequestNewObjectLayout(); + + // IStorage interface + STDMETHODIMP CreateStream( + const OLECHAR *pwcsName, + DWORD grfMode, + DWORD reserved1, + DWORD reserved2, + IStream **ppstm); + STDMETHODIMP OpenStream( + const OLECHAR *pwcsName, + void *reserved1, + DWORD grfMode, + DWORD reserved2, + IStream **ppstm); + STDMETHODIMP CreateStorage( + const OLECHAR *pwcsName, + DWORD grfMode, + DWORD reserved1, + DWORD reserved2, + IStorage **ppstg); + STDMETHODIMP OpenStorage( + const OLECHAR *pwcsName, + IStorage *pstgPriority, + DWORD grfMode, + SNB snbExclude, + DWORD reserved, + IStorage **ppstg); + STDMETHODIMP CopyTo( + DWORD ciidExclude, + const IID *rgiidExclude, + SNB snbExclude, + IStorage *pstgDest); + STDMETHODIMP MoveElementTo( + const OLECHAR *pwcsName, + IStorage *pstgDest, + const OLECHAR *pwcsNewName, + DWORD grfFlags); + STDMETHODIMP Commit(DWORD grfCommitFlags); + STDMETHODIMP Revert(); + STDMETHODIMP EnumElements( + DWORD reserved1, + void *reserved2, + DWORD reserved3, + IEnumSTATSTG **ppenum); + STDMETHODIMP DestroyElement(const OLECHAR *pwcsName); + STDMETHODIMP RenameElement( + const OLECHAR *pwcsOldName, + const OLECHAR *pwcsNewName); + STDMETHODIMP SetElementTimes( + const OLECHAR *pwcsName, + const FILETIME *pctime, + const FILETIME *patime, + const FILETIME *pmtime); + STDMETHODIMP SetClass(REFCLSID clsid); + STDMETHODIMP SetStateBits(DWORD grfStateBits, DWORD grfMask); + STDMETHODIMP Stat(STATSTG *pstatstg, DWORD grfStatFlag); + + // IServiceProvider interface + STDMETHODIMP QueryService( + REFGUID guidService, + REFIID riid, + void **ppvObject); + + // IWindowForBindingUI interface + STDMETHODIMP GetWindow(REFGUID rguidReason, HWND *phwnd); + + // IHttpSecurity interface + STDMETHODIMP OnSecurityProblem(DWORD dwProblem); + + // IDocHostUIHandler interface + STDMETHODIMP ShowContextMenu( + DWORD dwID, + POINT *ppt, + IUnknown *pcmdtReserved, + IDispatch *pdispReserved); + STDMETHODIMP GetHostInfo(DOCHOSTUIINFO *pInfo); + STDMETHODIMP ShowUI( + DWORD dwID, + IOleInPlaceActiveObject *pActiveObject, + IOleCommandTarget *pCommandTarget, + IOleInPlaceFrame *pFrame, + IOleInPlaceUIWindow *pDoc); + STDMETHODIMP HideUI(); + STDMETHODIMP UpdateUI(); + STDMETHODIMP EnableModeless(BOOL fEnable); + STDMETHODIMP OnDocWindowActivate(BOOL fActivate); + STDMETHODIMP OnFrameWindowActivate(BOOL fActivate); + STDMETHODIMP ResizeBorder( + LPCRECT prcBorder, + IOleInPlaceUIWindow *pUIWindow, + BOOL fRameWindow); + STDMETHODIMP TranslateAccelerator( + LPMSG lpMsg, + const GUID *pguidCmdGroup, + DWORD nCmdID); + STDMETHODIMP GetOptionKeyPath(LPOLESTR *pchKey, DWORD dw); + STDMETHODIMP GetDropTarget( + IDropTarget *pDropTarget, + IDropTarget **ppDropTarget); + STDMETHODIMP GetExternal(IDispatch **ppDispatch); + STDMETHODIMP TranslateUrl( + DWORD dwTranslate, + OLECHAR *pchURLIn, + OLECHAR **ppchURLOut); + STDMETHODIMP FilterDataObject(IDataObject *pDO, IDataObject **ppDORet); + +protected: + LONG m_nRefCount; + HWND m_hwndParent; + HWND m_hwndCtrl; + HWND m_hwndIEServer; + IWebBrowser2 *m_web_browser2; + IOleObject *m_ole_object; + IOleInPlaceObject *m_ole_inplace_object; + IDocHostUIHandler *m_pDocHostUIHandler; + RECT m_rc; + HRESULT m_hr; + BOOL m_bAllowInsecure; + LONG m_nZoomPercents; + + MWebBrowser(HWND hwndParent); + virtual ~MWebBrowser(); + + HRESULT CreateBrowser(HWND hwndParent); + BOOL IsCreated() const; + +private: + MWebBrowser(const MWebBrowser&); + MWebBrowser& operator=(const MWebBrowser&); +}; + +#endif // ndef MWEB_BROWSER_HPP_ diff --git a/plugins/winsharedutils/SimpleBrowser.cpp b/plugins/winsharedutils/SimpleBrowser.cpp new file mode 100644 index 00000000..43039660 --- /dev/null +++ b/plugins/winsharedutils/SimpleBrowser.cpp @@ -0,0 +1,102 @@ +// SimpleBrowser.cpp --- simple Win32 browser +// Copyright (C) 2019 Katayama Hirofumi MZ +// This file is public domain software. + +#define _CRT_SECURE_NO_WARNINGS +// SimpleBrowser.cpp --- simple Win32 browser +// Copyright (C) 2019 Katayama Hirofumi MZ +// This file is public domain software. + +#define _CRT_SECURE_NO_WARNINGS +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "MWebBrowser.hpp" + + +BOOL DoSetBrowserEmulation(DWORD dwValue) +{ + static const TCHAR s_szFeatureControl[] = + TEXT("SOFTWARE\\Microsoft\\Internet Explorer\\Main\\FeatureControl"); + + TCHAR szPath[MAX_PATH], *pchFileName; + GetModuleFileName(NULL, szPath, ARRAYSIZE(szPath)); + pchFileName = PathFindFileName(szPath); + + BOOL bOK = FALSE; + HKEY hkeyControl = NULL; + RegOpenKeyEx(HKEY_CURRENT_USER, s_szFeatureControl, 0, KEY_ALL_ACCESS, &hkeyControl); + if (hkeyControl) + { + HKEY hkeyEmulation = NULL; + RegCreateKeyEx(hkeyControl, TEXT("FEATURE_BROWSER_EMULATION"), 0, NULL, 0, + KEY_ALL_ACCESS, NULL, &hkeyEmulation, NULL); + if (hkeyEmulation) + { + if (dwValue) + { + DWORD value = dwValue, size = sizeof(value); + LONG result = RegSetValueEx(hkeyEmulation, pchFileName, 0, + REG_DWORD, (LPBYTE)&value, size); + bOK = (result == ERROR_SUCCESS); + } + else + { + RegDeleteValue(hkeyEmulation, pchFileName); + bOK = TRUE; + } + + RegCloseKey(hkeyEmulation); + } + + RegCloseKey(hkeyControl); + } + + return bOK; +} +extern "C" __declspec(dllexport) void* html_new( HWND parent) { + DoSetBrowserEmulation(1); + auto s_pWebBrowser = MWebBrowser::Create(parent); + if (!s_pWebBrowser) + return NULL; + + s_pWebBrowser->put_Silent(VARIANT_TRUE); + + s_pWebBrowser->AllowInsecure(TRUE); + + return s_pWebBrowser; +} + +extern "C" __declspec(dllexport) void html_navigate(void* web, wchar_t* path) { + if(!web)return; + auto ww =static_cast(web); + ww->Navigate2(path); +} +extern "C" __declspec(dllexport) void html_resize(void* web,int x,int y,int w, int h) { + if(!web)return; + auto ww = static_cast(web); + RECT r; + r.left = x; + r.top = y; + r.right = x + w; + r.bottom = y + h; + ww->MoveWindow(r); +} +extern "C" __declspec(dllexport) void html_release(void* web) { + if(!web)return; + auto ww = static_cast(web); + ww->Destroy(); + ww->Release(); +} \ No newline at end of file diff --git a/plugins/winsharedutils/WebBrowser.cpp b/plugins/winsharedutils/WebBrowser.cpp deleted file mode 100644 index 5cd7fbf1..00000000 --- a/plugins/winsharedutils/WebBrowser.cpp +++ /dev/null @@ -1,653 +0,0 @@ - -#include -#include -#include -#include -#include - -#include -#include -using namespace std; - -class WebBrowser : - public IOleClientSite, - public IOleInPlaceSite, - public IStorage -{ - -public: - - WebBrowser(HWND hWndParent); - - bool CreateBrowser(); - - RECT PixelToHiMetric(const RECT& _rc); - - virtual void SetRect(const RECT& _rc); - - // ----- Control methods ----- - - void GoBack(); - - void GoForward(); - - void Refresh(); - - void Navigate(wstring szUrl); - - // ----- IUnknown ----- - - virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, - void** ppvObject) override; - - virtual ULONG STDMETHODCALLTYPE AddRef(void); - - virtual ULONG STDMETHODCALLTYPE Release(void); - - // ---------- IOleWindow ---------- - - virtual HRESULT STDMETHODCALLTYPE GetWindow( - __RPC__deref_out_opt HWND* phwnd) override; - - virtual HRESULT STDMETHODCALLTYPE ContextSensitiveHelp( - BOOL fEnterMode) override; - - // ---------- IOleInPlaceSite ---------- - - virtual HRESULT STDMETHODCALLTYPE CanInPlaceActivate(void) override; - - virtual HRESULT STDMETHODCALLTYPE OnInPlaceActivate(void) override; - - virtual HRESULT STDMETHODCALLTYPE OnUIActivate(void) override; - - virtual HRESULT STDMETHODCALLTYPE GetWindowContext( - __RPC__deref_out_opt IOleInPlaceFrame** ppFrame, - __RPC__deref_out_opt IOleInPlaceUIWindow** ppDoc, - __RPC__out LPRECT lprcPosRect, - __RPC__out LPRECT lprcClipRect, - __RPC__inout LPOLEINPLACEFRAMEINFO lpFrameInfo) override; - - virtual HRESULT STDMETHODCALLTYPE Scroll( - SIZE scrollExtant) override; - - virtual HRESULT STDMETHODCALLTYPE OnUIDeactivate( - BOOL fUndoable) override; - - virtual HWND GetControlWindow(); - - virtual HRESULT STDMETHODCALLTYPE OnInPlaceDeactivate(void) override; - - virtual HRESULT STDMETHODCALLTYPE DiscardUndoState(void) override; - - virtual HRESULT STDMETHODCALLTYPE DeactivateAndUndo(void) override; - - virtual HRESULT STDMETHODCALLTYPE OnPosRectChange( - __RPC__in LPCRECT lprcPosRect) override; - - // ---------- IOleClientSite ---------- - - virtual HRESULT STDMETHODCALLTYPE SaveObject(void) override; - - virtual HRESULT STDMETHODCALLTYPE GetMoniker( - DWORD dwAssign, - DWORD dwWhichMoniker, - __RPC__deref_out_opt IMoniker** ppmk) override; - - virtual HRESULT STDMETHODCALLTYPE GetContainer( - __RPC__deref_out_opt IOleContainer** ppContainer) override; - - virtual HRESULT STDMETHODCALLTYPE ShowObject(void) override; - virtual HRESULT STDMETHODCALLTYPE OnShowWindow( - BOOL fShow) override; - - virtual HRESULT STDMETHODCALLTYPE RequestNewObjectLayout(void) override; - - // ----- IStorage ----- - - virtual HRESULT STDMETHODCALLTYPE CreateStream( - __RPC__in_string const OLECHAR* pwcsName, - DWORD grfMode, - DWORD reserved1, - DWORD reserved2, - __RPC__deref_out_opt IStream** ppstm) override; - - virtual HRESULT STDMETHODCALLTYPE OpenStream( - const OLECHAR* pwcsName, - void* reserved1, - DWORD grfMode, - DWORD reserved2, - IStream** ppstm) override; - - virtual HRESULT STDMETHODCALLTYPE CreateStorage( - __RPC__in_string const OLECHAR* pwcsName, - DWORD grfMode, - DWORD reserved1, - DWORD reserved2, - __RPC__deref_out_opt IStorage** ppstg) override; - - virtual HRESULT STDMETHODCALLTYPE OpenStorage( - __RPC__in_opt_string const OLECHAR* pwcsName, - __RPC__in_opt IStorage* pstgPriority, - DWORD grfMode, - __RPC__deref_opt_in_opt SNB snbExclude, - DWORD reserved, - __RPC__deref_out_opt IStorage** ppstg) override; - - virtual HRESULT STDMETHODCALLTYPE CopyTo( - DWORD ciidExclude, - const IID* rgiidExclude, - __RPC__in_opt SNB snbExclude, - IStorage* pstgDest) override; - - virtual HRESULT STDMETHODCALLTYPE MoveElementTo( - __RPC__in_string const OLECHAR* pwcsName, - __RPC__in_opt IStorage* pstgDest, - __RPC__in_string const OLECHAR* pwcsNewName, - DWORD grfFlags) override; - - virtual HRESULT STDMETHODCALLTYPE Commit( - DWORD grfCommitFlags) override; - - virtual HRESULT STDMETHODCALLTYPE Revert(void) override; - - virtual HRESULT STDMETHODCALLTYPE EnumElements( - DWORD reserved1, - void* reserved2, - DWORD reserved3, - IEnumSTATSTG** ppenum) override; - - virtual HRESULT STDMETHODCALLTYPE DestroyElement( - __RPC__in_string const OLECHAR* pwcsName) override; - - virtual HRESULT STDMETHODCALLTYPE RenameElement( - __RPC__in_string const OLECHAR* pwcsOldName, - __RPC__in_string const OLECHAR* pwcsNewName) override; - - virtual HRESULT STDMETHODCALLTYPE SetElementTimes( - __RPC__in_opt_string const OLECHAR* pwcsName, - __RPC__in_opt const FILETIME* pctime, - __RPC__in_opt const FILETIME* patime, - __RPC__in_opt const FILETIME* pmtime) override; - - virtual HRESULT STDMETHODCALLTYPE SetClass( - __RPC__in REFCLSID clsid) override; - virtual HRESULT STDMETHODCALLTYPE SetStateBits( - DWORD grfStateBits, - DWORD grfMask) override; - - virtual HRESULT STDMETHODCALLTYPE Stat( - __RPC__out STATSTG* pstatstg, - DWORD grfStatFlag) override; - -protected: - - IOleObject* oleObject; - IOleInPlaceObject* oleInPlaceObject; - - IWebBrowser2* webBrowser2; - - LONG iComRefCount; - - RECT rObject; - - HWND hWndParent; - HWND hWndControl; - -}; -WebBrowser::WebBrowser(HWND _hWndParent) -{ - iComRefCount = 0; - ::SetRect(&rObject, -300, -300, 300, 300); - hWndParent = _hWndParent; - - if (CreateBrowser() == FALSE) - { - return; - } - - ShowWindow(GetControlWindow(), SW_SHOW); - this->webBrowser2->put_Silent(VARIANT_TRUE);//免错误提示 - - this->Navigate(_T("about:blank")); -} - -bool WebBrowser::CreateBrowser() -{ - HRESULT hr; - hr = ::OleCreate(CLSID_WebBrowser, - IID_IOleObject, OLERENDER_DRAW, 0, this, this, - (void**)&oleObject); - - if (FAILED(hr)) - { - MessageBox(NULL, _T("Cannot create oleObject CLSID_WebBrowser"), - _T("Error"), - MB_ICONERROR); - return FALSE; - } - - hr = oleObject->SetClientSite(this); - hr = OleSetContainedObject(oleObject, TRUE); - - RECT posRect; - ::SetRect(&posRect, -300, -300, 300, 300); - hr = oleObject->DoVerb(OLEIVERB_INPLACEACTIVATE, - NULL, this, -1, hWndParent, &posRect); - if (FAILED(hr)) - { - MessageBox(NULL, _T("oleObject->DoVerb() failed"), - _T("Error"), - MB_ICONERROR); - return FALSE; - } - - hr = oleObject->QueryInterface(&webBrowser2); - if (FAILED(hr)) - { - MessageBox(NULL, _T("oleObject->QueryInterface(&webBrowser2) failed"), - _T("Error"), - MB_ICONERROR); - return FALSE; - } - - return TRUE; -} - -RECT WebBrowser::PixelToHiMetric(const RECT& _rc) -{ - static bool s_initialized = false; - static int s_pixelsPerInchX, s_pixelsPerInchY; - if (!s_initialized) - { - HDC hdc = ::GetDC(0); - s_pixelsPerInchX = ::GetDeviceCaps(hdc, LOGPIXELSX); - s_pixelsPerInchY = ::GetDeviceCaps(hdc, LOGPIXELSY); - ::ReleaseDC(0, hdc); - s_initialized = true; - } - - RECT rc; - rc.left = MulDiv(2540, _rc.left, s_pixelsPerInchX); - rc.top = MulDiv(2540, _rc.top, s_pixelsPerInchY); - rc.right = MulDiv(2540, _rc.right, s_pixelsPerInchX); - rc.bottom = MulDiv(2540, _rc.bottom, s_pixelsPerInchY); - return rc; -} - -void WebBrowser::SetRect(const RECT& _rc) -{ - rObject = _rc; - - { - RECT hiMetricRect = PixelToHiMetric(rObject); - SIZEL sz; - sz.cx = hiMetricRect.right - hiMetricRect.left; - sz.cy = hiMetricRect.bottom - hiMetricRect.top; - oleObject->SetExtent(DVASPECT_CONTENT, &sz); - } - - if (oleInPlaceObject != 0) - { - oleInPlaceObject->SetObjectRects(&rObject, &rObject); - } -} - -// ----- Control methods ----- - -void WebBrowser::GoBack() -{ - this->webBrowser2->GoBack(); -} - -void WebBrowser::GoForward() -{ - this->webBrowser2->GoForward(); -} - -void WebBrowser::Refresh() -{ - this->webBrowser2->Refresh(); -} - -void WebBrowser::Navigate(wstring szUrl) -{ - bstr_t url(szUrl.c_str()); - variant_t flags(0x02u); //navNoHistory - VARIANT url2; - url2.vt = VT_BSTR; - //url2.bstrVal =const_cast( LR"(C:\dataH\LunaTranslator_x86\cache\vndb\04472259b1e767bf451ac93d320450ef.html)"); - url2.bstrVal = const_cast (szUrl.c_str()); - this->webBrowser2->Navigate2(&url2, nullptr, nullptr, nullptr, nullptr); - // this->webBrowser2->Navigate(url, &flags, 0, 0, 0); //仅支持在线网页 -} - -// ----- IUnknown ----- - -HRESULT STDMETHODCALLTYPE WebBrowser::QueryInterface(REFIID riid, - void** ppvObject) -{ - if (riid == __uuidof(IUnknown)) - { - (*ppvObject) = static_cast(this); - } - else if (riid == __uuidof(IOleInPlaceSite)) - { - (*ppvObject) = static_cast(this); - } - else - { - return E_NOINTERFACE; - } - - AddRef(); - return S_OK; -} - -ULONG STDMETHODCALLTYPE WebBrowser::AddRef(void) -{ - iComRefCount++; - return iComRefCount; -} - -ULONG STDMETHODCALLTYPE WebBrowser::Release(void) -{ - iComRefCount--; - return iComRefCount; -} - -// ---------- IOleWindow ---------- - -HRESULT STDMETHODCALLTYPE WebBrowser::GetWindow( - __RPC__deref_out_opt HWND* phwnd) -{ - (*phwnd) = hWndParent; - return S_OK; -} - -HRESULT STDMETHODCALLTYPE WebBrowser::ContextSensitiveHelp( - BOOL fEnterMode) -{ - return E_NOTIMPL; -} - -// ---------- IOleInPlaceSite ---------- - -HRESULT STDMETHODCALLTYPE WebBrowser::CanInPlaceActivate(void) -{ - return S_OK; -} - -HRESULT STDMETHODCALLTYPE WebBrowser::OnInPlaceActivate(void) -{ - OleLockRunning(oleObject, TRUE, FALSE); - oleObject->QueryInterface(&oleInPlaceObject); - oleInPlaceObject->SetObjectRects(&rObject, &rObject); - - return S_OK; - -} - -HRESULT STDMETHODCALLTYPE WebBrowser::OnUIActivate(void) -{ - return S_OK; -} - -HRESULT STDMETHODCALLTYPE WebBrowser::GetWindowContext( - __RPC__deref_out_opt IOleInPlaceFrame** ppFrame, - __RPC__deref_out_opt IOleInPlaceUIWindow** ppDoc, - __RPC__out LPRECT lprcPosRect, - __RPC__out LPRECT lprcClipRect, - __RPC__inout LPOLEINPLACEFRAMEINFO lpFrameInfo) -{ - HWND hwnd = hWndParent; - - (*ppFrame) = NULL; - (*ppDoc) = NULL; - (*lprcPosRect).left = rObject.left; - (*lprcPosRect).top = rObject.top; - (*lprcPosRect).right = rObject.right; - (*lprcPosRect).bottom = rObject.bottom; - *lprcClipRect = *lprcPosRect; - - lpFrameInfo->fMDIApp = false; - lpFrameInfo->hwndFrame = hwnd; - lpFrameInfo->haccel = NULL; - lpFrameInfo->cAccelEntries = 0; - - return S_OK; -} - -HRESULT STDMETHODCALLTYPE WebBrowser::Scroll( - SIZE scrollExtant) -{ - return E_NOTIMPL; -} - -HRESULT STDMETHODCALLTYPE WebBrowser::OnUIDeactivate( - BOOL fUndoable) -{ - return S_OK; -} - -HWND WebBrowser::GetControlWindow() -{ - if (hWndControl != 0) - return hWndControl; - - if (oleInPlaceObject == 0) - return 0; - - oleInPlaceObject->GetWindow(&hWndControl); - return hWndControl; -} - -HRESULT STDMETHODCALLTYPE WebBrowser::OnInPlaceDeactivate(void) -{ - hWndControl = 0; - oleInPlaceObject = 0; - - return S_OK; -} - -HRESULT STDMETHODCALLTYPE WebBrowser::DiscardUndoState(void) -{ - return E_NOTIMPL; -} - -HRESULT STDMETHODCALLTYPE WebBrowser::DeactivateAndUndo(void) -{ - return E_NOTIMPL; -} - -HRESULT STDMETHODCALLTYPE WebBrowser::OnPosRectChange( - __RPC__in LPCRECT lprcPosRect) -{ - return E_NOTIMPL; -} - -// ---------- IOleClientSite ---------- - -HRESULT STDMETHODCALLTYPE WebBrowser::SaveObject(void) -{ - return E_NOTIMPL; -} - -HRESULT STDMETHODCALLTYPE WebBrowser::GetMoniker( - DWORD dwAssign, - DWORD dwWhichMoniker, - __RPC__deref_out_opt IMoniker** ppmk) -{ - if ((dwAssign == OLEGETMONIKER_ONLYIFTHERE) && - (dwWhichMoniker == OLEWHICHMK_CONTAINER)) - return E_FAIL; - - return E_NOTIMPL; -} - -HRESULT STDMETHODCALLTYPE WebBrowser::GetContainer( - __RPC__deref_out_opt IOleContainer** ppContainer) -{ - return E_NOINTERFACE; -} - -HRESULT STDMETHODCALLTYPE WebBrowser::ShowObject(void) -{ - return S_OK; -} - -HRESULT STDMETHODCALLTYPE WebBrowser::OnShowWindow( - BOOL fShow) -{ - return S_OK; -} - -HRESULT STDMETHODCALLTYPE WebBrowser::RequestNewObjectLayout(void) -{ - return E_NOTIMPL; -} - -// ----- IStorage ----- - -HRESULT STDMETHODCALLTYPE WebBrowser::CreateStream( - __RPC__in_string const OLECHAR* pwcsName, - DWORD grfMode, - DWORD reserved1, - DWORD reserved2, - __RPC__deref_out_opt IStream** ppstm) -{ - return E_NOTIMPL; -} - -HRESULT STDMETHODCALLTYPE WebBrowser::OpenStream( - const OLECHAR* pwcsName, - void* reserved1, - DWORD grfMode, - DWORD reserved2, - IStream** ppstm) -{ - return E_NOTIMPL; -} - -HRESULT STDMETHODCALLTYPE WebBrowser::CreateStorage( - __RPC__in_string const OLECHAR* pwcsName, - DWORD grfMode, - DWORD reserved1, - DWORD reserved2, - __RPC__deref_out_opt IStorage** ppstg) -{ - return E_NOTIMPL; -} - -HRESULT STDMETHODCALLTYPE WebBrowser::OpenStorage( - __RPC__in_opt_string const OLECHAR* pwcsName, - __RPC__in_opt IStorage* pstgPriority, - DWORD grfMode, - __RPC__deref_opt_in_opt SNB snbExclude, - DWORD reserved, - __RPC__deref_out_opt IStorage** ppstg) -{ - return E_NOTIMPL; -} - -HRESULT STDMETHODCALLTYPE WebBrowser::CopyTo( - DWORD ciidExclude, - const IID* rgiidExclude, - __RPC__in_opt SNB snbExclude, - IStorage* pstgDest) -{ - return E_NOTIMPL; -} - -HRESULT STDMETHODCALLTYPE WebBrowser::MoveElementTo( - __RPC__in_string const OLECHAR* pwcsName, - __RPC__in_opt IStorage* pstgDest, - __RPC__in_string const OLECHAR* pwcsNewName, - DWORD grfFlags) -{ - return E_NOTIMPL; -} - -HRESULT STDMETHODCALLTYPE WebBrowser::Commit( - DWORD grfCommitFlags) -{ - return E_NOTIMPL; -} - -HRESULT STDMETHODCALLTYPE WebBrowser::Revert(void) -{ - return E_NOTIMPL; -} - -HRESULT STDMETHODCALLTYPE WebBrowser::EnumElements( - DWORD reserved1, - void* reserved2, - DWORD reserved3, - IEnumSTATSTG** ppenum) -{ - return E_NOTIMPL; -} - -HRESULT STDMETHODCALLTYPE WebBrowser::DestroyElement( - __RPC__in_string const OLECHAR* pwcsName) -{ - return E_NOTIMPL; -} - -HRESULT STDMETHODCALLTYPE WebBrowser::RenameElement( - __RPC__in_string const OLECHAR* pwcsOldName, - __RPC__in_string const OLECHAR* pwcsNewName) -{ - return E_NOTIMPL; -} - -HRESULT STDMETHODCALLTYPE WebBrowser::SetElementTimes( - __RPC__in_opt_string const OLECHAR* pwcsName, - __RPC__in_opt const FILETIME* pctime, - __RPC__in_opt const FILETIME* patime, - __RPC__in_opt const FILETIME* pmtime) -{ - return E_NOTIMPL; -} - -HRESULT STDMETHODCALLTYPE WebBrowser::SetClass( - __RPC__in REFCLSID clsid) -{ - return S_OK; -} - -HRESULT STDMETHODCALLTYPE WebBrowser::SetStateBits( - DWORD grfStateBits, - DWORD grfMask) -{ - return E_NOTIMPL; -} - -HRESULT STDMETHODCALLTYPE WebBrowser::Stat( - __RPC__out STATSTG* pstatstg, - DWORD grfStatFlag) -{ - return E_NOTIMPL; -} - - -extern "C" __declspec(dllexport) void* html_new( HWND parent) { - auto web = new WebBrowser(parent); - return web; -} - -extern "C" __declspec(dllexport) void html_navigate(void* web, wchar_t* path) { - auto w = static_cast(web); - w->Navigate(path); -} -extern "C" __declspec(dllexport) void html_resize(void* web,int x,int y,int w, int h) { - auto ww = static_cast(web); - RECT r; - r.left = x; - r.top = y; - r.right = x + w; - r.bottom = y + h; - ww->SetRect(r); -} -extern "C" __declspec(dllexport) void html_release(void* web) { - delete web; -} \ No newline at end of file diff --git a/plugins/winsharedutils/dllmain.cpp b/plugins/winsharedutils/dllmain.cpp index a21ed7d0..7bffdf17 100644 --- a/plugins/winsharedutils/dllmain.cpp +++ b/plugins/winsharedutils/dllmain.cpp @@ -1,5 +1,4 @@ -// dllmain.cpp : 定义 DLL 应用程序的入口点。 -#include "pch.h" + #include"define.h" BOOL APIENTRY DllMain( HMODULE hModule, DWORD ul_reason_for_call,