cord-nvim 2.0.0-beta.28

🚀 The most extensible Discord Rich Presence plugin for Neovim, powered by Rust.
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
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
local async = require 'cord.core.async'
local activities = require 'cord.plugin.activity'
local ws_utils = require 'cord.plugin.fs.workspace'
local config_utils = require 'cord.plugin.config.util'
local hooks = require 'cord.plugin.activity.hooks'
local config = require 'cord.plugin.config'

local uv = vim.loop or vim.uv

---@class ActivityManager
---@field config CordConfig Configuration options
---@field tx table Event transmitter instance
---@field is_focused boolean Whether Neovim is focused
---@field is_paused boolean Whether activity updates are paused
---@field is_force_idle boolean Whether idle state is forced
---@field events_enabled boolean Whether events are enabled
---@field last_activity Activity Last activity state
---@field opts CordOpts Latest options passed to activity updates
---@field last_opts? CordOpts Previous options passed to activity updates, used to detect changes
---@field workspace_dir string Current workspace directory
---@field repo_url string|nil Current Git repository URL
---@field workspace_cache table Cache of workspace directories, their names and repositories
local ActivityManager = {}
local mt = { __index = ActivityManager }

---@class Activity
---@field type? string One of 'playing', 'listening', 'watching', 'competing'
---@field details? string Detailed information about what the user is doing
---@field state? string Secondary information about what the user is doing
---@field timestamps? ActivityTimestamps Contains `start` and `end` timestamps for the activity
---@field assets? ActivityAssets Defines images and tooltips, including `large_image`, `large_text`, `small_image`, and `small_text`
---@field buttons? CordButtonConfig[] Array of objects, each with `label` and `url`, defining interactive buttons in the presence
---@field is_idle? boolean Whether the activity should be considered as idle

---@class ActivityTimestamps
---@field start? integer Start timestamp in milliseconds
---@field end? integer End timestamp in milliseconds

---@class ActivityAssets
---@field large_image? string Large image ID or URL
---@field large_text? string Large image text
---@field small_image? string Small image ID or URL
---@field small_text? string Small image text

---@class CordOpts
---@field manager ActivityManager Reference to the ActivityManager instance
---@field name? string Name associated with the current mapping
---@field tooltip? string Tooltip associated with the current mapping
---@field filename string Current buffer's filename
---@field filetype string Current buffer's filetype
---@field is_read_only boolean Whether the current buffer is read-only
---@field cursor_line integer Current cursor line
---@field cursor_char integer Current cursor character
---@field timestamp number Timestamp passed to the Rich Presence in milliseconds
---@field workspace? string Current workspace name
---@field workspace_name? string Current workspace name (DEPRECATED)
---@field workspace_dir? string Current workspace directory
---@field repo_url? string Current Git repository URL, if any
---@field is_focused boolean Whether Neovim is focused
---@field is_idle boolean Whether the session is idle
---@field buttons? CordButtonConfig[] Buttons configuration
---@field type string Which category the asset belongs to, e.g. 'language' or 'docs'
---@field icon? string Asset icon URL or name, if any
---@field text? string Asset text, if any

---Create a new ActivityManager instance
---@param opts {config: CordConfig, tx: table} Configuration and transmitter options
ActivityManager.new = async.wrap(function(opts)
  local self = setmetatable({
    tx = opts.tx,
    is_focused = true,
    is_paused = false,
    is_force_idle = false,
    events_enabled = true,
    workspace_cache = {},
  }, mt)

  if config.hooks then
    for event, hook in pairs(config.hooks) do
      if type(hook) == 'function' then
        hooks.register(event, hook, 200)
      elseif type(hook) == 'table' then
        hooks.register(event, hook[1] or hook.fun, hook.priority or 200)
      end
    end
  end

  local rawdir = vim.fn.expand '%:p:h'
  local dir = ws_utils.find(rawdir):get() or vim.fn.getcwd()
  self.workspace_dir = dir

  local cache = {
    dir = dir,
    name = vim.fn.fnamemodify(dir, ':t'),
  }

  local repo_url = ws_utils.find_git_repository(dir):get()
  if repo_url then
    self.repo_url = repo_url
    cache.repo_url = repo_url
  end

  self.workspace_cache[rawdir] = cache

  local err = require('cord.api.plugin').init()
  if err then error(err, 0) end

  return self
end)

