gloomberb 0.19.6 → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (137) hide show
  1. package/LICENSE +0 -4
  2. package/package.json +6 -5
  3. package/patches/electrobun-devkit@2.0.5.patch +148 -0
  4. package/src/api-client/bond-trades.ts +59 -0
  5. package/src/api-client/data.ts +21 -0
  6. package/src/api-client/index.ts +2 -0
  7. package/src/api-client/types/account.ts +86 -0
  8. package/src/api-client/types/assist.ts +32 -0
  9. package/src/api-client/types/auth.ts +63 -0
  10. package/src/api-client/types/billing.ts +54 -0
  11. package/src/api-client/types/chat.ts +180 -0
  12. package/src/api-client/types/congress.ts +107 -0
  13. package/src/api-client/types/credit.ts +110 -0
  14. package/src/api-client/types/econ.ts +158 -0
  15. package/src/api-client/types/equity-diagnostic.ts +73 -0
  16. package/src/api-client/types/filings-and-calls.ts +350 -0
  17. package/src/api-client/types/index.ts +25 -0
  18. package/src/api-client/types/jobs.ts +147 -0
  19. package/src/api-client/types/market.ts +122 -0
  20. package/src/api-client/types/news.ts +91 -0
  21. package/src/api-client/types/notes-and-theses.ts +172 -0
  22. package/src/api-client/types/quotes.ts +28 -0
  23. package/src/api-client/types/scanners.ts +125 -0
  24. package/src/api-client/types/screener.ts +65 -0
  25. package/src/api-client/types/search.ts +107 -0
  26. package/src/api-client/types/sync.ts +14 -0
  27. package/src/api-client/types/team-collections.ts +43 -0
  28. package/src/api-client/types/team-views.ts +32 -0
  29. package/src/api-client/types/teams.ts +135 -0
  30. package/src/api-client/types/ticker-data.ts +57 -0
  31. package/src/api-client/types/tweets.ts +59 -0
  32. package/src/api-client/types/world-venues.ts +23 -0
  33. package/src/app/runtime/desktop-deeplink.ts +41 -6
  34. package/src/app/star-prompt/status-line.tsx +1 -1
  35. package/src/app.tsx +1 -7
  36. package/src/architecture/ui-tokens-allowlist.json +0 -8
  37. package/src/cli/commands/ticker.ts +17 -4
  38. package/src/cli/desktop-pane-shot-browser.ts +69 -3
  39. package/src/cli/pane-functions/catalog.ts +3 -1
  40. package/src/components/chart/composite/use-composite-chart-keyboard.ts +11 -2
  41. package/src/components/data-table/export.ts +4 -1
  42. package/src/components/layout/detached-pane-shell.tsx +10 -37
  43. package/src/components/layout/double-escape-close.ts +90 -0
  44. package/src/components/layout/header.tsx +3 -2
  45. package/src/components/layout/market-summary.ts +6 -3
  46. package/src/components/layout/pane/footer/index.tsx +2 -6
  47. package/src/components/layout/pane/footer/model.ts +6 -12
  48. package/src/components/layout/shell/active-drag.ts +53 -11
  49. package/src/components/layout/shell/drag/magnets.ts +128 -19
  50. package/src/components/layout/shell/pane/actions.ts +6 -2
  51. package/src/components/layout/shell/pane/management-shortcuts.ts +13 -51
  52. package/src/components/layout/status-bar.tsx +4 -78
  53. package/src/components/layout/status-widget-space.ts +5 -5
  54. package/src/components/onboarding/portfolio-step/positions-panel.tsx +1 -1
  55. package/src/components/ui/data-table/index.tsx +5 -1
  56. package/src/components/ui/data-table/render-cell.ts +19 -0
  57. package/src/components/ui/delayed-mark.tsx +59 -7
  58. package/src/components/ui/icon.tsx +1 -8
  59. package/src/components/ui/menu.tsx +6 -1
  60. package/src/i18n/es.ts +3 -3
  61. package/src/i18n/ja.ts +3 -3
  62. package/src/i18n/ko.ts +3 -3
  63. package/src/i18n/zh-cn.ts +3 -3
  64. package/src/i18n/zh-tw.ts +3 -3
  65. package/src/plugins/builtin/chat/content/composer.tsx +21 -27
  66. package/src/plugins/builtin/chat/content/index.tsx +31 -3
  67. package/src/plugins/builtin/chat/content/shortcuts.ts +4 -2
  68. package/src/plugins/builtin/chat/content/snapshot.ts +0 -3
  69. package/src/plugins/builtin/cloud/auth-actions.tsx +51 -23
  70. package/src/plugins/builtin/cloud/trial-offer-status-widget.tsx +3 -3
  71. package/src/plugins/builtin/cloud/upgrade-status-widget.tsx +32 -25
  72. package/src/plugins/builtin/congress-trades/model.ts +2 -1
  73. package/src/plugins/builtin/congress-trades/pane.tsx +3 -0
  74. package/src/plugins/builtin/custom-view/index.tsx +1 -1
  75. package/src/plugins/builtin/custom-view/loader.ts +85 -8
  76. package/src/plugins/builtin/custom-view/view-spec.ts +28 -0
  77. package/src/plugins/builtin/equity-screener/criterion-editor.tsx +13 -4
  78. package/src/plugins/builtin/equity-screener/headless.ts +33 -1
  79. package/src/plugins/builtin/equity-screener/model.ts +58 -15
  80. package/src/plugins/builtin/equity-screener/pane.tsx +36 -6
  81. package/src/plugins/builtin/executives/format.ts +5 -4
  82. package/src/plugins/builtin/executives/pane.tsx +1 -1
  83. package/src/plugins/builtin/help/index.tsx +55 -1
  84. package/src/plugins/builtin/insider/model.ts +30 -2
  85. package/src/plugins/builtin/jobs/model.ts +2 -2
  86. package/src/plugins/builtin/mna/model.ts +2 -2
  87. package/src/plugins/builtin/notes/files.ts +2 -0
  88. package/src/plugins/builtin/notes/owner.tsx +20 -1
  89. package/src/plugins/builtin/notes/quick-notes-pane.tsx +22 -4
  90. package/src/plugins/builtin/notes/store.ts +6 -1
  91. package/src/plugins/builtin/portfolio-list/header.tsx +1 -1
  92. package/src/plugins/builtin/research/corporate-actions-pane.tsx +29 -25
  93. package/src/plugins/builtin/series-inventory.ts +1 -0
  94. package/src/plugins/builtin/shared/earnings-report.ts +7 -2
  95. package/src/plugins/builtin/shared/use-quote-board.ts +85 -46
  96. package/src/plugins/builtin/short-interest/headless.ts +1 -1
  97. package/src/plugins/builtin/short-interest/model.ts +15 -6
  98. package/src/plugins/builtin/short-interest/types.ts +2 -0
  99. package/src/plugins/builtin/thirteenf/overlap-pane.tsx +3 -0
  100. package/src/plugins/builtin/thirteenf/pane.tsx +3 -0
  101. package/src/plugins/builtin/ticker-detail/overview/model.ts +5 -3
  102. package/src/plugins/builtin/ticker-detail/overview-tab.tsx +4 -4
  103. package/src/plugins/builtin/trace-bonds/detail.tsx +198 -0
  104. package/src/plugins/builtin/trace-bonds/headless.ts +62 -4
  105. package/src/plugins/builtin/trace-bonds/history.ts +155 -0
  106. package/src/plugins/builtin/trace-bonds/pane.tsx +64 -5
  107. package/src/plugins/installer.ts +16 -3
  108. package/src/plugins/plugin-names.ts +11 -2
  109. package/src/remote/controller.ts +9 -2
  110. package/src/remote/schema.ts +2 -1
  111. package/src/renderers/cloudflare/http-proxy.ts +67 -8
  112. package/src/renderers/cloudflare/proxy-session.ts +1 -1
  113. package/src/renderers/cloudflare/worker.ts +29 -2
  114. package/src/renderers/dom/desktop/icons.tsx +0 -2
  115. package/src/renderers/dom/styles.css +0 -3
  116. package/src/renderers/electrobun/bun/desktop/install-records.ts +59 -0
  117. package/src/renderers/electrobun/bun/desktop/installer-folder.ts +208 -592
  118. package/src/renderers/electrobun/bun/desktop/macos-objc.ts +14 -0
  119. package/src/renderers/electrobun/bun/desktop/update.ts +1 -1
  120. package/src/renderers/electrobun/bun/index.ts +19 -13
  121. package/src/renderers/electrobun/bun/window/create.ts +23 -3
  122. package/src/renderers/electrobun/bun/window/electrobun-window-host.ts +4 -4
  123. package/src/renderers/electrobun/bun/window/events.ts +4 -4
  124. package/src/renderers/electrobun/bun/window/frame.ts +2 -1
  125. package/src/renderers/electrobun/bun/window/native-min-size.ts +322 -0
  126. package/src/renderers/electrobun/view/backend-rpc.ts +1 -1
  127. package/src/sources/gloomberb-cloud/index.ts +5 -7
  128. package/src/sources/provider-router/batches.ts +18 -3
  129. package/src/sources/provider-router/financials.ts +18 -4
  130. package/src/types/data-provider.ts +14 -0
  131. package/src/types/financials.ts +15 -3
  132. package/src/types/headless.ts +2 -0
  133. package/src/utils/double-escape-close.ts +38 -16
  134. package/src/utils/format.ts +23 -3
  135. package/src/utils/price-earnings.ts +18 -0
  136. package/patches/electrobun@1.18.1.patch +0 -633
  137. package/src/api-client/types.ts +0 -2441
