This commit is contained in:
恍兮惚兮 2024-05-18 17:53:33 +08:00
parent ccf94f9cc7
commit f3d124f4e2
9 changed files with 162 additions and 41 deletions

View File

@ -192,7 +192,7 @@ class AnkiWindow(QWidget):
fields.update(self.loadfakefields())
html = self.parse_template(html, fields)
html = f'<style>{model_css}</style><div class="card">{html}</div>'
self.htmlbrowser.set_html(html)
self.htmlbrowser.setHtml(html)
def creattemplatetab(self):
@ -338,7 +338,7 @@ class AnkiWindow(QWidget):
_TR("DeckName"), getlineedit(globalconfig["ankiconnect"], "DeckName")
)
layout.addRow(
_TR("ModelName"), getlineedit(globalconfig["ankiconnect"], "ModelName2")
_TR("ModelName"), getlineedit(globalconfig["ankiconnect"], "ModelName3")
)
layout.addRow(
@ -359,6 +359,11 @@ class AnkiWindow(QWidget):
getsimpleswitch(globalconfig["ankiconnect"], "autoruntts"),
)
layout.addRow(
_TR("use QTextBrowser"),
getsimpleswitch(globalconfig, "searchwordusetextbrowser"),
)
layout.addWidget(QLabel())
layout.addRow(_TR("录音"), QLabel())
lb = QLabel()
@ -674,6 +679,8 @@ class searchwordW(closeashidewindow):
idx += 1
self.tabks.insert(idx, k)
self.tab.insertTab(idx, _TR(globalconfig["cishu"][k]["name"]))
if len(self.tabks) == 1:
self.tab.tabBarClicked.emit(0)
def setupUi(self):
self.setWindowIcon(qtawesome.icon("fa.search"))
@ -703,25 +710,30 @@ class searchwordW(closeashidewindow):
self.searchlayout.addWidget(ankiconnect)
self.tab = QTabBar(self)
self.tab.currentChanged.connect(
self.tab.tabBarClicked.connect(
lambda idx: self.textOutput.setHtml(self.cache_results[self.tabks[idx]])
)
self.tabks = []
self.setCentralWidget(ww)
textOutput = QTextBrowser(self)
if globalconfig["searchwordusetextbrowser"]:
textOutput = QTextBrowser(self)
def openlink(url):
try:
if url.url().lower().startswith("http"):
os.startfile(url.url())
except:
pass
def openlink(url):
try:
if url.url().lower().startswith("http"):
os.startfile(url.url())
except:
pass
textOutput.anchorClicked.connect(openlink)
textOutput.setUndoRedoEnabled(False)
textOutput.setReadOnly(True)
textOutput.setOpenLinks(False)
textOutput.anchorClicked.connect(openlink)
textOutput.setUndoRedoEnabled(False)
textOutput.setReadOnly(True)
textOutput.setOpenLinks(False)
else:
textOutput = auto_select_webview(self)
self.textOutput = textOutput
self.cache_results = {}
self.hiding = True

View File

@ -181,6 +181,7 @@ class Textbrowser:
def __init__(self, parent):
self.parent = parent
self.savey = 0
# self.shadowlabel=QLabel(parent)
# self.shadowlabel.savetext=''
self.align = False

View File

@ -517,6 +517,8 @@ class QUnFrameWindow(resizableframeless):
windows.SetForegroundWindow(int(self.winId()))
self.isfirstshow = False
self.setontopthread()
self.refreshtoolicon()
return super().showEvent(a0)
def canceltop(self):
@ -657,8 +659,6 @@ class QUnFrameWindow(resizableframeless):
self.document = self.translate_text.document()
self.document.contentsChanged.connect(self.textAreaChanged)
self.set_color_transparency()
self.refreshtoolicon()
self.thistimenotsetop = False
def createborderradiusstring(self, r, merge, top=False):

View File

@ -13,12 +13,11 @@ from PyQt5.QtWidgets import (
)
from webviewpy import (
webview_error_t,
webview_native_handle_kind_t,
Webview,
declare_library_path,
)
from PyQt5.QtGui import QCursor, QCloseEvent, QColor, QTextCursor, QResizeEvent
from PyQt5.QtGui import QCloseEvent, QColor, QTextCursor, QResizeEvent
from PyQt5.QtCore import Qt, pyqtSignal, QSize
from myutils.config import _TR, globalconfig
from PyQt5.QtWidgets import (
@ -552,6 +551,7 @@ class WebivewWidget(QWidget):
def __init__(self, parent=None, debug=False) -> None:
super().__init__(parent)
self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
declare_library_path(
os.path.abspath(
os.path.join(
@ -581,15 +581,19 @@ class WebivewWidget(QWidget):
size = getscaledrect(a0.size())
windows.MoveWindow(hwnd, 0, 0, size[0], size[1], True)
def set_html(self, html):
def setHtml(self, html):
self.webview.set_html(html)
def clear(self):
self.navigate("about:blank")
class mshtmlWidget(QWidget):
on_load = pyqtSignal(str)
def __init__(self, parent=None) -> None:
super().__init__(parent)
self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
self.browser = HTMLBrowser(int(self.winId()))
threading.Thread(target=self.__getcurrenturl).start()
@ -612,8 +616,15 @@ class mshtmlWidget(QWidget):
size = getscaledrect(a0.size())
self.browser.resize(0, 0, size[0], size[1])
def set_html(self, html):
print("not support, please use webview2")
def setHtml(self, html):
html = html.replace('target="_blank"', "")
html = "<html><head><meta http-equiv='x-ua-compatible' content='IE=edge'></head><body>{}</body></html>".format(
html
)
self.browser.set_html(html)
def clear(self):
self.navigate("about:blank")
def auto_select_webview(parent):

View File

@ -185,12 +185,17 @@ html_release = utilsdll.html_release
html_release.argtypes = (c_void_p,)
html_get_current_url = utilsdll.html_get_current_url
html_get_current_url.argtypes = c_void_p, c_wchar_p
html_set_html = utilsdll.html_set_html
html_set_html.argtypes = c_void_p, c_wchar_p,
class HTMLBrowser:
def __init__(self, parent) -> None:
self.html = html_new(parent)
def set_html(self, html):
html_set_html(self.html, html)
def resize(
self,
x,

View File

@ -192,6 +192,7 @@
600,
600
],
"searchwordusetextbrowser": true,
"settingfonttype": "Arial",
"showintab_sub": false,
"setting_geo_2": [

View File

@ -4,6 +4,7 @@
#include "MWebBrowser.hpp"
#include <ExDispid.h>
/*static*/ MWebBrowser *
MWebBrowser::Create(HWND hwndParent)
{
@ -16,22 +17,31 @@ MWebBrowser::Create(HWND hwndParent)
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)
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);
htmlSource = L"";
IConnectionPointContainer* container = nullptr;
m_web_browser2->QueryInterface(IID_IConnectionPointContainer, (void**)&container);
container->FindConnectionPoint(__uuidof(DWebBrowserEvents2), &callback);
IUnknown* punk = nullptr;
QueryInterface(IID_IUnknown, (void**)&punk);
callback->Advise(punk, &eventCookie);
punk->Release();
container->Release();
}
BOOL MWebBrowser::IsCreated() const
@ -185,7 +195,7 @@ void MWebBrowser::Destroy()
m_hwndIEServer = NULL;
}
RECT MWebBrowser::PixelToHIMETRIC(const RECT& rc)
RECT MWebBrowser::PixelToHIMETRIC(const RECT &rc)
{
HDC hDC = ::GetDC(NULL);
INT nPixelsPerInchX = ::GetDeviceCaps(hDC, LOGPIXELSX);
@ -199,7 +209,7 @@ RECT MWebBrowser::PixelToHIMETRIC(const RECT& rc)
return ret;
}
void MWebBrowser::MoveWindow(const RECT& rc)
void MWebBrowser::MoveWindow(const RECT &rc)
{
m_rc = rc;
@ -533,6 +543,10 @@ STDMETHODIMP MWebBrowser::QueryInterface(REFIID riid, void **ppvObj)
{
*ppvObj = static_cast<IDocHostUIHandler *>(this);
}
else if (riid == __uuidof(IDispatch))
*ppvObj = static_cast<IDispatch *>(this);
else if (riid == __uuidof(IOleClientSite))
*ppvObj = static_cast<IOleClientSite *>(this);
else
{
return E_NOINTERFACE;
@ -542,13 +556,15 @@ STDMETHODIMP MWebBrowser::QueryInterface(REFIID riid, void **ppvObj)
return S_OK;
}
STDMETHODIMP_(ULONG) MWebBrowser::AddRef()
STDMETHODIMP_(ULONG)
MWebBrowser::AddRef()
{
m_nRefCount++;
return m_nRefCount;
}
STDMETHODIMP_(ULONG) MWebBrowser::Release()
STDMETHODIMP_(ULONG)
MWebBrowser::Release()
{
--m_nRefCount;
if (m_nRefCount != 0)
@ -831,7 +847,6 @@ STDMETHODIMP MWebBrowser::GetWindow(REFGUID rguidReason, HWND *phwnd)
*phwnd = m_hwndParent;
return S_OK;
}
STDMETHODIMP MWebBrowser::OnSecurityProblem(DWORD dwProblem)
{
@ -844,11 +859,10 @@ STDMETHODIMP MWebBrowser::OnSecurityProblem(DWORD dwProblem)
SysFreeString(url);
}
{
return S_OK;
}
{
return S_OK;
}
@ -980,3 +994,59 @@ HRESULT MWebBrowser::Quit()
return m_web_browser2->Quit();
}
HRESULT MWebBrowser::GetTypeInfoCount(UINT *pctinfo) { return E_FAIL; }
HRESULT MWebBrowser::GetTypeInfo(UINT, LCID, ITypeInfo **) { return E_FAIL; }
HRESULT MWebBrowser::GetIDsOfNames(REFIID riid, LPOLESTR *rgszNames, UINT cNames, LCID lcid, DISPID *rgDispId) { return E_FAIL; }
HRESULT MWebBrowser::Invoke(DISPID dispIdMember, REFIID, LCID, WORD,
DISPPARAMS *pDispParams, VARIANT *pVarResult,
EXCEPINFO *, UINT *)
{
if (dispIdMember == DISPID_DOCUMENTCOMPLETE)
return OnCompleted(pDispParams);
else
return S_OK;
}
HRESULT MWebBrowser::OnCompleted(DISPPARAMS* args) {
HRESULT hr;
IDispatch *pDispatch = 0;
IHTMLDocument2 *pHtmlDoc2 = 0;
IPersistStreamInit *pPSI = 0;
IStream *pStream = 0;
HGLOBAL hHTMLContent;
if (htmlSource.empty()) return S_OK;
hr = m_web_browser2->get_Document(&pDispatch);
if (SUCCEEDED(hr) && pDispatch) hr = pDispatch->QueryInterface(IID_IHTMLDocument2, (void **)&pHtmlDoc2);
if (SUCCEEDED(hr) && pHtmlDoc2) hr = pHtmlDoc2->QueryInterface(IID_IPersistStreamInit, (void **)&pPSI);
// allocate global memory to copy the HTML content to
hHTMLContent = ::GlobalAlloc(GMEM_MOVEABLE, (htmlSource.size() + 1) * sizeof(TCHAR));
if (hHTMLContent)
{
wchar_t * p_content(static_cast<wchar_t *>(GlobalLock(hHTMLContent)));
::wcscpy(p_content, htmlSource.c_str());
GlobalUnlock(hHTMLContent);
// create a stream object based on the HTML content
if (SUCCEEDED(hr) && pPSI) hr = ::CreateStreamOnHGlobal(hHTMLContent, TRUE, &pStream);
if (SUCCEEDED(hr) && pStream) hr = pPSI->InitNew();
if (SUCCEEDED(hr)) hr = pPSI->Load(pStream);
}
if (pStream) pStream->Release();
if (pPSI) pPSI->Release();
if (pHtmlDoc2) pHtmlDoc2->Release();
if (pDispatch) pDispatch->Release();
htmlSource=L"";
return S_OK;
}
HRESULT MWebBrowser::SetHtml(const wchar_t* html){
htmlSource=html;
Navigate(L"about:blank");
return S_OK;
}

View File

@ -8,6 +8,7 @@
#define INITGUID
class MWebBrowser :
public IDispatch,
public IOleClientSite,
public IOleInPlaceSite,
public IStorage,
@ -17,6 +18,18 @@ class MWebBrowser :
{
public:
static MWebBrowser *Create(HWND hwndParent);
HRESULT OnCompleted(DISPPARAMS* args);
// ---------- IDispatch ----------
virtual HRESULT STDMETHODCALLTYPE GetTypeInfoCount(__RPC__out UINT *pctinfo) override;
virtual HRESULT STDMETHODCALLTYPE GetTypeInfo(UINT, LCID, __RPC__deref_out_opt ITypeInfo **) override;
virtual HRESULT STDMETHODCALLTYPE GetIDsOfNames(__RPC__in REFIID riid, __RPC__in_ecount_full(cNames) LPOLESTR *rgszNames, __RPC__in_range(0, 16384) UINT cNames, LCID lcid, __RPC__out_ecount_full(cNames) DISPID *rgDispId) override;
virtual HRESULT STDMETHODCALLTYPE Invoke(_In_ DISPID dispIdMember, _In_ REFIID, _In_ LCID, _In_ WORD, _In_ DISPPARAMS *pDispParams, _Out_opt_ VARIANT *pVarResult, _Out_opt_ EXCEPINFO*, _Out_opt_ UINT*) override;
std::wstring htmlSource;
IConnectionPoint* callback;
DWORD eventCookie;
RECT PixelToHIMETRIC(const RECT& rc);
HWND GetControlWindow();
@ -31,6 +44,7 @@ public:
void Refresh();
HRESULT Navigate(const WCHAR *url = L"about:blank");
HRESULT Navigate2(const WCHAR *url, DWORD dwFlags = 0);
HRESULT SetHtml(const wchar_t* html);
void Print(BOOL bBang = FALSE);
void PrintPreview();
void PageSetup();

View File

@ -153,8 +153,15 @@ extern "C" __declspec(dllexport) void html_get_current_url(void *web, wchar_t *u
if (!web)
return;
auto ww = static_cast<MWebBrowser *>(web);
ww->Destroy();
wchar_t *_u;
ww->get_LocationURL(&_u);
wcscpy(url, _u);
}
extern "C" __declspec(dllexport) void html_set_html(void *web, wchar_t *html)
{
if (!web)
return;
auto ww = static_cast<MWebBrowser *>(web);
ww->SetHtml(html);
}