File size: 2,256 Bytes
402daee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
--[[

  OptionsConfig.lua - General options configuration data model

]]--

-- Constructor
--
-- Parameters:
--   section: Section to write in reaper-extstate.ini
--   options: Mapping from option names to {type, default} pairs
--            type can be one of: 'string', 'number', 'boolean'
--
-- Example:
--   local options = OptionsConfig:new {
--     section = "ReaSpeech.Options",
--     options = {
--       patties_per_burger = {'number', 2},
--       ...
--     }
--   }
--

OptionsConfig = {}
OptionsConfig.__index = OptionsConfig

function OptionsConfig:new(o)
  o = o or {}
  setmetatable(o, self)
  assert(o.section, 'section is required')
  o.options = o.options or {}
  return o
end

function OptionsConfig:get(name)
  local option = self.options[name]
  assert(option, 'undefined option ' .. name)

  local option_type, option_default = table.unpack(option)

  if self:exists(name) then
    local str = reaper.GetExtState(self.section, name)

    if option_type == 'number' then
      return self:_string_to_number(str)
    elseif option_type == 'boolean' then
      return self:_string_to_boolean(str)
    else
      return str
    end
  else
    return option_default
  end
end

function OptionsConfig:set(name, value)
  local option = self.options[name]
  assert(option, 'undefined option ' .. name)

  local option_type, _ = table.unpack(option)

  local str
  if option_type == 'number' then
    str = self:_number_to_string(value)
  elseif option_type == 'boolean' then
    str = self:_boolean_to_string(value)
  else
    str = tostring(value)
  end

  reaper.SetExtState(self.section, name, str, true)
end

function OptionsConfig:delete(name)
  assert(self.options[name], 'undefined option ' .. name)
  reaper.DeleteExtState(self.section, name, true)
end

function OptionsConfig:exists(name)
  assert(self.options[name], 'undefined option ' .. name)
  return reaper.HasExtState(self.section, name)
end

function OptionsConfig:_string_to_number(str)
  return tonumber(str) or 0
end

function OptionsConfig:_string_to_boolean(str)
  return str == 'true'
end

function OptionsConfig:_number_to_string(num)
  return tostring(tonumber(num) or 0)
end

function OptionsConfig:_boolean_to_string(bool)
  return bool and 'true' or 'false'
end