@@ -1,30 +1,32 @@
1
- import { lstat, mkdir, readdir, readFile, rm, writeFile } from "fs/promises";
1
+ import { mkdir, readFile, rm, writeFile } from "fs/promises";
2
2
  import { tmpdir } from "os";
3
3
  import { win32 } from "path";
4
4
  import { logFailure } from "../../../../utils/log-failure";
5
- import { DESKTOP_APP_IDENTIFIER, DESKTOP_APP_IDENTIFIERS } from "../../shared/app-name";
6
- import { psString, runScriptAfterExit, runScriptInBackground, writePowerShellScript } from "./windows-script";
5
+ import { DESKTOP_APP_IDENTIFIERS } from "../../shared/app-name";
6
+ import { psString, runScriptInBackground, writePowerShellScript } from "./windows-script";
7
7
 
8
8
  /**
9
- * The Windows installer (scripts/windows-installer.iss) puts the app in its
10
- * own folder, `Programs\Gloom` unless the user picks another, and its Start
11
- * menu and Desktop shortcuts, the `gloom` command on PATH and its uninstall
12
- * entry lead there. Electrobun's updater knows nothing of it: it installs
13
- * every update into its own folder, `<app data>\<identifier>\<channel>\app`,
14
- * and opens it from there. The next start from a shortcut opened the build
15
- * from before the update, which offered the same update again, and
16
- * uninstalling left the updated copy behind.
9
+ * Electrobun 2 updates a Windows install only in its own folder,
10
+ * `<local app data>\<identifier>\<channel>\app`: its native update manager
11
+ * refuses any other, and its launcher writes the install's records there
12
+ * (the uninstaller, its Apps & features entry, the Start menu and Desktop
13
+ * shortcuts). The Windows installer (scripts/windows-installer.iss) installs
14
+ * into that folder too.
17
15
  *
18
- * So a build that finds itself in the updater's folder while the installer's
19
- * install is recorded quits before any window shows, and a script moves it
20
- * into the installer's folder and opens it from there. A build running from
21
- * the installer's folder removes a copy an earlier update left in the
22
- * updater's. Either way the shortcuts and uninstall entry Electrobun's own
23
- * setup made for its folder, if any, follow to the installer's.
24
- *
25
- * The app quits for the move only once the script has checked it can make
26
- * it, and tries a build at most three times, ten minutes apart: a move that
27
- * cannot happen never makes it quit and open again at every start.
16
+ * Installer installs from before Electrobun 2 live in the installer's own
17
+ * folder, `Programs\Gloom` unless the user picked another, with the
18
+ * installer's uninstall entry and the `gloom` command's PATH entry leading
19
+ * there. The last of those builds updates into Electrobun's folder and opens
20
+ * this build from it. This build then retires the installer's folder: its
21
+ * own uninstaller removes what it installed, its entry and PATH entry, and
22
+ * the shortcuts it made, which the launcher had just pointed at this folder
23
+ * and which come back here. What it leaves in a folder the installer picked
24
+ * (files the app wrote there) goes too; one the user picked keeps them.
25
+ * It runs in the background, once the window is up. Until it finishes,
26
+ * a file beside the app's folder names the installer's folder, and the next
27
+ * start runs it again: after the old build was still open, its uninstaller
28
+ * failed (its entry stays, for the next try), or a shortcut or PATH could
29
+ * not be written.
28
30
  */
29
31
 
30
32
  /** The installer's AppId, which names its uninstall entry (windows-installer.iss). */
@@ -35,45 +37,34 @@ export interface InstallerFolderContext {
35
37
  platform: string;
36
38
  execPath: string;
37
39
  homeDir: string;
38
- /** `%LOCALAPPDATA%`, where Electrobun keeps the updater's folder. */
40
+ /** `%LOCALAPPDATA%`, under which Electrobun keeps the app's folder. */
39
41
  localAppData?: string;
40
42
  /** The folder the installer's uninstall entry records, or null; read from the registry when left out. */
41
43
  readInstallerFolder?: () => Promise<string | null>;
42
44
  }
43
45
 
44
- export type InstallerFolderMove =
45
- /** Not an installer install, or already in its folder with nothing left elsewhere. */
46
+ export type InstallerFolderRetirement =
47
+ /** No installer install outside Electrobun's folder, or not from it. */
46
48
  | { kind: "none" }
47
- /** The app runs from the updater's folder, and quits for the script to move it and open it again. */
48
- | { kind: "relaunching" }
49
- /** A copy left in the updater's folder goes in the background. */
50
- | { kind: "removing" }
51
- /** The app runs from where it is: a try failed a moment ago, tries failed too often for this build, or the installer's folder is in use. */
52
- | { kind: "skipped" }
53
- | { kind: "failed" };
49
+ /** A script retires the installer's folder in the background. */
50
+ | { kind: "retiring"; folder: string };
51
+
52
+ /** How long after the start the script runs, out of the launch's way. */
53
+ const RETIRE_DELAY_MS = 10_000;
54
54
 
55
- /** How long a try at moving the app keeps it from trying again, so a move that cannot happen never makes it quit in a loop. */
56
- const RETRY_AFTER_MS = 10 * 60_000;
57
- /** Tries at moving one build before it stays in the updater's folder until the next update. */
58
- const MAX_MOVE_TRIES = 3;
59
- /** How long after the start a copy left in the updater's folder goes, out of the launch's way. */
60
- const REMOVAL_DELAY_MS = 10_000;
61
- const LAUNCHER = "bin\\launcher.exe";
55
+ /** Beside the app's folder: the installer's folder, while its retirement has not finished. */
56
+ const PENDING_FILE = "installer-folder.pending";
62
57
 
63
58
  function samePath(left: string, right: string): boolean {
64
59
  return win32.resolve(left).toLowerCase() === win32.resolve(right).toLowerCase();
65
60
  }
66
61
 
67
- async function exists(path: string): Promise<boolean> {
68
- return lstat(path).then(() => true, () => false);
69
- }
70
-
71
62
  function isDesktopIdentifierName(name: string): boolean {
72
63
  return DESKTOP_APP_IDENTIFIERS.some((identifier) => identifier.toLowerCase() === name.toLowerCase());
73
64
  }
74
65
 
75
66
  /**
76
- * The updater's folder the app runs from, from its `bin\bun.exe`:
67
+ * Electrobun's folder the app runs from, from its `bin\bun.exe`:
77
68
  * `<local app data>\<identifier>\<channel>\app`, under either identifier the
78
69
  * app has carried. Null anywhere else.
79
70
  */
