-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProfiles.lua
More file actions
398 lines (354 loc) · 14.2 KB
/
Copy pathProfiles.lua
File metadata and controls
398 lines (354 loc) · 14.2 KB
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
-- WickCore
-- Profiles.lua — saved variables with profiles, keyed switching, import/export.
--
-- Shape of a product's SavedVariables:
-- { profiles = { Default = {...}, ... }, profileKeys = { ["Name - Realm"] = "Default" },
-- global = {...}, char = { ["Name - Realm"] = {...} } }
--
-- A.db.profile / A.db.global / A.db.char are live tables with defaults applied.
local ADDON = ...
local Core = LibStub("WickCore-1.0", true)
if not Core or Core._sourceAddon ~= ADDON then return end
local Profiles = {}
Core.Profiles = Profiles
local DBProto = {}
DBProto.__index = DBProto
-- ============================================================
-- Keys
-- ============================================================
-- The client can load addons before it has the player's name, and then
-- UnitName answers "Unknown". A key built from that files every character
-- that starts that way under one entry, so while the name is missing the
-- key is held as provisional and nothing is saved under it; at login,
-- with the name known, the character gets its own.
function Profiles:PlayerName()
local name = UnitName and UnitName("player")
if name == nil or name == "" or name == "Unknown" or name == rawget(_G, "UNKNOWNOBJECT") then return nil end
return name
end
function Profiles:NameKnown() return self:PlayerName() ~= nil end
function Profiles:CharKey()
local realm = GetRealmName and GetRealmName() or "Realm"
return (self:PlayerName() or "Unknown") .. " - " .. realm
end
-- Entries an earlier build saved under the unnamed key belong to no one.
local function dropUnnamed(sv)
for k in pairs(sv.profileKeys) do if k:find("^Unknown %- ") then sv.profileKeys[k] = nil end end
for k in pairs(sv.char) do if k:find("^Unknown %- ") then sv.char[k] = nil end end
end
function Profiles:ClassKey()
local _, token = UnitClass("player")
return token or "UNKNOWN"
end
-- Spec on a trait client is the active talent config; elsewhere a class is
-- as fine as it gets.
function Profiles:SpecKey()
local CT = rawget(_G, "C_ClassTalents")
if CT and CT.GetActiveConfigID then
local ok, id = pcall(CT.GetActiveConfigID)
if ok and id then return self:ClassKey() .. ":" .. tostring(id) end
end
local SI = rawget(_G, "C_SpecializationInfo")
if SI and SI.GetSpecialization then
local ok, spec = pcall(SI.GetSpecialization)
if ok and spec then return self:ClassKey() .. ":" .. tostring(spec) end
end
return self:ClassKey()
end
function Profiles:ModeKey()
local mode = Core.Client:GameMode()
local hc = Core.Client:IsHardcore() and ":hc" or ""
return tostring(mode or "default") .. hc
end
-- ============================================================
-- Init
-- ============================================================
function Profiles:Init(addon, savedVar, defaults)
defaults = defaults or {}
local sv = _G[savedVar]
local handedOver = type(sv) == "table"
if type(sv) ~= "table" then sv = {} end
-- Always publish it. Products read their saved variable by name, and a
-- table restored from the store has to be reachable that way too.
_G[savedVar] = sv
sv.profiles = sv.profiles or {}
sv.profileKeys = sv.profileKeys or {}
sv.global = sv.global or {}
sv.char = sv.char or {}
sv.keyMode = sv.keyMode or "char"
local db = setmetatable({
addon = addon,
savedVar = savedVar,
sv = sv,
defaults = defaults,
callbacks = {},
}, DBProto)
db.fromStore = not handedOver
-- Only the client counts as having handed the table over. WicksProfile
-- assigns globals at file scope from a bake, and the store must still
-- be allowed to put something newer on top of that.
local bake = rawget(_G, "WicksProfile")
local baked = false
if handedOver and type(bake) == "table" and type(bake.restored) == "table" then
for _, name in ipairs(bake.restored) do if name == savedVar then baked = true end end
end
db.handedOver = handedOver and not baked
db.baked = baked
db.charKey = self:CharKey()
db.provisional = not self:NameKnown()
if not db.provisional then dropUnnamed(sv) end
db.global = Core.applyDefaults(sv.global, defaults.global or {})
db:_BindChar()
db:_Select(db:_KeyFor(sv.keyMode))
return db
end
-- The client assigns saved variables around ADDON_LOADED. If our binding
-- ever happens before that, the client's assignment replaces the global
-- and leaves us holding an abandoned table: every read sees defaults and
-- nothing is ever written back, while the real values sit on disk. Check
-- at login and adopt the live table when that has happened.
function DBProto:Rebind()
self:Rekey()
local live = _G[self.savedVar]
if type(live) ~= "table" or live == self.sv then return false end
return self:RebindTo(live)
end
-- Adopt a table from anywhere: the client's late assignment, or the
-- macro store handing settings back. The global is pointed at it so the
-- client serializes this table at logout, not the abandoned one.
function DBProto:RebindTo(live)
if type(live) ~= "table" then return false end
_G[self.savedVar] = live
live.profiles = live.profiles or {}
live.profileKeys = live.profileKeys or {}
live.global = live.global or {}
live.char = live.char or {}
live.keyMode = live.keyMode or self.sv.keyMode or "char"
self.sv = live
self.global = Core.applyDefaults(live.global, self.defaults.global or {})
self:_BindChar()
self:_Select(self:_KeyFor(live.keyMode))
self:_Fire("OnProfileChanged", self.profileName, self.profileName)
return true
end
-- This character's own table, or a loose one while its name is unknown.
function DBProto:_BindChar()
local sv = self.sv
if self.provisional then
self.char = Core.applyDefaults({}, self.defaults.char or {})
else
-- New to this addon: no table of its own until now. Worked out once
-- for each saved table bound (a late client table is looked at anew).
if self._charFor ~= sv then
self._charFor = sv
self.charIsNew = sv.char[self.charKey] == nil
end
sv.char[self.charKey] = Core.applyDefaults(sv.char[self.charKey] or {}, self.defaults.char or {})
self.char = sv.char[self.charKey]
end
end
-- The name has arrived: key this character by it and pick its profile.
-- Before the addon is enabled nothing has been built from the profile yet,
-- so the switch is quiet; after, it is announced like any other.
function DBProto:Rekey()
if not self.provisional or not Profiles:NameKnown() then return false end
self.provisional = nil
self.charKey = Profiles:CharKey()
dropUnnamed(self.sv)
self:_BindChar()
local was = self.profileName
self:_Select(self:_KeyFor(self.sv.keyMode))
if self.addon and self.addon.enabled and was ~= self.profileName then
self:_Fire("OnProfileChanged", self.profileName, was)
end
return true
end
-- The lookup key for the current keying mode.
function DBProto:_KeyFor(mode)
-- One profile for every character on the account.
if mode == "account" then return "account" end
if mode == "spec" then return "spec:" .. Profiles:SpecKey() end
if mode == "mode" then return "mode:" .. Profiles:ModeKey() end
if mode == "class" then return "class:" .. Profiles:ClassKey() end
return self.charKey
end
function DBProto:_Select(key)
-- A provisional key reads nothing and saves nothing.
if self.provisional and key == self.charKey then
self.key = key
self.profileName = self.profileName or "Default"
self.sv.profiles[self.profileName] = Core.applyDefaults(self.sv.profiles[self.profileName] or {}, self.defaults.profile or {})
self.profile = self.sv.profiles[self.profileName]
return
end
local name = self.sv.profileKeys[key] or "Default"
self.sv.profileKeys[key] = name
self.key = key
self.profileName = name
self.sv.profiles[name] = Core.applyDefaults(self.sv.profiles[name] or {}, self.defaults.profile or {})
self.profile = self.sv.profiles[name]
end
-- ============================================================
-- Profile management
-- ============================================================
function DBProto:GetProfiles()
local names = {}
for name in pairs(self.sv.profiles) do names[#names + 1] = name end
table.sort(names)
return names
end
function DBProto:GetCurrentProfile() return self.profileName end
function DBProto:SetProfile(name)
if not name or name == "" then return end
local old = self.profileName
self.sv.profileKeys[self.key] = name
self:_Select(self.key)
if old ~= name then self:_Fire("OnProfileChanged", name, old) end
end
function DBProto:CopyProfile(from)
local src = self.sv.profiles[from]
if not src or from == self.profileName then return false end
Core.wipe(self.profile)
for k, v in pairs(Core.copy(src)) do self.profile[k] = v end
Core.applyDefaults(self.profile, self.defaults.profile or {})
self:_Fire("OnProfileChanged", self.profileName, self.profileName)
return true
end
function DBProto:ResetProfile()
Core.wipe(self.profile)
Core.applyDefaults(self.profile, self.defaults.profile or {})
self:_Fire("OnProfileReset", self.profileName)
end
function DBProto:DeleteProfile(name)
if name == self.profileName or name == "Default" then return false end
self.sv.profiles[name] = nil
for key, pname in pairs(self.sv.profileKeys) do
if pname == name then self.sv.profileKeys[key] = "Default" end
end
return true
end
-- "char" (default), "spec", "class" or "mode" (game mode + hardcore).
function DBProto:SetKeyMode(mode)
-- The first time the account shares one profile, it is the one this
-- character is on, rather than a jump back to Default.
if mode == "account" and not self.sv.profileKeys.account then
self.sv.profileKeys.account = self.profileName
end
self.sv.keyMode = mode
local old = self.profileName
self:_Select(self:_KeyFor(mode))
if old ~= self.profileName then self:_Fire("OnProfileChanged", self.profileName, old) end
end
function DBProto:GetKeyMode() return self.sv.keyMode end
function DBProto:On(event, fn)
self.callbacks[event] = self.callbacks[event] or {}
table.insert(self.callbacks[event], fn)
end
function DBProto:_Fire(event, ...)
local hs = self.callbacks[event]
if not hs then return end
for i = 1, #hs do pcall(hs[i], ...) end
end
-- ============================================================
-- Serializer
-- ============================================================
-- Length-prefixed, so any byte content survives. Encoded once more for chat
-- safety: "|" and "~" are escaped, everything else passes through.
--
-- S<len>:<bytes> string
-- N<repr>; number
-- T / F booleans
-- { k v k v } table
local function serialize(v, out)
local t = type(v)
if t == "string" then
out[#out + 1] = "S" .. #v .. ":" .. v
elseif t == "number" then
out[#out + 1] = "N" .. string.format("%.17g", v) .. ";"
elseif t == "boolean" then
out[#out + 1] = v and "T" or "F"
elseif t == "table" then
out[#out + 1] = "{"
for k, val in pairs(v) do
local kt, vt = type(k), type(val)
if (kt == "string" or kt == "number") and (vt ~= "function" and vt ~= "userdata") then
serialize(k, out)
serialize(val, out)
end
end
out[#out + 1] = "}"
else
out[#out + 1] = "F"
end
end
local function deserialize(s, pos)
local c = s:sub(pos, pos)
if c == "S" then
local len, colon = s:match("^(%d+)():", pos + 1)
if not len then error("bad string at " .. pos) end
local start = colon + 1
len = tonumber(len)
return s:sub(start, start + len - 1), start + len
elseif c == "N" then
local num, after = s:match("^([^;]+);()", pos + 1)
if not num then error("bad number at " .. pos) end
return tonumber(num), after
elseif c == "T" then return true, pos + 1
elseif c == "F" then return false, pos + 1
elseif c == "{" then
local t = {}
pos = pos + 1
while s:sub(pos, pos) ~= "}" do
if pos > #s then error("unterminated table") end
local k, v
k, pos = deserialize(s, pos)
v, pos = deserialize(s, pos)
t[k] = v
end
return t, pos + 1
end
error("unexpected byte at " .. pos)
end
function Core.Serialize(v)
local out = {}
serialize(v, out)
return table.concat(out)
end
function Core.Deserialize(s)
local ok, v = pcall(function() return (deserialize(s, 1)) end)
if ok then return v end
return nil, v
end
-- Single pass each way. A two-pass gsub would turn a literal "~p" in the
-- payload into "|" on the way back.
local ENC = { ["~"] = "~~", ["|"] = "~p" }
local DEC = { ["~"] = "~", ["p"] = "|" }
local function encode(s)
return (s:gsub("[~|]", ENC))
end
local function decode(s)
return (s:gsub("~(.)", DEC))
end
local PREFIX = "WICK1:"
-- Export the current profile as a paste-able string.
function DBProto:Export(extra)
local payload = { addon = self.addon.name, version = self.addon.version, profile = self.profile, extra = extra }
return PREFIX .. encode(Core.Serialize(payload))
end
-- Import a string into the current profile. Returns true, payload or false, reason.
function DBProto:Import(str, allowOtherAddon)
str = Core.trim(str or "")
if str:sub(1, #PREFIX) ~= PREFIX then return false, "not a Wick export string" end
local payload, err = Core.Deserialize(decode(str:sub(#PREFIX + 1)))
if type(payload) ~= "table" or type(payload.profile) ~= "table" then
return false, err or "malformed"
end
if payload.addon ~= self.addon.name and not allowOtherAddon then
return false, "string is for " .. tostring(payload.addon)
end
Core.wipe(self.profile)
for k, v in pairs(payload.profile) do self.profile[k] = v end
Core.applyDefaults(self.profile, self.defaults.profile or {})
self:_Fire("OnProfileChanged", self.profileName, self.profileName)
return true, payload
end