diff --git a/README.md b/README.md index 7386d5f..35a9b97 100644 --- a/README.md +++ b/README.md @@ -36,6 +36,7 @@ Presence = require("presence"):setup({ main_image = "neovim", -- Main image display (either "neovim" or "file") client_id = "793271441293967371", -- Use your own Discord application client id (not recommended) log_level = nil, -- Log messages at or above this level (one of the following: "debug", "info", "warn", "error") + debounce_timeout = 15, -- Number of seconds to debounce TextChanged events (or calls to `:lua Presence:update(, true)`) }) ``` @@ -49,14 +50,18 @@ let g:presence_neovim_image_text = "The One True Text Editor" let g:presence_main_image = "neovim" let g:presence_client_id = "793271441293967371" let g:presence_log_level +let g:presence_debounce_timeout = 15 ``` ## Contributing -Pull requests are very welcome! Here some open todo items: +Pull requests are very welcome, feel free to open an issue! Here some open todo items: +- [x] Manage workspace state across multiple nvim instances (e.g. tmux) +- [x] Set activity on other autocommands (`TextChanged`, `VimLeavePre`) +- [ ] Set idle activity (track using `CursorMoved`) - [ ] Use named pipes to support Windows - [ ] Expose file assets table as a configurable option +- [ ] Manage activity properly in buffers in windows and tabs - [ ] Retry connection after initial setup or a closed pipe (i.e. after quitting Discord app) - [ ] Attempt to connect to a range of pipes from `discord-ipc-0` to `discord-ipc-9` (see [note](https://github.com/discord/discord-rpc/blob/master/documentation/hard-mode.md#notes)) -- [ ] Set activity on other autocommands (`:h events`) Discord asset additions and changes are also welcome! Supported file types can be found in [file_assets.lua](lua/presence/file_assets.lua) and their assets can be found [in this folder](https://www.dropbox.com/sh/j8913f0gav3toeh/AADxjn0NuTprGFtv3Il1Pqz-a?dl=0). diff --git a/autoload/presence.vim b/autoload/presence.vim index a4fb83a..eb149ac 100644 --- a/autoload/presence.vim +++ b/autoload/presence.vim @@ -4,6 +4,8 @@ function presence#SetAutoCmds() autocmd! if exists("g:presence_auto_update") && g:presence_auto_update autocmd BufRead * lua package.loaded.presence:update() + autocmd TextChanged * lua package.loaded.presence:update(nil, true) + autocmd VimLeavePre * lua package.loaded.presence:unregister_self() endif augroup END endfunction diff --git a/lua/deps/serpent.lua b/lua/deps/serpent.lua new file mode 100644 index 0000000..a043713 --- /dev/null +++ b/lua/deps/serpent.lua @@ -0,0 +1,140 @@ +local n, v = "serpent", "0.302" -- (C) 2012-18 Paul Kulchenko; MIT License +local c, d = "Paul Kulchenko", "Lua serializer and pretty printer" +local snum = {[tostring(1/0)]='1/0 --[[math.huge]]',[tostring(-1/0)]='-1/0 --[[-math.huge]]',[tostring(0/0)]='0/0'} +local badtype = {thread = true, userdata = true, cdata = true} +local getmetatable = debug and debug.getmetatable or getmetatable +local pairs = function(t) return next, t end -- avoid using __pairs in Lua 5.2+ +local keyword, globals, G = {}, {}, (_G or _ENV) +for _,k in ipairs({'and', 'break', 'do', 'else', 'elseif', 'end', 'false', + 'for', 'function', 'goto', 'if', 'in', 'local', 'nil', 'not', 'or', 'repeat', + 'return', 'then', 'true', 'until', 'while'}) do keyword[k] = true end +for k,v in pairs(G) do globals[v] = k end -- build func to name mapping +for _,g in ipairs({'coroutine', 'debug', 'io', 'math', 'string', 'table', 'os'}) do + for k,v in pairs(type(G[g]) == 'table' and G[g] or {}) do globals[v] = g..'.'..k end end + +local function s(t, opts) + local name, indent, fatal, maxnum = opts.name, opts.indent, opts.fatal, opts.maxnum + local sparse, custom, huge = opts.sparse, opts.custom, not opts.nohuge + local space, maxl = (opts.compact and '' or ' '), (opts.maxlevel or math.huge) + local maxlen, metatostring = tonumber(opts.maxlength), opts.metatostring + local iname, comm = '_'..(name or ''), opts.comment and (tonumber(opts.comment) or math.huge) + local numformat = opts.numformat or "%.17g" + local seen, sref, syms, symn = {}, {'local '..iname..'={}'}, {}, 0 + local function gensym(val) return '_'..(tostring(tostring(val)):gsub("[^%w]",""):gsub("(%d%w+)", + -- tostring(val) is needed because __tostring may return a non-string value + function(s) if not syms[s] then symn = symn+1; syms[s] = symn end return tostring(syms[s]) end)) end + local function safestr(s) return type(s) == "number" and tostring(huge and snum[tostring(s)] or numformat:format(s)) + or type(s) ~= "string" and tostring(s) -- escape NEWLINE/010 and EOF/026 + or ("%q"):format(s):gsub("\010","n"):gsub("\026","\\026") end + local function comment(s,l) return comm and (l or 0) < comm and ' --[['..select(2, pcall(tostring, s))..']]' or '' end + local function globerr(s,l) return globals[s] and globals[s]..comment(s,l) or not fatal + and safestr(select(2, pcall(tostring, s))) or error("Can't serialize "..tostring(s)) end + local function safename(path, name) -- generates foo.bar, foo[3], or foo['b a r'] + local n = name == nil and '' or name + local plain = type(n) == "string" and n:match("^[%l%u_][%w_]*$") and not keyword[n] + local safe = plain and n or '['..safestr(n)..']' + return (path or '')..(plain and path and '.' or '')..safe, safe end + local alphanumsort = type(opts.sortkeys) == 'function' and opts.sortkeys or function(k, o, n) -- k=keys, o=originaltable, n=padding + local maxn, to = tonumber(n) or 12, {number = 'a', string = 'b'} + local function padnum(d) return ("%0"..tostring(maxn).."d"):format(tonumber(d)) end + table.sort(k, function(a,b) + -- sort numeric keys first: k[key] is not nil for numerical keys + return (k[a] ~= nil and 0 or to[type(a)] or 'z')..(tostring(a):gsub("%d+",padnum)) + < (k[b] ~= nil and 0 or to[type(b)] or 'z')..(tostring(b):gsub("%d+",padnum)) end) end + local function val2str(t, name, indent, insref, path, plainindex, level) + local ttype, level, mt = type(t), (level or 0), getmetatable(t) + local spath, sname = safename(path, name) + local tag = plainindex and + ((type(name) == "number") and '' or name..space..'='..space) or + (name ~= nil and sname..space..'='..space or '') + if seen[t] then -- already seen this element + sref[#sref+1] = spath..space..'='..space..seen[t] + return tag..'nil'..comment('ref', level) end + -- protect from those cases where __tostring may fail + if type(mt) == 'table' and metatostring ~= false then + local to, tr = pcall(function() return mt.__tostring(t) end) + local so, sr = pcall(function() return mt.__serialize(t) end) + if (to or so) then -- knows how to serialize itself + seen[t] = insref or spath + t = so and sr or tr + ttype = type(t) + end -- new value falls through to be serialized + end + if ttype == "table" then + if level >= maxl then return tag..'{}'..comment('maxlvl', level) end + seen[t] = insref or spath + if next(t) == nil then return tag..'{}'..comment(t, level) end -- table empty + if maxlen and maxlen < 0 then return tag..'{}'..comment('maxlen', level) end + local maxn, o, out = math.min(#t, maxnum or #t), {}, {} + for key = 1, maxn do o[key] = key end + if not maxnum or #o < maxnum then + local n = #o -- n = n + 1; o[n] is much faster than o[#o+1] on large tables + for key in pairs(t) do if o[key] ~= key then n = n + 1; o[n] = key end end end + if maxnum and #o > maxnum then o[maxnum+1] = nil end + if opts.sortkeys and #o > maxn then alphanumsort(o, t, opts.sortkeys) end + local sparse = sparse and #o > maxn -- disable sparsness if only numeric keys (shorter output) + for n, key in ipairs(o) do + local value, ktype, plainindex = t[key], type(key), n <= maxn and not sparse + if opts.valignore and opts.valignore[value] -- skip ignored values; do nothing + or opts.keyallow and not opts.keyallow[key] + or opts.keyignore and opts.keyignore[key] + or opts.valtypeignore and opts.valtypeignore[type(value)] -- skipping ignored value types + or sparse and value == nil then -- skipping nils; do nothing + elseif ktype == 'table' or ktype == 'function' or badtype[ktype] then + if not seen[key] and not globals[key] then + sref[#sref+1] = 'placeholder' + local sname = safename(iname, gensym(key)) -- iname is table for local variables + sref[#sref] = val2str(key,sname,indent,sname,iname,true) end + sref[#sref+1] = 'placeholder' + local path = seen[t]..'['..tostring(seen[key] or globals[key] or gensym(key))..']' + sref[#sref] = path..space..'='..space..tostring(seen[value] or val2str(value,nil,indent,path)) + else + out[#out+1] = val2str(value,key,indent,nil,seen[t],plainindex,level+1) + if maxlen then + maxlen = maxlen - #out[#out] + if maxlen < 0 then break end + end + end + end + local prefix = string.rep(indent or '', level) + local head = indent and '{\n'..prefix..indent or '{' + local body = table.concat(out, ','..(indent and '\n'..prefix..indent or space)) + local tail = indent and "\n"..prefix..'}' or '}' + return (custom and custom(tag,head,body,tail,level) or tag..head..body..tail)..comment(t, level) + elseif badtype[ttype] then + seen[t] = insref or spath + return tag..globerr(t, level) + elseif ttype == 'function' then + seen[t] = insref or spath + if opts.nocode then return tag.."function() --[[..skipped..]] end"..comment(t, level) end + local ok, res = pcall(string.dump, t) + local func = ok and "((loadstring or load)("..safestr(res)..",'@serialized'))"..comment(t, level) + return tag..(func or globerr(t, level)) + else return tag..safestr(t) end -- handle all other types + end + local sepr = indent and "\n" or ";"..space + local body = val2str(t, name, indent) -- this call also populates sref + local tail = #sref>1 and table.concat(sref, sepr)..sepr or '' + local warn = opts.comment and #sref>1 and space.."--[[incomplete output with shared/self-references skipped]]" or '' + return not name and body..warn or "do local "..body..sepr..tail.."return "..name..sepr.."end" +end + +local function deserialize(data, opts) + local env = (opts and opts.safe == false) and G + or setmetatable({}, { + __index = function(t,k) return t end, + __call = function(t,...) error("cannot call functions") end + }) + local f, res = (loadstring or load)('return '..data, nil, nil, env) + if not f then f, res = (loadstring or load)(data, nil, nil, env) end + if not f then return f, res end + if setfenv then setfenv(f, env) end + return pcall(f) +end + +local function merge(a, b) if b then for k,v in pairs(b) do a[k] = v end end; return a; end +return { _NAME = n, _COPYRIGHT = c, _DESCRIPTION = d, _VERSION = v, serialize = s, + load = deserialize, + dump = function(a, opts) return s(a, merge({name = '_', compact = true, sparse = true}, opts)) end, + line = function(a, opts) return s(a, merge({sortkeys = true, comment = true}, opts)) end, + block = function(a, opts) return s(a, merge({indent = ' ', sortkeys = true, comment = true}, opts)) end } diff --git a/lua/presence/discord.lua b/lua/presence/discord.lua index 97a7206..77e190b 100644 --- a/lua/presence/discord.lua +++ b/lua/presence/discord.lua @@ -149,13 +149,19 @@ function Discord:set_activity(activity, on_response) self:call(self.opcodes.frame, payload, on_response) end -function Discord.generate_uuid() +function Discord.generate_uuid(seed) + local index = 0 local template ="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx" local uuid = template:gsub("[xy]", function(char) + -- Increment an index to seed per char + index = index + 1 + math.randomseed((seed or os.clock()) / index) + local n = char == "x" and math.random(0, 0xf) or math.random(8, 0xb) + return string.format("%x", n) end) diff --git a/lua/presence/init.lua b/lua/presence/init.lua index 7eb4639..c2a0087 100644 --- a/lua/presence/init.lua +++ b/lua/presence/init.lua @@ -1,7 +1,63 @@ +-------------------------------------------------- +-- ____ -- +-- / __ \________ ________ ____ ________ -- +-- / /_/ / ___/ _ \/ ___/ _ \/ __ \/ ___/ _ \ -- +-- / ____/ / / __(__ ) __/ / / / /__/ __/ -- +-- /_/ /_/ \___/____/\___/_/ /_/\___/\___/ -- +-- -- +-- Discord Rich Presence plugin for Neovim. -- +-------------------------------------------------- +-- Nvim peer-to-peer runtime state shape example: +-- +-- Presence = { +-- id = "ee1fc18f-2c81-4b88-b92e-cb801fbe8d85", +-- workspace = "/Users/user/Code/presence.nvim", +-- socket = "/var/folders/mm/8qfxwcdn29s8d_rzmj7bqxb40000gn/T/nvim9pEtTD/0", +-- +-- -- Last activity set by current client or any peer instance +-- last_activity = { +-- file = "/Users/user/Code/presence.nvim/README.md", +-- workspace = "/Users/user/Code/presence.nvim", +-- }, +-- +-- -- Other remote Neovim instances (peers) +-- peers = { +-- ["dd5eeafe-8d0d-44d7-9850-45d3884be1a0"] = { +-- workspace = "/Users/user/Code/presence.nvim", +-- socket = "/var/folders/mm/8qfxwcdn29s8d_rzmj7bqxb40000gn/T/nvim9pEtTD/0", +-- }, +-- ["346750e6-c416-44ff-98f3-eb44ea2ef15d"] = { +-- workspace = "/Users/user/Code/presence.nvim", +-- socket = "/var/folders/mm/8qfxwcdn29s8d_rzmj7bqxb40000gn/T/nvim09n664/0", +-- } +-- }, +-- +-- -- Workspace states across all peers +-- workspaces = { +-- ["/Users/user/Code/dotfiles"] = { +-- started_at = 1616033505, +-- updated_at = 1616033505 +-- }, +-- ["/Users/user/Code/presence.nvim"] = { +-- started_at = 1616033442, +-- updated_at = 1616033523 +-- }, +-- }, +-- +-- ... other methods and member variables +-- } local Presence = {} +Presence.is_authorized = false +Presence.is_connected = false +Presence.last_activity = {} +Presence.peers = {} +Presence.socket = vim.v.servername +Presence.workspace = nil +Presence.workspaces = {} local log = require("lib.log") local msgpack = require("deps.msgpack") +local serpent = require("deps.serpent") local Discord = require("presence.discord") local file_assets = require("presence.file_assets") @@ -12,6 +68,7 @@ function Presence:setup(options) -- Initialize logger self:set_option("log_level", nil, false) self.log = log:init({ level = options.log_level }) + self.log:debug("Setting up plugin...") -- Use the default or user-defined client id if provided if options.client_id then @@ -24,8 +81,19 @@ function Presence:setup(options) self:set_option("workspace_text", "Working on %s") self:set_option("neovim_image_text", "The One True Text Editor") self:set_option("client_id", "793271441293967371") + self:set_option("debounce_timeout", 15) - self.log:debug("Setting up plugin...") + -- Initialize discord RPC client + self.discord = Discord:init({ + logger = self.log, + client_id = options.client_id, + ipc_path = self.get_ipc_path(), + }) + + -- Seed instance id using unique socket address + local seed_nums = {} + self.socket:gsub(".", function(c) table.insert(seed_nums, c:byte()) end) + self.id = self.discord.generate_uuid(tonumber(table.concat(seed_nums)) / os.clock()) -- Ensure auto-update config is reflected in its global var setting vim.api.nvim_set_var("presence_auto_update", options.auto_update) @@ -33,21 +101,14 @@ function Presence:setup(options) -- Set autocommands vim.fn["presence#SetAutoCmds"]() - -- Internal state - self.is_connected = false - self.is_authorized = false - - self.discord = Discord:init({ - logger = self.log, - client_id = options.client_id, - ipc_path = self.get_ipc_path(), - }) - self.log:info("Completed plugin setup") -- Set global variable to indicate plugin has been set up vim.api.nvim_set_var("presence_has_setup", 1) + -- Register self to any remote Neovim instances + self:register_self() + return self end @@ -102,21 +163,6 @@ function Presence:cancel() end) end --- Send command to cancel the presence for all other remote Neovim instances -function Presence:cancel_all_remote_instances() - self:get_nvim_socket_addrs(function(sockets) - for i = 1, #sockets do - local nvim_socket = sockets[i] - - -- Skip if the nvim socket is the current instance - if nvim_socket ~= vim.v.servername then - local command = "lua package.loaded.presence:cancel()" - self:call_remote_nvim_instance(nvim_socket, command) - end - end - end) -end - -- Call a command on a remote Neovim instance at the provided IPC path function Presence:call_remote_nvim_instance(ipc_path, command) local remote_nvim_instance = vim.loop.new_pipe(true) @@ -128,13 +174,32 @@ function Presence:call_remote_nvim_instance(ipc_path, command) remote_nvim_instance:write(packed, function() self.log:debug(string.format("Wrote to remote nvim instance: %s", ipc_path)) - - remote_nvim_instance:shutdown() - remote_nvim_instance:close() end) end) end +-- Call a Presence method on a remote instance with a given list of arguments +function Presence:call_remote_method(socket, name, args) + local command_fmt = "lua package.loaded.presence:%s(%s)" + + -- Stringify the list of args + for i = 1, #args do + local arg = args[i] + if type(arg) == "string" then + args[i] = string.format([["%s"]], arg) + elseif type(arg) == "boolean" then + args[i] = string.format([["%s"]], tostring(arg)) + elseif type(arg) == "table" then + -- Wrap serpent dump with function invocation to pass in the table value + args[i] = string.format("(function() %s end)()", serpent.dump(arg)) + end + end + + local arglist = table.concat(args or {}, ",") + local command = string.format(command_fmt, name, arglist) + self:call_remote_nvim_instance(socket, command) +end + function Presence:connect(on_done) self.log:debug("Connecting to Discord...") @@ -224,7 +289,7 @@ function Presence:get_project_name(file_path) return nil end - return self.get_filename(project_path) + return self.get_filename(project_path), project_path end -- Get the name of the parent directory for the given path @@ -245,7 +310,13 @@ end -- Get all active local nvim unix domain socket addresses function Presence:get_nvim_socket_addrs(on_done) -- TODO: Find a better way to get paths of remote Neovim sockets lol - local cmd = [[netstat -u | grep --color=never "nvim.*/0" | awk -F "[ :]+" '{print $9}' | uniq]] + local cmd = table.concat({ + "netstat -u", + [[grep --color=never "nvim.*/0"]], + [[awk -F "[ :]+" '{print $9}']], + "sort", + "uniq", + }, "|") local sockets = {} local function handle_data(_, data) @@ -253,7 +324,7 @@ function Presence:get_nvim_socket_addrs(on_done) for i = 1, #data do local socket = data[i] - if socket ~= "" and socket ~= vim.v.servername then + if socket ~= "" and socket ~= self.socket then table.insert(sockets, socket) end end @@ -303,11 +374,15 @@ function Presence.discord_event(on_ready) end -- Update Rich Presence for the provided vim buffer -function Presence:update_for_buffer(buffer) - self.log:debug(string.format("Setting activity for %s...", buffer)) +function Presence:update_for_buffer(buffer, should_debounce) + if should_debounce and self.last_activity.file == buffer then + self.log:debug(string.format("Activity already set for %s, skipping...", buffer)) + return + end - -- Send command to cancel presence for all remote Neovim instances - self:cancel_all_remote_instances() + local activity_set_at = os.time() + + self.log:debug(string.format("Setting activity for %s...", buffer)) -- Parse vim buffer local filename = self.get_filename(buffer) @@ -326,9 +401,6 @@ function Presence:update_for_buffer(buffer) local file_text = description or name local neovim_image_text = self.options.neovim_image_text - -- TODO: Update timestamp to be workspace-specific - local started_at = os.time() - local use_file_as_main_image = self.options.main_image == "file" local assets = { large_image = use_file_as_main_image and asset_key or "neovim", @@ -346,12 +418,12 @@ function Presence:update_for_buffer(buffer) state = editing_text, assets = assets, timestamps = { - start = started_at + start = activity_set_at, }, } local workspace_text = self.options.workspace_text - local project_name = self:get_project_name(parent_dirpath) + local project_name, project_path = self:get_project_name(parent_dirpath) -- Include project details if available if project_name then @@ -360,9 +432,35 @@ function Presence:update_for_buffer(buffer) activity.details = type(workspace_text) == "function" and workspace_text(project_name, buffer) or string.format(workspace_text, project_name) + + self.workspace = project_path + self.last_activity = { + file = buffer, + set_at = activity_set_at, + workspace = project_path, + } + + if self.workspaces[project_path] then + self.workspaces[project_path].updated_at = activity_set_at + activity.timestamps = { + start = self.workspaces[project_path].started_at, + } + else + self.workspaces[project_path] = { + started_at = activity_set_at, + updated_at = activity_set_at, + } + end else self.log:debug("No project detected") + self.workspace = nil + self.last_activity = { + file = buffer, + set_at = activity_set_at, + workspace = nil, + } + -- When no project is detected, set custom workspace text if: -- * The custom function returns custom workspace text -- * The configured workspace text does not contain a directive @@ -376,6 +474,9 @@ function Presence:update_for_buffer(buffer) end end + -- Sync activity to all peers + self:sync_self_activity() + self.discord:set_activity(activity, function(err) if err then self.log:error("Failed to set activity in Discord: "..err) @@ -387,16 +488,205 @@ function Presence:update_for_buffer(buffer) end -- Update Rich Presence for the current or provided vim buffer for an authorized connection -Presence.update = Presence.discord_event(function(self, buffer) +Presence.update = Presence.discord_event(function(self, buffer, should_debounce) + -- Default update to not debounce by default + if should_debounce == nil then should_debounce = false end + + -- Debounce Rich Presence updates (default to 15 seconds): + -- https://discord.com/developers/docs/rich-presence/how-to#updating-presence + local last_updated_at = self.last_activity.set_at + local debounce_timeout = self.options.debounce_timeout + local should_skip = should_debounce and debounce_timeout and + last_updated_at and os.time() - last_updated_at <= debounce_timeout + + if should_skip then + local message_fmt = "Last activity sent was within %d seconds ago, skipping..." + self.log:debug(string.format(message_fmt, debounce_timeout)) + return + end + if buffer then - self:update_for_buffer(buffer) + self:update_for_buffer(buffer, should_debounce) else self.get_current_buffer(function(current_buffer) - self:update_for_buffer(current_buffer) + self:update_for_buffer(current_buffer, should_debounce) end) end end) +-- Register some remote peer +function Presence:register_peer(id, socket) + self.log:debug(string.format("Registering peer %s...", id)) + + self.peers[id] = { + socket = socket, + workspace = nil, + } + + self.log:info(string.format("Registered peer %s", id)) +end + +-- Unregister some remote peer +function Presence:unregister_peer(id, peer) + self.log:debug(string.format("Unregistering peer %s... %s", id, vim.inspect(peer))) + + -- Remove workspace if no other peers share the same workspace + -- Initialize to remove if the workspace differs from the local workspace, check peers below + local should_remove_workspace = peer.workspace ~= self.workspace + + local peers = {} + for peer_id, peer_data in pairs(self.peers) do + -- Omit peer from peers list + if peer_id ~= id then + peers[peer_id] = peer_data + + -- Should not remove workspace if another peer shares the workspace + if should_remove_workspace and peer.workspace == peer_data.workspace then + should_remove_workspace = false + end + end + end + + self.peers = peers + + -- Update workspaces if necessary + local workspaces = {} + if should_remove_workspace then + self.log:debug(string.format("Should remove workspace %s", peer.workspace)) + for workspace, data in pairs(self.workspaces) do + if workspace ~= peer.workspace then + workspaces[workspace] = data + end + end + + self.workspaces = workspaces + end + + self.log:info(string.format("Unregistered peer %s", id)) +end + +-- Unregister some remote peer and set activity +function Presence:unregister_peer_and_set_activity(id, peer) + self:unregister_peer(id, peer) + self:update() +end + +-- Register a remote peer and sync its data +function Presence:register_and_sync_peer(id, socket) + self:register_peer(id, socket) + + self.log:debug("Syncing data with newly registered peer...") + + -- Initialize the remote peer's list including self + local peers = { + [self.id] = { + socket = self.socket, + workspace = self.workspace, + } + } + for peer_id, peer in pairs(self.peers) do + if peer_id ~= id then + peers[peer_id] = peer + end + end + + self:call_remote_method(socket, "sync_self", {{ + last_activity = self.last_activity, + peers = peers, + workspaces = self.workspaces, + }}) +end + +-- Register self to any remote Neovim instances +-- Simply emits to all nvim socket addresses as we have not yet been synced with peer list +function Presence:register_self() + self:get_nvim_socket_addrs(function(sockets) + if #sockets == 0 then + self.log:debug("No other remote nvim instances") + return + end + + self.log:debug(string.format("Registering as a new peer to %d instance(s)...", #sockets)) + + -- Register and sync state with one of the sockets + self:call_remote_method(sockets[1], "register_and_sync_peer", { self.id, self.socket }) + + if #sockets == 1 then + return + end + + for i = 2, #sockets do + self:call_remote_method(sockets[i], "register_peer", { self.id, self.socket }) + end + end) +end + +-- Unregister self to all peers +function Presence:unregister_self() + local self_as_peer = { + socket = self.socket, + workspace = self.workspace, + } + + local i = 1 + for id, peer in pairs(self.peers) do + if self.options.auto_update and i == 1 then + self.log:debug(string.format("Unregistering self and setting activity for peer %s...", id)) + self:call_remote_method(peer.socket, "unregister_peer_and_set_activity", { self.id, self_as_peer }) + else + self.log:debug(string.format("Unregistering self to peer %s...", id)) + self:call_remote_method(peer.socket, "unregister_peer", { self.id, self_as_peer }) + end + i = i + 1 + end +end + +-- Sync self with data from a remote peer +function Presence:sync_self(data) + self.log:debug(string.format("Syncing data from remote peer...", vim.inspect(data))) + + for key, value in pairs(data) do + self[key] = value + end + + self.log:info("Synced runtime data from remote peer") +end + +-- Sync activity set by self to all peers +function Presence:sync_self_activity() + local self_as_peer = { + socket = self.socket, + workspace = self.workspace, + } + + for id, peer in pairs(self.peers) do + self.log:debug(string.format("Syncing activity to peer %s...", id)) + + local peers = { [self.id] = self_as_peer } + for peer_id, peer_data in pairs(self.peers) do + if peer_id ~= id then + peers[peer_id] = { + socket = peer_data.socket, + workspace = peer_data.workspace, + } + end + end + + self:call_remote_method(peer.socket, "sync_peer_activity", {{ + last_activity = self.last_activity, + peers = peers, + workspaces = self.workspaces, + }}) + end +end + +-- Sync activity set by peer +function Presence:sync_peer_activity(data) + self.log:debug(string.format("Syncing peer activity %s...", vim.inspect(data))) + self:cancel() + self:sync_self(data) +end + function Presence:stop() self.log:debug("Disconnecting from Discord...") self.discord:disconnect(function()