@@ -86,22 +77,6 @@ export function updaterAppFolder(execPath: string, localAppData: string): { fold
86
77
  return { folder: win32.join(localAppData, identifier, channel, "app"), channel };
87
78
  }
88
79
 
89
- /**
90
- * The updater's folders for `channel` under either identifier, and what a
91
- * removal that did not finish left of one (`app.removing-*`).
92
- */
93
- async function updaterFolders(localAppData: string, channel: string): Promise<string[]> {
94
- const folders: string[] = [];
95
- for (const identifier of DESKTOP_APP_IDENTIFIERS) {
96
- const parent = win32.join(localAppData, identifier, channel);
97
- for (const entry of await readdir(parent).catch(() => [] as string[])) {
98
- const name = entry.toLowerCase();
99
- if (name === "app" || name.startsWith("app.removing-")) folders.push(win32.join(parent, entry));
100
- }
101
- }
102
- return folders;
103
- }
104
-
105
80
  /** The value `name` holds in a `.reg` export, unescaped; null when it holds none or no string. */
106
81
  export function regExportValue(text: string, name: string): string | null {
107
82
  const prefix = `${JSON.stringify(name)}=`;
@@ -131,61 +106,18 @@ async function readInstallerFolderFromRegistry(): Promise<string | null> {
131
106
  }
132
107
  }
133
108
 
