This commit is contained in:
恍兮惚兮 2024-01-22 12:56:15 +08:00
parent 1e27c99d8d
commit a80a36c286
50 changed files with 1883 additions and 1415 deletions

View File

@ -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

View File

@ -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:

View File

@ -1,5 +1,5 @@
import requests
from myutils.utils import getproxy
from myutils.proxy import getproxy
class mojidict:
def search(self, word):

View File

@ -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:

View File

@ -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('<div class="head-content"(.*?)>([\\s\\S]*?)</span>(.*?)</div>',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('<div class="each-sense"(.*?)>([\\s\\S]*?)</div></div></div>',text)
try:
for _,ares in fnd:
asave=[]
res=re.findall('>(.*?)<',ares+'<')
for __ in res:
if __ !='':
asave.append(__)
save.append('<br>'.join(asave))
except:
print_exc()
fnd=re.findall('<li class="word-exp"(.*?)>([\\s\\S]*?)</span></li>',text)
try:
for _,ares in fnd:
asave=[]
res=re.findall('>(.*?)<',ares+'<')
for __ in res:
if __ !='':
asave.append(__)
save.append('<br>'.join(asave))
except:
print_exc()
return '<br><br>'.join(save)
fnd=re.findall('<section class="modules"(.*?)>([\\s\\S]*?)</section>',text)
return fnd[0][1]

View File

@ -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('<HEAD>','<HEAD><base href="{}">'.format(url)).replace('<head>','<head><base href="{}">'.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()

View File

@ -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=[

View File

@ -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("获取失败")

View File

@ -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),

View File

@ -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]=_

View File

@ -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

View File

@ -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:

View File

@ -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

View File

@ -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

View File

@ -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

View File

@ -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:

View File

@ -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}

View File

