forked from tomasklaen/uosc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
uosc.lua
3574 lines (3200 loc) · 118 KB
/
uosc.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
--[[
uosc 2.16.0 - 2022-Mar-21 | https://github.com/darsain/uosc
Minimalist cursor proximity based UI for MPV player.
uosc replaces the default osc UI, so that has to be disabled first.
Place these options into your `mpv.conf` file:
```
# required so that the 2 UIs don't fight each other
osc=no
# uosc provides its own seeking/volume indicators, so you also don't need this
osd-bar=no
# uosc will draw its own window controls if you disable window border
border=no
```
Options go in `script-opts/uosc.conf`. Defaults:
```
# timeline size when fully retracted, 0 will hide it completely
timeline_size_min=2
# timeline size when fully expanded, in pixels, 0 to disable
timeline_size_max=40
# same as ^ but when in fullscreen
timeline_size_min_fullscreen=0
timeline_size_max_fullscreen=60
# same thing as calling toggle-progress command once on startup
timeline_start_hidden=no
# comma separated states when timeline should always be visible. available: paused, audio
timeline_persistency=
# timeline opacity
timeline_opacity=0.8
# top border of background color to help visually separate timeline from video
timeline_border=1
# when scrolling above timeline, wheel will seek by this amount of seconds
timeline_step=5
# display seekable buffered ranges for streaming videos, syntax `color:opacity`,
# color is an BBGGRR hex code, set to `none` to disable
timeline_cached_ranges=345433:0.5
# floating number font scale adjustment
timeline_font_scale=1
# timeline chapters style: none, dots, lines, lines-top, lines-bottom
chapters=dots
chapters_opacity=0.3
# where to display volume controls: none, left, right
volume=right
volume_size=40
volume_size_fullscreen=60
volume_persistency=
volume_opacity=0.8
volume_border=1
volume_step=1
volume_font_scale=1
# playback speed widget: mouse drag or wheel to change, click to reset
speed=no
speed_size=46
speed_size_fullscreen=68
speed_persistency=
speed_opacity=1
speed_step=0.1
speed_font_scale=1
# controls all menus, such as context menu, subtitle loader/selector, etc
menu_item_height=36
menu_item_height_fullscreen=50
menu_wasd_navigation=no
menu_hjkl_navigation=no
menu_opacity=0.8
menu_font_scale=1
# menu button widget
# can be: never, bottom-bar, center
menu_button=never
menu_button_size=26
menu_button_size_fullscreen=30
menu_button_persistency=
menu_button_opacity=1
menu_button_border=1
# top bar with window controls and media title
# can be: never, no-border, always
top_bar=no-border
top_bar_size=40
top_bar_size_fullscreen=46
top_bar_persistency=
top_bar_controls=yes
top_bar_title=yes
# window border drawn in no-border mode
window_border_size=1
window_border_opacity=0.8
# pause video on clicks shorter than this number of milliseconds, 0 to disable
pause_on_click_shorter_than=0
# flash duration in milliseconds used by `flash-{element}` commands
flash_duration=1000
# distances in pixels below which elements are fully faded in/out
proximity_in=40
proximity_out=120
# BBGGRR - BLUE GREEN RED hex color codes
color_foreground=ffffff
color_foreground_text=000000
color_background=000000
color_background_text=ffffff
# use bold font weight throughout the whole UI
font_bold=no
# show total time instead of time remaining
total_time=no
# hide UI when mpv autohides the cursor
autohide=no
# can be: none, flash, static, manual (controlled by flash-pause-indicator and decide-pause-indicator commands)
pause_indicator=flash
# screen dim when stuff like menu is open, 0 to disable
curtain_opacity=0.5
# sizes to list in stream quality menu
stream_quality_options=4320,2160,1440,1080,720,480,360,240,144
# load first file when calling next on a last file in a directory and vice versa
directory_navigation_loops=no
# file types to look for when navigating media files
media_types=3gp,avi,bmp,flac,flv,gif,h264,h265,jpeg,jpg,m4a,m4v,mid,midi,mkv,mov,mp3,mp4,mp4a,mp4v,mpeg,mpg,oga,ogg,ogm,ogv,opus,png,rmvb,svg,tif,tiff,wav,weba,webm,webp,wma,wmv
# file types to look for when loading external subtitles
subtitle_types=aqt,gsub,jss,sub,ttxt,pjs,psb,rt,smi,slt,ssf,srt,ssa,ass,usf,idx,vt
# used to approximate text width
# if you are using some wide font and see a lot of right side clipping in menus,
# try bumping this up
font_height_to_letter_width_ratio=0.5
# `chapter_ranges` lets you transform chapter indicators into range indicators.
#
# Chapter range definition syntax:
# ```
# start_pattern<color:opacity>end_pattern
# ```
#
# Multiple start and end patterns can be defined by separating them with `|`:
# ```
# p1|pN<color:opacity>p1|pN
# ```
#
# Multiple chapter ranges can be defined by separating them with comma:
#
# chapter_ranges=range1,rangeN
#
# One of `start_pattern`s can be a custom keyword `{bof}` that will match
# beginning of file when it makes sense.
#
# One of `end_pattern`s can be a custom keyword `{eof}` that will match end of
# file when it makes sense.
#
# Patterns are lua patterns (http://lua-users.org/wiki/PatternsTutorial).
# They only need to occur in a title, not match it completely.
# Matching is case insensitive.
#
# `color` is a `bbggrr` hexadecimal color code.
# `opacity` is a float number from 0 to 1.
#
# Examples:
#
# Display anime openings and endings as ranges:
# ```
# chapter_ranges=^op| op$|opening<968638:0.5>.*, ^ed| ed$|^end|ending$<968638:0.5>.*|{eof}
# ```
#
# Display skippable youtube video sponsor blocks from https://github.com/po5/mpv_sponsorblock
# ```
# chapter_ranges=sponsor start<3535a5:.5>sponsor end, segment start<3535a5:0.5>segment end
# ```
chapter_ranges=^op| op$|opening<968638:0.5>.*, ^ed| ed$|^end|ending$<968638:0.5>.*|{eof}, sponsor start<3535a5:.5>sponsor end, segment start<3535a5:0.5>segment end
```
Available keybindings (place into `input.conf`):
```
Key script-binding uosc/peek-timeline
Key script-binding uosc/toggle-progress
Key script-binding uosc/flash-timeline
Key script-binding uosc/flash-top-bar
Key script-binding uosc/flash-volume
Key script-binding uosc/flash-speed
Key script-binding uosc/flash-pause-indicator
Key script-binding uosc/decide-pause-indicator
Key script-binding uosc/menu
Key script-binding uosc/load-subtitles
Key script-binding uosc/subtitles
Key script-binding uosc/audio
Key script-binding uosc/video
Key script-binding uosc/playlist
Key script-binding uosc/chapters
Key script-binding uosc/stream-quality
Key script-binding uosc/open-file
Key script-binding uosc/next
Key script-binding uosc/prev
Key script-binding uosc/first
Key script-binding uosc/last
Key script-binding uosc/next-file
Key script-binding uosc/prev-file
Key script-binding uosc/first-file
Key script-binding uosc/last-file
Key script-binding uosc/delete-file-next
Key script-binding uosc/delete-file-quit
Key script-binding uosc/show-in-directory
Key script-binding uosc/open-config-directory
```
]]
if mp.get_property('osc') == 'yes' then
mp.msg.info('Disabled because original osc is enabled!')
return
end
local assdraw = require('mp.assdraw')
local opt = require('mp.options')
local utils = require('mp.utils')
local msg = require('mp.msg')
local osd = mp.create_osd_overlay('ass-events')
local infinity = 1e309
-- OPTIONS/CONFIG/STATE
local options = {
timeline_size_min = 2,
timeline_size_max = 40,
timeline_size_min_fullscreen = 0,
timeline_size_max_fullscreen = 60,
timeline_start_hidden = false,
timeline_persistency = '',
timeline_opacity = 0.8,
timeline_border = 1,
timeline_step = 5,
timeline_cached_ranges = '345433:0.5',
timeline_font_scale = 1,
chapters = 'dots',
chapters_opacity = 0.3,
volume = 'right',
volume_size = 40,
volume_size_fullscreen = 60,
volume_persistency = '',
volume_opacity = 0.8,
volume_border = 1,
volume_step = 1,
volume_font_scale = 1,
speed = false,
speed_size = 46,
speed_size_fullscreen = 60,
speed_persistency = '',
speed_opacity = 1,
speed_step = 0.1,
speed_font_scale = 1,
menu_item_height = 36,
menu_item_height_fullscreen = 50,
menu_wasd_navigation = false,
menu_hjkl_navigation = false,
menu_opacity = 0.8,
menu_font_scale = 1,
menu_button = 'never',
menu_button_size = 26,
menu_button_size_fullscreen = 30,
menu_button_opacity = 1,
menu_button_persistency = '',
menu_button_border = 1,
top_bar = 'no-border',
top_bar_size = 40,
top_bar_size_fullscreen = 46,
top_bar_persistency = '',
top_bar_controls = true,
top_bar_title = true,
window_border_size = 1,
window_border_opacity = 0.8,
pause_on_click_shorter_than = 0,
flash_duration = 1000,
proximity_in = 40,
proximity_out = 120,
color_foreground = 'ffffff',
color_foreground_text = '000000',
color_background = '000000',
color_background_text = 'ffffff',
total_time = false,
font_bold = false,
autohide = false,
pause_indicator = 'flash',
curtain_opacity = 0.5,
stream_quality_options = '4320,2160,1440,1080,720,480,360,240,144',
directory_navigation_loops = false,
media_types = '3gp,asf,avi,bmp,flac,flv,gif,h264,h265,jpeg,jpg,m4a,m4v,mid,midi,mkv,mov,mp3,mp4,mp4a,mp4v,mpeg,mpg,oga,ogg,ogm,ogv,opus,png,rmvb,svg,tif,tiff,wav,weba,webm,webp,wma,wmv',
subtitle_types = 'aqt,gsub,jss,sub,ttxt,pjs,psb,rt,smi,slt,ssf,srt,ssa,ass,usf,idx,vt',
font_height_to_letter_width_ratio = 0.5,
chapter_ranges = '^op| op$|opening<968638:0.5>.*, ^ed| ed$|^end|ending$<968638:0.5>.*|{eof}, sponsor start<3535a5:.5>sponsor end, segment start<3535a5:0.5>segment end',
}
opt.read_options(options, 'uosc')
local config = {
render_delay = 0.03, -- sets max rendering frequency
font = mp.get_property('options/osd-font'),
menu_parent_opacity = 0.4,
menu_min_width = 260
}
local bold_tag = options.font_bold and '\\b1' or ''
local display = {
width = 1280,
height = 720,
aspect = 1.77778,
}
local cursor = {
hidden = true, -- true when autohidden or outside of the player window
x = 0,
y = 0,
}
local state = {
os = (function()
if os.getenv('windir') ~= nil then return 'windows' end
local homedir = os.getenv('HOME')
if homedir ~= nil and string.sub(homedir,1,6) == '/Users' then return 'macos' end
return 'linux'
end)(),
cwd = mp.get_property('working-directory'),
media_title = '',
duration = nil,
position = nil,
pause = false,
chapters = nil,
chapter_ranges = nil,
border = mp.get_property_native('border'),
fullscreen = mp.get_property_native('fullscreen'),
maximized = mp.get_property_native('window-maximized'),
fullormaxed = mp.get_property_native('fullscreen') or mp.get_property_native('window-maximized'),
render_timer = nil,
render_last_time = 0,
volume = nil,
volume_max = nil,
mute = nil,
is_audio = nil, -- true if file is audio only (mp3, etc)
cursor_autohide_timer = mp.add_timeout(mp.get_property_native('cursor-autohide') / 1000, function()
if not options.autohide then return end
handle_mouse_leave()
end),
mouse_bindings_enabled = false,
cached_ranges = nil,
}
local forced_key_bindings -- defined at the bottom next to events
-- HELPERS
function round(number)
local modulus = number % 1
return modulus < 0.5 and math.floor(number) or math.ceil(number)
end
function call_me_maybe(fn, value1, value2, value3)
if fn then fn(value1, value2, value3) end
end
function split(str, pattern)
local list = {}
local full_pattern = '(.-)' .. pattern
local last_end = 1
local start_index, end_index, capture = str:find(full_pattern, 1)
while start_index do
list[#list +1] = capture
last_end = end_index + 1
start_index, end_index, capture = str:find(full_pattern, last_end)
end
if last_end <= (#str + 1) then
capture = str:sub(last_end)
list[#list +1] = capture
end
return list
end
function itable_find(haystack, needle)
local is_needle = type(needle) == 'function' and needle or function(index, value)
return value == needle
end
for index, value in ipairs(haystack) do
if is_needle(index, value) then return index, value end
end
end
function itable_filter(haystack, needle)
local is_needle = type(needle) == 'function' and needle or function(index, value)
return value == needle
end
local filtered = {}
for index, value in ipairs(haystack) do
if is_needle(index, value) then filtered[#filtered + 1] = value end
end
return filtered
end
function itable_remove(haystack, needle)
local should_remove = type(needle) == 'function' and needle or function(value)
return value == needle
end
local new_table = {}
for _, value in ipairs(haystack) do
if not should_remove(value) then
new_table[#new_table + 1] = value
end
end
return new_table
end
function itable_slice(haystack, start_pos, end_pos)
start_pos = start_pos and start_pos or 1
end_pos = end_pos and end_pos or #haystack
if end_pos < 0 then end_pos = #haystack + end_pos + 1 end
if start_pos < 0 then start_pos = #haystack + start_pos + 1 end
local new_table = {}
for index, value in ipairs(haystack) do
if index >= start_pos and index <= end_pos then
new_table[#new_table + 1] = value
end
end
return new_table
end
function table_copy(table)
local new_table = {}
for key, value in pairs(table) do new_table[key] = value end
return new_table
end
-- Sorting comparator close to (but not exactly) how file explorers sort files
local word_order_comparator = (function()
local symbol_order
local default_order
if state.os == 'win' then
symbol_order = {
['!'] = 1, ['#'] = 2, ['$'] = 3, ['%'] = 4, ['&'] = 5, ['('] = 6, [')'] = 6, [','] = 7,
['.'] = 8, ["'"] = 9, ['-'] = 10, [';'] = 11, ['@'] = 12, ['['] = 13, [']'] = 13, ['^'] = 14,
['_'] = 15, ['`'] = 16, ['{'] = 17, ['}'] = 17, ['~'] = 18, ['+'] = 19, ['='] = 20,
}
default_order = 21
else
symbol_order = {
['`'] = 1, ['^'] = 2, ['~'] = 3, ['='] = 4, ['_'] = 5, ['-'] = 6, [','] = 7, [';'] = 8,
['!'] = 9, ["'"] = 10, ['('] = 11, [')'] = 11, ['['] = 12, [']'] = 12, ['{'] = 13, ['}'] = 14,
['@'] = 15, ['$'] = 16, ['*'] = 17, ['&'] = 18, ['%'] = 19, ['+'] = 20, ['.'] = 22, ['#'] = 23,
}
default_order = 21
end
return function (a, b)
a = a:lower()
b = b:lower()
for i = 1, math.max(#a, #b) do
local ai = a:sub(i, i)
local bi = b:sub(i, i)
if ai == nil and bi then return true end
if bi == nil and ai then return false end
local a_order = symbol_order[ai] or default_order
local b_order = symbol_order[bi] or default_order
if a_order == b_order then
return a < b
else
return a_order < b_order
end
end
end
end)()
-- Creates in-between frames to animate value from `from` to `to` numbers.
-- Returns function that terminates animation.
-- `to` can be a function that returns target value, useful for movable targets.
-- `speed` is an optional float between 1-instant and 0-infinite duration
-- `callback` is called either on animation end, or when animation is canceled
function tween(from, to, setter, speed, callback)
if type(speed) ~= 'number' then
callback = speed
speed = 0.3
end
local timeout
local getTo = type(to) == 'function' and to or function() return to end
local cutoff = math.abs(getTo() - from) * 0.01
function tick()
from = from + ((getTo() - from) * speed)
local is_end = math.abs(getTo() - from) <= cutoff
setter(is_end and getTo() or from)
request_render()
if is_end then
call_me_maybe(callback)
else
timeout:resume()
end
end
timeout = mp.add_timeout(0.016, tick)
tick()
return function()
timeout:kill()
call_me_maybe(callback)
end
end
-- Kills ongoing animation if one is already running on this element.
-- Killed animation will not get its `on_end` called.
function tween_element(element, from, to, setter, speed, callback)
if type(speed) ~= 'number' then
callback = speed
speed = 0.3
end
tween_element_stop(element)
element.stop_current_animation = tween(
from, to,
function(value) setter(element, value) end,
speed,
function()
element.stop_current_animation = nil
call_me_maybe(callback, element)
end
)
end
-- Stopped animation will not get its on_end called.
function tween_element_is_tweening(element)
return element and element.stop_current_animation
end
-- Stopped animation will not get its on_end called.
function tween_element_stop(element)
call_me_maybe(element and element.stop_current_animation)
end
-- Helper to automatically use an element property setter
function tween_element_property(element, prop, from, to, speed, callback)
tween_element(element, from, to, function(_, value) element[prop] = value end, speed, callback)
end
function get_point_to_rectangle_proximity(point, rect)
local dx = math.max(rect.ax - point.x, 0, point.x - rect.bx + 1)
local dy = math.max(rect.ay - point.y, 0, point.y - rect.by + 1)
return math.sqrt(dx*dx + dy*dy);
end
function text_width_estimate(letters, font_size)
return letters and letters * font_size * options.font_height_to_letter_width_ratio or 0
end
function opacity_to_alpha(opacity)
return 255 - math.ceil(255 * opacity)
end
function ass_opacity(opacity, fraction)
fraction = fraction ~= nil and fraction or 1
if type(opacity) == 'number' then
return string.format('{\\alpha&H%X&}', opacity_to_alpha(opacity * fraction))
else
return string.format(
'{\\1a&H%X&\\2a&H%X&\\3a&H%X&\\4a&H%X&}',
opacity_to_alpha((opacity[1] or 0) * fraction),
opacity_to_alpha((opacity[2] or 0) * fraction),
opacity_to_alpha((opacity[3] or 0) * fraction),
opacity_to_alpha((opacity[4] or 0) * fraction)
)
end
end
-- Ensures path is absolute and normalizes slashes to the current platform
function normalize_path(path)
if not path or is_protocol(path) then return path end
-- Ensure path is absolute
if not (path:match('^/') or path:match('^%a+:') or path:match('^\\\\')) then
path = utils.join_path(state.cwd, path)
end
-- Use proper slashes
if state.os == 'windows' then
return path:gsub('/', '\\')
else
return path:gsub('\\', '/')
end
end
-- Check if path is a protocol, such as `http://...`
function is_protocol(path)
return path:match('^%a[%a%d-_]+://')
end
function get_extension(path)
local parts = split(path, '%.')
return parts and #parts > 1 and parts[#parts] or nil
end
-- Serializes path into its semantic parts
function serialize_path(path)
if not path or is_protocol(path) then return end
path = normalize_path(path)
local parts = split(path, '[\\/]+')
if parts[#parts] == '' then table.remove(parts, #parts) end -- remove trailing separator
local basename = parts and parts[#parts] or path
local dirname = #parts > 1 and table.concat(itable_slice(parts, 1, #parts - 1), state.os == 'windows' and '\\' or '/') or nil
local dot_split = split(basename, '%.')
return {
path = path:sub(-1) == ':' and state.os == 'windows' and path..'\\' or path,
is_root = dirname == nil,
dirname = dirname,
basename = basename,
filename = #dot_split > 1 and table.concat(itable_slice(dot_split, 1, #dot_split - 1), '.') or basename,
extension = #dot_split > 1 and dot_split[#dot_split] or nil,
}
end
function get_files_in_directory(directory, allowed_types)
local files, error = utils.readdir(directory, 'files')
if not files then
msg.error('Retrieving files failed: '..(error or ''))
return
end
-- Filter only requested file types
if allowed_types then
files = itable_filter(files, function(_, file)
local extension = get_extension(file)
return extension and itable_find(allowed_types, extension:lower())
end)
end
table.sort(files, word_order_comparator)
return files
end
function get_adjacent_file(file_path, direction, allowed_types)
local current_file = serialize_path(file_path)
local files = get_files_in_directory(current_file.dirname, allowed_types)
if not files then return end
for index, file in ipairs(files) do
if current_file.basename == file then
if direction == 'forward' then
if files[index + 1] then return utils.join_path(current_file.dirname, files[index + 1]) end
if options.directory_navigation_loops and files[1] then return utils.join_path(current_file.dirname, files[1]) end
else
if files[index - 1] then return utils.join_path(current_file.dirname, files[index - 1]) end
if options.directory_navigation_loops and files[#files] then return utils.join_path(current_file.dirname, files[#files]) end
end
-- This is the only file in directory
return nil
end
end
end
-- Can't use `os.remove()` as it fails on paths with unicode characters.
-- Returns `result, error`, result is table of `status:number(<0=error), stdout, stderr, error_string, killed_by_us:boolean`
function delete_file(file_path)
local args = state.os == 'windows' and {'cmd', '/C', 'del', file_path} or {'rm', file_path}
return mp.command_native({name = 'subprocess', args = args, playback_only = false, capture_stdout = true, capture_stderr = true})
end
-- Ensures chapters are in chronological order
function get_normalized_chapters()
local chapters = mp.get_property_native('chapter-list')
if not chapters then return end
-- Copy table
chapters = itable_slice(chapters)
-- Ensure chronological order of chapters
table.sort(chapters, function(a, b) return a.time < b.time end)
return chapters
end
function is_element_persistent(name)
local option_name = name..'_persistency';
return (options[option_name].audio and state.is_audio) or (options[option_name].paused and state.pause)
end
-- Element
--[[
Signature:
{
-- element rectangle coordinates
ax = 0, ay = 0, bx = 0, by = 0,
-- cursor<>element relative proximity as a 0-1 floating number
-- where 0 = completely away, and 1 = touching/hovering
-- so it's easy to work with and throw into equations
proximity = 0,
-- raw cursor<>element proximity in pixels
proximity_raw = infinity,
-- called when element is created
?init = function(this),
-- called manually when disposing of element
?destroy = function(this),
-- triggered when event happens and cursor is above element
?on_{event_name} = function(this),
-- triggered when any event happens anywhere on a page
?on_global_{event_name} = function(this),
-- object
?render = function(this_element),
}
]]
local Element = {
ax = 0, ay = 0, bx = 0, by = 0,
proximity = 0, proximity_raw = infinity,
}
Element.__index = Element
function Element.new(props)
local element = setmetatable(props, Element)
element._eventListeners = {}
-- Flash timer
element._flash_out_timer = mp.add_timeout(options.flash_duration / 1000, function()
local getTo = function() return element.proximity end
element:tween_property('forced_proximity', 1, getTo, function()
element.forced_proximity = nil
end)
end)
element._flash_out_timer:kill()
element:init()
return element
end
function Element:init() end
function Element:destroy() end
-- Call method if it exists
function Element:maybe(name, ...)
if self[name] then return self[name](self, ...) end
end
-- Tween helpers
function Element:tween(...) tween_element(self, ...) end
function Element:tween_property(...) tween_element_property(self, ...) end
function Element:tween_stop() tween_element_stop(self) end
function Element:is_tweening() tween_element_is_tweening(self) end
-- Event listeners
function Element:on(name, handler)
if self._eventListeners[name] == nil then self._eventListeners[name] = {} end
local preexistingIndex = itable_find(self._eventListeners[name], handler)
if preexistingIndex then
return
else
self._eventListeners[name][#self._eventListeners[name] + 1] = handler
end
end
function Element:off(name, handler)
if self._eventListeners[name] == nil then return end
local index = itable_find(self._eventListeners, handler)
if index then table.remove(self._eventListeners, index) end
end
function Element:trigger(name, ...)
self:maybe('on_'..name, ...)
if self._eventListeners[name] == nil then return end
for _, handler in ipairs(self._eventListeners[name]) do handler(...) end
request_render()
end
-- Briefly flashes the element for `options.flash_duration` milliseconds.
-- Useful to visualize changes of volume and timeline when changed via hotkeys.
-- Implemented by briefly adding animated `forced_proximity` property to the element.
function Element:flash()
if options.flash_duration > 0 and (self.proximity < 1 or self._flash_out_timer:is_enabled()) then
self:tween_stop()
self.forced_proximity = 1
self._flash_out_timer:kill()
self._flash_out_timer:resume()
end
end
-- ELEMENTS
local Elements = {itable = {}}
Elements.__index = Elements
local elements = setmetatable({}, Elements)
function Elements:add(name, element)
local insert_index = #Elements.itable + 1
-- Replace if element already exists
if self:has(name) then
insert_index = itable_find(Elements.itable, function(_, element)
return element.name == name
end)
end
element.name = name
Elements.itable[insert_index] = element
self[name] = element
request_render()
end
function Elements:remove(name, props)
Elements.itable = itable_remove(Elements.itable, self[name])
self[name] = nil
request_render()
end
function Elements:trigger(name, ...)
for _, element in self:ipairs() do element:trigger(name, ...) end
end
function Elements:has(name) return self[name] ~= nil end
function Elements:ipairs() return ipairs(Elements.itable) end
function Elements:pairs(elements) return pairs(self) end
-- MENU
--[[
Usage:
```
local items = {
{title = 'Foo title', hint = 'Ctrl+F', value = 'foo'},
{title = 'Bar title', hint = 'Ctrl+B', value = 'bar'},
{
title = 'Submenu',
items = {
{title = 'Sub item 1', value = 'sub1'},
{title = 'Sub item 2', value = 'sub2'}
}
}
}
function open_item(value)
value -- value from `item.value`
end
menu:open(items, open_item)
```
]]
local Menu = {}
Menu.__index = Menu
local menu = setmetatable({key_bindings = {}, is_closing = false}, Menu)
function Menu:is_open(menu_type)
return elements.menu ~= nil and (not menu_type or elements.menu.type == menu_type)
end
function Menu:open(items, open_item, opts)
opts = opts or {}
if menu:is_open() then
if not opts.parent_menu then
menu:close(true, function()
menu:open(items, open_item, opts)
end)
return
end
else
menu:enable_key_bindings()
elements.curtain:fadein()
end
elements:add('menu', Element.new({
type = nil, -- menu type such as `menu`, `chapters`, ...
title = nil,
width = nil,
height = nil,
offset_x = 0, -- used to animated from/to left when submenu
item_height = nil,
item_spacing = 1,
item_content_spacing = nil,
font_size = nil,
scroll_step = nil,
scroll_height = nil,
scroll_y = 0,
opacity = 0,
relative_parent_opacity = 0.4,
items = items,
active_item = nil,
selected_item = nil,
open_item = open_item,
parent_menu = nil,
init = function(this)
-- Already initialized
if this.width ~= nil then return end
-- Apply options
for key, value in pairs(opts) do this[key] = value end
if not this.selected_item then
this.selected_item = this.active_item
end
-- Set initial dimensions
this:on_display_change()
-- Scroll to active item
this:scroll_to_item(this.active_item)
-- Transition in animation
menu.transition = {to = 'child', target = this}
local start_offset = this.parent_menu and (this.parent_menu.width + this.width) / 2 or 0
tween_element(menu.transition.target, 0, 1, function(_, pos)
this:set_offset_x(round(start_offset * (1 - pos)))
this.opacity = pos
this:set_parent_opacity(1 - ((1 - config.menu_parent_opacity) * pos))
end, function()
menu.transition = nil
update_proximities()
end)
end,
destroy = function(this)
request_render()
end,
on_display_change = function(this)
this.item_height = state.fullormaxed and options.menu_item_height_fullscreen or options.menu_item_height
this.font_size = round(this.item_height * 0.48 * options.menu_font_scale)
this.item_content_spacing = round((this.item_height - this.font_size) * 0.6)
this.scroll_step = this.item_height + this.item_spacing
-- Estimate width of a widest item
local estimated_max_width = 0
for _, item in ipairs(this.items) do
local item_text_length = ((item.title and item.title:len() or 0) + (item.hint and item.hint:len() or 0))
local spacings_in_item = item.hint and 3 or 2
local estimated_width = text_width_estimate(item_text_length, this.font_size) + (this.item_content_spacing * spacings_in_item)
if estimated_width > estimated_max_width then
estimated_max_width = estimated_width
end
end
-- Also check menu title
local menu_title_length = this.title and this.title:len() or 0
local estimated_menu_title_width = text_width_estimate(menu_title_length, this.font_size)
if estimated_menu_title_width > estimated_max_width then
estimated_max_width = estimated_menu_title_width
end
-- Coordinates and sizes are of the scrollable area to make
-- consuming values in rendering easier. Title drawn above this, so
-- we need to account for that in max_height and ay position.
this.width = round(math.min(math.max(estimated_max_width, config.menu_min_width), display.width * 0.9))
local title_height = this.title and this.scroll_step or 0
local max_height = round(display.height * 0.9) - title_height
this.height = math.min(round(this.scroll_step * #this.items) - this.item_spacing, max_height)
this.scroll_height = math.max((this.scroll_step * #this.items) - this.height - this.item_spacing, 0)
this.ax = round((display.width - this.width) / 2) + this.offset_x
this.ay = round((display.height - this.height) / 2 + (title_height / 2))
this.bx = round(this.ax + this.width)
this.by = round(this.ay + this.height)
if this.parent_menu then
this.parent_menu:on_display_change()
end
end,
update = function(this, props)
if props then
for key, value in pairs(props) do this[key] = value end
end
-- Reset indexes and scroll
this:select_index(this.selected_item)
this:activate_index(this.active_item)
this:scroll_to(this.scroll_y)
-- Trigger changes and re-render
this:on_display_change()
request_render()
end,
set_offset_x = function(this, offset)
local delta = offset - this.offset_x
this.offset_x = offset
this.ax = this.ax + delta
this.bx = this.bx + delta
if this.parent_menu then
this.parent_menu:set_offset_x(offset - ((this.width + this.parent_menu.width) / 2) - this.item_spacing)
else
update_proximities()
end
end,
fadeout = function(this, callback)
this:tween(1, 0, function(this, pos)
this.opacity = pos
this:set_parent_opacity(pos * config.menu_parent_opacity)
end, callback)
end,
set_parent_opacity = function(this, opacity)
if this.parent_menu then
this.parent_menu.opacity = opacity
this.parent_menu:set_parent_opacity(opacity * config.menu_parent_opacity)
end
end,
get_item_index_below_cursor = function(this)
return math.ceil((cursor.y - this.ay + this.scroll_y) / this.scroll_step)
end,
get_first_visible_index = function(this)