134
- /**
135
- * The installer's folder, when it holds the app. A move cut short (a power
136
- * cut between its renames) can leave its launcher in what the move set aside
137
- * there: the next move puts that back before anything else.
138
- */
139
- async function installerFolder(read: () => Promise<string | null>): Promise<string | null> {
140
- const folder = await read().catch(() => null);
141
- if (!folder) return null;
142
- if (await exists(win32.join(folder, LAUNCHER))) return win32.resolve(folder);
143
- for (const entry of await readdir(folder).catch(() => [] as string[])) {
144
- if (/^\.gloom-previous-/i.test(entry) && await exists(win32.join(folder, entry, LAUNCHER))) return win32.resolve(folder);
145
- }
146
- return null;
147
- }
148
-
149
- async function buildChannel(appFolder: string): Promise<string> {
150
- const info = await readFile(win32.join(appFolder, "Resources", "version.json"), "utf8").then((text) => JSON.parse(text) as { channel?: unknown }, () => null);
151
- return typeof info?.channel === "string" && info.channel ? info.channel : "stable";
152
- }
153
-
154
- interface InstallerFolderScript {
155
- /** The installer's folder. */
156
- target: string;
157
- /** The updater's folders to empty into it or remove; with `afterExit`, the first holds the running app. */
158
- sources: string[];
159
- /** This build's app data folder: the script's log goes there, and a folder it removes is moved there first. */
160
- folder: string;
161
- log: string;
162
- /**
163
- * The app runs from `sources[0]`: the script waits for everything running
164
- * from there to quit, moves it into `target` and opens it again. `cancel`
165
- * is the file the app writes when it stops waiting for the script.
166
- */
167
- afterExit?: { cancel: string; taskName: string };
168
- }
169
-
170
- // PowerShell 5.1. The build goes into the installer's folder by renames only:
171
- // from another drive it is copied beside the installed build first. A folder
172
- // of the build (bin, Resources) replaces the installed one whole when that
173
- // holds nothing but the app's files; in one that also holds other files (an
174
- // install in C:\Tools, whose bin was already there) only the app's files are
175
- // replaced. What it replaces waits beside it, in the installer's folder,
176
- // until all of the build is in, and goes back if it is not. Then the app
177
- // opens again, and the rest (shortcuts, uninstall entries, the copy it came
178
- // from) follows.
109
+ // PowerShell 5.1. The installer's uninstaller removes exactly what it
110
+ // installed and what earlier builds' moves listed in Resources\update-files.txt,
111
+ // with its PATH entry and its shortcuts. Without one (deleted by hand), its
112
+ // entry goes here. While the old build runs from the folder, or when its
113
+ // uninstaller fails, the entry stays and the next start tries again. The
114
+ // Start menu shortcut, and the Desktop one when there was one, then lead to
115
+ // this folder; next, what is left in the installer's default folder, which
116
+ // holds nothing of the user's, goes; the PATH entry moves last. Each of those
117
+ // steps fails on its own, and the script finishes (removing $Pending) only
118
+ // once all of them worked.
179
119
  const SCRIPT_BODY = String.raw`
180
- $Launcher = 'bin\launcher.exe'
181
- $FileList = 'Resources\update-files.txt'
182
- $UninstallPath = 'Software\Microsoft\Windows\CurrentVersion\Uninstall'
183
- $Journal = New-Object System.Collections.Generic.List[object]
184
- $Exited = $false
185
- $Opened = $false
186
-
187
- # UTF-8 without a byte order mark: the app reads the answer from the first
188
- # line, and a path with an accent in it reads back as it is.
120
+ $UninstallKey = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Uninstall\' + $InstallerEntry
189
121
  $LogEncoding = New-Object System.Text.UTF8Encoding $false
190
122
 
191
123
  function Write-Log([string]$Message) {
@@ -194,538 +126,222 @@ function Write-Log([string]$Message) {
194
126
  }
195
127
  }
196
128
 
197
- function Test-Under([string]$Path, [string]$Root) {
198
- if (-not $Path) { return $false }
199
- return $Path.Equals($Root, [StringComparison]::OrdinalIgnoreCase) -or $Path.StartsWith($Root + '\', [StringComparison]::OrdinalIgnoreCase)
200
- }
201
-
202
- # The processes whose program is in $Root, whatever started them.
203
- function Get-RunningUnder([string]$Root) {
204
- @(Get-Process -ErrorAction SilentlyContinue | Where-Object { try { Test-Under $_.Path $Root } catch { $false } })
205
- }
206
-
207
- # The processes running one of the build's programs from the installer's
208
- # folder, such as the gloom command: they keep its files from being replaced.
209
- # Another program the user keeps in that folder does not.
210
- function Get-AppRunningInTarget {
211
- @(Get-RunningUnder $Target | Where-Object { $BuildFiles.Contains($_.Path.Substring($Target.Length + 1)) })
129
+ function Get-NormalPath([string]$Path) {
130
+ if (-not $Path) { return '' }
131
+ $Path.Trim().Trim('"').TrimEnd('\', '/').ToLowerInvariant()
212
132
  }
213
133
 
214
- function Wait-Until([int]$Seconds, [scriptblock]$Condition) {
215
- for ($Wait = 0; $Wait -lt ($Seconds * 2); $Wait += 1) {
216
- if (& $Condition) { return $true }
217
- Start-Sleep -Milliseconds 500
218
- }
219
- return [bool](& $Condition)
134
+ # The programs running from a file in $Folder.
135
+ function Get-RunningFrom([string]$Folder) {
136
+ $Prefix = (Get-NormalPath $Folder) + '\'
137
+ @(Get-Process -ErrorAction SilentlyContinue | Where-Object {
138
+ try { $_.Path -and (Get-NormalPath $_.Path).StartsWith($Prefix) } catch { $false }
139
+ })
220
140
  }
221
141
 
222
- function Invoke-Retried([scriptblock]$Action, [string]$What) {
223
- for ($Attempt = 1; $true; $Attempt += 1) {
224
- try { & $Action | Out-Null; return } catch {
225
- if ($Attempt -ge 20) { throw ('could not ' + $What + ': ' + $_.Exception.Message) }
226
- Start-Sleep -Milliseconds 500
227
- }
142
+ # The user's PATH as written, %VARIABLES% unexpanded, and its kind: an
143
+ # expanded copy written back would freeze every variable in it.
144
+ function Get-UserPath {
145
+ $Key = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey('Environment')
146
+ try {
147
+ if (-not $Key) { return @{ Value = ''; Kind = [Microsoft.Win32.RegistryValueKind]::ExpandString } }
148
+ $Value = [string]$Key.GetValue('Path', '', [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames)
149
+ $Kind = if ($Value) { $Key.GetValueKind('Path') } else { [Microsoft.Win32.RegistryValueKind]::ExpandString }
150
+ @{ Value = $Value; Kind = $Kind }
151
+ } finally { if ($Key) { $Key.Close() } }
152
+ }
153
+
154
+ function Set-UserPath([string[]]$Entries, $Kind) {
155
+ $Key = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey('Environment')
156
+ try { $Key.SetValue('Path', ($Entries -join ';'), $Kind) } finally { $Key.Close() }
157
+ # Explorer reads the new PATH for what it opens next once it is told. A
158
+ # user variable set through .NET tells it (WM_SETTINGCHANGE); clearing one
159
+ # that is not there tells it and changes nothing, with no code compiled
160
+ # here for the message.
161
+ [Environment]::SetEnvironmentVariable('GloomPathChanged', $null, 'User')
162
+ }
163
+
164
+ function Update-UserPath([string]$Remove, [string]$Add) {
165
+ $Path = Get-UserPath
166
+ $Entries = @($Path.Value -split ';' | Where-Object { $_.Trim() -and ((Get-NormalPath $_) -ne (Get-NormalPath $Remove)) })
167
+ $Changed = $Entries.Count -ne @($Path.Value -split ';' | Where-Object { $_.Trim() }).Count
168
+ if ($Add -and -not ($Entries | Where-Object { (Get-NormalPath $_) -eq (Get-NormalPath $Add) })) {
169
+ $Entries += $Add
170
+ $Changed = $true
228
171
  }
229
- }
230
-
231
- function Get-Stamp { (Get-Date).ToUniversalTime().ToString('yyyyMMddHHmmss') + '-' + [guid]::NewGuid().ToString('N').Substring(0, 8) }
232
-
233
- function Test-Folder([string]$Path) {
234
- $Item = Get-Item -LiteralPath $Path -Force -ErrorAction SilentlyContinue
235
- return ($null -ne $Item) -and $Item.PSIsContainer -and -not ($Item.Attributes -band [IO.FileAttributes]::ReparsePoint)
236
- }
237
-
238
- # The files in $Root, as paths after $Prefix. A link is a file here: it is not followed.
239
- function Get-Files([string]$Root, [string]$Prefix) {
240
- foreach ($Item in @(Get-ChildItem -LiteralPath $Root -Force)) {
241
- $Relative = if ($Prefix) { $Prefix + '\' + $Item.Name } else { $Item.Name }
242
- if ($Item.PSIsContainer -and -not ($Item.Attributes -band [IO.FileAttributes]::ReparsePoint)) { Get-Files $Item.FullName $Relative } else { $Relative }
172
+ if ($Changed) {
173
+ Set-UserPath $Entries $Path.Kind
174
+ Write-Log ('PATH leads to ' + $Add + ', not ' + $Remove)
243
175
  }
244
176
  }
245
177
 
246
- function Remove-Tree([string]$Path) {
247
- if (Test-Path -LiteralPath $Path) { Invoke-Retried { Remove-Item -LiteralPath $Path -Recurse -Force } ('remove ' + $Path) }
248
- }
249
-
250
- # Makes the missing folders up to $Path, each noted to take back.
251
- function New-Folder([string]$Path) {
252
- if (Test-Path -LiteralPath $Path) { return }
253
- New-Folder (Split-Path -Parent $Path)
254
- New-Item -ItemType Directory -Path $Path | Out-Null
255
- $Journal.Add(@($null, $Path))
256
- }
257
-
258
- # A rename, noted to take back. Nothing lands inside a folder in its way.
259
- function Move-Noted([string]$From, [string]$To) {
260
- if (Test-Path -LiteralPath $To) { throw ($To + ' is in the way') }
261
- New-Folder (Split-Path -Parent $To)
262
- Invoke-Retried { Move-Item -LiteralPath $From -Destination $To } ('move ' + $From)
263
- $Journal.Add(@($From, $To))
264
- }
265
-
266
- function Undo-Noted {
267
- for ($Index = $Journal.Count - 1; $Index -ge 0; $Index -= 1) {
268
- $Step = $Journal[$Index]
269
- try {
270
- if ($null -eq $Step[0]) {
271
- [IO.Directory]::Delete($Step[1], $false)
272
- } else {
273
- if (Test-Path -LiteralPath $Step[0]) { throw ($Step[0] + ' is in the way') }
274
- Invoke-Retried { Move-Item -LiteralPath $Step[1] -Destination $Step[0] } ('put back ' + $Step[0])
275
- }
276
- } catch { Write-Log ('could not take back a step: ' + $_.Exception.Message) }
178
+ function Set-Shortcuts($Wanted) {
179
+ $Shell = New-Object -ComObject WScript.Shell
180
+ $Launcher = Join-Path $App 'bin\launcher.exe'
181
+ foreach ($Shortcut in $Wanted) {
182
+ if (Test-Path -LiteralPath $Shortcut.Path) {
183
+ if ((Get-NormalPath $Shell.CreateShortcut($Shortcut.Path).TargetPath) -eq (Get-NormalPath $Launcher)) { continue }
184
+ }
185
+ $Link = $Shell.CreateShortcut($Shortcut.Path)
186
+ $Link.TargetPath = $Launcher
187
+ $Link.WorkingDirectory = Join-Path $App 'bin'
188
+ $Link.IconLocation = $Launcher + ',0'
189
+ $Link.Save()
190
+ Write-Log ('pointed ' + $Shortcut.Path + ' at ' + $Launcher)
277
191
  }
278
- $Journal.Clear()
279
192
  }
280
193
 
281
- # The files earlier updates put in the installer's folder, as they listed them.
282
- function Read-FileList {
283
- $Path = Join-Path $Target $FileList
284
- if (-not (Test-Path -LiteralPath $Path)) { return }
285
- foreach ($Line in [IO.File]::ReadAllLines($Path)) {
286
- $Line = $Line.Trim()
287
- if ($Line -and $Line -notmatch '^[\\/]|:|\.\.') { $Line }
194
+ $Mutex = New-Object System.Threading.Mutex($false, 'Local\GloomInstallerFolder')
195
+ $Locked = $false
196
+ try {
197
+ New-Item -ItemType Directory -Force -Path (Split-Path -Parent $Log) | Out-Null
198
+ try { $Locked = $Mutex.WaitOne(0) } catch { $Locked = ($_.Exception.GetBaseException() -is [System.Threading.AbandonedMutexException]) }
199
+ if (-not $Locked) { Write-Log 'busy: another start retires the folder'; return }
200
+ Write-Log ('started: retiring ' + $Folder)
201
+ $Unfinished = @()
202
+
203
+ $Shortcuts = @(
204
+ @{ Path = (Join-Path ([Environment]::GetFolderPath('Programs')) 'Gloom.lnk'); Always = $true },
205
+ @{ Path = (Join-Path ([Environment]::GetFolderPath('Desktop')) 'Gloom.lnk'); Always = $false }
206
+ )
207
+ $Wanted = @($Shortcuts | Where-Object { $_.Always -or (Test-Path -LiteralPath $_.Path) })
208
+
209
+ $Uninstaller = ''
210
+ try { $Uninstaller = ([string](Get-ItemProperty -LiteralPath $UninstallKey -ErrorAction Stop).UninstallString).Trim().Trim('"') } catch { }
211
+ $Running = @()
212
+ if (Test-Path -LiteralPath $UninstallKey) {
213
+ # While the earlier build runs from there its files are locked, and its
214
+ # uninstaller would leave half an install. One that just handed over to
215
+ # this build may still be on its way out.
216
+ for ($Wait = 0; $Wait -lt 60; $Wait += 1) {
217
+ $Running = @(Get-RunningFrom $Folder)
218
+ if (-not $Running.Count) { break }
219
+ Start-Sleep -Milliseconds 500
220
+ }
288
221
  }
289
- }
290
-
291
- function Install-Build([string]$Source) {
292
- $Stamp = Get-Stamp
293
- $From = $Source
294
- $Next = $null
295
- if (-not [IO.Path]::GetPathRoot($Source).Equals([IO.Path]::GetPathRoot($Target), [StringComparison]::OrdinalIgnoreCase)) {
296
- $Next = Join-Path $Target ('.gloom-next-' + $Stamp)
222
+ if ($Running.Count) {
223
+ $Names = ($Running | ForEach-Object { $_.ProcessName } | Sort-Object -Unique) -join ', '
224
+ Write-Log ('the earlier build still runs from ' + $Folder + ' (' + $Names + '); its uninstall waits for the next start')
225
+ $Unfinished += 'uninstall'
226
+ } elseif ($Uninstaller -and (Test-Path -LiteralPath $Uninstaller)) {
227
+ $Code = $null
297
228
  try {
298
- New-Item -ItemType Directory -Path $Next | Out-Null
299
- foreach ($Entry in @(Get-ChildItem -LiteralPath $Source -Force)) {
300
- Copy-Item -LiteralPath $Entry.FullName -Destination (Join-Path $Next $Entry.Name) -Recurse -Force
301
- }
229
+ $Process = Start-Process -FilePath $Uninstaller -ArgumentList @('/VERYSILENT', '/SUPPRESSMSGBOXES', '/NORESTART') -PassThru -Wait
230
+ $Code = $Process.ExitCode
231
+ Write-Log ("the installer's uninstaller exited with " + $Code)
302
232
  } catch {
303
- $Reason = $_.Exception.Message
304
- try { Remove-Tree $Next } catch { Write-Log ('could not remove ' + $Next + ': ' + $_.Exception.Message) }
305
- throw ('could not copy the build into ' + $Target + ': ' + $Reason)
306
- }
307
- $From = $Next
308
- }
309
-
310
- $NewFiles = @(Get-Files $From '')
311
- $Listed = @(Read-FileList)
312
- $Own = New-Object 'System.Collections.Generic.HashSet[string]' ([StringComparer]::OrdinalIgnoreCase)
313
- foreach ($File in ($NewFiles + $Listed + @($FileList))) { [void]$Own.Add($File) }
314
- $Aside = Join-Path $Target ('.gloom-previous-' + $Stamp)
315
- $Journal.Clear()
316
- try {
317
- foreach ($Entry in @(Get-ChildItem -LiteralPath $From -Force)) {
318
- $Name = $Entry.Name
319
- $Old = Join-Path $Target $Name
320
- if (-not (Test-Path -LiteralPath $Old)) {
321
- Move-Noted $Entry.FullName $Old
322
- } elseif (-not $Entry.PSIsContainer) {
323
- if (Test-Folder $Old) { throw ($Old + ' is a folder') }
324
- Move-Noted $Old (Join-Path $Aside $Name)
325
- Move-Noted $Entry.FullName $Old
326
- } else {
327
- if (-not (Test-Folder $Old)) { throw ($Old + ' is not a folder') }
328
- $Others = @(Get-Files $Old $Name | Where-Object { -not $Own.Contains($_) })
329
- if ($Others.Count -eq 0) {
330
- Move-Noted $Old (Join-Path $Aside $Name)
331
- Move-Noted $Entry.FullName $Old
332
- Write-Log ('replaced ' + $Old)
333
- } else {
334
- Write-Log ('kept ' + $Others.Count + ' file(s) in ' + $Old + ' that are not the app''s, such as ' + $Others[0])
335
- foreach ($Relative in @(Get-Files $Entry.FullName $Name)) {
336
- $Place = Join-Path $Target $Relative
337
- if (Test-Path -LiteralPath $Place) {
338
- if (Test-Folder $Place) { throw ($Place + ' is a folder') }
339
- Move-Noted $Place (Join-Path $Aside $Relative)
340
- }
341
- Move-Noted (Join-Path $From $Relative) $Place
342
- }
343
- }
344
- }
233
+ Write-Log ("could not run the installer's uninstaller: " + $_.Exception.Message)
345
234
  }
346
- } catch {
347
- $Reason = $_.Exception.Message
348
- Undo-Noted
349
- if ($Next) { try { Remove-Tree $Next } catch { Write-Log ('could not remove ' + $Next + ': ' + $_.Exception.Message) } }
350
- throw $Reason
351
- }
352
- $Journal.Clear()
353
-
354
- # For the uninstaller, which removes what it installed itself: what updates
355
- # put here, the files of this build and those of earlier ones still here.
356
- try {
357
- $Files = New-Object 'System.Collections.Generic.HashSet[string]' ([StringComparer]::OrdinalIgnoreCase)
358
- foreach ($File in $NewFiles) { [void]$Files.Add($File) }
359
- foreach ($File in $Listed) { if (Test-Path -LiteralPath (Join-Path $Target $File)) { [void]$Files.Add($File) } }
360
- [IO.File]::WriteAllLines((Join-Path $Target $FileList), [string[]]@($Files | Sort-Object))
361
- } catch { Write-Log ('could not list the files for the uninstaller: ' + $_.Exception.Message) }
362
- foreach ($Leftover in @($Aside, $Next)) {
363
- if ($Leftover) {
364
- try { Remove-Tree $Leftover } catch { Write-Log ($_.Exception.Message + '; the app removes it at its next start') }
235
+ # It hands over to a copy of itself in the temp folder, which removes the
236
+ # entry last. One that failed has little left to do.
237
+ $Waits = if ($Code -eq 0) { 240 } else { 10 }
238
+ for ($Wait = 0; ($Wait -lt $Waits) -and (Test-Path -LiteralPath $UninstallKey); $Wait += 1) { Start-Sleep -Milliseconds 500 }
239
+ if (Test-Path -LiteralPath $UninstallKey) {
240
+ Write-Log "the installer's uninstaller did not finish; its entry stays for the next start to try again"
241
+ $Unfinished += 'uninstall'
365
242
  }
243
+ } elseif (Test-Path -LiteralPath $UninstallKey) {
244
+ Write-Log "the installer's uninstaller is gone; removing its entry here"
245
+ Remove-Item -LiteralPath $UninstallKey -Recurse -Force
366
246
  }
367
- }
368
-
369
- # What a move that did not finish left in the installer's folder.
370
- # A move cut short (a power cut between the two renames of bin, or an undo
371
- # that failed) can leave the installed build without some of its files, in
372
- # what it set aside. A folder or file of the build missing from the
373
- # installer's folder goes back; file by file only while the launcher is
374
- # missing, so a file a newer build dropped is not brought back beside it.
375
- function Restore-SetAside([string]$Aside) {
376
- try {
377
- foreach ($Entry in @(Get-ChildItem -LiteralPath $Aside -Force)) {
378
- $Place = Join-Path $Target $Entry.Name
379
- if (-not (Test-Path -LiteralPath $Place)) {
380
- Invoke-Retried { Move-Item -LiteralPath $Entry.FullName -Destination $Place } ('put back ' + $Place)
381
- Write-Log ('put back ' + $Place)
382
- }
383
- }
384
- if (Test-Path -LiteralPath (Join-Path $Target $Launcher)) { return }
385
- foreach ($Relative in @(Get-Files $Aside '')) {
386
- $Place = Join-Path $Target $Relative
387
- if (Test-Path -LiteralPath $Place) { continue }
388
- New-Item -ItemType Directory -Force -Path (Split-Path -Parent $Place) | Out-Null
389
- Invoke-Retried { Move-Item -LiteralPath (Join-Path $Aside $Relative) -Destination $Place } ('put back ' + $Place)
390
- Write-Log ('put back ' + $Place)
391
- }
392
- } catch { Write-Log ('could not put back what ' + $Aside + ' holds: ' + $_.Exception.Message) }
393
- }
394
247
 
395
- # What a move that did not finish left in the installer's folder: a copy of
396
- # a build on its way in, and what it set aside, newest first. Nothing set
397
- # aside goes while the installed build has no launcher: it may be the only
398
- # copy of it.
399
- function Remove-Staging {
400
- $Leftovers = @(Get-ChildItem -LiteralPath $Target -Directory -Force -ErrorAction SilentlyContinue |
401
- Where-Object { $_.Name -like '.gloom-next-*' -or $_.Name -like '.gloom-previous-*' } | Sort-Object Name -Descending)
402
- foreach ($Leftover in $Leftovers) {
403
- if ((Get-RunningUnder $Leftover.FullName).Count -gt 0) { continue }
404
- if ($Leftover.Name -like '.gloom-previous-*') {
405
- Restore-SetAside $Leftover.FullName
406
- if (-not (Test-Path -LiteralPath (Join-Path $Target $Launcher))) {
407
- Write-Log ('kept ' + $Leftover.FullName + ': the installed build has no ' + $Launcher)
408
- continue
409
- }
410
- }
411
- try { Remove-Tree $Leftover.FullName; Write-Log ('removed ' + $Leftover.FullName) } catch { Write-Log $_.Exception.Message }
248
+ # The uninstaller removed the shortcuts it made, which led there.
249
+ try { Set-Shortcuts $Wanted } catch {
250
+ Write-Log ('could not write the shortcuts: ' + $_.Exception.Message)
251
+ $Unfinished += 'shortcuts'
412
252
  }
413
- }
414
253
 
415
- function Open-App([string]$Path) {
416
- $script:Opened = $true
417
- try {
418
- Start-Process -FilePath $Path -WorkingDirectory (Split-Path -Parent $Path)
419
- Write-Log ('opened ' + $Path)
420
- } catch { Write-Log ('could not open ' + $Path + ': ' + $_.Exception.Message) }
421
- }
422
-
423
- # A value naming a path in $From, naming $To instead; null for any other.
424
- function Get-Retargeted([string]$Value, [string]$From, [string]$To) {
425
- if (-not $Value) { return $null }
426
- $Pattern = [regex]::Escape($From) + '(?=[\\/",;]|$)'
427
- $Evaluator = [System.Text.RegularExpressions.MatchEvaluator] ({ param($Found) $To }.GetNewClosure())
428
- $Next = [regex]::Replace($Value, $Pattern, $Evaluator, [System.Text.RegularExpressions.RegexOptions]::IgnoreCase)
429
- if ($Next -ceq $Value) { return $null }
430
- return $Next
431
- }
432
-
433
- # Electrobun's setup makes Desktop and Start menu shortcuts into its folder.
434
- function Update-Shortcuts([string]$From, [string]$To) {
435
- $Shell = New-Object -ComObject WScript.Shell
436
- $Folders = @(
437
- [Environment]::GetFolderPath('Desktop'),
438
- [Environment]::GetFolderPath('Programs'),
439
- (Join-Path $env:APPDATA 'Microsoft\Internet Explorer\Quick Launch')
440
- ) | Where-Object { $_ -and (Test-Path -LiteralPath $_) } | Sort-Object -Unique
441
- foreach ($Folder in $Folders) {
442
- foreach ($Link in @(Get-ChildItem -LiteralPath $Folder -Filter '*.lnk' -Recurse -File -Force -ErrorAction SilentlyContinue)) {
254
+ # The uninstaller leaves what the app wrote there after the install. That
255
+ # goes too, from a folder the installer picked itself only, and only once
256
+ # the uninstaller is done with it.
257
+ $DefaultFolders = @('Programs\Gloom', 'Programs\Gloomberb') | ForEach-Object { Get-NormalPath (Join-Path $env:LOCALAPPDATA $_) }
258
+ if (($Unfinished -notcontains 'uninstall') -and ($DefaultFolders -contains (Get-NormalPath $Folder))) {
259
+ for ($Wait = 0; ($Wait -lt 20) -and (Test-Path -LiteralPath $Folder); $Wait += 1) { Start-Sleep -Milliseconds 500 }
260
+ if (Test-Path -LiteralPath $Folder) {
261
+ $Left = @(Get-ChildItem -LiteralPath $Folder -Recurse -Force -File -ErrorAction SilentlyContinue | Select-Object -First 5 | ForEach-Object { $_.FullName.Substring($Folder.Length) })
443
262
  try {
444
- $Shortcut = $Shell.CreateShortcut($Link.FullName)
445
- $Changed = $false
446
- foreach ($Field in @('TargetPath', 'WorkingDirectory', 'IconLocation', 'Arguments')) {
447
- $Next = Get-Retargeted ([string]$Shortcut.$Field) $From $To
448
- if ($Next) { $Shortcut.$Field = $Next; $Changed = $true }
449
- }
450
- if ($Changed) { $Shortcut.Save(); Write-Log ('pointed ' + $Link.FullName + ' at ' + $To) }
451
- } catch { Write-Log ('could not update ' + $Link.FullName + ': ' + $_.Exception.Message) }
452
- }
453
- }
454
- }
455
-
456
- # The uninstall entry Electrobun's setup made for its folder goes with the
457
- # folder; the installer's own entry is the one that removes the app.
458
- function Remove-UninstallEntries([string]$Folder) {
459
- $Uninstall = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey($UninstallPath, $true)
460
- if (-not $Uninstall) { return }
461
- try {
462
- foreach ($Name in @($Uninstall.GetSubKeyNames())) {
463
- if ($Name -eq $InstallerEntry) { continue }
464
- $Key = $Uninstall.OpenSubKey($Name)
465
- if (-not $Key) { continue }
466
- $Location = [string]$Key.GetValue('InstallLocation', '')
467
- $Key.Close()
468
- if (Test-Under $Location.TrimEnd('\') $Folder) {
469
- try { $Uninstall.DeleteSubKeyTree($Name); Write-Log ('removed the uninstall entry ' + $Name) } catch { Write-Log ('could not remove the uninstall entry ' + $Name + ': ' + $_.Exception.Message) }
263
+ Remove-Item -LiteralPath $Folder -Recurse -Force
264
+ Write-Log ('removed ' + $Folder + ', which still held ' + ($Left -join ', '))
265
+ } catch {
266
+ Write-Log ('could not remove ' + $Folder + ': ' + $_.Exception.Message)
267
+ $Unfinished += 'folder'
470
268
  }
471
269
  }
472
- } finally { $Uninstall.Close() }
473
- }
474
-
475
- # Apps & features shows the version the installer's entry names.
476
- function Set-InstalledVersion {
477
- try {
478
- $Version = [string](Get-Content -LiteralPath (Join-Path $Target 'Resources\version.json') -Raw | ConvertFrom-Json).version
479
- $Key = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey($UninstallPath + '\' + $InstallerEntry, $true)
480
- if ($Key) {
481
- if ($Version) { $Key.SetValue('DisplayVersion', $Version); Write-Log ('the uninstall entry names version ' + $Version) }
482
- $Key.Close()
483
- }
484
- } catch { Write-Log ('could not update the uninstall entry: ' + $_.Exception.Message) }
485
- }
486
-
487
- # Moved into this build's app data folder first, out of the way of an update
488
- # installing into the updater's folder meanwhile, and of anything else that
489
- # moves the folders under an identifier.
490
- function Remove-Source([string]$Source) {
491
- if (-not (Test-Path -LiteralPath $Source)) { return }
492
- if ((Get-RunningUnder $Source).Count -gt 0) { Write-Log ('left ' + $Source + ': the app runs from it'); return }
493
- $Doomed = $Source
494
- if ((Split-Path -Leaf $Source) -notlike 'app.removing-*') {
495
- New-Item -ItemType Directory -Force -Path $AppData | Out-Null
496
- $Doomed = Join-Path $AppData ('app.removing-' + (Get-Stamp))
497
- Invoke-Retried { Move-Item -LiteralPath $Source -Destination $Doomed } ('set aside ' + $Source)
498
270
  }
499
- Invoke-Retried { Remove-Item -LiteralPath $Doomed -Recurse -Force } ('remove ' + $Doomed)
500
- Write-Log ('removed ' + $Source)
501
- }
502
271
 
503
- # One script at a time: the app opened in the installer's folder removes the
504
- # copy it came from too, and waits for this one.
505
- $Mutex = New-Object System.Threading.Mutex($false, 'Local\GloomInstallerFolder')
506
- $Locked = $false
507
- try {
508
- New-Item -ItemType Directory -Force -Path (Split-Path -Parent $Log) | Out-Null
509
- try { $Locked = $Mutex.WaitOne($(if ($AfterExit) { 5000 } else { 120000 })) } catch { $Locked = ($_.Exception.GetBaseException() -is [System.Threading.AbandonedMutexException]) }
510
- if ($AfterExit) {
511
- # The app quits only on "started": anything that keeps the move from
512
- # happening is said before, and the app runs on.
513
- if (Test-Path -LiteralPath $Cancel) { Write-Log 'the app stopped waiting before this started'; return }
514
- if (-not $Locked) { Write-Log 'busy: another move of the app runs'; return }
515
- if (-not (Test-Path -LiteralPath (Join-Path $Sources[0] $Launcher))) { Write-Log ('declined: no ' + $Launcher + ' in ' + $Sources[0]); return }
516
- $BuildFiles = New-Object 'System.Collections.Generic.HashSet[string]' ([StringComparer]::OrdinalIgnoreCase)
517
- foreach ($File in @(Get-Files $Sources[0] '')) { [void]$BuildFiles.Add($File) }
518
- # A build that just quit there for an update can take a moment to go.
519
- if (-not (Wait-Until 8 { (Get-AppRunningInTarget).Count -eq 0 })) {
520
- Write-Log ('busy: ' + @(Get-AppRunningInTarget)[0].Path + ' runs'); return
521
- }
522
- try {
523
- $Probe = Join-Path $Target ('.gloom-next-' + (Get-Stamp))
524
- New-Item -ItemType Directory -Path $Probe | Out-Null
525
- [IO.Directory]::Delete($Probe, $false)
526
- } catch { Write-Log ('declined: cannot write in ' + $Target + ': ' + $_.Exception.Message); return }
527
- Write-Log ('started ' + $PID)
528
- # The app and its WebView helpers, by where they run from. Having seen
529
- # "started", the app quits, however long that takes: a slow quit still
530
- # ends with it open again. Only one that stopped waiting for this, and
531
- # wrote $Cancel, runs on, and is left so.
532
- $Deadline = (Get-Date).AddMinutes(30)
533
- while ((Get-RunningUnder $Sources[0]).Count -gt 0 -and -not (Test-Path -LiteralPath $Cancel) -and (Get-Date) -lt $Deadline) {
534
- Start-Sleep -Milliseconds 500
535
- }
536
- if (Test-Path -LiteralPath $Cancel) { Write-Log 'the app stopped waiting; it stays where it is'; return }
537
- if ((Get-RunningUnder $Sources[0]).Count -gt 0) { throw 'the app did not quit' }
538
- $Exited = $true
539
- if (-not (Wait-Until 30 { (Get-AppRunningInTarget).Count -eq 0 })) { throw ('the app runs from ' + $Target) }
540
- Remove-Staging
541
- Install-Build $Sources[0]
542
- Write-Log ('moved ' + $Sources[0] + ' into ' + $Target)
543
- Open-App (Join-Path $Target $Launcher)
544
- Set-InstalledVersion
545
- } else {
546
- if (-not $Locked) { throw 'another move of the app runs' }
547
- Write-Log ('started ' + $PID)
272
+ try { Update-UserPath (Join-Path $Folder 'bin') (Join-Path $App 'bin') } catch {
273
+ Write-Log ('could not move the PATH entry: ' + $_.Exception.Message)
274
+ $Unfinished += 'PATH'
548
275
  }
549
- foreach ($Source in $Sources) {
550
- try {
551
- Update-Shortcuts $Source $Target
552
- Remove-UninstallEntries $Source
553
- Remove-Source $Source
554
- } catch { Write-Log ('could not remove ' + $Source + ': ' + $_.Exception.Message) }
276
+
277
+ if ($Unfinished.Count) {
278
+ Write-Log ('unfinished (' + ($Unfinished -join ', ') + '): the next start tries again')
279
+ exit 2
555
280
  }
556
- Remove-Staging
281
+ Remove-Item -LiteralPath $Pending -Force -ErrorAction SilentlyContinue
557
282
  Write-Log 'done'
558
283
  } catch {
559
- if ($AfterExit) { Write-Log ('move failed: ' + $_.Exception.Message) } else { Write-Log ('removal failed: ' + $_.Exception.Message) }
560
- # The app opens again only if it quit for this, from where it was.
561
- if ($Exited -and -not $Opened) {
562
- $Open = Join-Path $Sources[0] $Launcher
563
- if (-not (Test-Path -LiteralPath $Open)) { $Open = Join-Path $Target $Launcher }
564
- Open-App $Open
565
- }
284
+ Write-Log ('failed: ' + $_.Exception.Message)
285
+ exit 1
566
286
  } finally {
567
- $ErrorActionPreference = 'Continue'
568
287
  if ($Locked) { try { $Mutex.ReleaseMutex() } catch { } }
569
288
  $Mutex.Dispose()
570
- if ($TaskName) { schtasks.exe /delete /tn $TaskName /f | Out-Null }
571
289
  Remove-Item -LiteralPath $PSCommandPath -Force -ErrorAction SilentlyContinue
572
290
  }
573
291
  `;
