| 1 | using CascadeIDE.Features.Editor.Application; |
| 2 | using CascadeIDE.Services; |
| 3 | |
| 4 | namespace CascadeIDE.Features.Editor; |
| 5 | |
| 6 | /// <summary> |
| 7 | /// Один hi-freq throttler на главное окно (ADR 0103): не N фоновых consumer на N вкладок. |
| 8 | /// Стабилизированный выход обрабатывается только если <see cref="EditorInputDelta.FilePath"/> |
| 9 | /// совпадает с <see cref="CurrentFilePath"/>. |
| 10 | /// </summary> |
| 11 | public sealed partial class EditorWorkspaceViewModel |
| 12 | { |
| 13 | private EditorStabilizedInputThrottler? _editorStabilizedThrottler; |
| 14 | private CancellationTokenSource? _editorStabilizedCts; |
| 15 | private Action<EditorInputDelta>? _activeEditorStabilizedHudHandler; |
| 16 | |
| 17 | internal void SetActiveEditorStabilizedHudHandler(Action<EditorInputDelta>? handler) |
| 18 | { |
| 19 | _activeEditorStabilizedHudHandler = handler; |
| 20 | EnsureEditorStabilizedInputStarted(); |
| 21 | } |
| 22 | |
| 23 | internal void ClearActiveEditorStabilizedHudHandlerIfEquals(Action<EditorInputDelta>? handler) |
| 24 | { |
| 25 | if (ReferenceEquals(_activeEditorStabilizedHudHandler, handler)) |
| 26 | _activeEditorStabilizedHudHandler = null; |
| 27 | } |
| 28 | |
| 29 | internal bool TryPostEditorStabilizedInput(EditorInputDelta delta) |
| 30 | { |
| 31 | EnsureEditorStabilizedInputStarted(); |
| 32 | return _editorStabilizedThrottler!.TryPost(delta); |
| 33 | } |
| 34 | |
| 35 | private void EnsureEditorStabilizedInputStarted() |
| 36 | { |
| 37 | if (_editorStabilizedThrottler is not null) |
| 38 | return; |
| 39 | _editorStabilizedCts = new CancellationTokenSource(); |
| 40 | _editorStabilizedThrottler = new EditorStabilizedInputThrottler(UiScheduler.Default, TimeSpan.FromMilliseconds(24)); |
| 41 | _editorStabilizedThrottler.Start(OnEditorStabilizedInput, _editorStabilizedCts.Token); |
| 42 | } |
| 43 | |
| 44 | private void OnEditorStabilizedInput(EditorInputDelta d) |
| 45 | { |
| 46 | var path = CurrentFilePath; |
| 47 | if (string.IsNullOrEmpty(d.FilePath) || string.IsNullOrEmpty(path) |
| 48 | || !EditorTextCoordinateUtilities.PathsReferToSameFile(d.FilePath, path)) |
| 49 | return; |
| 50 | |
| 51 | _activeEditorStabilizedHudHandler?.Invoke(d); |
| 52 | _host.HostUpdateCodeNavigationMapCaretOffset(d.CaretOffset); |
| 53 | } |
| 54 | |
| 55 | internal void ShutdownEditorStabilizedInput() |
| 56 | { |
| 57 | _activeEditorStabilizedHudHandler = null; |
| 58 | _editorStabilizedCts?.Cancel(); |
| 59 | if (_editorStabilizedThrottler is { } t) |
| 60 | { |
| 61 | try |
| 62 | { |
| 63 | t.DisposeAsync().AsTask().GetAwaiter().GetResult(); |
| 64 | } |
| 65 | catch |
| 66 | { |
| 67 | } |
| 68 | } |
| 69 | |
| 70 | _editorStabilizedThrottler = null; |
| 71 | _editorStabilizedCts?.Dispose(); |
| 72 | _editorStabilizedCts = null; |
| 73 | } |
| 74 | } |
| 75 | |