summaryrefslogtreecommitdiff
path: root/mpv/scripts/file-browser/modules/addons/last-opened-directory.lua
blob: c68f4087fbc2a13f4bb557db739b6841f928cef7 (plain)
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
--[[
    An addon for mpv-file-browser which stores the last opened directory and
    sets it as the opened directory the next time mpv is opened.

    Available at: https://github.com/CogentRedTester/mpv-file-browser/tree/master/addons
]]--

local mp = require 'mp'
local msg = require 'mp.msg'

local fb = require 'file-browser'

local state_file = mp.command_native({'expand-path', fb.get_opt('last_opened_directory_file')}) --[[@as string]]
msg.verbose('using', state_file)

---@param directory? string
---@return nil
local function write_directory(directory)
    if not fb.get_opt('save_last_opened_directory') then return end

    local file = io.open(state_file, 'w+')

    if not file then return msg.error('could not open', state_file, 'for writing') end

    directory = directory or fb.get_directory() or ''
    msg.verbose('writing', directory, 'to', state_file)
    file:write(directory)
    file:close()
end

---@type ParserConfig
local addon = {
    api_version = '1.7.0',
    priority = 0,
}

function addon:setup()
    if not fb.get_opt('default_to_last_opened_directory') then return end

    local file = io.open(state_file, "r")
    if not file then
        return msg.info('failed to open', state_file, 'for reading (may be due to first load)')
    end

    local dir = file:read("*a")
    msg.verbose('setting default directory to', dir)
    fb.browse_directory(dir, false)
    file:close()
end

function addon:can_parse(dir, parse_state)
    if parse_state.source == 'browser' then write_directory(dir) end
    return false
end

function addon:parse()
    return nil
end

mp.register_event('shutdown', function() write_directory() end)

return addon