@ -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+1<len(methodsqueues):
methodsqueues[idx+1].put((gamepath,args))
def dispatachtask(gamepath):
if checkneed(gamepath)==False:
return
title=savehook_new_data[gamepath]['title']
p=gamepath.split('\\')
__t=[]
for _ in [title,p[-2],p[-1][:-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 i>0 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:

View File

@ -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('<body>','<body style="overflow-x: hidden;">')
##删除header
text=re.sub('<header>([\\s\\S]*?)</header>','',text)
text=re.sub('<footer>([\\s\\S]*?)</footer>','',text)
text=re.sub('<article class="vnreleases"([\\s\\S]*?)</article>','',text)
text=re.sub('<article class="vnstaff"([\\s\\S]*?)</article>','',text)
text=re.sub('<article id="stats"([\\s\\S]*?)</article>','',text)
text=re.sub('<nav>([\\s\\S]*?)</nav>','',text)
text=re.sub('<p class="itemmsg">([\\s\\S]*?)</p>','',text)
text=re.sub('<div id="vntags">([\\s\\S]*?)</div>','',text)
text=re.sub('<div id="tagops">([\\s\\S]*?)</div>','',text)
resavepath=infopath+'parsed.html'
if globalconfig['languageuse']==0:
text=re.sub('<a href="(.*?)" lang="ja-Latn" title="(.*?)">(.*?)</a>','<a href="\\1" lang="ja-Latn" title="\\3">\\2</a>',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

View File

@ -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)

View File

@ -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

View File

@ -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):

View File

@ -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

View File

@ -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('<img class="media-object subject-package"(.*?)data-normal="(.*?)">',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('<h4 class="media-heading">(.*?)</h4>',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

View File

@ -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('<a href="(.*?)" class="l">',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('<img src="(.*?)" width="(.*?)" class="cover"',text).groups()[0])
return 'https:'+imgurl
except:
pass
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',
}
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('<a href="(.*?)" class="subjectCover cover ll">',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

View File

@ -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('<div class="imghover--visible"><img src="(.*?)"',text).groups()[0])
return imgurl
except:
pass
try:
found=re.findall('<td class="tc_title"><a href="(.*?)"',text)
except:
return None
if len(found)==0:
return None
url='https://vndb.org'+found[0]
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)
text=response.text
except:
return None
else:
with open(savepath,'r',encoding='utf8') as ff:
text=ff.read()
try:
imgurl=(re.search('<div class="imghover--visible"><img src="(.*?)"',text).groups()[0])
return imgurl
except:
pass
def vndbsearchinfo(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('<div class="imghover--visible"><img src="(.*?)"',text).groups()[0])
return savepath
except:
pass
try:
found=re.findall('<td class="tc_title"><a href="(.*?)"',text)
except:
return None
if len(found)==0:
return None
url='https://vndb.org'+found[0]
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)
text=response.text
except:
return None
else:
with open(savepath,'r',encoding='utf8') as ff:
text=ff.read()
try:
imgurl=(re.search('<div class="imghover--visible"><img src="(.*?)"',text).groups()[0])
return savepath
except:
pass
def searchdatamethod(title):
if os.path.exists('./cache/vndb')==False:
os.mkdir('./cache/vndb')
imgurl=vndbsearch(title)
#print(imgurl)
savepath= vndbdownloadimg(imgurl)
infosavepath=vndbsearchinfo(title)
return {'imagepath':savepath,'infopath':infosavepath}
import re
def parsehtmlmethod(infopath):
with open(infopath,'r',encoding='utf8') as ff:
text=ff.read()
##隐藏横向滚动
text=text.replace('<body>','<body style="overflow-x: hidden;">')
##删除header
text=re.sub('<header>([\\s\\S]*?)</header>','',text)
text=re.sub('<footer>([\\s\\S]*?)</footer>','',text)
text=re.sub('<article class="vnreleases"([\\s\\S]*?)</article>','',text)
text=re.sub('<article class="vnstaff"([\\s\\S]*?)</article>','',text)
text=re.sub('<article id="stats"([\\s\\S]*?)</article>','',text)
text=re.sub('<nav>([\\s\\S]*?)</nav>','',text)
text=re.sub('<p class="itemmsg">([\\s\\S]*?)</p>','',text)
text=re.sub('<div id="vntags">([\\s\\S]*?)</div>','',text)
text=re.sub('<div id="tagops">([\\s\\S]*?)</div>','',text)
resavepath=infopath+'parsed.html'
if globalconfig['languageuse']==0:
text=re.sub('<a href="(.*?)" lang="ja-Latn" title="(.*?)">(.*?)</a>','<a href="\\1" lang="ja-Latn" title="\\3">\\2</a>',text)
try:
imgurl=(re.search('<div class="imghover--visible"><img src="(.*?)"',text).groups()[0])
savepath='./cache/vndb/'+b64string(imgurl)+'.jpg'
if os.path.exists(savepath):
text=re.sub('<div class="imghover--visible"><img src="(.*?)"','<div class="imghover--visible"><img src="file://'+os.path.abspath(savepath).replace('\\','/')+'"',text)
except:
print_exc()
with open(resavepath,'w',encoding='utf8') as ff:
ff.write(text)
return resavepath

View File

@ -150,8 +150,6 @@
"useproxy": true,
"usesysproxy": true,
"fullscreenmethod_3": 0,
"getvesionmethod": "githubrelease",
"updatemethod": "githubrelease",
"dialog_savegame_layout": {
"itemw": 250,
"itemh": 350,
@ -191,6 +189,11 @@
"tip": "读取剪贴板",
"icon": "fa.file-o"
},
"open_relative_link": {
"use": false,
"tip": "打开关联页面",
"icon": "fa.sitemap"
},
"mousetransbutton": {
"use": true,
"tip": "鼠标穿透窗口",

View File

@ -1,5 +1,5 @@
{
"version":"v2.35.0",
"version":"v2.36.0",
"language_list_show":["简体中文","日本語","English","Русский язык","Español","한국어","Français","繁體中文","Tiếng Việt","Türkçe","Polski","Українська Мова","Italiano","اللغة العربية","ภาษาไทย"] ,
"language_list_translator":["简体中文","日文","英文","俄语","西班牙语","韩语","法语","繁体中文","越南语","土耳其语","波兰语","乌克兰语","意大利语","阿拉伯语","泰语"],
"language_list_translator_inner":["zh", "ja", "en","ru","es","ko","fr","cht","vi","tr","pl","uk","it","ar","th"],
@ -295,7 +295,6 @@
"./files/plugins/DLL32/libcurl.dll",
"./files/plugins/DLL32/LunaHost32.dll"
]
},
"searchimgmethods":["vndbgetimg","bangumigetimg","2dfgetimg"]
}
}

