Skip to content

Commit

Permalink
.
Browse files Browse the repository at this point in the history
  • Loading branch information
HIllya51 committed Jan 8, 2025
1 parent 2893abd commit 646fcc2
Show file tree
Hide file tree
Showing 21 changed files with 145 additions and 106 deletions.
2 changes: 1 addition & 1 deletion cpp/version.cmake
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@

set(VERSION_MAJOR 6)
set(VERSION_MINOR 18)
set(VERSION_PATCH 0)
set(VERSION_PATCH 1)
set(VERSION_REVISION 0)
set(LUNA_VERSION "{${VERSION_MAJOR},${VERSION_MINOR},${VERSION_PATCH},${VERSION_REVISION}}")
add_library(VERSION_DEF ${CMAKE_CURRENT_LIST_DIR}/version_def.cpp)
Expand Down
2 changes: 1 addition & 1 deletion cpp/winsharedutils/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
project(winsharedutils)


add_library(winsharedutils MODULE webview2_extra.cpp AreoAcrylic.cpp screenshot.cpp ../implsapi.cpp hwnd.cpp globalmessagelistener.cpp theme.cpp version.cpp lnk.cpp levenshtein.cpp muteprocess.cpp sapi_dll.cpp simplemecab.cpp
add_library(winsharedutils MODULE clipboard.cpp webview2_extra.cpp AreoAcrylic.cpp screenshot.cpp ../implsapi.cpp hwnd.cpp globalmessagelistener.cpp theme.cpp version.cpp lnk.cpp levenshtein.cpp muteprocess.cpp sapi_dll.cpp simplemecab.cpp
applicationloopbackaudio/runer.cpp applicationloopbackaudio/LoopbackCapture.cpp
SimpleBrowser.cpp MWebBrowser.cpp icon.cpp ${versioninfo})
target_precompile_headers(winsharedutils REUSE_FROM pch)
Expand Down
68 changes: 36 additions & 32 deletions cpp/winsharedutils/clipboard.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,11 @@ bool tryopenclipboard(HWND hwnd = 0)

std::optional<std::wstring> clipboard_get_internal()
{
std::optional<std::wstring> data = {};
if (!IsClipboardFormatAvailable(CF_UNICODETEXT))
return {};
if (tryopenclipboard() == false)
return {};
std::optional<std::wstring> data = {};
do
{
HANDLE hData = GetClipboardData(CF_UNICODETEXT);
Expand Down Expand Up @@ -80,7 +82,13 @@ DECLARE_API bool clipboard_set(HWND hwnd, wchar_t *text)
CloseClipboard();
return success;
}

inline bool iscurrentowndclipboard()
{
auto ohwnd = GetClipboardOwner();
DWORD pid;
GetWindowThreadProcessId(ohwnd, &pid);
return pid == GetCurrentProcessId();
}
static void clipboard_callback_1(void (*callback)(const wchar_t *, bool), HANDLE hsema, HWND *hwnd)
{
const wchar_t CLASS_NAME[] = L"LunaClipboardListener";
Expand All @@ -91,14 +99,12 @@ static void clipboard_callback_1(void (*callback)(const wchar_t *, bool), HANDLE
static auto callbackx = [](HWND hWnd)
{
auto data = clipboard_get_internal();
if (!data)
return;
auto callback_ = reinterpret_cast<decltype(callback)>(GetWindowLongPtrW(hWnd, GWLP_USERDATA));
if (data && callback_)
{
auto ohwnd = GetClipboardOwner();
DWORD pid;
GetWindowThreadProcessId(ohwnd, &pid);
callback_(data.value().c_str(), pid == GetCurrentProcessId());
}
if (!callback_)
return;
callback_(data.value().c_str(), iscurrentowndclipboard());
};
#ifndef WINXP
if (WM_CLIPBOARDUPDATE == message)
Expand Down Expand Up @@ -158,9 +164,9 @@ static void clipboard_callback_1(void (*callback)(const wchar_t *, bool), HANDLE
DispatchMessage(&msg);
}
}
#ifndef WINXP
DECLARE_API HWND clipboard_callback(void (*callback)(const wchar_t *, bool))
{
#ifndef WINXP
HANDLE hsema = CreateSemaphoreW(0, 0, 10, 0);
HWND hwnd;

Expand All @@ -172,31 +178,26 @@ DECLARE_API HWND clipboard_callback(void (*callback)(const wchar_t *, bool))
return hwnd;
else
return NULL;
}
#else
static int running = false;
DECLARE_API HWND clipboard_callback(void (*callback)(const wchar_t *, bool))
{
running = true;
std::thread([=]()
static HANDLE clipboardUpdate;
clipboardUpdate = CreateEventW(nullptr, FALSE, TRUE, NULL);
auto __ = SetWindowsHookExW(WH_GETMESSAGE, [](int statusCode, WPARAM wParam, LPARAM lParam)
{
if (statusCode == HC_ACTION && wParam == PM_REMOVE && ((MSG*)lParam)->message == WM_CLIPBOARDUPDATE) SetEvent(clipboardUpdate);
return CallNextHookEx(NULL, statusCode, wParam, lParam); }, NULL, GetCurrentThreadId());
std::thread([=]
{
std::wstring last;
while(running){
Sleep(100);
auto data = clipboard_get_internal();
if(data){
if(last==data.value())continue;
last=data.value();
auto ohwnd = GetClipboardOwner();
DWORD pid;
GetWindowThreadProcessId(ohwnd, &pid);
callback(data.value().c_str(), pid == GetCurrentProcessId());
}
} })
while (WaitForSingleObject(clipboardUpdate, INFINITE) == WAIT_OBJECT_0)
{
auto data = clipboard_get_internal();
if(data)
callback(data.value().c_str(), iscurrentowndclipboard());
}
throw; })
.detach();
return NULL;
}
return (HWND) new std::pair<HANDLE, HHOOK>{clipboardUpdate, __};
#endif
}
DECLARE_API void clipboard_callback_stop(HWND hwnd)
{
#ifndef WINXP
Expand All @@ -205,7 +206,10 @@ DECLARE_API void clipboard_callback_stop(HWND hwnd)
RemoveClipboardFormatListener(hwnd);
DestroyWindow(hwnd);
#else
running = false;
auto __ = (std::pair<HANDLE, HHOOK> *)(hwnd);
UnhookWindowsHookEx(__->second);
CloseHandle(__->first);
delete __;
#endif
}

Expand Down
19 changes: 3 additions & 16 deletions py/LunaTranslator/LunaTranslator.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,18 +53,6 @@
from gui.setting_textinput_ocr import showocrimage


class _clipboardhelper(QObject):
setText = pyqtSignal(str)
setPixmap = pyqtSignal(QPixmap)
setImage = pyqtSignal(QImage)

def __init__(self):
super().__init__()
self.setPixmap.connect(QApplication.clipboard().setPixmap)
self.setImage.connect(QApplication.clipboard().setImage)
self.setText.connect(QApplication.clipboard().setText)


class MAINUI:
def __init__(self) -> None:
super().__init__()
Expand Down Expand Up @@ -99,7 +87,7 @@ def __init__(self) -> None:
self.autoswitchgameuid = True
self.istriggertoupdate = False
self.thishastranslated = True

@threader
def ttsautoforward(self):
if not globalconfig["ttsautoforward"]:
Expand Down Expand Up @@ -978,8 +966,8 @@ def clickwordcallback(self, word, append=False):
word = word.get("origorig", word["orig"])

if globalconfig["usecopyword"]:
gobject.baseobject.clipboardhelper.setText.emit(
(QApplication.clipboard().text("plain")[0] + word) if append else word
winsharedutils.clipboard_set(
(winsharedutils.clipboard_get() + word) if append else word
)
if globalconfig["usesearchword"]:
self.searchwordW.search_word.emit(word, append)
Expand Down Expand Up @@ -1156,7 +1144,6 @@ def parsedefaultfont(self):
# ).family()

def loadui(self):
self.clipboardhelper = _clipboardhelper()
self.installeventfillter()
self.parsedefaultfont()
self.loadmetadatas()
Expand Down
4 changes: 2 additions & 2 deletions py/LunaTranslator/gui/dialog_savedgame_setting.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@
import functools, uuid
from datetime import datetime, timedelta
from traceback import print_exc
import gobject
from language import TransLanguages
import gobject, winsharedutils
from myutils.config import (
savehook_new_data,
uid2gamepath,
Expand Down Expand Up @@ -631,7 +631,7 @@ def safeaddtags(_):
try:
gobject.global_dialog_savedgame_new.tagswidget.addTag(*_)
except:
gobject.baseobject.clipboardhelper.setText.emit(_[0])
winsharedutils.clipboard_set(_[0])

qw.labelclicked.connect(safeaddtags)
if first:
Expand Down
5 changes: 2 additions & 3 deletions py/LunaTranslator/gui/dialog_savedgame_v3.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
extradatas,
globalconfig,
)
from myutils.hwnd import clipboard_set_image
from myutils.utils import (
get_time_stamp,
loopbackrecorder,
Expand Down Expand Up @@ -572,9 +573,7 @@ def menu(self, _1, _):
if action == deleteimage:
self.removecurrent(False)
elif copyimage == action:
gobject.baseobject.clipboardhelper.setImage.emit(
QImage(extradatas["localedpath"].get(curr, curr))
)
clipboard_set_image(extradatas["localedpath"].get(curr, curr))
elif action == deleteimage_x:
self.removecurrent(True)
elif action == pos:
Expand Down
4 changes: 2 additions & 2 deletions py/LunaTranslator/gui/selecthook.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import functools, binascii
from collections import OrderedDict
from traceback import print_exc
import qtawesome, windows, gobject
import qtawesome, windows, winsharedutils, gobject
from textsource.texthook import codepage_display, codepage_real
from myutils.config import savehook_new_data, static_data, globalconfig, _TR, isascii
from myutils.utils import checkchaos, get_time_stamp, dynamiclink, is_ascii_control
Expand Down Expand Up @@ -693,7 +693,7 @@ def showmenu(self, p: QPoint):
except:
pass
elif action == copy:
gobject.baseobject.clipboardhelper.setText.emit(hc)
winsharedutils.clipboard_set(hc)

def opensolvetext(self):
try:
Expand Down
10 changes: 3 additions & 7 deletions py/LunaTranslator/gui/setting_hotkey.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,9 +49,7 @@ def registrhotkeys(self):
"_1": gobject.baseobject.translation_ui.startTranslater,
"_2": gobject.baseobject.translation_ui.changeTranslateMode,
"_3": self.showsignal.emit,
"_4": lambda: gobject.baseobject.clipboardhelper.setText.emit(
gobject.baseobject.currenttext
),
"_4": lambda: winsharedutils.clipboard_set(gobject.baseobject.currenttext),
"_5": gobject.baseobject.translation_ui.changeshowhiderawsig.emit,
"_51": gobject.baseobject.translation_ui.changeshowhidetranssig.emit,
"_6": lambda: gobject.baseobject.transhis.showsignal.emit(),
Expand All @@ -75,15 +73,13 @@ def registrhotkeys(self):
"_25": lambda: windows.SendMessage(
windows.FindWindow("WNDCLS_Magpie_Core_CLI_Message", None),
windows.RegisterWindowMessage("Magpie_Core_CLI_Message_ToggleOverlay"),
None,
None,
),
"_26": gobject.baseobject.translation_ui.ocr_once_signal.emit,
"_26_1": lambda: gobject.baseobject.translation_ui.ocr_do_function(
gobject.baseobject.translation_ui.ocr_once_follow_rect
),
"_27": gobject.baseobject.translation_ui.simulate_key_enter,
"_28": lambda: gobject.baseobject.clipboardhelper.setText.emit(
"_28": lambda: winsharedutils.clipboard_set(
gobject.baseobject.currenttranslate
),
"_29": lambda: gobject.baseobject.searchwordW.ankiwindow.recordbtn1.click(),
Expand All @@ -95,7 +91,7 @@ def registrhotkeys(self):
QPoint()
),
"36": lambda: gobject.baseobject.textgetmethod(
QApplication.clipboard().text("plain")[0], False
winsharedutils.clipboard_get(), False
),
"37": lambda: gobject.baseobject.searchwordW.search_word.emit(
winsharedutils.GetSelectedText(), False
Expand Down
4 changes: 2 additions & 2 deletions py/LunaTranslator/gui/showword.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import json, time, functools, os, base64, uuid
from urllib.parse import quote
from traceback import print_exc
import qtawesome, requests, gobject, windows, hashlib
import qtawesome, requests, gobject, windows, winsharedutils
import myutils.ankiconnect as anki
from myutils.hwnd import grabwindow
from myutils.config import globalconfig, static_data, _TR
Expand Down Expand Up @@ -971,7 +971,7 @@ def showmenu(self, _):
if action == search:
self.model.onDoubleClicked(idx)
elif copy == action:
gobject.baseobject.clipboardhelper.setText.emit(item.text())
winsharedutils.clipboard_set(item.text())
elif action == label:
if not idx.data(isLabeleddWord):
item.setData(True, isLabeleddWord)
Expand Down
4 changes: 2 additions & 2 deletions py/LunaTranslator/gui/transhist.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from qtsymbols import *
import functools
import qtawesome, gobject, threading
import qtawesome, winsharedutils, threading
from myutils.config import globalconfig
from myutils.utils import get_time_stamp
from gui.usefulwidget import closeashidewindow
Expand Down Expand Up @@ -70,7 +70,7 @@ def showmenu(self, tb, p):
if action == qingkong:
tb.clear()
elif action == copy:
gobject.baseobject.clipboardhelper.setText.emit(self.textOutput.textCursor().selectedText())
winsharedutils.clipboard_set(self.textOutput.textCursor().selectedText())
elif action == baocun:
ff = QFileDialog.getSaveFileName(self, directory="save.txt")
if ff[0] == "":
Expand Down
4 changes: 2 additions & 2 deletions py/LunaTranslator/gui/translatorUI.py
Original file line number Diff line number Diff line change
Expand Up @@ -566,7 +566,7 @@ def simulate_key_ctrl():
("setting", lambda: gobject.baseobject.settin_ui.showsignal.emit()),
(
"copy",
lambda: gobject.baseobject.clipboardhelper.setText.emit(gobject.baseobject.currenttext),
lambda: winsharedutils.clipboard_set(gobject.baseobject.currenttext),
),
("edit", gobject.baseobject.createedittextui),
("edittrans", lambda: edittrans(gobject.baseobject.commonstylebase)),
Expand Down Expand Up @@ -700,7 +700,7 @@ def simulate_key_ctrl():
(
"copy_once",
lambda: gobject.baseobject.textgetmethod(
QApplication.clipboard().text("plain")[0], False
winsharedutils.clipboard_get(), False
),
),
(
Expand Down
14 changes: 5 additions & 9 deletions py/LunaTranslator/gui/usefulwidget.py
Original file line number Diff line number Diff line change
Expand Up @@ -318,13 +318,13 @@ def copytable(self) -> str:
csv_writer.writerow(row)
csv_str = output.getvalue()
output.close()
gobject.baseobject.clipboardhelper.setText.emit(csv_str)
winsharedutils.clipboard_set(csv_str)

def pastetable(self):
current = self.currentIndex()
if not current.isValid():
return
string = QApplication.clipboard().text("plain")[0]
string = winsharedutils.clipboard_get()
try:
csv_file = io.StringIO(string)
csv_reader = csv.reader(csv_file, delimiter="\t")
Expand Down Expand Up @@ -1443,7 +1443,7 @@ def __init__(self, parent=None) -> None:
t.timeout.connect(self.__getcurrent)
t.timeout.emit()
t.start()
self.add_menu(0, _TR("复制"), gobject.baseobject.clipboardhelper.setText.emit)
self.add_menu(0, _TR("复制"), winsharedutils.clipboard_set)
self.add_menu(0, None, lambda: 1)

def __getcurrent(self):
Expand All @@ -1456,9 +1456,7 @@ def __(_u):
winsharedutils.html_get_current_url(self.browser, cb)

if winsharedutils.html_check_ctrlc(self.browser):
cb = winsharedutils.html_get_select_text_cb(
gobject.baseobject.clipboardhelper.setText.emit
)
cb = winsharedutils.html_get_select_text_cb(winsharedutils.clipboard_set)
winsharedutils.html_get_select_text(self.browser, cb)

def navigate(self, url):
Expand Down Expand Up @@ -1960,9 +1958,7 @@ def showmenu(self, p: QPoint):
self.hcmodel.removeRow(curr.row())
self.internalrealname.pop(curr.row())
elif action == copy:
gobject.baseobject.clipboardhelper.setText.emit(
self.hcmodel.itemFromIndex(curr).text()
)
winsharedutils.clipboard_set(self.hcmodel.itemFromIndex(curr).text())

elif action == up:

Expand Down
Loading

0 comments on commit 646fcc2

Please sign in to comment.