about summary refs log tree commit diff
path: root/.local/bin/rofi-translate
blob: f71557da6edb68409ee00c425de91d6b3a9980ef (plain)
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
#!/usr/bin/env lua

local function rofi(prompt, lines)
  local cmd = string.format(
    'printf "%s" | rofi -dmenu -i -p "%s"',
    table.concat(lines, "\n"),
    prompt
  )
  local handle = io.popen(cmd)
  local selection = handle:read("*a")
  handle:close()
  selection = selection:gsub("%s+$", "")
  if selection == "" then return nil end
  return selection
end

local function contains(tbl, val)
  for _, v in pairs(tbl) do
    if v == val then
      return true
    end
  end
  return false
end

local directions = {
  "English → Portuguese",
  "Portuguese → English"
}

local choice = rofi("Translate:", directions)
if (not choice) or (not contains(directions,choice)) then os.exit() end

local lang_pair = {
  ["English → Portuguese"] = "en:pt",
  ["Portuguese → English"] = "pt:en"
}
local pair = lang_pair[choice]

local text = rofi("󰗊", { "" })
if not text then os.exit() end

local trans_cmd = string.format('trans -b %s "%s"', pair, text:gsub('"', '\\"'))
local trans_handle = io.popen(trans_cmd)
local translation = trans_handle:read("*a")
trans_handle:close()
translation = translation:gsub("%s+$", "")

if translation == "" then
  translation = "(no translation returned)"
else
  io.popen("wl-copy " .. translation)
end

local notify_cmd = string.format(
  'notify-send -- "Translation (%s)" "%s"',
  choice,
  translation:gsub('"', '\\"')
)
os.execute(notify_cmd)