View File

@ -696,5 +696,10 @@
"绘制帧率": "رسم الإطار",
"窗口缩放": "نافذة التكبير",
"缩放方式": "طريقة التكبير",
"缩放/恢复游戏窗口": "التكبير / استعادة نافذة اللعبة"
"缩放/恢复游戏窗口": "التكبير / استعادة نافذة اللعبة",
"打开关联页面": "فتح صفحة الارتباط",
"添加关联页面": "إضافة ارتباط الصفحة",
"页面类型": "نوع الصفحة",
"页面链接": "رابط الصفحة",
"缓存": "مخابئ"
}

View File

@ -696,5 +696,10 @@
"绘制帧率": "繪製幀率",
"窗口缩放": "視窗縮放",
"缩放方式": "縮放管道",
"缩放/恢复游戏窗口": "縮放/恢復遊戲視窗"
"缩放/恢复游戏窗口": "縮放/恢復遊戲視窗",
"打开关联页面": "打開關聯頁面",
"添加关联页面": "添加關聯頁面",
"页面类型": "頁面類型",
"页面链接": "頁面連結",
"缓存": "緩存"
}

View File

@ -696,5 +696,10 @@
"绘制帧率": "Draw frame rate",
"窗口缩放": "Window Zoom",
"缩放方式": "Zoom method",
"缩放/恢复游戏窗口": "Zoom/Restore Game Window"
"缩放/恢复游戏窗口": "Zoom/Restore Game Window",
"打开关联页面": "Open the associated page",
"添加关联页面": "Add associated page",
"页面类型": "Page Type",
"页面链接": "Page Link",
"缓存": "cache"
}

View File

@ -696,5 +696,10 @@
"绘制帧率": "Dibuja la tasa de fotogramas",
"窗口缩放": "Ampliación de la ventana",
"缩放方式": "Modo de zoom",
"缩放/恢复游戏窗口": "Ampliar / restaurar la ventana del juego"
"缩放/恢复游戏窗口": "Ampliar / restaurar la ventana del juego",
"打开关联页面": "Abrir página asociada",
"添加关联页面": "Añadir página asociada",
"页面类型": "Tipo de página",
"页面链接": "Enlace de página",
"缓存": "Caché"
}

View File

@ -696,5 +696,10 @@
"绘制帧率": "Dessiner le framerate",
"窗口缩放": "Zoom de la fenêtre",
"缩放方式": "Mode de zoom",
"缩放/恢复游戏窗口": "Zoom / restaurer la fenêtre de jeu"
"缩放/恢复游戏窗口": "Zoom / restaurer la fenêtre de jeu",
"打开关联页面": "Ouvrir la page associée",
"添加关联页面": "Ajouter une page associée",
"页面类型": "Type de page",
"页面链接": "Liens vers les pages",
"缓存": "Cache"
}

View File

@ -696,5 +696,10 @@
"绘制帧率": "Disegna frame rate",
"窗口缩放": "Zoom finestra",
"缩放方式": "Metodo zoom",
"缩放/恢复游戏窗口": "Zoom/ripristina finestra di gioco"
"缩放/恢复游戏窗口": "Zoom/ripristina finestra di gioco",
"打开关联页面": "Apri la pagina associata",
"添加关联页面": "Aggiungi pagina associata",
"页面类型": "Tipo di pagina",
"页面链接": "Link pagina",
"缓存": "cache"
}

View File

@ -696,5 +696,10 @@
"绘制帧率": "描画フレームレート",
"窗口缩放": "ウィンドウのズーム",
"缩放方式": "スケール方法",
"缩放/恢复游戏窗口": "ゲームウィンドウのズーム/復元"
"缩放/恢复游戏窗口": "ゲームウィンドウのズーム/復元",
"打开关联页面": "関連ページを開く",
"添加关联页面": "関連ページの追加",
"页面类型": "ページタイプ",
"页面链接": "ページリンク",
"缓存": "キャッシュ"
}

View File

