Files
Reims-Go/internal/cli/handoff_windows.go

163 lines
4.7 KiB
Go

//go:build windows
package cli
import (
"encoding/json"
"errors"
"os"
"os/exec"
"runtime"
"syscall"
"time"
"unsafe"
"github.com/wailsapp/wails/v2/pkg/options"
"golang.org/x/sys/windows"
)
// Handing work to the desktop window speaks Wails v2's own single-instance
// protocol (internal/frontend/desktop/windows/single_instance.go, v2.17.1):
// the first instance owns a message-only window named
// "wails-app-<id>-sic" / "wails-app-<id>-siw" and reads a JSON
// options.SecondInstanceData from WM_COPYDATA with dwData 1542. Recheck
// these names when upgrading Wails.
const (
wmCopyData = 0x004A
wailsCopyDataID = 1542
smtoAbortIfHung = 0x0002
hwndMessage = ^uintptr(2) // HWND_MESSAGE, (HWND)-3
detachedProcess = 0x00000008
windowHandoffWorks = true
)
var (
user32 = syscall.NewLazyDLL("user32.dll")
procFindWindowExW = user32.NewProc("FindWindowExW")
procSendMessageW = user32.NewProc("SendMessageW")
procSendMessageTimeoutW = user32.NewProc("SendMessageTimeoutW")
procGetWindowPID = user32.NewProc("GetWindowThreadProcessId")
procAllowSetForeground = user32.NewProc("AllowSetForegroundWindow")
)
type copyDataStruct struct {
dwData uintptr
cbData uint32
lpData uintptr
}
// findWindow returns the running Reims-Go window's message window, or 0.
func findWindow() uintptr {
id := "wails-app-" + InstanceID
class, err := syscall.UTF16PtrFromString(id + "-sic")
if err != nil {
return 0
}
name, err := syscall.UTF16PtrFromString(id + "-siw")
if err != nil {
return 0
}
h, _, _ := procFindWindowExW.Call(hwndMessage, 0, uintptr(unsafe.Pointer(class)), uintptr(unsafe.Pointer(name)))
return h
}
// WindowForUpdate identifies the client with Wails' single-instance window.
// A missing window may mean the older client has just acquired its lock.
func WindowForUpdate() uint32 {
hwnd := findWindow()
if hwnd == 0 {
lockName := "wails-app-" + InstanceID + "sim"
h, err := windows.OpenMutex(windows.SYNCHRONIZE, false, windows.StringToUTF16Ptr(lockName))
if err == nil {
defer windows.CloseHandle(h)
for i := 0; i < 20 && hwnd == 0; i++ {
time.Sleep(25 * time.Millisecond)
hwnd = findWindow()
}
}
}
return windowPID(hwnd)
}
// DesktopWindowPID returns the current Wails single-instance owner, if any.
func DesktopWindowPID() uint32 { return windowPID(findWindow()) }
func windowPID(hwnd uintptr) uint32 {
var pid uint32
if hwnd != 0 {
procGetWindowPID.Call(hwnd, uintptr(unsafe.Pointer(&pid)))
}
return pid
}
// ForwardVMClose delegates both the request and the foreground permission
// inherited from the VM window that launched this helper.
func ForwardVMClose(name string) bool {
hwnd := findWindow()
if hwnd == 0 {
return false
}
if pid := windowPID(hwnd); pid != 0 {
procAllowSetForeground.Call(uintptr(pid))
}
return sendToWindow(hwnd, WindowArgs{CloseVM: name}.Args(), 500) == nil
}
// sendToWindow delivers args to the running window as if a second
// `reims-go.exe <args>` had been launched.
func sendToWindow(hwnd uintptr, args []string, timeoutMS uint32) error {
wd, _ := os.Getwd()
payload, err := json.Marshal(options.SecondInstanceData{Args: args, WorkingDirectory: wd})
if err != nil {
return err
}
buf, err := syscall.UTF16FromString(string(payload)) // NUL-terminated
if err != nil {
return err
}
cds := copyDataStruct{
dwData: wailsCopyDataID,
cbData: uint32(len(buf) * 2),
lpData: uintptr(unsafe.Pointer(&buf[0])),
}
if timeoutMS != 0 {
var result uintptr
sent, _, _ := procSendMessageTimeoutW.Call(hwnd, wmCopyData, 0,
uintptr(unsafe.Pointer(&cds)), smtoAbortIfHung, uintptr(timeoutMS), uintptr(unsafe.Pointer(&result)))
runtime.KeepAlive(buf)
if sent == 0 {
return errors.New("desktop window did not respond")
}
return nil
}
procSendMessageW.Call(hwnd, wmCopyData, 0, uintptr(unsafe.Pointer(&cds)))
runtime.KeepAlive(buf)
return nil
}
// spawnWindow launches this executable as the desktop window, detached from
// the caller's console and Ctrl+C, with no handles of the caller's: a pipe an
// agent reads from must close when this command exits, not when Reims-Go does.
func spawnWindow(args []string) error {
return spawnWindowWithDataRoot(args, "")
}
func spawnWindowWithDataRoot(args []string, dataRoot string) error {
exe, err := os.Executable()
if err != nil {
return err
}
if dataRoot != "" {
args = append(args, flagDataRoot+dataRoot)
}
cmd := exec.Command(exe, args...)
cmd.SysProcAttr = &syscall.SysProcAttr{CreationFlags: detachedProcess | syscall.CREATE_NEW_PROCESS_GROUP}
if err := cmd.Start(); err != nil {
return err
}
if cmd.Process == nil {
return errors.New("reims-go window did not start")
}
return cmd.Process.Release()
}