Files
toolshed-extensions/translate/init.lua
T

231 lines
10 KiB
Lua

-- Translate: "tr god morgen" translates what's typed into your language, or out of it when
-- that's what it's already in; "tr >de good morning" names the language to translate to, by its
-- code or its name (">swedish", ">tysk"), and "tr en>de good morning" the one it's in as well. "tr" alone translates what's selected in the
-- app Toolshed was opened from. Enter pastes the translation; ⌘K copies it, shows both texts or
-- opens Google Translate. Translate Selection replaces what's selected with its translation,
-- from a hotkey without opening Toolshed.
--
-- It asks the address Google Translate's own page asks, which needs no key but is nobody's
-- promise: Google may change it or turn requests away. What's translated is sent to Google.
-- Said plainly, as an automated client should.
local agent = "Toolshed-Translate-extension/1.0"
local address = "https://translate.googleapis.com/translate_a/single"
-- Google takes far more, but a launcher isn't for translating documents.
local longest = 5000
local encode = toolshed.url_encode
local escape = toolshed.escape
-- The languages offered in Settings and named in results: Google's code, the language's own
-- name, which is shown, and what else it's called, in English and Norwegian, to name it by.
local languages = {
{ "en", "English", "engelsk" }, { "no", "Norsk", "norwegian", "bokmål", "nb", "nn" }, { "sv", "Svenska", "swedish", "svensk" },
{ "da", "Dansk", "danish" }, { "fi", "Suomi", "finnish", "finsk" }, { "is", "Íslenska", "icelandic", "islandsk" },
{ "de", "Deutsch", "german", "tysk" }, { "nl", "Nederlands", "dutch", "nederlandsk" }, { "fr", "Français", "french", "fransk" },
{ "es", "Español", "spanish", "spansk" }, { "pt", "Português", "portuguese", "portugisisk" }, { "it", "Italiano", "italian", "italiensk" },
{ "pl", "Polski", "polish", "polsk" }, { "uk", "Українська", "ukrainian", "ukrainsk" }, { "ru", "Русский", "russian", "russisk" },
{ "tr", "Türkçe", "turkish", "tyrkisk" }, { "ar", "العربية", "arabic", "arabisk" }, { "hi", "हिन्दी", "hindi" },
{ "zh-CN", "中文", "chinese", "kinesisk", "zh" }, { "ja", "日本語", "japanese", "japansk" }, { "ko", "한국어", "korean", "koreansk" },
}
local names, options = {}, {}
for _, l in ipairs(languages) do
names[l[1]] = l[2]
table.insert(options, { value = l[1], title = l[2] })
end
-- The code of the language typed: its code, or the start of any of its names, so "swe",
-- "swedish" and "svensk" are all Swedish. A code Google has that isn't listed here goes as it is;
-- anything else isn't a language, and saying so beats Google handing the text back unchanged.
local function code_of(typed)
local wanted = typed:lower()
for _, l in ipairs(languages) do
if l[1]:lower() == wanted then return l[1] end
end
for _, l in ipairs(languages) do
for i = 2, #l do
if #wanted >= 3 and l[i]:lower():sub(1, #wanted) == wanted then return l[1] end
end
end
for _, l in ipairs(languages) do
for i = 3, #l do
if l[i] == wanted then return l[1] end
end
end
if wanted:match("^%a%a$") or wanted:match("^%a%a%-%a+$") then return typed end
error(toolshed.t("no-language", { name = typed }), 0)
end
-- Norwegian goes by three codes; Google answers with "no" whichever it was asked for.
local function same(a, b)
local function plain(code) return (code == "nb" or code == "nn") and "no" or code end
return plain(a) == plain(b)
end
local function name(code)
return names[code] or (same(code, "no") and names.no) or code
end
-- Asks Google for text in the language to, from the language given or "auto" to have it found.
-- Returns the translation and the language it was in.
local function ask(text, to, from, max_seconds)
local reply = toolshed.json.decode(toolshed.exec({
"curl", "-sSf", "--max-time", tostring(max_seconds), "-A", agent,
"-d", "client=gtx", "-d", "dt=t", "-d", "dj=1", "-d", "sl=" .. from, "-d", "tl=" .. to,
"--data-urlencode", "q=" .. text, address,
}))
local parts = {}
for _, sentence in ipairs(reply.sentences or {}) do
table.insert(parts, sentence.trans or "")
end
return table.concat(parts), reply.src or from
end
-- What's typed after the word: "en>de text" names both languages, ">de text" the one to
-- translate to, each by its code or its name. A language on its own isn't read as one, as "no"
-- and "en" are words too.
local function parse(rest)
local from, to, text = rest:match("^([^%s>]*)>([^%s>]+)%s+(.+)$")
if to then return text, code_of(to), from ~= "" and code_of(from) or "auto" end
return rest, nil, "auto"
end
-- Translates text as the settings say: into your language, or, when it's in that already, into
-- the other one. A language named in what was typed is used as it is.
local function translate(text, settings, to, from, max_seconds)
if #text > longest then error(toolshed.t("too-long", { count = longest }), 0) end
if to then
local out, src = ask(text, to, from, max_seconds)
return { text = out, from = src, to = to, original = text }
end
local out, src = ask(text, settings.language, "auto", max_seconds)
if same(src, settings.language) and not same(settings.other, settings.language) then
out = ask(text, settings.other, src, max_seconds)
return { text = out, from = src, to = settings.other, original = text }
end
return { text = out, from = src, to = settings.language, original = text }
end
local function one_line(text)
return (text:gsub("%s+", " "))
end
local function site(data)
return "https://translate.google.com/?sl=" .. encode(data.from) .. "&tl=" .. encode(data.to) .. "&text=" .. encode(data.original) .. "&op=translate"
end
return toolshed.toolbox {
key = "translate",
title = "i18n:toolbox.title",
description = "i18n:toolbox.description",
icon = "assets/google-translate.svg",
tint = "blue",
settings = {
{ key = "language", title = "i18n:setting.language.title", description = "i18n:setting.language.description", type = "choice", default = "en", options = options },
{ key = "other", title = "i18n:setting.other.title", description = "i18n:setting.other.description", type = "choice", default = "no", options = options },
},
tools = {
{
key = "translate",
title = "i18n:tool.translate.title",
words = { "tr", "translate" },
examples = { "tr god morgen", "tr >swedish good morning", "tr en>fr good morning" },
keywords = { "translate", "google", "language", "oversett", "språk" },
-- Google is asked once typing pauses, not for every letter on the way.
debounce = true,
items = true,
search = function(rest, settings)
local failed = function(why, text, from, to)
return { { title = toolshed.t("failed"), subtitle = tostring(why), icon = "info", action = "open",
data = { original = text, from = from or "auto", to = to or settings.language } } }
end
local understood, text, to, from = pcall(parse, rest)
if not understood then return failed(text, rest) end
local label
if rest == "" then
text, label = toolshed.selection(), toolshed.t("selected")
if not text or text:match("^%s*$") then return {} end
end
local ok, result = pcall(translate, text, settings, to, from, 4)
if not ok then return failed(result, text, from, to) end
return { {
title = one_line(result.text),
subtitle = name(result.from) .. " → " .. name(result.to),
label = label,
data = result,
} }
end,
actions = {
{
key = "paste", title = "i18n:action.paste", icon = "clipboard-paste", pastes = true,
run = function(ctx)
toolshed.clipboard.copy(ctx.data.text)
return { paste = true }
end,
},
{
key = "copy", title = "i18n:action.copy", icon = "copy", shortcut = "cmd+shift+c",
run = function(ctx)
toolshed.clipboard.copy(ctx.data.text)
return toolshed.t("copied")
end,
},
{
-- Both texts in full, for what's longer than a row shows.
key = "show", title = "i18n:action.show", icon = "book-a",
run = function(ctx)
local function block(code, text)
return '<div style="margin-bottom:6px;color:var(--text-secondary);font-size:12px">' .. escape(name(code)) .. '</div>'
.. '<div style="margin-bottom:18px;white-space:pre-wrap;user-select:text">' .. escape(text) .. '</div>'
end
return {
html = '<div style="padding:20px 24px;color:var(--text);line-height:1.5;overflow:auto;height:100%;box-sizing:border-box">'
.. block(ctx.data.to, ctx.data.text) .. block(ctx.data.from, ctx.data.original) .. '</div>',
source = "Google Translate",
jigs = {
{ title = toolshed.t("action.paste"), icon = "clipboard-paste", action = "paste", data = ctx.data },
{ title = toolshed.t("action.copy"), icon = "copy", action = "copy", data = ctx.data },
{ title = toolshed.t("action.open"), icon = "external-link", action = "open", data = ctx.data },
},
}
end,
},
{
key = "open", title = "i18n:action.open", icon = "external-link", shortcut = "cmd+enter",
run = function(ctx) toolshed.open(site(ctx.data)) end,
},
},
},
{
-- A command: it puts the translation where the text was, so there's nothing to show.
key = "selection",
title = "i18n:tool.selection.title",
description = "i18n:tool.selection.description",
keywords = { "translate", "selection", "replace", "oversett", "merket" },
background = true,
actions = {
{
key = "replace", title = "i18n:tool.selection.title", pastes = true,
run = function(ctx)
local text = toolshed.selection()
if not text or text:match("^%s*$") then
return { message = toolshed.t("nothing-selected"), status = "warning" }
end
local result = translate(text, ctx.settings, nil, "auto", 8)
toolshed.clipboard.copy(result.text)
return { paste = true }
end,
},
},
},
},
}