summaryrefslogtreecommitdiff
path: root/osd.lua
blob: 3be5e2d5a4de46d3bbb00620657d8d95598838c9 (plain) (blame)
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
-- Copyright 2025 David Vazgenovich Shakaryan

local config = require('config')

local mp_utils = require('mp.utils')

local osd = {}
local mt = {}
mt.__index = mt

local colours = {}
for k, v in pairs(config.colours) do
	-- constructed backwards as ASS colour tags expect BGR but we configure
	-- them as RGB
	tag = '&}'
	for byte in v:gmatch('..') do
		tag = byte:upper() .. tag
	end
	colours[k] = '{\\c&H' .. tag
end

local bgra_file = mp_utils.join_path(
	config.tmp_dir,
	mp.get_script_name() .. '-' .. mp_utils.getpid() .. '.bgra')

local function draw_rect(x1, y1, x2, y2)
	return string.format(
		'{\\p1}m %f %f l %f %f %f %f %f %f{\\p0}',
		x1, y1, x2, y1, x2, y2, x1, y2)
end

local cursor_glyph = '{\\pbo' .. math.floor(config.font_size / 5) .. '}' ..
	draw_rect(0, 0, math.ceil(config.font_size / 32), config.font_size)

local function asscape(str)
	-- remove newlines before escaping, since we don't want output to
	-- unexpectedly span multiple lines
	return mp.command_native({'escape-ass', (str:gsub('\n', ' '))})
end

function osd.new(init)
	local lines = math.floor((720 / config.font_size) + 0.5) - 1
	local t = setmetatable({
		fg = mp.create_osd_overlay('ass-events'),
		bg = mp.create_osd_overlay('ass-events'),
		menu_button = mp.create_osd_overlay('ass-events'),
		width = 0,
		height = 0,
		scale = 1,
		lines = lines,
		padding = math.floor((720 - (lines * config.font_size)) / 2),
	}, mt)
	t.bg.z = -1
	t.menu_button.z = 1
	t.menu_button.hidden = true

	for k, v in pairs(init or {}) do
		t[k] = v
	end

	return t
end

function mt:destroy()
	if self.magick_cmd_id then
		mp.abort_async_command(self.magick_cmd_id)
	end

	if mp_utils.file_info(bgra_file) then
		os.remove(bgra_file)
	end
end

function mt:dirty()
	self.is_dirty = true
end

function mt:flush(state)
	if self.is_dirty then
		self:redraw(state)
	end
end

function mt:resize(w, h)
	self.width = w
	self.height = h
	self.scale = h > 0 and h/720 or 1

	local sz = self.padding + self:measure_width('»') - 2
	local coords = {
		x1 = 2,
		y1 = self.padding + ((config.font_size - sz) / 2),
	}
	coords.x2 = coords.x1 + sz
	coords.y2 = coords.y1 + sz
	self.menu_button_coords = coords

	self.menu_button.data =
		'{\\pos(' .. coords.x1 .. ',' .. coords.y1 .. ')}' ..
		colours.menu_button_bg .. draw_rect(0, 0, sz, sz) .. '\n' ..
		'{\\q2\\fs' .. sz .. '\\bord0\\an5\\pos(' ..
		coords.x1 + sz/2 .. ',' .. coords.y1 + sz/2 ..')}' ..
		colours.menu_button_fg .. '≡'
	self.menu_button:update()
end

function mt:set_status(msg, level, no_dirty)
	if self.status_timer then
		self.status_timer:kill()
		self.status_timer = nil
	end

	self.status_msg = msg
	self.status_level = level

	if not no_dirty then
		self:dirty()
	end
end

function mt:flash_status(msg, level, secs)
	self:set_status(msg, level, true)
	self:render()

	self.status_timer = mp.add_timeout(secs or 3, function()
		self.status_timer = nil

		if self.status_msg == msg then
			self:set_status(nil, nil, true)
			self:render()
		end
	end)
end

function mt:flash_error(msg, secs)
	self:flash_status(msg, 'error', secs)
end

function mt:status_line()
	if not self.status_msg then
		return ''
	end

	local col = self.status_level == 'error' and colours.status_error or
		colours.status_info
	return col .. '🞸 {\\i1}' .. asscape(self.status_msg)
end

function mt:menu_lines(state)
	-- leaves an extra line for padding between titles and options
	return self.lines - state.depth - 1
end

