This commit is contained in:
恍兮惚兮 2024-11-12 02:57:11 +08:00
parent e600d05c1c
commit 7de2923616
25 changed files with 394 additions and 350 deletions

View File

@ -1,6 +1,7 @@
#include "utawarerumono.h" #include "utawarerumono.h"
bool utawarerumonoh() { bool utawarerumonoh()
{
const BYTE bytes[] = { const BYTE bytes[] = {
0x80, XX, 0x5C, 0x80, XX, 0x5C,
0x75 0x75
@ -8,20 +9,22 @@ bool utawarerumonoh() {
}; };
const BYTE bytes2[] = { const BYTE bytes2[] = {
0x80, XX, XX, XX, 0x5C, 0x80, XX, XX, XX, 0x5C,
0x75 0x75};
};
auto addr1 = MemDbg::findBytes(bytes, sizeof(bytes), processStartAddress, processStopAddress); auto addr1 = MemDbg::findBytes(bytes, sizeof(bytes), processStartAddress, processStopAddress);
auto addr2 = MemDbg::findBytes(bytes2, sizeof(bytes2), processStartAddress, processStopAddress); auto addr2 = MemDbg::findBytes(bytes2, sizeof(bytes2), processStartAddress, processStopAddress);
auto succ = false; auto succ = false;
for (auto addr : { addr1,addr2 }) { for (auto addr : {addr1, addr2})
if (addr == 0)continue; {
if (addr == 0)
continue;
const BYTE funcstart[] = { const BYTE funcstart[] = {
0x51,0x53 0x51, 0x53};
};
addr = reverseFindBytes(funcstart, sizeof(funcstart), addr - 0x100, addr); addr = reverseFindBytes(funcstart, sizeof(funcstart), addr - 0x100, addr);
if (addr == 0)return false; if (addr == 0)
return false;
HookParam hp; HookParam hp;
hp.address = addr; hp.address = addr;
hp.newlineseperator = L"\\n";
hp.offset = get_stack(1); hp.offset = get_stack(1);
hp.type = CODEC_UTF8 | USING_STRING | NO_CONTEXT; hp.type = CODEC_UTF8 | USING_STRING | NO_CONTEXT;
ConsoleOutput("utawarerumono"); ConsoleOutput("utawarerumono");
@ -29,26 +32,29 @@ bool utawarerumonoh() {
} }
return succ; return succ;
} }
bool utawarerumonoh2() { bool utawarerumonoh2()
{
const BYTE bytes2[] = { const BYTE bytes2[] = {
0x8b, 0xca, 0x8b, 0xca,
0xc1, 0xe9, 0x02, 0xc1, 0xe9, 0x02,
0xf3,0xa5 0xf3, 0xa5};
};
auto addr2 = Util::SearchMemory(bytes2, sizeof(bytes2), PAGE_EXECUTE, processStartAddress, processStopAddress); auto addr2 = Util::SearchMemory(bytes2, sizeof(bytes2), PAGE_EXECUTE, processStartAddress, processStopAddress);
auto succ = false; auto succ = false;
for (auto addr : addr2) { for (auto addr : addr2)
{
HookParam hp; HookParam hp;
hp.address = addr + 2; hp.address = addr + 2;
hp.offset = get_reg(regs::esi); hp.offset = get_reg(regs::esi);
hp.type = CODEC_UTF8 | USING_STRING | NO_CONTEXT; hp.type = CODEC_UTF8 | USING_STRING | NO_CONTEXT;
hp.newlineseperator = L"\\n";
ConsoleOutput("utawarerumono %p", addr); ConsoleOutput("utawarerumono %p", addr);
succ |= NewHook(hp, "utawarerumono"); succ |= NewHook(hp, "utawarerumono");
} }
return succ; return succ;
} }
bool utawarerumono::attach_function() { bool utawarerumono::attach_function()
{
bool b1 = utawarerumonoh(); bool b1 = utawarerumonoh();
bool b2 = utawarerumonoh2(); bool b2 = utawarerumonoh2();
return b1 || b2; return b1 || b2;

View File

@ -1,7 +1,7 @@
set(VERSION_MAJOR 5) set(VERSION_MAJOR 5)
set(VERSION_MINOR 57) set(VERSION_MINOR 58)
set(VERSION_PATCH 4) set(VERSION_PATCH 0)
set(VERSION_REVISION 0) set(VERSION_REVISION 0)
add_definitions(-DVERSION_MAJOR=${VERSION_MAJOR}) add_definitions(-DVERSION_MAJOR=${VERSION_MAJOR})
add_definitions(-DVERSION_MINOR=${VERSION_MINOR}) add_definitions(-DVERSION_MINOR=${VERSION_MINOR})

View File

@ -11,22 +11,25 @@ using namespace Microsoft::WRL;
if (FAILED((x))) \ if (FAILED((x))) \
return x; return x;
DECLARE_API void set_transparent_background(void* m_host){ DECLARE_API void set_transparent_background(void *m_host)
{
COREWEBVIEW2_COLOR color; COREWEBVIEW2_COLOR color;
ZeroMemory(&color, sizeof(color)); ZeroMemory(&color, sizeof(color));
wil::com_ptr<ICoreWebView2Controller> m_controller(reinterpret_cast<ICoreWebView2Controller *>(m_host)); wil::com_ptr<ICoreWebView2Controller> m_controller(reinterpret_cast<ICoreWebView2Controller *>(m_host));
wil::com_ptr<ICoreWebView2Controller2> coreWebView2 = wil::com_ptr<ICoreWebView2Controller2> coreWebView2 =
m_controller.try_query<ICoreWebView2Controller2>(); m_controller.try_query<ICoreWebView2Controller2>();
if(coreWebView2){ if (coreWebView2)
{
coreWebView2->put_DefaultBackgroundColor(color); coreWebView2->put_DefaultBackgroundColor(color);
} }
} }
DECLARE_API HRESULT put_PreferredColorScheme(void *m_host, COREWEBVIEW2_PREFERRED_COLOR_SCHEME scheme) DECLARE_API void put_PreferredColorScheme(void *m_host, COREWEBVIEW2_PREFERRED_COLOR_SCHEME scheme)
{ {
wil::com_ptr<ICoreWebView2Controller> m_controller(reinterpret_cast<ICoreWebView2Controller *>(m_host)); wil::com_ptr<ICoreWebView2Controller> m_controller(reinterpret_cast<ICoreWebView2Controller *>(m_host));
wil::com_ptr<ICoreWebView2> coreWebView2; wil::com_ptr<ICoreWebView2> coreWebView2;
[&]()
{
CHECK_FAILURE(m_controller->get_CoreWebView2(&coreWebView2)); CHECK_FAILURE(m_controller->get_CoreWebView2(&coreWebView2));
auto webView2_13 = coreWebView2.try_query<ICoreWebView2_13>(); auto webView2_13 = coreWebView2.try_query<ICoreWebView2_13>();
if (webView2_13) if (webView2_13)
@ -35,7 +38,8 @@ DECLARE_API HRESULT put_PreferredColorScheme(void *m_host, COREWEBVIEW2_PREFERRE
CHECK_FAILURE(webView2_13->get_Profile(&profile)); CHECK_FAILURE(webView2_13->get_Profile(&profile));
CHECK_FAILURE(profile->put_PreferredColorScheme(scheme)); CHECK_FAILURE(profile->put_PreferredColorScheme(scheme));
} }
return S_FALSE; return S_OK;
}();
} }
DECLARE_API void *add_ZoomFactorChanged(void *m_host, void (*signal)(double)) DECLARE_API void *add_ZoomFactorChanged(void *m_host, void (*signal)(double))
{ {
@ -60,9 +64,9 @@ DECLARE_API void *add_ZoomFactorChanged(void *m_host, void (*signal)(double))
} }
DECLARE_API void remove_ZoomFactorChanged(void *m_host, void *m_zoomFactorChangedToken) DECLARE_API void remove_ZoomFactorChanged(void *m_host, void *m_zoomFactorChangedToken)
{ {
auto token = reinterpret_cast<EventRegistrationToken *>(m_zoomFactorChangedToken);
reinterpret_cast<ICoreWebView2Controller *>(m_host)->remove_ZoomFactorChanged(*reinterpret_cast<EventRegistrationToken *>(m_zoomFactorChangedToken)); reinterpret_cast<ICoreWebView2Controller *>(m_host)->remove_ZoomFactorChanged(*token);
delete m_zoomFactorChangedToken; delete token;
} }
DECLARE_API double get_ZoomFactor(void *m_host) DECLARE_API double get_ZoomFactor(void *m_host)
{ {
@ -74,3 +78,85 @@ DECLARE_API void put_ZoomFactor(void *m_host, double zoomFactor)
{ {
reinterpret_cast<ICoreWebView2Controller *>(m_host)->put_ZoomFactor(zoomFactor); reinterpret_cast<ICoreWebView2Controller *>(m_host)->put_ZoomFactor(zoomFactor);
} }
// https://github.com/MicrosoftEdge/WebView2Feedback/blob/main/specs/WebMessageObjects.md
DECLARE_API void remove_WebMessageReceived(void *m_host, void *m_webMessageReceivedToken)
{
auto token = reinterpret_cast<EventRegistrationToken *>(m_webMessageReceivedToken);
wil::com_ptr<ICoreWebView2Controller> m_controller(reinterpret_cast<ICoreWebView2Controller *>(m_host));
wil::com_ptr<ICoreWebView2> m_webView;
[&]()
{
CHECK_FAILURE(m_controller->get_CoreWebView2(&m_webView));
CHECK_FAILURE(m_webView->remove_WebMessageReceived(*token));
return S_OK;
}();
delete token;
}
DECLARE_API void *add_WebMessageReceived(void *m_host, void (*callback)(const wchar_t *))
{
wil::com_ptr<ICoreWebView2Controller> m_controller(reinterpret_cast<ICoreWebView2Controller *>(m_host));
wil::com_ptr<ICoreWebView2Controller4> coreWebView4 =
m_controller.try_query<ICoreWebView2Controller4>();
if (coreWebView4)
{
coreWebView4->put_AllowExternalDrop(true);
}
wil::com_ptr<ICoreWebView2> m_webView;
EventRegistrationToken *m_webMessageReceivedToken = new EventRegistrationToken;
[&]()
{
CHECK_FAILURE(m_controller->get_CoreWebView2(&m_webView));
CHECK_FAILURE(m_webView->add_WebMessageReceived(
Callback<ICoreWebView2WebMessageReceivedEventHandler>(
[=](ICoreWebView2 *sender, ICoreWebView2WebMessageReceivedEventArgs *args) noexcept
{
wil::unique_cotaskmem_string message;
CHECK_FAILURE(args->TryGetWebMessageAsString(&message));
if (std::wstring(L"FilesDropped") == message.get())
{
wil::com_ptr<ICoreWebView2WebMessageReceivedEventArgs2> args2 =
wil::com_ptr<ICoreWebView2WebMessageReceivedEventArgs>(args)
.query<ICoreWebView2WebMessageReceivedEventArgs2>();
if (args2)
{
wil::com_ptr<ICoreWebView2ObjectCollectionView>
objectsCollection;
CHECK_FAILURE(args2->get_AdditionalObjects(&objectsCollection));
unsigned int length;
CHECK_FAILURE(objectsCollection->get_Count(&length));
std::vector<std::wstring> paths;
for (unsigned int i = 0; i < length; i++)
{
wil::com_ptr<IUnknown> object;
CHECK_FAILURE(objectsCollection->GetValueAtIndex(i, &object));
// Note that objects can be null.
if (object)
{
wil::com_ptr<ICoreWebView2File> file =
object.query<ICoreWebView2File>();
if (file)
{
// Add the file to message to be sent back to webview
wil::unique_cotaskmem_string path;
CHECK_FAILURE(file->get_Path(&path));
paths.push_back(path.get());
}
}
}
// ProcessPaths(paths);
if (paths.size())
{
callback(paths[0].c_str());
}
}
}
return S_OK;
})
.Get(),
m_webMessageReceivedToken));
return S_OK;
}();
return m_webMessageReceivedToken;
}

View File

@ -12,7 +12,6 @@ from myutils.config import (
set_font_default, set_font_default,
_TR, _TR,
) )
from ctypes import c_int, CFUNCTYPE, c_void_p
from myutils.utils import ( from myutils.utils import (
minmaxmoveobservefunc, minmaxmoveobservefunc,
parsemayberegexreplace, parsemayberegexreplace,
@ -260,7 +259,6 @@ class MAINUI:
return return
else: else:
msgs = [ msgs = [
("<msg_info_not_refresh>", False, False),
("<msg_info_refresh>", False, True), ("<msg_info_refresh>", False, True),
("<msg_error_not_refresh>", True, False), ("<msg_error_not_refresh>", True, False),
("<msg_error_refresh>", True, True), ("<msg_error_refresh>", True, True),
@ -1099,7 +1097,9 @@ class MAINUI:
threading.Thread( threading.Thread(
target=minmaxmoveobservefunc, args=(self.translation_ui,) target=minmaxmoveobservefunc, args=(self.translation_ui,)
).start() ).start()
self.messagecallback__ = CFUNCTYPE(None, c_int, c_void_p)(self.messagecallback) self.messagecallback__ = winsharedutils.globalmessagelistener_cb(
self.messagecallback
)
winsharedutils.globalmessagelistener(self.messagecallback__) winsharedutils.globalmessagelistener(self.messagecallback__)
self.inittray() self.inittray()
self.playtimemanager = playtimemanager() self.playtimemanager = playtimemanager()

View File

@ -1,5 +1,4 @@
import sys, os import sys, os
from ctypes import windll, wintypes
def dopathexists(file: str): def dopathexists(file: str):
@ -12,10 +11,7 @@ def dopathexists(file: str):
file = windows.check_maybe_unc_file(file) file = windows.check_maybe_unc_file(file)
if not file: if not file:
return False return False
PathFileExists = windll.Shlwapi.PathFileExistsW return bool(windows.PathFileExists(os.path.abspath(file)))
PathFileExists.argtypes = (wintypes.LPCWSTR,)
PathFileExists.restype = wintypes.BOOL
return bool(PathFileExists(os.path.abspath(file)))
def overridepathexists(): def overridepathexists():
@ -28,7 +24,7 @@ def prepareqtenv():
# win7 no vcredist2015 # win7 no vcredist2015
windows.addenvpath("./files/runtime/") windows.addenvpath("./files/runtime/")
windows.loadlibrary("./files/runtime/PyQt5/Qt5/bin/Qt5Core.dll") windows.LoadLibraryW("./files/runtime/PyQt5/Qt5/bin/Qt5Core.dll")
from qtsymbols import QApplication, isqt5, Qt, QFont, QLocale from qtsymbols import QApplication, isqt5, Qt, QFont, QLocale

View File

@ -176,6 +176,7 @@ class rangeselect(QMainWindow):
self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground) self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)
self.backlabel = QLabel(self) self.backlabel = QLabel(self)
self.rectlabel = QLabel(self) self.rectlabel = QLabel(self)
self.backlabel.move(0, 0)
# self.setWindowOpacity(0.5) # self.setWindowOpacity(0.5)
self.setMouseTracking(True) self.setMouseTracking(True)
self.setCursor(Qt.CursorShape.CrossCursor) self.setCursor(Qt.CursorShape.CrossCursor)
@ -183,7 +184,6 @@ class rangeselect(QMainWindow):
def reset(self): def reset(self):
winsharedutils.maximum_window(int(self.winId())) winsharedutils.maximum_window(int(self.winId()))
winsharedutils.maximum_window(int(self.backlabel.winId()))
self.once = True self.once = True
self.is_drawing = False self.is_drawing = False
self.start_point = QPoint() self.start_point = QPoint()
@ -200,6 +200,9 @@ class rangeselect(QMainWindow):
"background-color: rgba(255,255,255, %s)" % globalconfig["ocrselectalpha"] "background-color: rgba(255,255,255, %s)" % globalconfig["ocrselectalpha"]
) )
def resizeEvent(self, e: QResizeEvent):
self.backlabel.resize(e.size())
def paintEvent(self, event): def paintEvent(self, event):
if self.is_drawing: if self.is_drawing:

View File

@ -1,6 +1,6 @@
from qtsymbols import * from qtsymbols import *
from myutils.config import globalconfig from myutils.config import globalconfig
import importlib, copy import importlib, copy, os
from webviewpy import webview_exception from webviewpy import webview_exception
from gui.usefulwidget import getQMessageBox from gui.usefulwidget import getQMessageBox
from traceback import print_exc from traceback import print_exc
@ -8,6 +8,7 @@ from traceback import print_exc
class Textbrowser(QFrame): class Textbrowser(QFrame):
contentsChanged = pyqtSignal(QSize) contentsChanged = pyqtSignal(QSize)
dropfilecallback = pyqtSignal(str)
def resizeEvent(self, event: QResizeEvent): def resizeEvent(self, event: QResizeEvent):
self.textbrowser.resize(event.size()) self.textbrowser.resize(event.size())
@ -24,6 +25,7 @@ class Textbrowser(QFrame):
if self.textbrowser: if self.textbrowser:
self.textbrowser.hide() self.textbrowser.hide()
self.textbrowser.contentsChanged.disconnect() self.textbrowser.contentsChanged.disconnect()
self.textbrowser.dropfilecallback.disconnect()
self.textbrowser.deleteLater() self.textbrowser.deleteLater()
if __ == "QWebEngine": if __ == "QWebEngine":
__ = "webview" __ = "webview"
@ -51,6 +53,7 @@ class Textbrowser(QFrame):
self.textbrowser.move(0, 0) self.textbrowser.move(0, 0)
self.textbrowser.setMouseTracking(True) self.textbrowser.setMouseTracking(True)
self.textbrowser.contentsChanged.connect(self._contentsChanged) self.textbrowser.contentsChanged.connect(self._contentsChanged)
self.textbrowser.dropfilecallback.connect(self.normdropfilepath)
self.textbrowser.resize(size) self.textbrowser.resize(size)
self.textbrowser.show() self.textbrowser.show()
self.textbrowser.setselectable(globalconfig["selectable"]) self.textbrowser.setselectable(globalconfig["selectable"])
@ -59,6 +62,9 @@ class Textbrowser(QFrame):
self.textbrowser.showhidetranslate(globalconfig["showfanyi"]) self.textbrowser.showhidetranslate(globalconfig["showfanyi"])
self.refreshcontent() self.refreshcontent()
def normdropfilepath(self, file):
self.dropfilecallback.emit(os.path.normpath(file))
def refreshcontent(self): def refreshcontent(self):
traces = self.trace.copy() traces = self.trace.copy()
self.clear() self.clear()

View File

@ -3,7 +3,13 @@ import time, functools, threading, os, importlib, shutil, uuid
from traceback import print_exc from traceback import print_exc
import windows, qtawesome, gobject, winsharedutils import windows, qtawesome, gobject, winsharedutils
from myutils.wrapper import threader, tryprint from myutils.wrapper import threader, tryprint
from myutils.config import globalconfig, saveallconfig, static_data, savehook_new_data from myutils.config import (
globalconfig,
saveallconfig,
static_data,
savehook_new_data,
savehook_new_list,
)
from gui.dialog_savedgame import dialog_setting_game from gui.dialog_savedgame import dialog_setting_game
from myutils.subproc import endsubprocs from myutils.subproc import endsubprocs
from myutils.ocrutil import ocr_run, imageCut from myutils.ocrutil import ocr_run, imageCut
@ -12,13 +18,13 @@ from myutils.utils import (
str2rgba, str2rgba,
makehtml, makehtml,
loadpostsettingwindowmethod_maybe, loadpostsettingwindowmethod_maybe,
find_or_create_uid,
) )
from myutils.hwnd import ( from myutils.hwnd import (
mouseselectwindow, mouseselectwindow,
grabwindow, grabwindow,
getExeIcon, getExeIcon,
getcurrexe, getcurrexe,
hwndratex,
) )
from gui.setting_about import doupdate from gui.setting_about import doupdate
from gui.dialog_memory import dialog_memory from gui.dialog_memory import dialog_memory
@ -33,6 +39,7 @@ from gui.usefulwidget import (
from gui.edittext import edittrans from gui.edittext import edittrans
from gui.dialog_savedgame import dialog_savedgame_integrated from gui.dialog_savedgame import dialog_savedgame_integrated
from gui.dialog_savedgame_setting import favorites, calculate_centered_rect from gui.dialog_savedgame_setting import favorites, calculate_centered_rect
from gui.dialog_savedgame_common import startgame
from gui.dynalang import LDialog from gui.dynalang import LDialog
@ -947,6 +954,7 @@ class TranslatorWindow(resizableframeless):
self.left_bottom_corner = self.geometry().bottomLeft() self.left_bottom_corner = self.geometry().bottomLeft()
self.translate_text = Textbrowser(self) self.translate_text = Textbrowser(self)
self.translate_text.move(0, 0) self.translate_text.move(0, 0)
self.translate_text.dropfilecallback.connect(self.dropfilecallback)
self.translate_text.contentsChanged.connect(self.textAreaChanged) self.translate_text.contentsChanged.connect(self.textAreaChanged)
self.translate_text.textbrowser.setselectable(globalconfig["selectable"]) self.translate_text.textbrowser.setselectable(globalconfig["selectable"])
self.titlebar.raise_() self.titlebar.raise_()
@ -957,6 +965,14 @@ class TranslatorWindow(resizableframeless):
t.start() t.start()
self.adjustbuttons = self.titlebar.adjustbuttons self.adjustbuttons = self.titlebar.adjustbuttons
def dropfilecallback(self, file: str):
if not (file.lower().endswith(".exe") or file.lower().endswith(".lnk")):
return
uid = find_or_create_uid(savehook_new_list, file)
if uid not in savehook_new_list:
savehook_new_list.insert(0, uid)
startgame(uid)
def showEvent(self, e): def showEvent(self, e):
if not self.firstshow: if not self.firstshow:
self.enterfunction() self.enterfunction()

View File

@ -1230,11 +1230,15 @@ class abstractwebview(QWidget):
class WebivewWidget(abstractwebview): class WebivewWidget(abstractwebview):
html_limit = 1572834 html_limit = 1572834
# https://github.com/MicrosoftEdge/WebView2Feedback/issues/1355#issuecomment-1384161283 # https://github.com/MicrosoftEdge/WebView2Feedback/issues/1355#issuecomment-1384161283
dropfilecallback = pyqtSignal(str)
def __del__(self): def __del__(self):
if not self.webview: if not self.webview:
return return
winsharedutils.remove_ZoomFactorChanged(self.get_controller(), self.__token) winsharedutils.remove_ZoomFactorChanged(self.get_controller(), self.__token)
winsharedutils.remove_WebMessageReceived(
self.get_controller(), self.m_webMessageReceivedToken
)
def bind(self, fname, func): def bind(self, fname, func):
self.webview.bind(fname, func) self.webview.bind(fname, func)
@ -1256,13 +1260,19 @@ class WebivewWidget(abstractwebview):
super().__init__(parent) super().__init__(parent)
self.webview = None self.webview = None
self.webview = Webview(debug=debug, window=int(self.winId())) self.webview = Webview(debug=debug, window=int(self.winId()))
zoomfunc = winsharedutils.add_ZoomFactorChanged_CALLBACK( self.m_webMessageReceivedToken = None
self.zoomfunc = winsharedutils.add_ZoomFactorChanged_CALLBACK(
self.on_ZoomFactorChanged.emit self.on_ZoomFactorChanged.emit
) )
self.__token = winsharedutils.add_ZoomFactorChanged( self.__token = winsharedutils.add_ZoomFactorChanged(
self.get_controller(), zoomfunc self.get_controller(), self.zoomfunc
)
self.dropfilecallback__ref = winsharedutils.add_WebMessageReceived_cb(
self.dropfilecallback.emit
)
self.m_webMessageReceivedToken = winsharedutils.add_WebMessageReceived(
self.get_controller(), self.dropfilecallback__ref
) )
self.keepref = [zoomfunc]
self.webview.bind("__on_load", self._on_load) self.webview.bind("__on_load", self._on_load)
self.webview.init("""window.__on_load(window.location.href)""") self.webview.init("""window.__on_load(window.location.href)""")
if usedarklight: if usedarklight:

View File

@ -1,7 +1,5 @@
import winsharedutils import winsharedutils
import os, functools, csv, gobject import os, csv, gobject
from ctypes import CFUNCTYPE, c_char_p
from hiraparse.basehira import basehira from hiraparse.basehira import basehira
# # 2.1.2 src schema # # 2.1.2 src schema
@ -61,7 +59,7 @@ class mecabwrap:
fields = list(csv.reader([feature.decode(codec)]))[0] fields = list(csv.reader([feature.decode(codec)]))[0]
res.append((surface.decode(codec), fields)) res.append((surface.decode(codec), fields))
fp = CFUNCTYPE(None, c_char_p, c_char_p)(cb) fp = winsharedutils.mecab_parse_cb(cb)
succ = winsharedutils.mecab_parse(self.kks, text.encode(codec), fp) succ = winsharedutils.mecab_parse(self.kks, text.encode(codec), fp)
if not succ: if not succ:
raise Exception("mecab parse failed") raise Exception("mecab parse failed")

View File

@ -173,8 +173,8 @@ def ListProcess(exe=None):
return ret.get(exe, []) return ret.get(exe, [])
def getExeIcon(name, icon=True, cache=False): def getExeIcon(name: str, icon=True, cache=False):
if name.lower()[-4:] == ".lnk": if name.lower().endswith(".lnk"):
exepath, args, iconpath, dirp = winsharedutils.GetLnkTargetPath(name) exepath, args, iconpath, dirp = winsharedutils.GetLnkTargetPath(name)
if os.path.exists(iconpath): if os.path.exists(iconpath):
name = iconpath name = iconpath

View File

@ -27,16 +27,16 @@ class Launcher:
class LEbase(Launcher): class LEbase(Launcher):
def runX(self, exe, usearg, dirpath, config): ... def runX(self, exe, usearg, dirpath, config): ...
def run(self, game, config): def run(self, game: str, config):
dirpath = os.path.dirname(game) dirpath = os.path.dirname(game)
if game.lower()[-4:] not in [".lnk", ".exe"]: if not (game.lower().endswith(".exe") or game.lower().endswith(".lnk")):
# 对于其他文件需要AssocQueryStringW获取命令行才能正确le太麻烦放弃。 # 对于其他文件需要AssocQueryStringW获取命令行才能正确le太麻烦放弃。
windows.ShellExecute(None, "open", game, "", dirpath, windows.SW_SHOW) windows.ShellExecute(None, "open", game, "", dirpath, windows.SW_SHOW)
return return
execheck3264 = game execheck3264 = game
usearg = '"{}"'.format(game) usearg = '"{}"'.format(game)
if game.lower()[-4:] == ".lnk": if game.lower().endswith(".lnk"):
exepath, args, iconpath, dirp = winsharedutils.GetLnkTargetPath(game) exepath, args, iconpath, dirp = winsharedutils.GetLnkTargetPath(game)
if args != "": if args != "":

View File

@ -2,12 +2,10 @@ import windows
import os, time import os, time
import codecs, hashlib, shutil import codecs, hashlib, shutil
import socket, gobject, uuid, subprocess, functools import socket, gobject, uuid, subprocess, functools
import ctypes, importlib, json import importlib, json
import ctypes.wintypes
from qtsymbols import * from qtsymbols import *
from string import Formatter from string import Formatter
from ctypes import CDLL, c_void_p, CFUNCTYPE, c_size_t, cast, c_char, POINTER from ctypes import cast, c_char, POINTER
from ctypes.wintypes import HANDLE
from traceback import print_exc from traceback import print_exc
from myutils.config import ( from myutils.config import (
globalconfig, globalconfig,
@ -305,7 +303,7 @@ def duplicateconfig(uidold):
return uid return uid
def find_or_create_uid(targetlist, gamepath, title=None): def find_or_create_uid(targetlist, gamepath: str, title=None):
uids = findgameuidofpath(gamepath, findall=True) uids = findgameuidofpath(gamepath, findall=True)
if len(uids) == 0: if len(uids) == 0:
uid = initanewitem(title) uid = initanewitem(title)
@ -315,6 +313,11 @@ def find_or_create_uid(targetlist, gamepath, title=None):
+ "/" + "/"
+ os.path.basename(gamepath) + os.path.basename(gamepath)
) )
if gamepath.lower().endswith(".lnk"):
exepath, _, _, _ = winsharedutils.GetLnkTargetPath(gamepath)
uid2gamepath[uid] = exepath
savehook_new_data[uid]["launchpath"] = gamepath
else:
uid2gamepath[uid] = gamepath uid2gamepath[uid] = gamepath
trysearchforid(uid, [title] + guessmaybetitle(gamepath, title)) trysearchforid(uid, [title] + guessmaybetitle(gamepath, title))
return uid return uid
@ -429,18 +432,6 @@ def getfilemd5(file, default="0"):
def minmaxmoveobservefunc(self): def minmaxmoveobservefunc(self):
user32 = ctypes.windll.user32
WinEventProcType = ctypes.CFUNCTYPE(
None,
ctypes.wintypes.HANDLE,
ctypes.wintypes.DWORD,
ctypes.wintypes.HWND,
ctypes.wintypes.LONG,
ctypes.wintypes.LONG,
ctypes.wintypes.DWORD,
ctypes.wintypes.DWORD,
)
self.lastpos = None self.lastpos = None
def win_event_callback( def win_event_callback(
@ -492,7 +483,7 @@ def minmaxmoveobservefunc(self):
except: except:
print_exc() print_exc()
win_event_callback_cfunc = WinEventProcType(win_event_callback) win_event_callback_cfunc = windows.WINEVENTPROC(win_event_callback)
eventpairs = ( eventpairs = (
(windows.EVENT_SYSTEM_FOREGROUND, windows.EVENT_SYSTEM_FOREGROUND), (windows.EVENT_SYSTEM_FOREGROUND, windows.EVENT_SYSTEM_FOREGROUND),
@ -501,16 +492,16 @@ def minmaxmoveobservefunc(self):
def _(): def _():
for pair in eventpairs: for pair in eventpairs:
hook_id = user32.SetWinEventHook( hook_id = windows.SetWinEventHook(
pair[0], pair[1], 0, win_event_callback_cfunc, 0, 0, 0 pair[0], pair[1], 0, win_event_callback_cfunc, 0, 0, 0
) )
msg = ctypes.wintypes.MSG() msg = windows.MSG()
while ctypes.windll.user32.GetMessageW(ctypes.byref(msg), None, 0, 0) != 0: while windows.GetMessageW(windows.byref(msg), None, 0, 0) != 0:
ctypes.windll.user32.TranslateMessage(ctypes.byref(msg)) windows.TranslateMessage(windows.byref(msg))
ctypes.windll.user32.DispatchMessageW(ctypes.byref(msg)) windows.DispatchMessageW(windows.byref(msg))
ctypes.windll.user32.UnhookWindowsHookEx(hook_id) windows.UnhookWindowsHookEx(hook_id)
_() _()
@ -831,7 +822,7 @@ class audiocapture:
self.stoped = threading.Lock() self.stoped = threading.Lock()
self.stoped.acquire() self.stoped.acquire()
self.data = None self.data = None
self.cb1 = CFUNCTYPE(None, c_void_p, c_size_t)(self.__datacollect) self.cb1 = winsharedutils.StartCaptureAsync_cb(self.__datacollect)
self.mutex = winsharedutils.StartCaptureAsync(self.cb1) self.mutex = winsharedutils.StartCaptureAsync(self.cb1)

View File

@ -3,12 +3,7 @@ import time
import _thread as thread import _thread as thread
import windows import windows
import ctypes
from ctypes import wintypes
byref = ctypes.byref
user32 = ctypes.windll.user32
PM_REMOVE = 0x0001
unique_int = 0 unique_int = 0
@ -37,7 +32,7 @@ class SystemHotkey:
self.changedlock.acquire() self.changedlock.acquire()
self.hk_ref[unique_int] = hotkey self.hk_ref[unique_int] = hotkey
self.changedlock.release() self.changedlock.release()
if not user32.RegisterHotKey(None, unique_int, masks, keycode): if not windows.RegisterHotKey(None, unique_int, masks, keycode):
self._error = True self._error = True
self.waitforregist.release() self.waitforregist.release()
@ -58,7 +53,7 @@ class SystemHotkey:
break break
if _use: if _use:
del self.hk_ref[_use] del self.hk_ref[_use]
user32.UnregisterHotKey(None, _use) windows.UnregisterHotKey(None, _use)
self.changedlock.release() self.changedlock.release()
self.hk_action_queue.put(lambda: nt_unregister(hotkey)) self.hk_action_queue.put(lambda: nt_unregister(hotkey))
@ -78,7 +73,7 @@ class SystemHotkey:
) )
def _nt_wait(self): def _nt_wait(self):
msg = wintypes.MSG() msg = windows.MSG()
while 1: while 1:
try: try:
remove_or_add = self.hk_action_queue.get(block=False) remove_or_add = self.hk_action_queue.get(block=False)
@ -87,7 +82,7 @@ class SystemHotkey:
pass pass
else: else:
remove_or_add() remove_or_add()
if user32.PeekMessageA(byref(msg), 0, 0, 0, PM_REMOVE): if windows.PeekMessageA(windows.pointer(msg), 0, 0, 0, windows.PM_REMOVE):
if msg.message == windows.WM_HOTKEY: if msg.message == windows.WM_HOTKEY:
self.changedlock.acquire() self.changedlock.acquire()
hotkey = self.hk_ref[msg.wParam][0], self.hk_ref[msg.wParam][1] hotkey = self.hk_ref[msg.wParam][0], self.hk_ref[msg.wParam][1]

View File

@ -1,4 +1,4 @@
import gobject, os import gobject
from requests import RequestException, Timeout from requests import RequestException, Timeout
from ctypes import ( from ctypes import (
CDLL, CDLL,

View File

@ -1,4 +1,4 @@
import gobject, os, uuid, windows import gobject, os, uuid
from ocrengines.baseocrclass import baseocr from ocrengines.baseocrclass import baseocr
from ctypes import CDLL, c_void_p, c_wchar_p, c_char_p, CFUNCTYPE, c_bool, c_int from ctypes import CDLL, c_void_p, c_wchar_p, c_char_p, CFUNCTYPE, c_bool, c_int
import winsharedutils import winsharedutils

View File

@ -53,8 +53,22 @@ class Qlabel_c(QLabel):
class TextBrowser(QWidget, dataget): class TextBrowser(QWidget, dataget):
contentsChanged = pyqtSignal(QSize) contentsChanged = pyqtSignal(QSize)
dropfilecallback = pyqtSignal(str)
_padding = 5 _padding = 5
def dragEnterEvent(self, event: QDragEnterEvent):
if event.mimeData().hasUrls():
event.accept()
else:
event.ignore()
def dropEvent(self, event: QDropEvent):
files = [u.toLocalFile() for u in event.mimeData().urls()]
if not files:
return
file = files[0]
self.dropfilecallback.emit(file)
def __makeborder(self, size: QSize): def __makeborder(self, size: QSize):
# border是用来当可选取时用来拖动的 # border是用来当可选取时用来拖动的
# webview2的绘制和qt的绘制不兼容qt的半透明对他无效必须缩放否则遮挡所以还是各写一份吧。 # webview2的绘制和qt的绘制不兼容qt的半透明对他无效必须缩放否则遮挡所以还是各写一份吧。
@ -85,6 +99,7 @@ class TextBrowser(QWidget, dataget):
def __init__(self, parent) -> None: def __init__(self, parent) -> None:
super().__init__(parent) super().__init__(parent)
self.setAcceptDrops(True)
self.atback_color = QLabel(self) self.atback_color = QLabel(self)
self.atback_color.setMouseTracking(True) self.atback_color.setMouseTracking(True)
self.atback2 = QLabel(self) self.atback2 = QLabel(self)

View File

@ -19,6 +19,21 @@
display: none; display: none;
} }
</style> </style>
<script>document.addEventListener('DOMContentLoaded', () => {
//https://github.com/MicrosoftEdge/WebView2Feedback/blob/main/specs/WebMessageObjects.md
// 阻止浏览器默认行为
['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
document.body.addEventListener(eventName, (e) => {
e.preventDefault();
e.stopPropagation();
}, false);
});
document.body.addEventListener('drop', (e) => { chrome.webview.postMessageWithAdditionalObjects("FilesDropped", e.dataTransfer.files); }, false);
});
</script>
<script> <script>
//nativte api //nativte api
function safe_calllunaheightchange(h) { function safe_calllunaheightchange(h) {

View File

@ -10,6 +10,7 @@ testsavejs = False
class TextBrowser(QWidget, dataget): class TextBrowser(QWidget, dataget):
dropfilecallback = pyqtSignal(str)
contentsChanged = pyqtSignal(QSize) contentsChanged = pyqtSignal(QSize)
_padding = 5 _padding = 5
@ -75,6 +76,7 @@ class TextBrowser(QWidget, dataget):
os.path.abspath(r"LunaTranslator\rendertext\webview.html") os.path.abspath(r"LunaTranslator\rendertext\webview.html")
) )
self.webivewwidget.set_transparent_background() self.webivewwidget.set_transparent_background()
self.webivewwidget.dropfilecallback.connect(self.dropfilecallback)
self.webivewwidget.bind("calllunaclickedword", self.calllunaclickedword) self.webivewwidget.bind("calllunaclickedword", self.calllunaclickedword)
self.webivewwidget.bind("calllunaheightchange", self.calllunaheightchange) self.webivewwidget.bind("calllunaheightchange", self.calllunaheightchange)
self.saveiterclasspointer = {} self.saveiterclasspointer = {}

View File

@ -3,7 +3,6 @@ import json
import windows, gobject import windows, gobject
from myutils.config import globalconfig, magpie_config from myutils.config import globalconfig, magpie_config
from myutils.subproc import subproc_w from myutils.subproc import subproc_w
from ctypes import c_int, CFUNCTYPE, c_void_p
import winsharedutils import winsharedutils
class Method(scalebase): class Method(scalebase):
@ -19,7 +18,7 @@ class Method(scalebase):
self.setuistatus(int(bool(status))) self.setuistatus(int(bool(status)))
def init(self): def init(self):
self.messagecallback__ = CFUNCTYPE(None, c_int, c_void_p)(self.messagecallback) self.messagecallback__ = winsharedutils.globalmessagelistener_cb(self.messagecallback)
winsharedutils.globalmessagelistener(self.messagecallback__) winsharedutils.globalmessagelistener(self.messagecallback__)
self.jspath = gobject.gettempdir("magpie.config.json") self.jspath = gobject.gettempdir("magpie.config.json")
self.engine = subproc_w( self.engine = subproc_w(

View File

@ -13,9 +13,7 @@ class livecaptions(basetext):
threading.Thread(target=os.system, args=("livecaptions.exe",)).start() threading.Thread(target=os.system, args=("livecaptions.exe",)).start()
self.curr = "" self.curr = ""
self.lastshow = "" self.lastshow = ""
self._kep = winrtutils.CFUNCTYPE(winrtutils.c_void_p, winrtutils.c_wchar_p)( self._kep = winrtutils.livecaption_start_callback(self.callback)
self.callback
)
self.sem = winrtutils.livecaption_start(self._kep) self.sem = winrtutils.livecaption_start(self._kep)
self.lasttime = time.time() self.lasttime = time.time()
self.flashtime = time.time() self.flashtime = time.time()

View File

@ -29,12 +29,15 @@ from ctypes.wintypes import (
BOOL, BOOL,
WORD, WORD,
DWORD, DWORD,
LONG,
MSG,
PHKEY, PHKEY,
HKEY, HKEY,
LPDWORD, LPDWORD,
LPBYTE, LPBYTE,
HMONITOR, HMONITOR,
LPCVOID, LPCVOID,
LPMSG,
LPWSTR, LPWSTR,
WPARAM, WPARAM,
LPARAM, LPARAM,
@ -42,8 +45,16 @@ from ctypes.wintypes import (
LPCWSTR, LPCWSTR,
HANDLE, HANDLE,
UINT, UINT,
HHOOK,
HMODULE,
LPLONG,
HDC,
SHORT,
USHORT,
) )
HWINEVENTHOOK = HANDLE
LRESULT = LPLONG
WAIT_TIMEOUT = 258 WAIT_TIMEOUT = 258
SW_HIDE = 0 SW_HIDE = 0
SW_SHOWNORMAL = 1 SW_SHOWNORMAL = 1
@ -202,35 +213,37 @@ _Advapi32 = windll.Advapi32
_GetWindowRect = _user32.GetWindowRect _GetWindowRect = _user32.GetWindowRect
_GetWindowRect.argtypes = HWND, POINTER(RECT) _GetWindowRect.argtypes = HWND, POINTER(RECT)
_GetForegroundWindow = _user32.GetForegroundWindow GetForegroundWindow = _user32.GetForegroundWindow
_WindowFromPoint = _user32.WindowFromPoint GetForegroundWindow.restype = HWND
_WindowFromPoint.argtypes = (POINT,) WindowFromPoint = _user32.WindowFromPoint
_ShowWindow = _user32.ShowWindow WindowFromPoint.argtypes = (POINT,)
_ShowWindow.argtypes = c_int, c_int WindowFromPoint.restype = HWND
ShowWindow = _user32.ShowWindow
ShowWindow.argtypes = HWND, c_int
ShowWindow.restype = BOOL
GetWindowLong = _user32.GetWindowLongW
GetWindowLong.argtypes = HWND, c_int
GetWindowLong.restype = LONG
_GetWindowLong = _user32.GetWindowLongW SetWindowLong = _user32.SetWindowLongW
_GetWindowLong.argtypes = c_int, c_int SetWindowLong.argtypes = HWND, c_int, LONG
SetWindowLong.restype = LONG
_SetWindowLongW = _user32.SetWindowLongW
_SetWindowLongW.argtypes = c_int, c_int, c_int
BringWindowToTop = _user32.BringWindowToTop BringWindowToTop = _user32.BringWindowToTop
BringWindowToTop.argtypes = (HWND,) BringWindowToTop.argtypes = (HWND,)
_GetDC = _user32.GetDC GetDC = _user32.GetDC
_GetDC.restype = c_void_p GetDC.restype = HDC
_ReleaseDC = _user32.ReleaseDC ReleaseDC = _user32.ReleaseDC
_ReleaseDC.argtypes = c_void_p, c_void_p ReleaseDC.argtypes = HWND, HDC
ReleaseDC.restype = c_int
def ReleaseDC(_, hdc):
return _ReleaseDC(_, hdc)
_GetCursorPos = _user32.GetCursorPos _GetCursorPos = _user32.GetCursorPos
_GetCursorPos.argtypes = (POINTER(POINT),) _GetCursorPos.argtypes = (POINTER(POINT),)
_GetDeviceCaps = _gdi32.GetDeviceCaps GetDeviceCaps = _gdi32.GetDeviceCaps
_GetDeviceCaps.argtypes = c_int, c_int GetDeviceCaps.argtypes = HDC, c_int
GetDeviceCaps.restype = c_int
_SetWindowPos = _user32.SetWindowPos _SetWindowPos = _user32.SetWindowPos
_SetWindowPos.argtypes = c_int, c_void_p, c_int, c_int, c_int, c_int, c_uint _SetWindowPos.argtypes = c_int, c_void_p, c_int, c_int, c_int, c_int, c_uint
_GetWindowText = _user32.GetWindowTextW _GetWindowText = _user32.GetWindowTextW
@ -239,50 +252,44 @@ _GetWindowTextLength = _user32.GetWindowTextLengthW
_MoveWindow = _user32.MoveWindow _MoveWindow = _user32.MoveWindow
_MoveWindow.argtypes = c_int, c_int, c_int, c_int, c_int, c_bool _MoveWindow.argtypes = c_int, c_int, c_int, c_int, c_int, c_bool
_IsWindow = _user32.IsWindow SetForegroundWindow = _user32.SetForegroundWindow
_IsWindowEnabled = _user32.IsWindowEnabled SetForegroundWindow.argtypes = (HWND,)
_IsWindowVisible = _user32.IsWindowVisible
_SetForegroundWindow = _user32.SetForegroundWindow
_SetForegroundWindow.argtypes = (c_int,)
_GetClientRect = _user32.GetClientRect _GetClientRect = _user32.GetClientRect
_GetClientRect.argtypes = c_int, POINTER(RECT) _GetClientRect.argtypes = c_int, POINTER(RECT)
_FindWindow = _user32.FindWindowW FindWindow = _user32.FindWindowW
_FindWindow.argtypes = c_wchar_p, c_wchar_p FindWindow.argtypes = LPCWSTR, LPCWSTR
_SetFocus = _user32.SetFocus FindWindow.restype = HWND
_SetFocus.argtypes = (c_int,) SetFocus = _user32.SetFocus
SetFocus.argtypes = (HWND,)
_EnumWindows = _user32.EnumWindows _EnumWindows = _user32.EnumWindows
_EnumWindows.argtypes = WNDENUMPROC, c_void_p _EnumWindows.argtypes = WNDENUMPROC, c_void_p
_ShellExecuteW = _shell32.ShellExecuteW _ShellExecuteW = _shell32.ShellExecuteW
_ShellExecuteW.argtypes = c_void_p, c_wchar_p, c_wchar_p, c_wchar_p, c_wchar_p, c_int _ShellExecuteW.argtypes = c_void_p, c_wchar_p, c_wchar_p, c_wchar_p, c_wchar_p, c_int
_OpenProcess = _kernel32.OpenProcess _OpenProcess = _kernel32.OpenProcess
_OpenProcess.argtypes = c_uint, c_bool, c_uint _OpenProcess.argtypes = c_uint, c_bool, c_uint
_CloseHandle = _kernel32.CloseHandle CloseHandle = _kernel32.CloseHandle
CloseHandle.argtypes = (HANDLE,)
CloseHandle.restype = BOOL
_SendMessage = _user32.SendMessageW _SendMessage = _user32.SendMessageW
_SendMessage.argtypes = c_int, c_uint, c_void_p, c_void_p _SendMessage.argtypes = c_int, c_uint, c_void_p, c_void_p
_keybd_event = _user32.keybd_event _keybd_event = _user32.keybd_event
_keybd_event.argtypes = c_byte, c_byte, c_uint, c_void_p _keybd_event.argtypes = c_byte, c_byte, c_uint, c_void_p
_RegisterWindowMessage = _user32.RegisterWindowMessageW RegisterWindowMessageW = _user32.RegisterWindowMessageW
RegisterWindowMessageW.argtypes = (LPCWSTR,)
RegisterWindowMessageW.restype = UINT
_GetWindowThreadProcessId = _user32.GetWindowThreadProcessId _GetWindowThreadProcessId = _user32.GetWindowThreadProcessId
_GetWindowThreadProcessId.argtypes = HWND, c_void_p _GetWindowThreadProcessId.argtypes = HWND, c_void_p
_GetClipboardOwner = _user32.GetClipboardOwner GetClipboardOwner = _user32.GetClipboardOwner
GetClipboardOwner.restype = HWND
try: try:
_GetModuleFileNameExW = _psapi.GetModuleFileNameExW _GetModuleFileNameExW = _psapi.GetModuleFileNameExW
except: except:
_GetModuleFileNameExW = _kernel32.GetModuleFileNameExW _GetModuleFileNameExW = _kernel32.GetModuleFileNameExW
_GetModuleFileNameExW.argtypes = c_void_p, c_void_p, c_wchar_p, c_uint _GetModuleFileNameExW.argtypes = HANDLE, HMODULE, LPWSTR, DWORD
_GetModuleFileNameExW.restype = DWORD
def GetModuleFileNameEx(handle, module=None):
buff = create_unicode_buffer(260)
_GetModuleFileNameExW(handle, module, buff, 260)
return buff.value
_GetLogicalDrives = _kernel32.GetLogicalDrives
_QueryDosDeviceW = _kernel32.QueryDosDeviceW _QueryDosDeviceW = _kernel32.QueryDosDeviceW
_QueryDosDeviceW.argtypes = c_wchar_p, c_wchar_p, c_uint _QueryDosDeviceW.argtypes = c_wchar_p, c_wchar_p, c_uint
@ -300,7 +307,8 @@ _WNetGetUniversalNameW = _Mpr.WNetGetUniversalNameW
_WNetGetUniversalNameW.argtypes = c_wchar_p, c_uint, c_wchar_p, POINTER(c_uint) _WNetGetUniversalNameW.argtypes = c_wchar_p, c_uint, c_wchar_p, POINTER(c_uint)
_GetLogicalDriveStringsW = _kernel32.GetLogicalDriveStringsW _GetLogicalDriveStringsW = _kernel32.GetLogicalDriveStringsW
_GetLogicalDriveStringsW.argtypes = c_uint, c_wchar_p _GetLogicalDriveStringsW.argtypes = DWORD, LPWSTR
_GetLogicalDriveStringsW.restype = DWORD
_GetCurrentDirectoryW = _kernel32.GetCurrentDirectoryW _GetCurrentDirectoryW = _kernel32.GetCurrentDirectoryW
_GetCurrentDirectoryW.argtypes = c_uint, c_wchar_p _GetCurrentDirectoryW.argtypes = c_uint, c_wchar_p
@ -445,10 +453,6 @@ def CreateProcess(
return _pinfo return _pinfo
def GetClipboardOwner():
return _GetClipboardOwner()
def GetWindowThreadProcessId(hwnd): def GetWindowThreadProcessId(hwnd):
pid = c_uint() pid = c_uint()
handle = _GetWindowThreadProcessId(hwnd, pointer(pid)) handle = _GetWindowThreadProcessId(hwnd, pointer(pid))
@ -457,18 +461,6 @@ def GetWindowThreadProcessId(hwnd):
return pid.value return pid.value
def RegisterWindowMessage(lpString):
return _RegisterWindowMessage(c_wchar_p(lpString))
def SetFocus(hwnd):
return _SetFocus(hwnd)
def GetForegroundWindow():
return _GetForegroundWindow()
def GetWindowRect(hwnd): def GetWindowRect(hwnd):
_rect = RECT() _rect = RECT()
if _GetWindowRect(hwnd, pointer(_rect)): if _GetWindowRect(hwnd, pointer(_rect)):
@ -483,22 +475,6 @@ def GetClientRect(hwnd):
return (_rect.left, _rect.top, _rect.right, _rect.bottom) return (_rect.left, _rect.top, _rect.right, _rect.bottom)
def ShowWindow(hwnd, nCmdShow):
return _ShowWindow(hwnd, nCmdShow)
def GetWindowLong(hwnd, nIndex):
return _GetWindowLong(hwnd, nIndex)
def SetWindowLong(hwnd, nIndex, value):
return _SetWindowLongW(hwnd, nIndex, value)
def GetDC(hwnd):
return _GetDC(hwnd)
def GetDpiForWindow(hwnd): def GetDpiForWindow(hwnd):
try: try:
_GetDpiForWindow = _user32.GetDpiForWindow _GetDpiForWindow = _user32.GetDpiForWindow
@ -515,14 +491,6 @@ def GetCursorPos():
return _p return _p
def GetDeviceCaps(hdc, index):
return _GetDeviceCaps(hdc, index)
def WindowFromPoint(point):
return _WindowFromPoint(point)
def SetWindowPos(hwnd, InsertAfter, X, Y, cx, cy, uFlags): def SetWindowPos(hwnd, InsertAfter, X, Y, cx, cy, uFlags):
return _SetWindowPos(hwnd, InsertAfter, X, Y, cx, cy, uFlags) return _SetWindowPos(hwnd, InsertAfter, X, Y, cx, cy, uFlags)
@ -538,26 +506,6 @@ def MoveWindow(hwnd, X, Y, w, h, bRepaint):
return _MoveWindow(hwnd, X, Y, w, h, bRepaint) return _MoveWindow(hwnd, X, Y, w, h, bRepaint)
def IsWindow(hwnd):
return _IsWindow(hwnd)
def IsWindowEnabled(hwnd):
return _IsWindowEnabled(hwnd)
def IsWindowVisible(hwnd):
return _IsWindowVisible(hwnd)
def SetForegroundWindow(hwnd):
return _SetForegroundWindow(hwnd)
def FindWindow(classname, windowname):
return _FindWindow(c_wchar_p(classname), c_wchar_p(windowname))
def EnumWindows(lpEnumFunc, lParam): def EnumWindows(lpEnumFunc, lParam):
return _EnumWindows(WNDENUMPROC(lpEnumFunc), 0) return _EnumWindows(WNDENUMPROC(lpEnumFunc), 0)
@ -570,10 +518,6 @@ def OpenProcess(dwDesiredAccess, bInheritHandle, dwProcessId):
return _OpenProcess(dwDesiredAccess, bInheritHandle, dwProcessId) return _OpenProcess(dwDesiredAccess, bInheritHandle, dwProcessId)
def CloseHandle(handle):
return _CloseHandle(handle)
def SendMessage(hwnd, message, wp=None, lp=None): def SendMessage(hwnd, message, wp=None, lp=None):
return _SendMessage(hwnd, message, wp, lp) return _SendMessage(hwnd, message, wp, lp)
@ -582,21 +526,16 @@ def keybd_event(bVk, bScan, dwFlags, _):
_keybd_event(bVk, bScan, dwFlags, _) _keybd_event(bVk, bScan, dwFlags, _)
_WaitForSingleObject = _kernel32.WaitForSingleObject WaitForSingleObject = _kernel32.WaitForSingleObject
_WaitForSingleObject.argtypes = c_void_p, c_uint WaitForSingleObject.argtypes = HANDLE, DWORD
WaitForSingleObject.restype = DWORD
def WaitForSingleObject(handle, dwms):
return _WaitForSingleObject(handle, dwms)
INFINITE = -1 INFINITE = -1
_SetEvent = _kernel32.SetEvent SetEvent = _kernel32.SetEvent
SetEvent.argtypes = (HANDLE,)
SetEvent.restype = BOOL
def SetEvent(hevent):
return _SetEvent(hevent)
class ACLStruct(Structure): class ACLStruct(Structure):
@ -745,12 +684,9 @@ def CreateFile(
) )
_WaitNamedPipeW = _kernel32.WaitNamedPipeW WaitNamedPipe = _kernel32.WaitNamedPipeW
_WaitNamedPipeW.argtypes = c_wchar_p, c_uint WaitNamedPipe.argtypes = LPCWSTR, DWORD
WaitNamedPipe.restype = BOOL
def WaitNamedPipe(pipename, timeout):
return _WaitNamedPipeW(pipename, timeout)
# _TerminateProcess=_kernel32.TerminateProcess # _TerminateProcess=_kernel32.TerminateProcess
@ -789,91 +725,25 @@ def IsUserAnAdmin():
return False return False
_GetKeyState = _user32.GetKeyState GetKeyState = _user32.GetKeyState
_GetKeyState.restype = c_short GetKeyState.argtypes = (c_int,)
GetKeyState.restype = SHORT
GetAsyncKeyState = _user32.GetAsyncKeyState GetAsyncKeyState = _user32.GetAsyncKeyState
GetAsyncKeyState.argtypes = (c_int,)
GetAsyncKeyState.restype = SHORT
def GetKeyState(key):
return _GetKeyState(key)
GA_ROOT = 2 GA_ROOT = 2
_GetAncestor = _user32.GetAncestor _GetAncestor = _user32.GetAncestor
_GetAncestor.argtypes = HWND, UINT
_GetAncestor.restype = HWND
def GetAncestor(hwnd): def GetAncestor(hwnd):
return _GetAncestor(hwnd, GA_ROOT) return _GetAncestor(hwnd, GA_ROOT)
_CreateNamedPipe = _kernel32.CreateNamedPipeW
_CreateNamedPipe.argtypes = (
c_wchar_p,
c_uint,
c_uint,
c_uint,
c_uint,
c_uint,
c_uint,
c_void_p,
)
def CreateNamedPipe(
pipeName,
openMode,
pipeMode,
nMaxInstances,
nOutBufferSize,
nInBufferSize,
nDefaultTimeOut,
sa=pointer(get_SECURITY_ATTRIBUTES()),
):
return _CreateNamedPipe(
pipeName,
openMode,
pipeMode,
nMaxInstances,
nOutBufferSize,
nInBufferSize,
nDefaultTimeOut,
sa,
)
PIPE_TYPE_BYTE = 0
PIPE_READMODE_BYTE = 0
_DisconnectNamedPipe = _kernel32.DisconnectNamedPipe
def DisconnectNamedPipe(pipe):
return _DisconnectNamedPipe(pipe)
_ConnectNamedPipe = _kernel32.ConnectNamedPipe
def ConnectNamedPipe(pipe, lpoverlap):
return _ConnectNamedPipe(pipe, lpoverlap)
_MessageBoxW = _user32.MessageBoxW
_MessageBoxW.argtypes = c_void_p, c_wchar_p, c_wchar_p, c_uint
def MessageBox(hwnd, text, title, _type):
return _MessageBoxW(hwnd, text, title, _type)
_CancelIo = _kernel32.CancelIo
_CancelIo.argtypes = (c_void_p,)
def CancelIo(hfile):
return _CancelIo(hfile)
def GetDpiForWindow(hwnd): def GetDpiForWindow(hwnd):
try: try:
_GetDpiForWindow = _user32.GetDpiForWindow _GetDpiForWindow = _user32.GetDpiForWindow
@ -934,22 +804,14 @@ def CreatePipe(lpsecu=None, sz=0):
return AutoHandle(hread.value), AutoHandle(hwrite.value) return AutoHandle(hread.value), AutoHandle(hwrite.value)
_CopyFile = _kernel32.CopyFileW CopyFile = _kernel32.CopyFileW
_CopyFile.argtypes = LPCWSTR, LPCWSTR, BOOL CopyFile.argtypes = LPCWSTR, LPCWSTR, BOOL
_CopyFile.restype = BOOL CopyFile.restype = BOOL
def CopyFile(src, dst, bFailIfExists): SetProp = _user32.SetPropW
return _CopyFile(src, dst, bFailIfExists) SetProp.argtypes = HWND, LPCWSTR, HANDLE
SetProp.restype = BOOL
_SetPropW = _user32.SetPropW
_SetPropW.argtypes = HWND, LPCWSTR, HANDLE
_SetPropW.restype = BOOL
def SetProp(hwnd, string, hdata):
return _SetPropW(hwnd, string, hdata)
_GetEnvironmentVariableW = _kernel32.GetEnvironmentVariableW _GetEnvironmentVariableW = _kernel32.GetEnvironmentVariableW
@ -965,12 +827,8 @@ def addenvpath(path):
_SetEnvironmentVariableW("PATH", env.value + ";" + path) _SetEnvironmentVariableW("PATH", env.value + ";" + path)
_LoadLibraryW = _kernel32.LoadLibraryW LoadLibraryW = _kernel32.LoadLibraryW
_LoadLibraryW.argtypes = (LPCWSTR,) LoadLibraryW.argtypes = (LPCWSTR,)
def loadlibrary(path):
_LoadLibraryW(path)
SECTION_MAP_WRITE = 0x0002 SECTION_MAP_WRITE = 0x0002
@ -1056,3 +914,48 @@ _MonitorFromWindow.restype = HMONITOR
def MonitorFromWindow(hwnd, dwFlags=MONITOR_DEFAULTTONEAREST): def MonitorFromWindow(hwnd, dwFlags=MONITOR_DEFAULTTONEAREST):
return _MonitorFromWindow(hwnd, dwFlags) return _MonitorFromWindow(hwnd, dwFlags)
WINEVENTPROC = CFUNCTYPE(
None,
HANDLE,
DWORD,
HWND,
LONG,
LONG,
DWORD,
DWORD,
)
PM_REMOVE = 0x0001
PeekMessageA = _user32.PeekMessageA
PeekMessageA.argtypes = LPMSG, HWND, UINT, UINT, UINT
PeekMessageA.restype = BOOL
RegisterHotKey = _user32.RegisterHotKey
RegisterHotKey.argtypes = HWND, c_int, UINT, UINT
RegisterHotKey.restype = BOOL
UnregisterHotKey = _user32.UnregisterHotKey
UnregisterHotKey.restype = BOOL
UnregisterHotKey.argtypes = HWND, c_int
UnhookWindowsHookEx = _user32.UnhookWindowsHookEx
UnhookWindowsHookEx.argtypes = (HHOOK,)
UnhookWindowsHookEx.restype = BOOL
TranslateMessage = _user32.TranslateMessage
TranslateMessage.argtypes = (LPMSG,)
TranslateMessage.restype = BOOL
DispatchMessageW = _user32.DispatchMessageW
DispatchMessageW.argtypes = (LPMSG,)
DispatchMessageW.restype = LRESULT
GetMessageW = _user32.GetMessageW
GetMessageW.argtypes = LPMSG, HWND, UINT, UINT
GetMessageW.restype = BOOL
SetWinEventHook = _user32.SetWinEventHook
SetWinEventHook.restype = HWINEVENTHOOK
SetWinEventHook.argtypes = DWORD, DWORD, HMODULE, WINEVENTPROC, DWORD, DWORD, DWORD
PathFileExists = windll.Shlwapi.PathFileExistsW
PathFileExists.argtypes = (LPCWSTR,)
PathFileExists.restype = BOOL

View File

@ -73,8 +73,9 @@ if winrtutilsdll:
return ret[0] return ret[0]
return None return None
livecaption_start_callback = CFUNCTYPE(c_void_p, c_wchar_p)
livecaption_start = winrtutilsdll.livecaption_start livecaption_start = winrtutilsdll.livecaption_start
livecaption_start.argtypes = (c_void_p,) livecaption_start.argtypes = (livecaption_start_callback,)
livecaption_start.restype = HANDLE livecaption_start.restype = HANDLE
livecaption_stop = winrtutilsdll.livecaption_stop livecaption_stop = winrtutilsdll.livecaption_stop
livecaption_stop.argtypes = (HANDLE,) livecaption_stop.argtypes = (HANDLE,)

View File

@ -49,9 +49,9 @@ levenshtein_ratio.restype = c_double
mecab_init = utilsdll.mecab_init mecab_init = utilsdll.mecab_init
mecab_init.argtypes = c_char_p, c_wchar_p mecab_init.argtypes = c_char_p, c_wchar_p
mecab_init.restype = c_void_p mecab_init.restype = c_void_p
mecab_parse_cb = CFUNCTYPE(None, c_char_p, c_char_p)
mecab_parse = utilsdll.mecab_parse mecab_parse = utilsdll.mecab_parse
mecab_parse.argtypes = (c_void_p, c_char_p, c_void_p) mecab_parse.argtypes = (c_void_p, c_char_p, mecab_parse_cb)
mecab_parse.restype = c_bool mecab_parse.restype = c_bool
mecab_end = utilsdll.mecab_end mecab_end = utilsdll.mecab_end
@ -235,8 +235,9 @@ def queryversion(exe):
return None return None
globalmessagelistener_cb = CFUNCTYPE(None, c_int, c_void_p)
globalmessagelistener = utilsdll.globalmessagelistener globalmessagelistener = utilsdll.globalmessagelistener
globalmessagelistener.argtypes = (c_void_p,) globalmessagelistener.argtypes = (globalmessagelistener_cb,)
dispatchcloseevent = utilsdll.dispatchcloseevent dispatchcloseevent = utilsdll.dispatchcloseevent
setdwmextendframe = utilsdll.setdwmextendframe setdwmextendframe = utilsdll.setdwmextendframe
@ -332,11 +333,14 @@ put_ZoomFactor = utilsdll.put_ZoomFactor
put_ZoomFactor.argtypes = c_void_p, c_double put_ZoomFactor.argtypes = c_void_p, c_double
put_PreferredColorScheme = utilsdll.put_PreferredColorScheme put_PreferredColorScheme = utilsdll.put_PreferredColorScheme
put_PreferredColorScheme.argtypes = c_void_p, c_int put_PreferredColorScheme.argtypes = c_void_p, c_int
put_PreferredColorScheme.restype = c_long
set_transparent_background = utilsdll.set_transparent_background set_transparent_background = utilsdll.set_transparent_background
set_transparent_background.argtypes = (c_void_p,) set_transparent_background.argtypes = (c_void_p,)
add_WebMessageReceived = utilsdll.add_WebMessageReceived
add_WebMessageReceived_cb = CFUNCTYPE(c_void_p, c_wchar_p)
add_WebMessageReceived.argtypes = (c_void_p, add_WebMessageReceived_cb)
add_WebMessageReceived.restype = c_void_p
remove_WebMessageReceived = utilsdll.remove_WebMessageReceived
remove_WebMessageReceived.argtypes = c_void_p, c_void_p
clipboard_callback = utilsdll.clipboard_callback clipboard_callback = utilsdll.clipboard_callback
clipboard_callback.argtypes = (c_void_p,) clipboard_callback.argtypes = (c_void_p,)
clipboard_callback.restype = HWND clipboard_callback.restype = HWND
@ -364,9 +368,9 @@ GetMonitorDpiScaling = utilsdll.GetMonitorDpiScaling
GetMonitorDpiScaling.argtypes = (HWND,) GetMonitorDpiScaling.argtypes = (HWND,)
GetMonitorDpiScaling.restype = UINT GetMonitorDpiScaling.restype = UINT
StartCaptureAsync_cb = CFUNCTYPE(None, c_void_p, c_size_t)
StartCaptureAsync = utilsdll.StartCaptureAsync StartCaptureAsync = utilsdll.StartCaptureAsync
StartCaptureAsync.argtypes = (c_void_p,) StartCaptureAsync.argtypes = (StartCaptureAsync_cb,)
StartCaptureAsync.restype = HANDLE StartCaptureAsync.restype = HANDLE
StopCaptureAsync = utilsdll.StopCaptureAsync StopCaptureAsync = utilsdll.StopCaptureAsync
StopCaptureAsync.argtypes = (HANDLE,) StopCaptureAsync.argtypes = (HANDLE,)

View File

@ -1590,7 +1590,7 @@
"name": "百度_v2" "name": "百度_v2"
}, },
"baidu": { "baidu": {
"use": false, "use": true,
"color": "#ff65db", "color": "#ff65db",
"name": "百度_v1" "name": "百度_v1"
}, },