feat(webview): close the web views when both apps are parked and idle
- after 3 min without protocol calls, holds, dialogs, subscribers or a login the views and the environment close, the browser processes exit - the next call brings them back at the park page and waits for it before running; a reload request wakes that app at the full app - browser exit while asleep does not trigger a restart Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@@ -19,6 +19,13 @@ impl Subscribers {
19
19
}
20
20
}
21
21
22
pub(crate) fn has_live(&mut self) -> bool {
23
for sinks in self.sinks.values_mut() {
24
sinks.retain(|sink| !sink.is_closed());
25
}
26
self.sinks.values().any(|sinks| !sinks.is_empty())
27
}
28
22
29
/// Ends every event stream, so subscribers attach again to the new webviews.
23
30
pub(crate) fn clear(&mut self) {
24
31
self.sinks.clear();
@@ -19,6 +19,13 @@ impl Subscribers {19
}19
}20
}20
}21
21
22
pub(crate) fn has_live(&mut self) -> bool {23
for sinks in self.sinks.values_mut() {24
sinks.retain(|sink| !sink.is_closed());25
}26
self.sinks.values().any(|sinks| !sinks.is_empty())27
}28
22
/// Ends every event stream, so subscribers attach again to the new webviews.29
/// Ends every event stream, so subscribers attach again to the new webviews.23
pub(crate) fn clear(&mut self) {30
pub(crate) fn clear(&mut self) {24
self.sinks.clear();31
self.sinks.clear();@@ -25,6 +25,7 @@ use crate::cdp_failure::{CallContext, failure_reason, tab_state};
25
25
use crate::fanout::Subscribers;
26
26
use crate::host_dialog::{self, Dialog};
27
27
use crate::park::{ParkDecision, ParkGate};
28
use crate::sleep::{Activity, Sleep};
28
29
use crate::transport::{HostState, UiRequest, WebViewTransport};
29
30
use crate::{BROWSER_ARGUMENTS, FORWARDED_EVENTS};
30
31
@@ -35,6 +36,8 @@ const LOGIN_TIMER: usize = 1;
35
36
const LOGIN_SHOW_DELAY_MS: u32 = 4000;
36
37
const PARK_TIMER: usize = 2;
37
38
const PARK_DELAY_MS: u32 = 60_000;
39
const SLEEP_TIMER: usize = 3;
40
const SLEEP_CHECK_MS: u32 = 60_000;
38
41
const LOGIN_PROMPT_INTERVAL: Duration = Duration::from_secs(600);
39
42
const WINDOW_WIDTH: i32 = 1100;
40
43
const WINDOW_HEIGHT: i32 = 800;
@@ -62,6 +65,7 @@ pub(crate) struct Shared {
62
65
requests: mpsc::Receiver<UiRequest>,
63
66
restarting: Cell<bool>,
64
67
last_login_prompt: Cell<Option<Instant>>,
68
sleep: RefCell<Sleep<TabCommand>>,
65
69
}
66
70
67
71
thread_local! {
@@ -123,9 +127,11 @@ fn run(
123
127
requests,
124
128
restarting: Cell::new(false),
125
129
last_login_prompt: Cell::new(None),
130
sleep: RefCell::new(Sleep::default()),
126
131
});
127
132
SHARED.with(|slot| *slot.borrow_mut() = Some(shared.clone()));
128
133
load(&shared);
134
unsafe { SetTimer(Some(shared.windows[&App::Teams]), SLEEP_TIMER, SLEEP_CHECK_MS, None) };
129
135
let mut message = MSG::default();
130
136
while unsafe { GetMessageW(&mut message, None, 0, 0) }.as_bool() {
131
137
unsafe {
@@ -169,7 +175,7 @@ fn create_windows(title: &str) -> windows::core::Result<HashMap<App, HWND>> {
169
175
}
170
176
171
177
fn load(shared: &Rc<Shared>) {
172
match create_views(shared) {
178
match create_views(shared, |app| app.start_url()) {
173
179
Ok(()) => shared.state.send_modify(|state| {
174
180
state.ready = true;
175
181
state.failure = None;
@@ -181,11 +187,11 @@ fn load(shared: &Rc<Shared>) {
181
187
}
182
188
}
183
189
184
fn create_views(shared: &Rc<Shared>) -> std::result::Result<(), String> {
190
fn create_views(shared: &Rc<Shared>, first_url: impl Fn(App) -> &'static str) -> std::result::Result<(), String> {
185
191
let environment = create_environment(&shared.config.user_data_folder)?;
186
192
*shared.environment.borrow_mut() = Some(environment.clone());
187
193
for app in App::ALL {
188
let view = create_view(shared, &environment, app)
194
let view = create_view(shared, &environment, app, first_url(app))
189
195
.map_err(|error| format!("{app} webview: {error}"))?;
190
196
shared.views.borrow_mut().insert(app, view);
191
197
}
@@ -230,6 +236,7 @@ fn create_view(
230
236
shared: &Rc<Shared>,
231
237
environment: &ICoreWebView2Environment,
232
238
app: App,
239
first_url: &str,
233
240
) -> windows::core::Result<View> {
234
241
let window = shared.windows[&app];
235
242
let (sender, receiver) = mpsc::channel();
@@ -264,7 +271,7 @@ fn create_view(
264
271
watch_loads(&webview, app)?;
265
272
watch_failures(&webview, app)?;
266
273
forward_events(&webview, app)?;
267
unsafe { webview.Navigate(&HSTRING::from(app.start_url())) }?;
274
unsafe { webview.Navigate(&HSTRING::from(first_url)) }?;
268
275
Ok(View {
269
276
controller,
270
277
webview,
@@ -289,6 +296,10 @@ fn watch_loads(webview: &ICoreWebView2, app: App) -> windows::core::Result<()> {
289
296
return Ok(());
290
297
};
291
298
let url = current_url(&shared, app);
299
let waiting = shared.sleep.borrow_mut().loaded(app);
300
for command in waiting {
301
call(&shared, app, command);
302
}
292
303
if is_running_app(app, &url) {
293
304
unsafe { SetTimer(Some(shared.windows[&app]), PARK_TIMER, PARK_DELAY_MS, None) };
294
305
if shared.park_gate.borrow().held(app) {
@@ -319,7 +330,10 @@ fn park(shared: &Shared, app: App) {
319
330
}
320
331
321
332
/// A held tab stays loaded for the whole call, so its renderer is told to shrink instead of being parked.
322
fn hold(shared: &Shared, app: App, held: bool) {
333
fn hold(shared: &Rc<Shared>, app: App, held: bool) {
334
if held {
335
wake_views(shared, None);
336
}
323
337
shared.park_gate.borrow_mut().hold(app, held);
324
338
if held
325
339
&& let Some(webview) = webview_of(shared, app)
@@ -358,6 +372,9 @@ fn watch_failures(webview: &ICoreWebView2, app: App) -> windows::core::Result<()
358
372
};
359
373
let mut kind = COREWEBVIEW2_PROCESS_FAILED_KIND::default();
360
374
unsafe { arguments.ProcessFailedKind(&mut kind) }?;
375
if shared.sleep.borrow().asleep() {
376
return Ok(());
377
}
361
378
if kind == COREWEBVIEW2_PROCESS_FAILED_KIND_BROWSER_PROCESS_EXITED {
362
379
if !shared.restarting.replace(true) {
363
380
unsafe {
@@ -453,6 +470,7 @@ fn drain(shared: &Rc<Shared>) {
453
470
}
454
471
}
455
472
UiRequest::OpenDialog { id, spec, events } => {
473
wake_views(shared, None);
456
474
host_dialog::open(shared, id, spec, events)
457
475
}
458
476
UiRequest::Dialog { id, command } => host_dialog::run(shared, id, command),
@@ -460,7 +478,12 @@ fn drain(shared: &Rc<Shared>) {
460
478
}
461
479
}
462
480
463
fn call(shared: &Shared, app: App, command: TabCommand) {
481
fn call(shared: &Rc<Shared>, app: App, command: TabCommand) {
482
shared.sleep.borrow_mut().touch(Instant::now());
483
wake_views(shared, None);
484
let Some(command) = shared.sleep.borrow_mut().admit(app, command) else {
485
return;
486
};
464
487
let Some(webview) = webview_of(shared, app) else {
465
488
return command.respond(Err(Error::Cdp("webview is restarting".into())));
466
489
};
@@ -518,7 +541,11 @@ fn describe_failure(app: App, method: &str, parameters_bytes: usize, hresult: &s
518
541
failure_reason(&context, hresult, json)
519
542
}
520
543
521
fn wake(shared: &Shared, app: App) {
544
fn wake(shared: &Rc<Shared>, app: App) {
545
if shared.sleep.borrow().asleep() {
546
wake_views(shared, Some(app));
547
return;
548
}
522
549
let Some(webview) = webview_of(shared, app) else {
523
550
return;
524
551
};
@@ -562,6 +589,10 @@ fn show(shared: &Shared, app: App) {
562
589
563
590
fn restart(shared: &Rc<Shared>) {
564
591
shared.state.send_modify(|state| state.ready = false);
592
let stranded = shared.sleep.borrow_mut().reset();
593
for command in stranded {
594
command.respond(Err(Error::Cdp("webview is restarting".into())));
595
}
565
596
shared.subscribers.borrow_mut().clear();
566
597
shared.park_gate.borrow_mut().forget_commands();
567
598
host_dialog::close_all(shared);
@@ -580,6 +611,49 @@ fn restart(shared: &Rc<Shared>) {
580
611
shared.restarting.set(false);
581
612
}
582
613
614
/// Both apps parked and unused for a while: the web views close so the browser processes exit.
615
fn maybe_sleep(shared: &Rc<Shared>) {
616
let urls: Vec<String> = App::ALL.iter().map(|&app| current_url(shared, app)).collect();
617
let activity = Activity {
618
restarting: shared.restarting.get(),
619
all_parked: App::ALL.iter().zip(&urls).all(|(app, url)| app.is_park_url(url)),
620
login_pending: urls.iter().any(|url| is_login_url(url)),
621
held: App::ALL.iter().any(|&app| shared.park_gate.borrow().held(app)),
622
in_flight: App::ALL.iter().any(|&app| shared.park_gate.borrow().in_flight(app) > 0),
623
dialogs_open: !shared.dialogs.borrow().is_empty(),
624
subscribed: shared.subscribers.borrow_mut().has_live(),
625
};
626
if !shared.sleep.borrow().should_sleep(activity, Instant::now()) {
627
return;
628
}
629
shared.sleep.borrow_mut().fall_asleep();
630
let views: Vec<View> = shared.views.borrow_mut().drain().map(|(_, view)| view).collect();
631
for view in views {
632
unsafe {
633
let _ = view.controller.Close();
634
}
635
}
636
*shared.environment.borrow_mut() = None;
637
}
638
639
/// Brings the web views back at the park page, or `full` at the running app when it was asked to reload.
640
fn wake_views(shared: &Rc<Shared>, full: Option<App>) {
641
if !shared.sleep.borrow_mut().wake() {
642
return;
643
}
644
let outcome = create_views(shared, |app| if Some(app) == full { app.start_url() } else { app.park_url() });
645
if let Err(reason) = outcome {
646
let stranded = shared.sleep.borrow_mut().reset();
647
for command in stranded {
648
command.respond(Err(Error::Cdp(reason.clone())));
649
}
650
shared.state.send_modify(|state| {
651
state.ready = false;
652
state.failure = Some(reason);
653
});
654
}
655
}
656
583
657
pub(crate) fn fit(window: HWND, controller: &ICoreWebView2Controller) {
584
658
let mut bounds = RECT::default();
585
659
unsafe {
@@ -626,6 +700,7 @@ extern "system" fn window_procedure(
626
700
shared.last_login_prompt.set(Some(Instant::now()));
627
701
}
628
702
}
703
WM_TIMER if wparam.0 == SLEEP_TIMER => maybe_sleep(&shared),
629
704
WM_TIMER if wparam.0 == PARK_TIMER => {
630
705
unsafe {
631
706
let _ = KillTimer(Some(window), PARK_TIMER);
@@ -25,6 +25,7 @@ use crate::cdp_failure::{CallContext, failure_reason, tab_state};25
use crate::fanout::Subscribers;25
use crate::fanout::Subscribers;26
use crate::host_dialog::{self, Dialog};26
use crate::host_dialog::{self, Dialog};27
use crate::park::{ParkDecision, ParkGate};27
use crate::park::{ParkDecision, ParkGate};28
use crate::sleep::{Activity, Sleep};28
use crate::transport::{HostState, UiRequest, WebViewTransport};29
use crate::transport::{HostState, UiRequest, WebViewTransport};29
use crate::{BROWSER_ARGUMENTS, FORWARDED_EVENTS};30
use crate::{BROWSER_ARGUMENTS, FORWARDED_EVENTS};30
31
@@ -35,6 +36,8 @@ const LOGIN_TIMER: usize = 1;35
const LOGIN_SHOW_DELAY_MS: u32 = 4000;36
const LOGIN_SHOW_DELAY_MS: u32 = 4000;36
const PARK_TIMER: usize = 2;37
const PARK_TIMER: usize = 2;37
const PARK_DELAY_MS: u32 = 60_000;38
const PARK_DELAY_MS: u32 = 60_000;39
const SLEEP_TIMER: usize = 3;40
const SLEEP_CHECK_MS: u32 = 60_000;38
const LOGIN_PROMPT_INTERVAL: Duration = Duration::from_secs(600);41
const LOGIN_PROMPT_INTERVAL: Duration = Duration::from_secs(600);39
const WINDOW_WIDTH: i32 = 1100;42
const WINDOW_WIDTH: i32 = 1100;40
const WINDOW_HEIGHT: i32 = 800;43
const WINDOW_HEIGHT: i32 = 800;@@ -62,6 +65,7 @@ pub(crate) struct Shared {62
requests: mpsc::Receiver<UiRequest>,65
requests: mpsc::Receiver<UiRequest>,63
restarting: Cell<bool>,66
restarting: Cell<bool>,64
last_login_prompt: Cell<Option<Instant>>,67
last_login_prompt: Cell<Option<Instant>>,68
sleep: RefCell<Sleep<TabCommand>>,65
}69
}66
70
67
thread_local! {71
thread_local! {@@ -123,9 +127,11 @@ fn run(123
requests,127
requests,124
restarting: Cell::new(false),128
restarting: Cell::new(false),125
last_login_prompt: Cell::new(None),129
last_login_prompt: Cell::new(None),130
sleep: RefCell::new(Sleep::default()),126
});131
});127
SHARED.with(|slot| *slot.borrow_mut() = Some(shared.clone()));132
SHARED.with(|slot| *slot.borrow_mut() = Some(shared.clone()));128
load(&shared);133
load(&shared);134
unsafe { SetTimer(Some(shared.windows[&App::Teams]), SLEEP_TIMER, SLEEP_CHECK_MS, None) };129
let mut message = MSG::default();135
let mut message = MSG::default();130
while unsafe { GetMessageW(&mut message, None, 0, 0) }.as_bool() {136
while unsafe { GetMessageW(&mut message, None, 0, 0) }.as_bool() {131
unsafe {137
unsafe {@@ -169,7 +175,7 @@ fn create_windows(title: &str) -> windows::core::Result<HashMap<App, HWND>> {169
}175
}170
176
171
fn load(shared: &Rc<Shared>) {177
fn load(shared: &Rc<Shared>) {172
match create_views(shared) {178
match create_views(shared, |app| app.start_url()) {173
Ok(()) => shared.state.send_modify(|state| {179
Ok(()) => shared.state.send_modify(|state| {174
state.ready = true;180
state.ready = true;175
state.failure = None;181
state.failure = None;@@ -181,11 +187,11 @@ fn load(shared: &Rc<Shared>) {181
}187
}182
}188
}183
189
184
fn create_views(shared: &Rc<Shared>) -> std::result::Result<(), String> {190
fn create_views(shared: &Rc<Shared>, first_url: impl Fn(App) -> &'static str) -> std::result::Result<(), String> {185
let environment = create_environment(&shared.config.user_data_folder)?;191
let environment = create_environment(&shared.config.user_data_folder)?;186
*shared.environment.borrow_mut() = Some(environment.clone());192
*shared.environment.borrow_mut() = Some(environment.clone());187
for app in App::ALL {193
for app in App::ALL {188
let view = create_view(shared, &environment, app)194
let view = create_view(shared, &environment, app, first_url(app))189
.map_err(|error| format!("{app} webview: {error}"))?;195
.map_err(|error| format!("{app} webview: {error}"))?;190
shared.views.borrow_mut().insert(app, view);196
shared.views.borrow_mut().insert(app, view);191
}197
}@@ -230,6 +236,7 @@ fn create_view(230
shared: &Rc<Shared>,236
shared: &Rc<Shared>,231
environment: &ICoreWebView2Environment,237
environment: &ICoreWebView2Environment,232
app: App,238
app: App,239
first_url: &str,233
) -> windows::core::Result<View> {240
) -> windows::core::Result<View> {234
let window = shared.windows[&app];241
let window = shared.windows[&app];235
let (sender, receiver) = mpsc::channel();242
let (sender, receiver) = mpsc::channel();@@ -264,7 +271,7 @@ fn create_view(264
watch_loads(&webview, app)?;271
watch_loads(&webview, app)?;265
watch_failures(&webview, app)?;272
watch_failures(&webview, app)?;266
forward_events(&webview, app)?;273
forward_events(&webview, app)?;267
unsafe { webview.Navigate(&HSTRING::from(app.start_url())) }?;274
unsafe { webview.Navigate(&HSTRING::from(first_url)) }?;268
Ok(View {275
Ok(View {269
controller,276
controller,270
webview,277
webview,@@ -289,6 +296,10 @@ fn watch_loads(webview: &ICoreWebView2, app: App) -> windows::core::Result<()> {289
return Ok(());296
return Ok(());290
};297
};291
let url = current_url(&shared, app);298
let url = current_url(&shared, app);299
let waiting = shared.sleep.borrow_mut().loaded(app);300
for command in waiting {301
call(&shared, app, command);302
}292
if is_running_app(app, &url) {303
if is_running_app(app, &url) {293
unsafe { SetTimer(Some(shared.windows[&app]), PARK_TIMER, PARK_DELAY_MS, None) };304
unsafe { SetTimer(Some(shared.windows[&app]), PARK_TIMER, PARK_DELAY_MS, None) };294
if shared.park_gate.borrow().held(app) {305
if shared.park_gate.borrow().held(app) {@@ -319,7 +330,10 @@ fn park(shared: &Shared, app: App) {319
}330
}320
331
321
/// A held tab stays loaded for the whole call, so its renderer is told to shrink instead of being parked.332
/// A held tab stays loaded for the whole call, so its renderer is told to shrink instead of being parked.322
fn hold(shared: &Shared, app: App, held: bool) {333
fn hold(shared: &Rc<Shared>, app: App, held: bool) {334
if held {335
wake_views(shared, None);336
}323
shared.park_gate.borrow_mut().hold(app, held);337
shared.park_gate.borrow_mut().hold(app, held);324
if held338
if held325
&& let Some(webview) = webview_of(shared, app)339
&& let Some(webview) = webview_of(shared, app)@@ -358,6 +372,9 @@ fn watch_failures(webview: &ICoreWebView2, app: App) -> windows::core::Result<()358
};372
};359
let mut kind = COREWEBVIEW2_PROCESS_FAILED_KIND::default();373
let mut kind = COREWEBVIEW2_PROCESS_FAILED_KIND::default();360
unsafe { arguments.ProcessFailedKind(&mut kind) }?;374
unsafe { arguments.ProcessFailedKind(&mut kind) }?;375
if shared.sleep.borrow().asleep() {376
return Ok(());377
}361
if kind == COREWEBVIEW2_PROCESS_FAILED_KIND_BROWSER_PROCESS_EXITED {378
if kind == COREWEBVIEW2_PROCESS_FAILED_KIND_BROWSER_PROCESS_EXITED {362
if !shared.restarting.replace(true) {379
if !shared.restarting.replace(true) {363
unsafe {380
unsafe {@@ -453,6 +470,7 @@ fn drain(shared: &Rc<Shared>) {453
}470
}454
}471
}455
UiRequest::OpenDialog { id, spec, events } => {472
UiRequest::OpenDialog { id, spec, events } => {473
wake_views(shared, None);456
host_dialog::open(shared, id, spec, events)474
host_dialog::open(shared, id, spec, events)457
}475
}458
UiRequest::Dialog { id, command } => host_dialog::run(shared, id, command),476
UiRequest::Dialog { id, command } => host_dialog::run(shared, id, command),@@ -460,7 +478,12 @@ fn drain(shared: &Rc<Shared>) {460
}478
}461
}479
}462
480
463
fn call(shared: &Shared, app: App, command: TabCommand) {481
fn call(shared: &Rc<Shared>, app: App, command: TabCommand) {482
shared.sleep.borrow_mut().touch(Instant::now());483
wake_views(shared, None);484
let Some(command) = shared.sleep.borrow_mut().admit(app, command) else {485
return;486
};464
let Some(webview) = webview_of(shared, app) else {487
let Some(webview) = webview_of(shared, app) else {465
return command.respond(Err(Error::Cdp("webview is restarting".into())));488
return command.respond(Err(Error::Cdp("webview is restarting".into())));466
};489
};@@ -518,7 +541,11 @@ fn describe_failure(app: App, method: &str, parameters_bytes: usize, hresult: &s518
failure_reason(&context, hresult, json)541
failure_reason(&context, hresult, json)519
}542
}520
543
521
fn wake(shared: &Shared, app: App) {544
fn wake(shared: &Rc<Shared>, app: App) {545
if shared.sleep.borrow().asleep() {546
wake_views(shared, Some(app));547
return;548
}522
let Some(webview) = webview_of(shared, app) else {549
let Some(webview) = webview_of(shared, app) else {523
return;550
return;524
};551
};@@ -562,6 +589,10 @@ fn show(shared: &Shared, app: App) {562
589
563
fn restart(shared: &Rc<Shared>) {590
fn restart(shared: &Rc<Shared>) {564
shared.state.send_modify(|state| state.ready = false);591
shared.state.send_modify(|state| state.ready = false);592
let stranded = shared.sleep.borrow_mut().reset();593
for command in stranded {594
command.respond(Err(Error::Cdp("webview is restarting".into())));595
}565
shared.subscribers.borrow_mut().clear();596
shared.subscribers.borrow_mut().clear();566
shared.park_gate.borrow_mut().forget_commands();597
shared.park_gate.borrow_mut().forget_commands();567
host_dialog::close_all(shared);598
host_dialog::close_all(shared);@@ -580,6 +611,49 @@ fn restart(shared: &Rc<Shared>) {580
shared.restarting.set(false);611
shared.restarting.set(false);581
}612
}582
613
614
/// Both apps parked and unused for a while: the web views close so the browser processes exit.615
fn maybe_sleep(shared: &Rc<Shared>) {616
let urls: Vec<String> = App::ALL.iter().map(|&app| current_url(shared, app)).collect();617
let activity = Activity {618
restarting: shared.restarting.get(),619
all_parked: App::ALL.iter().zip(&urls).all(|(app, url)| app.is_park_url(url)),620
login_pending: urls.iter().any(|url| is_login_url(url)),621
held: App::ALL.iter().any(|&app| shared.park_gate.borrow().held(app)),622
in_flight: App::ALL.iter().any(|&app| shared.park_gate.borrow().in_flight(app) > 0),623
dialogs_open: !shared.dialogs.borrow().is_empty(),624
subscribed: shared.subscribers.borrow_mut().has_live(),625
};626
if !shared.sleep.borrow().should_sleep(activity, Instant::now()) {627
return;628
}629
shared.sleep.borrow_mut().fall_asleep();630
let views: Vec<View> = shared.views.borrow_mut().drain().map(|(_, view)| view).collect();631
for view in views {632
unsafe {633
let _ = view.controller.Close();634
}635
}636
*shared.environment.borrow_mut() = None;637
}638
639
/// Brings the web views back at the park page, or `full` at the running app when it was asked to reload.640
fn wake_views(shared: &Rc<Shared>, full: Option<App>) {641
if !shared.sleep.borrow_mut().wake() {642
return;643
}644
let outcome = create_views(shared, |app| if Some(app) == full { app.start_url() } else { app.park_url() });645
if let Err(reason) = outcome {646
let stranded = shared.sleep.borrow_mut().reset();647
for command in stranded {648
command.respond(Err(Error::Cdp(reason.clone())));649
}650
shared.state.send_modify(|state| {651
state.ready = false;652
state.failure = Some(reason);653
});654
}655
}656
583
pub(crate) fn fit(window: HWND, controller: &ICoreWebView2Controller) {657
pub(crate) fn fit(window: HWND, controller: &ICoreWebView2Controller) {584
let mut bounds = RECT::default();658
let mut bounds = RECT::default();585
unsafe {659
unsafe {@@ -626,6 +700,7 @@ extern "system" fn window_procedure(626
shared.last_login_prompt.set(Some(Instant::now()));700
shared.last_login_prompt.set(Some(Instant::now()));627
}701
}628
}702
}703
WM_TIMER if wparam.0 == SLEEP_TIMER => maybe_sleep(&shared),629
WM_TIMER if wparam.0 == PARK_TIMER => {704
WM_TIMER if wparam.0 == PARK_TIMER => {630
unsafe {705
unsafe {631
let _ = KillTimer(Some(window), PARK_TIMER);706
let _ = KillTimer(Some(window), PARK_TIMER);@@ -15,6 +15,8 @@ mod host_dialog;
15
15
mod main_embed;
16
16
#[cfg(any(windows, test))]
17
17
mod park;
18
#[cfg(any(windows, test))]
19
mod sleep;
18
20
#[cfg(windows)]
19
21
mod transport;
20
22
@@ -15,6 +15,8 @@ mod host_dialog;15
mod main_embed;15
mod main_embed;16
#[cfg(any(windows, test))]16
#[cfg(any(windows, test))]17
mod park;17
mod park;18
#[cfg(any(windows, test))]19
mod sleep;18
#[cfg(windows)]20
#[cfg(windows)]19
mod transport;21
mod transport;20
22
@@ -0,0 +1,141 @@
1
use std::collections::{HashMap, HashSet};
2
use std::time::{Duration, Instant};
3
4
use session::App;
5
6
pub(crate) const SLEEP_AFTER: Duration = Duration::from_secs(180);
7
8
/// What keeps the web views running; any of these blocks closing them.
9
#[derive(Debug, Clone, Copy, Default)]
10
pub(crate) struct Activity {
11
pub restarting: bool,
12
pub all_parked: bool,
13
pub login_pending: bool,
14
pub held: bool,
15
pub in_flight: bool,
16
pub dialogs_open: bool,
17
pub subscribed: bool,
18
}
19
20
/// The web views close once both apps are parked and idle, and come back on the next protocol call, at the park page.
21
#[derive(Debug)]
22
pub(crate) struct Sleep<C> {
23
asleep: bool,
24
last_use: Instant,
25
loading: HashSet<App>,
26
queued: HashMap<App, Vec<C>>,
27
}
28
29
impl<C> Default for Sleep<C> {
30
fn default() -> Self {
31
Sleep { asleep: false, last_use: Instant::now(), loading: HashSet::new(), queued: HashMap::new() }
32
}
33
}
34
35
impl<C> Sleep<C> {
36
pub(crate) fn touch(&mut self, now: Instant) {
37
self.last_use = now;
38
}
39
40
pub(crate) fn asleep(&self) -> bool {
41
self.asleep
42
}
43
44
pub(crate) fn should_sleep(&self, activity: Activity, now: Instant) -> bool {
45
!self.asleep
46
&& self.loading.is_empty()
47
&& now.duration_since(self.last_use) >= SLEEP_AFTER
48
&& activity.all_parked
49
&& !(activity.restarting
50
|| activity.login_pending
51
|| activity.held
52
|| activity.in_flight
53
|| activity.dialogs_open
54
|| activity.subscribed)
55
}
56
57
pub(crate) fn fall_asleep(&mut self) {
58
self.asleep = true;
59
}
60
61
/// Answers whether the views have to be created now.
62
pub(crate) fn wake(&mut self) -> bool {
63
if !self.asleep {
64
return false;
65
}
66
self.asleep = false;
67
self.loading = App::ALL.into_iter().collect();
68
true
69
}
70
71
/// A call for an app that is still loading its page waits; `Some` hands it back to run now.
72
pub(crate) fn admit(&mut self, app: App, command: C) -> Option<C> {
73
if self.loading.contains(&app) {
74
self.queued.entry(app).or_default().push(command);
75
None
76
} else {
77
Some(command)
78
}
79
}
80
81
pub(crate) fn loaded(&mut self, app: App) -> Vec<C> {
82
self.loading.remove(&app);
83
self.queued.remove(&app).unwrap_or_default()
84
}
85
86
pub(crate) fn reset(&mut self) -> Vec<C> {
87
self.asleep = false;
88
self.loading.clear();
89
self.queued.drain().flat_map(|(_, commands)| commands).collect()
90
}
91
}
92
93
#[cfg(test)]
94
mod tests {
95
use super::*;
96
97
fn idle() -> Activity {
98
Activity { all_parked: true, ..Activity::default() }
99
}
100
101
#[test]
102
fn parked_idle_views_sleep_after_the_quiet_period() {
103
let sleep: Sleep<u32> = Sleep::default();
104
let start = sleep.last_use;
105
assert!(!sleep.should_sleep(idle(), start + SLEEP_AFTER - Duration::from_secs(1)));
106
assert!(sleep.should_sleep(idle(), start + SLEEP_AFTER));
107
}
108
109
#[test]
110
fn a_running_app_a_login_or_any_user_keeps_them_awake() {
111
let sleep: Sleep<u32> = Sleep::default();
112
let later = sleep.last_use + SLEEP_AFTER;
113
assert!(!sleep.should_sleep(Activity { all_parked: false, ..idle() }, later));
114
for blocked in [
115
Activity { login_pending: true, ..idle() },
116
Activity { held: true, ..idle() },
117
Activity { in_flight: true, ..idle() },
118
Activity { dialogs_open: true, ..idle() },
119
Activity { subscribed: true, ..idle() },
120
Activity { restarting: true, ..idle() },
121
] {
122
assert!(!sleep.should_sleep(blocked, later), "{blocked:?}");
123
}
124
}
125
126
#[test]
127
fn calls_wait_for_the_page_after_waking_and_run_in_order() {
128
let mut sleep = Sleep::default();
129
sleep.fall_asleep();
130
assert!(sleep.wake());
131
assert!(!sleep.wake());
132
assert_eq!(sleep.admit(App::Teams, 1), None);
133
assert_eq!(sleep.admit(App::Teams, 2), None);
134
assert_eq!(sleep.admit(App::Outlook, 3), None);
135
assert!(!sleep.should_sleep(idle(), sleep.last_use + SLEEP_AFTER));
136
assert_eq!(sleep.loaded(App::Teams), vec![1, 2]);
137
assert_eq!(sleep.admit(App::Teams, 4), Some(4));
138
assert_eq!(sleep.reset(), vec![3]);
139
assert_eq!(sleep.admit(App::Outlook, 5), Some(5));
140
}
141
}
@@ -0,0 +1,141 @@1
use std::collections::{HashMap, HashSet};2
use std::time::{Duration, Instant};3
4
use session::App;5
6
pub(crate) const SLEEP_AFTER: Duration = Duration::from_secs(180);7
8
/// What keeps the web views running; any of these blocks closing them.9
#[derive(Debug, Clone, Copy, Default)]10
pub(crate) struct Activity {11
pub restarting: bool,12
pub all_parked: bool,13
pub login_pending: bool,14
pub held: bool,15
pub in_flight: bool,16
pub dialogs_open: bool,17
pub subscribed: bool,18
}19
20
/// The web views close once both apps are parked and idle, and come back on the next protocol call, at the park page.21
#[derive(Debug)]22
pub(crate) struct Sleep<C> {23
asleep: bool,24
last_use: Instant,25
loading: HashSet<App>,26
queued: HashMap<App, Vec<C>>,27
}28
29
impl<C> Default for Sleep<C> {30
fn default() -> Self {31
Sleep { asleep: false, last_use: Instant::now(), loading: HashSet::new(), queued: HashMap::new() }32
}33
}34
35
impl<C> Sleep<C> {36
pub(crate) fn touch(&mut self, now: Instant) {37
self.last_use = now;38
}39
40
pub(crate) fn asleep(&self) -> bool {41
self.asleep42
}43
44
pub(crate) fn should_sleep(&self, activity: Activity, now: Instant) -> bool {45
!self.asleep46
&& self.loading.is_empty()47
&& now.duration_since(self.last_use) >= SLEEP_AFTER48
&& activity.all_parked49
&& !(activity.restarting50
|| activity.login_pending51
|| activity.held52
|| activity.in_flight53
|| activity.dialogs_open54
|| activity.subscribed)55
}56
57
pub(crate) fn fall_asleep(&mut self) {58
self.asleep = true;59
}60
61
/// Answers whether the views have to be created now.62
pub(crate) fn wake(&mut self) -> bool {63
if !self.asleep {64
return false;65
}66
self.asleep = false;67
self.loading = App::ALL.into_iter().collect();68
true69
}70
71
/// A call for an app that is still loading its page waits; `Some` hands it back to run now.72
pub(crate) fn admit(&mut self, app: App, command: C) -> Option<C> {73
if self.loading.contains(&app) {74
self.queued.entry(app).or_default().push(command);75
None76
} else {77
Some(command)78
}79
}80
81
pub(crate) fn loaded(&mut self, app: App) -> Vec<C> {82
self.loading.remove(&app);83
self.queued.remove(&app).unwrap_or_default()84
}85
86
pub(crate) fn reset(&mut self) -> Vec<C> {87
self.asleep = false;88
self.loading.clear();89
self.queued.drain().flat_map(|(_, commands)| commands).collect()90
}91
}92
93
#[cfg(test)]94
mod tests {95
use super::*;96
97
fn idle() -> Activity {98
Activity { all_parked: true, ..Activity::default() }99
}100
101
#[test]102
fn parked_idle_views_sleep_after_the_quiet_period() {103
let sleep: Sleep<u32> = Sleep::default();104
let start = sleep.last_use;105
assert!(!sleep.should_sleep(idle(), start + SLEEP_AFTER - Duration::from_secs(1)));106
assert!(sleep.should_sleep(idle(), start + SLEEP_AFTER));107
}108
109
#[test]110
fn a_running_app_a_login_or_any_user_keeps_them_awake() {111
let sleep: Sleep<u32> = Sleep::default();112
let later = sleep.last_use + SLEEP_AFTER;113
assert!(!sleep.should_sleep(Activity { all_parked: false, ..idle() }, later));114
for blocked in [115
Activity { login_pending: true, ..idle() },116
Activity { held: true, ..idle() },117
Activity { in_flight: true, ..idle() },118
Activity { dialogs_open: true, ..idle() },119
Activity { subscribed: true, ..idle() },120
Activity { restarting: true, ..idle() },121
] {122
assert!(!sleep.should_sleep(blocked, later), "{blocked:?}");123
}124
}125
126
#[test]127
fn calls_wait_for_the_page_after_waking_and_run_in_order() {128
let mut sleep = Sleep::default();129
sleep.fall_asleep();130
assert!(sleep.wake());131
assert!(!sleep.wake());132
assert_eq!(sleep.admit(App::Teams, 1), None);133
assert_eq!(sleep.admit(App::Teams, 2), None);134
assert_eq!(sleep.admit(App::Outlook, 3), None);135
assert!(!sleep.should_sleep(idle(), sleep.last_use + SLEEP_AFTER));136
assert_eq!(sleep.loaded(App::Teams), vec![1, 2]);137
assert_eq!(sleep.admit(App::Teams, 4), Some(4));138
assert_eq!(sleep.reset(), vec![3]);139
assert_eq!(sleep.admit(App::Outlook, 5), Some(5));140
}141
}