574
292
 
575
- /** The script that moves the app into the installer's folder or removes the updater's copy, with its paths written in. */
576
- export function installerFolderScript({ target, sources, folder, log, afterExit }: InstallerFolderScript): string {
293
+ /**
294
+ * The script that retires the installer's folder `folder` for the app in
295
+ * `app`, with its paths written in. It removes `pending` once it finished.
296
+ */
297
+ export function installerFolderScript({ folder, app, log, pending }: { folder: string; app: string; log: string; pending: string }): string {
577
298
  const header = [
578
299
  "$ErrorActionPreference = 'Stop'",
579
- `$Target = ${psString(target)}`,
580
- `$Sources = @(${sources.map(psString).join(", ")})`,
581
- `$AppData = ${psString(folder)}`,
300
+ `$Folder = ${psString(folder)}`,
301
+ `$App = ${psString(app)}`,
582
302
  `$Log = ${psString(log)}`,
303
+ `$Pending = ${psString(pending)}`,
583
304
  `$InstallerEntry = ${psString(INSTALLER_ENTRY)}`,
584
- `$AfterExit = ${afterExit ? "$true" : "$false"}`,
585
- `$Cancel = ${psString(afterExit?.cancel ?? "")}`,
586
- `$TaskName = ${psString(afterExit?.taskName ?? "")}`,
587
305
  ];
588
306
  return `${header.join("\n")}\n${SCRIPT_BODY}`;
589
307
  }
590
308
 
591
- /** The tries at moving a build into the installer's folder, kept across starts. */
592
- export interface MoveTries {
593
- /** The build they were for: its version and hash. */
594
- build: string;
595
- /** Tries that failed, or would have: each one the app may have quit for. */
596
- failed: number;
597
- /** When the last one started, in ms. */
598
- last: number;
599
- }
600
-
601
- /** Whether the app may try to move `build` now, after `tries`. */
602
- export function mayTryMove(tries: MoveTries | null, build: string, now: number): boolean {
603
- if (!tries || tries.build !== build) return true;
604
- return tries.failed < MAX_MOVE_TRIES && now - tries.last >= RETRY_AFTER_MS;
309
+ /** The installer's folder a retirement that did not finish left in `path`; null without one. */
310
+ async function readPendingFolder(path: string): Promise<string | null> {
311
+ const text = await readFile(path, "utf8").catch(() => "");
312
+ const folder = text.replace(/^\uFEFF/, "").trim();
313
+ return folder && win32.isAbsolute(folder) ? folder : null;
605
314
  }
606
315
 
607
316
  /**
608
- * `tries` with one more for `build` at `now`. Every try counts as failed when
609
- * it starts: one that works leaves this build's updater folder for good. One
610
- * the script put off because the installer's folder was in use does not.
317
+ * Retires an installer install's folder once the app runs from Electrobun's.
318
+ * Anywhere else, and without such an install or a retirement left
319
+ * unfinished, it returns without writing anything.
611
320
  */
612
- export function noteMoveTry(tries: MoveTries | null, build: string, now: number, counts = true): MoveTries {
613
- const failed = tries?.build === build ? tries.failed : 0;
614
- return { build, failed: failed + (counts ? 1 : 0), last: now };
615
- }
616
-
617
- async function readMoveTries(path: string): Promise<MoveTries | null> {
618
- const value = await readFile(path, "utf8").then((text) => JSON.parse(text) as Partial<MoveTries>, () => null);
619
- if (!value || typeof value.build !== "string" || typeof value.failed !== "number" || typeof value.last !== "number") return null;
620
- return { build: value.build, failed: value.failed, last: value.last };
621
- }
622
-
623
- async function writeMoveTries(path: string, tries: MoveTries): Promise<void> {
624
- await writeFile(path, JSON.stringify(tries), "utf8");
625
- }
626
-
627
- /** The build in `appFolder`, by its version and hash. */
628
- async function buildId(appFolder: string): Promise<string> {
629
- const info = await readFile(win32.join(appFolder, "Resources", "version.json"), "utf8").then((text) => JSON.parse(text) as { version?: unknown; hash?: unknown }, () => null);
630
- return `${String(info?.version ?? "")}+${String(info?.hash ?? "")}`;
631
- }
632
-
633
- /** Where the script, its log and the tries go: the app data folder of this build's identifier. */
634
- function scriptFolder(localAppData: string, channel: string): string {
635
- return win32.join(localAppData, DESKTOP_APP_IDENTIFIER, channel);
636
- }
637
-
638
- async function moveIntoInstallerFolder(
639
- localAppData: string,
640
- running: { folder: string; channel: string },
641
- target: string,
642
- ): Promise<InstallerFolderMove> {
643
- const folder = scriptFolder(localAppData, running.channel);
644
- const triesPath = win32.join(folder, "installer-folder-tries.json");
645
- const build = await buildId(running.folder);
646
- const tries = await readMoveTries(triesPath);
647
- const now = Date.now();
648
- if (!mayTryMove(tries, build, now)) return { kind: "skipped" };
649
- // Noted before the app can quit for it: a try that cannot be noted is not made.
650
- try {
651
- await mkdir(folder, { recursive: true });
652
- await writeMoveTries(triesPath, noteMoveTry(tries, build, now));
653
- } catch (error) {
654
- logFailure("desktop-installer-folder", "Could not note a try at moving the app into the installer's folder")(error);
655
- return { kind: "failed" };
656
- }
657
- const log = win32.join(folder, "installer-folder.log");
658
- const cancel = win32.join(folder, "installer-folder.cancel");
659
- await rm(log, { force: true });
660
- await rm(cancel, { force: true });
661
- const others = (await updaterFolders(localAppData, running.channel)).filter((path) => !samePath(path, running.folder));
662
- const taskName = `GloomInstallerFolder-${now}`;
663
- const script = win32.join(folder, "installer-folder-move.ps1");
664
- try {
665
- await writePowerShellScript(script, installerFolderScript({
666
- target,
667
- sources: [running.folder, ...others],
668
- folder,
669
- log,
670
- afterExit: { cancel, taskName },
671
- }));
672
- const answer = await runScriptAfterExit(script, log, cancel, taskName);
673
- if (answer.kind === "started") return { kind: "relaunching" };
674
- if (answer.kind === "busy") await writeMoveTries(triesPath, noteMoveTry(tries, build, now, false)).catch(() => {});
675
- console.error(`[desktop] the app stays where it is, for now: ${answer.reason}`);
676
- return { kind: "skipped" };
677
- } catch (error) {
678
- logFailure("desktop-installer-folder", "Could not run the script that moves the app into the installer's folder")(error);
679
- return { kind: "failed" };
680
- }
681
- }
321
+ export async function settleInstallerFolder(context: InstallerFolderContext): Promise<InstallerFolderRetirement> {
322
+ if (context.platform !== "win32") return { kind: "none" };
323
+ const localAppData = context.localAppData || win32.join(context.homeDir, "AppData", "Local");
324
+ const running = updaterAppFolder(context.execPath, localAppData);
325
+ if (!running) return { kind: "none" };
326
+ const channelRoot = win32.dirname(running.folder);
327
+ const pending = win32.join(channelRoot, PENDING_FILE);
328
+ const recorded = await (context.readInstallerFolder ?? readInstallerFolderFromRegistry)().catch(() => null)
329
+ ?? await readPendingFolder(pending);
330
+ if (!recorded || samePath(recorded, running.folder)) return { kind: "none" };
331
+ const folder = win32.resolve(recorded);
682
332
 
683
- function removeUpdaterCopies(localAppData: string, channel: string, target: string, sources: string[]): InstallerFolderMove {
684
333
  const timer = setTimeout(() => {
685
- const folder = scriptFolder(localAppData, channel);
686
- const script = win32.join(folder, "installer-folder-cleanup.ps1");
687
- const log = win32.join(folder, "installer-folder-cleanup.log");
688
- void mkdir(folder, { recursive: true })
689
- .then(() => rm(log, { force: true }))
690
- .then(() => writePowerShellScript(script, installerFolderScript({ target, sources, folder, log })))
334
+ const script = win32.join(channelRoot, "installer-folder-retire.ps1");
335
+ const log = win32.join(channelRoot, "installer-folder.log");
336
+ void mkdir(channelRoot, { recursive: true })
337
+ .then(() => writeFile(pending, folder, "utf8"))
338
+ .then(() => writePowerShellScript(script, installerFolderScript({ folder, app: running.folder, log, pending })))
691
339
  .then(() => runScriptInBackground(script))
692
340
  .then((code) => {
693
341
  if (code !== 0) throw new Error(`the script exited with ${code}`);
694
342
  })
695
- .catch(logFailure("desktop-installer-folder", "Could not remove the copy of the app an update left"));
696
- }, REMOVAL_DELAY_MS);
343
+ .catch(logFailure("desktop-installer-folder", "Could not retire the installer's folder"));
344
+ }, RETIRE_DELAY_MS);
697
345
  timer.unref?.();
698
- return { kind: "removing" };
699
- }
700
-
701
- /**
702
- * Puts an installer install's app in the installer's folder. Anywhere else,
703
- * and with nothing left in the updater's folder, it returns without writing
704
- * anything. On `relaunching` the caller quits at once, before any window
705
- * opens.
706
- */
707
- export async function settleInstallerFolder(context: InstallerFolderContext): Promise<InstallerFolderMove> {
708
- if (context.platform !== "win32") return { kind: "none" };
709
- const localAppData = context.localAppData || win32.join(context.homeDir, "AppData", "Local");
710
- const read = context.readInstallerFolder ?? readInstallerFolderFromRegistry;
711
-
712
- const running = updaterAppFolder(context.execPath, localAppData);
713
- if (running) {
714
- const target = await installerFolder(read);
715
- if (!target || samePath(target, running.folder)) return { kind: "none" };
716
- return moveIntoInstallerFolder(localAppData, running, target);
717
- }
718
-
719
- const bin = win32.dirname(context.execPath);
720
- if (win32.basename(bin).toLowerCase() !== "bin") return { kind: "none" };
721
- const app = win32.dirname(bin);
722
- const channel = await buildChannel(app);
723
- const copies = await updaterFolders(localAppData, channel);
724
- const leftovers = (await readdir(app).catch(() => [] as string[])).filter((name) => /^\.gloom-(next|previous)-/i.test(name));
725
- if (copies.length === 0 && leftovers.length === 0) return { kind: "none" };
726
- // Only from the installer's folder: a copy run from anywhere else (a
727
- // portable one) leaves an install from Electrobun's own setup alone.
728
- const target = await installerFolder(read);
729
- if (!target || !samePath(target, app)) return { kind: "none" };
730
- return removeUpdaterCopies(localAppData, channel, target, copies);
346
+ return { kind: "retiring", folder };
731
347
  }