import 'package:flutter/material.dart'; import 'terminal_browser_keys_stub.dart' if (dart.library.js_interop) 'terminal_browser_keys_web.dart' as impl; /// What captures the browser's own keys: the Keyboard Lock API in full /// screen on the web ([impl]); nothing elsewhere. abstract class TerminalBrowserKeysBackend { /// Whether this browser can lock its keys (Chrome and Edge can; Firefox, /// Safari and native builds cannot). bool get supported; /// Enters full screen and locks the keys; false if the browser refused. Future lock(); /// Unlocks the keys and leaves full screen. Future unlock(); /// Called when the browser ends the capture itself (Esc held, full screen /// left another way). set onReleased(void Function() callback); } /// "Capture browser keys": while on, the page is full screen with the /// keyboard locked, so Ctrl+W, Ctrl+T, Ctrl+N, Ctrl+Tab and the like reach /// the terminal instead of closing or opening browser tabs. Holding Esc /// ends it, as the browser requires. A no-op where [supported] is false. class TerminalBrowserKeys extends ChangeNotifier { TerminalBrowserKeys({TerminalBrowserKeysBackend? backend}) : _backend = backend ?? impl.TerminalBrowserKeysPlatform() { _backend.onReleased = _released; } /// The app's one capture (the page is full screen once at most). static TerminalBrowserKeys instance = TerminalBrowserKeys(); final TerminalBrowserKeysBackend _backend; bool _active = false; bool get supported => _backend.supported; bool get active => _active; /// Starts the capture; false where unsupported or refused. Future capture() async { if (!supported) return false; if (_active) return true; final locked = await _backend.lock(); if (locked != _active) { _active = locked; notifyListeners(); } return locked; } /// Ends the capture. Future release() async { if (!_active) return; _active = false; notifyListeners(); await _backend.unlock(); } void _released() { if (!_active) return; _active = false; notifyListeners(); } } /// The menu label for [keys]' toggle. String terminalBrowserKeysLabel(TerminalBrowserKeys keys) => keys.active ? 'Release browser keys' : 'Capture browser keys'; /// Turns the capture on or off from a menu, saying what happened. Future toggleTerminalBrowserKeys( BuildContext context, [ TerminalBrowserKeys? keys, ]) async { final capture = keys ?? TerminalBrowserKeys.instance; final messenger = ScaffoldMessenger.maybeOf(context); if (capture.active) { await capture.release(); return; } final captured = await capture.capture(); messenger ?..hideCurrentSnackBar() ..showSnackBar( SnackBar( content: Text( captured ? 'Browser keys such as Ctrl+W go to the terminal. ' 'Hold Esc to leave full screen.' : 'This browser did not let the page capture its keys.', ), ), ); }