-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinit.lua
More file actions
1018 lines (851 loc) · 30.2 KB
/
Copy pathinit.lua
File metadata and controls
1018 lines (851 loc) · 30.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
--[[
================================================================================
UI LAYER - PROVIDER-AGNOSTIC REFACTORING GUIDE
================================================================================
PURPOSE:
Provides user interface utilities including selection tracking, notifications,
immersive mode, and visual feedback. Should be completely provider-agnostic,
emitting events that handlers can subscribe to.
ARCHITECTURAL PRINCIPLES:
1. UI operations are provider-independent
2. Emit events, don't call handlers directly
3. Selection extraction is a reusable utility
4. Visual feedback uses standard Neovim APIs
5. No business logic, only presentation
CURRENT ARCHITECTURAL VIOLATIONS:
☐ get_current_selection() logic could be extracted to utils/selection.lua
☐ Selection tracking directly calls handler methods (should emit events)
☐ Immersive mode couples to specific provider features
REQUIRED REFACTORING:
1. EXTRACT SELECTION UTILITY (Priority: HIGH)
FROM: lua/diffusion/ui/init.lua
TO: lua/diffusion/utils/selection.lua
CREATE: get_visual_marks()
- Returns {file_path, start_line, end_line, text} or nil
- Handles visual marks '< and '>
- Handles current mode detection
- Fallback to word/line under cursor
- Reusable by commands and UI layer
WHY: DiffusionSend command needs this, UI needs this
- Avoid duplication
- Single source of truth for selection extraction
- Testable in isolation
2. DECOUPLE SELECTION TRACKING (Priority: MEDIUM)
CURRENT: Selection tracking calls protocol:send_selection()
SHOULD: Emit "ui:selection_changed" event
- Handlers subscribe if they want real-time tracking
- Claude: Subscribes, sends MCP selection_changed
- OpenCode: Doesn't subscribe (no real-time tracking)
- Makes feature opt-in per provider
3. DOCUMENT VISUAL SELECTION MODES (Priority: LOW)
ADD COMMENTS explaining:
- Visual mode ('v'): Character-wise selection
- Visual Line ('V'): Line-wise selection
- Visual Block ('\22'): Block selection
- Mark behavior: '< and '> persist after exit
- Column indexing: 0-based vs 1-based conversions
PROVIDER-SPECIFIC VS GENERIC OPERATIONS:
GENERIC (belongs in this file):
- Visual selection extraction (vim.fn.getpos, marks)
- Cursor position tracking
- Mode detection (vim.fn.mode)
- Notifications (vim.notify)
- Immersive mode UI (overlay, statusline)
- Visual feedback (virtual text, highlights)
- Selection debouncing
PROVIDER-SPECIFIC (does NOT belong here):
- MCP selection_changed format (belongs in Claude handler)
- HTTP endpoint selection sync (belongs in OpenCode handler)
- At-mention message creation (belongs in handlers)
- Provider-specific notification formats
SELECTION EXTRACTION DETAILS:
Visual Marks:
- '< = Start of last visual selection (line, col)
- '> = End of last visual selection (line, col)
- Persist after exiting visual mode
- Use vim.fn.getpos("'<") and vim.fn.getpos("'>")
- Format: {bufnum, lnum, col, off}
Mode Detection:
- vim.fn.mode() returns current mode
- 'v' = visual, 'V' = visual-line, '\22' = visual-block
- 'n' = normal (marks may still be valid)
- Must check mode before assuming visual selection active
Column Indexing:
- vim.fn.getpos() returns 1-based column
- nvim_buf_get_text() expects 0-based column
- Must convert: col_0based = col_1based - 1
- End column is exclusive in nvim_buf_get_text
REFACTORING CHECKLIST:
☐ Extract selection logic to utils/selection.lua
☐ Create get_visual_marks() utility function
☐ Update UI layer to use new utility
☐ Update DiffusionSend to use new utility
☐ Change selection tracking to emit events
☐ Add unit tests for selection utility
☐ Document mode detection behavior
☐ Update this header as refactoring progresses
NOTE: This header must be updated as each refactoring task is completed.
Mark checkboxes with ☑ when done.
================================================================================
--]]
-- UI utilities for diffusion.nvim
-- Handles user interface operations and interactions
local UI = {}
function UI:new(events, config)
local instance = {
_events = events,
_logger = require('diffusion.utils.logger'):child("UI"),
_selection_tracker = nil,
_immersive_mode = false,
_ticker = nil,
_virtual_text = nil,
_config = config or {},
_event_subscriptions = {}, -- Track event subscriptions for cleanup
_immersive_event_subscriptions = {}, -- Track immersive mode subscriptions separately
_stats = {
selections_captured = 0,
notifications_sent = 0,
ui_interactions = 0
}
}
setmetatable(instance, { __index = self })
-- Basic notifications for server/service events (with subscription tracking)
if instance._events then
local server_started_handler = function(d)
instance:show_notification(string.format('Diffusion %s server on %s:%s', d.protocol or '-', '127.0.0.1', d.port or '?'), 'info')
end
local service_switched_handler = function(d)
instance:show_notification(string.format('Service: %s -> %s', tostring(d.from), tostring(d.to)), 'trace')
end
instance._events:on('server:started', server_started_handler)
instance._events:on('service_switched', service_switched_handler)
-- Track subscriptions for cleanup
table.insert(instance._event_subscriptions, { event = 'server:started', handler = server_started_handler })
table.insert(instance._event_subscriptions, { event = 'service_switched', handler = service_switched_handler })
end
return instance
end
-- Alias for new() to match expected interface
function UI:init(events, config)
return self:new(events, config)
end
-- Get current text selection
function UI:get_current_selection()
-- Track stats for UI monitoring
self._stats.selections_captured = self._stats.selections_captured + 1
-- Delegate to centralized selection utility
local selection_util = require('diffusion.utils.selection')
local selection = selection_util.get_current_selection()
-- UI-specific logging
self._logger:debug("Captured selection via utility", {
file = selection and selection.file_path,
text_length = selection and selection.text and #selection.text or 0,
selection_type = selection and selection.selection_type or "none"
})
return selection
end
-- Get visual selection
function UI:_get_visual_selection()
local mode = vim.fn.mode()
-- If currently in visual mode, use live selection
if mode:match('[vV\22]') then
-- Get current cursor position and visual start
local cursor_pos = vim.api.nvim_win_get_cursor(0)
local start_pos = vim.fn.getpos('v') -- Visual start position
if start_pos[2] == 0 then
return nil
end
-- Determine selection bounds (handle selection direction) with correct 0-based columns
local start_line, start_col0, end_line, end_col0
local v_line1, v_col1 = start_pos[2], start_pos[3] -- getpos('v') is 1-based col
local cur_line1, cur_col0 = cursor_pos[1], cursor_pos[2] -- cursor col is 0-based
local v_col0 = math.max(0, (v_col1 or 1) - 1)
if v_line1 < cur_line1 or (v_line1 == cur_line1 and v_col0 <= cur_col0) then
start_line, start_col0 = v_line1, v_col0
end_line, end_col0 = cur_line1, cur_col0
else
start_line, start_col0 = cur_line1, cur_col0
end_line, end_col0 = v_line1, v_col0
end
-- Handle different visual modes
if mode == 'V' then
-- Visual line mode: select whole lines
start_col0 = 0
local eol_col1 = vim.fn.col({ end_line, '$' }) or 1
end_col0 = math.max(0, eol_col1 - 1)
elseif mode == '\22' then
-- Visual block mode: handle block selection
-- For now, treat as regular selection
end
-- Ensure columns are ordered safely
if start_line == end_line and start_col0 > end_col0 then
start_col0, end_col0 = end_col0, start_col0
end
-- Get selected text (nvim_buf_get_text uses 0-based, end_col is exclusive-friendly)
local lines = vim.api.nvim_buf_get_text(0, start_line - 1, start_col0, end_line - 1, end_col0, {})
local selected_text = table.concat(lines, '\n')
if selected_text == "" then
return nil
end
return {
text = selected_text,
file_path = vim.api.nvim_buf_get_name(0),
start_line = start_line,
start_col = start_col0 + 1, -- store as 1-based for consistency elsewhere
end_line = end_line,
end_col = end_col0 + 1,
selection_type = "visual_live"
}
else
-- Not in visual mode, use marks
local start_pos = vim.fn.getpos("'<")
local end_pos = vim.fn.getpos("'>")
-- Check if marks are valid
if start_pos[2] == 0 or end_pos[2] == 0 then
return nil
end
-- Convert to 0-based indexing for nvim_buf_get_text and normalize
local start_line0 = start_pos[2] - 1
local start_col0 = math.max(0, (start_pos[3] or 1) - 1)
local end_line0 = end_pos[2] - 1
local end_col0 = math.max(0, (end_pos[3] or 1) - 1)
if start_line0 == end_line0 and start_col0 > end_col0 then
start_col0, end_col0 = end_col0, start_col0
end
-- Get selected text without yanking (non-intrusive)
local lines = vim.api.nvim_buf_get_text(0, start_line0, start_col0, end_line0, end_col0, {})
local selected_text = table.concat(lines, '\n')
if selected_text == "" then
return nil
end
return {
text = selected_text,
file_path = vim.api.nvim_buf_get_name(0),
start_line = start_pos[2],
start_col = start_pos[3],
end_line = end_pos[2],
end_col = end_pos[3],
selection_type = "visual_marks"
}
end
end
-- Get previous selection (from '< and '> marks)
function UI:_get_previous_selection()
local start_pos = vim.fn.getpos("'<")
local end_pos = vim.fn.getpos("'>")
-- Check if marks are valid
if start_pos[2] == 0 or end_pos[2] == 0 then
return nil
end
-- Get text between marks
local lines = vim.api.nvim_buf_get_lines(0, start_pos[2] - 1, end_pos[2], false)
if #lines == 0 then
return nil
end
-- Handle single line selection
if #lines == 1 then
local line = lines[1]
local start_col = math.min(start_pos[3], #line + 1)
local end_col = math.min(end_pos[3], #line + 1)
lines[1] = line:sub(start_col, end_col)
else
-- Multi-line selection
if #lines > 1 then
-- Trim first line
local first_line = lines[1]
local start_col = math.min(start_pos[3], #first_line + 1)
lines[1] = first_line:sub(start_col)
-- Trim last line
local last_line = lines[#lines]
local end_col = math.min(end_pos[3], #last_line + 1)
lines[#lines] = last_line:sub(1, end_col)
end
end
local selected_text = table.concat(lines, '\n')
if selected_text == "" then
return nil
end
return {
text = selected_text,
file_path = vim.api.nvim_buf_get_name(0),
start_line = start_pos[2],
start_col = start_pos[3],
end_line = end_pos[2],
end_col = end_pos[3],
selection_type = "previous"
}
end
-- Get fallback selection (current line or word)
function UI:_get_fallback_selection()
local cursor_pos = vim.api.nvim_win_get_cursor(0)
local line_num = cursor_pos[1]
local col_num = cursor_pos[2]
-- Try to get word under cursor first
local word = vim.fn.expand('<cword>')
if word and word ~= "" then
return {
text = word,
file_path = vim.api.nvim_buf_get_name(0),
start_line = line_num,
start_col = col_num,
end_line = line_num,
end_col = col_num + #word,
selection_type = "word"
}
end
-- Fallback to current line
local line = vim.api.nvim_get_current_line()
if line and line ~= "" then
return {
text = line,
file_path = vim.api.nvim_buf_get_name(0),
start_line = line_num,
start_col = 1,
end_line = line_num,
end_col = #line,
selection_type = "line"
}
end
return nil
end
-- Setup selection tracking
function UI:setup_selection_tracking(enabled)
if not enabled then
if self._selection_tracker then
self:_cleanup_selection_tracking()
end
return
end
self._logger:debug("Setting up selection tracking")
-- Create autocommand group
local augroup = vim.api.nvim_create_augroup('DiffusionSelectionTracking', { clear = true })
-- Track cursor movements and selections
vim.api.nvim_create_autocmd({'CursorMoved', 'CursorMovedI'}, {
group = augroup,
callback = function()
self:_on_cursor_moved()
end
})
vim.api.nvim_create_autocmd({'ModeChanged'}, {
group = augroup,
callback = function()
self:_on_mode_changed()
end
})
-- Track file changes for filename context
vim.api.nvim_create_autocmd({'BufEnter', 'WinEnter'}, {
group = augroup,
callback = function()
-- Small delay to ensure buffer is fully loaded
vim.defer_fn(function()
self:_send_file_context()
end, 50)
end
})
self._selection_tracker = {
augroup = augroup,
last_selection = nil,
last_mode = vim.fn.mode()
}
end
-- Handle cursor movement
function UI:_on_cursor_moved()
if not self._selection_tracker then
return
end
local current_mode = vim.fn.mode()
-- Real-time tracking in visual mode (no debounce)
if current_mode:match('[vV\22]') then
self:_send_visual_selection_immediately()
else
-- Normal mode: debounced file context updates
if self._selection_tracker.cursor_timer then
self._selection_tracker.cursor_timer:stop()
-- Only close if not already closing (vim.defer_fn timers auto-cleanup)
if not self._selection_tracker.cursor_timer:is_closing() then
self._selection_tracker.cursor_timer:close()
end
self._selection_tracker.cursor_timer = nil
end
self._selection_tracker.cursor_timer = vim.defer_fn(function()
-- vim.defer_fn timers auto-close after firing, just clear the reference
if self._selection_tracker then
self._selection_tracker.cursor_timer = nil
end
self:_send_file_context()
end, 100) -- Faster file context updates
end
end
-- Handle mode changes
function UI:_on_mode_changed()
if not self._selection_tracker then
return
end
local new_mode = vim.fn.mode()
local old_mode = self._selection_tracker.last_mode
self._selection_tracker.last_mode = new_mode
-- Entering visual mode - start real-time tracking
if not old_mode:match('[vV\22]') and new_mode:match('[vV\22]') then
self._logger:debug("Entered visual mode - starting real-time selection tracking")
self:_send_visual_selection_immediately()
-- Exiting visual mode - clear selection and send empty selection
elseif old_mode:match('[vV\22]') and not new_mode:match('[vV\22]') then
self._logger:debug("Exited visual mode - clearing selection")
self:_send_empty_selection()
end
end
-- Check for selection changes
function UI:_check_selection_change()
local current_selection = self:get_current_selection()
local last_selection = self._selection_tracker.last_selection
-- Check if selection changed significantly
local selection_changed = false
if not last_selection or not current_selection then
selection_changed = (last_selection ~= nil) ~= (current_selection ~= nil)
elseif current_selection.text ~= last_selection.text or
current_selection.file_path ~= last_selection.file_path then
selection_changed = true
end
if selection_changed then
self._selection_tracker.last_selection = current_selection
-- Emit selection change event (only if tracking enabled)
if self._config.track_selection ~= false and current_selection then
self._events:emit('ui:selection_changed', {
file_path = current_selection.file_path,
start_line = current_selection.start_line,
end_line = current_selection.end_line,
text = current_selection.text,
selection_type = current_selection.selection_type,
timestamp = os.time()
})
end
end
end
-- Public: manually trigger a selection tracking pass
function UI:track_selection()
-- If selection tracking is not initialized, still attempt a single pass
if not self._selection_tracker then
self._selection_tracker = { last_selection = nil, last_mode = vim.fn.mode() }
end
self:_check_selection_change()
end
-- Send real-time visual selection immediately (no debounce)
function UI:_send_visual_selection_immediately()
-- Use centralized selection utility
local selection_util = require('diffusion.utils.selection')
local selection = selection_util.get_current_selection()
if selection and selection.text and selection.text ~= "" then
self._logger:debug("Sending real-time visual selection", {
file = selection.file_path,
text_length = #selection.text,
start_line = selection.start_line,
end_line = selection.end_line
})
-- Emit selection change event immediately (only if tracking enabled)
if self._config.track_selection ~= false then
self._events:emit('ui:selection_changed', {
file_path = selection.file_path,
start_line = selection.start_line,
end_line = selection.end_line,
text = selection.text,
selection_type = selection.selection_type,
timestamp = os.time()
})
end
self._selection_tracker.last_selection = selection
end
end
-- Send current file context (cursor position, no selection)
function UI:_send_file_context()
local file_path = vim.api.nvim_buf_get_name(0)
-- Skip if no file or is a special buffer
if not file_path or file_path == "" or file_path:match("^%w+://") then
return
end
local cursor_pos = vim.api.nvim_win_get_cursor(0)
local line_num = cursor_pos[1]
local col_num = cursor_pos[2]
-- Send empty selection with file context (no selected text)
local file_context = {
text = "", -- No selected text
file_path = file_path,
start_line = line_num,
start_col = col_num + 1, -- Convert to 1-based
end_line = line_num,
end_col = col_num + 1,
selection_type = "cursor"
}
-- Check if this context is identical to the last one sent (deduplication)
if self._selection_tracker.last_selection then
local last = self._selection_tracker.last_selection
if last.file_path == file_context.file_path and
last.start_line == file_context.start_line and
last.start_col == file_context.start_col and
last.text == file_context.text and
last.selection_type == file_context.selection_type then
-- Identical context, skip sending
return
end
end
self._logger:debug("Sending file context (no selection)", {
file = file_path,
line = line_num
})
-- Emit file context event with empty selection (only if tracking enabled)
if self._config.track_selection ~= false then
self._events:emit('ui:selection_changed', {
file_path = file_context.file_path,
start_line = file_context.start_line,
end_line = file_context.end_line,
text = file_context.text,
selection_type = file_context.selection_type,
timestamp = os.time()
})
end
self._selection_tracker.last_selection = file_context
end
-- Send empty selection to clear any existing selection in Claude Code
function UI:_send_empty_selection()
local file_path = vim.api.nvim_buf_get_name(0)
-- Skip if no file or is a special buffer
if not file_path or file_path == "" or file_path:match("^%w+://") then
return
end
local cursor_pos = vim.api.nvim_win_get_cursor(0)
local line_num = cursor_pos[1]
local col_num = cursor_pos[2]
-- Create empty selection
local empty_selection = {
text = "", -- Empty text
file_path = file_path,
start_line = line_num,
start_col = col_num + 1,
end_line = line_num,
end_col = col_num + 1,
selection_type = "empty"
}
-- Check if this selection is identical to the last one sent (deduplication)
if self._selection_tracker.last_selection then
local last = self._selection_tracker.last_selection
if last.file_path == empty_selection.file_path and
last.start_line == empty_selection.start_line and
last.start_col == empty_selection.start_col and
last.text == empty_selection.text and
last.selection_type == empty_selection.selection_type then
-- Identical selection, skip sending
return
end
end
self._logger:debug("Sending empty selection", {
file = file_path,
line = line_num
})
-- Emit empty selection event (only if tracking enabled)
if self._config.track_selection ~= false then
self._events:emit('ui:selection_changed', {
file_path = empty_selection.file_path,
start_line = empty_selection.start_line,
end_line = empty_selection.end_line,
text = empty_selection.text,
selection_type = empty_selection.selection_type,
timestamp = os.time()
})
end
self._selection_tracker.last_selection = empty_selection
end
-- Cleanup selection tracking
function UI:_cleanup_selection_tracking()
if self._selection_tracker then
if self._selection_tracker.cursor_timer then
self._selection_tracker.cursor_timer:stop()
self._selection_tracker.cursor_timer:close() -- Release timer resources
self._selection_tracker.cursor_timer = nil
end
pcall(vim.api.nvim_del_augroup_by_id, self._selection_tracker.augroup)
self._selection_tracker = nil
end
end
-- Enable immersive mode
function UI:enable_immersive_mode()
if self._immersive_mode then
return
end
self._immersive_mode = true
self._logger:info("Immersive mode enabled")
-- Setup immersive mode features
self:_setup_immersive_mode()
-- Emit event
self._events:emit('immersive_mode_changed', {
enabled = true
})
end
-- Disable immersive mode
function UI:disable_immersive_mode()
if not self._immersive_mode then
return
end
self._immersive_mode = false
self._logger:info("Immersive mode disabled")
-- Cleanup immersive mode
self:_cleanup_immersive_mode()
-- Emit event
self._events:emit('immersive_mode_changed', {
enabled = false
})
end
-- Setup immersive mode features
function UI:_setup_immersive_mode()
-- Auto-selection tracking
self:setup_selection_tracking(true)
-- Enhanced visual feedback
vim.o.cursorline = true
-- Overlay panel for output + prompt
local Overlay = require('diffusion.ui.overlay')
self._overlay = Overlay:new(self._events)
self._overlay:show()
-- Unsubscribe any existing immersive event handlers before re-registering
-- (prevents handler accumulation when _setup_immersive_mode is called multiple times)
for _, sub in ipairs(self._immersive_event_subscriptions or {}) do
self._events:off(sub.event, sub.handler)
end
self._immersive_event_subscriptions = {}
-- Listen to key events to log minimal provider activity (with tracking)
local service_switched_handler = function(d)
if self._overlay then self._overlay:append_output('Sys:', string.format('Switched service: %s -> %s', d.from or '-', d.to or '-')) end
end
local diff_accepted_handler = function(d)
if self._overlay then self._overlay:append_output('Diff:', 'Accepted ' .. (d.file_path or '')) end
end
local diff_rejected_handler = function(d)
if self._overlay then self._overlay:append_output('Diff:', 'Rejected ' .. (d.file_path or '')) end
end
self._events:on('service_switched', service_switched_handler)
self._events:on('diff_accepted', diff_accepted_handler)
self._events:on('diff_rejected', diff_rejected_handler)
-- Track subscriptions for cleanup
table.insert(self._immersive_event_subscriptions, { event = 'service_switched', handler = service_switched_handler })
table.insert(self._immersive_event_subscriptions, { event = 'diff_accepted', handler = diff_accepted_handler })
table.insert(self._immersive_event_subscriptions, { event = 'diff_rejected', handler = diff_rejected_handler })
end
-- Cleanup immersive mode
function UI:_cleanup_immersive_mode()
-- Unsubscribe immersive mode event listeners (prevents memory leak)
for _, sub in ipairs(self._immersive_event_subscriptions or {}) do
self._events:off(sub.event, sub.handler)
end
self._immersive_event_subscriptions = {}
-- Restore settings
self:_cleanup_selection_tracking()
if self._overlay then self._overlay:close(); self._overlay = nil end
-- Restore cursor settings (if they were changed)
-- Note: We don't restore these automatically as user might have had them enabled
end
-- Setup status line integration
function UI:_setup_statusline_integration()
-- Add diffusion status to statusline
vim.g.diffusion_statusline_active = true
-- This would integrate with popular statusline plugins
-- Implementation would vary based on the statusline plugin
end
-- Show notification
function UI:show_notification(message, level, opts)
opts = opts or {}
level = level or "info"
self._stats.notifications_sent = self._stats.notifications_sent + 1
-- Use vim.notify if available (Neovim 0.7+)
if vim.notify then
local notify_opts = {
title = opts.title or "Diffusion.nvim",
timeout = opts.timeout or 3000
}
vim.notify(message, vim.log.levels[level:upper()], notify_opts)
else
-- Fallback to echo
local hl_group = "Normal"
if level == "error" then
hl_group = "ErrorMsg"
elseif level == "warn" then
hl_group = "WarningMsg"
end
vim.api.nvim_echo({{message, hl_group}}, false, {})
end
end
-- Show progress notification
function UI:show_progress(message, progress)
local progress_text = ""
if progress then
progress_text = string.format(" (%d%%)", math.floor(progress * 100))
end
self:show_notification(message .. progress_text, "info", {
timeout = 1000
})
end
-- Get UI statistics
function UI:get_stats()
local stats = vim.deepcopy(self._stats)
stats.selection_tracking_enabled = self._selection_tracker ~= nil
stats.immersive_mode_enabled = self._immersive_mode
return stats
end
-- Check if immersive mode is enabled
function UI:is_immersive_mode()
return self._immersive_mode
end
-- Toggle immersive mode
function UI:toggle_immersive_mode()
if self._immersive_mode then
self:disable_immersive_mode()
else
self:enable_immersive_mode()
end
end
-- Toggle ticker window
function UI:toggle_ticker()
if not self._ticker then
local Ticker = require('diffusion.ui.ticker')
self._ticker = Ticker:new(self._events)
end
self._ticker:toggle()
self._logger:info("Ticker window toggled")
end
-- Toggle virtual text streaming
function UI:toggle_virtual_text()
if not self._virtual_text then
local VirtualText = require('diffusion.ui.virtual_text')
self._virtual_text = VirtualText:new(self._events)
end
self._virtual_text:toggle()
self._logger:info("Virtual text streaming toggled")
end
-- Configure ticker window
function UI:configure_ticker(config)
if not self._ticker then
local Ticker = require('diffusion.ui.ticker')
self._ticker = Ticker:new(self._events)
end
self._ticker:configure(config)
end
-- Configure virtual text
function UI:configure_virtual_text(config)
if not self._virtual_text then
local VirtualText = require('diffusion.ui.virtual_text')
self._virtual_text = VirtualText:new(self._events)
end
self._virtual_text:configure(config)
end
-- Get ticker status
function UI:get_ticker_status()
return self._ticker and self._ticker._active or false
end
-- Get virtual text status
function UI:get_virtual_text_status()
return self._virtual_text and self._virtual_text._active or false
end
-- Cleanup UI
function UI:cleanup()
self:disable_immersive_mode()
self:_cleanup_selection_tracking()
-- Cleanup ticker and virtual text
if self._ticker then
self._ticker:hide()
self._ticker = nil
end
if self._virtual_text then
self._virtual_text:hide()
self._virtual_text = nil
end
self._logger:info("UI cleanup completed")
end
-- Destroy UI instance (full cleanup including constructor subscriptions)
function UI:destroy()
-- First run standard cleanup
self:cleanup()
-- Unsubscribe constructor event listeners (prevents memory leak)
for _, sub in ipairs(self._event_subscriptions or {}) do
self._events:off(sub.event, sub.handler)
end
self._event_subscriptions = {}
self._logger:info("UI instance destroyed")
end
-- Start UI based on configuration
function UI:start(config)
config = config or self._config or {}
-- selection tracking if requested
if config.track_selections then
self:setup_selection_tracking(true)
end
-- immersive overlay if requested
if config.immersive_mode then
self:enable_immersive_mode()
end
end
-- Create singleton instance
local _instance = nil
-- Get or create singleton instance
function UI.get_instance(events, config)
if not _instance then
_instance = UI:new(events, config)
end
return _instance
end
-- Module interface - delegate to singleton
local M = {}
-- Initialize the UI singleton with events
function M:init(events, config)
return UI.get_instance(events, config)
end
function M:get_current_selection()
return UI.get_instance():get_current_selection()
end
function M:setup_selection_tracking(enabled)
return UI.get_instance():setup_selection_tracking(enabled)
end
function M:enable_immersive_mode()
return UI.get_instance():enable_immersive_mode()
end
function M:disable_immersive_mode()
return UI.get_instance():disable_immersive_mode()
end
function M:toggle_immersive_mode()
return UI.get_instance():toggle_immersive_mode()
end
function M:is_immersive_mode()
return UI.get_instance():is_immersive_mode()
end
function M:show_notification(message, level, opts)
return UI.get_instance():show_notification(message, level, opts)
end
function M:show_progress(message, progress)
return UI.get_instance():show_progress(message, progress)
end
function M:get_stats()
return UI.get_instance():get_stats()
end
function M:cleanup()
return UI.get_instance():cleanup()
end
function M:destroy()
if _instance then
_instance:destroy()
_instance = nil -- Reset singleton so a fresh instance can be created
end
end
function M:toggle_ticker()
return UI.get_instance():toggle_ticker()
end
function M:toggle_virtual_text()
return UI.get_instance():toggle_virtual_text()
end