Trans.nvim/lua/Trans/core/translate.lua

92 lines
1.9 KiB
Lua
Raw Normal View History

local Trans = require('Trans')
local util = Trans.util
2023-03-09 19:42:41 +08:00
local function new_data(opts)
2023-03-09 19:42:41 +08:00
opts = opts or {}
2023-03-12 09:56:31 +08:00
local mode = opts.method or ({
n = 'normal',
v = 'visual',
2023-03-11 11:32:13 +08:00
})[vim.api.nvim_get_mode().mode]
2023-03-12 09:56:31 +08:00
local str = util.get_str(mode)
2023-03-09 19:42:41 +08:00
if str == '' then return end
2023-03-12 09:56:31 +08:00
local strategy = Trans.conf.strategy[mode]
2023-03-09 19:42:41 +08:00
local data = {
str = str,
2023-03-12 09:56:31 +08:00
mode = mode,
frontend = strategy.frontend,
2023-03-12 09:56:31 +08:00
backend = strategy.backend,
2023-03-11 11:32:13 +08:00
result = {},
2023-03-09 19:42:41 +08:00
}
if util.is_English(str) then
data.from = 'en'
data.to = 'zh'
else
data.from = 'zh'
data.to = 'en'
end
-- TODO : Check if the str is a word
data.is_word = true
return data
end
2023-03-09 19:42:41 +08:00
local function set_result(data)
local backend_list = data.backend
local backends = Trans.backend
local frontend = Trans.frontend[data.frontend]
-- HACK :Rewrite this function to support multi request
local function do_query(name)
local backend = backends[name]
if backend.no_wait then
backend.query(data)
else
backend.query(data)
frontend.wait(data.result, name, backend.timeout)
end
return type(data.result[name]) == "table"
end
for _, name in ipairs(backend_list) do
if do_query(name) then
-- TODO : process data
break
end
end
end
2023-03-11 11:32:13 +08:00
local function render_window(data)
-- TODO
print('begin to render window')
end
2023-03-11 11:32:13 +08:00
-- HACK : Core process logic
local function process(opts)
Trans.translate = coroutine.wrap(process)
local data = new_data(opts)
if not data then return end
set_result(data)
local success = false
for _, v in pairs(data.result) do
if type(v) == "table" then
success = true
break
end
end
2023-03-09 19:42:41 +08:00
vim.pretty_print(data)
if success == false then return end
render_window(data)
2023-03-09 19:42:41 +08:00
end
return coroutine.wrap(process)