@ -696,5 +696,10 @@
"绘制帧率": "프레임 레이트 그리기",
"窗口缩放": "창 크기 조절",
"缩放方式": "배율 조정 방법",
"缩放/恢复游戏窗口": "게임 창 확대 / 복원"
"缩放/恢复游戏窗口": "게임 창 확대 / 복원",
"打开关联页面": "연관 페이지 열기",
"添加关联页面": "연관 페이지 추가",
"页面类型": "페이지 유형",
"页面链接": "페이지 링크",
"缓存": "캐시"
}

View File

@ -696,5 +696,10 @@
"绘制帧率": "Rysuj częstotliwość klatek",
"窗口缩放": "Powiększenie okna",
"缩放方式": "Metoda powiększania",
"缩放/恢复游戏窗口": "Powiększ/przywróć okno gry"
"缩放/恢复游戏窗口": "Powiększ/przywróć okno gry",
"打开关联页面": "Otwórz powiązaną stronę",
"添加关联页面": "Dodaj powiązaną stronę",
"页面类型": "Typ strony",
"页面链接": "Link do strony",
"缓存": "pamięć podręczna"
}

View File

@ -696,5 +696,10 @@
"绘制帧率": "Рисовать частоту кадров",
"窗口缩放": "Масштаб окна",
"缩放方式": "Режим масштабирования",
"缩放/恢复游戏窗口": "Увеличить / восстановить игровое окно"
"缩放/恢复游戏窗口": "Увеличить / восстановить игровое окно",
"打开关联页面": "Открыть страницу",
"添加关联页面": "Добавить ассоциированную страницу",
"页面类型": "Тип страницы",
"页面链接": "Ссылка на страницу",
"缓存": "Кэш"
}

View File

@ -696,5 +696,10 @@
"绘制帧率": "วาดอัตราเฟรม",
"窗口缩放": "หน้าต่างซูม",
"缩放方式": "โหมดซูม",
"缩放/恢复游戏窗口": "ซูม / กู้คืนหน้าต่างเกม"
"缩放/恢复游戏窗口": "ซูม / กู้คืนหน้าต่างเกม",
"打开关联页面": "เปิดหน้าพันธมิตร",
"添加关联页面": "เพิ่มหน้าพันธมิตร",
"页面类型": "ประเภทหน้า",
"页面链接": "ลิงค์หน้า",
"缓存": "แคช"
}

View File

@ -696,5 +696,10 @@
"绘制帧率": "Çerçive hızını çiz",
"窗口缩放": "Pencere Yakınlaştır",
"缩放方式": "Yakınlaştırma yöntemi",
"缩放/恢复游戏窗口": "Oyun Penceresini Yakınlaştır/Geri Döndür"
"缩放/恢复游戏窗口": "Oyun Penceresini Yakınlaştır/Geri Döndür",
"打开关联页面": "İlişkili sayfanı aç",
"添加关联页面": "İlişkili sayfa ekle",
"页面类型": "Sayfa Türü",
"页面链接": "Sayfa Bağlantısı",
"缓存": "cache"
}

View File

@ -696,5 +696,10 @@
"绘制帧率": "Малювати швидкість рамок",
"窗口缩放": "Масштаб вікна",
"缩放方式": "Метод масштабу",
"缩放/恢复游戏窗口": "Збільшити/відновити вікно гри"
"缩放/恢复游戏窗口": "Збільшити/відновити вікно гри",
"打开关联页面": "Відкрити пов’ язану сторінку",
"添加关联页面": "Додати пов’ язану сторінку",
"页面类型": "Тип сторінки",
"页面链接": "Посилання сторінки",
"缓存": "кеш"
}

View File

@ -696,5 +696,10 @@
"绘制帧率": "Vẽ tỷ lệ khung",
"窗口缩放": "Thu phóng cửa sổ",
"缩放方式": "Cách thu phóng",
"缩放/恢复游戏窗口": "Thu phóng/khôi phục cửa sổ trò chơi"
"缩放/恢复游戏窗口": "Thu phóng/khôi phục cửa sổ trò chơi",
"打开关联页面": "Mở trang liên kết",
"添加关联页面": "Thêm trang liên kết",
"页面类型": "Loại trang",
"页面链接": "Liên kết trang",
"缓存": "Bộ nhớ tạm"
}

View File

@ -696,5 +696,10 @@
"绘制帧率": "",
"窗口缩放": "",
"缩放方式": "",
"缩放/恢复游戏窗口": ""
"缩放/恢复游戏窗口": "",
"打开关联页面": "",
"添加关联页面": "",
"页面类型": "",
"页面链接": "",
"缓存": ""
}