---Run the activity manager
---@return nil
function ActivityManager:run()
  self.workspace = vim.fn.fnamemodify(self.workspace_dir, ':t')
  self.last_updated = uv.now()

  hooks.run('ready', self)

  self:queue_update(true)
  if config.advanced.plugin.autocmds then self.setup_autocmds() end

  if config.idle.enabled then
    self.idle_timer = uv.new_timer()
    self.idle_timer:start(
      0,
      config.idle.timeout,
      vim.schedule_wrap(function() self:check_idle() end)
    )
  end
end

---Clean up the activity manager
---@return nil
function ActivityManager:cleanup()
  self:clear_autocmds()
  if self.idle_timer then
    self.idle_timer:stop()
    if not self.idle_timer:is_closing() then self.idle_timer:close() end
  end
end

---Check if an activity update is needed
---@return boolean Whether an update is needed
function ActivityManager:should_update()
  local should_update = not self.last_opts
    or self.opts.filename ~= self.last_opts.filename
    or self.opts.filetype ~= self.last_opts.filetype
    or self.opts.is_read_only ~= self.last_opts.is_read_only
    or self.opts.cursor_line ~= self.last_opts.cursor_line
    or self.opts.cursor_char ~= self.last_opts.cursor_char
    or self.opts.is_focused ~= self.last_opts.is_focused

  return should_update
end

---Queue an activity update
---@param force_update? boolean Whether to force the update regardless of conditions
function ActivityManager:queue_update(force_update)
  if not self.events_enabled then return end

  self.opts = self:build_opts()
  if not self.is_force_idle and (force_update or self:should_update()) then
    if self.is_idle then hooks.run('idle_leave', self.opts) end
    self:update_activity()
  end
end

---Check if the activity should be updated to idle
---@return nil
function ActivityManager:check_idle()
  if not self.events_enabled then return end
  if not config.idle.enabled and not self.is_force_idle then return end
  if self.is_idle then return end

  local time_elapsed = uv.now() - self.last_updated
  if
    self.is_force_idle
    or (time_elapsed >= config.idle.timeout and (config.idle.ignore_focus or not self.is_focused))
  then
    self:update_idle_activity()
  else
    local time_remaining = config.idle.timeout - time_elapsed
    self.idle_timer:stop()
    self.idle_timer:start(
      time_remaining,
      0,
      vim.schedule_wrap(function()
        self.idle_timer:start(
          0,
          config.idle.timeout,
          vim.schedule_wrap(function() self:check_idle() end)
        )
      end)
    )
  end
end

---Update the activity to idle
---@return nil
function ActivityManager:update_idle_activity()
  if not self.opts then self.opts = self:build_opts() end
  self.opts.is_idle = true
  self.is_idle = true
  self.last_updated = uv.now()

  if config.idle.show_status then
    local buttons = config_utils.get_buttons(self.opts)
    self.opts.buttons = buttons
    if config.timestamp.enabled and config.timestamp.reset_on_idle then
      self.opts.timestamp = os.time()
    end

    local activity = activities.build_idle_activity(self.opts)

    hooks.run('post_activity', self.opts, activity)

    if self.should_skip_update then
      self.should_skip_update = false
      return
    end

    self.tx:update_activity(activity)
    hooks.run('idle_enter', self.opts)
  else
    hooks.run('post_activity', self.opts)

    if self.should_skip_update then
      self.should_skip_update = false
      return
    end

    self.tx:clear_activity()
    hooks.run('idle_enter', self.opts)
  end
end

