@xiaolikt/ai-vault 0.12.3 → 0.13.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.
@@ -2,7 +2,8 @@
2
2
  //!
3
3
  //! Linux zenity (X11 or Wayland)
4
4
  //! macOS osascript (a native dialog, hidden answer for secrets)
5
- //! Windows PowerShell + WinForms (a native dialog, PasswordChar for secrets)
5
+ //! Windows a small WinForms program of our own (`windows/dialog.cs`), which
6
+ //! follows the display and the user's theme
6
7
  //!
7
8
  //! When no window can open at all, the caller gets `NoUi` and the host UI
8
9
  //! (pi/omp prompt) takes over. Cancel and our own timeout end the prompt here:
@@ -170,421 +171,226 @@ mod mac {
170
171
 
171
172
  // -------------------------------------------------------------- Windows
172
173
 
174
+ // The windows are their own small program: `windows/dialog.cs`, a WinForms
175
+ // binary that `build.rs` compiles with the C# compiler Windows ships. It reads
176
+ // one JSON request on the stdin it inherits (never a console of its own) and
177
+ // writes one JSON answer:
178
+ //
179
+ // {"kind":"password"|"text"|"confirm","title":…,"label":…,"mask":bool,
180
+ // "ok":…,"cancel":…,"show":…,"allow":…,"deny":…}
181
+ // -> {"ok":bool,"cancelled":bool,"value":"…","on":"a screen"|""}
182
+ //
183
+ // It used to be PowerShell scripts, about two seconds a window: loading the
184
+ // assemblies and compiling the DPI helper for every prompt. The program reads
185
+ // the palette from the settings Windows already keeps and opens in about
186
+ // 150 ms. Without it (an older install, a platform package built before it)
187
+ // the scripts below are used again.
188
+
173
189
  #[cfg(target_os = "windows")]
174
190
  mod win {
175
- use super::{Answer, DIALOG_SECONDS};
176
- use std::io::Read;
177
- use std::path::PathBuf;
178
- use std::process::{Command, Stdio};
179
- use std::thread::JoinHandle;
180
- use std::time::{Duration, Instant};
181
-
182
- // WinForms from PowerShell: no extra dependency, and the windows can follow
183
- // the display and the theme. Exit 0 = OK (value on stdout), 1 = cancel,
184
- // 2 = no window.
185
- //
186
- // Four things matter on a real Windows desktop:
187
- // * `[Console]::Out.Write` encodes with the console's code page (936 on a
188
- // Chinese Windows), so a password typed in Chinese arrived as mojibake
189
- // and keyed a store no other machine could open. The value leaves as
190
- // UTF-8 bytes through the raw stream instead.
191
- // * Any error (a policy that forbids Add-Type, WinForms that will not
192
- // load) used to make PowerShell exit 1, which reads as "the user
193
- // cancelled": the host was told not to retry. The scripts trap into
194
- // exit 2, and an exit 1 that printed an error counts the same.
195
- // * Windows turns the IME off in a password edit control (so that a
196
- // candidate window cannot show what is typed), and a Chinese password
197
- // could not be entered at all. The field is an ordinary text box whose
198
- // text is hidden by colour; a bullet per character is drawn over it.
199
- // * `Controls.Add` puts a control at the back, and the label with the
200
- // bullets sat under the box: what was typed looked like nothing. It is
201
- // brought to the front. (DrawToBitmap paints the other way round, so
202
- // only a capture from the screen showed it.)
203
- const PRELUDE: &str = r#"
204
- $ErrorActionPreference = 'Stop'
205
- try {
206
- Add-Type -AssemblyName System.Windows.Forms, System.Drawing
207
- [System.Windows.Forms.Application]::EnableVisualStyles()
208
-
209
- # The window follows the display and the theme, the way a zenity window
210
- # follows the GTK theme: DPI-aware when the display is scaled, a dark
211
- # palette and a dark title bar when the user's apps are dark, and the
212
- # user's accent colour on the one positive button.
213
- $scale = 1.0
214
- $dark = $false
215
- $accent = [System.Drawing.Color]::FromArgb(0, 120, 212)
216
- $native = $false
217
- try {
218
- Add-Type -TypeDefinition 'using System; using System.Runtime.InteropServices; public static class AiVaultWin { [DllImport("user32.dll")] public static extern bool SetProcessDPIAware(); [DllImport("dwmapi.dll")] public static extern int DwmSetWindowAttribute(IntPtr h, int a, ref int v, int s); }'
219
- $native = $true
220
- } catch { }
221
- try {
222
- $dpi = [int](Get-ItemProperty 'HKCU:\Control Panel\Desktop\WindowMetrics' -Name AppliedDPI -ErrorAction Stop).AppliedDPI
223
- if ($dpi -gt 96 -and $native -and [AiVaultWin]::SetProcessDPIAware()) { $scale = $dpi / 96.0 }
224
- } catch { }
225
- try {
226
- $dark = [int](Get-ItemProperty 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Themes\Personalize' -Name AppsUseLightTheme -ErrorAction Stop).AppsUseLightTheme -eq 0
227
- } catch { }
228
- try {
229
- $palette = (Get-ItemProperty 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\Accent' -Name AccentPalette -ErrorAction Stop).AccentPalette
230
- if ($palette -and $palette.Length -ge 4) { $accent = [System.Drawing.Color]::FromArgb($palette[2], $palette[1], $palette[0]) }
231
- } catch { }
232
- $accentHover = [System.Drawing.Color]::FromArgb([Math]::Min(255, $accent.R + 24), [Math]::Min(255, $accent.G + 24), [Math]::Min(255, $accent.B + 24))
233
- $onAccent = if ((0.299 * $accent.R + 0.587 * $accent.G + 0.114 * $accent.B) -gt 150) { [System.Drawing.Color]::Black } else { [System.Drawing.Color]::White }
234
- if ($dark) {
235
- $paper = [System.Drawing.Color]::FromArgb(32, 32, 32)
236
- $card = [System.Drawing.Color]::FromArgb(43, 43, 43)
237
- $hover = [System.Drawing.Color]::FromArgb(54, 54, 54)
238
- $line = [System.Drawing.Color]::FromArgb(66, 66, 66)
239
- $ink = [System.Drawing.Color]::FromArgb(255, 255, 255)
240
- $muted = [System.Drawing.Color]::FromArgb(170, 170, 170)
241
- } else {
242
- $paper = [System.Drawing.Color]::FromArgb(243, 243, 243)
243
- $card = [System.Drawing.Color]::FromArgb(255, 255, 255)
244
- $hover = [System.Drawing.Color]::FromArgb(234, 234, 234)
245
- $line = [System.Drawing.Color]::FromArgb(173, 173, 173)
246
- $ink = [System.Drawing.Color]::FromArgb(26, 26, 26)
247
- $muted = [System.Drawing.Color]::FromArgb(96, 96, 96)
248
- }
249
-
250
- function Px([double]$v) { [int][Math]::Round($v * $scale) }
251
-
252
- # One typeface for Latin and Chinese where there is one; the system's otherwise.
253
- $families = [System.Drawing.FontFamily]::Families | ForEach-Object { $_.Name }
254
- $ui = 'Segoe UI'
255
- foreach ($name in 'Microsoft YaHei UI', 'Microsoft YaHei') {
256
- if ($families -contains $name) { $ui = $name; break }
257
- }
258
- function New-Font([double]$size, [System.Drawing.FontStyle]$style = [System.Drawing.FontStyle]::Regular) {
259
- [System.Drawing.Font]::new($ui, [single]$size, $style, [System.Drawing.GraphicsUnit]::Point)
260
- }
261
-
262
- # A control's shape with round corners. Call it once the control has its size.
263
- function Round-Corners($control, [int]$radius) {
264
- $w = $control.Width; $h = $control.Height; $d = [Math]::Min($radius * 2, [Math]::Min($w, $h))
265
- if ($d -lt 2) { return }
266
- $path = [System.Drawing.Drawing2D.GraphicsPath]::new()
267
- $path.AddArc(0, 0, $d, $d, 180, 90); $path.AddArc($w - $d, 0, $d, $d, 270, 90)
268
- $path.AddArc($w - $d, $h - $d, $d, $d, 0, 90); $path.AddArc(0, $h - $d, $d, $d, 90, 90)
269
- $path.CloseFigure()
270
- $control.Region = [System.Drawing.Region]::new($path)
271
- }
272
-
273
- function New-Window([string]$title) {
274
- $w = [System.Windows.Forms.Form]::new()
275
- $w.Text = $title
276
- $w.FormBorderStyle = 'FixedDialog'; $w.MaximizeBox = $false; $w.MinimizeBox = $false
277
- $w.AutoScaleMode = 'None'
278
- $w.StartPosition = 'CenterScreen'; $w.TopMost = $true
279
- $w.BackColor = $paper; $w.Font = New-Font 10
280
- $w.Icon = [System.Drawing.Icon]::new([System.Drawing.SystemIcons]::Shield, (Px 16), (Px 16))
281
- $w.ClientSize = [System.Drawing.Size]::new((Px 460), 0)
282
- if ($dark -and $native) {
283
- $on = 1 # DWMWA_USE_IMMERSIVE_DARK_MODE: the title bar follows the theme
284
- [void][AiVaultWin]::DwmSetWindowAttribute($w.Handle, 20, [ref]$on, 4)
285
- }
286
- return $w
287
- }
288
-
289
- # A label that wraps, as tall as its text needs.
290
- function Add-Text($w, [string]$text, [int]$top) {
291
- $lbl = [System.Windows.Forms.Label]::new()
292
- $lbl.Text = $text; $lbl.Font = New-Font 10.5; $lbl.ForeColor = $ink
293
- $lbl.Left = Px 24; $lbl.Top = $top; $lbl.Width = (Px 460) - (Px 48)
294
- $g = $lbl.CreateGraphics()
295
- $lbl.Height = [int]($g.MeasureString($text, $lbl.Font, $lbl.Width).Height) + (Px 2)
296
- $g.Dispose()
297
- $w.Controls.Add($lbl)
298
- return $lbl
299
- }
300
-
301
- # kind: accent (the one positive action), outline (an equal partner), quiet
302
- # (text only, like the Cancel of a GNOME dialog).
303
- function New-Button($w, [string]$text, [string]$result, [string]$kind) {
304
- $b = [System.Windows.Forms.Button]::new()
305
- $b.Text = $text; $b.DialogResult = $result; $b.FlatStyle = 'Flat'; $b.Tag = $kind
306
- $b.Size = [System.Drawing.Size]::new((Px 96), (Px 34))
307
- $b.Font = New-Font 10 ([System.Drawing.FontStyle]::Bold)
308
- if ($kind -eq 'accent') {
309
- $b.FlatAppearance.BorderSize = 0; $b.BackColor = $accent; $b.ForeColor = $onAccent
310
- Round-Corners $b (Px 6)
311
- } elseif ($kind -eq 'outline') {
312
- $b.FlatAppearance.BorderSize = 1; $b.FlatAppearance.BorderColor = $line
313
- $b.BackColor = $card; $b.ForeColor = $ink
314
- Round-Corners $b (Px 6)
315
- } else {
316
- $b.FlatAppearance.BorderSize = 0; $b.BackColor = $paper; $b.ForeColor = $ink
317
- $b.Font = New-Font 10
318
- }
319
- $b.Add_MouseEnter({ if ($this.Tag -eq 'accent') { $this.BackColor = $accentHover } else { $this.BackColor = $hover } })
320
- $b.Add_MouseLeave({ if ($this.Tag -eq 'accent') { $this.BackColor = $accent } elseif ($this.Tag -eq 'quiet') { $this.BackColor = $paper } else { $this.BackColor = $card } })
321
- $w.Controls.Add($b)
322
- return $b
323
- }
324
-
325
- # A row at the bottom, flush right, in the order given (left to right): as
326
- # in a GNOME dialog, the affirmative button is the rightmost one.
327
- function Add-Buttons($w, $buttons, [int]$top) {
328
- $x = $w.ClientSize.Width - (Px 24)
329
- for ($i = $buttons.Count - 1; $i -ge 0; $i--) {
330
- $b = $buttons[$i]
331
- $b.Left = $x - $b.Width; $b.Top = $top
332
- $x = $b.Left - (Px 8)
191
+ use super::DIALOG_SECONDS;
192
+
193
+ /// Where `build.rs` leaves the dialog program, beside the CLI.
194
+ const PROGRAM: &str = "dialog.exe";
195
+
196
+ /// What a window is for.
197
+ #[derive(Clone, Copy, PartialEq)]
198
+ enum Kind {
199
+ /// A password: bullets over a field that keeps the IME, and a link to show it.
200
+ Secret,
201
+ /// One line of text, in the clear.
202
+ Text,
203
+ /// Yes or no, with both buttons weighing the same.
204
+ Confirm,
205
+ }
206
+
207
+ impl Kind {
208
+ fn name(self) -> &'static str {
209
+ match self {
210
+ Kind::Secret => "password",
211
+ Kind::Text => "text",
212
+ Kind::Confirm => "confirm",
213
+ }
333
214
  }
334
- $w.ClientSize = [System.Drawing.Size]::new((Px 460), $top + (Px 34) + (Px 24))
335
- }
336
- "#;
337
-
338
- const PREAMBLE: &str = r#"
339
- $f = New-Window $env:AI_VAULT_DLG_TITLE
340
- $secret = $env:AI_VAULT_DLG_SECRET -eq '1'
341
-
342
- $lbl = Add-Text $f $env:AI_VAULT_DLG_TEXT (Px 22)
343
-
344
- # The field: a panel draws a border that scales with the display and turns
345
- # to the accent colour while the field has the focus; the text box fills it.
346
- $field = [System.Windows.Forms.Panel]::new()
347
- $field.BackColor = $line
348
- $field.Left = Px 24; $field.Top = $lbl.Bottom + (Px 12); $field.Width = (Px 460) - (Px 48); $field.Height = Px 40
349
- Round-Corners $field (Px 6)
350
- $inner = [System.Windows.Forms.Panel]::new()
351
- $inner.BackColor = $card; $inner.Dock = 'Fill'
352
- $field.Padding = [System.Windows.Forms.Padding]::new((Px 1))
353
- $inner.Add_SizeChanged({ Round-Corners $inner (Px 5) })
354
- $field.Controls.Add($inner)
355
- $f.Controls.Add($field)
356
-
357
- $box = [System.Windows.Forms.TextBox]::new()
358
- $box.Font = New-Font 11
359
- $box.BorderStyle = 'None'; $box.AutoSize = $false
360
- $box.BackColor = $card
361
- if ($secret) { $box.ForeColor = $card }
362
- $box.Height = $box.PreferredHeight
363
- $inner.Padding = [System.Windows.Forms.Padding]::new((Px 12), 0, (Px 12), 0)
364
- $inner.Controls.Add($box)
365
-
366
- # Over the box, a label with one bullet per typed character and a caret of
367
- # its own: the box keeps its text (and the IME), and shows none of it.
368
- $mask = [System.Windows.Forms.Label]::new()
369
- $mask.BackColor = $card; $mask.Font = New-Font 12; $mask.ForeColor = $ink
370
- $mask.TextAlign = 'MiddleLeft'
371
- $mask.Padding = [System.Windows.Forms.Padding]::new((Px 12), 0, 0, 0)
372
- $mask.Visible = $secret
373
- $caret = [System.Windows.Forms.Label]::new()
374
- $caret.BackColor = $ink; $caret.Width = [Math]::Max(1, (Px 1)); $caret.Height = Px 18
375
- $caret.Visible = $false
376
- if ($secret) { $inner.Controls.Add($mask); $inner.Controls.Add($caret) }
377
- # Controls.Add puts a control at the BACK: the mask and the caret have to be
378
- # in front of the box, or the box paints over them.
379
- $mask.BringToFront(); $caret.BringToFront()
380
- function Layout-Field {
381
- $box.Left = $inner.Padding.Left
382
- $box.Top = [int](($inner.ClientSize.Height - $box.Height) / 2)
383
- $box.Width = $inner.ClientSize.Width - $inner.Padding.Horizontal
384
- $mask.Bounds = $inner.ClientRectangle
385
- Update-Mask
386
- }
387
- $inner.Add_SizeChanged({ Round-Corners $inner (Px 5); Layout-Field })
388
-
389
- $show = [System.Windows.Forms.LinkLabel]::new()
390
- $show.Text = $env:AI_VAULT_DLG_SHOW
391
- $show.Font = New-Font 9.5
392
- $show.LinkColor = $accent; $show.ActiveLinkColor = $accentHover; $show.VisitedLinkColor = $accent
393
- $show.LinkBehavior = [System.Windows.Forms.LinkBehavior]::HoverUnderline
394
- $show.Visible = $secret
395
- $f.Controls.Add($show)
396
- $show.Width = $show.PreferredWidth + (Px 4); $show.Height = $show.PreferredHeight
397
- $show.Left = $field.Right - $show.Width; $show.Top = $field.Bottom + (Px 10)
398
-
399
- $shown = $false
400
- function Set-Field-Look {
401
- if ($shown -or -not $secret) { $box.ForeColor = $ink; $mask.Visible = $false }
402
- else { $box.ForeColor = $card; $mask.Visible = $true }
403
- $caret.Visible = ($box.Focused -and -not $shown -and $secret)
404
- Update-Mask
405
- }
406
- function Update-Mask {
407
- $mask.Text = ('● ' * $box.TextLength).TrimEnd()
408
- $typed = if ($mask.Text) { $mask.Text + ' ' } else { '' }
409
- $width = [System.Windows.Forms.TextRenderer]::MeasureText($typed, $mask.Font).Width
410
- $caret.Left = $mask.Left + [Math]::Min($mask.Padding.Left + $width, $mask.Width - $caret.Width)
411
- $caret.Top = $mask.Top + [int](($mask.Height - $caret.Height) / 2)
412
- }
413
- $box.Add_TextChanged({ Update-Mask })
414
- $box.Add_GotFocus({ $caret.Visible = (-not $shown -and $secret); $field.BackColor = $accent })
415
- $box.Add_LostFocus({ $caret.Visible = $false; $field.BackColor = $line })
416
- $mask.Add_Click({ $box.Focus() })
417
- $show.Add_LinkClicked({ $shown = -not $shown; Set-Field-Look; [void]$box.Focus() })
418
- $blink = [System.Windows.Forms.Timer]::new(); $blink.Interval = 530
419
- $blink.Add_Tick({ if ($box.Focused -and $secret -and -not $shown) { $caret.Visible = -not $caret.Visible } })
420
- $blink.Start()
421
-
422
- $cancel = New-Button $f $env:AI_VAULT_DLG_CANCEL 'Cancel' 'quiet'
423
- $ok = New-Button $f $env:AI_VAULT_DLG_OK 'OK' 'accent'
424
- $bottom = $(if ($secret) { $show.Bottom } else { $field.Bottom }) + (Px 20)
425
- Add-Buttons $f @($cancel, $ok) $bottom
426
- $f.AcceptButton = $ok; $f.CancelButton = $cancel
427
- $f.Add_Shown({ Layout-Field; [void]$box.Focus() })
428
-
429
- if ($f.ShowDialog() -eq 'OK') {
430
- $bytes = [System.Text.Encoding]::UTF8.GetBytes($box.Text)
431
- $stdout = [Console]::OpenStandardOutput()
432
- $stdout.Write($bytes, 0, $bytes.Length); $stdout.Flush()
433
- exit 0
434
- }
435
- exit 1
436
- } catch {
437
- [Console]::Error.Write($_)
438
- exit 2
439
- }
440
- "#;
441
-
442
- // A window of its own rather than a MessageBox: the buttons then say
443
- // Allow and Deny in the user's language, and it matches the other one.
444
- // Both weigh the same, and Deny has the focus: Enter is the safe answer
445
- // from wherever the focus starts, Esc too. Allow takes a click, or Tab
446
- // and Enter on it.
447
- const CONFIRM: &str = r#"
448
- $f = New-Window $env:AI_VAULT_DLG_TITLE
449
- $lbl = Add-Text $f $env:AI_VAULT_DLG_TEXT (Px 22)
450
-
451
- $deny = New-Button $f $env:AI_VAULT_DLG_DENY 'Cancel' 'outline'
452
- $allow = New-Button $f $env:AI_VAULT_DLG_ALLOW 'OK' 'outline'
453
- Add-Buttons $f @($deny, $allow) ($lbl.Bottom + (Px 24))
454
- $f.AcceptButton = $deny
455
- $f.CancelButton = $deny
456
- $f.Add_Shown({ $deny.Focus() })
457
-
458
- if ($f.ShowDialog() -eq 'OK') { exit 0 }
459
- exit 1
460
- } catch {
461
- [Console]::Error.Write($_)
462
- exit 2
463
- }
464
- "#;
215
+ }
465
216
 
466
- /// Windows PowerShell by its full path. The window takes the master
467
- /// password, so the bare name is not left for a PATH entry or a working
468
- /// directory to answer to.
469
- fn powershell_exe() -> PathBuf {
470
- std::env::var_os("SystemRoot")
471
- .map(PathBuf::from)
472
- .map(|root| root.join("System32").join("WindowsPowerShell").join("v1.0").join("powershell.exe"))
473
- .unwrap_or_else(|| PathBuf::from("powershell"))
217
+ /// The words in the window, in the user's language.
218
+ struct Words {
219
+ title: String,
220
+ label: String,
221
+ ok: &'static str,
222
+ cancel: &'static str,
223
+ show: &'static str,
224
+ allow: &'static str,
225
+ deny: &'static str,
226
+ }
227
+
228
+ fn words(title: &str, label: &str) -> Words {
229
+ Words {
230
+ title: title.to_string(),
231
+ label: label.to_string(),
232
+ ok: crate::i18n::tr("OK", "确定"),
233
+ cancel: crate::i18n::tr("Cancel", "取消"),
234
+ show: crate::i18n::tr("Show", "显示"),
235
+ allow: crate::i18n::tr("Allow", "允许"),
236
+ deny: crate::i18n::tr("Deny", "拒绝"),
237
+ }
474
238
  }
475
239
 
476
- struct Out {
477
- spawned: bool,
478
- code: i32,
479
- stdout: String,
480
- stderr: String,
240
+ fn json_string(text: &str) -> String {
241
+ let mut out = String::with_capacity(text.len() + 2);
242
+ out.push('"');
243
+ for c in text.chars() {
244
+ match c {
245
+ '"' => out.push_str("\\\""),
246
+ '\\' => out.push_str("\\\\"),
247
+ '\n' => out.push_str("\\n"),
248
+ '\r' => out.push_str("\\r"),
249
+ '\t' => out.push_str("\\t"),
250
+ c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
251
+ c => out.push(c),
252
+ }
253
+ }
254
+ out.push('"');
255
+ out
256
+ }
257
+
258
+ fn request(kind: Kind, w: &Words, mask: bool) -> String {
259
+ format!(
260
+ "{{\"kind\":{},\"title\":{},\"label\":{},\"mask\":{},\"ok\":{},\"cancel\":{},\"show\":{},\"allow\":{},\"deny\":{}}}",
261
+ json_string(kind.name()),
262
+ json_string(&w.title),
263
+ json_string(&w.label),
264
+ mask,
265
+ json_string(w.ok),
266
+ json_string(w.cancel),
267
+ json_string(w.show),
268
+ json_string(w.allow),
269
+ json_string(w.deny),
270
+ )
481
271
  }
482
272
 
483
- /// Read a pipe to its end on its own thread: a chatty start must not block
484
- /// on a full pipe while the window is open.
485
- fn drain<R: Read + Send + 'static>(pipe: Option<R>) -> JoinHandle<String> {
486
- std::thread::spawn(move || {
487
- let mut bytes = Vec::new();
488
- if let Some(mut pipe) = pipe {
489
- let _ = pipe.read_to_end(&mut bytes);
273
+ /// A string field out of the program's flat JSON answer.
274
+ fn field(json: &str, key: &str) -> Option<String> {
275
+ let at = json.find(&format!("\"{key}\":"))? + key.len() + 3;
276
+ let rest = &json[at..];
277
+ let Some(body) = rest.strip_prefix('"') else {
278
+ if rest.starts_with("true") {
279
+ return Some("true".to_string());
490
280
  }
491
- String::from_utf8_lossy(&bytes).into_owned()
492
- })
493
- }
494
-
495
- fn powershell(body: &str, title: &str, text: &str, secret: bool) -> Out {
496
- let script = format!("{PRELUDE}{body}");
497
- let mut cmd = Command::new(powershell_exe());
498
- cmd.args(["-NoProfile", "-NonInteractive", "-STA", "-Command", &script])
499
- .env("AI_VAULT_DLG_TITLE", title)
500
- .env("AI_VAULT_DLG_TEXT", text)
501
- .env("AI_VAULT_DLG_SECRET", if secret { "1" } else { "0" })
502
- .env("AI_VAULT_DLG_OK", crate::i18n::tr("OK", "确定"))
503
- .env("AI_VAULT_DLG_CANCEL", crate::i18n::tr("Cancel", "取消"))
504
- .env("AI_VAULT_DLG_SHOW", crate::i18n::tr("Show", "显示"))
505
- .env("AI_VAULT_DLG_ALLOW", crate::i18n::tr("Allow", "允许"))
506
- .env("AI_VAULT_DLG_DENY", crate::i18n::tr("Deny", "拒绝"))
507
- .stdin(Stdio::null())
508
- .stdout(Stdio::piped())
509
- .stderr(Stdio::piped());
510
- let unspawned = || Out {
511
- spawned: false,
512
- code: 127,
513
- stdout: String::new(),
514
- stderr: String::new(),
515
- };
516
- let mut child = match cmd.spawn() {
517
- Ok(child) => child,
518
- Err(_) => return unspawned(),
281
+ if rest.starts_with("false") {
282
+ return Some("false".to_string());
283
+ }
284
+ return None;
519
285
  };
520
- let stdout = drain(child.stdout.take());
521
- let stderr = drain(child.stderr.take());
286
+ let mut out = String::new();
287
+ let mut chars = body.chars();
288
+ while let Some(c) = chars.next() {
289
+ match c {
290
+ '"' => return Some(out),
291
+ '\\' => match chars.next() {
292
+ Some('n') => out.push('\n'),
293
+ Some('r') => out.push('\r'),
294
+ Some('t') => out.push('\t'),
295
+ Some('u') => {
296
+ let hex: String = chars.by_ref().take(4).collect();
297
+ if let Ok(code) = u32::from_str_radix(&hex, 16) {
298
+ if let Some(c) = char::from_u32(code) {
299
+ out.push(c);
300
+ }
301
+ }
302
+ }
303
+ Some(c) => out.push(c),
304
+ None => break,
305
+ },
306
+ c => out.push(c),
307
+ }
308
+ }
309
+ None
310
+ }
311
+
312
+ /// The dialog program, next to this executable, when `build.rs` put it there.
313
+ fn program() -> Option<std::path::PathBuf> {
314
+ let exe = std::env::current_exe().ok()?;
315
+ let beside = exe.parent()?.join(PROGRAM);
316
+ beside.is_file().then_some(beside)
317
+ }
318
+
319
+ fn wait(child: &mut std::process::Child) -> Option<bool> {
320
+ use std::time::{Duration, Instant};
522
321
  // A window nobody answers must not hold the caller forever, exactly as
523
- // zenity's --timeout does not: after DIALOG_SECONDS it is ours to close,
524
- // and closing it is a cancel. (Windows has no `giving up after`.)
322
+ // zenity's --timeout does not. Closing it is a cancel.
525
323
  let deadline = Instant::now() + Duration::from_secs(DIALOG_SECONDS as u64);
526
- let status = loop {
324
+ loop {
527
325
  match child.try_wait() {
528
- Ok(Some(status)) => break Some(status),
529
- Ok(None) if Instant::now() < deadline => std::thread::sleep(Duration::from_millis(100)),
326
+ Ok(Some(_)) => return Some(true),
327
+ Ok(None) if Instant::now() < deadline => std::thread::sleep(Duration::from_millis(50)),
530
328
  _ => {
531
329
  let _ = child.kill();
532
330
  let _ = child.wait();
533
- break None;
331
+ return None;
534
332
  }
535
333
  }
536
- };
537
- let stdout = stdout.join().unwrap_or_default();
538
- let stderr = stderr.join().unwrap_or_default();
539
- match status {
540
- None => Out { spawned: true, code: 1, stdout, stderr },
541
- Some(status) => Out { spawned: true, code: status.code().unwrap_or(-1), stdout, stderr },
542
334
  }
543
335
  }
544
336
 
545
- /// Exit 1 with nothing on stderr is the user's cancel. Anything else means
546
- /// no answer came out of a window: our own exit 2, a script PowerShell
547
- /// could not even parse (exit 1, with the error on stderr), or a crash.
548
- fn failed(out: &Out) -> bool {
549
- !out.spawned || (out.code != 0 && out.code != 1) || (out.code == 1 && !out.stderr.trim().is_empty())
550
- }
551
-
552
- pub fn prompt_secret(title: &str, label: &str) -> Answer<String> {
553
- let out = powershell(PREAMBLE, title, label, true);
554
- if failed(&out) {
555
- return Answer::NoUi;
337
+ /// Ask the dialog program. `Ok(None)` means it could not run or reported no
338
+ /// screen: the caller decides what to do instead.
339
+ fn ask(kind: Kind, w: &Words, mask: bool) -> Option<super::Answer<String>> {
340
+ use std::io::{Read, Write};
341
+ use std::process::{Command, Stdio};
342
+ use super::Answer;
343
+ let program = program()?;
344
+ let mut child = Command::new(&program)
345
+ .stdin(Stdio::piped())
346
+ .stdout(Stdio::piped())
347
+ .stderr(Stdio::piped())
348
+ .spawn()
349
+ .ok()?;
350
+ let body = request(kind, w, mask);
351
+ if let Some(mut stdin) = child.stdin.take() {
352
+ let _ = stdin.write_all(body.as_bytes());
556
353
  }
557
- if out.code != 0 || out.stdout.is_empty() {
558
- return Answer::Cancelled;
354
+ if wait(&mut child).is_none() {
355
+ return Some(Answer::Cancelled);
559
356
  }
560
- Answer::Value(out.stdout)
561
- }
562
-
563
- pub fn prompt_text(title: &str, label: &str) -> Answer<String> {
564
- let out = powershell(PREAMBLE, title, label, false);
565
- if failed(&out) {
566
- return Answer::NoUi;
357
+ let mut out = String::new();
358
+ child.stdout.take()?.read_to_string(&mut out).ok()?;
359
+ if field(&out, "on").as_deref() == Some("") {
360
+ return None; // no screen
567
361
  }
568
- if out.code != 0 {
569
- return Answer::Cancelled;
362
+ match field(&out, "ok").as_deref() {
363
+ Some("true") => Some(Answer::Value(field(&out, "value").unwrap_or_default())),
364
+ _ => Some(Answer::Cancelled),
570
365
  }
571
- Answer::Value(out.stdout)
572
366
  }
573
367
 
574
- pub fn confirm(title: &str, message: &str) -> Answer<bool> {
575
- let out = powershell(CONFIRM, title, message, false);
576
- if failed(&out) {
577
- return Answer::NoUi;
368
+ pub fn prompt_secret(title: &str, label: &str, revealable: bool) -> super::Answer<String> {
369
+ ask(Kind::Secret, &words(title, label), revealable).unwrap_or(super::Answer::NoUi)
370
+ }
371
+
372
+ pub fn prompt_text(title: &str, label: &str) -> super::Answer<String> {
373
+ ask(Kind::Text, &words(title, label), false).unwrap_or(super::Answer::NoUi)
374
+ }
375
+
376
+ pub fn confirm(title: &str, message: &str) -> super::Answer<bool> {
377
+ match ask(Kind::Confirm, &words(title, message), false) {
378
+ Some(super::Answer::Value(_)) => super::Answer::Value(true),
379
+ Some(super::Answer::Cancelled) => super::Answer::Cancelled,
380
+ Some(super::Answer::NoUi) | None => super::Answer::NoUi,
578
381
  }
579
- Answer::Value(out.code == 0)
580
382
  }
581
383
 
582
- /// Whether this process may show a window at all. Only the interactive
583
- /// session's window station (`WinSta0`) is visible; a service, a scheduled
584
- /// task that runs without a logged-on user, or an sshd session gets a
585
- /// `Service-0x0-…` station instead, where a dialog would open onto a
586
- /// desktop nobody sees and never be answered.
384
+ /// Whether this process may show a window at all: a window station that is
385
+ /// not visible, or an input desktop it cannot open, means a service, a
386
+ /// scheduled task without a logged-on user, or an sshd session.
587
387
  pub fn has_display() -> bool {
388
+ use std::process::{Command, Stdio};
389
+ if let Some(program) = program() {
390
+ if let Ok(out) = Command::new(program).arg("--probe").stdin(Stdio::null()).output() {
391
+ return String::from_utf8_lossy(&out.stdout) == "on";
392
+ }
393
+ }
588
394
  // USEROBJECTFLAGS, as user32 lays it out: two BOOLs and a DWORD.
589
395
  #[repr(C)]
590
396
  #[derive(Default)]
@@ -605,9 +411,13 @@ try {
605
411
  len: u32,
606
412
  needed: *mut u32,
607
413
  ) -> i32;
414
+ fn OpenInputDesktop(flags: u32, inherit: i32, access: u32) -> *mut core::ffi::c_void;
415
+ fn CloseDesktop(desktop: *mut core::ffi::c_void) -> i32;
608
416
  }
609
- // SAFETY: two Win32 queries against the calling process's own window
610
- // station; every pointer is either handed out by the OS or a live local.
417
+ const DESKTOP_READOBJECTS: u32 = 0x0001;
418
+ // SAFETY: Win32 queries against the calling process's own window station
419
+ // and the input desktop; every pointer is handed out by the OS or is a
420
+ // live local.
611
421
  unsafe {
612
422
  let station = GetProcessWindowStation();
613
423
  if station.is_null() {
@@ -622,7 +432,15 @@ try {
622
432
  std::mem::size_of::<UserObjectFlags>() as u32,
623
433
  &mut needed,
624
434
  );
625
- ok != 0 && flags.dw_flags & WSF_VISIBLE != 0
435
+ if ok == 0 || flags.dw_flags & WSF_VISIBLE == 0 {
436
+ return false;
437
+ }
438
+ let desktop = OpenInputDesktop(0, 0, DESKTOP_READOBJECTS);
439
+ if desktop.is_null() {
440
+ return false;
441
+ }
442
+ CloseDesktop(desktop);
443
+ true
626
444
  }
627
445
  }
628
446
  }
@@ -772,14 +590,20 @@ pub fn for_dialog(value: &str, max: usize) -> String {
772
590
  }
773
591
 
774
592
  /// Secret entry. Empty and cancel are both "no value".
775
- pub fn prompt_secret(title: &str, label: &str) -> Answer<String> {
593
+ /// A password. `revealable` puts a link in the window that shows what was typed:
594
+ /// right for a master password (a typo is expensive), not for an entry's own
595
+ /// password (it is read back with `vault_get` anyway).
596
+ /// `revealable` is read on Windows only (the "show what was typed" link);
597
+ /// zenity and osascript have no such link, so the parameter is unused there.
598
+ #[cfg_attr(not(target_os = "windows"), allow(unused_variables))]
599
+ pub fn prompt_secret(title: &str, label: &str, revealable: bool) -> Answer<String> {
776
600
  #[cfg(target_os = "macos")]
777
601
  {
778
602
  return mac::prompt_secret(title, label);
779
603
  }
780
604
  #[cfg(target_os = "windows")]
781
605
  {
782
- return win::prompt_secret(title, label);
606
+ return win::prompt_secret(title, label, revealable);
783
607
  }
784
608
  #[cfg(not(any(target_os = "macos", target_os = "windows")))]
785
609
  prompt_secret_zenity(title, label)