diff options
Diffstat (limited to 'player/lua')
-rw-r--r-- | player/lua/auto_profiles.lua | 28 | ||||
-rw-r--r-- | player/lua/console.lua | 561 | ||||
-rw-r--r-- | player/lua/defaults.lua | 24 | ||||
-rw-r--r-- | player/lua/input.lua | 69 | ||||
-rw-r--r-- | player/lua/meson.build | 3 | ||||
-rw-r--r-- | player/lua/osc.lua | 94 | ||||
-rw-r--r-- | player/lua/stats.lua | 316 |
7 files changed, 768 insertions, 327 deletions
diff --git a/player/lua/auto_profiles.lua b/player/lua/auto_profiles.lua index 9dca878..a0f5802 100644 --- a/player/lua/auto_profiles.lua +++ b/player/lua/auto_profiles.lua @@ -164,8 +164,8 @@ local function compile_cond(name, s) return chunk end -local function load_profiles() - for i, v in ipairs(mp.get_property_native("profile-list")) do +local function load_profiles(profiles_property) + for _, v in ipairs(profiles_property) do local cond = v["profile-cond"] if cond and #cond > 0 then local profile = { @@ -182,17 +182,25 @@ local function load_profiles() end end -load_profiles() +mp.observe_property("profile-list", "native", function (_, profiles_property) + profiles = {} + watched_properties = {} + cached_properties = {} + properties_to_profiles = {} + mp.unobserve_property(on_property_change) -if #profiles < 1 and mp.get_property("load-auto-profiles") == "auto" then - -- make it exit immediately - _G.mp_event_loop = function() end - return -end + load_profiles(profiles_property) + + if #profiles < 1 and mp.get_property("load-auto-profiles") == "auto" then + -- make it exit immediately + _G.mp_event_loop = function() end + return + end + + on_idle() -- re-evaluate all profiles immediately +end) mp.register_idle(on_idle) for _, name in ipairs({"on_load", "on_preloaded", "on_before_start_file"}) do mp.add_hook(name, 50, on_hook) end - -on_idle() -- re-evaluate all profiles immediately diff --git a/player/lua/console.lua b/player/lua/console.lua index 44e9436..bbfaf47 100644 --- a/player/lua/console.lua +++ b/player/lua/console.lua @@ -27,11 +27,13 @@ local opts = { -- multiplied by "scale". font_size = 16, border_size = 1, + case_sensitive = true, -- Remove duplicate entries in history as to only keep the latest one. history_dedup = true, -- The ratio of font height to font width. -- Adjusts table width of completion suggestions. - font_hw_ratio = 2.0, + -- Values in the range 1.8..2.5 make sense for common monospace fonts. + font_hw_ratio = 'auto', } function detect_platform() @@ -48,6 +50,7 @@ end local platform = detect_platform() if platform == 'windows' then opts.font = 'Consolas' + opts.case_sensitive = false elseif platform == 'darwin' then opts.font = 'Menlo' else @@ -66,11 +69,21 @@ local styles = { -- cccc66 cc9966 cc99cc 537bd2 debug = '{\\1c&Ha09f93&}', - verbose = '{\\1c&H99cc99&}', + v = '{\\1c&H99cc99&}', warn = '{\\1c&H66ccff&}', error = '{\\1c&H7a77f2&}', fatal = '{\\1c&H5791f9&\\b1}', suggestion = '{\\1c&Hcc99cc&}', + selected_suggestion = '{\\1c&H2fbdfa&\\b1}', +} + +local terminal_styles = { + debug = '\027[1;30m', + v = '\027[32m', + warn = '\027[33m', + error = '\027[31m', + fatal = '\027[1;31m', + selected_suggestion = '\027[7m', } local repl_active = false @@ -78,15 +91,26 @@ local insert_mode = false local pending_update = false local line = '' local cursor = 1 -local history = {} +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 log_buffer = {} -local suggestion_buffer = {} +local log_buffers = {[id] = {}} local key_bindings = {} local global_margins = { t = 0, b = 0 } +local input_caller +local suggestion_buffer = {} +local selected_suggestion_index +local completion_start_position +local completion_append local file_commands = {} local path_separator = platform == 'windows' and '\\' or '/' +local completion_old_line +local completion_old_cursor local update_timer = nil update_timer = mp.add_periodic_timer(0.05, function() @@ -107,9 +131,88 @@ mp.observe_property("user-data/osc/margins", "native", function(_, val) update() end) +do + 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' + local x1, y1 = nil, nil + size = size / 0.8 + -- prevent endless loop + local repetitions_left = 5 + repeat + size = size * 0.8 + local ass = assdraw.ass_new() + ass.text = template:format(align, size, opts.font, rotation, text) + _, _, x1, y1 = measure_bounds(ass.text) + repetitions_left = repetitions_left - 1 + -- make sure nothing got clipped + until (x1 and x1 < osd_width and y1 < osd_height) or repetitions_left == 0 + local width = (repetitions_left == 0 and not x1) and 0 or (horizontal and x1 or y1) + 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 + 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 +end + -- Add a line to the log buffer (which is limited to 100 lines) -function log_add(style, text) - log_buffer[#log_buffer + 1] = { style = style, text = text } +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 @@ -126,19 +229,7 @@ end -- Escape a string for verbatim display on the OSD function ass_escape(str) - -- There is no escape for '\' in ASS (I think?) but '\' is used verbatim if - -- it isn't followed by a recognised character, so add a zero-width - -- non-breaking space - str = str:gsub('\\', '\\\239\187\191') - str = str:gsub('{', '\\{') - str = str:gsub('}', '\\}') - -- Precede newlines with a ZWNBSP to prevent ASS's weird collapsing of - -- consecutive newlines - str = str:gsub('\n', '\239\187\191\\N') - -- Turn leading spaces into hard spaces to prevent ASS from stripping them - str = str:gsub('\\N ', '\\N\\h') - str = str:gsub('^ ', '\\h') - return str + return mp.command_native({'escape-ass', str}) end -- Takes a list of strings, a max width in characters and @@ -206,7 +297,9 @@ function format_table(list, width_max, rows_max) 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 string.format('%' .. spaces .. 's', ' ') or '' + local spacing = column_count > 1 + and ass_escape(string.format('%' .. spaces .. 's', ' ')) + or '' local rows = {} for row = 1, row_count do @@ -217,12 +310,17 @@ function format_table(list, width_max, rows_max) -- 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] = string.format(format_string, list[i]) + columns[column] = ass_escape(string.format(format_string, list[i])) + + if i == selected_suggestion_index then + columns[column] = styles.selected_suggestion .. columns[column] + .. '{\\b0}'.. styles.suggestion + end end -- first row is at the bottom rows[row_count - row + 1] = table.concat(columns, spacing) end - return table.concat(rows, '\n'), row_count + return table.concat(rows, ass_escape('\n')), row_count end local function print_to_terminal() @@ -233,13 +331,19 @@ local function print_to_terminal() end local log = '' - for _, log_line in ipairs(log_buffer) do - log = log .. log_line.text + for _, log_line in ipairs(log_buffers[id]) do + log = log .. log_line.terminal_style .. log_line.text .. '\027[0m' end - local suggestions = table.concat(suggestion_buffer, '\t') - if suggestions ~= '' then - suggestions = suggestions .. '\n' + local suggestions = '' + for i, suggestion in ipairs(suggestion_buffer) do + if i == selected_suggestion_index then + suggestions = suggestions .. terminal_styles.selected_suggestion .. + suggestion .. '\027[0m' + else + suggestions = suggestions .. suggestion + end + suggestions = suggestions .. (i < #suggestion_buffer and '\t' or '\n') end local before_cur = line:sub(1, cursor - 1) @@ -249,22 +353,18 @@ local function print_to_terminal() after_cur = ' ' end - mp.osd_message(log .. suggestions .. '> ' .. before_cur .. '\027[7m' .. - after_cur:sub(1, 1) .. '\027[0m' .. after_cur:sub(2), 999) + mp.osd_message(log .. suggestions .. prompt .. ' ' .. before_cur .. + '\027[7m' .. after_cur:sub(1, 1) .. '\027[0m' .. + after_cur:sub(2), 999) end -- Render the REPL and console as an ASS OSD function update() pending_update = false - -- Print to the terminal when there is no VO. Check both vo-configured so - -- it works with --force-window --idle and no video tracks, and whether - -- there is a video track so that the condition doesn't become true while - -- switching VO at runtime, making mp.osd_message() print to the VO's OSD. - -- This issue does not happen when switching VO without any video track - -- regardless of the condition used. - if not mp.get_property_native('vo-configured') - and not mp.get_property('current-tracks/video') then + -- 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') then print_to_terminal() return end @@ -300,8 +400,9 @@ function update() -- thin as possible and make it appear to be 1px wide by giving it 0.5px -- horizontal borders. local cheight = opts.font_size * 8 - local cglyph = '{\\r' .. - '\\1a&H44&\\3a&H44&\\4a&H99&' .. + local cglyph = '{\\rDefault' .. + (mp.get_property_native('focused') == false + and '\\alpha&HFF&' or '\\1a&H44&\\3a&H44&\\4a&H99&') .. '\\1c&Heeeeee&\\3c&Heeeeee&\\4c&H000000&' .. '\\xbord0.5\\ybord0\\xshad0\\yshad1\\p4\\pbo24}' .. 'm 0 0 l 1 0 l 1 ' .. cheight .. ' l 0 ' .. cheight .. @@ -317,12 +418,13 @@ function update() local screeny_factor = (1 - global_margins.t - global_margins.b) local lines_max = math.ceil(screeny * screeny_factor / opts.font_size - 1.5) -- Estimate how many characters fit in one line - local width_max = math.ceil(screenx / opts.font_size * opts.font_hw_ratio) + local width_max = math.ceil(screenx / opts.font_size * get_font_hw_ratio()) local suggestions, rows = format_table(suggestion_buffer, width_max, lines_max) - local suggestion_ass = style .. styles.suggestion .. ass_escape(suggestions) + local suggestion_ass = style .. styles.suggestion .. suggestions local log_ass = '' + local log_buffer = log_buffers[id] local log_messages = #log_buffer local log_max_lines = math.max(0, lines_max - rows) if log_max_lines < log_messages then @@ -339,7 +441,7 @@ function update() if #suggestions > 0 then ass:append(suggestion_ass .. '\\N') end - ass:append(style .. '> ' .. before_cur) + ass:append(style .. ass_escape(prompt) .. ' ' .. before_cur) ass:append(cglyph) ass:append(style .. after_cur) @@ -348,7 +450,7 @@ function update() ass:new_event() ass:an(1) ass:pos(2, screeny - 2 - global_margins.b * screeny) - ass:append(style .. '{\\alpha&HFF&}> ' .. before_cur) + ass:append(style .. '{\\alpha&HFF&}' .. ass_escape(prompt) .. ' ' .. before_cur) ass:append(cglyph) ass:append(style .. '{\\alpha&HFF&}' .. after_cur) @@ -362,12 +464,28 @@ function set_active(active) repl_active = true insert_mode = false mp.enable_key_bindings('console-input', 'allow-hide-cursor+allow-vo-dragging') - mp.enable_messages('terminal-default') define_key_bindings() + + if not input_caller then + prompt = default_prompt + id = default_id + history = histories[id] + history_pos = #history + 1 + mp.enable_messages('terminal-default') + end else repl_active = false + suggestion_buffer = {} undefine_key_bindings() mp.enable_messages('silent:terminal-default') + + if input_caller then + mp.commandv('script-message-to', input_caller, 'input-event', + 'closed', line, cursor) + input_caller = nil + line = '' + cursor = 1 + end collectgarbage() end update() @@ -429,6 +547,16 @@ function len_utf8(str) return len end +local function handle_edit() + suggestion_buffer = {} + update() + + if input_caller then + mp.commandv('script-message-to', input_caller, 'input-event', 'edited', + line) + end +end + -- Insert a character at the current cursor position (any_unicode) function handle_char_input(c) if insert_mode then @@ -437,8 +565,7 @@ function handle_char_input(c) line = line:sub(1, cursor - 1) .. c .. line:sub(cursor) end cursor = cursor + #c - suggestion_buffer = {} - update() + handle_edit() end -- Remove the character behind the cursor (Backspace) @@ -447,16 +574,14 @@ function handle_backspace() local prev = prev_utf8(line, cursor) line = line:sub(1, prev - 1) .. line:sub(cursor) cursor = prev - suggestion_buffer = {} - update() + handle_edit() end -- Remove the character in front of the cursor (Del) function handle_del() if cursor > line:len() then return end line = line:sub(1, cursor - 1) .. line:sub(next_utf8(line, cursor)) - suggestion_buffer = {} - update() + handle_edit() end -- Toggle insert mode (Ins) @@ -467,12 +592,14 @@ end -- Move the cursor to the next character (Right) function next_char(amount) cursor = next_utf8(line, cursor) + suggestion_buffer = {} update() end -- Move the cursor to the previous character (Left) function prev_char(amount) cursor = prev_utf8(line, cursor) + suggestion_buffer = {} update() end @@ -482,8 +609,7 @@ function clear() cursor = 1 insert_mode = false history_pos = #history + 1 - suggestion_buffer = {} - update() + handle_edit() end -- Close the REPL if the current line is empty, otherwise delete the next @@ -521,7 +647,8 @@ function help_command(param) end end if not cmd then - log_add(styles.error, 'No command matches "' .. param .. '"!') + log_add('No command matches "' .. param .. '"!\n', styles.error, + terminal_styles.error) return end output = output .. 'Command "' .. cmd.name .. '"\n' @@ -536,7 +663,7 @@ function help_command(param) output = output .. 'This command supports variable arguments.\n' end end - log_add('', output) + log_add(output) end -- Add a line to the history and deduplicate @@ -556,20 +683,25 @@ end -- Run the current command and clear the line (Enter) function handle_enter() - if line == '' then + if line == '' and input_caller == nil then return end - if history[#history] ~= line then + if history[#history] ~= line and line ~= '' then history_add(line) 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) + if input_caller then + mp.commandv('script-message-to', input_caller, 'input-event', 'submit', + line) else - mp.command(line) + -- 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 clear() @@ -607,6 +739,7 @@ function go_history(new_pos) end cursor = line:len() + 1 insert_mode = false + suggestion_buffer = {} update() end @@ -632,6 +765,7 @@ function prev_word() -- string in order to do a "backwards" find. This wouldn't be as annoying -- to do if Lua didn't insist on 1-based indexing. cursor = line:len() - select(2, line:reverse():find('%s*[^%s]*', line:len() - cursor + 2)) + 1 + suggestion_buffer = {} update() end @@ -639,6 +773,7 @@ end -- the next word. (Ctrl+Right) function next_word() cursor = select(2, line:find('%s*[^%s]*', cursor)) + 1 + suggestion_buffer = {} update() end @@ -659,19 +794,21 @@ local function command_list_and_help() end local function property_list() - local option_info = { - 'name', 'type', 'set-from-commandline', 'set-locally', 'default-value', - 'min', 'max', 'choices', - } - local properties = mp.get_property_native('property-list') + for _, sub_property in pairs({'video', 'audio', 'sub', 'sub2'}) do + properties[#properties + 1] = 'current-tracks/' .. sub_property + end + for _, option in ipairs(mp.get_property_native('options')) do properties[#properties + 1] = 'options/' .. option properties[#properties + 1] = 'file-local-options/' .. option properties[#properties + 1] = 'option-info/' .. option - for _, sub_property in ipairs(option_info) do + for _, sub_property in pairs({ + 'name', 'type', 'set-from-commandline', 'set-locally', + 'default-value', 'min', 'max', 'choices', + }) do properties[#properties + 1] = 'option-info/' .. option .. '/' .. sub_property end @@ -789,7 +926,7 @@ function build_completers() { pattern = '^%s*change[-_]list%s+"?([%w_-]+)"?%s+"()%a*$', list = list_option_verb_list, append = '" ' }, { pattern = '^%s*([av]f)%s+()%a*$', list = list_option_verb_list, append = ' ' }, { pattern = '^%s*([av]f)%s+"()%a*$', list = list_option_verb_list, append = '" ' }, - { pattern = '${=?()[%w_/-]*$', list = property_list, append = '}' }, + { pattern = '${[=>]?()[%w_/-]*$', list = property_list, append = '}' }, } for _, command in pairs({'set', 'add', 'cycle', 'cycle[-_]values', 'multiply'}) do @@ -820,32 +957,6 @@ function build_completers() return completers end --- Use 'list' to find possible tab-completions for 'part.' --- Returns a list of all potential completions and the longest --- common prefix of all the matching list items. -function complete_match(part, list) - local completions = {} - local prefix = nil - - for _, candidate in ipairs(list) do - if candidate:sub(1, part:len()) == part then - if prefix and prefix ~= candidate then - local prefix_len = part:len() - while prefix:sub(1, prefix_len + 1) - == candidate:sub(1, prefix_len + 1) do - prefix_len = prefix_len + 1 - end - prefix = candidate:sub(1, prefix_len) - else - prefix = candidate - end - completions[#completions + 1] = candidate - end - end - - return completions, prefix -end - function common_prefix_length(s1, s2) local common_count = 0 for i = 1, #s1 do @@ -873,8 +984,101 @@ function max_overlap_length(s1, s2) return 0 end +-- If str starts with the first or last characters of prefix, strip them. +local function strip_common_characters(str, prefix) + return str:sub(1 + math.max( + common_prefix_length(prefix, str), + max_overlap_length(prefix, str))) +end + +-- Find the longest common case-sensitive prefix of the entries in "list". +local function find_common_prefix(list) + local prefix = list[1] + + for i = 2, #list do + prefix = prefix:sub(1, common_prefix_length(prefix, list[i])) + end + + return prefix +end + +-- Return the entries of "list" beginning with "part" and the longest common +-- prefix of the matches. +local function complete_match(part, list) + local completions = {} + + for _, candidate in pairs(list) do + if candidate:sub(1, part:len()) == part then + completions[#completions + 1] = candidate + end + end + + local prefix = find_common_prefix(completions) + + if opts.case_sensitive then + return completions, prefix + end + + completions = {} + local lower_case_completions = {} + local lower_case_part = part:lower() + + for _, candidate in pairs(list) do + if candidate:sub(1, part:len()):lower() == lower_case_part then + completions[#completions + 1] = candidate + lower_case_completions[#lower_case_completions + 1] = candidate:lower() + end + end + + local lower_case_prefix = find_common_prefix(lower_case_completions) + + -- Behave like GNU readline with completion-ignore-case On. + -- part = 'fooBA', completions = {'foobarbaz', 'fooBARqux'} => + -- prefix = 'fooBARqux', lower_case_prefix = 'foobar', return 'fooBAR' + if prefix then + return completions, prefix:sub(1, lower_case_prefix:len()) + end + + -- part = 'fooba', completions = {'fooBARbaz', 'fooBarqux'} => + -- prefix = nil, lower_case_prefix ='foobar', return 'fooBAR' + if lower_case_prefix then + return completions, completions[1]:sub(1, lower_case_prefix:len()) + end + + return {}, part +end + +local function cycle_through_suggestions(backwards) + selected_suggestion_index = selected_suggestion_index + (backwards and -1 or 1) + + if selected_suggestion_index > #suggestion_buffer then + selected_suggestion_index = 1 + elseif selected_suggestion_index < 1 then + selected_suggestion_index = #suggestion_buffer + end + + local before_cur = line:sub(1, completion_start_position - 1) .. + suggestion_buffer[selected_suggestion_index] .. completion_append + line = before_cur .. strip_common_characters(line:sub(cursor), completion_append) + cursor = before_cur:len() + 1 + update() +end + -- Complete the option or property at the cursor (TAB) -function complete() +function complete(backwards) + if #suggestion_buffer > 0 then + cycle_through_suggestions(backwards) + return + end + + if input_caller then + completion_old_line = line + completion_old_cursor = cursor + mp.commandv('script-message-to', input_caller, 'input-event', + 'complete', line:sub(1, cursor - 1)) + return + end + local before_cur = line:sub(1, cursor - 1) local after_cur = line:sub(cursor) @@ -882,47 +1086,56 @@ function complete() for _, completer in ipairs(build_completers()) do -- Completer patterns should return the start of the word to be -- completed as the first capture. - local s, s2 = before_cur:match(completer.pattern) - if not s then + local s2 + completion_start_position, s2 = before_cur:match(completer.pattern) + if not completion_start_position then -- Multiple input commands can be separated by semicolons, so all -- completions that are anchored at the start of the string with -- '^' can start from a semicolon as well. Replace ^ with ; and try -- to match again. - s, s2 = before_cur:match(completer.pattern:gsub('^^', ';')) + completion_start_position, s2 = + before_cur:match(completer.pattern:gsub('^^', ';')) end - if s then + if completion_start_position then local hint if s2 then - hint = s - s = s2 + hint = completion_start_position + completion_start_position = s2 + end + + -- Expand ~ in file completion. + if completer.list == file_list and hint:find('^~' .. path_separator) then + local home = mp.command_native({'expand-path', '~/'}) + before_cur = before_cur:sub(1, completion_start_position - #hint - 1) .. + home .. + before_cur:sub(completion_start_position - #hint + 1) + hint = home .. hint:sub(2) + completion_start_position = completion_start_position + #home - 1 end -- If the completer's pattern found a word, check the completer's -- list for possible completions - local part = before_cur:sub(s) + local part = before_cur:sub(completion_start_position) local completions, prefix = complete_match(part, completer.list(hint)) if #completions > 0 then -- If there was only one full match from the list, add -- completer.append to the final string. This is normally a -- space or a quotation mark followed by a space. - local after_cur_index = 1 + completion_append = completer.append or '' if #completions == 1 then - local append = completer.append or '' - prefix = prefix .. append - - -- calculate offset into after_cur - local prefix_len = common_prefix_length(append, after_cur) - local overlap_size = max_overlap_length(append, after_cur) - after_cur_index = math.max(prefix_len, overlap_size) + 1 + prefix = prefix .. completion_append + after_cur = strip_common_characters(after_cur, completion_append) else table.sort(completions) suggestion_buffer = completions + selected_suggestion_index = 0 end -- Insert the completion and update - before_cur = before_cur:sub(1, s - 1) .. prefix + before_cur = before_cur:sub(1, completion_start_position - 1) .. + prefix cursor = before_cur:len() + 1 - line = before_cur .. after_cur:sub(after_cur_index) + line = before_cur .. after_cur update() return end @@ -933,12 +1146,14 @@ end -- Move the cursor to the beginning of the line (HOME) function go_home() cursor = 1 + suggestion_buffer = {} update() end -- Move the cursor to the end of the line (END) function go_end() cursor = line:len() + 1 + suggestion_buffer = {} update() end @@ -950,7 +1165,7 @@ function del_word() before_cur = before_cur:gsub('[^%s]+%s*$', '', 1) line = before_cur .. after_cur cursor = before_cur:len() + 1 - update() + handle_edit() end -- Delete from the cursor to the end of the word (Ctrl+Del) @@ -962,25 +1177,25 @@ function del_next_word() after_cur = after_cur:gsub('^%s*[^%s]+', '', 1) line = before_cur .. after_cur - update() + handle_edit() end -- Delete from the cursor to the end of the line (Ctrl+K) function del_to_eol() line = line:sub(1, cursor - 1) - update() + handle_edit() end -- Delete from the cursor back to the start of the line (Ctrl+U) function del_to_start() line = line:sub(cursor) cursor = 1 - update() + handle_edit() end -- Empty the log buffer of all messages (Ctrl+L) function clear_log_buffer() - log_buffer = {} + log_buffers[id] = {} update() end @@ -1047,7 +1262,7 @@ function paste(clip) local after_cur = line:sub(cursor) line = before_cur .. text .. after_cur cursor = cursor + text:len() - update() + handle_edit() end -- List of input bindings. This is a weird mashup between common GUI text-input @@ -1087,6 +1302,7 @@ function get_bindings() { 'alt+f', next_word }, { 'tab', complete }, { 'ctrl+i', complete }, + { 'shift+tab', function() complete(true) end }, { 'ctrl+a', go_home }, { 'home', go_home }, { 'ctrl+e', go_end }, @@ -1151,16 +1367,105 @@ mp.add_key_binding(nil, 'enable', function() set_active(true) end) +mp.register_script_message('disable', function() + set_active(false) +end) + -- Add a script-message to show the REPL and fill it with the provided text mp.register_script_message('type', function(text, cursor_pos) show_and_type(text, cursor_pos) end) +mp.register_script_message('get-input', function (script_name, args) + if repl_active then + return + end + + input_caller = script_name + args = utils.parse_json(args) + prompt = args.prompt or default_prompt + line = args.default_text or '' + cursor = tonumber(args.cursor_position) or line:len() + 1 + id = args.id or script_name .. prompt + if histories[id] == nil then + histories[id] = {} + log_buffers[id] = {} + end + history = histories[id] + history_pos = #history + 1 + + set_active(true) + mp.commandv('script-message-to', input_caller, 'input-event', 'opened') +end) + +mp.register_script_message('log', function (message) + -- input.get's edited handler is invoked after submit, so avoid modifying + -- the default log. + if input_caller == nil then + return + end + + message = utils.parse_json(message) + + log_add(message.text .. '\n', + message.error and styles.error or message.style, + message.error and terminal_styles.error or message.terminal_style) +end) + +mp.register_script_message('set-log', function (log) + if input_caller == nil then + return + end + + log = utils.parse_json(log) + log_buffers[id] = {} + + for i = 1, #log do + if type(log[i]) == 'table' then + log[i].text = log[i].text .. '\n' + log[i].style = log[i].style or '' + log[i].terminal_style = log[i].terminal_style or '' + log_buffers[id][i] = log[i] + else + log_buffers[id][i] = { + text = log[i] .. '\n', + style = '', + terminal_style = '', + } + end + end + + update() +end) + +mp.register_script_message('complete', function(list, start_pos) + if line ~= completion_old_line or cursor ~= completion_old_cursor then + return + end + + local completions, prefix = complete_match(line:sub(start_pos, cursor), + utils.parse_json(list)) + local before_cur = line:sub(1, start_pos - 1) .. prefix + local after_cur = line:sub(cursor) + cursor = before_cur:len() + 1 + line = before_cur .. after_cur + + if #completions > 1 then + suggestion_buffer = completions + selected_suggestion_index = 0 + completion_start_position = start_pos + completion_append = '' + end + + update() +end) + -- Redraw the REPL when the OSD size changes. This is needed because the -- PlayRes of the OSD will need to be adjusted. mp.observe_property('osd-width', 'native', update) mp.observe_property('osd-height', 'native', update) mp.observe_property('display-hidpi-scale', 'native', update) +mp.observe_property('focused', 'native', update) -- Enable log messages. In silent mode, mpv will queue log messages in a buffer -- until enable_messages is called again without the silent: prefix. @@ -1185,20 +1490,8 @@ mp.register_event('log-message', function(e) if e.level == 'trace' then return end -- Use color for debug/v/warn/error/fatal messages. - local style = '' - if e.level == 'debug' then - style = styles.debug - elseif e.level == 'v' then - style = styles.verbose - elseif e.level == 'warn' then - style = styles.warn - elseif e.level == 'error' then - style = styles.error - elseif e.level == 'fatal' then - style = styles.fatal - end - - log_add(style, '[' .. e.prefix .. '] ' .. e.text) + log_add('[' .. e.prefix .. '] ' .. e.text, styles[e.level], + terminal_styles[e.level]) end) collectgarbage() diff --git a/player/lua/defaults.lua b/player/lua/defaults.lua index 233d1d6..baa3a24 100644 --- a/player/lua/defaults.lua +++ b/player/lua/defaults.lua @@ -809,28 +809,4 @@ function mp_utils.subprocess_detached(t) mp.commandv("run", unpack(t.args)) end -function mp_utils.shared_script_property_set(name, value) - if value ~= nil then - -- no such thing as change-list with mpv_node, so build a string value - mp.commandv("change-list", "shared-script-properties", "append", - name .. "=" .. value) - else - mp.commandv("change-list", "shared-script-properties", "remove", name) - end -end - -function mp_utils.shared_script_property_get(name) - local map = mp.get_property_native("shared-script-properties") - return map and map[name] -end - --- cb(name, value) on change and on init -function mp_utils.shared_script_property_observe(name, cb) - -- it's _very_ wasteful to observe the mpv core "super" property for every - -- shared sub-property, but then again you shouldn't use this - mp.observe_property("shared-script-properties", "native", function(_, val) - cb(name, val and val[name]) - end) -end - return {} diff --git a/player/lua/input.lua b/player/lua/input.lua new file mode 100644 index 0000000..24283e4 --- /dev/null +++ b/player/lua/input.lua @@ -0,0 +1,69 @@ +--[[ +This file is part of mpv. + +mpv is free software; you can redistribute it and/or +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 of the License, or (at your option) any later version. + +mpv is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public +License along with mpv. If not, see <http://www.gnu.org/licenses/>. +]] + +local utils = require "mp.utils" +local input = {} + +function input.get(t) + mp.commandv("script-message-to", "console", "get-input", + mp.get_script_name(), utils.format_json({ + prompt = t.prompt, + default_text = t.default_text, + cursor_position = t.cursor_position, + id = t.id, + })) + + mp.register_script_message("input-event", function (type, text, cursor_position) + if t[type] then + local suggestions, completion_start_position = t[type](text, cursor_position) + + if type == "complete" and suggestions then + mp.commandv("script-message-to", "console", "complete", + utils.format_json(suggestions), completion_start_position) + end + end + + if type == "closed" then + mp.unregister_script_message("input-event") + end + end) + + return true +end + +function input.terminate() + mp.commandv("script-message-to", "console", "disable") +end + +function input.log(message, style, terminal_style) + mp.commandv("script-message-to", "console", "log", utils.format_json({ + text = message, + style = style, + terminal_style = terminal_style, + })) +end + +function input.log_error(message) + mp.commandv("script-message-to", "console", "log", + utils.format_json({ text = message, error = true })) +end + +function input.set_log(log) + mp.commandv("script-message-to", "console", "set-log", utils.format_json(log)) +end + +return input diff --git a/player/lua/meson.build b/player/lua/meson.build index 362c87c..1d87938 100644 --- a/player/lua/meson.build +++ b/player/lua/meson.build @@ -1,5 +1,6 @@ lua_files = ['defaults.lua', 'assdraw.lua', 'options.lua', 'osc.lua', - 'ytdl_hook.lua', 'stats.lua', 'console.lua', 'auto_profiles.lua'] + 'ytdl_hook.lua', 'stats.lua', 'console.lua', 'auto_profiles.lua', + 'input.lua'] foreach file: lua_files lua_file = custom_target(file, input: join_paths(source_root, 'player', 'lua', file), diff --git a/player/lua/osc.lua b/player/lua/osc.lua index 45a5d90..3ba1890 100644 --- a/player/lua/osc.lua +++ b/player/lua/osc.lua @@ -38,6 +38,7 @@ local user_opts = { seekrangeseparate = true, -- whether the seekranges overlay on the bar-style seekbar seekrangealpha = 200, -- transparency of seekranges seekbarkeyframes = true, -- use keyframes when dragging the seekbar + scrollcontrols = true, -- allow scrolling when hovering certain OSC elements title = "${media-title}", -- string compatible with property-expansion -- to be shown as OSC title tooltipborder = 1, -- border of tooltip in bottom/topbar @@ -51,6 +52,7 @@ local user_opts = { boxvideo = false, -- apply osc_param.video_margins to video windowcontrols = "auto", -- whether to show window controls windowcontrols_alignment = "right", -- which side to show window controls on + windowcontrols_title = "${media-title}", -- same as title but for windowcontrols greenandgrumpy = false, -- disable santa hat livemarkers = true, -- update seekbar chapter markers on duration change chapters_osd = true, -- whether to show chapters OSD on next/prev @@ -125,6 +127,7 @@ local state = { input_enabled = true, showhide_enabled = false, windowcontrols_buttons = false, + windowcontrols_title = false, dmx_cache = 0, using_video_margins = false, border = true, @@ -410,10 +413,10 @@ function set_track(type, next) mp.commandv("set", type, new_track_mpv) - if new_track_osc == 0 then + if new_track_osc == 0 then show_message(nicetypes[type] .. " Track: none") else - show_message(nicetypes[type] .. " Track: " + show_message(nicetypes[type] .. " Track: " .. new_track_osc .. "/" .. #tracks_osc[type] .. " [".. (tracks_osc[type][new_track_osc].lang or "unknown") .."] " .. (tracks_osc[type][new_track_osc].title or "")) @@ -436,7 +439,7 @@ end function window_controls_enabled() val = user_opts.windowcontrols if val == "auto" then - return not state.border + return not (state.border and state.title_bar) else return val ~= "no" end @@ -952,10 +955,7 @@ function show_message(text, duration) -- may slow down massively on huge input text = string.sub(text, 0, 4000) - -- replace actual linebreaks with ASS linebreaks - text = string.gsub(text, "\n", "\\N") - - state.message_text = text + state.message_text = mp.command_native({"escape-ass", text}) if not state.message_hide_timer then state.message_hide_timer = mp.add_timeout(0, request_tick) @@ -1158,10 +1158,9 @@ function window_controls(topbar) -- Window Title ne = new_element("wctitle", "button") ne.content = function () - local title = mp.command_native({"expand-text", user_opts.title}) - -- escape ASS, and strip newlines and trailing slashes - title = title:gsub("\\n", " "):gsub("\\$", ""):gsub("{","\\{") - return not (title == "") and title or "mpv" + local title = mp.command_native({"expand-text", user_opts.windowcontrols_title}) + title = title:gsub("\n", " ") + return title ~= "" and mp.command_native({"escape-ass", title}) or "mpv" end local left_pad = 5 local right_pad = 10 @@ -1789,9 +1788,8 @@ function osc_init() ne.content = function () local title = state.forced_title or mp.command_native({"expand-text", user_opts.title}) - -- escape ASS, and strip newlines and trailing slashes - title = title:gsub("\\n", " "):gsub("\\$", ""):gsub("{","\\{") - return not (title == "") and title or "mpv" + title = title:gsub("\n", " ") + return title ~= "" and mp.command_native({"escape-ass", title}) or "mpv" end ne.eventresponder["mbtn_left_up"] = function () @@ -1937,10 +1935,13 @@ function osc_init() function () set_track("audio", -1) end ne.eventresponder["shift+mbtn_left_down"] = function () show_message(get_tracklist("audio"), 2) end - ne.eventresponder["wheel_down_press"] = - function () set_track("audio", 1) end - ne.eventresponder["wheel_up_press"] = - function () set_track("audio", -1) end + + if user_opts.scrollcontrols then + ne.eventresponder["wheel_down_press"] = + function () set_track("audio", 1) end + ne.eventresponder["wheel_up_press"] = + function () set_track("audio", -1) end + end --cy_sub ne = new_element("cy_sub", "button") @@ -1960,10 +1961,13 @@ function osc_init() function () set_track("sub", -1) end ne.eventresponder["shift+mbtn_left_down"] = function () show_message(get_tracklist("sub"), 2) end - ne.eventresponder["wheel_down_press"] = - function () set_track("sub", 1) end - ne.eventresponder["wheel_up_press"] = - function () set_track("sub", -1) end + + if user_opts.scrollcontrols then + ne.eventresponder["wheel_down_press"] = + function () set_track("sub", 1) end + ne.eventresponder["wheel_up_press"] = + function () set_track("sub", -1) end + end --tog_fs ne = new_element("tog_fs", "button") @@ -2053,10 +2057,13 @@ function osc_init() "absolute-percent", "exact") end ne.eventresponder["reset"] = function (element) element.state.lastseek = nil end - ne.eventresponder["wheel_up_press"] = - function () mp.commandv("osd-auto", "seek", 10) end - ne.eventresponder["wheel_down_press"] = - function () mp.commandv("osd-auto", "seek", -10) end + + if user_opts.scrollcontrols then + ne.eventresponder["wheel_up_press"] = + function () mp.commandv("osd-auto", "seek", 10) end + ne.eventresponder["wheel_down_press"] = + function () mp.commandv("osd-auto", "seek", -10) end + end -- tc_left (current pos) @@ -2140,10 +2147,12 @@ function osc_init() ne.eventresponder["mbtn_left_up"] = function () mp.commandv("cycle", "mute") end - ne.eventresponder["wheel_up_press"] = - function () mp.commandv("osd-auto", "add", "volume", 5) end - ne.eventresponder["wheel_down_press"] = - function () mp.commandv("osd-auto", "add", "volume", -5) end + if user_opts.scrollcontrols then + ne.eventresponder["wheel_up_press"] = + function () mp.commandv("osd-auto", "add", "volume", 5) end + ne.eventresponder["wheel_down_press"] = + function () mp.commandv("osd-auto", "add", "volume", -5) end + end -- load layout @@ -2439,6 +2448,18 @@ function render() if osc_param.areas["window-controls-title"] then for _,cords in ipairs(osc_param.areas["window-controls-title"]) do + if state.osc_visible then -- activate only when OSC is actually visible + set_virt_mouse_area(cords.x1, cords.y1, cords.x2, cords.y2, "window-controls-title") + end + if state.osc_visible ~= state.windowcontrols_title then + if state.osc_visible then + mp.enable_key_bindings("window-controls-title", "allow-vo-dragging") + else + mp.disable_key_bindings("window-controls-title", "allow-vo-dragging") + end + state.windowcontrols_title = state.osc_visible + end + if mouse_hit_coords(cords.x1, cords.y1, cords.x2, cords.y2) then mouse_over_osc = true end @@ -2709,7 +2730,7 @@ function update_duration_watch() if want_watch ~= duration_watched then if want_watch then - mp.observe_property("duration", nil, on_duration) + mp.observe_property("duration", "native", on_duration) else mp.unobserve_property(on_duration) end @@ -2722,8 +2743,8 @@ update_duration_watch() mp.register_event("shutdown", shutdown) mp.register_event("start-file", request_init) -mp.observe_property("track-list", nil, request_init) -mp.observe_property("playlist", nil, request_init) +mp.observe_property("track-list", "native", request_init) +mp.observe_property("playlist", "native", request_init) mp.observe_property("chapter-list", "native", function(_, list) list = list or {} -- safety, shouldn't return nil table.sort(list, function(a, b) return a.time < b.time end) @@ -2760,6 +2781,12 @@ mp.observe_property("border", "bool", request_init_resize() end ) +mp.observe_property("title-bar", "bool", + function(name, val) + state.title_bar = val + request_init_resize() + end +) mp.observe_property("window-maximized", "bool", function(name, val) state.maximized = val @@ -2915,3 +2942,4 @@ mp.register_script_message("osc-idlescreen", idlescreen_visibility) set_virt_mouse_area(0, 0, 0, 0, "input") set_virt_mouse_area(0, 0, 0, 0, "window-controls") +set_virt_mouse_area(0, 0, 0, 0, "window-controls-title") diff --git a/player/lua/stats.lua b/player/lua/stats.lua index 16e8b68..3d093c7 100644 --- a/player/lua/stats.lua +++ b/player/lua/stats.lua @@ -30,6 +30,8 @@ local o = { print_perfdata_passes = false, -- when true, print the full information about all passes filter_params_max_length = 100, -- a filter list longer than this many characters will be shown one filter per line instead show_frame_info = false, -- whether to show the current frame info + term_width_limit = -1, -- overwrites the terminal width + term_height_limit = -1, -- overwrites the terminal height debug = false, -- Graph options and style @@ -83,6 +85,15 @@ local o = { } options.read_options(o) +o.term_width_limit = tonumber(o.term_width_limit) or -1 +o.term_height_limit = tonumber(o.term_height_limit) or -1 +if o.term_width_limit < 0 then + o.term_width_limit = nil +end +if o.term_height_limit < 0 then + o.term_height_limit = nil +end + local format = string.format local max = math.max local min = math.min @@ -118,9 +129,6 @@ local function graph_add_value(graph, value) graph.max = max(graph.max, value) end --- "\\<U+2060>" in UTF-8 (U+2060 is WORD-JOINER) -local ESC_BACKSLASH = "\\" .. string.char(0xE2, 0x81, 0xA0) - local function no_ASS(t) if not o.use_ass then return t @@ -128,16 +136,7 @@ local function no_ASS(t) -- mp.osd_message supports ass-escape using osd-ass-cc/{0|1} return ass_stop .. t .. ass_start else - -- mp.set_osd_ass doesn't support ass-escape. roll our own. - -- similar to mpv's sub/osd_libass.c:mangle_ass(...), excluding - -- space after newlines because no_ASS is not used with multi-line. - -- space at the beginning is replaced with "\\h" because it matters - -- at the beginning of a line, and we can't know where our output - -- ends up. no issue if it ends up at the middle of a line. - return tostring(t) - :gsub("\\", ESC_BACKSLASH) - :gsub("{", "\\{") - :gsub("^ ", "\\h") + return mp.command_native({"escape-ass", tostring(t)}) end end @@ -222,7 +221,7 @@ local function generate_graph(values, i, len, v_max, v_avg, scale, x_tics) local bg_box = format("{\\bord0.5}{\\3c&H%s&}{\\1c&H%s&}m 0 %f l %f %f %f 0 0 0", o.plot_bg_border_color, o.plot_bg_color, y_max, x_max, y_max, x_max) - return format("%s{\\r}{\\pbo%f}{\\shad0}{\\alpha&H00}{\\p1}%s{\\p0}{\\bord0}{\\1c&H%s}{\\p1}%s{\\p0}%s", + return format("%s{\\r}{\\rDefault}{\\pbo%f}{\\shad0}{\\alpha&H00}{\\p1}%s{\\p0}{\\bord0}{\\1c&H%s}{\\p1}%s{\\p0}%s", o.prefix_sep, y_offset, bg_box, o.plot_color, table.concat(s), text_style()) end @@ -277,7 +276,13 @@ local function sorted_keys(t, comp_fn) return keys end -local function append_perfdata(s, dedicated_page, print_passes) +local function scroll_hint() + local hint = format("(hint: scroll with %s/%s)", o.key_scroll_up, o.key_scroll_down) + if not o.use_ass then return " " .. hint end + return format(" {\\fs%s}%s{\\fs%s}", o.font_size * 0.66, hint, o.font_size) +end + +local function append_perfdata(header, s, dedicated_page, print_passes) local vo_p = mp.get_property_native("vo-passes") if not vo_p then return @@ -318,11 +323,12 @@ local function append_perfdata(s, dedicated_page, print_passes) -- ensure that the fixed title is one element and every scrollable line is -- also one single element. - s[#s+1] = format("%s%s%s%s{\\fs%s}%s%s{\\fs%s}", + local h = dedicated_page and header or s + h[#h+1] = format("%s%s%s%s{\\fs%s}%s{\\fs%s}%s", dedicated_page and "" or o.nl, dedicated_page and "" or o.indent, b("Frame Timings:"), o.prefix_sep, o.font_size * 0.66, - "(last/average/peak μs)", - dedicated_page and " (hint: scroll with ↑↓)" or "", o.font_size) + "(last/average/peak μs)", o.font_size, + dedicated_page and scroll_hint() or "") for _,frame in ipairs(sorted_keys(vo_p)) do -- ensure fixed display order local data = vo_p[frame] @@ -363,11 +369,6 @@ local function append_perfdata(s, dedicated_page, print_passes) end end -local function ellipsis(s, maxlen) - if not maxlen or s:len() <= maxlen then return s end - return s:sub(1, maxlen - 3) .. "..." -end - -- command prefix tokens to strip - includes generic property commands local cmd_prefixes = { osd_auto=1, no_osd=1, osd_bar=1, osd_msg=1, osd_msg_bar=1, raw=1, sync=1, @@ -419,7 +420,7 @@ local function keyname_cells(k) return klen end -local function get_kbinfo_lines(width) +local function get_kbinfo_lines() -- active keys: only highest priority of each key, and not our (stats) keys local bindings = mp.get_property_native("input-bindings", {}) local active = {} -- map: key-name -> bind-info @@ -482,8 +483,6 @@ local function get_kbinfo_lines(width) or format("{\\q2\\fn%s}%s {\\fn%s}{\\fs%d\\u1}", o.font_mono, kspaces, o.font, 1.3*o.font_size) local spost = term and "" or format("{\\u0\\fs%d}", o.font_size) - local _, itabs = o.indent:gsub("\t", "") - local cutoff = term and (width or 79) - o.indent:len() - itabs * 7 - spre:len() -- create the display lines local info_lines = {} @@ -497,38 +496,25 @@ local function get_kbinfo_lines(width) if bind.comment then bind.cmd = bind.cmd .. " # " .. bind.comment end - append(info_lines, ellipsis(bind.cmd, cutoff), - { prefix = kpre .. no_ASS(align_right(bind.key)) .. kpost }) + append(info_lines, bind.cmd, { prefix = kpre .. no_ASS(align_right(bind.key)) .. kpost }) end return info_lines end -local function append_general_perfdata(s, offset) - local perf_info = mp.get_property_native("perf-info") or {} - local count = 0 - for _, data in ipairs(perf_info) do - count = count + 1 - end - offset = max(1, min((offset or 1), count)) - - local i = 0 - for _, data in ipairs(perf_info) do - i = i + 1 - if i >= offset then - append(s, data.text or data.value, {prefix="["..tostring(i).."] "..data.name..":"}) - - if o.plot_perfdata and o.use_ass and data.value then - buf = perf_buffers[data.name] - if not buf then - buf = {0, pos = 1, len = 50, max = 0} - perf_buffers[data.name] = buf - end - graph_add_value(buf, data.value) - s[#s+1] = generate_graph(buf, buf.pos, buf.len, buf.max, nil, 0.8, 1) +local function append_general_perfdata(s) + for i, data in ipairs(mp.get_property_native("perf-info") or {}) do + append(s, data.text or data.value, {prefix="["..tostring(i).."] "..data.name..":"}) + + if o.plot_perfdata and o.use_ass and data.value then + buf = perf_buffers[data.name] + if not buf then + buf = {0, pos = 1, len = 50, max = 0} + perf_buffers[data.name] = buf end + graph_add_value(buf, data.value) + s[#s] = s[#s] .. generate_graph(buf, buf.pos, buf.len, buf.max, nil, 0.8, 1) end end - return offset end local function append_display_sync(s) @@ -806,6 +792,7 @@ local function append_img_params(s, r, ro) end local indent = o.prefix_sep .. o.prefix_sep + r = ro or r local pixel_format = r["hw-pixelformat"] or r["pixelformat"] append(s, pixel_format, {prefix="Format:"}) @@ -828,7 +815,7 @@ local function append_fps(s, prop, eprop) local unit = prop == "display-fps" and " Hz" or " fps" local suffix = single and "" or " (specified)" local esuffix = single and "" or " (estimated)" - local prefix = prop == "display-fps" and "Refresh Rate:" or "Frame rate:" + local prefix = prop == "display-fps" and "Refresh Rate:" or "Frame Rate:" local nl = o.nl local indent = o.indent @@ -855,6 +842,8 @@ local function add_video_out(s) append(s, vo, {prefix_sep="", nl="", indent=""}) append_property(s, "display-names", {prefix_sep="", prefix="(", suffix=")", no_prefix_markup=true, nl="", indent=" "}) + append(s, mp.get_property_native("current-gpu-context"), + {prefix="Context:", nl="", indent=o.prefix_sep .. o.prefix_sep}) append_property(s, "avsync", {prefix="A-V:"}) append_fps(s, "display-fps", "estimated-display-fps") if append_property(s, "decoder-frame-drop-count", @@ -862,9 +851,9 @@ local function add_video_out(s) append_property(s, "frame-drop-count", {suffix=" (output)", nl="", indent=""}) end append_display_sync(s) - append_perfdata(s, false, o.print_perfdata_passes) + append_perfdata(nil, s, false, o.print_perfdata_passes) - if mp.get_property_native("deinterlace") then + if mp.get_property_native("deinterlace-active") then append_property(s, "deinterlace", {prefix="Deinterlacing:"}) end @@ -902,12 +891,11 @@ local function add_video(s) return end - local osd_dims = mp.get_property_native("osd-dimensions") - local scaled_width = osd_dims["w"] - osd_dims["ml"] - osd_dims["mr"] - local scaled_height = osd_dims["h"] - osd_dims["mt"] - osd_dims["mb"] - append(s, "", {prefix=o.nl .. o.nl .. "Video:", nl="", indent=""}) - if append_property(s, "video-codec", {prefix_sep="", nl="", indent=""}) then + local track = mp.get_property_native("current-tracks/video") + if track and append(s, track["codec-desc"], {prefix_sep="", nl="", indent=""}) then + append(s, track["codec-profile"], {prefix="[", nl="", indent=" ", prefix_sep="", + no_prefix_markup=true, suffix="]"}) append_property(s, "hwdec-current", {prefix="HW:", nl="", indent=o.prefix_sep .. o.prefix_sep, no_prefix_markup=false, suffix=""}, {no=true, [""]=true}) @@ -947,19 +935,39 @@ end local function add_audio(s) local r = mp.get_property_native("audio-params") -- in case of e.g. lavfi-complex there can be no input audio, only output - if not r then - r = mp.get_property_native("audio-out-params") - end + local ro = mp.get_property_native("audio-out-params") or r + r = r or ro if not r then return end + local merge = function(r, ro, prop) + local a = r[prop] or ro[prop] + local b = ro[prop] or r[prop] + return (a == b or a == nil) and a or (a .. " ➜ " .. b) + end + append(s, "", {prefix=o.nl .. o.nl .. "Audio:", nl="", indent=""}) - append_property(s, "audio-codec", {prefix_sep="", nl="", indent=""}) - local cc = append(s, r["channel-count"], {prefix="Channels:"}) - append(s, r["format"], {prefix="Format:", nl=cc and "" or o.nl, + local track = mp.get_property_native("current-tracks/audio") + if track then + append(s, track["codec-desc"], {prefix_sep="", nl="", indent=""}) + append(s, track["codec-profile"], {prefix="[", nl="", indent=" ", prefix_sep="", + no_prefix_markup=true, suffix="]"}) + end + append_property(s, "current-ao", {prefix="AO:", nl="", + indent=o.prefix_sep .. o.prefix_sep}) + local dev = append_property(s, "audio-device", {prefix="Device:"}) + local ao_mute = mp.get_property_native("ao-mute") and " (Muted)" or "" + append_property(s, "ao-volume", {prefix="AO Volume:", suffix="%" .. ao_mute, + nl=dev and "" or o.nl, + indent=dev and o.prefix_sep .. o.prefix_sep}) + if math.abs(mp.get_property_native("audio-delay")) > 1e-6 then + append_property(s, "audio-delay", {prefix="A-V delay:"}) + end + local cc = append(s, merge(r, ro, "channel-count"), {prefix="Channels:"}) + append(s, merge(r, ro, "format"), {prefix="Format:", nl=cc and "" or o.nl, indent=cc and o.prefix_sep .. o.prefix_sep}) - append(s, r["samplerate"], {prefix="Sample Rate:", suffix=" Hz"}) + append(s, merge(r, ro, "samplerate"), {prefix="Sample Rate:", suffix=" Hz"}) append_property(s, "packet-audio-bitrate", {prefix="Bitrate:", suffix=" kbps"}) append_filters(s, "af", "Filters:") end @@ -987,6 +995,91 @@ local function eval_ass_formatting() end end +-- assumptions: +-- s is composed of SGR escape sequences and/or printable UTF8 sequences +-- printable codepoints occupy one terminal cell (we don't have wcwidth) +-- tabstops are 8, 16, 24..., and the output starts at 0 or a tabstop +-- note: if maxwidth <= 2 and s doesn't fit: the result is "..." (more than 2) +function term_ellipsis(s, maxwidth) + local TAB, ESC, SGR_END = 9, 27, ("m"):byte() + local width, ellipsis = 0, "..." + local fit_len, in_sgr + + for i = 1, #s do + local x = s:byte(i) + + if in_sgr then + in_sgr = x ~= SGR_END + elseif x == ESC then + in_sgr = true + ellipsis = "\27[0m..." -- ensure SGR reset + elseif x < 128 or x >= 192 then -- non UTF8-continuation + -- tab adds till the next stop, else add 1 + width = width + (x == TAB and 8 - width % 8 or 1) + + if fit_len == nil and width > maxwidth - 3 then + fit_len = i - 1 -- adding "..." still fits maxwidth + end + if width > maxwidth then + return s:sub(1, fit_len) .. ellipsis + end + end + end + + return s +end + +local function term_ellipsis_array(arr, from, to, max_width) + for i = from, to do + arr[i] = term_ellipsis(arr[i], max_width) + end + return arr +end + +-- split str into a table +-- example: local t = split(s, "\n") +-- plain: whether pat is a plain string (default false - pat is a pattern) +local function split(str, pat, plain) + local init = 1 + local r, i, find, sub = {}, 1, string.find, string.sub + repeat + local f0, f1 = find(str, pat, init, plain) + r[i], i = sub(str, init, f0 and f0 - 1), i+1 + init = f0 and f1 + 1 + until f0 == nil + return r +end + +-- Composes the output with header and scrollable content +-- Returns string of the finished page and the actually chosen offset +-- +-- header : table of the header where each entry is one line +-- content : table of the content where each entry is one line +-- apply_scroll: scroll the content +local function finalize_page(header, content, apply_scroll) + local term_size = mp.get_property_native("term-size", {}) + local term_width = o.term_width_limit or term_size.w or 80 + local term_height = o.term_height_limit or term_size.h or 24 + local from, to = 1, #content + if apply_scroll and term_height > 0 then + -- Up to 40 lines for libass because it can put a big performance toll on + -- libass to process many lines which end up outside (below) the screen. + -- In the terminal reduce height by 2 for the status line (can be more then one line) + local max_content_lines = (o.use_ass and 40 or term_height - 2) - #header + -- in the terminal the scrolling should stop once the last line is visible + local max_offset = o.use_ass and #content or #content - max_content_lines + 1 + from = max(1, min((pages[curr_page].offset or 1), max_offset)) + to = min(#content, from + max_content_lines - 1) + pages[curr_page].offset = from + end + local output = table.concat(header) .. table.concat(content, "", from, to) + if not o.use_ass and term_width > 0 then + local t = split(output, "\n", true) + -- limit width for the terminal + output = table.concat(term_ellipsis_array(t, 1, #t, term_width), "\n") + end + return output, from +end -- Returns an ASS string with "normal" stats local function default_stats() @@ -997,70 +1090,44 @@ local function default_stats() add_video_out(stats) add_video(stats) add_audio(stats) - return table.concat(stats) -end - -local function scroll_vo_stats(stats, fixed_items, offset) - local ret = {} - local count = #stats - fixed_items - offset = max(1, min((offset or 1), count)) - - for i, line in pairs(stats) do - if i <= fixed_items or i >= fixed_items + offset then - ret[#ret+1] = stats[i] - end - end - return ret, offset + return finalize_page({}, stats, false) end -- Returns an ASS string with extended VO stats local function vo_stats() - local stats = {} + local header, content = {}, {} eval_ass_formatting() - add_header(stats) - - -- first line (title) added next is considered fixed - local fixed_items = #stats + 1 - append_perfdata(stats, true, true) - - local page = pages[o.key_page_2] - stats, page.offset = scroll_vo_stats(stats, fixed_items, page.offset) - return table.concat(stats) + add_header(header) + append_perfdata(header, content, true, true) + header = {table.concat(header)} + return finalize_page(header, content, true) end local kbinfo_lines = nil -local function keybinding_info(after_scroll) +local function keybinding_info(after_scroll, bindlist) local header = {} local page = pages[o.key_page_4] eval_ass_formatting() add_header(header) - append(header, "", {prefix=format("%s: {\\fs%s}%s{\\fs%s}", page.desc, - o.font_size * 0.66, "(hint: scroll with ↑↓)", o.font_size), nl="", - indent=""}) + append(header, "", {prefix=format("%s:%s", page.desc, scroll_hint()), nl="", indent=""}) + header = {table.concat(header)} if not kbinfo_lines or not after_scroll then - kbinfo_lines = get_kbinfo_lines() + kbinfo_lines = get_kbinfo_lines(o.term_width_limit) end - -- up to 20 lines for the terminal - so that mpv can also print - -- the status line without scrolling, and up to 40 lines for libass - -- because it can put a big performance toll on libass to process - -- many lines which end up outside (below) the screen. - local term = not o.use_ass - local nlines = #kbinfo_lines - page.offset = max(1, min((page.offset or 1), term and nlines - 20 or nlines)) - local maxline = min(nlines, page.offset + (term and 20 or 40)) - return table.concat(header) .. - table.concat(kbinfo_lines, "", page.offset, maxline) + + return finalize_page(header, kbinfo_lines, not bindlist) end local function perf_stats() - local stats = {} + local header, content = {}, {} eval_ass_formatting() - add_header(stats) + add_header(header) local page = pages[o.key_page_0] - append(stats, "", {prefix=page.desc .. ":", nl="", indent=""}) - page.offset = append_general_perfdata(stats, page.offset) - return table.concat(stats) + append(header, "", {prefix=format("%s:%s", page.desc, scroll_hint()), nl="", indent=""}) + append_general_perfdata(content) + header = {table.concat(header)} + return finalize_page(header, content, true) end local function opt_time(t) @@ -1076,18 +1143,18 @@ local function cache_stats() eval_ass_formatting() add_header(stats) - append(stats, "", {prefix="Cache info:", nl="", indent=""}) + append(stats, "", {prefix="Cache Info:", nl="", indent=""}) local info = mp.get_property_native("demuxer-cache-state") if info == nil then append(stats, "Unavailable.", {}) - return table.concat(stats) + return finalize_page({}, stats, false) end local a = info["reader-pts"] local b = info["cache-end"] - append(stats, opt_time(a) .. " - " .. opt_time(b), {prefix = "Packet queue:"}) + append(stats, opt_time(a) .. " - " .. opt_time(b), {prefix = "Packet Queue:"}) local r = nil if a ~= nil and b ~= nil then @@ -1101,7 +1168,7 @@ local function cache_stats() nil, 0.8, 1) r_graph = o.prefix_sep .. r_graph end - append(stats, opt_time(r), {prefix = "Read-ahead:", suffix = r_graph}) + append(stats, opt_time(r), {prefix = "Readahead:", suffix = r_graph}) -- These states are not necessarily exclusive. They're about potentially -- separate mechanisms, whose states may be decoupled. @@ -1140,17 +1207,17 @@ local function cache_stats() else fc = "(disabled)" end - append(stats, fc, {prefix = "Disk cache:"}) + append(stats, fc, {prefix = "Disk Cache:"}) - append(stats, info["debug-low-level-seeks"], {prefix = "Media seeks:"}) - append(stats, info["debug-byte-level-seeks"], {prefix = "Stream seeks:"}) + append(stats, info["debug-low-level-seeks"], {prefix = "Media Seeks:"}) + append(stats, info["debug-byte-level-seeks"], {prefix = "Stream Seeks:"}) append(stats, "", {prefix=o.nl .. o.nl .. "Ranges:", nl="", indent=""}) append(stats, info["bof-cached"] and "yes" or "no", - {prefix = "Start cached:"}) + {prefix = "Start Cached:"}) append(stats, info["eof-cached"] and "yes" or "no", - {prefix = "End cached:"}) + {prefix = "End Cached:"}) local ranges = info["seekable-ranges"] or {} for n, r in ipairs(ranges) do @@ -1159,7 +1226,7 @@ local function cache_stats() {prefix = format("Range %s:", n)}) end - return table.concat(stats) + return finalize_page({}, stats, false) end -- Record 1 sample of cache statistics. @@ -1188,8 +1255,8 @@ pages = { [o.key_page_1] = { f = default_stats, desc = "Default" }, [o.key_page_2] = { f = vo_stats, desc = "Extended Frame Timings", scroll = true }, [o.key_page_3] = { f = cache_stats, desc = "Cache Statistics" }, - [o.key_page_4] = { f = keybinding_info, desc = "Active key bindings", scroll = true }, - [o.key_page_0] = { f = perf_stats, desc = "Internal performance info", scroll = true }, + [o.key_page_4] = { f = keybinding_info, desc = "Active Key Bindings", scroll = true }, + [o.key_page_0] = { f = perf_stats, desc = "Internal Performance Info", scroll = true }, } @@ -1409,9 +1476,8 @@ if o.bindlist ~= "no" then mp.add_timeout(0, function() -- wait for all other scripts to finish init o.ass_formatting = false o.no_ass_indent = " " - eval_ass_formatting() - io.write(pages[o.key_page_4].desc .. ":" .. - table.concat(get_kbinfo_lines(width)) .. "\n") + o.term_size = { w = width , h = 0} + io.write(keybinding_info(false, true) .. "\n") mp.command("quit") end) end |