diff --git a/docs/subsystems/gui-shell.md b/docs/subsystems/gui-shell.md index f5123a37c..572038761 100644 --- a/docs/subsystems/gui-shell.md +++ b/docs/subsystems/gui-shell.md @@ -933,6 +933,32 @@ and the old one quitting only after its stream) and socket passing in [`handoff_test.go`](../../internal/handoff/handoff_test.go), and `update-wait.test.cjs`. +### Where Windows installs magpie + +There is no installer: the Windows exe opened from Downloads, the Desktop +or a temp folder installs itself (`update.Settle`, called from `gui.Run`). +The first time, with nothing installed, it asks where in Windows' task +dialog (`installDialog` in +[`installdir_windows.go`](../../internal/gui/installdir_windows.go)): the +folder, Install, Change… and Cancel, in the tray's language. Change… opens +the folder picker, and a folder picked gets `magpie` added unless it is +named that already (`update.InstallDir`). The default is +`%LOCALAPPDATA%\Programs\magpie`; another folder is recorded at +`HKCU\Software\magpie` `InstallLocation`, so the next exe downloaded +replaces the copy there without asking (feng_21795_78266 on Discord). +A folder only an administrator can write to (Program Files, Windows) or +one downloads land in is refused in the dialog (`update.Installable`), not +elevated: magpie is installed for the user alone (HKCU's Run, the user's +PATH) and updates itself without elevation, so an admin folder would +stop its updates. Cancel runs the exe where it is. The shortcut, App +Paths, autostart, the `magpie://` scheme, PATH and self-update all take +the running exe's folder, so they follow the choice. Uninstall forgets +the record (`update.ForgetInstallDir`) and leaves the program where it +is, as before. See `TestSettleInstallsWhereTheUserChose`, +`TestSettleOffersTheChosenFolderAgain`, `TestInstallableRefuses` in +[`install_test.go`](../../internal/update/install_test.go) and +`TestInstallWordsEveryLanguage`. + ## Verification The session readers include Cursor CLI chat stores, Cursor editor project diff --git a/internal/gui/app.go b/internal/gui/app.go index dbb12d377..530d4bc9a 100644 --- a/internal/gui/app.go +++ b/internal/gui/app.go @@ -331,7 +331,9 @@ func Run(version string, showMain bool, link string) error { } // Windows: the app opened from Downloads (or the Desktop, or a zip) // opens the copy installed in the user's programs folder, putting - // itself there first, and Open at login opens that one from now on + // itself there first, and Open at login opens that one from now on. + // The first time, it asks where (installdir_windows.go). + askInstallFolder() if from, to := update.Settle(); to != "" { err := update.Forward(from, to) if err == nil { diff --git a/internal/gui/installdir.go b/internal/gui/installdir.go new file mode 100644 index 000000000..1656b6d4f --- /dev/null +++ b/internal/gui/installdir.go @@ -0,0 +1,82 @@ +//go:build !nogui + +package gui + +import ( + "errors" + "fmt" + + "github.com/yetone/magpie/internal/update" +) + +// The Windows app opened from Downloads installs itself (update.Settle), +// and the first time it asks where, in a dialog of Windows' own +// (installdir_windows.go): the folder, Install, Change… and Cancel, as an +// installer's folder page has them (feng_21795_78266 on Discord). + +// installWords are the dialog's words in one language: its title, the +// question, the two buttons, the folder picker's title, and what is said +// when the folder can't be used: one only an administrator can write +// to, one downloads land in, and any other failure. +type installWords struct { + title, ask, install, change, pick string + admin, downloads, failed string +} + +var installText = map[string]installWords{ + "en": { + title: "magpie", ask: "Install magpie in this folder?", install: "Install", change: "Change…", + pick: "Choose where to install magpie", + admin: "Only an administrator can write to %s. magpie is installed for you alone and updates itself, so choose a folder of your own.", + downloads: "Downloads land in %s. Choose another folder.", + failed: "magpie can't be installed in %s: %v", + }, + "zh": { + title: "magpie", ask: "把 magpie 安装到这个文件夹?", install: "安装", change: "更改…", + pick: "选择 magpie 的安装位置", + admin: "只有管理员才能写入 %s。magpie 只为你安装,并会自己更新,请选择一个你自己的文件夹。", + downloads: "%s 是下载存放的地方,请选择另一个文件夹。", + failed: "magpie 无法安装到 %s:%v", + }, + "zh-TW": { + title: "magpie", ask: "把 magpie 安裝到這個資料夾?", install: "安裝", change: "變更…", + pick: "選擇 magpie 的安裝位置", + admin: "只有系統管理員才能寫入 %s。magpie 只為你安裝,並會自己更新,請選擇一個你自己的資料夾。", + downloads: "%s 是下載存放的地方,請選擇另一個資料夾。", + failed: "magpie 無法安裝到 %s:%v", + }, + "ja": { + title: "magpie", ask: "このフォルダーに magpie をインストールしますか?", install: "インストール", change: "変更…", + pick: "magpie のインストール先を選択", + admin: "%s に書き込めるのは管理者だけです。magpie はあなた専用にインストールされ、自分で更新するので、あなた自身のフォルダーを選んでください。", + downloads: "%s はダウンロードの保存先です。別のフォルダーを選んでください。", + failed: "%s に magpie をインストールできません:%v", + }, + "de": { + title: "magpie", ask: "magpie in diesem Ordner installieren?", install: "Installieren", change: "Ändern…", + pick: "Speicherort für magpie wählen", + admin: "Nur ein Administrator darf in %s schreiben. magpie wird nur für Sie installiert und aktualisiert sich selbst, wählen Sie also einen eigenen Ordner.", + downloads: "In %s landen Downloads. Wählen Sie einen anderen Ordner.", + failed: "magpie kann nicht in %s installiert werden: %v", + }, +} + +// installWordsFor is the dialog's words in lang (trayLang's), English +// where it has none. +func installWordsFor(lang string) installWords { + if w, ok := installText[lang]; ok { + return w + } + return installText["en"] +} + +// refusal is what the dialog says about dir, which check refused with err. +func (w installWords) refusal(dir string, err error) string { + switch { + case errors.Is(err, update.ErrNeedsAdmin): + return fmt.Sprintf(w.admin, dir) + case errors.Is(err, update.ErrDownloadFolder): + return fmt.Sprintf(w.downloads, dir) + } + return fmt.Sprintf(w.failed, dir, err) +} diff --git a/internal/gui/installdir_other.go b/internal/gui/installdir_other.go new file mode 100644 index 000000000..7dddc53ab --- /dev/null +++ b/internal/gui/installdir_other.go @@ -0,0 +1,6 @@ +//go:build !windows && !nogui + +package gui + +// askInstallFolder: only Windows installs a download itself. +func askInstallFolder() {} diff --git a/internal/gui/installdir_test.go b/internal/gui/installdir_test.go new file mode 100644 index 000000000..635cf7cba --- /dev/null +++ b/internal/gui/installdir_test.go @@ -0,0 +1,49 @@ +//go:build !nogui + +package gui + +import ( + "errors" + "strings" + "testing" + + "github.com/yetone/magpie/internal/update" +) + +// TestInstallWordsEveryLanguage: each language the dialog speaks has every +// word, with the folder (and the error) where the English has them. +func TestInstallWordsEveryLanguage(t *testing.T) { + for _, lang := range []string{"en", "zh", "zh-TW", "ja", "de"} { + w, ok := installText[lang] + if !ok { + t.Fatalf("%s: no words", lang) + } + for name, s := range map[string]string{"title": w.title, "ask": w.ask, "install": w.install, "change": w.change, "pick": w.pick} { + if s == "" || strings.Contains(s, "%") { + t.Errorf("%s %s = %q", lang, name, s) + } + } + dir := `D:\Apps\magpie` + for _, c := range []struct { + err error + want []string + }{ + {update.ErrNeedsAdmin, []string{dir}}, + {update.ErrDownloadFolder, []string{dir}}, + {errors.New("disk full"), []string{dir, "disk full"}}, + } { + got := w.refusal(dir, c.err) + if strings.Contains(got, "%!") { + t.Errorf("%s %v: %q", lang, c.err, got) + } + for _, s := range c.want { + if !strings.Contains(got, s) { + t.Errorf("%s %v: %q lacks %q", lang, c.err, got, s) + } + } + } + } + if installWordsFor("fr") != installText["en"] { + t.Error("a language without words isn't English") + } +} diff --git a/internal/gui/installdir_windows.go b/internal/gui/installdir_windows.go new file mode 100644 index 000000000..cc49f51c8 --- /dev/null +++ b/internal/gui/installdir_windows.go @@ -0,0 +1,240 @@ +//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 +} diff --git a/internal/uninstall/uninstall.go b/internal/uninstall/uninstall.go index ce218c507..2b941a868 100644 --- a/internal/uninstall/uninstall.go +++ b/internal/uninstall/uninstall.go @@ -89,6 +89,7 @@ var ( removeShortcut = shortcut.Remove removeScheme = unregisterScheme endPII = pii.Remove + forgetInstall = update.ForgetInstallDir executable = os.Executable wired = (*agent.Agent).Wired disconnectOne = disconnect @@ -178,6 +179,9 @@ func System(r *Report) { {"Start menu shortcut", func() error { return removeShortcut(exe) }}, {"magpie:// links", func() error { return removeScheme(exe) }}, {"privacy model's helper", endPII}, + // Windows: the folder chosen to install in, so a download opened + // after this asks again + {"install folder record", forgetInstall}, } { d := Done{What: s.what} if err := s.do(); err != nil { diff --git a/internal/uninstall/uninstall_test.go b/internal/uninstall/uninstall_test.go index b12ea2e55..717b499c2 100644 --- a/internal/uninstall/uninstall_test.go +++ b/internal/uninstall/uninstall_test.go @@ -25,7 +25,9 @@ func fakes(t *testing.T, list []*agent.Agent, isWired map[string]bool, failing m wasAgents, wasWired, wasDisconnect := agents, wired, disconnectOne wasFailover, wasLeftovers, wasPort, wasRestart := endFailover, endLeftovers, portRollouts, restartCodexApp wasService, wasAutostart, wasShortcut, wasScheme, wasPII, wasExe := removeService, autostartOff, removeShortcut, removeScheme, endPII, executable + wasForget := forgetInstall t.Cleanup(func() { + forgetInstall = wasForget agents, wired, disconnectOne = wasAgents, wasWired, wasDisconnect endFailover, endLeftovers, portRollouts, restartCodexApp = wasFailover, wasLeftovers, wasPort, wasRestart removeService, autostartOff, removeShortcut, removeScheme, endPII, executable = wasService, wasAutostart, wasShortcut, wasScheme, wasPII, wasExe @@ -55,6 +57,7 @@ func fakes(t *testing.T, list []*agent.Agent, isWired map[string]bool, failing m removeShortcut = func(string) error { did = append(did, "shortcut"); return nil } removeScheme = func(string) error { did = append(did, "scheme"); return nil } endPII = step("pii") + forgetInstall = step("install folder") executable = func() (string, error) { return "/opt/magpie/magpie", nil } return &did } @@ -90,7 +93,7 @@ func TestRunOrder(t *testing.T) { r := Run(context.Background()) - want := []string{"service", "autostart", "shortcut", "scheme", "pii", "failover", "disconnect codex", "disconnect claude", "leftovers", "rollouts", "codex app"} + want := []string{"service", "autostart", "shortcut", "scheme", "pii", "install folder", "failover", "disconnect codex", "disconnect claude", "leftovers", "rollouts", "codex app"} if !slices.Equal(*did, want) { t.Fatalf("did %q, want %q", *did, want) } @@ -118,7 +121,7 @@ func TestKeepData(t *testing.T) { r := KeepData(context.Background()) - want := []string{"service", "autostart", "shortcut", "scheme", "pii", "failover", "disconnect codex", "leftovers", "rollouts", "codex app"} + want := []string{"service", "autostart", "shortcut", "scheme", "pii", "install folder", "failover", "disconnect codex", "leftovers", "rollouts", "codex app"} if !slices.Equal(*did, want) { t.Fatalf("did %q, want %q", *did, want) } diff --git a/internal/update/install.go b/internal/update/install.go index 1f900d400..9f8272353 100644 --- a/internal/update/install.go +++ b/internal/update/install.go @@ -1,8 +1,10 @@ package update import ( + "errors" "fmt" "io" + "io/fs" "log" "os" "path/filepath" @@ -26,6 +28,16 @@ import ( // file. Opened again, it opens the installed copy, or puts itself there // first when it is the newer version. // +// The first time, before anything is copied, the user is asked where to +// put it (AskFolder, Windows' own dialog in the GUI), with that folder as +// the default (feng_21795_78266 on Discord). A folder other than the +// default is kept in HKCU\Software\magpie (InstallLocation), so a +// download opened later finds it there, never asks again and never moves +// it. A folder the user can't write to is refused with the reason: +// magpie installs for the one user, updates itself without an +// administrator, and its login item and PATH are the user's own, so a +// copy in Program Files would need an administrator for every update. +// // It is left alone, and runs where it is as before, when it runs from // anywhere else (a folder the user chose: D:\Tools, a USB drive), when it // is portable (a data folder or .portable file beside it, appdir), or @@ -58,8 +70,104 @@ var ( // installCLI puts the installed folder on the user's PATH with the // command a terminal runs there installCLI = cliPlace + // recordedDir is the folder the user chose to install in, "" when + // none was (the default, or a magpie installed before it could be + // chosen); recordDir keeps it + recordedDir = readInstallDir + recordDir = writeInstallDir ) +// AskFolder, when set, asks the user where to install the download, +// offering suggest, a folder: it answers the folder chosen, which check +// has accepted, or "" when the user would rather not install (the +// download then runs where it is). Unset, the suggestion is taken. +var AskFolder func(suggest string, check func(dir string) error) string + +// ErrNeedsAdmin is a folder chosen to install in that only an +// administrator can write to. +var ErrNeedsAdmin = errors.New("only an administrator can write to this folder") + +// ErrDownloadFolder is a folder chosen to install in that downloads land +// in: the copy there would be taken for a download again. +var ErrDownloadFolder = errors.New("downloads land in this folder") + +// InstallDir is the folder a folder picked in AskFolder's dialog means: +// itself when it is named magpie, else a magpie folder inside it, as +// installers do. +func InstallDir(picked string) string { + picked = filepath.Clean(picked) + if strings.EqualFold(filepath.Base(picked), "magpie") { + return picked + } + return filepath.Join(picked, "magpie") +} + +// Installable says why dir can't be installed in, nil when it can: a +// file is written into it and removed, and the folders made for that are +// removed again, so a folder looked at and then not chosen isn't left. +func Installable(dir string) error { + if !filepath.IsAbs(dir) { + return fmt.Errorf("%s is not a full path", dir) + } + if downloadFolder(dir) { + return ErrDownloadFolder + } + top := "" + for d := filepath.Clean(dir); !exists(d); d = filepath.Dir(d) { + top = d + if filepath.Dir(d) == d { + break + } + } + if top != "" { + defer os.RemoveAll(top) + } + if err := os.MkdirAll(dir, 0o755); err != nil { + return writeErr(err) + } + f, err := os.CreateTemp(dir, ".magpie-install-*") + if err != nil { + return writeErr(err) + } + f.Close() + os.Remove(f.Name()) + return nil +} + +func writeErr(err error) error { + if errors.Is(err, fs.ErrPermission) { + return ErrNeedsAdmin + } + return err +} + +// exeName is what the installed copy is called. +const exeName = "magpie.exe" + +// installed is where magpie is installed: the folder the user chose, else +// the default; ok is false when neither holds it, and to is then where +// to offer, the folder chosen before first. +func installed() (to string, ok bool) { + def := installTarget() + if def == "" { + return "", false + } + var chosen string + if d := recordedDir(); d != "" && filepath.IsAbs(d) { + chosen = filepath.Join(d, exeName) + if exists(chosen) { + return chosen, true + } + } + if exists(def) { + return def, true + } + if chosen != "" { + return chosen, false + } + return def, false +} + // Settle installs the desktop app run from a download folder (see // above), and says what to open instead of running on here: from is this // exe and to the installed one, both "" when this one runs on. Anything @@ -86,15 +194,33 @@ func Settle() (from, to string) { // settle is Settle for exe: the installed exe to open instead, "" to run // exe where it is. func settle(exe string) (string, error) { - to := installTarget() + to, ok := installed() if to == "" || samePath(exe, to) || !downloadFolder(filepath.Dir(exe)) || portableData() != "" { return "", nil } - if !exists(to) { - if err := installFresh(exe, to); err != nil { - return "", err + if !ok { + dir := filepath.Dir(to) + if AskFolder != nil { + if dir = AskFolder(dir, Installable); dir == "" { + return "", nil + } + } + to = filepath.Join(dir, exeName) + if samePath(exe, to) { + return "", nil + } + // the default needs no record, unless one names another folder + if !samePath(to, installTarget()) || recordedDir() != "" { + if err := recordDir(dir); err != nil { + log.Println("install: keeping the folder chosen:", err) + } + } + if !exists(to) { + if err := installFresh(exe, to); err != nil { + return "", err + } + return to, nil } - return to, nil } if sameFile(exe, to) || sameBytes(exe, to) { return to, nil @@ -248,8 +374,8 @@ func forwards(exe string) bool { if runtime.GOOS != "windows" || os.Getenv(NoInstallEnv) == "1" { return false } - to := installTarget() - return to != "" && !samePath(exe, to) && downloadFolder(filepath.Dir(exe)) && portableData() == "" && exists(to) + to, ok := installed() + return ok && !samePath(exe, to) && downloadFolder(filepath.Dir(exe)) && portableData() == "" } // samePath says whether two paths name the same file, Windows' way: in diff --git a/internal/update/install_other.go b/internal/update/install_other.go index fb7f9509d..dfd7374d2 100644 --- a/internal/update/install_other.go +++ b/internal/update/install_other.go @@ -7,6 +7,11 @@ func installPath() string { return "" } func isDownloadFolder(string) bool { return false } func exeVersion(string) uint64 { return 0 } func webViewDefault(string) string { return "" } +func readInstallDir() string { return "" } +func writeInstallDir(string) error { return nil } + +// ForgetInstallDir does nothing: only Windows records where it installed. +func ForgetInstallDir() error { return nil } // hide does nothing: a name starting with a dot is hidden already. func hide(string) {} diff --git a/internal/update/install_test.go b/internal/update/install_test.go index 43fe8099b..51b5c10d2 100644 --- a/internal/update/install_test.go +++ b/internal/update/install_test.go @@ -17,6 +17,8 @@ type installFixture struct { versions map[string]uint64 placed []string // folders installCLI was asked to put on PATH portable string + record string // the folder chosen, as HKCU\Software\magpie keeps it + asked []string // what AskFolder was offered } func newInstallFixture(t *testing.T) *installFixture { @@ -36,7 +38,9 @@ func newInstallFixture(t *testing.T) *installFixture { t.Fatal(err) } saved := []any{installTarget, downloadFolder, fileVersion, portableData, webViewHome, installCLI} + wasRead, wasWrite, wasAsk := recordedDir, recordDir, AskFolder t.Cleanup(func() { + recordedDir, recordDir, AskFolder = wasRead, wasWrite, wasAsk installTarget = saved[0].(func() string) downloadFolder = saved[1].(func(string) bool) fileVersion = saved[2].(func(string) uint64) @@ -60,9 +64,28 @@ func newInstallFixture(t *testing.T) *installFixture { f.placed = append(f.placed, dir) return nil } + recordedDir = func() string { return f.record } + recordDir = func(dir string) error { f.record = dir; return nil } + AskFolder = nil return f } +// ask has AskFolder answer dir, after the check it is given accepts it, +// and note what it was offered. +func (f *installFixture) ask(t *testing.T, dir string) { + t.Helper() + AskFolder = func(suggest string, check func(string) error) string { + f.asked = append(f.asked, suggest) + if dir == "" { + return "" + } + if err := check(dir); err != nil { + t.Fatalf("check refused %s: %v", dir, err) + } + return dir + } +} + func (f *installFixture) installed(t *testing.T, b string, version uint64) { t.Helper() if err := os.MkdirAll(filepath.Dir(f.to), 0o755); err != nil { @@ -387,3 +410,165 @@ func TestInFolder(t *testing.T) { t.Error("a folder that isn't absolute holds things") } } + +// The first time, the user is asked where to install, offered the +// default; the folder they choose is where magpie goes, what goes on +// PATH, and what is kept for the next download (feng_21795_78266 on +// Discord). +func TestSettleInstallsWhereTheUserChose(t *testing.T) { + f := newInstallFixture(t) + mine := filepath.Join(filepath.Dir(f.downloads), "D", "Apps", "magpie") + f.ask(t, mine) + to, err := settle(f.exe) + if err != nil { + t.Fatal(err) + } + want := filepath.Join(mine, "magpie.exe") + if to != want { + t.Fatalf("settle opens %q, want %q", to, want) + } + if len(f.asked) != 1 || !samePath(f.asked[0], filepath.Dir(f.to)) { + t.Fatalf("offered %q, want the default %q once", f.asked, filepath.Dir(f.to)) + } + if got := readString(t, want); got != "MZ new download" { + t.Fatalf("installed copy holds %q", got) + } + if exists(f.to) { + t.Fatal("installed in the default folder too") + } + if len(f.placed) != 1 || !samePath(f.placed[0], mine) { + t.Fatalf("PATH given %v, want %s", f.placed, mine) + } + if !samePath(f.record, mine) { + t.Fatalf("kept %q, want %q", f.record, mine) + } + if forwards(f.exe) != (runtime.GOOS == "windows") { + t.Fatal("the download isn't taken as opening the chosen copy") + } + + // opened again, and again as a newer version: never asked, never + // moved, and the newer one goes in the chosen folder + f.versions[want] = 1 << 32 + f.versions[f.exe] = 2 << 32 + for i := 0; i < 2; i++ { + to, err = settle(f.exe) + if err != nil || to != want { + t.Fatalf("again: settle = %q, %v; want %q", to, err, want) + } + } + if len(f.asked) != 1 { + t.Fatalf("asked again: %q", f.asked) + } + if exists(f.to) { + t.Fatal("moved to the default folder") + } + if len(f.placed) != 1 { + t.Fatalf("PATH written again: %v", f.placed) + } +} + +// Declining the dialog installs nothing: the download runs where it is. +func TestSettleDeclinedRunsHere(t *testing.T) { + f := newInstallFixture(t) + f.ask(t, "") + if to, err := settle(f.exe); to != "" || err != nil { + t.Fatalf("settle = %q, %v after declining", to, err) + } + if exists(f.to) || f.record != "" || len(f.placed) != 0 { + t.Fatalf("installed after declining: %v %q %v", exists(f.to), f.record, f.placed) + } +} + +// A magpie in the default folder from before there was a choice is +// installed: it is opened with no question and no record. +func TestSettleDefaultInstallAsksNothing(t *testing.T) { + f := newInstallFixture(t) + f.installed(t, "MZ installed", 0) + f.ask(t, filepath.Join(t.TempDir(), "magpie")) + to, err := settle(f.exe) + if err != nil || to != f.to { + t.Fatalf("settle = %q, %v; want %q", to, err, f.to) + } + if len(f.asked) != 0 || f.record != "" { + t.Fatalf("asked %q, kept %q", f.asked, f.record) + } +} + +// A chosen folder since emptied is offered again, not the default. +func TestSettleOffersTheChosenFolderAgain(t *testing.T) { + f := newInstallFixture(t) + gone := filepath.Join(t.TempDir(), "magpie") + f.record = gone + f.ask(t, filepath.Dir(f.to)) + to, err := settle(f.exe) + if err != nil || to != f.to { + t.Fatalf("settle = %q, %v; want %q", to, err, f.to) + } + if len(f.asked) != 1 || !samePath(f.asked[0], gone) { + t.Fatalf("offered %q, want %q", f.asked, gone) + } + if !samePath(f.record, filepath.Dir(f.to)) { + t.Fatalf("kept %q after the default was chosen", f.record) + } +} + +// A folder picked is used as it is when named magpie, else a magpie +// folder goes inside it. +func TestInstallDir(t *testing.T) { + root := t.TempDir() + for _, c := range []struct{ picked, want string }{ + {filepath.Join(root, "Apps"), filepath.Join(root, "Apps", "magpie")}, + {filepath.Join(root, "Apps", "magpie"), filepath.Join(root, "Apps", "magpie")}, + {filepath.Join(root, "Apps", "Magpie") + string(filepath.Separator), filepath.Join(root, "Apps", "Magpie")}, + } { + if got := InstallDir(c.picked); got != c.want { + t.Errorf("InstallDir(%q) = %q, want %q", c.picked, got, c.want) + } + } +} + +// A download folder, or one the user can't write to (Program Files +// without an administrator), is refused with the reason; the folder it +// had to make for the check isn't left behind. +func TestInstallableRefuses(t *testing.T) { + f := newInstallFixture(t) + if err := Installable(f.downloads); err != ErrDownloadFolder { + t.Fatalf("Downloads: %v", err) + } + if err := Installable("magpie"); err == nil { + t.Fatal("a relative folder accepted") + } + tmp := t.TempDir() + if err := Installable(filepath.Join(tmp, "new", "magpie")); err != nil { + t.Fatalf("a folder of the user's own: %v", err) + } + if exists(filepath.Join(tmp, "new")) { + t.Fatal("the folders made for the check were left") + } + if err := Installable(tmp); err != nil { + t.Fatalf("a folder there already: %v", err) + } + if left, _ := os.ReadDir(tmp); !exists(tmp) || len(left) != 0 { + t.Fatalf("check left %v", left) + } + if runtime.GOOS == "windows" { + return // a folder's mode doesn't stop a write there; tried for real on Windows + } + ro := filepath.Join(t.TempDir(), "ro") + if err := os.MkdirAll(ro, 0o555); err != nil { + t.Fatal(err) + } + if err := os.Chmod(ro, 0o555); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { os.Chmod(ro, 0o755) }) + if os.Getuid() == 0 { + t.Skip("root writes anywhere") + } + if err := Installable(ro); err != ErrNeedsAdmin { + t.Fatalf("a folder the user can't write: %v", err) + } + if err := Installable(filepath.Join(ro, "magpie")); err != ErrNeedsAdmin { + t.Fatalf("a folder that can't be made: %v", err) + } +} diff --git a/internal/update/install_windows.go b/internal/update/install_windows.go index 1b4b5ac6f..c5e1c34f4 100644 --- a/internal/update/install_windows.go +++ b/internal/update/install_windows.go @@ -6,6 +6,7 @@ import ( ptr "unsafe" "golang.org/x/sys/windows" + "golang.org/x/sys/windows/registry" "github.com/yetone/magpie/internal/appdir" ) @@ -91,3 +92,50 @@ func hide(p string) { windows.SetFileAttributes(u, a|windows.FILE_ATTRIBUTE_HIDDEN) } } + +// installKey holds InstallLocation, the folder the user chose to install +// magpie in (Settle). Uninstall removes it. +const installKey = `Software\magpie` + +func readInstallDir() string { + k, err := registry.OpenKey(registry.CURRENT_USER, installKey, registry.QUERY_VALUE) + if err != nil { + return "" + } + defer k.Close() + v, _, err := k.GetStringValue("InstallLocation") + if err != nil { + return "" + } + return v +} + +func writeInstallDir(dir string) error { + k, _, err := registry.CreateKey(registry.CURRENT_USER, installKey, registry.SET_VALUE) + if err != nil { + return err + } + defer k.Close() + return k.SetStringValue("InstallLocation", dir) +} + +// ForgetInstallDir takes out the record of the folder magpie was +// installed in, and its key once nothing else is in it. +func ForgetInstallDir() error { + k, err := registry.OpenKey(registry.CURRENT_USER, installKey, registry.SET_VALUE|registry.QUERY_VALUE) + if err != nil { + return nil + } + err = k.DeleteValue("InstallLocation") + n, _ := k.Stat() + k.Close() + if err != nil && err != registry.ErrNotExist { + return err + } + if n != nil && n.ValueCount == 0 && n.SubKeyCount == 0 { + if err := registry.DeleteKey(registry.CURRENT_USER, installKey); err != nil && err != registry.ErrNotExist { + return err + } + } + return nil +}