feat: non-blocking API

This commit is contained in:
əlemi 2024-09-17 16:33:22 +02:00
parent 646760f3cb
commit 9dea608f04
Signed by: alemi
GPG key ID: A4895B84D311642C
5 changed files with 179 additions and 170 deletions

View file

@ -13,7 +13,6 @@ local ticks = {}
---@param buffer? integer buffer to use for attaching (will clear content) ---@param buffer? integer buffer to use for attaching (will clear content)
---@param content? string if provided, set this content after attaching ---@param content? string if provided, set this content after attaching
---@param nowait? boolean skip waiting for initial content sync ---@param nowait? boolean skip waiting for initial content sync
---@return BufferController
local function attach(name, buffer, content, nowait) local function attach(name, buffer, content, nowait)
if buffer_id_map[name] ~= nil then if buffer_id_map[name] ~= nil then
error("already attached to buffer " .. name) error("already attached to buffer " .. name)
@ -25,114 +24,113 @@ local function attach(name, buffer, content, nowait)
vim.api.nvim_set_option_value('fileformat', 'unix', { buf = buffer }) vim.api.nvim_set_option_value('fileformat', 'unix', { buf = buffer })
vim.api.nvim_buf_set_name(buffer, name) vim.api.nvim_buf_set_name(buffer, name)
local controller = session.workspace:attach(name):await() session.workspace:attach(name):and_then(function (controller)
if not nowait then
if not nowait then local promise = controller:poll()
local promise = controller:poll() for i=1, 20, 1 do
for i=1, 20, 1 do if promise.ready then break end
if promise.ready then break end vim.uv.sleep(100)
vim.uv.sleep(100) end
end end
end
-- TODO map name to uuid -- TODO map name to uuid
id_buffer_map[buffer] = name id_buffer_map[buffer] = name
buffer_id_map[name] = buffer buffer_id_map[name] = buffer
ticks[buffer] = 0 ticks[buffer] = 0
-- hook serverbound callbacks -- hook serverbound callbacks
-- TODO breaks when deleting whole lines at buffer end -- TODO breaks when deleting whole lines at buffer end
vim.api.nvim_buf_attach(buffer, false, { vim.api.nvim_buf_attach(buffer, false, {
on_bytes = function(_, buf, tick, start_row, start_col, start_offset, old_end_row, old_end_col, old_end_byte_len, new_end_row, new_end_col, new_byte_len) on_bytes = function(_, buf, tick, start_row, start_col, start_offset, old_end_row, old_end_col, old_end_byte_len, new_end_row, new_end_col, new_byte_len)
if tick <= ticks[buf] then return end if tick <= ticks[buf] then return end
if id_buffer_map[buf] == nil then return true end -- unregister callback handler if id_buffer_map[buf] == nil then return true end -- unregister callback handler
if CODEMP.config.debug then print(string.format( if CODEMP.config.debug then print(string.format(
"start(row:%s, col:%s) offset:%s end(row:%s, col:%s new(row:%s, col:%s)) len(old:%s, new:%s)", "start(row:%s, col:%s) offset:%s end(row:%s, col:%s new(row:%s, col:%s)) len(old:%s, new:%s)",
start_row, start_col, start_offset, old_end_row, old_end_col, new_end_row, new_end_col, old_end_byte_len, new_byte_len start_row, start_col, start_offset, old_end_row, old_end_col, new_end_row, new_end_col, old_end_byte_len, new_byte_len
)) end )) end
local end_offset = start_offset + old_end_byte_len local end_offset = start_offset + old_end_byte_len
local change_content = "" local change_content = ""
local len = utils.buffer.len(buf) local len = utils.buffer.len(buf)
if start_offset + new_byte_len + 1 > len then if start_offset + new_byte_len + 1 > len then
-- i dont know why but we may go out of bounds when doing 'dd' at the end of buffer?? -- i dont know why but we may go out of bounds when doing 'dd' at the end of buffer??
local delta = (start_offset + new_byte_len + 1) - len local delta = (start_offset + new_byte_len + 1) - len
if CODEMP.config.debug then print("/!\\ bytes out of bounds by " .. delta .. ", adjusting") end if CODEMP.config.debug then print("/!\\ bytes out of bounds by " .. delta .. ", adjusting") end
end_offset = end_offset - delta end_offset = end_offset - delta
start_offset = start_offset - delta start_offset = start_offset - delta
end end
if new_byte_len > 0 then if new_byte_len > 0 then
local actual_end_col = new_end_col local actual_end_col = new_end_col
if new_end_row == 0 then actual_end_col = new_end_col + start_col end if new_end_row == 0 then actual_end_col = new_end_col + start_col end
local actual_end_row = start_row + new_end_row local actual_end_row = start_row + new_end_row
-- -- when bulk inserting at the end we go out of bounds, so we probably need to clamp? -- -- when bulk inserting at the end we go out of bounds, so we probably need to clamp?
-- -- issue: row=x+1 col=0 and row=x col=0 may be very far apart! we need to get last col of row x, ughh.. -- -- issue: row=x+1 col=0 and row=x col=0 may be very far apart! we need to get last col of row x, ughh..
-- -- also, this doesn't work so it will stay commented out for a while longer -- -- also, this doesn't work so it will stay commented out for a while longer
-- if new_end_row ~= old_end_row and new_end_col == 0 then -- if new_end_row ~= old_end_row and new_end_col == 0 then
-- -- we may be dealing with the last line of the buffer, get_text could error because out-of-bounds -- -- we may be dealing with the last line of the buffer, get_text could error because out-of-bounds
-- local row_count = vim.api.nvim_buf_line_count(buf) -- local row_count = vim.api.nvim_buf_line_count(buf)
-- if actual_end_row + 1 > row_count then -- if actual_end_row + 1 > row_count then
-- local delta = (actual_end_row + 1) - row_count -- local delta = (actual_end_row + 1) - row_count
-- if CODEMP.config.debug then print("/!\\ row out of bounds by " .. delta .. ", adjusting") end -- if CODEMP.config.debug then print("/!\\ row out of bounds by " .. delta .. ", adjusting") end
-- actual_end_row = actual_end_row - delta -- actual_end_row = actual_end_row - delta
-- actual_end_col = len - vim.api.nvim_buf_get_offset(buf, row_count) -- actual_end_col = len - vim.api.nvim_buf_get_offset(buf, row_count)
-- end -- end
-- end -- end
local lines = vim.api.nvim_buf_get_text(buf, start_row, start_col, actual_end_row, actual_end_col, {}) local lines = vim.api.nvim_buf_get_text(buf, start_row, start_col, actual_end_row, actual_end_col, {})
change_content = table.concat(lines, '\n') change_content = table.concat(lines, '\n')
end end
if CODEMP.config.debug then if CODEMP.config.debug then
print(string.format("sending: %s..%s '%s'", start_offset, start_offset + old_end_byte_len, change_content)) print(string.format("sending: %s..%s '%s'", start_offset, start_offset + old_end_byte_len, change_content))
end end
controller:send({ controller:send({
start = start_offset, finish = end_offset, content = change_content start = start_offset, finish = end_offset, content = change_content
}):await() }):await()
end, end,
}) })
local async = vim.loop.new_async(vim.schedule_wrap(function () local async = vim.loop.new_async(vim.schedule_wrap(function ()
while true do while true do
local event = controller:try_recv():await() local event = controller:try_recv():await()
if event == nil then break end if event == nil then break end
ticks[buffer] = vim.api.nvim_buf_get_changedtick(buffer) ticks[buffer] = vim.api.nvim_buf_get_changedtick(buffer)
if CODEMP.config.debug then if CODEMP.config.debug then
print(" ~~ applying change ~~ " .. event.start .. ".." .. event.finish .. "::[" .. event.content .. "]") print(" ~~ applying change ~~ " .. event.start .. ".." .. event.finish .. "::[" .. event.content .. "]")
end end
utils.buffer.set_content(buffer, event.content, event.start, event.finish) utils.buffer.set_content(buffer, event.content, event.start, event.finish)
if event.hash ~= nil then if event.hash ~= nil then
if utils.hash(utils.buffer.get_content(buffer)) ~= event.hash then if utils.hash(utils.buffer.get_content(buffer)) ~= event.hash then
-- OUT OF SYNC! -- OUT OF SYNC!
-- TODO this may be destructive! we should probably prompt the user before doing this -- TODO this may be destructive! we should probably prompt the user before doing this
print(" /!\\ out of sync, resynching...") print(" /!\\ out of sync, resynching...")
utils.buffer.set_content(buffer, controller:content():await()) utils.buffer.set_content(buffer, controller:content():await())
return return
end
end end
end end
end))
local remote_content = controller:content():await()
if content ~= nil then
-- TODO this may happen too soon!!
local _ = controller:send({
start = 0, finish = #remote_content, content = content
}) -- no need to await
else
local current_content = utils.buffer.get_content(buffer)
if current_content ~= remote_content then
ticks[buffer] = vim.api.nvim_buf_get_changedtick(buffer)
utils.buffer.set_content(buffer, remote_content)
end
end end
end))
local remote_content = controller:content():await() controller:callback(function (_) async:send() end)
if content ~= nil then vim.defer_fn(function() async:send() end, 500) -- force a try_recv after 500ms
-- TODO this may happen too soon!!
local _ = controller:send({
start = 0, finish = #remote_content, content = content
}) -- no need to await
else
local current_content = utils.buffer.get_content(buffer)
if current_content ~= remote_content then
ticks[buffer] = vim.api.nvim_buf_get_changedtick(buffer)
utils.buffer.set_content(buffer, remote_content)
end
end
controller:callback(function (_controller) async:send() end) local filetype = vim.filetype.match({ buf = buffer })
vim.defer_fn(function() async:send() end, 500) -- force a try_recv after 500ms vim.api.nvim_set_option_value("filetype", filetype, { buf = buffer })
print(" ++ attached to buffer " .. name)
local filetype = vim.filetype.match({ buf = buffer }) require('codemp.window').update()
vim.api.nvim_set_option_value("filetype", filetype, { buf = buffer }) end)
print(" ++ attached to buffer " .. name)
require('codemp.window').update()
return controller
end end
---@param name string ---@param name string
@ -180,9 +178,10 @@ local function create(buffer)
if session.workspace == nil then if session.workspace == nil then
error("join a workspace first") error("join a workspace first")
end end
session.workspace:create(buffer):await() session.workspace:create(buffer):and_then(function ()
print(" ++ created buffer " .. buffer) print(" ++ created buffer " .. buffer)
require('codemp.window').update() require('codemp.window').update()
end)
end end
return { return {

View file

@ -8,9 +8,11 @@ local function connect()
if CODEMP.config.password == nil then if CODEMP.config.password == nil then
CODEMP.config.password = vim.g.codemp_password or vim.fn.input("password > ", "") CODEMP.config.password = vim.g.codemp_password or vim.fn.input("password > ", "")
end end
session.client = CODEMP.native.connect(CODEMP.config):await() CODEMP.native.connect(CODEMP.config):and_then(function (client)
require('codemp.window').update() session.client = client
vim.schedule(function () workspace.list() end) require('codemp.window').update()
workspace.list()
end)
end end
return { return {

View file

@ -50,9 +50,10 @@ local connected_actions = {
start = function(ws) start = function(ws)
if ws == nil then error("missing workspace name") end if ws == nil then error("missing workspace name") end
session.client:create_workspace(ws):await() session.client:create_workspace(ws):and_then(function ()
vim.schedule(function () workspace.list() end) print(" <> created workspace " .. ws)
print(" <> created workspace " .. ws) workspace.list()
end)
end, end,
available = function() available = function()
@ -71,8 +72,9 @@ local connected_actions = {
else else
ws = vim.fn.input("workspace > ", "") ws = vim.fn.input("workspace > ", "")
end end
session.client:invite_to_workspace(ws, user):await() session.client:invite_to_workspace(ws, user):and_then(function ()
print(" ][ invited " .. user .. " to workspace " .. ws) print(" :: invited " .. user .. " to workspace " .. ws)
end)
end, end,
disconnect = function() disconnect = function()
@ -108,8 +110,9 @@ local joined_actions = {
delete = function(path) delete = function(path)
if path == nil then error("missing buffer name") end if path == nil then error("missing buffer name") end
session.workspace:delete(path):await() session.workspace:delete(path):and_then(function()
print(" xx deleted buffer " .. path) print(" xx deleted buffer " .. path)
end)
end, end,
buffers = function() buffers = function()

View file

@ -116,18 +116,20 @@ M.delete = function(state, path, extra)
vim.ui.input({ prompt = "delete buffer '" .. selected.name .. "'?" }, function (input) vim.ui.input({ prompt = "delete buffer '" .. selected.name .. "'?" }, function (input)
if input == nil then return end if input == nil then return end
if not vim.startswith("y", string.lower(input)) then return end if not vim.startswith("y", string.lower(input)) then return end
session.workspace:delete(selected.name):await() session.workspace:delete(selected.name):and_then(function ()
print("deleted buffer " .. selected.name) print("deleted buffer " .. selected.name)
manager.refresh("codemp") manager.refresh("codemp")
end)
end) end)
elseif selected.type == "workspace" then elseif selected.type == "workspace" then
if session.client == nil then error("connect to server first") end if session.client == nil then error("connect to server first") end
vim.ui.input({ prompt = "delete buffer '" .. selected.name .. "'?" }, function (input) vim.ui.input({ prompt = "delete buffer '" .. selected.name .. "'?" }, function (input)
if input == nil then return end if input == nil then return end
if not vim.startswith("y", string.lower(input)) then return end if not vim.startswith("y", string.lower(input)) then return end
session.client:delete_workspace(selected.name):await() session.client:delete_workspace(selected.name):and_then(function ()
print("deleted workspace " .. selected.name) print("deleted workspace " .. selected.name)
manager.refresh("codemp") manager.refresh("codemp")
end)
end) end)
end end
end end
@ -138,21 +140,24 @@ M.add = function(state, path, extra)
if vim.startswith(selected.name, "#") then if vim.startswith(selected.name, "#") then
vim.ui.input({ prompt = "new buffer path" }, function(input) vim.ui.input({ prompt = "new buffer path" }, function(input)
if input == nil or input == "" then return end if input == nil or input == "" then return end
session.workspace:create(input):await() session.workspace:create(input):and_then(function ()
manager.refresh("codemp") manager.refresh("codemp")
end)
end) end)
elseif selected.name == "workspaces" then elseif selected.name == "workspaces" then
vim.ui.input({ prompt = "new workspace name" }, function(input) vim.ui.input({ prompt = "new workspace name" }, function(input)
if input == nil or input == "" then return end if input == nil or input == "" then return end
session.client:create_workspace(input):await() session.client:create_workspace(input):and_then(function ()
vim.schedule(function () require('codemp.workspace').list() end) require('codemp.workspace').list()
end)
end) end)
end end
elseif selected.type == "workspace" then elseif selected.type == "workspace" then
vim.ui.input({ prompt = "user name to invite" }, function(input) vim.ui.input({ prompt = "user name to invite" }, function(input)
if input == nil or input == "" then return end if input == nil or input == "" then return end
session.client:invite_to_workspace(selected.name, input):await() session.client:invite_to_workspace(selected.name, input):and_then(function ()
print("invited user " .. input .. " to workspace " .. selected.name) print("invited user " .. input .. " to workspace " .. selected.name)
end)
end) end)
end end
manager.refresh("codemp") manager.refresh("codemp")

View file

@ -12,22 +12,24 @@ local user_hl = {}
local function fetch_workspaces_list() local function fetch_workspaces_list()
local new_list = {} local new_list = {}
local owned = session.client:list_workspaces(true, false):await() session.client:list_workspaces(true, false):and_then(function (owned)
for _, ws in pairs(owned) do for _, ws in pairs(owned) do
table.insert(new_list, { table.insert(new_list, {
name = ws, name = ws,
owned = true, owned = true,
}) })
end end
local invited = session.client:list_workspaces(false, true):await() session.client:list_workspaces(false, true):and_then(function (invited)
for _, ws in pairs(invited) do for _, ws in pairs(invited) do
table.insert(new_list, { table.insert(new_list, {
name = ws, name = ws,
owned = false, owned = false,
}) })
end end
session.available = new_list session.available = new_list
require('codemp.window').update() require('codemp.window').update()
end)
end)
end end
---@param ws Workspace ---@param ws Workspace
@ -105,42 +107,40 @@ local function register_cursor_handler(ws)
end end
---@param workspace string workspace name to join ---@param workspace string workspace name to join
---@return Workspace
---join a workspace and register event handlers ---join a workspace and register event handlers
local function join(workspace) local function join(workspace)
local ws = session.client:join_workspace(workspace):await() session.client:join_workspace(workspace):and_then(function (ws)
print(" >< joined workspace " .. ws.name) print(" >< joined workspace " .. ws.name)
register_cursor_callback(ws) register_cursor_callback(ws)
register_cursor_handler(ws) register_cursor_handler(ws)
utils.poller( utils.poller(
function() return ws:event() end, function() return ws:event() end,
function(event) function(event)
if event.type == "leave" then if event.type == "leave" then
if buffers.users[event.value] ~= nil then if buffers.users[event.value] ~= nil then
local buf_name = buffers.users[event.value] local buf_name = buffers.users[event.value]
local buf_id = buffers.map_rev[buf_name] local buf_id = buffers.map_rev[buf_name]
if buf_id ~= nil then if buf_id ~= nil then
vim.api.nvim_buf_clear_namespace(buf_id, user_hl[event.value].ns, 0, -1) vim.api.nvim_buf_clear_namespace(buf_id, user_hl[event.value].ns, 0, -1)
end
buffers.users[event.value] = nil
user_hl[event.value] = nil
end end
buffers.users[event.value] = nil elseif event.type == "join" then
user_hl[event.value] = nil buffers.users[event.value] = ""
user_hl[event.value] = {
ns = vim.api.nvim_create_namespace("codemp-cursor-" .. event.value),
hi = utils.color(event.value),
pos = { 0, 0 },
}
end end
elseif event.type == "join" then require('codemp.window').update()
buffers.users[event.value] = ""
user_hl[event.value] = {
ns = vim.api.nvim_create_namespace("codemp-cursor-" .. event.value),
hi = utils.color(event.value),
pos = { 0, 0 },
}
end end
require('codemp.window').update() )
end
)
session.workspace = ws session.workspace = ws
require('codemp.window').update() require('codemp.window').update()
end)
return ws
end end
local function leave() local function leave()