forked from mpv-player/mpv
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconsole.lua
More file actions
2007 lines (1726 loc) · 63.5 KB
/
console.lua
File metadata and controls
2007 lines (1726 loc) · 63.5 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
-- 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 msg = require "mp.msg"
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 script_opts = {
monospace_font = "",
font_size = 24,
border_size = 1.65,
background_alpha = 80,
gap = 0.2,
padding = 10,
menu_outline_size = 0,
menu_outline_color = "#FFFFFF",
corner_radius = 8,
margin_x = -1,
margin_y = -1,
scale_with_window = "auto",
focused_color = "#222222",
focused_back_color = "#FFFFFF",
match_color = "#0088FF",
exact_match = false,
case_sensitive = false,
history_dedup = true,
font_hw_ratio = "auto",
}
local opts = script_opts
local styles = {
error = "{\\1c&H7a77f2&}",
completion = "{\\1c&Hcc99cc&}",
inactive = "{\\alpha&H66&}",
}
for key, style in pairs(styles) do
styles[key] = style .. "{\\3c&H111111&}"
end
local terminal_styles = {
error = "\027[31m",
selected_completion = "\027[7m",
default_item = "\027[1m",
disabled = "\027[38;5;8m",
matched_position = "\027[34m",
match_end = "\027[39m",
}
local open = false
local osd_msg_active = false
local insert_mode = false
local pending_update = false
local ime_active = false
local line = ""
local cursor = 1
local prompt
local id
local overlay = mp.create_osd_overlay("ass-events")
local width_overlay = mp.create_osd_overlay("ass-events")
width_overlay.compute_bounds = true
width_overlay.hidden = true
local histories = {}
local history = {}
local history_pos = 1
local searching_history = false
local history_paths = {}
local histories_to_save = {}
local MAX_LOG_LINES = 10000
local log_buffers = {}
local log_offset = 0
local key_bindings = {}
local global_margins = { t = 0, b = 0 }
local input_caller
local input_caller_handler
local keep_open = false
local completion_buffer = {}
local dim_completions = false
local selected_completion_index
local completion_pos
local completion_append
local autoselect_completion
local has_completions
local selectable_items
local matches = {}
local focused_match = 1
local first_match_to_print = 1
local default_item
local item_positions = {}
local max_item_width = 0
local horizontal_offset = 0
local complete
local cycle_through_completions
local set_active
local render
local property_cache = {}
local completion_timer = mp.add_timeout(0.1, function()
dim_completions = true
render()
end, true)
local function get_property_cached(name, def)
if property_cache[name] ~= nil then
return property_cache[name]
end
return def
end
local function get_font()
if not has_completions then
return
end
if opts.monospace_font ~= "" then
return opts.monospace_font
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()
if opts.margin_x > -1 then
return opts.margin_x
end
if global_margins.t > 0 or global_margins.b > 0 then
return mp.get_property_native("option-info/osd-margin-x/default-value")
end
return mp.get_property_native("osd-margin-x")
end
local function get_margin_y()
if opts.margin_y > -1 then
return opts.margin_y
end
if global_margins.t > 0 or global_margins.b > 0 then
return mp.get_property_native("option-info/osd-margin-y/default-value")
end
return 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
local function utf8_positions(str)
local pos = 1
local positions = {true}
while pos <= str:len() do
pos = next_utf8(str, pos)
positions[pos] = true
end
return positions
end
-- Converts values to strings, using JSON formatting for tables.
-- JSON is used instead of utils.to_string as that is the format the
-- values are received in from script-messages.
local function to_string(v)
if type(v) == "table" then
return utils.format_json(v)
else
return tostring(v)
end
end
-- Functions to calculate the font width.
local width_length_ratio = 0.5
local osd_width, osd_height = 0, 0
local text_osd = mp.create_osd_overlay("ass-events")
text_osd.compute_bounds, text_osd.hidden = true, true
local function measure_bounds(ass_text)
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)
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()
if should_scale() and osd_height > 0 then
return osd_height / 720
end
return get_property_cached("display-hidpi-scale", 1)
end
local function terminal_output()
-- Unlike vo-configured, current-vo doesn't become falsy while switching VO,
-- which would print the log to the OSD.
return not mp.get_property("current-vo") or not mp.get_property_native("video-osd")
end
local function get_scaled_osd_dimensions()
local scale = scale_factor()
return osd_width / scale, osd_height / scale
end
local function get_line_height()
if selectable_items then
return opts.font_size * (1 + opts.gap)
end
return opts.font_size
end
local function calculate_max_lines()
if terminal_output() 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() - (selectable_items and opts.padding * 2 or 0))
/ get_line_height()
-- 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 calculate_max_item_width()
if not selectable_items or terminal_output() then
return
end
local longest_item = prompt .. ("a"):rep(9)
for _, item in pairs(selectable_items) do
if #item > #longest_item then
longest_item = item
end
end
local osd_w, osd_h = get_scaled_osd_dimensions()
local font = get_font()
width_overlay.res_x = osd_w
width_overlay.res_y = osd_h
width_overlay.data = "{\\fs" .. opts.font_size ..
(font and "\\fn" .. font or "") .. "\\q2}" ..
ass_escape(longest_item)
local result = width_overlay:update()
if result.x0 then
max_item_width = math.min(result.x1 - result.x0,
osd_w - get_margin_x() * 2 - opts.padding * 2)
end
end
local function should_highlight_completion(i)
return i == selected_completion_index or
(i == 1 and selected_completion_index == 0 and autoselect_completion)
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 color_option_to_ass(color)
return color:sub(6,7) .. color:sub(4,5) .. 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 "{\\b1\\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
local style_override = dim_completions and styles.inactive or ""
columns[column] = get_selected_ass() .. style_override .. columns[column] ..
"{\\b\\1a&\\3a&}" .. styles.completion .. style_override
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)
local result = require "mp.fzy".filter(needle, haystacks)
table.sort(result, function (i, j)
if i[3] ~= j[3] then
return i[3] > j[3]
end
return i[1] < j[1]
end)
return result
end
local function find_matches(needle, haystacks)
if not opts.exact_match and needle:sub(1, 1) ~= "'" then
return fuzzy_find(needle, haystacks)
end
if not opts.exact_match then
needle = needle:sub(2)
end
if not opts.case_sensitive then
needle = needle:lower()
end
local result = {}
local needle_words = {}
for word in needle:gmatch("%S+") do
needle_words[#needle_words + 1] = word
end
for i, haystack in ipairs(haystacks) do
if not opts.case_sensitive then
haystack = haystack:lower()
end
local matching_positions = {}
for _, word in pairs(needle_words) do
local start, e = haystack:find(word, 1, true)
if start then
for j = start, e do
matching_positions[#matching_positions + 1] = j
end
else
matching_positions = nil
break
end
end
if matching_positions then
table.sort(matching_positions)
result[#result + 1] = { i, matching_positions }
end
end
return result
end
local function get_matches_to_print(terminal)
if not selectable_items or focused_match == 0 then
return {}
end
local items = {}
local max_lines = calculate_max_lines()
local escape = terminal and function (str) return str end or ass_escape
local highlight = terminal and terminal_styles.matched_position or
"{\\1c&H" .. color_option_to_ass(opts.match_color) .. "}"
if focused_match < first_match_to_print then
first_match_to_print = focused_match
elseif focused_match > first_match_to_print + max_lines - 1 then
first_match_to_print = focused_match - max_lines + 1
end
local last_match_to_print = math.min(first_match_to_print + max_lines - 1,
#matches)
if last_match_to_print - first_match_to_print + 1 < math.min(max_lines, #matches) and
last_match_to_print >= math.min(max_lines, #matches) then
first_match_to_print = last_match_to_print - math.min(max_lines, #matches) + 1
end
for i = first_match_to_print, last_match_to_print do
local item = ""
local end_highlight = terminal and terminal_styles.match_end or "{\\1c}"
if terminal then
if matches[i].index == default_item then
item = terminal_styles.default_item
end
if i == focused_match then
item = item .. terminal_styles.selected_completion
end
else
if i == focused_match then
if searching_history and
mp.get_property("osd-border-style") == "outline-and-shadow" then
item = get_selected_ass()
else
item = "{\\1c&H" .. color_option_to_ass(opts.focused_color) .. "&}"
end
end_highlight = item
end
end
local char_positions = utf8_positions(matches[i].text)
local start_of_last_match = matches[i].positions[1]
if not start_of_last_match then
item = item .. escape(matches[i].text)
elseif start_of_last_match > 1 then
item = item .. escape(matches[i].text:sub(1, start_of_last_match - 1))
end
for j, pos in ipairs(matches[i].positions) do
local last_pos = matches[i].positions[j - 1]
if last_pos and pos > last_pos + 1 then
if char_positions[start_of_last_match] and char_positions[last_pos + 1] then
item = item .. highlight ..
escape(matches[i].text:sub(start_of_last_match, last_pos)) ..
end_highlight ..
escape(matches[i].text:sub(last_pos + 1, pos - 1))
else
item = item .. escape(matches[i].text:sub(start_of_last_match, pos - 1))
end
start_of_last_match = pos
end
end
if start_of_last_match then
local last_pos = matches[i].positions[#matches[i].positions]
if char_positions[start_of_last_match] and char_positions[last_pos + 1] then
item = item .. highlight ..
escape(matches[i].text:sub(start_of_last_match, last_pos)) ..
end_highlight ..
escape(matches[i].text:sub(last_pos + 1))
else
item = item .. escape(matches[i].text:sub(start_of_last_match))
end
end
items[#items + 1] = item
end
return items
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 open then
if osd_msg_active then
mp.osd_message("")
end
osd_msg_active = false
return
end
local log = ""
local counter = ""
if selectable_items then
if #selectable_items > calculate_max_lines() then
local digits = math.ceil(math.log(#selectable_items, 10))
counter = terminal_styles.disabled ..
"[" .. string.format("%0" .. digits .. "d", focused_match) ..
"/" .. string.format("%0" .. digits .. "d", #matches) ..
"]\027[0m "
end
local clip = mp.get_property("term-clip-cc")
for _, item in ipairs(get_matches_to_print(true)) do
log = log .. clip .. item .. "\027[0m\n"
end
else
for _, log_line in ipairs(log_buffers[id]) do
log = log .. log_line.terminal_style .. log_line.text .. "\027[0m\n"
end
if not dim_completions then
for i, completion in ipairs(completion_buffer) do
if should_highlight_completion(i) then
log = log .. terminal_styles.selected_completion ..
completion .. "\027[0m"
else
log = log .. completion
end
log = log .. (i < #completion_buffer and "\t" or "\n")
end
end
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 .. counter .. prompt .. " " .. before_cur .. "\027[7m" ..
after_cur:sub(1, 1) .. "\027[0m" .. after_cur:sub(2), 999)
osd_msg_active = true
end
render = function()
pending_update = false
if terminal_output() 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 after closing the console
if not open then
update_overlay("", 0, 0, 0)
return
end
local ass = assdraw.ass_new()
local osd_w, osd_h = get_scaled_osd_dimensions()
local line_height = get_line_height()
local max_lines = calculate_max_lines()
local x, y, alignment, clipping_coordinates
if selectable_items and not searching_history then
x = (osd_w - max_item_width) / 2
y = osd_h *
(global_margins.t + (1 - global_margins.t - global_margins.b) / 2) -
(math.min(#selectable_items, max_lines) + 1.5) * line_height / 2
alignment = 7
clipping_coordinates = x .. ",0," .. x + max_item_width .. "," .. osd_h
else
x = get_margin_x()
y = osd_h * (1 - global_margins.b) - get_margin_y()
alignment = 1
-- Avoid drawing below topbar OSC when there are wrapped lines.
local coordinate_top = math.floor(global_margins.t * osd_h + 0.5)
clipping_coordinates = "0," .. coordinate_top .. "," .. osd_w .. "," .. osd_h
end
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 border_style = mp.get_property("osd-border-style")
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" ..
(get_property_cached("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))
local log_ass = ""
local log_buffer = log_buffers[id] or {}
log_offset = math.max(math.min(log_offset, #log_buffer - 1), 0)
local last = #log_buffer - log_offset
local first = math.max(last - math.min(max_lines, #log_buffer) + 1, 1)
for i = first, last do
log_ass = log_ass .. style .. log_buffer[i].style ..
ass_escape(log_buffer[i].text) .. "\\N"
end
local completion_ass = ""
if completion_buffer[1] and not selectable_items 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.
-- TODO: --osd-margin-x should scale with osd-width and PlayResX to make
-- the calculation accurate.
local width_max = math.floor(
(osd_w - x - mp.get_property_native("osd-margin-x") * 2)
/ 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 ..
(dim_completions and styles.inactive or "") ..
completions .. "\\N"
end
-- Background
if selectable_items and
(not searching_history or border_style == "background-box") then
style = style .. "{\\bord0\\blur0\\4a&Hff&}"
local back_color, back_alpha = mpv_color_to_ass(mp.get_property(
border_style == "background-box" and "osd-back-color" or "osd-outline-color"))
if not searching_history then
back_alpha = string.format("%x", opts.background_alpha)
end
ass:new_event()
ass:an(alignment)
ass:pos(x, y)
ass:append("{\\1c&H" .. back_color .. "&\\1a&H" .. back_alpha ..
"&\\bord" .. opts.menu_outline_size .. "\\3c&H" ..
color_option_to_ass(opts.menu_outline_color) .. "\\blur0&}")
if border_style == "background-box" then
ass:append("{\\4a&Hff&}")
end
ass:draw_start()
ass:round_rect_cw(-opts.padding,
opts.padding * (alignment == 7 and -1 or 1),
max_item_width + opts.padding,
(1.5 + math.min(#matches, max_lines)) * line_height +
opts.padding * (alignment == 7 and 1 or 2),
opts.corner_radius, opts.corner_radius)
ass:draw_stop()
end
local items = get_matches_to_print()
item_positions = {}
for i, item in ipairs(items) do
local item_y = alignment == 7
and y + (1 + i) * line_height
or y - (1.5 + #items - i) * line_height
if (first_match_to_print - 1 + i == focused_match or
matches[first_match_to_print - 1 + i].index == default_item)
and (not searching_history or border_style == "background-box") then
ass:new_event()
ass:an(4)
ass:pos(x, item_y)
ass:append("{\\blur0\\bord0\\4aH&ff&\\1c&H" ..
color_option_to_ass(opts.focused_back_color) .. "&}")
if first_match_to_print - 1 + i ~= focused_match then
ass:append("{\\1aH&cc&}")
end
ass:draw_start()
ass:rect_cw(-opts.padding, 0, max_item_width + opts.padding, line_height)
ass:draw_stop()
end
ass:new_event()
ass:an(4)
ass:pos(x - horizontal_offset, item_y)
ass:append(style .. item)
item_positions[#item_positions + 1] =
{ item_y - line_height / 2, item_y + line_height / 2 }
end
-- Scrollbar
if selectable_items and #matches > max_lines then
ass:new_event()
ass:an(alignment + 2)
ass:pos(x + max_item_width, y)
ass:append(style)
if not searching_history or border_style == "background-box" then
ass:append("{\\bord0\\4a&Hff&\\blur0}")
end
ass:append(focused_match .. "/" .. #matches)
local start_percentage = (first_match_to_print - 1) / #matches
local end_percentage = (first_match_to_print - 1 + max_lines) / #matches
if end_percentage - start_percentage < 0.04 then
local diff = 0.04 - (end_percentage - start_percentage)
start_percentage = start_percentage * (1 - diff)
end_percentage = end_percentage + diff * (1 - end_percentage)
end
local max_height = max_lines * line_height
local bar_y = alignment == 7
and y + 1.5 * line_height + start_percentage * max_height
or y - 1.5 * line_height - max_height * (1 - end_percentage)
local height = max_height * (end_percentage - start_percentage)
ass:new_event()
ass:an(alignment)
ass:append("{\\blur0\\4a&Hff&\\bord1}")
ass:pos(x + max_item_width + opts.padding - 1, bar_y)
ass:draw_start()
ass:rect_cw(0, 0, -opts.padding / 2, height)
ass:draw_stop()
end
ass:new_event()
ass:an(alignment)
ass:pos(x, y)
if not selectable_items then
ass:append(log_ass .. "\\N" .. completion_ass)
end
ass:append(style .. ass_escape(prompt) .. " " .. before_cur)
ass:append(cglyph)
ass:append(style .. after_cur)
-- Redraw the cursor with the input text invisible. This will make the
-- cursor appear in front of the text.
ass:new_event()
ass:an(alignment)
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 history and deduplicate
local function history_add(text)
if history[#history] == text or text == "" then
return
end
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
if history_paths[id] then
histories_to_save[id] = histories_to_save[id] .. text .. "\n"
end
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 not selectable_items then
handle_cursor_move()
mp.commandv("script-message-to", input_caller, input_caller_handler, "edited",
utils.format_json({line}))
return
end
matches = {}
for i, match in ipairs(find_matches(line, selectable_items)) do
matches[i] = {