restoreWorkspace method
Restores what persistWorkspace saved, or an empty list when nothing is stored — a first launch is not a failure.
Implementation
Future<List<DVTabWorkspaceController>> restoreWorkspace(String name) async {
final int started = performance.mark();
final stored = await shared.getReserved(_workspaceKey(name));
if (stored is! DVJsonList) return <DVTabWorkspaceController>[];
final restored = <DVTabWorkspaceController>[];
final dropped = <String>[];
for (final entry in stored.value) {
if (entry is! DVJsonMap) continue;
final tabs = entry.value['tabs'];
if (tabs is! DVJsonList) continue;
// Kept paths and their old positions together, because the stored active
// index counts the tabs that were saved. Dropping one before it and
// keeping the number selects a different tab -- silently, since it is
// still a valid index.
final kept = <String>[];
final oldIndexOf = <int>[];
for (var i = 0; i < tabs.value.length; i++) {
final path = tabs.value[i];
if (path is! DVJsonString) continue;
if (knownRoutes.isNotEmpty && !knownRoutes.contains(path.value)) {
dropped.add(path.value);
continue;
}
kept.add(path.value);
oldIndexOf.add(i);
}
// Only when dropping emptied it. A workspace that was saved with no
// tabs is a real empty workspace and comes back as one; a workspace
// whose every route has since gone comes back not at all, because an
// empty one there looks like the user closed everything themselves.
if (kept.isEmpty && tabs.value.isNotEmpty) continue;
final controller = DVTabWorkspaceController(
tabs: <DVTab>[for (final String path in kept) DVTab(DVRouteTarget(path))],
);
final active = entry.value['active'];
if (active is DVJsonNumber) {
final int wanted = active.value.toInt();
var index = oldIndexOf.indexOf(wanted);
// The tab that was active is gone, so the nearest surviving one.
if (index < 0) {
index = oldIndexOf.where((int old) => old < wanted).length;
if (index >= kept.length) index = kept.length - 1;
}
controller.activate(index);
}
restored.add(controller);
}
if (dropped.isNotEmpty) {
// info, not a warning: a page removed between releases is normal, and
// the workspace comes back without it rather than not coming back.
await _reportRestoreDrop(name, dropped);
}
performance.recordRestoreFrom(
started,
name: name,
tabs: restored.fold(0, (int n, DVTabWorkspaceController w) => n + w.tabs.length),
);
return restored;
}