Files
magpie/internal/gui/installdir_windows.go
T
yetone 49c9491b73 update: the Windows app asks where to install, the first time
The Windows exe opened from Downloads (or the Desktop, or temp)
installed itself into %LOCALAPPDATA%\Programs\magpie without a word.
Now, the first time, with nothing installed yet, Windows' task dialog
asks "Install magpie in this folder?". It shows the folder and offers
Install, Change… and Cancel, in the tray's language (en, zh, zh-TW,
ja, de).

- Change… opens the system folder picker. A picked folder gets
  "magpie" added unless it is already named that (update.InstallDir).
- A folder other than the default is recorded at HKCU\Software\magpie
  InstallLocation. So the next exe downloaded replaces the copy there
  in place and asks nothing (installed(), forwards()).
- Cancel runs the exe where it is, as a portable copy, and nothing is
  recorded.
- Uninstall forgets the record (update.ForgetInstallDir, a new System
  step).
- The shortcut, App Paths, autostart, magpie://, the PATH entry and
  self-update already take the running exe's folder, so they follow
  the choice.

Program Files and other folders only an administrator can write to
are refused in the dialog (update.Installable test-writes and maps a
permission error to ErrNeedsAdmin). They are not elevated into.
magpie installs per user (HKCU Run, the user's PATH), and its
self-update replaces the exe without elevation (CanElevate is false on
Windows). So an admin folder would make every update fail, or would
need a UAC prompt on each one. A downloads folder is refused too.
Refusing is the simplest correct choice: it costs a user nothing they
had before, and keeps updates silent. Any folders the test-write made
are removed again.

Docs: gui-shell.md, "Where Windows installs magpie".

Run (mote, at this head on origin/main f9e6061b8):
- gofmt -l is clean.
- go build ./... and go vet of update, uninstall and gui.
- GOOS=windows go vet of gui, update and uninstall.
- GOOS=windows GOARCH=arm64 go build ./....
- GOOS=linux go vet -tags nogui of the same packages.
- go test -count=1 ./internal/update ./internal/uninstall, and
  -run TestInstallWords|TestTrayLang ./internal/gui: ok.

Run (win-run, xiaomi-gpu):
- internal/uninstall ok, and gui TestInstallWordsEveryLanguage ok.
- internal/update: one red, TestPackagedByDpkg. It is red on
  origin/main too: an NTFS stream from the fixture name
  magpie:amd64.list (#4603).

Real Windows 11 run (xiaomi-gpu, a sandbox USERPROFILE/LOCALAPPDATA
under C:\Users\yeton\magpie-idir, MAGPIE_ADDR on 3481, exe in its
Downloads, driven over UI Automation and TDM_CLICK_BUTTON):
- The dialog came up in Chinese, with the app icon and the default
  folder.
- Change… → C:\Program Files was refused with the administrator note
  and the warning icon, and no folder was left behind. C:\Windows was
  refused the same way.
- Change… → …\Tools gave …\Tools\magpie. Install put magpie.exe and
  magpie.com there, and the app ran from there.
- Afterwards InstallLocation, the user's PATH, App Paths and
  magpie:// all named …\Tools\magpie. `magpie version` from a fresh
  PATH resolved to …\Tools\magpie\magpie.com. `magpie autostart on`
  wrote Run = "…\Tools\magpie\magpie.exe" tray.
- Upgrade: a 0.1.9001 build downloaded into Downloads asked nothing.
  It replaced …\Tools\magpie\magpie.exe (FileVersion 0.1.9001) and ran
  from there.
- `magpie uninstall --yes` removed autostart, App Paths, the scheme
  and the record, and deleted the sandbox data. The next exe asked
  again.
- Cancel ran the exe from Downloads and recorded nothing.
- The registry and folders were put back as they were before the run,
  checked by a snapshot diff.

Broken by hand:
- recordedDir's lookup turned off: TestSettleInstallsWhereTheUserChose
  and TestSettleOffersTheChosenFolderAgain went red.
- AskFolder skipped: those two and TestSettleDeclinedRunsHere went red.

Not tried:
- The in-app self-update download. There is no newer release to
  download; the in-place replace path was run with a downloaded exe.
- The en, ja, de and zh-TW dialogs on screen. Their words are checked
  by TestInstallWordsEveryLanguage only.
- arm64 Windows.
- A Downloads folder moved by OneDrive.
- The Start-menu shortcut. The box's real App Paths already held
  another session's magpie, so shortcut.ensure took the shortcut as
  removed by the user. This is existing behaviour.

Not changed: uninstall still leaves the PATH entry and the exe, as
before for every install (#5500). Related to #2663, which asks for a
first-run choice of where magpie lives.

Reported-by: feng_21795_78266 (Discord)
2026-11-06 17:34:48 +08:00

241 lines
7.2 KiB
Go

//go:build windows && !nogui
package gui
import (
"encoding/binary"
"errors"
"log"
"path/filepath"
"runtime"
"syscall"
"unsafe"
ole "github.com/go-ole/go-ole"
"golang.org/x/sys/windows"
"github.com/yetone/magpie/internal/settings"
"github.com/yetone/magpie/internal/update"
)
// askInstallFolder has update.Settle ask where to install, in the
// reader's language.
func askInstallFolder() {
update.AskFolder = func(suggest string, check func(string) error) string {
w := installWordsFor(trayLang(settings.Load().Lang, systemLang))
var out string
done := make(chan struct{})
// COM and the dialogs on a thread of their own, which ends with
// the goroutine: Wails sets up the main thread later
go func() {
runtime.LockOSThread()
defer close(done)
out = installDialog(w, suggest, check)
}()
<-done
return out
}
}
const (
idInstall = 100
idChange = 101
)
// installDialog asks until the user installs in a folder check accepts,
// or cancels (""). With no dialog to be had, dir is taken, as before
// there was a choice.
func installDialog(w installWords, dir string, check func(string) error) string {
note := ""
for {
btn, err := taskDialog(w, dir, note)
if err != nil {
log.Println("install: the folder dialog:", err)
return dir
}
switch btn {
case idInstall:
if err := check(dir); err != nil {
note = w.refusal(dir, err)
continue
}
return dir
case idChange:
picked, err := pickInstallFolder(w.pick, dir)
if err != nil {
log.Println("install: the folder picker:", err)
}
if picked == "" {
continue
}
dir, note = update.InstallDir(picked), ""
if err := check(dir); err != nil {
note = w.refusal(dir, err)
}
default:
return ""
}
}
}
var (
comctl32 = windows.NewLazySystemDLL("comctl32.dll")
procTaskDialogIndi = comctl32.NewProc("TaskDialogIndirect")
procSHCreateItem = windows.NewLazySystemDLL("shell32.dll").NewProc("SHCreateItemFromParsingName")
)
// taskDialog shows Windows' task dialog (comctl32 6, which the exe's
// manifest asks for): the folder under the question, Install, Change…
// and Cancel, and note, a refusal, with a warning icon above. It answers
// the button pressed.
func taskDialog(w installWords, dir, note string) (int, error) {
if err := procTaskDialogIndi.Find(); err != nil {
return 0, err
}
keep := [][]uint16{}
str := func(s string) uintptr {
u, _ := windows.UTF16FromString(s)
keep = append(keep, u)
return uintptr(unsafe.Pointer(&u[0]))
}
// TASKDIALOG_BUTTON and TASKDIALOGCONFIG are packed to 1 byte
// (commctrl.h's pshpack1), so they are laid out by hand
buttons := make([]byte, 2*12)
for i, b := range []struct {
id int32
label string
}{{idInstall, w.install}, {idChange, w.change}} {
binary.LittleEndian.PutUint32(buttons[i*12:], uint32(b.id))
binary.LittleEndian.PutUint64(buttons[i*12+4:], uint64(str(b.label)))
}
// the folder, or what is wrong with it, which names it
content := dir
if note != "" {
content = note
}
const (
tdfAllowCancel = 0x0008
tdfSizeToFit = 0x01000000 // TDF_SIZE_TO_CONTENT: a long folder isn't cut short
tdcbfCancel = 0x0008
tdWarningIcon = 0xFFFF // MAKEINTRESOURCEW(-1)
appIcon = 3 // the exe's icon group (build/windows/winres.json)
cfgSize = 160
)
var mod windows.Handle
_ = windows.GetModuleHandleEx(0, nil, &mod)
show := func(icon uintptr) (int, uintptr) {
cfg := make([]byte, cfgSize)
le := binary.LittleEndian
le.PutUint32(cfg[0:], cfgSize)
le.PutUint64(cfg[12:], uint64(mod))
le.PutUint32(cfg[20:], tdfAllowCancel|tdfSizeToFit)
le.PutUint32(cfg[24:], tdcbfCancel)
le.PutUint64(cfg[28:], uint64(str(w.title)))
le.PutUint64(cfg[36:], uint64(icon))
le.PutUint64(cfg[44:], uint64(str(w.ask)))
le.PutUint64(cfg[52:], uint64(str(content)))
le.PutUint32(cfg[60:], 2)
le.PutUint64(cfg[64:], uint64(uintptr(unsafe.Pointer(&buttons[0]))))
le.PutUint32(cfg[72:], idInstall)
var pressed int32
hr, _, _ := procTaskDialogIndi.Call(uintptr(unsafe.Pointer(&cfg[0])), uintptr(unsafe.Pointer(&pressed)), 0, 0)
runtime.KeepAlive(cfg)
return int(pressed), hr
}
icon := uintptr(appIcon)
if note != "" {
icon = tdWarningIcon
}
pressed, hr := show(icon)
if hr != 0 && icon == appIcon {
// a build without the icon in its resources
pressed, hr = show(0)
}
runtime.KeepAlive(keep)
runtime.KeepAlive(buttons)
if hr != 0 {
return 0, syscall.Errno(hr)
}
return pressed, nil
}
// pickInstallFolder is Windows' folder picker (IFileOpenDialog with
// FOS_PICKFOLDERS), opened where dir is, or the nearest folder above it
// there is: the folder picked, "" when none was.
func pickInstallFolder(title, dir string) (string, error) {
if err := ole.CoInitializeEx(0, ole.COINIT_APARTMENTTHREADED|0x4 /* COINIT_DISABLE_OLE1DDE */); err != nil {
var oe *ole.OleError
// S_FALSE: COM was set up on this thread already
if !errors.As(err, &oe) || oe.Code() != 1 {
return "", err
}
}
defer ole.CoUninitialize()
d, err := ole.CreateInstance(ole.NewGUID("{DC1C5A9C-E88A-4dde-A5A1-60F82A20AEF7}"), ole.NewGUID("{d57c7288-d4ad-4768-be02-9d969532d960}"))
if err != nil {
return "", err
}
defer d.Release()
// IFileOpenDialog's vtable: IUnknown (0-2), Show (3), then IFileDialog
const (
show = 3
setOptions = 9
getOptions = 10
setFolder = 12
setTitle = 17
getResult = 20
pickFolders = 0x20
forceFS = 0x40
pathMust = 0x800
cancelled = 0x800704C7 // HRESULT_FROM_WIN32(ERROR_CANCELLED)
)
call := func(obj unsafe.Pointer, i int, args ...uintptr) uintptr {
vt := *(*unsafe.Pointer)(obj)
fn := *(*uintptr)(unsafe.Add(vt, i*int(unsafe.Sizeof(uintptr(0)))))
hr, _, _ := syscall.SyscallN(fn, append([]uintptr{uintptr(obj)}, args...)...)
return hr
}
obj := unsafe.Pointer(d)
var opts uint32
if hr := call(obj, getOptions, uintptr(unsafe.Pointer(&opts))); hr != 0 {
return "", syscall.Errno(hr)
}
if hr := call(obj, setOptions, uintptr(opts|pickFolders|forceFS|pathMust)); hr != 0 {
return "", syscall.Errno(hr)
}
if t, err := windows.UTF16PtrFromString(title); err == nil {
call(obj, setTitle, uintptr(unsafe.Pointer(t)))
}
start := filepath.Dir(filepath.Clean(dir))
for !isDir(start) && filepath.Dir(start) != start {
start = filepath.Dir(start)
}
if p, err := windows.UTF16PtrFromString(start); err == nil && isDir(start) {
iidShellItem := ole.NewGUID("{43826d1e-e718-42ee-bc55-a1e261c37bfe}")
var item unsafe.Pointer
if hr, _, _ := procSHCreateItem.Call(uintptr(unsafe.Pointer(p)), 0, uintptr(unsafe.Pointer(iidShellItem)), uintptr(unsafe.Pointer(&item))); hr == 0 && item != nil {
call(obj, setFolder, uintptr(item))
call(item, 2) // Release
}
}
switch hr := call(obj, show, 0); hr {
case 0:
case cancelled:
return "", nil
default:
return "", syscall.Errno(hr)
}
var res unsafe.Pointer
if hr := call(obj, getResult, uintptr(unsafe.Pointer(&res))); hr != 0 || res == nil {
return "", syscall.Errno(hr)
}
defer call(res, 2) // Release
const getDisplayName, sigdnFileSysPath = 5, 0x80058000
var name *uint16
if hr := call(res, getDisplayName, sigdnFileSysPath, uintptr(unsafe.Pointer(&name))); hr != 0 || name == nil {
return "", syscall.Errno(hr)
}
defer windows.CoTaskMemFree(unsafe.Pointer(name))
return windows.UTF16PtrToString(name), nil
}