---Update the activity
---@return nil
function ActivityManager:update_activity()
  self.is_idle = false
  self.is_force_idle = false
  self.last_opts = self.opts
  self.last_updated = uv.now()
  self.opts.is_idle = false

  hooks.run('pre_activity', self.opts)

  local activity = activities.build_activity(self.opts)
  if activity == true then return end
  if activity == false then return self:clear_activity() end

  hooks.run('post_activity', self.opts, activity)

  if self.should_skip_update then
    self.should_skip_update = false
    return
  end

  self.tx:update_activity(activity)
end

---Skip the next activity update
---@return nil
function ActivityManager:skip_update() self.should_skip_update = true end

---Pause activity updates and events
---@return nil
function ActivityManager:pause()
  if self.is_paused then return end

  self:pause_events()
  if self.idle_timer then self.idle_timer:stop() end
  self.is_paused = true
end

---Resume activity updates and events
---@return nil
function ActivityManager:resume()
  if not self.is_paused then return end

  self:resume_events()
  if self.idle_timer then
    self.idle_timer:stop()
    self.idle_timer:start(
      0,
      config.idle.timeout,
      vim.schedule_wrap(function() self:check_idle() end)
    )
  end
  self.is_paused = false
end

---Pause only events, keeping the current activity state
---@return nil
function ActivityManager:pause_events() self.events_enabled = false end

---Resume events after they were paused
---@return nil
function ActivityManager:resume_events()
  self.events_enabled = true
  self:queue_update(true)
end

---Set idle state
---@return nil
function ActivityManager:idle() self:update_idle_activity() end

---Force idle state
---@return nil
function ActivityManager:force_idle()
  self.is_force_idle = true
  self:update_idle_activity()
end

---Unforce idle state
---@return nil
function ActivityManager:unidle()
  self.is_force_idle = false
  self:queue_update(true)
end

---Toggle idle state
---@return nil
function ActivityManager:toggle_idle()
  if self.is_force_idle or self.is_idle then
    self:unidle()
  else
    self:idle()
  end
end

---Hide the activity
---@return nil
function ActivityManager:hide()
  self:pause()
  self:clear_activity(true)
end

---Suppress the activity for current Neovim instance
---@return nil
function ActivityManager:suppress()
  self:pause()
  self:clear_activity()
end

---Toggle the activity
---@return nil
function ActivityManager:toggle()
  if self.is_paused then
    self:resume()
  else
    self:hide()
  end
end

---Toggle suppress state
---@return nil
function ActivityManager:toggle_suppress()
  if self.is_paused then
    self:resume()
  else
    self:suppress()
  end
end

---Setup autocmds
---@return nil
function ActivityManager.setup_autocmds()
  vim.cmd [[
    augroup CordActivityManager
      autocmd!
      autocmd BufEnter * lua require'cord.server'.manager:on_buf_enter()
      autocmd FocusGained * lua require'cord.server'.manager:on_focus_gained()
      autocmd FocusLost * lua require'cord.server'.manager:on_focus_lost()
    augroup END
  ]]

  if config.advanced.plugin.cursor_update == 'on_hold' then
    vim.cmd [[
      augroup CordActivityManager
        autocmd CursorHold,CursorHoldI * lua require'cord.server'.manager:on_cursor_update()
      augroup END
    ]]
  elseif config.advanced.plugin.cursor_update == 'on_move' then
    vim.cmd [[
      augroup CordActivityManager
        autocmd CursorMoved,CursorMovedI * lua require'cord.server'.manager:on_cursor_update()
      augroup END
    ]]
  end
end

---Clear autocmds
---@return nil
function ActivityManager.clear_autocmds()
  vim.cmd [[
    augroup CordActivityManager
      autocmd!
    augroup END
  ]]
end

---Set the activity
---@param activity table Activity to set
---@return nil
function ActivityManager:set_activity(activity) self.tx:update_activity(activity) end

---Clear the activity
---@param force? boolean Whether to force clear the activity
---@return nil
function ActivityManager:clear_activity(force) self.tx:clear_activity(force) end

