-
Notifications
You must be signed in to change notification settings - Fork 3k
/
Copy pathconsole.lua
1982 lines (1705 loc) · 63.3 KB
/
console.lua
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
-- Copyright (C) 2019 the mpv developers
--
-- Permission to use, copy, modify, and/or distribute this software for any
-- purpose with or without fee is hereby granted, provided that the above
-- copyright notice and this permission notice appear in all copies.
--
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
-- SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
-- OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
-- CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
local utils = require 'mp.utils'
local assdraw = require 'mp.assdraw'
local function detect_platform()
local platform = mp.get_property_native('platform')
if platform == 'darwin' or platform == 'windows' then
return platform
elseif os.getenv('WAYLAND_DISPLAY') or os.getenv('WAYLAND_SOCKET') then
return 'wayland'
end
return 'x11'
end
local platform = detect_platform()
-- Default options
local opts = {
font = "",
font_size = 24,
border_size = 1.65,
margin_x = -1,
margin_y = -1,
scale_with_window = "auto",
case_sensitive = platform ~= 'windows' and true or false,
history_dedup = true,
font_hw_ratio = 'auto',
}
local styles = {
-- Colors are stolen from base16 Eighties by Chris Kempson
-- and converted to BGR as is required by ASS.
-- 2d2d2d 393939 515151 697374
-- 939fa0 c8d0d3 dfe6e8 ecf0f2
-- 7a77f2 5791f9 66ccff 99cc99
-- cccc66 cc9966 cc99cc 537bd2
debug = '{\\1c&Ha09f93&}',
v = '{\\1c&H99cc99&}',
warn = '{\\1c&H66ccff&}',
error = '{\\1c&H7a77f2&}',
fatal = '{\\1c&H5791f9&}',
completion = '{\\1c&Hcc99cc&}',
disabled = '{\\1c&Hcccccc&}',
}
for key, style in pairs(styles) do
styles[key] = style .. '{\\3c&H111111&}'
end
local terminal_styles = {
debug = '\027[90m',
v = '\027[32m',
warn = '\027[33m',
error = '\027[31m',
fatal = '\027[91m',
selected_completion = '\027[7m',
default_item = '\027[1m',
disabled = '\027[38;5;8m',
}
local repl_active = false
local osd_msg_active = false
local insert_mode = false
local pending_update = false
local line = ''
local cursor = 1
local default_prompt = '>'
local prompt = default_prompt
local default_id = 'default'
local id = default_id
local histories = {[id] = {}}
local history = histories[id]
local history_pos = 1
local searching_history = false
local log_buffers = {[id] = {}}
local key_bindings = {}
local dont_bind_up_down = false
local overlay = mp.create_osd_overlay('ass-events')
local global_margins = { t = 0, b = 0 }
local input_caller
local completion_buffer = {}
local selected_completion_index
local completion_pos
local completion_append
local path_separator = platform == 'windows' and '\\' or '/'
local completion_old_line
local completion_old_cursor
local selectable_items
local matches = {}
local selected_match = 1
local first_match_to_print = 1
local default_item
local complete
local cycle_through_completions
local set_active
local function get_font()
if opts.font ~= '' then
return opts.font
end
if selectable_items and not searching_history then
return
end
-- Pick a better default font for Windows and macOS
if platform == 'windows' then
return 'Consolas'
end
if platform == 'darwin' then
return 'Menlo'
end
return 'monospace'
end
local function get_margin_x()
return opts.margin_x > -1 and opts.margin_x or mp.get_property_native('osd-margin-x')
end
local function get_margin_y()
return opts.margin_y > -1 and opts.margin_y or mp.get_property_native('osd-margin-y')
end
-- Naive helper function to find the next UTF-8 character in 'str' after 'pos'
-- by skipping continuation bytes. Assumes 'str' contains valid UTF-8.
local function next_utf8(str, pos)
if pos > str:len() then return pos end
repeat
pos = pos + 1
until pos > str:len() or str:byte(pos) < 0x80 or str:byte(pos) > 0xbf
return pos
end
-- As above, but finds the previous UTF-8 character in 'str' before 'pos'
local function prev_utf8(str, pos)
if pos <= 1 then return pos end
repeat
pos = pos - 1
until pos <= 1 or str:byte(pos) < 0x80 or str:byte(pos) > 0xbf
return pos
end
local function len_utf8(str)
local len = 0
local pos = 1
while pos <= str:len() do
pos = next_utf8(str, pos)
len = len + 1
end
return len
end
-- Functions to calculate the font width.
local width_length_ratio = 0.5
local osd_width, osd_height = 100, 100
---Update osd resolution if valid
local function update_osd_resolution()
local dim = mp.get_property_native('osd-dimensions')
if not dim or dim.w == 0 or dim.h == 0 then
return
end
osd_width = dim.w
osd_height = dim.h
end
local text_osd = mp.create_osd_overlay('ass-events')
text_osd.compute_bounds, text_osd.hidden = true, true
local function measure_bounds(ass_text)
update_osd_resolution()
text_osd.res_x, text_osd.res_y = osd_width, osd_height
text_osd.data = ass_text
local res = text_osd:update()
return res.x0, res.y0, res.x1, res.y1
end
---Measure text width and normalize to a font size of 1
---text has to be ass safe
local function normalized_text_width(text, size, horizontal)
local align, rotation = horizontal and 7 or 1, horizontal and 0 or -90
local template = '{\\pos(0,0)\\rDefault\\blur0\\bord0\\shad0\\q2\\an%s\\fs%s\\fn%s\\frz%s}%s'
size = size / 0.8
local width
-- Limit to 5 iterations
local repetitions_left = 5
for i = 1, repetitions_left do
size = size * 0.8
local ass = assdraw.ass_new()
ass.text = template:format(align, size, get_font(), rotation, text)
local _, _, x1, y1 = measure_bounds(ass.text)
-- Check if nothing got clipped
if x1 and x1 < osd_width and y1 < osd_height then
width = horizontal and x1 or y1
break
end
if i == repetitions_left then
width = 0
end
end
return width / size, horizontal and osd_width or osd_height
end
local function fit_on_osd(text)
local estimated_width = #text * width_length_ratio
if osd_width >= osd_height then
-- Fill the osd as much as possible, bigger is more accurate.
return math.min(osd_width / estimated_width, osd_height), true
else
return math.min(osd_height / estimated_width, osd_width), false
end
end
local measured_font_hw_ratio = nil
local function get_font_hw_ratio()
local font_hw_ratio = tonumber(opts.font_hw_ratio)
if font_hw_ratio then
return font_hw_ratio
end
if not measured_font_hw_ratio then
local alphabet = 'abcdefghijklmnopqrstuvwxyz'
local text = alphabet:rep(3)
update_osd_resolution()
local size, horizontal = fit_on_osd(text)
local normalized_width = normalized_text_width(text, size * 0.9, horizontal)
measured_font_hw_ratio = #text / normalized_width * 0.95
end
return measured_font_hw_ratio
end
-- Escape a string for verbatim display on the OSD
local function ass_escape(str)
return mp.command_native({'escape-ass', str})
end
local function should_scale()
return opts.scale_with_window == "yes" or
(opts.scale_with_window == "auto" and mp.get_property_native("osd-scale-by-window"))
end
local function scale_factor()
local height = mp.get_property_native('osd-height')
if should_scale() and height > 0 then
return height / 720
end
return mp.get_property_native('display-hidpi-scale', 1)
end
local function get_scaled_osd_dimensions()
local dims = mp.get_property_native('osd-dimensions')
local scale = scale_factor()
return dims.w / scale, dims.h /scale
end
local function calculate_max_log_lines()
if not mp.get_property_native('vo-configured')
or not mp.get_property_native('video-osd') then
-- Subtract 1 for the input line and for each line in the status line.
-- This does not detect wrapped lines.
return mp.get_property_native('term-size/h', 24) - 2 -
select(2, mp.get_property('term-status-msg'):gsub('\\n', ''))
end
return math.floor((select(2, get_scaled_osd_dimensions())
* (1 - global_margins.t - global_margins.b)
- get_margin_y())
/ opts.font_size
-- Subtract 1 for the input line and 0.5 for the empty
-- line between the log and the input line.
- 1.5)
end
local function should_highlight_completion(i)
return i == selected_completion_index or
(i == 1 and selected_completion_index == 0 and input_caller == nil)
end
local function mpv_color_to_ass(color)
return color:sub(8,9) .. color:sub(6,7) .. color:sub(4,5),
string.format('%x', 255 - tonumber('0x' .. color:sub(2,3)))
end
local function get_selected_ass()
local color, alpha = mpv_color_to_ass(mp.get_property('osd-selected-color'))
local outline_color, outline_alpha =
mpv_color_to_ass(mp.get_property('osd-selected-outline-color'))
return '{\\1c&H' .. color .. '&\\1a&H' .. alpha ..
'&\\3c&H' .. outline_color .. '&\\3a&H' .. outline_alpha .. '&}'
end
-- Takes a list of strings, a max width in characters and
-- optionally a max row count.
-- The result contains at least one column.
-- Rows are cut off from the top if rows_max is specified.
-- returns a string containing the formatted table and the row count
local function format_grid(list, width_max, rows_max)
if #list == 0 then
return '', 0
end
local spaces_min = 2
local spaces_max = 8
local list_size = #list
local column_count = 1
local row_count = list_size
local column_widths
-- total width without spacing
local width_total = 0
local list_widths = {}
for i, item in ipairs(list) do
list_widths[i] = len_utf8(item)
end
-- use as many columns as possible
for columns = 2, list_size do
local rows_lower_bound = math.min(rows_max, math.ceil(list_size / columns))
local rows_upper_bound = math.min(rows_max, list_size,
math.ceil(list_size / (columns - 1) - 1))
for rows = rows_upper_bound, rows_lower_bound, -1 do
local cw = {}
width_total = 0
-- find out width of each column
for column = 1, columns do
local width = 0
for row = 1, rows do
local i = row + (column - 1) * rows
local item_width = list_widths[i]
if not item_width then break end
if width < item_width then
width = item_width
end
end
cw[column] = width
width_total = width_total + width
if width_total + (columns - 1) * spaces_min > width_max then
break
end
end
if width_total + (columns - 1) * spaces_min <= width_max then
row_count = rows
column_count = columns
column_widths = cw
else
break
end
end
if width_total + (columns - 1) * spaces_min > width_max then
break
end
end
local spaces = math.floor((width_max - width_total) / (column_count - 1))
spaces = math.max(spaces_min, math.min(spaces_max, spaces))
local spacing = column_count > 1
and ass_escape(string.format('%' .. spaces .. 's', ' '))
or ''
local rows = {}
for row = 1, row_count do
local columns = {}
for column = 1, column_count do
local i = row + (column - 1) * row_count
if i > #list then break end
-- more then 99 leads to 'invalid format (width or precision too long)'
local format_string = column == column_count and '%s'
or '%-' .. math.min(column_widths[column], 99) .. 's'
columns[column] = ass_escape(string.format(format_string, list[i]))
if should_highlight_completion(i) then
columns[column] = '{\\b1}' .. get_selected_ass() .. columns[column] ..
'{\\b\\1a&\\3a&}' .. styles.completion
end
end
-- first row is at the bottom
rows[row_count - row + 1] = table.concat(columns, spacing)
end
return table.concat(rows, ass_escape('\n')), row_count
end
local function fuzzy_find(needle, haystacks, case_sensitive)
local result = require 'mp.fzy'.filter(needle, haystacks, case_sensitive)
table.sort(result, function (i, j)
if i[3] ~= j[3] then
return i[3] > j[3]
end
return i[1] < j[1]
end)
for i, value in ipairs(result) do
result[i] = value[1]
end
return result
end
local function populate_log_with_matches()
if not selectable_items or selected_match == 0 then
return
end
log_buffers[id] = {}
local log = log_buffers[id]
local max_log_lines = calculate_max_log_lines()
local print_counter = false
if #matches > max_log_lines then
print_counter = true
max_log_lines = max_log_lines - 1
end
if selected_match < first_match_to_print then
first_match_to_print = selected_match
elseif selected_match > first_match_to_print + max_log_lines - 1 then
first_match_to_print = selected_match - max_log_lines + 1
end
local last_match_to_print = math.min(first_match_to_print + max_log_lines - 1,
#matches)
if print_counter then
log[1] = {
text = '',
style = styles.disabled .. selected_match .. '/' .. #matches ..
' {\\fs' .. opts.font_size * 0.75 .. '}[' ..
first_match_to_print .. '-' .. last_match_to_print .. ']',
terminal_style = terminal_styles.disabled .. selected_match .. '/' ..
#matches .. ' [' .. first_match_to_print .. '-' ..
last_match_to_print .. ']',
}
end
for i = first_match_to_print, last_match_to_print do
local style = ''
local terminal_style = ''
if i == selected_match or matches[i].index == default_item then
style = get_selected_ass()
end
if matches[i].index == default_item then
terminal_style = terminal_styles.default_item
end
if i == selected_match then
style = style .. '{\\b1}'
terminal_style = terminal_style .. terminal_styles.selected_completion
end
log[#log + 1] = {
text = matches[i].text,
style = style,
terminal_style = terminal_style,
}
end
end
local function update_overlay(data, res_x, res_y, z)
if overlay.data == data and
overlay.res_x == res_x and
overlay.res_y == res_y and
overlay.z == z then
return
end
overlay.data = data
overlay.res_x = res_x
overlay.res_y = res_y
overlay.z = z
overlay:update()
end
local function print_to_terminal()
-- Clear the log after closing the console.
if not repl_active then
if osd_msg_active then
mp.osd_message('')
end
osd_msg_active = false
return
end
populate_log_with_matches()
local log = ''
local clip = selectable_items and mp.get_property('term-clip-cc') or ''
for _, log_line in ipairs(log_buffers[id]) do
log = log .. clip .. log_line.terminal_style .. log_line.text .. '\027[0m\n'
end
local completions = ''
for i, completion in ipairs(completion_buffer) do
if should_highlight_completion(i) then
completions = completions .. terminal_styles.selected_completion ..
completion .. '\027[0m'
else
completions = completions .. completion
end
completions = completions .. (i < #completion_buffer and '\t' or '\n')
end
local before_cur = line:sub(1, cursor - 1)
local after_cur = line:sub(cursor)
-- Ensure there is a character with inverted colors to print.
if after_cur == '' then
after_cur = ' '
end
mp.osd_message(log .. completions .. prompt .. ' ' .. before_cur ..
'\027[7m' .. after_cur:sub(1, 1) .. '\027[0m' ..
after_cur:sub(2), 999)
osd_msg_active = true
end
local function render()
pending_update = false
-- Unlike vo-configured, current-vo doesn't become falsy while switching VO,
-- which would print the log to the OSD.
if not mp.get_property('current-vo') or not mp.get_property_native('video-osd') then
print_to_terminal()
return
end
-- Clear the OSD if the console was being printed to the terminal
if osd_msg_active then
mp.osd_message('')
osd_msg_active = false
end
-- Clear the OSD if the REPL is not active
if not repl_active then
update_overlay('', 0, 0, 0)
return
end
local ass = assdraw.ass_new()
local osd_w, osd_h = get_scaled_osd_dimensions()
local x = get_margin_x()
local y = osd_h * (1 - global_margins.b) - get_margin_y()
local font = get_font()
-- Use the same blur value as the rest of the OSD. 288 is the OSD's
-- PlayResY.
local blur = mp.get_property_native('osd-blur') * osd_h / 288
local coordinate_top = math.floor(global_margins.t * osd_h + 0.5)
local clipping_coordinates = '0,' .. coordinate_top .. ',' ..
osd_w .. ',' .. osd_h
local style = '{\\r' ..
(font and '\\fn' .. font or '') ..
'\\fs' .. opts.font_size ..
'\\bord' .. opts.border_size .. '\\fsp0' ..
'\\blur' .. blur ..
(selectable_items and '\\q2' or '\\q1') ..
'\\clip(' .. clipping_coordinates .. ')}'
-- Create the cursor glyph as an ASS drawing. ASS will draw the cursor
-- inline with the surrounding text, but it sets the advance to the width
-- of the drawing. So the cursor doesn't affect layout too much, make it as
-- thin as possible and make it appear to be 1px wide by giving it 0.5px
-- horizontal borders.
local color, alpha = mpv_color_to_ass(mp.get_property('osd-color'))
local cheight = opts.font_size * 8
local cglyph = '{\\r\\blur0' ..
(mp.get_property_native('focused') == false
and '\\alpha&HFF&' or '\\3a&H' .. alpha .. '&') ..
'\\3c&H' .. color .. '&' ..
'\\xbord0.5\\ybord0\\xshad0\\yshad1\\p4\\pbo24}' ..
'm 0 0 l 1 0 l 1 ' .. cheight .. ' l 0 ' .. cheight ..
'{\\p0}'
local before_cur = ass_escape(line:sub(1, cursor - 1))
local after_cur = ass_escape(line:sub(cursor))
-- Render log messages as ASS.
-- This will render at most screeny / font_size - 1 messages.
local max_lines = calculate_max_log_lines()
local completion_ass = ''
if next(completion_buffer) then
-- Estimate how many characters fit in one line
-- Even with bottom-left anchoring,
-- libass/ass_render.c:ass_render_event() subtracts --osd-margin-x from
-- the maximum text width twice.
local width_max = math.floor(
(osd_w - x - mp.get_property_native('osd-margin-x') * 2 / scale_factor())
/ opts.font_size * get_font_hw_ratio())
local completions, rows = format_grid(completion_buffer, width_max, max_lines)
max_lines = max_lines - rows
completion_ass = style .. styles.completion .. completions .. '\\N'
end
populate_log_with_matches()
local log_ass = ''
local log_buffer = log_buffers[id]
local box = mp.get_property('osd-border-style') == 'background-box'
for i = #log_buffer - math.min(max_lines, #log_buffer) + 1, #log_buffer do
local log_item = style .. log_buffer[i].style .. ass_escape(log_buffer[i].text)
-- Put every selectable item in its own event to prevent libass from
-- drawing them taller than opts.font_size with taller fonts, which
-- makes the hovered item calculation inaccurate and clips the counter.
-- But not with background-box, because it makes it look bad by
-- overlapping the semitransparent backgrounds of every line.
if selectable_items and not box then
ass:new_event()
ass:an(1)
ass:pos(x, y - (1.5 + #log_buffer - i) * opts.font_size)
ass:append(log_item)
else
log_ass = log_ass .. log_item .. '\\N'
end
end
ass:new_event()
ass:an(1)
ass:pos(x, y)
ass:append(log_ass .. '\\N')
ass:append(completion_ass)
ass:append(style .. ass_escape(prompt) .. ' ' .. before_cur)
ass:append(cglyph)
ass:append(style .. after_cur)
-- Redraw the cursor with the REPL text invisible. This will make the
-- cursor appear in front of the text.
ass:new_event()
ass:an(1)
ass:pos(x, y)
ass:append(style .. '{\\alpha&HFF&}' .. ass_escape(prompt) .. ' ' .. before_cur)
ass:append(cglyph)
ass:append(style .. '{\\alpha&HFF&}' .. after_cur)
-- z with selectable_items needs to be greater than the OSC's.
update_overlay(ass.text, osd_w, osd_h, selectable_items and 2000 or 0)
end
local update_timer = nil
update_timer = mp.add_periodic_timer(0.05, function()
if pending_update then
render()
else
update_timer:kill()
end
end)
update_timer:kill()
-- Add a line to the log buffer (which is limited to 100 lines)
local function log_add(text, style, terminal_style)
local log_buffer = log_buffers[id]
log_buffer[#log_buffer + 1] = {
text = text,
style = style or '',
terminal_style = terminal_style or '',
}
if #log_buffer > 100 then
table.remove(log_buffer, 1)
end
if repl_active then
if not update_timer:is_enabled() then
render()
update_timer:resume()
else
pending_update = true
end
end
end
-- Add a line to the history and deduplicate
local function history_add(text)
if opts.history_dedup then
-- More recent entries are more likely to be repeated
for i = #history, 1, -1 do
if history[i] == text then
table.remove(history, i)
break
end
end
end
history[#history + 1] = text
end
local function handle_cursor_move()
-- Don't show completions after a command is entered because they move its
-- output up, and allow clearing completions by emptying the line.
if line == '' then
completion_buffer = {}
render()
else
complete()
end
end
local function handle_edit()
if selectable_items then
matches = {}
for i, match in ipairs(fuzzy_find(line, selectable_items)) do
matches[i] = { index = match, text = selectable_items[match] }
end
if line == '' and default_item then
selected_match = default_item
local max_lines = calculate_max_log_lines()
first_match_to_print = math.max(1, selected_match - math.floor(max_lines / 2) + 1)
if first_match_to_print > #selectable_items - max_lines + 2 then
first_match_to_print = math.max(1, #selectable_items - max_lines + 1)
end
else
selected_match = 1
end
render()
return
end
handle_cursor_move()
if input_caller then
mp.commandv('script-message-to', input_caller, 'input-event', 'edited',
utils.format_json({line}))
end
end
-- Insert a character at the current cursor position (any_unicode)
local function handle_char_input(c)
if insert_mode then
line = line:sub(1, cursor - 1) .. c .. line:sub(next_utf8(line, cursor))
else
line = line:sub(1, cursor - 1) .. c .. line:sub(cursor)
end
cursor = cursor + #c
handle_edit()
end
-- Remove the character behind the cursor (Backspace)
local function handle_backspace()
if cursor <= 1 then return end
local prev = prev_utf8(line, cursor)
line = line:sub(1, prev - 1) .. line:sub(cursor)
cursor = prev
handle_edit()
end
-- Remove the character in front of the cursor (Del)
local function handle_del()
if cursor > line:len() then return end
line = line:sub(1, cursor - 1) .. line:sub(next_utf8(line, cursor))
handle_edit()
end
-- Toggle insert mode (Ins)
local function handle_ins()
insert_mode = not insert_mode
end
-- Move the cursor to the next character (Right)
local function next_char()
cursor = next_utf8(line, cursor)
handle_cursor_move()
end
-- Move the cursor to the previous character (Left)
local function prev_char()
cursor = prev_utf8(line, cursor)
handle_cursor_move()
end
-- Clear the current line (Ctrl+C)
local function clear()
line = ''
cursor = 1
insert_mode = false
history_pos = #history + 1
handle_edit()
end
-- Close the REPL if the current line is empty, otherwise delete the next
-- character (Ctrl+D)
local function maybe_exit()
if line == '' then
set_active(false)
else
handle_del()
end
end
local function help_command(param)
local cmdlist = mp.get_property_native('command-list')
table.sort(cmdlist, function(c1, c2)
return c1.name < c2.name
end)
local output = ''
if param == '' then
output = 'Available commands:\n'
for _, cmd in ipairs(cmdlist) do
output = output .. ' ' .. cmd.name
end
output = output .. '\n'
output = output .. 'Use "help command" to show information about a command.\n'
output = output .. "ESC or Ctrl+d exits the console.\n"
else
local cmd = nil
for _, curcmd in ipairs(cmdlist) do
if curcmd.name:find(param, 1, true) then
cmd = curcmd
if curcmd.name == param then
break -- exact match
end
end
end
if not cmd then
log_add('No command matches "' .. param .. '"!', styles.error,
terminal_styles.error)
return
end
output = output .. 'Command "' .. cmd.name .. '"\n'
for _, arg in ipairs(cmd.args) do
output = output .. ' ' .. arg.name .. ' (' .. arg.type .. ')'
if arg.optional then
output = output .. ' (optional)'
end
output = output .. '\n'
end
if cmd.vararg then
output = output .. 'This command supports variable arguments.\n'
end
end
log_add(output:sub(1, -2))
end
local function unbind_mouse()
mp.remove_key_binding('_console_mouse_move')
mp.remove_key_binding('_console_mbtn_left')
end
-- Run the current command and clear the line (Enter)
local function handle_enter()
if searching_history then
searching_history = false
selectable_items = nil
line = #matches > 0 and matches[selected_match].text or ''
cursor = #line + 1
log_buffers[id] = {}
handle_edit()
unbind_mouse()
return
end
if line == '' and input_caller == nil then
return
end
if selectable_items then
if #matches > 0 then
mp.commandv('script-message-to', input_caller, 'input-event', 'submit',
utils.format_json({matches[selected_match].index}))
end
set_active(false)
elseif input_caller then
mp.commandv('script-message-to', input_caller, 'input-event', 'submit',
utils.format_json({line}))
else
if selected_completion_index == 0 then
cycle_through_completions()
end
-- match "help [<text>]", return <text> or "", strip all whitespace
local help = line:match('^%s*help%s+(.-)%s*$') or
(line:match('^%s*help$') and '')
if help then
help_command(help)
else
mp.command(line)
end
end
if history[#history] ~= line and line ~= '' then
history_add(line)
end
clear()
end
local function determine_hovered_item()
local height = select(2, get_scaled_osd_dimensions())
local y = mp.get_property_native('mouse-pos').y / scale_factor()
local log_bottom_pos = height * (1 - global_margins.b)
- get_margin_y()
- 1.5 * opts.font_size
if y > log_bottom_pos then
return
end
local max_lines = calculate_max_log_lines()
-- Subtract 1 line for the position counter.
if #matches > max_lines then
max_lines = max_lines - 1
end
local last = math.min(first_match_to_print - 1 + max_lines, #matches)
local hovered_item = last - math.floor((log_bottom_pos - y) / opts.font_size)
if hovered_item >= first_match_to_print then
return hovered_item
end
end
local function bind_mouse()
mp.add_forced_key_binding('MOUSE_MOVE', '_console_mouse_move', function()
local item = determine_hovered_item()
if item and item ~= selected_match then
selected_match = item
render()
end
end)
mp.add_forced_key_binding('MBTN_LEFT', '_console_mbtn_left', function()
local item = determine_hovered_item()
if item then
selected_match = item
handle_enter()
else
set_active(false)
end
end)
end
-- Go to the specified position in the command history
local function go_history(new_pos)
local old_pos = history_pos
history_pos = new_pos
-- Restrict the position to a legal value
if history_pos > #history + 1 then
history_pos = #history + 1
elseif history_pos < 1 then
history_pos = 1
end
-- Do nothing if the history position didn't actually change
if history_pos == old_pos then
return
end
-- If the user was editing a non-history line, save it as the last history
-- entry. This makes it much less frustrating to accidentally hit Up/Down
-- while editing a line.
if old_pos == #history + 1 and line ~= '' and history[#history] ~= line then
history_add(line)
end
-- Now show the history line (or a blank line for #history + 1)
if history_pos <= #history then
line = history[history_pos]
else
line = ''
end
cursor = line:len() + 1
insert_mode = false
handle_edit()
end
-- Go to the specified relative position in the command history (Up, Down)
local function move_history(amount, is_wheel)
if is_wheel and selectable_items then