function mt:menu_title(menu)
	local str = asscape(menu.title)
	local col = menu.search_active and colours.selected or colours.title

	if menu.type == 'search' then
		str = str:gsub('<text>', asscape(menu.search_text))

		if str:find('<text_with_cursor>', 1, true) then
			str = str:gsub('<text_with_cursor>',
				asscape(menu.search_text:sub(
						1, menu.search_cursor - 1)) ..
					cursor_glyph ..
					asscape(menu.search_text:sub(
						menu.search_cursor)))
		end

		str = str:gsub('<colours.info>', colours.info)
		str = str:gsub('<num_matches>', #menu.options)
		str = str:gsub('<num_total>', #menu.search_options)
	end

	if menu.sorted then
		str = colours.icon_sorted .. '⇅ ' .. col .. str
	end

	return col .. '» ' .. str
end

function mt:option_icons(opt, info)
	local str = ''
	if info.selected then
		str = colours.selected .. '› '
	end
	if info.playing then
		str = str .. colours.icon_playing .. '\226\143\186 '
	end
	if info.favourited then
		str = str .. colours.icon_favourite .. '★ '
	end
	if opt.active then
		str = str .. colours.icon_active .. '\226\143\186 '
	end
	if opt.missing then
		str = str .. colours.icon_missing .. '!!!MISSING!!! '
	end
	return str
end

function mt:option_text(opt, info)
	local str = opt.name
	local col = colours.option
	if info.selected then
		col = info.empty and colours.selected_empty or colours.selected
	elseif info.empty then
		col = colours.group_empty
	elseif opt.type == 'group' then
		col = colours.group
	end

	if opt.matches then
		local buf = ''
		local hl_col = info.empty and colours.search_hl_empty or
			colours.search_hl
		local n = 0

		for _, match in ipairs(opt.matches) do
			buf = buf .. col ..
				asscape(str:sub(n + 1, match.start - 1)) ..
				hl_col ..
				asscape(str:sub(match.start, match.stop))
			n = match.stop
		end
		str = buf .. col .. asscape(str:sub(n + 1))
	else
		str = col .. asscape(str)
	end

	if opt.type == 'group' then
		str = col .. '[' .. str .. ']'
	end

	if opt.info and #opt.info > 0 then
		str = str .. colours.info .. ' (' .. asscape(opt.info) .. ')'
	end

	return str
end

function mt:option_path(opt, info)
	if not opt.path or #opt.path == 0 then
		return ''
	end

	local str = info.empty and colours.search_path_empty or
		colours.search_path
	for i = #opt.path, 1, -1 do
		str = str .. ' « ' .. asscape(opt.path[i].name)
	end
	return str
end

function mt:load_img()
	local f = mp_utils.file_info(self.img.path)
	if not f then
		return
	end

	if self.magick_cmd_id then
		mp.abort_async_command(self.magick_cmd_id)
	end

	local magick_cmd = {
		'magick', self.img.path,
		'-depth', '8',
		'-resize', string.format(
			'x%%[fx:max(min(%d,%d*h/w),min(%d,%d*h/w))]',
			self.img.min_h, self.img.min_w,
			self.img.max_h, self.img.max_w),
		'-print', '%w %h',
		bgra_file
	}
	print('exec: ' .. mp_utils.to_string(magick_cmd))
	self.img.magick_cmd = magick_cmd
	self.magick_cmd = magick_cmd
	self.magick_cmd_id = mp.command_native_async({
		name = 'subprocess',
		args = magick_cmd,
		capture_stdout = true,
		playback_only = false,
	}, function (_, res)
		if magick_cmd ~= self.magick_cmd then
			return
		end

		self.magick_cmd = nil
		self.magick_cmd_id = nil

		if not self.img then
			return
		end

		if not res or res.status ~= 0 then
			if self.img_fail_cb then
				self.img_fail_cb()
			end
			return
		end

		local w, h = res.stdout:match('(.+) (.+)')
		self.img.cmd = {
			name = 'overlay-add',
			id = 0,
			file = bgra_file,
			w = w,
			h = h,
			x = self.img.right - w,
			y = self.img.top,
			fmt = 'bgra',
			offset = 0,
			stride = 4*w,
		}

		self:draw_img()
	end)
end

function mt:clear_img(purge)
	if self.img_overlay_id then
		mp.command_native(
			{name = 'overlay-remove', id = self.img_overlay_id})
		self.img_overlay_id = nil
	end

	if purge then
		self.img = nil
	end
end

function mt:draw_img()
	if not self.img then
		return
	end

	if not self.img.magick_cmd then
		self:load_img()
		return
	end

	if self.img.cmd and not self:is_hidden() then
		mp.command_native(self.img.cmd)
		self.img_overlay_id = self.img.cmd.id
	end
end

-- returns (upd, new)
-- upd: if anything changed, e.g. position
-- new: if the image also changed, i.e. different path or size
function mt:set_img(path, menu_res)
	-- images require *real* dimensions and coordinates, unlike other OSD
	-- functions which scale the given values automatically
	local padding = math.ceil(self.scale * self.padding)
	local start = math.ceil(self.scale * menu_res.x1)
	local fs = self.scale * config.font_size

	-- images are scaled to fit the available OSD area when treated as
	-- having the 2:3 aspect ratio of a standard film poster. a minimum
	-- size, derived from font size and total area, is used as a fallback
	-- when insufficient space remains, potentially overlapping the tail
	-- end of text. when the underlying image reaches this minimum height,
	-- the 2:3 treatment is abandoned, fixing the height and allowing the
	-- image to grow horizontally to an arbitrary limit, after which the
	-- width becomes fixed and the height continues to shrink.
	--
	-- this is designed to keep images legible while fixing at least one
	-- dimension under normal circumstances, preventing jarring switches
	-- between different images rendered on the same menu.
	--
	-- because we have only the total width of the current OSD text, we
	-- cannot slightly reduce the image width to avoid overlapping some
	-- longer line at the bottom, as we do not know where the offending
	-- line is. if it were possible to place images *under* text, maybe
	-- we'd allow overlap, but mpv currently hard-codes this order.
	local pw = self.width - 2*padding
	local min_h = math.min(3 * fs, pw * 3/2)
	local min_w = math.ceil(math.min(3 * min_h, pw))
	local max_h = math.max(min_h, math.min(
		self.height - 2*padding, (pw - start) * 3/2))
	local max_w = math.ceil(max_h * 2/3)
	min_h = math.floor(min_h)
	max_h = math.floor(max_h)
	local top = padding
	local right = self.width - padding

	if self.img and path == self.img.path and
			min_h == self.img.min_h and
			min_w == self.img.min_w and
			max_h == self.img.max_h and
			max_w == self.img.max_w then
		if top == self.img.top and right == self.img.right then
			return false, false
		end

		self.img.top = top
		self.img.right = right
		if self.img.cmd then
			self.img.cmd.x = right - self.img.cmd.w
			self.img.cmd.y = top
		end
		return true, false
	end

	self.img = {
		path = path,
		min_h = min_h,
		min_w = min_w,
		max_h = max_h,
		max_w = max_w,
		top = top,
		right = right,
	}
	return true, true
end

function mt:draw_scrollbar(state)
	local menu = state:menu()
	local opts = #menu.options
	local lines = self:menu_lines(state)
	if opts <= lines then
		return
	end

	local top = self.padding + ((self.lines - lines) * config.font_size)
	local h = 720 - self.padding - top
	local w = self.padding - 4
	local hh = math.max(config.font_size / 2, h * lines / opts)
	local pos = (h - hh) * (menu.view_top - 1) / (opts - lines)

	return (
		-- bg
		colours.scrollbar_bg ..
		'{\\pos(2,' .. top .. ')}' .. draw_rect(0, 0, w, h) .. '\n' ..
		-- fg
		colours.scrollbar_fg .. '{\\bord0}' ..
		'{\\pos(2,' .. top + pos .. ')}' .. draw_rect(0, 0, w, hh))
end

-- this takes the data generated by redraw() and related functions, prepares it
-- for rendering and pushes the result to the actual OSD. since it has no
-- dependence on `state', it's simpler and more efficient to use this directly
-- for things like displaying status messages.
function mt:render()
	local out = {}

	for _, v in ipairs(self.out.titles) do
		out[#out+1] = v
	end

	-- use spacer line between titles and options for status messages
	out[#out+1] = self:status_line()

	for _, v in ipairs(self.out.options) do
		out[#out+1] = v
	end

	local buf = {}
	-- each line uses a new ASS event with explicit positioning. otherwise,
	-- lines with nonstandard height break things.
	-- \q2 disables line wrapping
	local pre = '{\\q2\\fs' .. config.font_size ..
		'\\pos(' .. self.padding .. ',%s)}'
	for i, v in ipairs(out) do
		local offset = self.padding + ((i - 1) * config.font_size)
		buf[#buf+1] = pre:format(offset) .. v
	end
	-- rendering `max' is needed to compute bounds only when there is an
	-- image to display.
	if self.out.img then
		buf[#buf+1] = '{\\alpha&HFF&}' .. pre:format(0) ..
			table.concat(self.out.max, '\\N')
	end
	self.fg.data = table.concat(buf, '\n')

	self.fg.compute_bounds = not not self.out.img_path
	local res = self.fg:update()
	-- unset compute_bounds because it is relatively expensive and we don't
	-- need it when update() is called to toggle visibility of the last
	-- rendered data.
	self.fg.compute_bounds = false
	self.bg:update()
	if self.out.img_path then
		local upd, new = self:set_img(self.out.img_path, res)
		if upd then
			if new then
				self:clear_img()
			end
			self:draw_img()
		end
	else
		self:clear_img(true)
	end
end

function mt:redraw(state)
	local out_titles = {}
	local out_options = {}

	-- to determine the area left for images, we use the computed bounds of
	-- the rendered menu, which shifts when the cursor is moved to/from the
	-- longest line. to prevent this, this table stores the menu options
	-- with the cursor drawn on every line, which we then *invisibly* draw
	-- behind the actual menu, resulting in static bounds.
	--
	-- to avoid wasting space, we consider only the cursor icon, as the
	-- goal here is to avoid images being resized as a result of simple
	-- menu navigation. state changes with associated icons, such as
	-- playing a file, may still change the computed bounds, as may
	-- navigation which moves the viewport.
	local out_max = {}

	for i = 1, state.depth do
		out_titles[#out_titles+1] = self:menu_title(state.menus[i])
	end

	local menu = state:menu()

	local img
	if menu.img_url then
		img = menu.img_url
	end

	for i = menu.view_top, math.min(
			menu.view_top + self:menu_lines(state) - 1,
			#menu.options) do
		local opt = menu.options[i]

		-- use real-time count for favourites
		if opt.id == 'favourites' then
			opt.info = tostring(#state.favourites)
		end

		local selected = i == menu.cursor and not menu.search_active
		local info = {
			selected = selected,
			empty = (opt.type == 'group' and not opt.lazy and
				#opt.children == 0),
			playing = not not (
				opt.id and opt.id == state.playing_id),
			favourited = not not (
				opt.id and state:favourited(opt.id)),
		}
		local str = self:option_text(opt, info) ..
			self:option_path(opt, info)
		out_options[#out_options+1] = self:option_icons(opt, info) ..
			str

		if selected and opt.img_url then
			img = opt.img_url
		end

		info.selected = true
		out_max[#out_max+1] = self:option_icons(opt, info) .. str
	end

	self.out = {
		titles = out_titles,
		options = out_options,
		max = out_max,
	}

	-- we can draw this directly from here since any changes handled by
	-- render() will not modify this.
	self.bg.data =
		'{\\pos(0,0)\\alpha&H' .. config.bg_alpha .. '&\\c&H&}' ..
		draw_rect(0, 0, 7680, 720)
	local sb = self:draw_scrollbar(state)
	if sb then
		self.bg.data = self.bg.data .. '\n' .. sb
	end

	if img and self.img_path_func then
		self.out.img_path = self.img_path_func(img, function(path)
			-- these are set by render(), which we always call
			-- before returning.
			if self.img and path == self.img.path then
				self:draw_img()
			end
		end)
	end

	self:render()
	self.is_dirty = false
end

function mt:toggle_hidden()
	local hidden = not self:is_hidden()

	self.fg.hidden = hidden
	self.fg:update()
	self.bg.hidden = hidden
	self.bg:update()

	if hidden then
		self:clear_img()
	else
		self:draw_img()
	end
end

function mt:is_hidden()
	return self.fg.hidden
end

function mt:get_mouse_line(mpos)
	local x = mpos.x / self.scale
	local w = self.width / self.scale
	if x < self.padding or x > w - self.padding then
		return
	end

	local y = mpos.y / self.scale
	local line = math.floor((y - self.padding) / config.font_size) + 1
	if line < 1 or line > self.lines then
		return
	end
	return line
end

function mt:mouse_over_button_area(mpos)
	if not mpos.hover then
		return false
	end

	local y = mpos.y / self.scale
	return y < self.padding + (2 * config.font_size)
end

function mt:mouse_over_menu_button(mpos)
	if not mpos.hover then
		return false
	end

	local x = mpos.x / self.scale
	local y = mpos.y / self.scale
	local coords = self.menu_button_coords
	return coords and
		x > coords.x1 and x < coords.x2 and
		y > coords.y1 and y < coords.y2
end

function mt:show_menu_button(bool)
	if self.menu_button.hidden ~= bool then
		return
	end

	self.menu_button.hidden = not bool
	self.menu_button:update()
end

function mt:measure_width(str)
	local e = self.menu_button
	local data = e.data
	local hidden = e.hidden
	e.hidden = true
	e.compute_bounds = true

	local block = '\xe2\x96\x88'
	local pre = '{\\q2\\fs' .. config.font_size .. '\\pos(0,0)}' .. block
	e.data = pre .. block
	local size = e:update().x1
	e.data = pre .. str .. block
	size = e:update().x1 - size

	e.data = data
	e.hidden = hidden
	e.compute_bounds = false

	return size
end

return osd