From 491c253c7b7ad146c243bf81784bbafff8d7c6f8 Mon Sep 17 00:00:00 2001 From: Clement Guyon Date: Mon, 23 Nov 2026 14:44:10 +0100 Subject: [PATCH 01/18] Test fakes: record modifier-only shortcut registrations and settings opens --- .../test/helpers/dictation_fakes.dart | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/apps/app_macos/test/helpers/dictation_fakes.dart b/apps/app_macos/test/helpers/dictation_fakes.dart index 62aa0f2..037608c 100644 --- a/apps/app_macos/test/helpers/dictation_fakes.dart +++ b/apps/app_macos/test/helpers/dictation_fakes.dart @@ -49,6 +49,22 @@ final class FakeGlobalShortcutChannel extends GlobalShortcutChannel { return registerResult; } + /// Raccourcis « modificateurs seuls » posés (masque Carbon), dans l'ordre + /// (`registerModifiers`, voir global_shortcut_modifier_only_test.dart). + final List registeredModifiers = []; + + /// Résultat des prochains `registerModifiers` (faux : refusé, Accessibilité + /// absente). + bool registerModifiersResult = true; + + // ponytail: absent de GlobalShortcutChannel tant que le raccourci + // modificateurs seuls n'est pas codé ; devient alors une vraie surcharge. + @override + Future registerModifiers({required int modifiers}) async { + registeredModifiers.add(modifiers); + return registerModifiersResult; + } + @override Future unregister() async => unregisterCalls++; @@ -84,9 +100,15 @@ final class FakeTextOutputChannel extends TextOutputChannel { .map((String e) => e.substring('copy:'.length)) .toList(); + /// Ouvertures du volet Accessibilité des Réglages Système. + int openSettingsCalls = 0; + @override Future isAccessibilityTrusted() async => trusted; + @override + Future openAccessibilitySettings() async => openSettingsCalls++; + @override Future copy(String text) async { log.add('copy:$text'); From 89a06f7783086df1e41b9dd4b6b81868339d3d79 Mon Sep 17 00:00:00 2001 From: Clement Guyon Date: Mon, 23 Nov 2026 14:44:10 +0100 Subject: [PATCH 02/18] Spec: store a modifier-only dictation shortcut in prefs.json --- ...difier_only_shortcut_preferences_test.dart | 148 ++++++++++++++++++ 1 file changed, 148 insertions(+) create mode 100644 apps/app_macos/test/application/services/dictation/modifier_only_shortcut_preferences_test.dart diff --git a/apps/app_macos/test/application/services/dictation/modifier_only_shortcut_preferences_test.dart b/apps/app_macos/test/application/services/dictation/modifier_only_shortcut_preferences_test.dart new file mode 100644 index 0000000..cff8ad1 --- /dev/null +++ b/apps/app_macos/test/application/services/dictation/modifier_only_shortcut_preferences_test.dart @@ -0,0 +1,148 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:ici_transcript/application/services/dictation/dictation_preferences.dart'; +import 'package:ici_transcript/core/platform/app_data_directory.dart'; + +/// Raccourci de dictée « modificateurs seuls » (⌘⌥, sans autre touche) dans +/// prefs.json. +/// +/// Stockage choisi : +/// - modèle : `DictationShortcut(keyCode: null, modifiers: )`, +/// `keyCode` null = modificateurs seuls ; +/// - prefs.json : `dictation_modifiers` présent, `dictation_key_code` ABSENT +/// (le `PrefsStore` retire une clé de valeur null ; aucune clé nouvelle). +/// Un sentinelle (-1) est écarté : la version actuelle le passerait à +/// `UInt32(keyCode)` côté Swift, qui plante sur un négatif. Avec la clé +/// absente, une version plus ancienne relit simplement ⌃⌥Espace ; +/// - un prefs.json d'avant (code de touche + modificateurs) se lit sans +/// changement ; +/// - modificateurs seuls illisibles (un seul modificateur, ⇧ seul, masque 0) +/// : défaut ⌃⌥Espace, jamais un raccourci inutilisable. +/// +/// Masques Carbon : cmd 256, shift 512, option 2048, control 4096 ; +/// ⌘⌥ = 2304. +void main() { + final File prefs = File('${appDataDirectory()}/prefs.json'); + const DictationShortcut cmdOption = DictationShortcut( + keyCode: null, + modifiers: 256 | 2048, + ); + + setUp(() { + expect(prefs.path, startsWith(Directory.systemTemp.path)); + if (prefs.existsSync()) prefs.deleteSync(); + }); + + Map stored() => + jsonDecode(prefs.readAsStringSync()) as Map; + + void writeByHand(Map json) { + prefs.parent.createSync(recursive: true); + prefs.writeAsStringSync(jsonEncode(json)); + } + + test('un prefs.json d avant (code de touche + modificateurs) se lit sans ' + 'changement', () async { + writeByHand({ + 'dictation_enabled': true, + 'dictation_key_code': 2, + 'dictation_modifiers': 4608, + 'dictation_output_mode': 'clipboard', + }); + + final DictationSettings s = await DictationPreferences().load(); + + expect(s.shortcut.keyCode, 2); + expect(s.shortcut.modifiers, 4608); + expect(s.outputMode, DictationOutputMode.clipboard); + }); + + test('⌘⌥ seuls : stockés en modificateurs sans code de touche', () async { + await DictationPreferences().save( + const DictationSettings(shortcut: cmdOption), + ); + + expect(stored(), containsPair('dictation_modifiers', 2304)); + expect(stored().containsKey('dictation_key_code'), isFalse); + }); + + test('⌘⌥ seuls : relus à l identique par une autre instance', () async { + await DictationPreferences().save( + const DictationSettings( + enabled: false, + shortcut: cmdOption, + outputMode: DictationOutputMode.clipboard, + ), + ); + + final DictationSettings s = await DictationPreferences().load(); + + expect(s.enabled, isFalse); + expect(s.shortcut.keyCode, isNull); + expect(s.shortcut.modifiers, 2304); + expect(s.outputMode, DictationOutputMode.clipboard); + }); + + test('d un raccourci à touche vers ⌘⌥ seuls : l ancien code de touche ne ' + 'reste pas', () async { + await DictationPreferences().save( + const DictationSettings( + shortcut: DictationShortcut(keyCode: 49, modifiers: 6144), + ), + ); + await DictationPreferences().save( + const DictationSettings(shortcut: cmdOption), + ); + + final DictationSettings s = await DictationPreferences().load(); + + expect(s.shortcut.keyCode, isNull); + expect(s.shortcut.modifiers, 2304); + expect(stored().containsKey('dictation_key_code'), isFalse); + }); + + test('de ⌘⌥ seuls vers un raccourci à touche : relu avec sa touche', () async { + await DictationPreferences().save( + const DictationSettings(shortcut: cmdOption), + ); + await DictationPreferences().save( + const DictationSettings( + shortcut: DictationShortcut(keyCode: 2, modifiers: 2304), + ), + ); + + final DictationSettings s = await DictationPreferences().load(); + + expect(s.shortcut.keyCode, 2); + expect(s.shortcut.modifiers, 2304); + }); + + test('modificateurs seuls écrits à la main dans prefs.json : lus comme ' + 'tels', () async { + writeByHand({'dictation_modifiers': 4096 | 512}); + + final DictationSettings s = await DictationPreferences().load(); + + expect(s.shortcut.keyCode, isNull); + expect(s.shortcut.modifiers, 4608); + }); + + for (final ({String name, int modifiers}) bad + in <({String name, int modifiers})>[ + (name: '⌘ seul', modifiers: 256), + (name: '⇧ seul', modifiers: 512), + (name: 'aucun modificateur', modifiers: 0), + ]) { + test('modificateurs seuls invalides sur disque (${bad.name}) : défaut ' + '⌃⌥Espace', () async { + writeByHand({'dictation_modifiers': bad.modifiers}); + + final DictationSettings s = await DictationPreferences().load(); + + expect(s.shortcut.keyCode, 49); + expect(s.shortcut.modifiers, 4096 | 2048); + }); + } +} From be74fe2d77ab38e5eac629a55a9a90e46e30d011 Mon Sep 17 00:00:00 2001 From: Clement Guyon Date: Mon, 23 Nov 2026 14:44:11 +0100 Subject: [PATCH 03/18] Spec: global shortcut channel contract for modifier-only shortcuts --- .../global_shortcut_channel_test.dart | 39 +++++++- .../global_shortcut_modifier_only_test.dart | 88 +++++++++++++++++++ 2 files changed, 126 insertions(+), 1 deletion(-) create mode 100644 apps/app_macos/test/core/platform/global_shortcut_modifier_only_test.dart diff --git a/apps/app_macos/test/core/platform/global_shortcut_channel_test.dart b/apps/app_macos/test/core/platform/global_shortcut_channel_test.dart index 3c6adab..957e86f 100644 --- a/apps/app_macos/test/core/platform/global_shortcut_channel_test.dart +++ b/apps/app_macos/test/core/platform/global_shortcut_channel_test.dart @@ -17,8 +17,14 @@ import 'package:ici_transcript/core/platform/global_shortcut_channel.dart'; /// /// - `keyLabel` : voir global_shortcut_key_label_test.dart. /// +/// - `registerModifiers` (raccourci modificateurs seuls) : voir +/// global_shortcut_modifier_only_test.dart. +/// /// EventChannel `com.icitranscript/global_shortcut_events` -/// - {type: 'pressed' | 'released' | 'cancel'} ; tout autre type est ignoré. +/// - {type: 'pressed' | 'released' | 'cancel' | 'aborted'} ; tout autre type +/// est ignoré. `aborted` : une autre touche est enfoncée pendant que les +/// modificateurs d'un raccourci modificateurs seuls sont tenus (sens +/// détaillé dans global_shortcut_modifier_only_test.dart). void main() { TestWidgetsFlutterBinding.ensureInitialized(); const MethodChannel method = MethodChannel( @@ -132,4 +138,35 @@ void main() { ]); }, ); + + test('événement aborted (raccourci modificateurs seuls) : transmis, ' + 'distinct de cancel', () async { + messenger.setMockStreamHandler( + events, + MockStreamHandler.inline( + onListen: (Object? arguments, MockStreamHandlerEventSink sink) { + sink + ..success({'type': 'pressed'}) + ..success({'type': 'aborted'}) + ..success({'type': 'pressed'}) + ..success({'type': 'released'}); + }, + ), + ); + final List seen = []; + + final StreamSubscription sub = GlobalShortcutChannel() + .events + .listen(seen.add); + await pumpEventQueue(); + await sub.cancel(); + + // Par le nom : la valeur `aborted` n'existe pas encore dans l'enum. + expect(seen.map((ShortcutEvent e) => e.name).toList(), [ + 'pressed', + 'aborted', + 'pressed', + 'released', + ]); + }); } diff --git a/apps/app_macos/test/core/platform/global_shortcut_modifier_only_test.dart b/apps/app_macos/test/core/platform/global_shortcut_modifier_only_test.dart new file mode 100644 index 0000000..a639346 --- /dev/null +++ b/apps/app_macos/test/core/platform/global_shortcut_modifier_only_test.dart @@ -0,0 +1,88 @@ +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:ici_transcript/core/platform/global_shortcut_channel.dart'; + +/// Raccourci de dictée « modificateurs seuls » (⌘⌥, sans autre touche) : +/// côté Dart du plugin Swift GlobalShortcutPlugin. Carbon +/// (RegisterEventHotKey) ne sait pas poser un raccourci sans touche : le +/// plugin surveille les modificateurs en global, ce qui demande la +/// permission Accessibilité. +/// +/// Contrat (ajouté à celui de global_shortcut_channel_test.dart) : +/// +/// MethodChannel `com.icitranscript/global_shortcut` +/// - `registerModifiers` {modifiers: int (masque Carbon : cmd 256, shift +/// 512, option 2048, control 4096 ; au moins deux, dont ⌃, ⌥ ou ⌘)} → +/// null. Remplace le raccourci précédent (à touche ou modificateurs +/// seuls). Lève PlatformException `ACCESSIBILITY_REQUIRED` si +/// l'Accessibilité n'est pas accordée : rien n'est posé (jamais un +/// raccourci posé mais muet). Dart : `registerModifiers(modifiers:)` rend +/// vrai si posé, faux sinon (refus ou plugin absent), sans lever. +/// - `unregister` retire aussi la surveillance des modificateurs. +/// - `setCancelKeyEnabled` : inchangé (Échap pendant une dictée). +/// +/// EventChannel `com.icitranscript/global_shortcut_events`, mêmes types : +/// - `pressed` : exactement les modificateurs choisis sont enfoncés (aucun +/// autre modificateur, aucune autre touche) ; +/// - `released` : l'un d'eux est relâché après un `pressed`, sans autre +/// touche entre-temps ; +/// - `aborted` (nouveau) : une touche autre qu'un modificateur (Échap +/// comprise) est enfoncée pendant que les modificateurs sont tenus après +/// un `pressed` : l'utilisateur tape un raccourci d'une autre app (⌘⌥Échap, +/// ⌘⌥D). Aucun `released` ne suit pour cet appui ; un `released` égaré est +/// ignoré par la dictée. Échap tapée avec les modificateurs tenus donne +/// `aborted`, jamais `cancel` ; +/// - `cancel` : inchangé, Échap pendant une dictée, modificateurs relâchés. +/// +/// Le passage de `aborted` dans le flux Dart est épinglé dans +/// global_shortcut_channel_test.dart. +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + const MethodChannel method = MethodChannel( + 'com.icitranscript/global_shortcut', + ); + final TestDefaultBinaryMessenger messenger = + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger; + final List calls = []; + + void answer(Object? Function(MethodCall call) handler) { + messenger.setMockMethodCallHandler(method, (MethodCall call) async { + calls.add(call); + return handler(call); + }); + } + + setUp(calls.clear); + tearDown(() => messenger.setMockMethodCallHandler(method, null)); + + test('registerModifiers envoie le masque seul, sans code de touche ; vrai ' + 'si posé', () async { + answer((_) => null); + + final bool ok = await GlobalShortcutChannel().registerModifiers( + modifiers: 256 | 2048, + ); + + expect(ok, isTrue); + expect(calls.single.method, 'registerModifiers'); + expect(calls.single.arguments, {'modifiers': 2304}); + }); + + test('Accessibilité absente : faux, sans lever', () async { + answer((_) => throw PlatformException(code: 'ACCESSIBILITY_REQUIRED')); + + final bool ok = await GlobalShortcutChannel().registerModifiers( + modifiers: 2304, + ); + + expect(ok, isFalse); + }); + + test('plugin absent : faux, sans lever', () async { + final bool ok = await GlobalShortcutChannel().registerModifiers( + modifiers: 2304, + ); + + expect(ok, isFalse); + }); +} From 68392ae51d631bcd40fbbfad7dea51e6e3c3f9b2 Mon Sep 17 00:00:00 2001 From: Clement Guyon Date: Mon, 23 Nov 2026 14:44:11 +0100 Subject: [PATCH 04/18] Spec: dictation with a modifier-only shortcut, aborted chords --- ...odifier_only_shortcut_controller_test.dart | 305 ++++++++++++++++++ 1 file changed, 305 insertions(+) create mode 100644 apps/app_macos/test/application/services/dictation/modifier_only_shortcut_controller_test.dart diff --git a/apps/app_macos/test/application/services/dictation/modifier_only_shortcut_controller_test.dart b/apps/app_macos/test/application/services/dictation/modifier_only_shortcut_controller_test.dart new file mode 100644 index 0000000..4f9c0ae --- /dev/null +++ b/apps/app_macos/test/application/services/dictation/modifier_only_shortcut_controller_test.dart @@ -0,0 +1,305 @@ +import 'dart:async'; + +import 'package:fake_async/fake_async.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:ici_transcript/application/services/dictation/dictation_controller.dart'; +import 'package:ici_transcript/application/services/dictation/dictation_preferences.dart'; +import 'package:ici_transcript/core/platform/global_shortcut_channel.dart'; + +import '../../../helpers/dictation_fakes.dart'; + +/// Dictée avec un raccourci « modificateurs seuls » (⌘⌥, sans autre touche), +/// demandé par l'utilisateur (« un raccourci à deux touches »). +/// +/// Comportement épinglé : +/// - le raccourci est posé par `registerModifiers` (masque Carbon), jamais +/// par `register` (Carbon ne sait pas poser un raccourci sans touche) ; +/// - mêmes gestes qu'un raccourci à touche : appui bref (< 300 ms) = +/// bascule, appui maintenu = parler tant qu'il est tenu ; +/// - `aborted` (le plugin a vu une autre touche pendant que ⌘⌥ étaient +/// tenus : l'utilisateur tape ⌘⌥Échap ou ⌘⌥D d'une autre app) : +/// - la dictée lancée par cet appui est jetée sans bruit : rien collé, +/// rien copié, ni erreur ni « rien entendu », capture arrêtée, flux +/// fermé, Échap libérée, serveur rendu à l'arbitre ; +/// - une dictée déjà en cours (lancée par un appui bref plus tôt) n'est +/// PAS arrêtée par cet appui : elle continue, un appui bref suivant +/// l'arrête comme d'habitude ; +/// - un `released` égaré après `aborted` ne fait rien ; +/// - Échap (`cancel`) annule toujours une dictée en cours ; +/// - Accessibilité absente : le plugin refuse, l'état du raccourci dit +/// `ShortcutStatus.needsAccessibility` (jamais « déjà pris », jamais +/// « posé ») ; réappliquer les réglages après l'accord repose le raccourci. +/// +/// Contrat du canal : global_shortcut_modifier_only_test.dart. +void main() { + const DictationShortcut cmdOption = DictationShortcut( + keyCode: null, + modifiers: 256 | 2048, + ); + const DictationSettings clipboardMode = DictationSettings( + shortcut: cmdOption, + outputMode: DictationOutputMode.clipboard, + ); + const DictationSettings pasteMode = DictationSettings( + shortcut: cmdOption, + outputMode: DictationOutputMode.paste, + ); + + DictationHarness launched( + FakeAsync async, { + DictationSettings settings = clipboardMode, + }) => DictationHarness(async)..launch(settings); + + void abort(DictationHarness d) { + d.shortcuts.emit(ShortcutEvent.aborted); + d.async.elapse(Duration.zero); + } + + /// États montrés à partir de maintenant. + List watch(DictationHarness d) { + final List seen = []; + d.controller.stateStream.skip(1).listen(seen.add); + d.async.elapse(Duration.zero); + return seen; + } + + /// Rien ne reste de la dictée jetée : ni texte, ni capture, ni flux, ni + /// Échap, ni prise du serveur, ni état d'échec. + void expectDiscarded(DictationHarness d, List seen) { + d.async.elapse(DictationController.finalTextTimeout * 2); + expect(d.state, isA()); + expect(d.output.log, isEmpty, reason: 'rien collé ni copié'); + expect(d.remote.finalCommits, 0, reason: 'rien envoyé à transcrire'); + expect(d.audio.stopCalls, 1, reason: 'capture arrêtée'); + expect(d.remote.connected, isFalse, reason: 'flux fermé'); + expect(d.shortcuts.cancelKey.last, isFalse, reason: 'Échap libérée'); + expect(d.arbiter.backfillMustYield, isFalse, reason: 'serveur rendu'); + expect( + seen.where( + (DictationState s) => + s is DictationDone || + s is DictationNothingHeard || + s is DictationError, + ), + isEmpty, + reason: 'jeté sans bruit', + ); + } + + group('enregistrement du raccourci', () { + test('⌘⌥ seuls : posé par registerModifiers, jamais comme une touche', () { + fakeAsync((FakeAsync async) { + final DictationHarness d = launched(async); + + expect(d.shortcuts.registeredModifiers, [2304]); + expect(d.shortcuts.registered, isEmpty); + expect(d.controller.shortcutStatus, ShortcutStatus.registered); + }); + }); + + test('de ⌃⌥Espace à ⌘⌥ puis retour : l ancien retiré chaque fois', () { + fakeAsync((FakeAsync async) { + final DictationHarness d = launched( + async, + settings: const DictationSettings(), + ); + expect(d.shortcuts.registered, hasLength(1)); + + unawaited(d.controller.apply(clipboardMode)); + async.elapse(Duration.zero); + expect(d.shortcuts.unregisterCalls, 1); + expect(d.shortcuts.registeredModifiers, [2304]); + + unawaited(d.controller.apply(const DictationSettings())); + async.elapse(Duration.zero); + expect(d.shortcuts.unregisterCalls, 2); + expect(d.shortcuts.registered.last, (keyCode: 49, modifiers: 6144)); + expect(d.shortcuts.registeredModifiers, [2304]); + }); + }); + }); + + group('mêmes gestes qu un raccourci à touche', () { + test('appui bref : la dictée continue ; un second appui bref l arrête et ' + 'produit le texte une fois', () { + fakeAsync((FakeAsync async) { + final DictationHarness d = launched(async); + + d.press(); + async.elapse(const Duration(milliseconds: 120)); + d.release(); + d.say(20); + expect(d.state, isA()); + expect(d.remote.finalCommits, 0); + + d.press(); + d.release(); + expect(d.state, isA()); + d.remote.emitDone('Bonjour à tous.'); + async.elapse(Duration.zero); + + expect(d.output.copies, ['Bonjour à tous.']); + }); + }); + + test('appui maintenu : parler tant que ⌘⌥ sont tenus, le relâchement ' + 'arrête', () { + fakeAsync((FakeAsync async) { + final DictationHarness d = launched(async); + + d.press(); + d.say(8); + expect(d.state, isA()); + d.release(); + + expect(d.state, isA()); + d.remote.emitDone('Note rapide.'); + async.elapse(Duration.zero); + expect(d.output.copies, ['Note rapide.']); + }); + }); + + test('Échap annule une dictée en cours, comme avant', () { + fakeAsync((FakeAsync async) { + final DictationHarness d = launched(async); + d.press(); + d.release(); + d.say(5); + + d.cancel(); + + expect(d.state, isA()); + expect(d.output.log, isEmpty); + }); + }); + }); + + group('une autre touche pendant ⌘⌥ : raccourci d une autre app', () { + test('pendant les 300 ms : la dictée lancée par cet appui est jetée sans ' + 'bruit, rien n est collé', () { + fakeAsync((FakeAsync async) { + final DictationHarness d = launched(async, settings: pasteMode); + final List seen = watch(d); + + d.press(); + d.say(1); + abort(d); + + expectDiscarded(d, seen); + }); + }); + + test('après 2 s tenus à parler : jetée aussi, rien n est collé', () { + fakeAsync((FakeAsync async) { + final DictationHarness d = launched(async, settings: pasteMode); + final List seen = watch(d); + + d.press(); + d.say(20); + abort(d); + + expectDiscarded(d, seen); + }); + }); + + test('un relâchement égaré après l abandon ne fait rien', () { + fakeAsync((FakeAsync async) { + final DictationHarness d = launched(async); + final List seen = watch(d); + d.press(); + d.say(1); + abort(d); + + d.release(); + + expectDiscarded(d, seen); + expect(d.audio.startCalls, 1); + }); + }); + + test('une dictée lancée par un appui bref plus tôt n est pas arrêtée ; ' + 'un appui bref suivant l arrête', () { + fakeAsync((FakeAsync async) { + final DictationHarness d = launched(async); + d.press(); + d.release(); + d.say(10); + + // ⌘⌥D tapé dans une autre app pendant la dictée. + d.press(); + abort(d); + final int sentBefore = d.remote.sentAudio.length; + d.say(10); + + expect(d.state, isA()); + expect(d.audio.stopCalls, 0); + expect(d.remote.finalCommits, 0); + expect(d.remote.sentAudio.length, greaterThan(sentBefore)); + expect(d.output.log, isEmpty); + + d.press(); + d.release(); + expect(d.state, isA()); + d.remote.emitDone('Toujours là.'); + async.elapse(Duration.zero); + expect(d.output.copies, ['Toujours là.']); + }); + }); + + test('après un abandon, l appui suivant démarre une dictée normale', () { + fakeAsync((FakeAsync async) { + final DictationHarness d = launched(async); + d.press(); + abort(d); + + d.press(); + d.say(8); + d.release(); + d.remote.emitDone('Deuxième essai.'); + async.elapse(Duration.zero); + + expect(d.audio.startCalls, 2); + expect(d.output.copies, ['Deuxième essai.']); + }); + }); + }); + + group('Accessibilité', () { + test('absente : le raccourci n est pas posé et l état le dit (ni « déjà ' + 'pris » ni « posé »)', () { + fakeAsync((FakeAsync async) { + final DictationHarness d = DictationHarness(async); + d.output.trusted = false; + d.shortcuts.registerModifiersResult = false; + + d.launch(clipboardMode); + + expect(d.shortcuts.registeredModifiers, [2304]); + expect( + d.controller.shortcutStatus, + ShortcutStatus.needsAccessibility, + ); + }); + }); + + test('accordée ensuite : réappliquer les mêmes réglages repose le ' + 'raccourci, qui marche', () { + fakeAsync((FakeAsync async) { + final DictationHarness d = DictationHarness(async); + d.output.trusted = false; + d.shortcuts.registerModifiersResult = false; + d.launch(clipboardMode); + + d.output.trusted = true; + d.shortcuts.registerModifiersResult = true; + unawaited(d.controller.apply(clipboardMode)); + async.elapse(Duration.zero); + + expect(d.shortcuts.registeredModifiers, [2304, 2304]); + expect(d.controller.shortcutStatus, ShortcutStatus.registered); + d.press(); + expect(d.state, isA()); + }); + }); + }); +} From cdecee81aabcd79525448b60273a84e861d4a9ba Mon Sep 17 00:00:00 2001 From: Clement Guyon Date: Mon, 23 Nov 2026 14:44:11 +0100 Subject: [PATCH 05/18] Spec: record a modifier-only shortcut in Settings --- .../dictation_shortcut_recorder_test.dart | 254 ++++++++++++++++++ 1 file changed, 254 insertions(+) create mode 100644 apps/app_macos/test/features/settings/dictation_shortcut_recorder_test.dart diff --git a/apps/app_macos/test/features/settings/dictation_shortcut_recorder_test.dart b/apps/app_macos/test/features/settings/dictation_shortcut_recorder_test.dart new file mode 100644 index 0000000..a22286b --- /dev/null +++ b/apps/app_macos/test/features/settings/dictation_shortcut_recorder_test.dart @@ -0,0 +1,254 @@ +import 'package:core_presentation/core_presentation.dart'; +import 'package:dio/dio.dart'; +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_riverpod/misc.dart' show Override; +import 'package:flutter_test/flutter_test.dart'; +import 'package:ici_transcript/application/services/dictation/dictation_controller.dart'; +import 'package:ici_transcript/core/platform/app_data_directory.dart'; +import 'package:ici_transcript/core/providers/platform/audio_capture.provider.dart'; +import 'package:ici_transcript/core/providers/services/api_key_store.provider.dart'; +import 'package:ici_transcript/core/providers/services/dictation.provider.dart'; +import 'package:ici_transcript/core/providers/services/llm_dio.provider.dart'; +import 'package:ici_transcript/features/live_transcription/presentation/screens/live/live_transcription.view_model.dart'; +import 'package:ici_transcript/features/onboarding/presentation/ollama_setup.view_model.dart'; +import 'package:ici_transcript/features/settings/presentation/screens/settings/settings.screen.dart'; + +import '../../helpers/dictation_fakes.dart'; +import '../../helpers/fake_view_models.dart'; +import '../../helpers/localized_app.dart'; +import '../../helpers/settings_fakes.dart'; + +/// Enregistreur du raccourci de dictée (Réglages › Dictée › Raccourci › +/// « Modifier »). Rapport : l'utilisateur appuie ⌘⌥ (rien d'autre) et rien +/// ne se passe ; il voulait un raccourci « à deux touches ». +/// +/// Comportement épinglé : +/// - deux modificateurs ou plus parmi ⌃ ⌥ ⇧ ⌘ (donc au moins un de ⌃ ⌥ ⌘), +/// enfoncés puis relâchés sans autre touche : raccourci « modificateurs +/// seuls » enregistré (prefs.json : `dictation_modifiers` sans +/// `dictation_key_code`, voir modifier_only_shortcut_preferences_test) ; +/// la ligne affiche ses symboles dans l'ordre d'Apple déjà épinglé +/// (⌃⌥⇧⌘) : ⌘ + ⌥ s'affiche « ⌥⌘ », quel que soit l'ordre d'appui ou de +/// relâchement ; gardé au redémarrage ; +/// - un seul modificateur (⌘ seul, ⇧ seul) : refusé, message en français +/// dans la section (`settings.dictation.shortcut_needs_two_modifiers`), +/// rien d'enregistré ; l'enregistreur reste à l'écoute pour un autre essai ; +/// - modificateurs + touche : comme aujourd'hui (⌘⌥ puis D = « ⌥⌘D »), le +/// relâchement des modificateurs qui suit ne l'écrase pas ; +/// - Échap : annule, rien d'enregistré. +/// +/// Touches simulées en macOS (`platform: 'macos'`) : la table des codes de +/// touche est celle de macOS. +void main() { + late FakeGlobalShortcutChannel shortcuts; + + setUp(() { + resetPrefs(); + shortcuts = FakeGlobalShortcutChannel()..keyLabels[2] = 'D'; + }); + + List overrides() => [ + globalShortcutChannelProvider.overrideWithValue(shortcuts), + apiKeyStoreProvider.overrideWithValue(InMemoryApiKeyStore()), + llmDioProvider.overrideWithValue( + Dio()..httpClientAdapter = RecordingHttpAdapter(), + ), + audioCaptureChannelProvider.overrideWithValue(DevicesAudioChannel()), + liveTranscriptionViewModelProvider.overrideWith( + FakeLiveTranscriptionViewModel.new, + ), + ollamaSetupViewModelProvider.overrideWith( + () => FakeOllamaSetupViewModel(kOllamaReady), + ), + dictationShortcutStatusProvider.overrideWith( + (Ref ref) => Stream.value(ShortcutStatus.registered), + ), + ]; + + Future io(WidgetTester tester) async { + for (int i = 0; i < 6; i++) { + await tester.runAsync( + () => Future.delayed(const Duration(milliseconds: 30)), + ); + await tester.pump(const Duration(milliseconds: 50)); + } + } + + /// Ouvre Réglages ; deux appels dans un test = redémarrage. + Future open(WidgetTester tester) async { + await tester.pumpWidget(const SizedBox.shrink()); + await pumpLocalized( + tester, + const SettingsScreen(), + overrides: overrides(), + size: const Size(1280, 4000), + settle: false, + ); + for (int i = 0; i < 40; i++) { + if (find.text(appDataDirectory()).evaluate().isNotEmpty) break; + await io(tester); + } + await io(tester); + } + + final Finder section = find.byKey( + const ValueKey('settings-dictation'), + ); + Finder inSection(Finder f) => find.descendant(of: section, matching: f); + Finder changeButton() => inSection( + find.widgetWithText(OatsButton, 'settings.dictation.shortcut_change'.tr()), + ); + Finder recording() => + inSection(find.text('settings.dictation.shortcut_recording'.tr())); + Finder twoModifiersMessage() => inSection( + find.text('settings.dictation.shortcut_needs_two_modifiers'.tr()), + ); + + Future startRecording(WidgetTester tester) async { + await tester.ensureVisible(changeButton()); + await tester.tap(changeButton()); + await tester.pump(); + expect(recording(), findsOneWidget); + } + + Future down(WidgetTester tester, LogicalKeyboardKey key) async { + await tester.sendKeyDownEvent(key, platform: 'macos'); + await tester.pump(); + } + + Future up(WidgetTester tester, LogicalKeyboardKey key) async { + await tester.sendKeyUpEvent(key, platform: 'macos'); + await tester.pump(); + } + + Map prefsOrEmpty() => + prefsFile.existsSync() ? readPrefs() : {}; + + testWidgets('⌘⌥ puis D : raccourci à touche, comme aujourd hui', ( + WidgetTester tester, + ) async { + await open(tester); + await startRecording(tester); + + await down(tester, LogicalKeyboardKey.metaLeft); + await down(tester, LogicalKeyboardKey.altLeft); + await down(tester, LogicalKeyboardKey.keyD); + await up(tester, LogicalKeyboardKey.keyD); + await up(tester, LogicalKeyboardKey.altLeft); + await up(tester, LogicalKeyboardKey.metaLeft); + await io(tester); + + expect(recording(), findsNothing); + expect(inSection(find.text('⌥⌘D')), findsOneWidget); + expect(prefsOrEmpty(), containsPair('dictation_key_code', 2)); + expect(prefsOrEmpty(), containsPair('dictation_modifiers', 2304)); + }); + + testWidgets('⌘⌥ seuls, enfoncés puis relâchés : enregistrés, affichés ' + '« ⌥⌘ », gardés au redémarrage', (WidgetTester tester) async { + await open(tester); + await startRecording(tester); + + await down(tester, LogicalKeyboardKey.metaLeft); + await down(tester, LogicalKeyboardKey.altLeft); + await up(tester, LogicalKeyboardKey.altLeft); + await up(tester, LogicalKeyboardKey.metaLeft); + await io(tester); + + expect(recording(), findsNothing); + expect(inSection(find.text('⌥⌘')), findsOneWidget); + expect(prefsOrEmpty(), containsPair('dictation_modifiers', 2304)); + expect(prefsOrEmpty().containsKey('dictation_key_code'), isFalse); + + await open(tester); + expect(inSection(find.text('⌥⌘')), findsOneWidget); + }); + + testWidgets('⌥ puis ⌘, relâchés dans l autre ordre : même « ⌥⌘ »', ( + WidgetTester tester, + ) async { + await open(tester); + await startRecording(tester); + + await down(tester, LogicalKeyboardKey.altRight); + await down(tester, LogicalKeyboardKey.metaRight); + await up(tester, LogicalKeyboardKey.altRight); + await up(tester, LogicalKeyboardKey.metaRight); + await io(tester); + + expect(inSection(find.text('⌥⌘')), findsOneWidget); + expect(prefsOrEmpty(), containsPair('dictation_modifiers', 2304)); + }); + + testWidgets('⌥⇧ : accepté (⇧ compte s il accompagne ⌃, ⌥ ou ⌘)', ( + WidgetTester tester, + ) async { + await open(tester); + await startRecording(tester); + + await down(tester, LogicalKeyboardKey.altLeft); + await down(tester, LogicalKeyboardKey.shiftLeft); + await up(tester, LogicalKeyboardKey.shiftLeft); + await up(tester, LogicalKeyboardKey.altLeft); + await io(tester); + + expect(inSection(find.text('⌥⇧')), findsOneWidget); + expect(prefsOrEmpty(), containsPair('dictation_modifiers', 2048 | 512)); + expect(prefsOrEmpty().containsKey('dictation_key_code'), isFalse); + }); + + for (final ({String name, LogicalKeyboardKey key}) single + in <({String name, LogicalKeyboardKey key})>[ + (name: '⌘', key: LogicalKeyboardKey.metaLeft), + (name: '⇧', key: LogicalKeyboardKey.shiftLeft), + ]) { + testWidgets('${single.name} seul : refusé avec un message en français, ' + 'rien d enregistré, nouvel essai possible', ( + WidgetTester tester, + ) async { + expect( + frValue('settings.dictation.shortcut_needs_two_modifiers'), + isA(), + reason: 'message dans fr.json', + ); + await open(tester); + await startRecording(tester); + + await down(tester, single.key); + await up(tester, single.key); + await io(tester); + + expect(twoModifiersMessage(), findsOneWidget); + expect(prefsOrEmpty().containsKey('dictation_modifiers'), isFalse); + expect(recording(), findsOneWidget); + + // Toujours à l'écoute : ⌘⌥ est pris tout de suite. + await down(tester, LogicalKeyboardKey.metaLeft); + await down(tester, LogicalKeyboardKey.altLeft); + await up(tester, LogicalKeyboardKey.altLeft); + await up(tester, LogicalKeyboardKey.metaLeft); + await io(tester); + + expect(twoModifiersMessage(), findsNothing); + expect(inSection(find.text('⌥⌘')), findsOneWidget); + }); + } + + testWidgets('Échap : enregistrement annulé, raccourci inchangé', ( + WidgetTester tester, + ) async { + await open(tester); + await startRecording(tester); + + await down(tester, LogicalKeyboardKey.escape); + await up(tester, LogicalKeyboardKey.escape); + await io(tester); + + expect(recording(), findsNothing); + expect(inSection(find.textContaining('⌃⌥Espace')), findsOneWidget); + expect(prefsOrEmpty().containsKey('dictation_modifiers'), isFalse); + }); +} From 182bc598e6eaef174e145bdbee7e743307c93418 Mon Sep 17 00:00:00 2001 From: Clement Guyon Date: Mon, 23 Nov 2026 14:44:11 +0100 Subject: [PATCH 06/18] Spec: modifier-only shortcut needs Accessibility, never silently dead --- ...dictation_shortcut_accessibility_test.dart | 259 ++++++++++++++++++ 1 file changed, 259 insertions(+) create mode 100644 apps/app_macos/test/features/settings/dictation_shortcut_accessibility_test.dart diff --git a/apps/app_macos/test/features/settings/dictation_shortcut_accessibility_test.dart b/apps/app_macos/test/features/settings/dictation_shortcut_accessibility_test.dart new file mode 100644 index 0000000..99502a8 --- /dev/null +++ b/apps/app_macos/test/features/settings/dictation_shortcut_accessibility_test.dart @@ -0,0 +1,259 @@ +import 'dart:convert'; + +import 'package:core_data/database/app_database.dart'; +import 'package:core_presentation/core_presentation.dart'; +import 'package:dio/dio.dart'; +import 'package:drift/native.dart'; +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_riverpod/misc.dart' show Override; +import 'package:flutter_test/flutter_test.dart'; +import 'package:ici_transcript/application/services/dictation/dictation_controller.dart'; +import 'package:ici_transcript/core/platform/app_data_directory.dart'; +import 'package:ici_transcript/core/providers/data/database.provider.dart'; +import 'package:ici_transcript/core/providers/kernel.provider.dart'; +import 'package:ici_transcript/core/providers/platform/audio_capture.provider.dart'; +import 'package:ici_transcript/core/providers/platform/process_manager.provider.dart'; +import 'package:ici_transcript/core/providers/services/api_key_store.provider.dart'; +import 'package:ici_transcript/core/providers/services/dictation.provider.dart'; +import 'package:ici_transcript/core/providers/services/llm_dio.provider.dart'; +import 'package:ici_transcript/features/live_transcription/presentation/screens/live/live_transcription.view_model.dart'; +import 'package:ici_transcript/features/onboarding/presentation/ollama_setup.view_model.dart'; +import 'package:ici_transcript/features/settings/presentation/screens/settings/settings.screen.dart'; +import 'package:ici_transcript/features/settings/presentation/screens/settings/settings_dictation.view_model.dart'; +import 'package:rxdart/rxdart.dart'; + +import '../../helpers/dictation_fakes.dart'; +import '../../helpers/fake_view_models.dart'; +import '../../helpers/live_service_fakes.dart'; +import '../../helpers/localized_app.dart'; +import '../../helpers/settings_fakes.dart'; + +/// Raccourci « modificateurs seuls » (⌘⌥) et permission Accessibilité. +/// Surveiller les modificateurs en global demande l'Accessibilité ; sans +/// elle le plugin refuse (`registerModifiers` → faux, voir +/// global_shortcut_modifier_only_test) et la dictée le dit +/// (`ShortcutStatus.needsAccessibility`). +/// +/// Comportement épinglé : +/// - raccourci modificateurs seuls refusé faute d'Accessibilité : la ligne +/// du raccourci le dit en français +/// (`settings.dictation.shortcut_needs_accessibility`), avec, à côté du +/// message, la même action que le mode collage (« Ouvrir les Réglages », +/// `settings.dictation.accessibility_open` → volet Accessibilité des +/// Réglages Système) ; jamais le texte « déjà pris » ; +/// - permission accordée (état du raccourci qui passe à `registered`) : le +/// message disparaît ; +/// - raccourci à touche, Accessibilité absente : pas ce message (Carbon n'a +/// pas besoin de l'Accessibilité ; la ligne Accessibilité du bas reste) ; +/// - jamais muet : au retour des Réglages Système avec l'Accessibilité +/// accordée (`refreshAccessibility`, appelé à la reprise de l'app), le +/// raccourci est reposé et marche, sans le réenregistrer. +void main() { + late FakeGlobalShortcutChannel shortcuts; + late FakeTextOutputChannel output; + late BehaviorSubject status; + + void saveModifierOnlyByHand() { + prefsFile.parent.createSync(recursive: true); + prefsFile.writeAsStringSync( + jsonEncode({'dictation_modifiers': 256 | 2048}), + ); + } + + setUp(() { + resetPrefs(); + shortcuts = FakeGlobalShortcutChannel(); + output = FakeTextOutputChannel()..trusted = false; + status = BehaviorSubject.seeded( + ShortcutStatus.needsAccessibility, + ); + addTearDown(status.close); + }); + + List overrides() => [ + globalShortcutChannelProvider.overrideWithValue(shortcuts), + textOutputChannelProvider.overrideWithValue(output), + apiKeyStoreProvider.overrideWithValue(InMemoryApiKeyStore()), + llmDioProvider.overrideWithValue( + Dio()..httpClientAdapter = RecordingHttpAdapter(), + ), + audioCaptureChannelProvider.overrideWithValue(DevicesAudioChannel()), + liveTranscriptionViewModelProvider.overrideWith( + FakeLiveTranscriptionViewModel.new, + ), + ollamaSetupViewModelProvider.overrideWith( + () => FakeOllamaSetupViewModel(kOllamaReady), + ), + dictationShortcutStatusProvider.overrideWith((Ref ref) => status.stream), + ]; + + Future io(WidgetTester tester) async { + for (int i = 0; i < 6; i++) { + await tester.runAsync( + () => Future.delayed(const Duration(milliseconds: 30)), + ); + await tester.pump(const Duration(milliseconds: 50)); + } + } + + Future open(WidgetTester tester) async { + await tester.pumpWidget(const SizedBox.shrink()); + await pumpLocalized( + tester, + const SettingsScreen(), + overrides: overrides(), + size: const Size(1280, 4000), + settle: false, + ); + for (int i = 0; i < 40; i++) { + if (find.text(appDataDirectory()).evaluate().isNotEmpty) break; + await io(tester); + } + await io(tester); + } + + final Finder section = find.byKey( + const ValueKey('settings-dictation'), + ); + Finder inSection(Finder f) => find.descendant(of: section, matching: f); + Finder needsAccessibility() => inSection( + find.text('settings.dictation.shortcut_needs_accessibility'.tr()), + ); + Finder openSettingsButton() => find.widgetWithText( + OatsButton, + 'settings.dictation.accessibility_open'.tr(), + ); + + /// « Ouvrir les Réglages » le plus proche de [message] : dans le plus petit + /// ancêtre commun, qui ne doit pas être la ligne Accessibilité du bas. + Finder actionNextTo(Finder message) { + for (final Element ancestor in find + .ancestor(of: message, matching: find.byWidgetPredicate((_) => true)) + .evaluate()) { + final Finder button = find.descendant( + of: find.byElementPredicate((Element e) => e == ancestor), + matching: openSettingsButton(), + ); + if (button.evaluate().isEmpty) continue; + final Finder permissionRow = find.descendant( + of: find.byElementPredicate((Element e) => e == ancestor), + matching: find.text('settings.dictation.accessibility'.tr()), + ); + expect( + permissionRow, + findsNothing, + reason: 'l action doit être à côté du message du raccourci', + ); + return button.first; + } + fail('aucun « Ouvrir les Réglages » à côté du message'); + } + + testWidgets('⌘⌥ refusé faute d Accessibilité : la ligne le dit, avec ' + '« Ouvrir les Réglages » à côté', (WidgetTester tester) async { + expect( + frValue('settings.dictation.shortcut_needs_accessibility'), + isA(), + reason: 'message dans fr.json', + ); + saveModifierOnlyByHand(); + await open(tester); + + expect(inSection(find.text('⌥⌘')), findsOneWidget); + expect(needsAccessibility(), findsOneWidget); + expect( + inSection(find.text('settings.dictation.shortcut_unavailable'.tr())), + findsNothing, + ); + + final Finder action = actionNextTo(needsAccessibility()); + await tester.ensureVisible(action); + await tester.tap(action); + await tester.pump(); + + expect(output.openSettingsCalls, 1); + }); + + testWidgets('permission accordée, raccourci posé : le message disparaît', ( + WidgetTester tester, + ) async { + saveModifierOnlyByHand(); + await open(tester); + expect(needsAccessibility(), findsOneWidget); + + output.trusted = true; + status.add(ShortcutStatus.registered); + await io(tester); + + expect(needsAccessibility(), findsNothing); + }); + + testWidgets('raccourci à touche, Accessibilité absente : pas ce message', ( + WidgetTester tester, + ) async { + status.add(ShortcutStatus.registered); + await open(tester); + + expect(inSection(find.textContaining('⌃⌥Espace')), findsOneWidget); + expect(needsAccessibility(), findsNothing); + }); + + test('jamais muet : au retour des Réglages Système avec l Accessibilité ' + 'accordée, ⌘⌥ est reposé sans le réenregistrer', () async { + saveModifierOnlyByHand(); + shortcuts.registerModifiersResult = false; + final ProviderContainer container = ProviderContainer( + overrides: [ + databaseProvider.overrideWithValue( + AppDatabase(NativeDatabase.memory()), + ), + processManagerChannelProvider.overrideWithValue( + FakeProcessManagerChannel(), + ), + audioCaptureChannelProvider.overrideWithValue( + FakeAudioCaptureChannel(), + ), + globalShortcutChannelProvider.overrideWithValue(shortcuts), + textOutputChannelProvider.overrideWithValue(output), + ], + ); + addTearDown(container.dispose); + + await container.read(kernelProvider.future); + await eventually(() { + expect(shortcuts.registeredModifiers, [2304]); + expect( + container.read(dictationControllerProvider).shortcutStatus, + ShortcutStatus.needsAccessibility, + ); + }); + + // Réglages ouverts, l'utilisateur accorde l'Accessibilité puis revient. + container.listen(dictationSettingsViewModelProvider, (_, _) {}); + await eventually( + () => expect( + container + .read(dictationSettingsViewModelProvider) + .settings + .shortcut + .modifiers, + 2304, + ), + ); + output.trusted = true; + shortcuts.registerModifiersResult = true; + await container + .read(dictationSettingsViewModelProvider.notifier) + .refreshAccessibility(); + + await eventually(() { + expect(shortcuts.registeredModifiers, [2304, 2304]); + expect( + container.read(dictationControllerProvider).shortcutStatus, + ShortcutStatus.registered, + ); + }); + }); +} From ad9cae9eda7a49e750266b8d858ef91cad3b6902 Mon Sep 17 00:00:00 2001 From: Clement Guyon Date: Mon, 23 Nov 2026 14:48:47 +0100 Subject: [PATCH 07/18] Spec: aborted chord during a recording; assert status, not call counts --- ...odifier_only_shortcut_controller_test.dart | 108 +++++++++++++++++- 1 file changed, 106 insertions(+), 2 deletions(-) diff --git a/apps/app_macos/test/application/services/dictation/modifier_only_shortcut_controller_test.dart b/apps/app_macos/test/application/services/dictation/modifier_only_shortcut_controller_test.dart index 4f9c0ae..aa80016 100644 --- a/apps/app_macos/test/application/services/dictation/modifier_only_shortcut_controller_test.dart +++ b/apps/app_macos/test/application/services/dictation/modifier_only_shortcut_controller_test.dart @@ -1,12 +1,18 @@ import 'dart:async'; +import 'dart:io'; +import 'package:clock/clock.dart' as wall; +import 'package:core_data/datasources/remote/impl/transcription.remote.data_source.impl.dart'; +import 'package:core_domain/domain/enum/audio_source.enum.dart'; import 'package:fake_async/fake_async.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:ici_transcript/application/services/dictation/dictation_controller.dart'; import 'package:ici_transcript/application/services/dictation/dictation_preferences.dart'; +import 'package:ici_transcript/application/services/live_transcription.service.dart'; import 'package:ici_transcript/core/platform/global_shortcut_channel.dart'; import '../../../helpers/dictation_fakes.dart'; +import '../../../helpers/live_service_fakes.dart'; /// Dictée avec un raccourci « modificateurs seuls » (⌘⌥, sans autre touche), /// demandé par l'utilisateur (« un raccourci à deux touches »). @@ -25,6 +31,10 @@ import '../../../helpers/dictation_fakes.dart'; /// PAS arrêtée par cet appui : elle continue, un appui bref suivant /// l'arrête comme d'habitude ; /// - un `released` égaré après `aborted` ne fait rien ; +/// - pendant un enregistrement (dictée prise sur le micro de la réunion) : +/// même règle, l'enregistrement continue ; ce que devient la phrase de +/// réunion dite pendant un appui abandonné (note ou exclue comme une +/// dictée annulée) n'est pas tranché ici ; /// - Échap (`cancel`) annule toujours une dictée en cours ; /// - Accessibilité absente : le plugin refuse, l'état du raccourci dit /// `ShortcutStatus.needsAccessibility` (jamais « déjà pris », jamais @@ -274,7 +284,7 @@ void main() { d.launch(clipboardMode); - expect(d.shortcuts.registeredModifiers, [2304]); + expect(d.shortcuts.registered, isEmpty); expect( d.controller.shortcutStatus, ShortcutStatus.needsAccessibility, @@ -295,11 +305,105 @@ void main() { unawaited(d.controller.apply(clipboardMode)); async.elapse(Duration.zero); - expect(d.shortcuts.registeredModifiers, [2304, 2304]); + expect(d.shortcuts.registeredModifiers.last, 2304); expect(d.controller.shortcutStatus, ShortcutStatus.registered); d.press(); expect(d.state, isA()); }); }); }); + + group('pendant un enregistrement', () { + late LiveServiceHarness h; + late DictationHarness d; + late FakeAsync clock; + int id = 0; + + setUp(() { + final Directory dir = Directory(LiveTranscriptionService.recordingsDir); + expect(dir.path, startsWith(Directory.systemTemp.path)); + if (dir.existsSync()) dir.deleteSync(recursive: true); + }); + + void setUpIn(FakeAsync async) { + clock = async; + id = 0; + final FakeVoxServer server = FakeVoxServer(); + final FakeVoxSocket mic = FakeVoxSocket(server) + ..reply = (int n) => 'Phrase $n.'; + h = LiveServiceHarness( + async, + remote: TranscriptionRemoteDataSourceImpl( + micClient: mic, + systemClient: FakeVoxSocket(server), + ), + ); + d = DictationHarness(async, live: h)..launch(clipboardMode); + h.start(); + } + + /// [count] × 100 ms de micro, voisé ou non. + void run(int count, {bool voiced = false}) { + for (int i = 0; i < count; i++) { + final int ts = wall.clock.now().millisecondsSinceEpoch; + h.audio + ..emit(chunk(AudioSource.input, id, timestampMs: ts, voiced: voiced)) + ..emit(chunk(AudioSource.output, id, timestampMs: ts)); + id++; + clock.elapse(const Duration(milliseconds: 100)); + } + } + + void abortIn() { + d.shortcuts.emit(ShortcutEvent.aborted); + clock.elapse(Duration.zero); + } + + test('appui abandonné : aucun texte, l enregistrement continue', () { + fakeAsync((FakeAsync async) { + setUpIn(async); + run(20, voiced: true); + run(15); + + d.press(); + run(3, voiced: true); + abortIn(); + run(20, voiced: true); + run(20); + async.elapse(const Duration(seconds: 2)); + + expect(d.output.log, isEmpty); + expect(d.state, isA()); + expect(h.service.isRecording, isTrue); + expect(h.audio.stopCalls, 0); + }); + }); + + test('dictée en bascule : un appui abandonné ne l arrête pas, un appui ' + 'bref suivant l arrête', () { + fakeAsync((FakeAsync async) { + setUpIn(async); + run(20, voiced: true); + run(15); + + d.press(); + d.release(); + run(10, voiced: true); + d.press(); + abortIn(); + run(10, voiced: true); + expect(d.state, isA()); + expect(d.output.log, isEmpty); + + d.press(); + d.release(); + run(20); + async.elapse(const Duration(seconds: 2)); + + expect(d.state, isA()); + expect(d.output.copies, hasLength(1)); + expect(h.service.isRecording, isTrue); + }); + }); + }); } From b81b18770a4cd377ebf40080da04713da922e7d4 Mon Sep 17 00:00:00 2001 From: Clement Guyon Date: Mon, 23 Nov 2026 14:48:47 +0100 Subject: [PATCH 08/18] Spec: unreadable key code loads the default shortcut --- .../modifier_only_shortcut_preferences_test.dart | 16 +++++++++++++++- .../dictation_shortcut_accessibility_test.dart | 3 +-- 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/apps/app_macos/test/application/services/dictation/modifier_only_shortcut_preferences_test.dart b/apps/app_macos/test/application/services/dictation/modifier_only_shortcut_preferences_test.dart index cff8ad1..048f715 100644 --- a/apps/app_macos/test/application/services/dictation/modifier_only_shortcut_preferences_test.dart +++ b/apps/app_macos/test/application/services/dictation/modifier_only_shortcut_preferences_test.dart @@ -19,7 +19,8 @@ import 'package:ici_transcript/core/platform/app_data_directory.dart'; /// - un prefs.json d'avant (code de touche + modificateurs) se lit sans /// changement ; /// - modificateurs seuls illisibles (un seul modificateur, ⇧ seul, masque 0) -/// : défaut ⌃⌥Espace, jamais un raccourci inutilisable. +/// ou code de touche présent mais illisible : défaut ⌃⌥Espace, jamais un +/// raccourci inutilisable. /// /// Masques Carbon : cmd 256, shift 512, option 2048, control 4096 ; /// ⌘⌥ = 2304. @@ -129,6 +130,19 @@ void main() { expect(s.shortcut.modifiers, 4608); }); + test('code de touche présent mais illisible : défaut ⌃⌥Espace, jamais ' + 'lu comme modificateurs seuls', () async { + writeByHand({ + 'dictation_key_code': 'abc', + 'dictation_modifiers': 4096 | 2048, + }); + + final DictationSettings s = await DictationPreferences().load(); + + expect(s.shortcut.keyCode, 49); + expect(s.shortcut.modifiers, 4096 | 2048); + }); + for (final ({String name, int modifiers}) bad in <({String name, int modifiers})>[ (name: '⌘ seul', modifiers: 256), diff --git a/apps/app_macos/test/features/settings/dictation_shortcut_accessibility_test.dart b/apps/app_macos/test/features/settings/dictation_shortcut_accessibility_test.dart index 99502a8..145081e 100644 --- a/apps/app_macos/test/features/settings/dictation_shortcut_accessibility_test.dart +++ b/apps/app_macos/test/features/settings/dictation_shortcut_accessibility_test.dart @@ -223,7 +223,6 @@ void main() { await container.read(kernelProvider.future); await eventually(() { - expect(shortcuts.registeredModifiers, [2304]); expect( container.read(dictationControllerProvider).shortcutStatus, ShortcutStatus.needsAccessibility, @@ -249,7 +248,7 @@ void main() { .refreshAccessibility(); await eventually(() { - expect(shortcuts.registeredModifiers, [2304, 2304]); + expect(shortcuts.registeredModifiers.last, 2304); expect( container.read(dictationControllerProvider).shortcutStatus, ShortcutStatus.registered, From d04d011e5c040e74314cc13c9b334360edb11fa1 Mon Sep 17 00:00:00 2001 From: Clement Guyon Date: Mon, 23 Nov 2026 14:54:39 +0100 Subject: [PATCH 09/18] =?UTF-8?q?feat:=20modifier-only=20dictation=20short?= =?UTF-8?q?cut=20(=E2=8C=A5=E2=8C=98)=20on=20the=20Dart=20side?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Why: the user asked for a two-key shortcut and pressed ⌘⌥ in the recorder; modifier-only combos were silently ignored (Carbon cannot register them). What: DictationShortcut.keyCode is nullable (null = modifiers only, stored as dictation_modifiers without dictation_key_code; old prefs load unchanged; invalid masks fall back to ⌃⌥Espace); the channel gains registerModifiers and the aborted event; the controller registers through registerModifiers, reports needsAccessibility when refused and retries on each apply; an aborted press discards the dictation it started without any output or error, while a toggled dictation's stop press is decided on release so an aborted chord leaves it running; during a meeting an aborted press is abandoned (no interval saved, the microphone text goes to the note). Réglages records ⌥⌘ chords, refuses a single modifier with a French message, shows the Accessibility need next to the shortcut and re-registers when the permission comes back. Proof: the modifier-only specs (preferences, controller, channel, recorder, accessibility) and the existing dictation/settings specs pass (390). --- apps/app_macos/assets/translations/fr.json | 4 +- .../dictation/dictation_controller.dart | 76 ++++++++-- .../dictation/dictation_preferences.dart | 35 ++++- .../services/live_transcription.service.dart | 12 ++ .../platform/global_shortcut_channel.dart | 31 +++- .../settings/settings_dictation.section.dart | 143 +++++++++++++++--- .../settings_dictation.view_model.dart | 27 +++- .../generated/translations/locale_keys.g.dart | 2 + 8 files changed, 287 insertions(+), 43 deletions(-) diff --git a/apps/app_macos/assets/translations/fr.json b/apps/app_macos/assets/translations/fr.json index 452c0f7..6fbc117 100644 --- a/apps/app_macos/assets/translations/fr.json +++ b/apps/app_macos/assets/translations/fr.json @@ -301,7 +301,9 @@ "model_missing": "Le modèle de transcription (plusieurs Go) n'est pas encore sur ce Mac. Rien n'est téléchargé sans votre accord.", "download_model": "Télécharger le modèle", "model_downloading": "Téléchargement du modèle… La dictée sera prête à la fin.", - "model_download_failed": "Le téléchargement a échoué. Vérifiez la connexion, puis réessayez." + "model_download_failed": "Le téléchargement a échoué. Vérifiez la connexion, puis réessayez.", + "shortcut_needs_two_modifiers": "Un seul modificateur ne suffit pas : tenez-en deux, par exemple ⌥ et ⌘, ou ajoutez une touche.", + "shortcut_needs_accessibility": "Ce raccourci sans touche demande l'Accessibilité pour être vu dans toutes les apps. Il ne marche pas tant qu'elle n'est pas accordée." } }, "ollama": { diff --git a/apps/app_macos/lib/application/services/dictation/dictation_controller.dart b/apps/app_macos/lib/application/services/dictation/dictation_controller.dart index 62e02bc..b8aac84 100644 --- a/apps/app_macos/lib/application/services/dictation/dictation_controller.dart +++ b/apps/app_macos/lib/application/services/dictation/dictation_controller.dart @@ -92,7 +92,10 @@ enum DictationDelivery { enum DictationErrorReason { timeout, microphone, serverUnavailable } /// État du raccourci global. -enum ShortcutStatus { disabled, registered, unavailable } +/// +/// [needsAccessibility] : raccourci « modificateurs seuls » refusé faute +/// d'Accessibilité (la surveillance globale des modificateurs l'exige). +enum ShortcutStatus { disabled, registered, unavailable, needsAccessibility } /// Dictée (T2) : raccourci global maintenu (ou appui bref = bascule), texte /// final produit une seule fois (presse-papiers ou collage). @@ -218,19 +221,29 @@ final class DictationController { _shortcutStatus.add(ShortcutStatus.disabled); return; } + // Mêmes réglages déjà posés : rien à refaire. Un raccourci refusé (pris, + // Accessibilité absente) est retenté à chaque application. final bool sameShortcut = wasEnabled && + shortcutStatus == ShortcutStatus.registered && previous!.shortcut.keyCode == settings.shortcut.keyCode && previous.shortcut.modifiers == settings.shortcut.modifiers; if (!sameShortcut) { if (wasEnabled) await _shortcuts.unregister(); - final bool ok = await _shortcuts.register( - keyCode: settings.shortcut.keyCode, - modifiers: settings.shortcut.modifiers, - ); + final int? keyCode = settings.shortcut.keyCode; + final int modifiers = settings.shortcut.modifiers; + // Modificateurs seuls : Carbon ne sait pas les poser, le plugin les + // surveille (Accessibilité requise). + final bool ok = keyCode == null + ? await _shortcuts.registerModifiers(modifiers: modifiers) + : await _shortcuts.register(keyCode: keyCode, modifiers: modifiers); if (ok) _shortcutEvents ??= _shortcuts.events.listen(_onShortcut); _shortcutStatus.add( - ok ? ShortcutStatus.registered : ShortcutStatus.unavailable, + ok + ? ShortcutStatus.registered + : keyCode == null + ? ShortcutStatus.needsAccessibility + : ShortcutStatus.unavailable, ); } unawaited(_warmServer()); @@ -371,7 +384,27 @@ final class DictationController { _onReleased(); case ShortcutEvent.cancel: if (_run case final _Run run when !run.finished) _cancel(run); + case ShortcutEvent.aborted: + _onAborted(); + } + } + + bool get _modifiersOnly => _settings?.shortcut.keyCode == null; + + /// Une autre touche (ou un clic) pendant que les modificateurs seuls sont + /// tenus : c'était le raccourci d'une autre app (⌘⌥Échap, ⌘⌥-glisser). + void _onAborted() { + final _Run? run = _run; + if (run == null || run.finished || run.captureEnded) return; + if (run.stopOnRelease) { + // Appui d'arrêt d'une bascule : la dictée continue, son relâchement + // égaré ne fait rien. + run.stopOnRelease = false; + run.ignoreRelease = true; + return; } + // Appui qui a lancé la dictée : jetée sans bruit (ni texte, ni erreur). + if (!run.toggled) _cancel(run, abandon: true); } void _onPressed() { @@ -382,7 +415,17 @@ final class DictationController { if (current != null && !current.finished) { current.ignoreRelease = true; // Second appui d'une bascule : il arrête. Sinon (transcription) : ignoré. - if (current.toggled && !current.captureEnded) _endCapture(current); + if (current.toggled && !current.captureEnded) { + if (_modifiersOnly) { + // Modificateurs seuls : arrêt au relâchement, un `aborted` d'ici + // là (raccourci d'une autre app) laisse la dictée continuer. + current + ..ignoreRelease = false + ..stopOnRelease = true; + } else { + _endCapture(current); + } + } return; } unawaited(_begin(current)); @@ -391,6 +434,11 @@ final class DictationController { void _onReleased() { final _Run? run = _run; if (run == null || run.finished || run.captureEnded) return; + if (run.stopOnRelease) { + run.stopOnRelease = false; + _endCapture(run); + return; + } if (run.ignoreRelease) { run.ignoreRelease = false; return; @@ -654,8 +702,15 @@ final class DictationController { return DictationDelivery.pasted; } - void _cancel(_Run run) { - run.meeting?.cancel(); + /// Échap : la dictée est annulée (ses mots exclus de la note aussi). + /// [abandon] : appui abandonné (raccourci d'une autre app) : pendant une + /// réunion, rien n'était dicté, le micro reste à la note. + void _cancel(_Run run, {bool abandon = false}) { + if (abandon) { + run.meeting?.abandon(); + } else { + run.meeting?.cancel(); + } run.late = false; _end(run, const DictationIdle()); unawaited(_closeStream(run)); @@ -736,6 +791,9 @@ final class _Run { Timer? finalTimer; bool toggled = false; bool ignoreRelease = false; + + /// Modificateurs seuls : second appui d'une bascule, arrêt au relâchement. + bool stopOnRelease = false; bool captureEnded = false; bool committed = false; bool streaming = false; diff --git a/apps/app_macos/lib/application/services/dictation/dictation_preferences.dart b/apps/app_macos/lib/application/services/dictation/dictation_preferences.dart index 920ebb3..4c465f3 100644 --- a/apps/app_macos/lib/application/services/dictation/dictation_preferences.dart +++ b/apps/app_macos/lib/application/services/dictation/dictation_preferences.dart @@ -15,7 +15,28 @@ class DictationShortcut { modifiers: 4096 | 2048, ); - final int keyCode; + /// Code de touche macOS ; null : modificateurs seuls (⌘⌥), surveillés + /// par le plugin (Accessibilité requise), Carbon ne sachant pas les poser. + final int? keyCode; + + /// Masques Carbon (HIToolbox Events.h). + static const int command = 256; + static const int shift = 512; + static const int option = 2048; + static const int control = 4096; + + /// Modificateurs seuls utilisables : au moins deux parmi ⌃⌥⇧⌘, dont ⌃, ⌥ + /// ou ⌘ (⇧ seul ou un seul modificateur volerait une frappe ordinaire). + static bool isValidModifiersOnly(int modifiers) { + const int all = command | shift | option | control; + if (modifiers & ~all != 0) return false; + int count = 0; + for (final int bit in [command, shift, option, control]) { + if (modifiers & bit != 0) count++; + } + return count >= 2 && modifiers & (command | option | control) != 0; + } + final int modifiers; } @@ -49,12 +70,20 @@ class DictationPreferences { Future load() async { final Map json = await _store.read(); const DictationSettings d = DictationSettings(); - final int? keyCode = prefValue(json, _keyCode); + final Object? keyCode = json[_keyCode]; final int? modifiers = prefValue(json, _modifiers); + // Clé absente avec des modificateurs valides : modificateurs seuls. Une + // clé présente mais illisible n'est jamais lue comme telle. + final bool modifiersOnly = + !json.containsKey(_keyCode) && + modifiers != null && + DictationShortcut.isValidModifiersOnly(modifiers); return DictationSettings( enabled: prefValue(json, _enabled) ?? d.enabled, - shortcut: keyCode != null && modifiers != null + shortcut: keyCode is int && modifiers != null ? DictationShortcut(keyCode: keyCode, modifiers: modifiers) + : modifiersOnly + ? DictationShortcut(keyCode: null, modifiers: modifiers) : d.shortcut, outputMode: DictationOutputMode.values.asNameMap()[json[_outputMode]] ?? diff --git a/apps/app_macos/lib/application/services/live_transcription.service.dart b/apps/app_macos/lib/application/services/live_transcription.service.dart index 98db6b8..ded828e 100644 --- a/apps/app_macos/lib/application/services/live_transcription.service.dart +++ b/apps/app_macos/lib/application/services/live_transcription.service.dart @@ -1714,6 +1714,14 @@ final class LiveTranscriptionService { // Bien au-delà du délai de garde de la dictée (texte tardif encore livré). static const Duration _dictationGiveUp = Duration(seconds: 60); + void _abandonDictation(MeetingDictation d) { + d + ..onText = null + ..onComplete = null; + _dictations.remove(d); + d._finish(); + } + /// Un `done` micro de la dictée : il ne va pas à la note. bool _routeToDictation(TranscriptEventRemoteModel event) { final UtteranceWindow? window = _transcriptionRemoteDataSource.windowOf( @@ -1871,6 +1879,10 @@ final class MeetingDictation { /// Annulation : ses mots sont jetés, ni sortie ni note. void cancel() => _service._endDictation(this, cancelled: true); + /// Appui abandonné (raccourci d'une autre app) : ce n'était pas une + /// dictée. Aucun intervalle noté, le micro dit depuis l'appui va à la note. + void abandon() => _service._abandonDictation(this); + void _finish() { if (_complete) return; _complete = true; diff --git a/apps/app_macos/lib/core/platform/global_shortcut_channel.dart b/apps/app_macos/lib/core/platform/global_shortcut_channel.dart index bf4d257..959e7c3 100644 --- a/apps/app_macos/lib/core/platform/global_shortcut_channel.dart +++ b/apps/app_macos/lib/core/platform/global_shortcut_channel.dart @@ -1,7 +1,11 @@ import 'package:flutter/services.dart'; /// Événement du raccourci global de la dictée. -enum ShortcutEvent { pressed, released, cancel } +/// +/// [aborted] : une autre touche ou un clic pendant que les modificateurs +/// d'un raccourci « modificateurs seuls » sont tenus (raccourci d'une autre +/// app) ; aucun [released] ne suit pour cet appui. +enum ShortcutEvent { pressed, released, cancel, aborted } /// Dart wrapper autour du plugin Swift GlobalShortcutPlugin (raccourci /// global Carbon, appui maintenu pour dicter, Échap pour annuler). @@ -23,6 +27,7 @@ class GlobalShortcutChannel { {'type': 'pressed'} => ShortcutEvent.pressed, {'type': 'released'} => ShortcutEvent.released, {'type': 'cancel'} => ShortcutEvent.cancel, + {'type': 'aborted'} => ShortcutEvent.aborted, _ => null, }, ) @@ -45,6 +50,22 @@ class GlobalShortcutChannel { } } + /// Raccourci « modificateurs seuls » (masque Carbon, ⌘⌥ = 2304), à la + /// place du précédent. Faux si refusé (Accessibilité absente) ou plugin + /// absent. + Future registerModifiers({required int modifiers}) async { + try { + await _method.invokeMethod('registerModifiers', { + 'modifiers': modifiers, + }); + return true; + } on PlatformException { + return false; + } on MissingPluginException { + return false; + } + } + /// Caractères de la touche [keyCode] dans la disposition de clavier /// courante, sans modificateur ; null si inconnus ou plugin absent. Future keyLabel(int keyCode) async { @@ -63,8 +84,8 @@ class GlobalShortcutChannel { Future unregister() => _method.invokeMethod('unregister'); /// Capture Échap seulement pendant une dictée. - Future setCancelKeyEnabled(bool enabled) => _method - .invokeMethod('setCancelKeyEnabled', { - 'enabled': enabled, - }); + Future setCancelKeyEnabled(bool enabled) => _method.invokeMethod( + 'setCancelKeyEnabled', + {'enabled': enabled}, + ); } diff --git a/apps/app_macos/lib/features/settings/presentation/screens/settings/settings_dictation.section.dart b/apps/app_macos/lib/features/settings/presentation/screens/settings/settings_dictation.section.dart index 3045e22..ae29d06 100644 --- a/apps/app_macos/lib/features/settings/presentation/screens/settings/settings_dictation.section.dart +++ b/apps/app_macos/lib/features/settings/presentation/screens/settings/settings_dictation.section.dart @@ -27,8 +27,10 @@ String dictationShortcutLabel(DictationShortcut shortcut, String? keyLabel) { if (m & _carbonShift != 0) '\u21E7', if (m & _carbonCommand != 0) '\u2318', ].join(); + final int? keyCode = shortcut.keyCode; + if (keyCode == null) return mods; // modificateurs seuls : « ⌥⌘ » // Espace : un seul texte traduit (« ⌃⌥Espace »), modificateurs compris. - if (shortcut.keyCode == _macSpace) { + if (keyCode == _macSpace) { return LocaleKeys.settings_dictation_shortcut_space.tr( args: [mods], ); @@ -59,6 +61,13 @@ class _DictationSectionState extends ConsumerState<_DictationSection> { ); final FocusNode _recorderFocus = FocusNode(); bool _recording = false; + // Modificateurs tenus ensemble depuis le dernier « tout relâché », et si + // une autre touche est venue (alors ce n'est pas un raccourci + // modificateurs seuls). + int _chord = 0; + bool _chordHadKey = false; + // Un seul modificateur relâché : refusé, message affiché. + bool _needsTwo = false; @override void initState() { @@ -74,32 +83,75 @@ class _DictationSectionState extends ConsumerState<_DictationSection> { } void _startRecording() { - setState(() => _recording = true); + _chord = 0; + _chordHadKey = false; + setState(() { + _recording = true; + _needsTwo = false; + }); _recorderFocus.requestFocus(); } + static final Set _modifierKeys = + LogicalKeyboardKey.expandSynonyms({ + LogicalKeyboardKey.control, + LogicalKeyboardKey.alt, + LogicalKeyboardKey.shift, + LogicalKeyboardKey.meta, + }); + + static int _heldModifiers() { + final HardwareKeyboard k = HardwareKeyboard.instance; + return (k.isControlPressed ? _carbonControl : 0) | + (k.isAltPressed ? _carbonOption : 0) | + (k.isShiftPressed ? _carbonShift : 0) | + (k.isMetaPressed ? _carbonCommand : 0); + } + + /// Modificateurs relâchés sans autre touche : raccourci « modificateurs + /// seuls » (au moins deux, dont ⌃, ⌥ ou ⌘), sinon refusé avec un message. + void _onModifiersReleased() { + final int chord = _chord; + final bool hadKey = _chordHadKey; + _chord = 0; + _chordHadKey = false; + if (hadKey || chord == 0) return; + if (!DictationShortcut.isValidModifiersOnly(chord)) { + setState(() => _needsTwo = true); + return; + } + setState(() { + _recording = false; + _needsTwo = false; + }); + ref + .read(dictationSettingsViewModelProvider.notifier) + .setShortcut(DictationShortcut(keyCode: null, modifiers: chord)); + } + KeyEventResult _onKey(FocusNode _, KeyEvent event) { + final bool modifierKey = _modifierKeys.contains(event.logicalKey); + if (event is KeyUpEvent) { + if (modifierKey && _heldModifiers() == 0) _onModifiersReleased(); + return KeyEventResult.handled; + } if (event is! KeyDownEvent) return KeyEventResult.handled; + if (modifierKey) { + _chord |= _heldModifiers(); + if (_needsTwo) setState(() => _needsTwo = false); + return KeyEventResult.handled; + } + _chordHadKey = true; final PhysicalKeyboardKey key = event.physicalKey; if (key == PhysicalKeyboardKey.escape) { - setState(() => _recording = false); + setState(() { + _recording = false; + _needsTwo = false; + }); return KeyEventResult.handled; } final int? keyCode = _macKeyCodes[key]; - final HardwareKeyboard k = HardwareKeyboard.instance; - final int modifiers = - (k.isControlPressed ? _carbonControl : 0) | - (k.isAltPressed ? _carbonOption : 0) | - (k.isShiftPressed ? _carbonShift : 0) | - (k.isMetaPressed ? _carbonCommand : 0); - final bool modifierKey = { - ...LogicalKeyboardKey.expandSynonyms({ - LogicalKeyboardKey.control, - LogicalKeyboardKey.alt, - LogicalKeyboardKey.shift, - LogicalKeyboardKey.meta, - }), - }.contains(event.logicalKey); + final int modifiers = _heldModifiers(); // Une touche seule volerait la frappe à toutes les apps : il faut ⌃, ⌥ // ou ⌘ (⇧ seul ne suffit pas), sauf pour une touche de fonction. final bool strongModifier = @@ -109,7 +161,10 @@ class _DictationSectionState extends ConsumerState<_DictationSection> { (!strongModifier && !_isFunctionKey(key))) { return KeyEventResult.handled; } - setState(() => _recording = false); + setState(() { + _recording = false; + _needsTwo = false; + }); ref .read(dictationSettingsViewModelProvider.notifier) .setShortcut(DictationShortcut(keyCode: keyCode, modifiers: modifiers)); @@ -124,10 +179,15 @@ class _DictationSectionState extends ConsumerState<_DictationSection> { final DictationSettingsViewModel vm = ref.read( dictationSettingsViewModelProvider.notifier, ); - final bool unavailable = - ref.watch(dictationShortcutStatusProvider).value == - ShortcutStatus.unavailable; + final ShortcutStatus? status = ref + .watch(dictationShortcutStatusProvider) + .value; + final bool unavailable = status == ShortcutStatus.unavailable; final DictationSettings settings = state.settings; + final bool needsAccessibility = + settings.enabled && + settings.shortcut.keyCode == null && + status == ShortcutStatus.needsAccessibility; final bool modelMissing = settings.enabled && ref.watch(transcriptionModelCachedProvider).value == false; @@ -208,6 +268,47 @@ class _DictationSectionState extends ConsumerState<_DictationSection> { style: o.meta.copyWith(color: o.danger), ), ), + if (_recording && _needsTwo) + Padding( + padding: const EdgeInsets.fromLTRB( + OatsSpace.lg, + 0, + OatsSpace.lg, + OatsSpace.md, + ), + child: Text( + LocaleKeys.settings_dictation_shortcut_needs_two_modifiers + .tr(), + style: o.meta.copyWith(color: o.danger), + ), + ), + if (needsAccessibility) + Padding( + padding: const EdgeInsets.fromLTRB( + OatsSpace.lg, + 0, + OatsSpace.lg, + OatsSpace.md, + ), + child: Row( + children: [ + Expanded( + child: Text( + LocaleKeys + .settings_dictation_shortcut_needs_accessibility + .tr(), + style: o.meta.copyWith(color: o.danger), + ), + ), + const SizedBox(width: OatsSpace.md), + OatsButton( + label: LocaleKeys.settings_dictation_accessibility_open + .tr(), + onPressed: vm.openAccessibilitySettings, + ), + ], + ), + ), ], ), _Row( diff --git a/apps/app_macos/lib/features/settings/presentation/screens/settings/settings_dictation.view_model.dart b/apps/app_macos/lib/features/settings/presentation/screens/settings/settings_dictation.view_model.dart index 341ba5b..ac1da7e 100644 --- a/apps/app_macos/lib/features/settings/presentation/screens/settings/settings_dictation.view_model.dart +++ b/apps/app_macos/lib/features/settings/presentation/screens/settings/settings_dictation.view_model.dart @@ -103,9 +103,26 @@ class DictationSettingsViewModel extends _$DictationSettingsViewModel { ); /// Relit la permission Accessibilité (retour des Réglages Système). + /// + /// Accordée avec un raccourci « modificateurs seuls » : il est reposé + /// (jamais un raccourci muet), sans le réenregistrer. Future refreshAccessibility() async { final bool trusted = await _output.isAccessibilityTrusted(); - if (ref.mounted) state = state._with(accessibilityTrusted: trusted); + if (!ref.mounted) return; + state = state._with(accessibilityTrusted: trusted); + final DictationSettings s = state.settings; + if (trusted && s.enabled && s.shortcut.keyCode == null) { + // Nouvelle instance : le contrôleur réapplique même à l'identique. + ref + .read(dictationSettingsAppliedProvider.notifier) + .set( + DictationSettings( + enabled: s.enabled, + shortcut: s.shortcut, + outputMode: s.outputMode, + ), + ); + } } /// Demande système d'Accessibilité. @@ -146,7 +163,9 @@ class DictationSettingsViewModel extends _$DictationSettingsViewModel { if (ref.mounted) state = state._with(keyLabel: () => label); } - Future _keyLabel(DictationSettings settings) => ref - .read(globalShortcutChannelProvider) - .keyLabel(settings.shortcut.keyCode); + Future _keyLabel(DictationSettings settings) async { + final int? keyCode = settings.shortcut.keyCode; + if (keyCode == null) return null; // modificateurs seuls : pas de touche + return ref.read(globalShortcutChannelProvider).keyLabel(keyCode); + } } diff --git a/apps/app_macos/lib/generated/translations/locale_keys.g.dart b/apps/app_macos/lib/generated/translations/locale_keys.g.dart index 9d7ff3f..a158996 100644 --- a/apps/app_macos/lib/generated/translations/locale_keys.g.dart +++ b/apps/app_macos/lib/generated/translations/locale_keys.g.dart @@ -259,6 +259,8 @@ abstract class LocaleKeys { static const settings_dictation_download_model = 'settings.dictation.download_model'; static const settings_dictation_model_downloading = 'settings.dictation.model_downloading'; static const settings_dictation_model_download_failed = 'settings.dictation.model_download_failed'; + static const settings_dictation_shortcut_needs_two_modifiers = 'settings.dictation.shortcut_needs_two_modifiers'; + static const settings_dictation_shortcut_needs_accessibility = 'settings.dictation.shortcut_needs_accessibility'; static const settings_dictation = 'settings.dictation'; static const settings = 'settings'; static const ollama_step_binary = 'ollama.step_binary'; From 5e6c2022efb621db8c5d89a4624fde9d00f83080 Mon Sep 17 00:00:00 2001 From: Clement Guyon Date: Mon, 23 Nov 2026 14:56:05 +0100 Subject: [PATCH 10/18] feat: watch modifier-only shortcuts with NSEvent monitors MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Why: Carbon RegisterEventHotKey cannot register a shortcut without a key, so ⌥⌘ needs to be watched natively. What: registerModifiers installs global and local NSEvent monitors on flagsChanged, keyDown and mouse downs (refused with ACCESSIBILITY_REQUIRED unless AXIsProcessTrusted); pressed when exactly the chosen modifiers become held by adding a key, released when one goes up, aborted (no released) on any key or mouse button down or an extra modifier while held; a key pressed with modifiers held taints the chord until all are up; caps lock, fn and numeric pad flags are ignored. Escape cancel is armed without modifiers only for these shortcuts. Registering a keyed shortcut or unregistering removes the monitors. Proof: flutter build macos --debug compiles and links; not run live. --- .../macos/Runner/GlobalShortcutPlugin.swift | 136 +++++++++++++++++- 1 file changed, 134 insertions(+), 2 deletions(-) diff --git a/apps/app_macos/macos/Runner/GlobalShortcutPlugin.swift b/apps/app_macos/macos/Runner/GlobalShortcutPlugin.swift index 8275328..7976fdf 100644 --- a/apps/app_macos/macos/Runner/GlobalShortcutPlugin.swift +++ b/apps/app_macos/macos/Runner/GlobalShortcutPlugin.swift @@ -1,4 +1,6 @@ +import ApplicationServices import Carbon +import Cocoa import FlutterMacOS import Foundation @@ -8,14 +10,31 @@ import Foundation /// - `register` {keyCode, modifiers} (Carbon virtual key code and modifier /// mask) -> nil; replaces the previous shortcut; FlutterError /// `SHORTCUT_UNAVAILABLE` when Carbon refuses it. -/// - `unregister` -> nil (also disarms Escape). +/// - `registerModifiers` {modifiers} (Carbon mask, at least two modifiers) +/// -> nil: a modifier-only shortcut (⌥⌘), which Carbon cannot register. +/// Watched with NSEvent global + local monitors, which only see key events +/// when the app is trusted for Accessibility: FlutterError +/// `ACCESSIBILITY_REQUIRED` otherwise (never a silently dead shortcut). +/// Replaces the previous shortcut, keyed or not. +/// - `unregister` -> nil (also disarms Escape and removes the monitors). /// - `keyLabel` {keyCode} -> String?: characters the key types in the /// current keyboard layout, without modifiers (AZERTY: 13 -> "Z"); nil when /// it cannot be translated. /// - `setCancelKeyEnabled` {enabled} -> nil: Escape is a hotkey only while /// a dictation runs, so it keeps working in other apps the rest of the time. /// Event channel `com.icitranscript/global_shortcut_events`: -/// {type: pressed | released | cancel}, always on the main thread. +/// {type: pressed | released | cancel | aborted}, always on the main thread. +/// Modifier-only: `pressed` when exactly the chosen modifiers become held +/// (caps lock, fn and numeric pad flags ignored); `released` when one of +/// them goes up; `aborted` (and no `released`) when a key or a mouse button +/// goes down, or another modifier joins, while they are held: that was +/// another app's shortcut (⌘⌥Esc, ⌘⌥-drag in Finder). +/// NSEvent monitors (Apple documentation): +/// - https://developer.apple.com/documentation/appkit/nsevent/addglobalmonitorforevents(matching:handler:) +/// (events of other apps only; key events require Accessibility) +/// - https://developer.apple.com/documentation/appkit/nsevent/addlocalmonitorforevents(matching:handler:) +/// (this app's own events; returning the event leaves it unchanged) +/// - https://developer.apple.com/documentation/appkit/nsevent/modifierflags-swift.struct/deviceindependentflagsmask /// /// Carbon hotkeys fire while another app is frontmost and need no /// Accessibility permission. Apple's Carbon reference pages are no longer @@ -48,6 +67,17 @@ class GlobalShortcutPlugin: NSObject, FlutterPlugin, FlutterStreamHandler { /// part of ⌃⌥ of ⌃⌥Space when cancelling (at most 16 hotkeys). private var cancelRefs: [EventHotKeyRef] = [] private var mainModifiers: UInt32 = 0 + + // Modifier-only shortcut (NSEvent monitors). + private var chordMask: NSEvent.ModifierFlags? + private var monitors: [Any] = [] + private var chordDown = false + private var chordAborted = false + // A key went down while modifiers were held: no `pressed` until every + // modifier is up (releasing ⇧ of ⌘⌥⇧4 must not start a dictation). + private var chordTainted = false + private var lastFlags: NSEvent.ModifierFlags = [] + private static let chordFlags: NSEvent.ModifierFlags = [.command, .option, .control, .shift] private var handlerRef: EventHandlerRef? private var sink: FlutterEventSink? /// Pressed seen without its release yet (guards against repeats). @@ -93,6 +123,22 @@ class GlobalShortcutPlugin: NSObject, FlutterPlugin, FlutterStreamHandler { message: "RegisterEventHotKey failed", details: Int(status) )) + case "registerModifiers": + guard let modifiers = args?["modifiers"] as? Int else { + result(FlutterError(code: "BAD_ARGS", message: "Missing modifiers", details: nil)) + return + } + unregisterMain() + guard AXIsProcessTrusted() else { + result(FlutterError( + code: "ACCESSIBILITY_REQUIRED", + message: "Modifier-only shortcuts need Accessibility", + details: nil + )) + return + } + installChord(Self.flags(fromCarbon: UInt32(modifiers))) + result(nil) case "keyLabel": guard let keyCode = args?["keyCode"] as? Int else { result(FlutterError(code: "BAD_ARGS", message: "Missing keyCode", details: nil)) @@ -233,6 +279,92 @@ class GlobalShortcutPlugin: NSObject, FlutterPlugin, FlutterStreamHandler { if let ref = mainRef { UnregisterEventHotKey(ref) } mainRef = nil isDown = false + // Escape is then armed without modifiers only: ⌘⌥Esc stays a key + // down seen by the monitors (aborted), never a cancel hotkey. + mainModifiers = 0 + removeChord() + } + + // MARK: Modifier-only shortcut + + private static func flags(fromCarbon mask: UInt32) -> NSEvent.ModifierFlags { + var flags: NSEvent.ModifierFlags = [] + if mask & UInt32(cmdKey) != 0 { flags.insert(.command) } + if mask & UInt32(shiftKey) != 0 { flags.insert(.shift) } + if mask & UInt32(optionKey) != 0 { flags.insert(.option) } + if mask & UInt32(controlKey) != 0 { flags.insert(.control) } + return flags + } + + private func installChord(_ mask: NSEvent.ModifierFlags) { + chordMask = mask + chordDown = false + chordAborted = false + chordTainted = false + lastFlags = NSEvent.modifierFlags.intersection(Self.chordFlags) + let events: NSEvent.EventTypeMask = [ + .flagsChanged, .keyDown, .leftMouseDown, .rightMouseDown, .otherMouseDown, + ] + if let global = NSEvent.addGlobalMonitorForEvents(matching: events, handler: { [weak self] event in + self?.onChordEvent(event) + }) { + monitors.append(global) + } + if let local = NSEvent.addLocalMonitorForEvents(matching: events, handler: { [weak self] event in + self?.onChordEvent(event) + return event + }) { + monitors.append(local) + } + } + + private func removeChord() { + monitors.forEach { NSEvent.removeMonitor($0) } + monitors = [] + chordMask = nil + chordDown = false + chordAborted = false + chordTainted = false + } + + private func onChordEvent(_ event: NSEvent) { + guard let mask = chordMask else { return } + let flags = event.modifierFlags.intersection(Self.chordFlags) + if event.type != .flagsChanged { + // Key or mouse button down with modifiers held: another app's + // shortcut or gesture. + if !flags.isEmpty { chordTainted = true } + if chordDown && !chordAborted { + chordAborted = true + emit("aborted") + } + return + } + let previous = lastFlags + lastFlags = flags + if flags.isEmpty { chordTainted = false } + if !chordDown { + // Exactly the chosen modifiers, reached by adding a key (never by + // releasing an extra one). + if flags == mask && previous.isStrictSubset(of: mask) && !chordTainted { + chordDown = true + chordAborted = false + emit("pressed") + } + return + } + if !flags.isSuperset(of: mask) { + // One of them went up. + chordDown = false + if !chordAborted { emit("released") } + chordAborted = false + chordTainted = !flags.isEmpty && chordTainted + } else if flags != mask && !chordAborted { + // Another modifier joined (⌘⌥⇧…): not our shortcut. + chordAborted = true + chordTainted = true + emit("aborted") + } } @discardableResult From 1fe43f90b6719d70db26a2d7b15829e616672d61 Mon Sep 17 00:00:00 2001 From: Clement Guyon Date: Mon, 23 Nov 2026 15:00:34 +0100 Subject: [PATCH 11/18] fix: keep the meeting sentence id when a dictation starts MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Why: pressing the dictation shortcut during a meeting dropped the id of the sentence in progress; when that sentence had already been checkpointed, its final text was saved under a new id and the note got two lines (seen with an aborted ⌥⌘ press in a scratch test). What: beginDictation no longer clears the microphone phrase; the sentence's done replaces its provisional row. The recorder hint now says two modifiers alone are accepted. Proof: scratch test (deleted) went from two rows to one; dictation specs pass (119). --- apps/app_macos/assets/translations/fr.json | 2 +- .../lib/application/services/live_transcription.service.dart | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/apps/app_macos/assets/translations/fr.json b/apps/app_macos/assets/translations/fr.json index 6fbc117..e1a7855 100644 --- a/apps/app_macos/assets/translations/fr.json +++ b/apps/app_macos/assets/translations/fr.json @@ -286,7 +286,7 @@ "shortcut": "Raccourci", "shortcut_change": "Modifier", "shortcut_recording": "Tapez le raccourci…", - "shortcut_recording_hint": "Échap pour annuler. Ajoutez ⌃, ⌥ ou ⌘ à la touche.", + "shortcut_recording_hint": "Échap pour annuler. Deux modificateurs seuls (⌥ et ⌘, par exemple) ou des modificateurs et une touche.", "shortcut_unavailable": "Ce raccourci est déjà pris par une autre app. Choisissez-en un autre.", "shortcut_space": "{}Espace", "key_code": "Touche {}", diff --git a/apps/app_macos/lib/application/services/live_transcription.service.dart b/apps/app_macos/lib/application/services/live_transcription.service.dart index ded828e..9128cb0 100644 --- a/apps/app_macos/lib/application/services/live_transcription.service.dart +++ b/apps/app_macos/lib/application/services/live_transcription.service.dart @@ -1669,7 +1669,8 @@ final class LiveTranscriptionService { isFinal: true, sources: {AudioSource.input}, ); - _clearMicPhrase(); + // La phrase de réunion en cours garde son id : son `done` remplace le + // provisoire déjà sauvé (sinon deux lignes dans la note). return d; } From bd251936fa448e9f217aaa569c198f0665e3bdeb Mon Sep 17 00:00:00 2001 From: Clement Guyon Date: Mon, 23 Nov 2026 15:13:47 +0100 Subject: [PATCH 12/18] Spec: modifier-only chords act only once known to be ours (tapped, holdMs) --- .../global_shortcut_channel_test.dart | 37 +++++++++++-- .../global_shortcut_modifier_only_test.dart | 55 ++++++++++++------- .../test/helpers/dictation_fakes.dart | 12 +++- 3 files changed, 76 insertions(+), 28 deletions(-) diff --git a/apps/app_macos/test/core/platform/global_shortcut_channel_test.dart b/apps/app_macos/test/core/platform/global_shortcut_channel_test.dart index 957e86f..4634616 100644 --- a/apps/app_macos/test/core/platform/global_shortcut_channel_test.dart +++ b/apps/app_macos/test/core/platform/global_shortcut_channel_test.dart @@ -21,10 +21,10 @@ import 'package:ici_transcript/core/platform/global_shortcut_channel.dart'; /// global_shortcut_modifier_only_test.dart. /// /// EventChannel `com.icitranscript/global_shortcut_events` -/// - {type: 'pressed' | 'released' | 'cancel' | 'aborted'} ; tout autre type -/// est ignoré. `aborted` : une autre touche est enfoncée pendant que les -/// modificateurs d'un raccourci modificateurs seuls sont tenus (sens -/// détaillé dans global_shortcut_modifier_only_test.dart). +/// - {type: 'pressed' | 'released' | 'cancel' | 'aborted' | 'tapped'} ; tout +/// autre type est ignoré. `tapped` et `aborted` : raccourci modificateurs +/// seuls seulement (appui bref confirmé ; autre touche après un appui +/// maintenu), sens détaillé dans global_shortcut_modifier_only_test.dart. void main() { TestWidgetsFlutterBinding.ensureInitialized(); const MethodChannel method = MethodChannel( @@ -169,4 +169,33 @@ void main() { 'released', ]); }); + + test('événement tapped (appui bref d un raccourci modificateurs seuls) : ' + 'transmis', () async { + messenger.setMockStreamHandler( + events, + MockStreamHandler.inline( + onListen: (Object? arguments, MockStreamHandlerEventSink sink) { + sink + ..success({'type': 'tapped'}) + ..success({'type': 'pressed'}) + ..success({'type': 'released'}); + }, + ), + ); + final List seen = []; + + final StreamSubscription sub = GlobalShortcutChannel() + .events + .listen(seen.add); + await pumpEventQueue(); + await sub.cancel(); + + // Par le nom : la valeur `tapped` n'existe pas encore dans l'enum. + expect(seen.map((ShortcutEvent e) => e.name).toList(), [ + 'tapped', + 'pressed', + 'released', + ]); + }); } diff --git a/apps/app_macos/test/core/platform/global_shortcut_modifier_only_test.dart b/apps/app_macos/test/core/platform/global_shortcut_modifier_only_test.dart index a639346..22e7a27 100644 --- a/apps/app_macos/test/core/platform/global_shortcut_modifier_only_test.dart +++ b/apps/app_macos/test/core/platform/global_shortcut_modifier_only_test.dart @@ -12,29 +12,36 @@ import 'package:ici_transcript/core/platform/global_shortcut_channel.dart'; /// /// MethodChannel `com.icitranscript/global_shortcut` /// - `registerModifiers` {modifiers: int (masque Carbon : cmd 256, shift -/// 512, option 2048, control 4096 ; au moins deux, dont ⌃, ⌥ ou ⌘)} → -/// null. Remplace le raccourci précédent (à touche ou modificateurs -/// seuls). Lève PlatformException `ACCESSIBILITY_REQUIRED` si -/// l'Accessibilité n'est pas accordée : rien n'est posé (jamais un -/// raccourci posé mais muet). Dart : `registerModifiers(modifiers:)` rend -/// vrai si posé, faux sinon (refus ou plugin absent), sans lever. +/// 512, option 2048, control 4096 ; au moins deux, dont ⌃, ⌥ ou ⌘), +/// holdMs: int (seuil d'appui, = `DictationController.holdThreshold`, +/// seule source de la valeur)} → null. Remplace le raccourci précédent (à +/// touche ou modificateurs seuls). Lève PlatformException +/// `ACCESSIBILITY_REQUIRED` si l'Accessibilité n'est pas accordée : rien +/// n'est posé (jamais un raccourci posé mais muet). Dart : +/// `registerModifiers(modifiers:, holdThreshold:)` rend vrai si posé, faux +/// sinon (refus ou plugin absent), sans lever. /// - `unregister` retire aussi la surveillance des modificateurs. /// - `setCancelKeyEnabled` : inchangé (Échap pendant une dictée). /// -/// EventChannel `com.icitranscript/global_shortcut_events`, mêmes types : -/// - `pressed` : exactement les modificateurs choisis sont enfoncés (aucun -/// autre modificateur, aucune autre touche) ; -/// - `released` : l'un d'eux est relâché après un `pressed`, sans autre -/// touche entre-temps ; -/// - `aborted` (nouveau) : une touche autre qu'un modificateur (Échap -/// comprise) est enfoncée pendant que les modificateurs sont tenus après -/// un `pressed` : l'utilisateur tape un raccourci d'une autre app (⌘⌥Échap, -/// ⌘⌥D). Aucun `released` ne suit pour cet appui ; un `released` égaré est -/// ignoré par la dictée. Échap tapée avec les modificateurs tenus donne -/// `aborted`, jamais `cancel` ; +/// EventChannel `com.icitranscript/global_shortcut_events`. Un accord n'agit +/// qu'une fois su être le nôtre (revue de la PR #29 : ⌘⌥I, ⌘⌥Échap, ⌘⌥D ne +/// doivent ni allumer le point orange du micro ni couper une phrase de +/// réunion). Dès que exactement les modificateurs choisis sont enfoncés +/// (aucun autre modificateur, aucune autre touche), l'appui est INDÉCIS : +/// - pendant `holdMs`, une autre touche (Échap comprise) ou un bouton de +/// souris → RIEN n'est émis pour cet appui, ni maintenant ni au +/// relâchement ; +/// - relâché avant `holdMs` sans rien d'autre → `tapped` (nouveau) : appui +/// bref, bascule ; +/// - tenu `holdMs` sans rien d'autre → `pressed`, émis au seuil : appui +/// maintenu confirmé ; puis `released` au relâchement ; +/// - après `pressed`, une autre touche ou un clic → `aborted` (aucun +/// `released` ne suit ; un `released` égaré est ignoré par la dictée). +/// Échap tapée avec les modificateurs tenus donne `aborted` ou rien, +/// jamais `cancel` ; /// - `cancel` : inchangé, Échap pendant une dictée, modificateurs relâchés. /// -/// Le passage de `aborted` dans le flux Dart est épinglé dans +/// Le passage de `tapped` et `aborted` dans le flux Dart est épinglé dans /// global_shortcut_channel_test.dart. void main() { TestWidgetsFlutterBinding.ensureInitialized(); @@ -55,17 +62,21 @@ void main() { setUp(calls.clear); tearDown(() => messenger.setMockMethodCallHandler(method, null)); - test('registerModifiers envoie le masque seul, sans code de touche ; vrai ' - 'si posé', () async { + test('registerModifiers envoie le masque et le seuil d appui, sans code de ' + 'touche ; vrai si posé', () async { answer((_) => null); final bool ok = await GlobalShortcutChannel().registerModifiers( modifiers: 256 | 2048, + holdThreshold: const Duration(milliseconds: 300), ); expect(ok, isTrue); expect(calls.single.method, 'registerModifiers'); - expect(calls.single.arguments, {'modifiers': 2304}); + expect(calls.single.arguments, { + 'modifiers': 2304, + 'holdMs': 300, + }); }); test('Accessibilité absente : faux, sans lever', () async { @@ -73,6 +84,7 @@ void main() { final bool ok = await GlobalShortcutChannel().registerModifiers( modifiers: 2304, + holdThreshold: const Duration(milliseconds: 300), ); expect(ok, isFalse); @@ -81,6 +93,7 @@ void main() { test('plugin absent : faux, sans lever', () async { final bool ok = await GlobalShortcutChannel().registerModifiers( modifiers: 2304, + holdThreshold: const Duration(milliseconds: 300), ); expect(ok, isFalse); diff --git a/apps/app_macos/test/helpers/dictation_fakes.dart b/apps/app_macos/test/helpers/dictation_fakes.dart index 037608c..6f099af 100644 --- a/apps/app_macos/test/helpers/dictation_fakes.dart +++ b/apps/app_macos/test/helpers/dictation_fakes.dart @@ -57,11 +57,17 @@ final class FakeGlobalShortcutChannel extends GlobalShortcutChannel { /// absente). bool registerModifiersResult = true; - // ponytail: absent de GlobalShortcutChannel tant que le raccourci - // modificateurs seuls n'est pas codé ; devient alors une vraie surcharge. + /// Seuil d'appui transmis à chaque `registerModifiers` (null : non + /// transmis). + final List registeredHoldThresholds = []; + @override - Future registerModifiers({required int modifiers}) async { + Future registerModifiers({ + required int modifiers, + Duration? holdThreshold, + }) async { registeredModifiers.add(modifiers); + registeredHoldThresholds.add(holdThreshold); return registerModifiersResult; } From f04fb0e0637a0a350087a072bce5a8c82f488697 Mon Sep 17 00:00:00 2001 From: Clement Guyon Date: Mon, 23 Nov 2026 15:13:47 +0100 Subject: [PATCH 13/18] Spec: controller reacts to tapped and threshold-confirmed pressed --- ...odifier_only_shortcut_controller_test.dart | 92 ++++++++++++++----- 1 file changed, 68 insertions(+), 24 deletions(-) diff --git a/apps/app_macos/test/application/services/dictation/modifier_only_shortcut_controller_test.dart b/apps/app_macos/test/application/services/dictation/modifier_only_shortcut_controller_test.dart index aa80016..ef43f95 100644 --- a/apps/app_macos/test/application/services/dictation/modifier_only_shortcut_controller_test.dart +++ b/apps/app_macos/test/application/services/dictation/modifier_only_shortcut_controller_test.dart @@ -20,10 +20,17 @@ import '../../../helpers/live_service_fakes.dart'; /// Comportement épinglé : /// - le raccourci est posé par `registerModifiers` (masque Carbon), jamais /// par `register` (Carbon ne sait pas poser un raccourci sans touche) ; -/// - mêmes gestes qu'un raccourci à touche : appui bref (< 300 ms) = -/// bascule, appui maintenu = parler tant qu'il est tenu ; -/// - `aborted` (le plugin a vu une autre touche pendant que ⌘⌥ étaient -/// tenus : l'utilisateur tape ⌘⌥Échap ou ⌘⌥D d'une autre app) : +/// - un accord n'agit qu'une fois su être le nôtre (revue PR #29) : le +/// plugin ne dit rien pendant le seuil d'appui, que le contrôleur lui +/// transmet (`DictationController.holdThreshold`, seule source) ; ⌘⌥ puis +/// une touche ou un clic pendant ce seuil ne produit AUCUN événement, donc +/// rien ici (ni capture, ni micro de réunion détourné, ni collage) ; +/// - `tapped` (appui bref propre) = bascule : il démarre, le suivant arrête ; +/// - `pressed` arrive au seuil : appui maintenu déjà confirmé, capture +/// ouverte à ce moment ; `released` arrête quelle que soit l'attente entre +/// les deux (le seuil n'est jamais recompté côté Dart) ; +/// - `aborted` (autre touche ou clic après `pressed` : l'utilisateur tenait +/// ⌘⌥ puis a tapé ⌘⌥Échap ou ⌘⌥D d'une autre app) : /// - la dictée lancée par cet appui est jetée sans bruit : rien collé, /// rien copié, ni erreur ni « rien entendu », capture arrêtée, flux /// fermé, Échap libérée, serveur rendu à l'arbitre ; @@ -60,6 +67,12 @@ void main() { DictationSettings settings = clipboardMode, }) => DictationHarness(async)..launch(settings); + /// Appui bref propre, confirmé par le plugin. + void tap(DictationHarness d) { + d.shortcuts.emit(ShortcutEvent.tapped); + d.async.elapse(Duration.zero); + } + void abort(DictationHarness d) { d.shortcuts.emit(ShortcutEvent.aborted); d.async.elapse(Duration.zero); @@ -104,6 +117,11 @@ void main() { expect(d.shortcuts.registeredModifiers, [2304]); expect(d.shortcuts.registered, isEmpty); expect(d.controller.shortcutStatus, ShortcutStatus.registered); + expect( + d.shortcuts.registeredHoldThresholds.last, + DictationController.holdThreshold, + reason: 'le seuil vient du contrôleur, nulle part ailleurs', + ); }); }); @@ -130,20 +148,32 @@ void main() { }); group('mêmes gestes qu un raccourci à touche', () { - test('appui bref : la dictée continue ; un second appui bref l arrête et ' - 'produit le texte une fois', () { + test('tant que le plugin ne dit rien, rien ne s ouvre (accord indécis ' + 'ou raccourci d une autre app)', () { fakeAsync((FakeAsync async) { final DictationHarness d = launched(async); + final int startsBefore = d.process.starts.length; - d.press(); - async.elapse(const Duration(milliseconds: 120)); - d.release(); - d.say(20); + async.elapse(const Duration(seconds: 2)); + + expect(d.audio.startCalls, 0); + expect(d.remote.connects, isEmpty); + expect(d.process.starts.length, startsBefore); + expect(d.output.log, isEmpty); + }); + }); + + test('appui bref (tapped) : la dictée démarre et continue ; un second ' + 'appui bref l arrête et produit le texte une fois', () { + fakeAsync((FakeAsync async) { + final DictationHarness d = launched(async); + + tap(d); expect(d.state, isA()); + d.say(20); expect(d.remote.finalCommits, 0); - d.press(); - d.release(); + tap(d); expect(d.state, isA()); d.remote.emitDone('Bonjour à tous.'); async.elapse(Duration.zero); @@ -152,6 +182,20 @@ void main() { }); }); + test('pressed puis released 50 ms après : arrêt (le maintien est déjà ' + 'confirmé par le plugin, jamais pris pour une bascule)', () { + fakeAsync((FakeAsync async) { + final DictationHarness d = launched(async); + + d.press(); + async.elapse(const Duration(milliseconds: 50)); + d.release(); + + expect(d.state, isNot(isA())); + expect(d.audio.stopCalls, 1); + }); + }); + test('appui maintenu : parler tant que ⌘⌥ sont tenus, le relâchement ' 'arrête', () { fakeAsync((FakeAsync async) { @@ -172,8 +216,7 @@ void main() { test('Échap annule une dictée en cours, comme avant', () { fakeAsync((FakeAsync async) { final DictationHarness d = launched(async); - d.press(); - d.release(); + tap(d); d.say(5); d.cancel(); @@ -185,7 +228,7 @@ void main() { }); group('une autre touche pendant ⌘⌥ : raccourci d une autre app', () { - test('pendant les 300 ms : la dictée lancée par cet appui est jetée sans ' + test('juste après le seuil : la dictée lancée par cet appui est jetée sans ' 'bruit, rien n est collé', () { fakeAsync((FakeAsync async) { final DictationHarness d = launched(async, settings: pasteMode); @@ -231,11 +274,10 @@ void main() { 'un appui bref suivant l arrête', () { fakeAsync((FakeAsync async) { final DictationHarness d = launched(async); - d.press(); - d.release(); + tap(d); d.say(10); - // ⌘⌥D tapé dans une autre app pendant la dictée. + // ⌘⌥ tenus au-delà du seuil puis D (raccourci d'une autre app). d.press(); abort(d); final int sentBefore = d.remote.sentAudio.length; @@ -247,8 +289,7 @@ void main() { expect(d.remote.sentAudio.length, greaterThan(sentBefore)); expect(d.output.log, isEmpty); - d.press(); - d.release(); + tap(d); expect(d.state, isA()); d.remote.emitDone('Toujours là.'); async.elapse(Duration.zero); @@ -354,6 +395,11 @@ void main() { } } + void tapIn() { + d.shortcuts.emit(ShortcutEvent.tapped); + clock.elapse(Duration.zero); + } + void abortIn() { d.shortcuts.emit(ShortcutEvent.aborted); clock.elapse(Duration.zero); @@ -386,8 +432,7 @@ void main() { run(20, voiced: true); run(15); - d.press(); - d.release(); + tapIn(); run(10, voiced: true); d.press(); abortIn(); @@ -395,8 +440,7 @@ void main() { expect(d.state, isA()); expect(d.output.log, isEmpty); - d.press(); - d.release(); + tapIn(); run(20); async.elapse(const Duration(seconds: 2)); From 3705deb8e977026de6d4a7963b6afdeb76be22e1 Mon Sep 17 00:00:00 2001 From: Clement Guyon Date: Mon, 23 Nov 2026 15:13:48 +0100 Subject: [PATCH 14/18] Spec: no-speech timeout and maximum dictation duration --- .../dictation/dictation_time_limits_test.dart | 143 ++++++++++++++++++ 1 file changed, 143 insertions(+) create mode 100644 apps/app_macos/test/application/services/dictation/dictation_time_limits_test.dart diff --git a/apps/app_macos/test/application/services/dictation/dictation_time_limits_test.dart b/apps/app_macos/test/application/services/dictation/dictation_time_limits_test.dart new file mode 100644 index 0000000..d141612 --- /dev/null +++ b/apps/app_macos/test/application/services/dictation/dictation_time_limits_test.dart @@ -0,0 +1,143 @@ +import 'package:fake_async/fake_async.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:ici_transcript/application/services/dictation/dictation_controller.dart'; +import 'package:ici_transcript/application/services/dictation/dictation_preferences.dart'; + +import '../../../helpers/dictation_fakes.dart'; + +/// Aucune dictée n'attend sans fin un événement qui ne vient jamais (revue de +/// la PR #29) : un `released` ou un `aborted` que macOS n'a pas livré (champ +/// de saisie sécurisée qui cache les touches, accord mal vu par le plugin), +/// une bascule oubliée. Vaut pour tous les raccourcis. +/// +/// Bornes, en un seul endroit (`DictationController`) : +/// - `noSpeechTimeout` = 8 s : aucune parole depuis le début de la dictée → +/// elle finit sans bruit : capture arrêtée, rien collé ni copié, pas +/// d'erreur, Échap libérée ; +/// - `maxDictationDuration` = 3 min : la capture s'arrête, le texte dit +/// jusque-là est produit une fois ; un relâchement tardif ne fait rien de +/// plus. +/// +/// Parole = chunk voisé du faux micro (énergie non nulle). +void main() { + const DictationSettings clipboardMode = DictationSettings( + outputMode: DictationOutputMode.clipboard, + ); + + DictationHarness launched(FakeAsync async) => + DictationHarness(async)..launch(clipboardMode); + + int chunksIn(Duration d) => d.inMilliseconds ~/ 100; + + void expectEndedSilently(DictationHarness d, List seen) { + expect(d.state, isNot(isA())); + expect(d.audio.stopCalls, 1, reason: 'capture arrêtée'); + expect(d.output.log, isEmpty, reason: 'rien collé ni copié'); + expect(d.shortcuts.cancelKey.last, isFalse, reason: 'Échap libérée'); + expect(seen.whereType(), isEmpty, reason: 'sans bruit'); + expect(seen.whereType(), isEmpty); + } + + List watch(DictationHarness d) { + final List seen = []; + d.controller.stateStream.listen(seen.add); + d.async.elapse(Duration.zero); + return seen; + } + + test('bornes : 8 s sans parole, 3 min au plus', () { + expect(DictationController.noSpeechTimeout, const Duration(seconds: 8)); + expect( + DictationController.maxDictationDuration, + const Duration(minutes: 3), + ); + }); + + group('aucune parole', () { + test('bascule sans un mot : finit sans bruit à 8 s, pas avant', () { + fakeAsync((FakeAsync async) { + final DictationHarness d = launched(async); + final List seen = watch(d); + d.press(); + d.release(); // appui bref : bascule, plus aucun événement attendu + + d.say(chunksIn(DictationController.noSpeechTimeout) - 2, voiced: false); + expect(d.state, isA()); + d.say(3, voiced: false); + async.elapse(DictationController.finalTextTimeout); + + expectEndedSilently(d, seen); + }); + }); + + test('appui maintenu dont le relâchement n arrive jamais : finit sans ' + 'bruit à 8 s', () { + fakeAsync((FakeAsync async) { + final DictationHarness d = launched(async); + final List seen = watch(d); + d.press(); + + d.say(chunksIn(DictationController.noSpeechTimeout) + 1, voiced: false); + async.elapse(DictationController.finalTextTimeout); + + expectEndedSilently(d, seen); + }); + }); + + test('quelques mots au début : pas de fin à 8 s du début', () { + fakeAsync((FakeAsync async) { + final DictationHarness d = launched(async); + d.press(); + d.release(); + + d.say(10); + d.say(chunksIn(DictationController.noSpeechTimeout) - 10, voiced: false); + d.say(2, voiced: false); + + expect(d.state, isA()); + expect(d.audio.stopCalls, 0); + }); + }); + }); + + group('durée maximale', () { + test('bascule qui parle sans fin : arrêt à 3 min, le texte est produit ' + 'une fois', () { + fakeAsync((FakeAsync async) { + final DictationHarness d = launched(async); + d.press(); + d.release(); + + d.say(chunksIn(DictationController.maxDictationDuration) - 2); + expect(d.state, isA()); + expect(d.remote.finalCommits, 0); + d.say(3); + + expect(d.state, isA()); + expect(d.remote.finalCommits, 1); + d.remote.emitDone('Long discours.'); + async.elapse(Duration.zero); + expect(d.output.copies, ['Long discours.']); + }); + }); + + test('appui maintenu sans relâchement : arrêt à 3 min, texte produit ; ' + 'le relâchement tardif ne fait rien de plus', () { + fakeAsync((FakeAsync async) { + final DictationHarness d = launched(async); + d.press(); + + d.say(chunksIn(DictationController.maxDictationDuration) + 1); + expect(d.state, isA()); + d.remote.emitDone('Texte jusque-là.'); + async.elapse(Duration.zero); + d.release(); + async.elapse(const Duration(seconds: 1)); + + expect(d.output.copies, ['Texte jusque-là.']); + expect(d.remote.finalCommits, 1); + expect(d.audio.startCalls, 1); + }); + }); + }); +} From 46e4220a671dfa58b99d65cfbf4d0f8b306d863f Mon Sep 17 00:00:00 2001 From: Clement Guyon Date: Mon, 23 Nov 2026 15:13:48 +0100 Subject: [PATCH 15/18] Spec: retry modifier-only registration when the app resumes --- ...dictation_shortcut_accessibility_test.dart | 53 ++++++++++++++++++- 1 file changed, 52 insertions(+), 1 deletion(-) diff --git a/apps/app_macos/test/features/settings/dictation_shortcut_accessibility_test.dart b/apps/app_macos/test/features/settings/dictation_shortcut_accessibility_test.dart index 145081e..522af4d 100644 --- a/apps/app_macos/test/features/settings/dictation_shortcut_accessibility_test.dart +++ b/apps/app_macos/test/features/settings/dictation_shortcut_accessibility_test.dart @@ -49,7 +49,10 @@ import '../../helpers/settings_fakes.dart'; /// pas besoin de l'Accessibilité ; la ligne Accessibilité du bas reste) ; /// - jamais muet : au retour des Réglages Système avec l'Accessibilité /// accordée (`refreshAccessibility`, appelé à la reprise de l'app), le -/// raccourci est reposé et marche, sans le réenregistrer. +/// raccourci est reposé et marche, sans le réenregistrer ; +/// - et même Réglages fermés (revue PR #29) : après un refus +/// `ACCESSIBILITY_REQUIRED`, chaque retour au premier plan de l'app +/// (cycle de vie `resumed`) retente la pose, sans relancer l'app. void main() { late FakeGlobalShortcutChannel shortcuts; late FakeTextOutputChannel output; @@ -255,4 +258,52 @@ void main() { ); }); }); + + testWidgets('Réglages fermés : l app revient au premier plan avec ' + 'l Accessibilité accordée, ⌘⌥ est reposé sans relancer', ( + WidgetTester tester, + ) async { + saveModifierOnlyByHand(); + shortcuts.registerModifiersResult = false; + final ProviderContainer container = ProviderContainer( + overrides: [ + databaseProvider.overrideWithValue( + AppDatabase(NativeDatabase.memory()), + ), + processManagerChannelProvider.overrideWithValue( + FakeProcessManagerChannel(), + ), + audioCaptureChannelProvider.overrideWithValue( + FakeAudioCaptureChannel(), + ), + globalShortcutChannelProvider.overrideWithValue(shortcuts), + textOutputChannelProvider.overrideWithValue(output), + ], + ); + addTearDown(container.dispose); + ShortcutStatus status() => + container.read(dictationControllerProvider).shortcutStatus; + + await tester.runAsync(() async { + await container.read(kernelProvider.future); + await eventually( + () => expect(status(), ShortcutStatus.needsAccessibility), + ); + }); + + // L'utilisateur accorde l'Accessibilité dans les Réglages Système, puis + // revient à l'app (aucun écran de Réglages ouvert). + output.trusted = true; + shortcuts.registerModifiersResult = true; + tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.inactive); + tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed); + await tester.pump(); + + await tester.runAsync( + () => eventually(() { + expect(status(), ShortcutStatus.registered); + expect(shortcuts.registeredModifiers.last, 2304); + }), + ); + }); } From d80475022499eada5363cfd610e0044c7f388519 Mon Sep 17 00:00:00 2001 From: Clement Guyon Date: Mon, 23 Nov 2026 15:14:30 +0100 Subject: [PATCH 16/18] Spec: a pause after speech never ends a dictation --- .../dictation/dictation_time_limits_test.dart | 33 +++++++++++++++++-- 1 file changed, 30 insertions(+), 3 deletions(-) diff --git a/apps/app_macos/test/application/services/dictation/dictation_time_limits_test.dart b/apps/app_macos/test/application/services/dictation/dictation_time_limits_test.dart index d141612..09e8a5d 100644 --- a/apps/app_macos/test/application/services/dictation/dictation_time_limits_test.dart +++ b/apps/app_macos/test/application/services/dictation/dictation_time_limits_test.dart @@ -11,9 +11,12 @@ import '../../../helpers/dictation_fakes.dart'; /// une bascule oubliée. Vaut pour tous les raccourcis. /// /// Bornes, en un seul endroit (`DictationController`) : -/// - `noSpeechTimeout` = 8 s : aucune parole depuis le début de la dictée → -/// elle finit sans bruit : capture arrêtée, rien collé ni copié, pas -/// d'erreur, Échap libérée ; +/// - `noSpeechTimeout` = 8 s, SEULEMENT avant la première parole : personne +/// n'a parlé → la dictée finit sans bruit : capture arrêtée, rien collé ni +/// copié, pas d'erreur, Échap libérée. Après une parole, aucune pause, +/// même longue, ne l'arrête (décision du coordinateur, 2026-11-23) : seuls +/// le relâchement, le second appui, Échap ou la durée maximale la +/// terminent ; /// - `maxDictationDuration` = 3 min : la capture s'arrête, le texte dit /// jusque-là est produit une fois ; un relâchement tardif ne fait rien de /// plus. @@ -98,6 +101,30 @@ void main() { expect(d.audio.stopCalls, 0); }); }); + + test('une fois la parole entendue, une pause de 20 s n arrête pas : une ' + 'seule dictée avec les deux parties', () { + fakeAsync((FakeAsync async) { + final DictationHarness d = launched(async); + d.press(); + d.release(); + + d.say(10); + d.remote.pauseDetected(); + d.remote.emitDone('Première partie.'); + d.say(200, voiced: false); + expect(d.state, isA()); + expect(d.audio.stopCalls, 0); + d.say(10); + d.press(); + d.release(); + d.remote.emitDone('Seconde partie.'); + async.elapse(Duration.zero); + + expect(d.output.copies, ['Première partie. Seconde partie.']); + expect(d.audio.startCalls, 1); + }); + }); }); group('durée maximale', () { From b6da2d8a28587d739d84a451a9c15d68f950eb16 Mon Sep 17 00:00:00 2001 From: Clement Guyon Date: Mon, 23 Nov 2026 15:18:56 +0100 Subject: [PATCH 17/18] feat: act on a modifier-only chord only once it is ours; bound every dictation MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Why: review of PR #29: any ⌘⌥+key opened the microphone and an aborted press split a meeting sentence; a lost release or a forgotten toggle could keep a dictation open forever; Accessibility granted with Settings closed left the shortcut dead until relaunch. What: registerModifiers passes holdMs (from holdThreshold, the single source); the controller handles tapped (toggle start/stop) and treats pressed as an already-confirmed hold (no threshold recount); noSpeechTimeout (8 s, only before the first speech, ends silently) and maxDictationDuration (3 min, ends and delivers the text so far) bound every dictation; on app resume a shortcut refused for Accessibility is retried, Settings open or not. Proof: the new specs (channel, modifier-only controller, time limits, accessibility resume) and the dictation/core/settings specs pass (463). --- .../dictation/dictation_controller.dart | 87 ++++++++++++++++++- .../platform/global_shortcut_channel.dart | 15 +++- .../services/dictation.provider.dart | 12 +++ 3 files changed, 108 insertions(+), 6 deletions(-) diff --git a/apps/app_macos/lib/application/services/dictation/dictation_controller.dart b/apps/app_macos/lib/application/services/dictation/dictation_controller.dart index b8aac84..57d1e6e 100644 --- a/apps/app_macos/lib/application/services/dictation/dictation_controller.dart +++ b/apps/app_macos/lib/application/services/dictation/dictation_controller.dart @@ -1,4 +1,6 @@ import 'dart:async'; +import 'dart:math' as math; +import 'dart:typed_data'; import 'package:clock/clock.dart'; import 'package:core_data/datasources/remote/transcription.remote.data_source.dart'; @@ -145,6 +147,13 @@ final class DictationController { /// (bascule), un second appui l'arrête. static const Duration holdThreshold = Duration(milliseconds: 300); + /// Personne n'a parlé depuis l'appui : la dictée finit sans bruit. Ne + /// vaut qu'avant la première parole. + static const Duration noSpeechTimeout = Duration(seconds: 8); + + /// Au-delà, la capture s'arrête et le texte dit jusque-là est produit. + static const Duration maxDictationDuration = Duration(minutes: 3); + /// Texte final attendu au plus tard ce délai après la fin de la capture. static const Duration finalTextTimeout = Duration(seconds: 15); @@ -235,7 +244,10 @@ final class DictationController { // Modificateurs seuls : Carbon ne sait pas les poser, le plugin les // surveille (Accessibilité requise). final bool ok = keyCode == null - ? await _shortcuts.registerModifiers(modifiers: modifiers) + ? await _shortcuts.registerModifiers( + modifiers: modifiers, + holdThreshold: holdThreshold, + ) : await _shortcuts.register(keyCode: keyCode, modifiers: modifiers); if (ok) _shortcutEvents ??= _shortcuts.events.listen(_onShortcut); _shortcutStatus.add( @@ -249,6 +261,16 @@ final class DictationController { unawaited(_warmServer()); } + /// L'app revient au premier plan : un raccourci refusé faute + /// d'Accessibilité est retenté (accordée entre-temps dans les Réglages + /// Système), sans relancer l'app. + Future retryShortcut() async { + final DictationSettings? settings = _settings; + if (settings == null || !settings.enabled) return; + if (shortcutStatus != ShortcutStatus.needsAccessibility) return; + await apply(settings); + } + /// Prête le serveur à [work] (coach, diarization : un seul modèle à la /// fois en mémoire) : arrêté pendant le travail, relancé dès la fin si la /// dictée est activée. Rend le résultat ou l'erreur de [work]. @@ -386,9 +408,44 @@ final class DictationController { if (_run case final _Run run when !run.finished) _cancel(run); case ShortcutEvent.aborted: _onAborted(); + case ShortcutEvent.tapped: + _onTapped(); } } + /// Appui bref propre d'un raccourci modificateurs seuls : bascule. Il + /// démarre une dictée, ou arrête celle en cours. + void _onTapped() { + if (_live.isStarting) return; + final _Run? current = _run; + if (current != null && !current.finished) { + if (current.toggled && !current.captureEnded) _endCapture(current); + return; + } + unawaited(_begin(current, toggled: true)); + } + + /// Après une parole, une pause ne termine jamais : relâchement, second + /// appui, Échap ou durée maximale seulement. + void _heardSpeech(_Run run) { + if (run.heardSpeech) return; + run.heardSpeech = true; + run.noSpeechTimer?.cancel(); + } + + // Seuil de parole d'un chunk (PCM16) : au moins 2 % d'échantillons forts, + // comme la source distante (un clic isolé n'est pas de la parole). + static bool _isSpeech(AudioChunk chunk) { + final ByteData samples = ByteData.sublistView(chunk.data); + final int count = chunk.data.length ~/ 2; + if (count == 0) return false; + int loud = 0; + for (int i = 0; i < count; i++) { + if (samples.getInt16(i * 2, Endian.little).abs() > 500) loud++; + } + return loud >= math.max(3, count ~/ 50); + } + bool get _modifiersOnly => _settings?.shortcut.keyCode == null; /// Une autre touche (ou un clic) pendant que les modificateurs seuls sont @@ -443,15 +500,18 @@ final class DictationController { run.ignoreRelease = false; return; } - if (clock.now().difference(run.pressedAt) < holdThreshold) { + // Modificateurs seuls : `pressed` n'arrive qu'au seuil, le maintien est + // déjà confirmé par le plugin (jamais recompté ici). + if (!_modifiersOnly && + clock.now().difference(run.pressedAt) < holdThreshold) { run.toggled = true; // appui bref : l'écoute continue return; } _endCapture(run); } - Future _begin(_Run? previous) async { - final _Run run = _Run(clock.now()); + Future _begin(_Run? previous, {bool toggled = false}) async { + final _Run run = _Run(clock.now())..toggled = toggled; _run = run; if (_modelCached != null && !await _isModelCached()) { // Ni capture, ni Échap, ni serveur : Réglages propose le téléchargement. @@ -461,6 +521,17 @@ final class DictationController { } unawaited(_shortcuts.setCancelKeyEnabled(true)); _arbiter.dictationStarted(); + // Bornes : personne n'a parlé (fin sans bruit), ou trop long (texte dit + // jusque-là produit). Un relâchement jamais livré n'attend pas sans fin. + run.noSpeechTimer = Timer(noSpeechTimeout, () { + if (!run.finished && !run.captureEnded && !run.heardSpeech) _cancel(run); + }); + run.maxTimer = Timer(maxDictationDuration, () { + if (!run.finished && !run.captureEnded) { + run.ignoreRelease = true; + _endCapture(run); + } + }); // Ancien flux resté ouvert après un délai de garde : fermé d'abord. if (previous != null && previous.streaming) { previous.late = false; @@ -521,6 +592,7 @@ final class DictationController { if (run.finished || run.captureEnded || chunk.source != AudioSource.input) { return; } + if (!run.heardSpeech && _isSpeech(chunk)) _heardSpeech(run); if (run.streaming) { _remote.sendAudio(chunk); return; @@ -728,6 +800,8 @@ final class DictationController { if (run.finished) return; run.finished = true; run.finalTimer?.cancel(); + run.noSpeechTimer?.cancel(); + run.maxTimer?.cancel(); _stopCapture(run); run.buffer.clear(); unawaited(_shortcuts.setCancelKeyEnabled(false)); @@ -794,6 +868,11 @@ final class _Run { /// Modificateurs seuls : second appui d'une bascule, arrêt au relâchement. bool stopOnRelease = false; + + /// Une parole a été entendue : plus de fin faute de parole. + bool heardSpeech = false; + Timer? noSpeechTimer; + Timer? maxTimer; bool captureEnded = false; bool committed = false; bool streaming = false; diff --git a/apps/app_macos/lib/core/platform/global_shortcut_channel.dart b/apps/app_macos/lib/core/platform/global_shortcut_channel.dart index 959e7c3..194fa26 100644 --- a/apps/app_macos/lib/core/platform/global_shortcut_channel.dart +++ b/apps/app_macos/lib/core/platform/global_shortcut_channel.dart @@ -5,7 +5,11 @@ import 'package:flutter/services.dart'; /// [aborted] : une autre touche ou un clic pendant que les modificateurs /// d'un raccourci « modificateurs seuls » sont tenus (raccourci d'une autre /// app) ; aucun [released] ne suit pour cet appui. -enum ShortcutEvent { pressed, released, cancel, aborted } +/// +/// [tapped] : appui bref propre d'un raccourci « modificateurs seuls » +/// (relâché avant le seuil, rien d'autre) ; pour ces raccourcis [pressed] +/// n'arrive qu'au seuil, l'appui maintenu étant alors confirmé. +enum ShortcutEvent { pressed, released, cancel, aborted, tapped } /// Dart wrapper autour du plugin Swift GlobalShortcutPlugin (raccourci /// global Carbon, appui maintenu pour dicter, Échap pour annuler). @@ -28,6 +32,7 @@ class GlobalShortcutChannel { {'type': 'released'} => ShortcutEvent.released, {'type': 'cancel'} => ShortcutEvent.cancel, {'type': 'aborted'} => ShortcutEvent.aborted, + {'type': 'tapped'} => ShortcutEvent.tapped, _ => null, }, ) @@ -53,10 +58,16 @@ class GlobalShortcutChannel { /// Raccourci « modificateurs seuls » (masque Carbon, ⌘⌥ = 2304), à la /// place du précédent. Faux si refusé (Accessibilité absente) ou plugin /// absent. - Future registerModifiers({required int modifiers}) async { + /// Le plugin ne dit rien pendant [holdThreshold] : un accord suivi d'une + /// autre touche ou d'un clic n'est jamais le nôtre. + Future registerModifiers({ + required int modifiers, + Duration? holdThreshold, + }) async { try { await _method.invokeMethod('registerModifiers', { 'modifiers': modifiers, + if (holdThreshold != null) 'holdMs': holdThreshold.inMilliseconds, }); return true; } on PlatformException { diff --git a/apps/app_macos/lib/core/providers/services/dictation.provider.dart b/apps/app_macos/lib/core/providers/services/dictation.provider.dart index c03cb30..ef80f6a 100644 --- a/apps/app_macos/lib/core/providers/services/dictation.provider.dart +++ b/apps/app_macos/lib/core/providers/services/dictation.provider.dart @@ -2,6 +2,7 @@ import 'dart:async'; import 'package:core_data/datasources/remote/impl/transcription.remote.data_source.impl.dart'; import 'package:core_foundation/logging/logger.dart'; +import 'package:flutter/widgets.dart'; import 'package:ici_transcript/application/services/dictation/dictation_controller.dart'; import 'package:ici_transcript/application/services/dictation/dictation_preferences.dart'; import 'package:ici_transcript/core/platform/global_shortcut_channel.dart'; @@ -99,7 +100,18 @@ DictationController dictationController(Ref ref) { controller.stateStream, ref.read(dictationActiveProvider.notifier).set, ); + // Retour au premier plan : un raccourci refusé faute d'Accessibilité est + // retenté, même Réglages fermés. Sans binding (tests sans widgets) : rien. + AppLifecycleListener? lifecycle; + try { + lifecycle = AppLifecycleListener( + onResume: () => unawaited(controller.retryShortcut()), + ); + } catch (_) { + lifecycle = null; + } ref.onDispose(() async { + lifecycle?.dispose(); await dictating.cancel(); await controller.dispose(); await remote.dispose(); From 4b42b32d18e05321225c6036efd045b17736bcc8 Mon Sep 17 00:00:00 2001 From: Clement Guyon Date: Mon, 23 Nov 2026 15:18:56 +0100 Subject: [PATCH 18/18] feat: decide modifier-only chords natively with a hold threshold and event counters MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Why: a key down consumed by another app's hotkey (⌘⌥D, ⌘⌥Esc) is not delivered to a global NSEvent monitor, so a quick chord looked like a clean tap of ours. What: after exactly the chosen modifiers go down the press is undecided and nothing is emitted for holdMs; a clean release before -> tapped; a clean hold to the threshold -> pressed then released; any key, mouse button or extra modifier -> nothing (aborted after pressed). Cleanliness is checked against CGEventSource.counterForEventType(.hidSystemState) for key and mouse downs, snapshotted at chord down and at pressed; monitors stay for flagsChanged and early rejection. Proof: throwaway probe (F19 posted with CGEvent while a Carbon hotkey held it: hotkey fired, global monitor saw nothing, keyDown counter +1); flutter build macos --debug links. Not run live. --- .../macos/Runner/GlobalShortcutPlugin.swift | 139 +++++++++++++----- 1 file changed, 106 insertions(+), 33 deletions(-) diff --git a/apps/app_macos/macos/Runner/GlobalShortcutPlugin.swift b/apps/app_macos/macos/Runner/GlobalShortcutPlugin.swift index 7976fdf..c9e3605 100644 --- a/apps/app_macos/macos/Runner/GlobalShortcutPlugin.swift +++ b/apps/app_macos/macos/Runner/GlobalShortcutPlugin.swift @@ -23,12 +23,24 @@ import Foundation /// - `setCancelKeyEnabled` {enabled} -> nil: Escape is a hotkey only while /// a dictation runs, so it keeps working in other apps the rest of the time. /// Event channel `com.icitranscript/global_shortcut_events`: -/// {type: pressed | released | cancel | aborted}, always on the main thread. -/// Modifier-only: `pressed` when exactly the chosen modifiers become held -/// (caps lock, fn and numeric pad flags ignored); `released` when one of -/// them goes up; `aborted` (and no `released`) when a key or a mouse button -/// goes down, or another modifier joins, while they are held: that was -/// another app's shortcut (⌘⌥Esc, ⌘⌥-drag in Finder). +/// {type: pressed | released | cancel | aborted | tapped}, always on the +/// main thread. +/// Modifier-only (`registerModifiers` {modifiers, holdMs}): a chord acts only +/// once it is known to be ours. When exactly the chosen modifiers become held +/// (caps lock, fn and numeric pad flags ignored) the press is undecided and +/// NOTHING is emitted for holdMs; released before holdMs with nothing else -> +/// `tapped`; still held at holdMs with nothing else -> `pressed`, then +/// `released` when one of them goes up; any key, mouse button or extra +/// modifier while undecided -> no event at all; after `pressed` -> `aborted` +/// (and no `released`). "Nothing else" is decided by the system-wide event +/// counters, not only by the monitors: a key down consumed by another app's +/// hotkey (⌘⌥D, ⌘⌥Esc) is not delivered to a global monitor but is counted. +/// - https://developer.apple.com/documentation/coregraphics/cgeventsource/counterforeventtype(_:eventtype:) +/// ("count of events of a given type seen since the window server +/// started"; modifiers count as flagsChanged, not keyDown; autorepeat not +/// counted). Checked with a throwaway probe on 2026-11-23: a synthetic F19 +/// consumed by a Carbon hotkey was not seen by the global monitor but +/// raised the .hidSystemState keyDown counter by one. /// NSEvent monitors (Apple documentation): /// - https://developer.apple.com/documentation/appkit/nsevent/addglobalmonitorforevents(matching:handler:) /// (events of other apps only; key events require Accessibility) @@ -68,11 +80,14 @@ class GlobalShortcutPlugin: NSObject, FlutterPlugin, FlutterStreamHandler { private var cancelRefs: [EventHotKeyRef] = [] private var mainModifiers: UInt32 = 0 - // Modifier-only shortcut (NSEvent monitors). + // Modifier-only shortcut (NSEvent monitors + event counters). + private enum ChordPhase { case idle, undecided, down, rejected } private var chordMask: NSEvent.ModifierFlags? + private var chordHold: TimeInterval = 0.3 private var monitors: [Any] = [] - private var chordDown = false - private var chordAborted = false + private var chordPhase: ChordPhase = .idle + private var chordCount: UInt32 = 0 + private var chordTimer: DispatchWorkItem? // A key went down while modifiers were held: no `pressed` until every // modifier is up (releasing ⇧ of ⌘⌥⇧4 must not start a dictation). private var chordTainted = false @@ -137,7 +152,8 @@ class GlobalShortcutPlugin: NSObject, FlutterPlugin, FlutterStreamHandler { )) return } - installChord(Self.flags(fromCarbon: UInt32(modifiers))) + let holdMs = args?["holdMs"] as? Int ?? 300 + installChord(Self.flags(fromCarbon: UInt32(modifiers)), hold: Double(holdMs) / 1000) result(nil) case "keyLabel": guard let keyCode = args?["keyCode"] as? Int else { @@ -296,10 +312,10 @@ class GlobalShortcutPlugin: NSObject, FlutterPlugin, FlutterStreamHandler { return flags } - private func installChord(_ mask: NSEvent.ModifierFlags) { + private func installChord(_ mask: NSEvent.ModifierFlags, hold: TimeInterval) { chordMask = mask - chordDown = false - chordAborted = false + chordHold = hold + chordPhase = .idle chordTainted = false lastFlags = NSEvent.modifierFlags.intersection(Self.chordFlags) let events: NSEvent.EventTypeMask = [ @@ -322,11 +338,23 @@ class GlobalShortcutPlugin: NSObject, FlutterPlugin, FlutterStreamHandler { monitors.forEach { NSEvent.removeMonitor($0) } monitors = [] chordMask = nil - chordDown = false - chordAborted = false + chordTimer?.cancel() + chordTimer = nil + chordPhase = .idle chordTainted = false } + /// Key and mouse button downs seen system-wide (HID state), including + /// those consumed by another app's hotkey. + private static func inputCount() -> UInt32 { + let types: [CGEventType] = [.keyDown, .leftMouseDown, .rightMouseDown, .otherMouseDown] + return types.reduce(UInt32(0)) { + $0 &+ CGEventSource.counterForEventType(.hidSystemState, eventType: $1) + } + } + + private var otherInputSinceSnapshot: Bool { Self.inputCount() != chordCount } + private func onChordEvent(_ event: NSEvent) { guard let mask = chordMask else { return } let flags = event.modifierFlags.intersection(Self.chordFlags) @@ -334,37 +362,82 @@ class GlobalShortcutPlugin: NSObject, FlutterPlugin, FlutterStreamHandler { // Key or mouse button down with modifiers held: another app's // shortcut or gesture. if !flags.isEmpty { chordTainted = true } - if chordDown && !chordAborted { - chordAborted = true + switch chordPhase { + case .undecided: reject() + case .down: + chordPhase = .rejected emit("aborted") + case .idle, .rejected: break } return } let previous = lastFlags lastFlags = flags if flags.isEmpty { chordTainted = false } - if !chordDown { + switch chordPhase { + case .idle: // Exactly the chosen modifiers, reached by adding a key (never by // releasing an extra one). if flags == mask && previous.isStrictSubset(of: mask) && !chordTainted { - chordDown = true - chordAborted = false - emit("pressed") + startUndecided() } - return + case .undecided: + if !flags.isSuperset(of: mask) { + // Released before the threshold: ours only if nothing else + // happened anywhere. + let clean = !otherInputSinceSnapshot + cancelTimer() + chordPhase = .idle + if clean { emit("tapped") } + } else if flags != mask { + reject() // another modifier joined (⌘⌥⇧…) + } + case .down: + if !flags.isSuperset(of: mask) { + chordPhase = .idle + // A key consumed by another app's hotkey while held. + emit(otherInputSinceSnapshot ? "aborted" : "released") + } else if flags != mask { + chordPhase = .rejected + chordTainted = true + emit("aborted") + } + case .rejected: + if !flags.isSuperset(of: mask) { chordPhase = .idle } } - if !flags.isSuperset(of: mask) { - // One of them went up. - chordDown = false - if !chordAborted { emit("released") } - chordAborted = false - chordTainted = !flags.isEmpty && chordTainted - } else if flags != mask && !chordAborted { - // Another modifier joined (⌘⌥⇧…): not our shortcut. - chordAborted = true - chordTainted = true - emit("aborted") + } + + private func startUndecided() { + chordPhase = .undecided + chordCount = Self.inputCount() + let timer = DispatchWorkItem { [weak self] in self?.onHoldThreshold() } + chordTimer = timer + DispatchQueue.main.asyncAfter(deadline: .now() + chordHold, execute: timer) + } + + private func onHoldThreshold() { + chordTimer = nil + guard chordPhase == .undecided, let mask = chordMask else { return } + let held = NSEvent.modifierFlags.intersection(Self.chordFlags) == mask + guard held, !otherInputSinceSnapshot else { + reject() + return } + chordPhase = .down + chordCount = Self.inputCount() + emit("pressed") + } + + /// Not ours: no event for this press, wait for its modifiers to go up. + private func reject() { + cancelTimer() + chordPhase = .rejected + chordTainted = true + } + + private func cancelTimer() { + chordTimer?.cancel() + chordTimer = nil } @discardableResult