---Check if the time should be updated
---@return boolean Whether the time should be updated
function ActivityManager:should_update_time()
  return config.timestamp.enabled
      and (config.timestamp.reset_on_change or config.timestamp.reset_on_idle and self.is_idle)
    or false
end

---Handle buffer enter event
---@return nil
function ActivityManager:on_buf_enter()
  local rawdir = vim.fn.expand '%:p:h'
  local cached = self.workspace_cache[rawdir]
  if cached then
    if cached.dir ~= self.workspace_dir then
      self.workspace_dir = cached.dir
      self.workspace = cached.name
      self.repo_url = cached.repo_url
      self.opts.workspace_dir = self.workspace_dir
      self.opts.workspace_name = self.workspace
      self.opts.workspace = self.workspace
      self.opts.repo_url = self.repo_url

      hooks.run('workspace_change', self.opts)
    end

    self:queue_update()
    return
  elseif cached == false then
    if self.workspace_dir then
      self.workspace_dir = nil
      self.workspace = nil
      self.repo_url = nil
      self.opts.workspace_dir = nil
      self.opts.workspace_name = nil
      self.opts.workspace = nil
      self.opts.repo_url = nil

      hooks.run('workspace_change', self.opts)
    end

    self:queue_update()
    return
  end

  async.run(function()
    local ws_utils = require 'cord.plugin.fs.workspace'
    local dir = ws_utils.find(vim.fn.expand '%:p:h'):get() or vim.fn.getcwd()

    if not dir then
      self.workspace_cache[rawdir] = false
      self:queue_update()
      return
    end

    self.workspace_dir = dir
    self.workspace = vim.fn.fnamemodify(self.workspace_dir, ':t')
    self.opts.workspace_dir = self.workspace_dir
    self.opts.workspace_name = self.workspace
    self.opts.workspace = self.workspace

    local repo_url = ws_utils.find_git_repository(self.workspace_dir):get()
    self.repo_url = repo_url
    self.opts.repo_url = repo_url

    self.workspace_cache[rawdir] = {
      dir = self.workspace_dir,
      name = self.workspace,
      repo_url = self.repo_url,
    }

    hooks.run('workspace_change', self.opts)

    self:queue_update()
  end)
end

---Handle focus gained event
---@return nil
function ActivityManager:on_focus_gained()
  if not self.events_enabled then return end
  self.is_focused = true
  self.opts.is_focused = true

  if config.idle.unidle_on_focus then self:queue_update(true) end
end

---Handle focus lost event
---@return nil
function ActivityManager:on_focus_lost()
  if not self.events_enabled then return end
  self.is_focused = false
  self.opts.is_focused = false
end

---Handle cursor update event
---@return nil
function ActivityManager:on_cursor_update()
  if not self.events_enabled then return end
  self:queue_update()
end

---Build options
---@return CordOpts
function ActivityManager:build_opts()
  local cursor_position = vim.api.nvim_win_get_cursor(0)
  local opts = {
    manager = self,
    filename = vim.fn.expand '%:t',
    filetype = vim.bo.filetype,
    buftype = vim.bo.buftype,
    is_read_only = vim.bo.readonly or not vim.bo.modifiable,
    cursor_line = cursor_position[1],
    cursor_char = cursor_position[2],
    workspace_dir = self.workspace_dir,
    workspace_name = self.workspace,
    workspace = self.workspace,
    repo_url = self.repo_url,
    is_focused = self.is_focused,
    is_idle = self.is_idle,
  }
  if config.timestamp.enabled then
    if self.last_opts and self.last_opts.timestamp then
      opts.timestamp = self.last_opts.timestamp
    else
      opts.timestamp = os.time()
    end
  end
  if self:should_update_time() then opts.timestamp = os.time() end
  local buttons = config_utils.get_buttons(opts)
  opts.buttons = buttons

  return opts
end

return ActivityManager