View File

@ -34,7 +34,7 @@ shutil.copytree(launch,targetdir,dirs_exist_ok=True)
shutil.copytree(r'.\files',rf'{targetdir}\files')
shutil.copy(r'..\LICENSE',targetdir)
for f in ['hiraparse','ocrengines','webresource','translator','cishu','tts','network']:
for f in ['hiraparse','ocrengines','translator','cishu','tts','network']:
shutil.copytree(rf'.\LunaTranslator\{f}',rf'{targetdir_in}\{f}')
def remove(f):

View File

@ -22,7 +22,7 @@ set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY $<1:${CMAKE_FINAL_OUTPUT_DIRECTORY}>)
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")

View File

@ -0,0 +1,989 @@
// MWebBrowser.cpp --- simple Win32 Web Browser
// Copyright (C) 2019 Katayama Hirofumi MZ <katayama.hirofumi.mz@gmail.com>
// This file is public domain software.
#include "MWebBrowser.hpp"
#include <cwchar>
#include <comdef.h>
#include <shlwapi.h>
#include <cstdio>
#include <cstring>
#include <cassert>
#include <mshtmhst.h>
/*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<IHTMLDocument2 *>(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<IHTMLDocument2 *>(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<IOleClientSite *>(this);
}
else if (riid == __uuidof(IOleInPlaceSite))
{
*ppvObj = static_cast<IOleInPlaceSite *>(this);
}
else if (riid == __uuidof(IServiceProvider))
{
*ppvObj = static_cast<IServiceProvider *>(this);
}
else if (riid == __uuidof(IDocHostUIHandler))
{
*ppvObj = static_cast<IDocHostUIHandler *>(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<IHttpSecurity *>(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();
}

View File

@ -0,0 +1,225 @@
// MWebBrowser.cpp --- simple Win32 Web Browser
// Copyright (C) 2019 Katayama Hirofumi MZ <katayama.hirofumi.mz@gmail.com>
// This file is public domain software.
#ifndef MWEB_BROWSER_HPP_
#define MWEB_BROWSER_HPP_ 13 // Version 13
#define INITGUID
#include <windows.h>
#include <exdisp.h>
#include <mshtml.h>
#include <mshtmhst.h>
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_

View File

@ -0,0 +1,102 @@
// SimpleBrowser.cpp --- simple Win32 browser
// Copyright (C) 2019 Katayama Hirofumi MZ <katayama.hirofumi.mz@gmail.com>
// This file is public domain software.
#define _CRT_SECURE_NO_WARNINGS
// SimpleBrowser.cpp --- simple Win32 browser
// Copyright (C) 2019 Katayama Hirofumi MZ <katayama.hirofumi.mz@gmail.com>
// This file is public domain software.
#define _CRT_SECURE_NO_WARNINGS
#include <windows.h>
#include <windowsx.h>
#include <commctrl.h>
#include <commdlg.h>
#include <mmsystem.h>
#include <shlobj.h>
#include <shlwapi.h>
#include <mshtml.h>
#include <string>
#include <cctype>
#include <cassert>
#include <strsafe.h>
#include <comdef.h>
#include <mshtmcid.h>
#include <process.h>
#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<MWebBrowser*>(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<MWebBrowser*>(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<MWebBrowser*>(web);
ww->Destroy();
ww->Release();
}

View File

@ -1,653 +0,0 @@

#include <comdef.h>
#include <Exdisp.h>
#include <string>
#include <tchar.h>
#include <Windows.h>
#include <exdisp.h>
#include <mshtml.h>
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<BSTR>( LR"(C:\dataH\LunaTranslator_x86\cache\vndb\04472259b1e767bf451ac93d320450ef.html)");
url2.bstrVal = const_cast<BSTR> (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<IOleClientSite*>(this);
}
else if (riid == __uuidof(IOleInPlaceSite))
{
(*ppvObject) = static_cast<IOleInPlaceSite*>(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<WebBrowser*>(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<WebBrowser*>(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;
}

View File

@ -1,5 +1,4 @@
// dllmain.cpp : 定义 DLL 应用程序的入口点。
#include "pch.h"

#include"define.h"
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,