-- Calculator: Standard (as Windows' was: each operator works on what's
-- there so far, 2 + 3 × 4 = 20), Scientific (a whole expression with
-- brackets and functions, worked out by precedence) and Converter. The
-- keyboard works in all three; the history is shared by the first two.
local c8 = require "c8"
local win, tabs, side, history_list
-- What's kept: the history, the tab, the converter's choices. Before the
-- tabs the file was the history alone (a list), so take that as it is
local saved = c8.load("calculator") or {}
if saved[1] or next(saved) == nil then
saved = { history = saved }
end
local history = saved.history or {}
saved.history = history
local function keep()
c8.save("calculator", saved)
end
local function fmt(n)
if n ~= n or n == math.huge or n == -math.huge then
return "Can't do that"
end
if n == math.floor(n) and math.abs(n) < 1e15 then
return string.format("%d", n)
end
return string.format("%.12g", n)
end
local function remember(line)
table.insert(history, 1, line)
history[21] = nil
keep()
if history_list then
history_list:count(#history)
end
end
-- Standard -----------------------------------------------------------
local std = { acc = nil, op = nil, entry = "0", fresh = true }
local std_shown, std_above
local symbols = { ["+"] = "+", ["-"] = "−", ["*"] = "×", ["/"] = "÷" }
local function std_show()
std_shown:set(std.entry)
std_above:set(std.acc and (fmt(std.acc) .. " " .. symbols[std.op]) or " ")
end
local function apply(a, o, b)
if o == "+" then return a + b
elseif o == "-" then return a - b
elseif o == "*" then return a * b
elseif o == "/" then return b == 0 and 0 / 0 or a / b end
return b
end
local function value()
return tonumber(std.entry) or 0
end
local function digit(d)
if std.fresh or std.entry == "0" then
std.entry = d == "." and "0." or d
std.fresh = false
elseif d ~= "." or not std.entry:find(".", 1, true) then
if #std.entry < 16 then
std.entry = std.entry .. d
end
end
std_show()
end
local function operator(o)
if std.acc and std.op and not std.fresh then
std.acc = apply(std.acc, std.op, value())
std.entry = fmt(std.acc)
else
std.acc = value()
end
std.op, std.fresh = o, true
std_show()
end
local function equals()
if not std.op then
return
end
local b = value()
local result = apply(std.acc, std.op, b)
remember(fmt(std.acc) .. " " .. symbols[std.op] .. " " .. fmt(b)
.. " = " .. fmt(result))
std.entry, std.acc, std.op, std.fresh = fmt(result), nil, nil, true
std_show()
end
local function unary(fn)
std.entry = fmt(fn(value()))
std.fresh = true
std_show()
end
local function clear(all)
std.entry, std.fresh = "0", true
if all then
std.acc, std.op = nil, nil
end
std_show()
end
local function backspace()
if std.fresh then
return
end
std.entry = std.entry:sub(1, -2)
if std.entry == "" or std.entry == "-" then
std.entry = "0"
end
std_show()
end
local function percent()
unary(function(x) return (std.acc or 0) * x / 100 end)
end
local std_keys = {
{ "%", percent },
{ "CE", function() clear(false) end },
{ "C", function() clear(true) end },
{ "⌫", backspace },
{ "1/x", function() unary(function(x) return x == 0 and 0 / 0 or 1 / x end) end },
{ "x²", function() unary(function(x) return x * x end) end },
{ "√", function() unary(function(x) return x < 0 and 0 / 0 or math.sqrt(x) end) end },
{ "÷", function() operator("/") end },
{ "7" }, { "8" }, { "9" }, { "×", function() operator("*") end },
{ "4" }, { "5" }, { "6" }, { "−", function() operator("-") end },
{ "1" }, { "2" }, { "3" }, { "+", function() operator("+") end },
{ "±", function()
std.entry = std.entry:sub(1, 1) == "-" and std.entry:sub(2) or
(std.entry ~= "0" and "-" .. std.entry or std.entry)
std_show()
end },
{ "0" }, { "." }, { "=", equals, primary = true },
}
local function standard()
std_shown = c8.label { text = std.entry, style = "header", align = "end" }
std_above = c8.label { text = " ", color = "secondary", align = "end" }
local grid = c8.grid { columns = 4, column_spacing = 4, row_spacing = 4,
expand_columns = { 1, 2, 3, 4 }, fill = true }
for _, k in ipairs(std_keys) do
local fn = k[2] or function() digit(k[1]) end
grid:add(c8.button { label = k[1], primary = k.primary, fill = true,
height = 56, on_click = fn })
end
std_show()
return c8.column { spacing = 8, fill = true, padding = { 0, 12, 0, 12 },
std_above, std_shown, c8.spacer { height = 8 }, grid }
end
local function std_key(t, k)
if t and t:match("^[0-9.]$") then digit(t)
elseif t == "," then digit(".")
elseif t == "+" or t == "-" or t == "*" or t == "/" then operator(t)
elseif t == "=" or k == "Return" or k == "KP_Enter" then equals()
elseif k == "BackSpace" then backspace()
elseif k == "Escape" then clear(true)
elseif k == "Delete" then clear(false)
elseif t == "%" then percent()
else
return false
end
return true
end
-- Scientific ---------------------------------------------------------
-- The expression is a list of tokens: numbers (as typed), constants,
-- operators, functions (each opens a bracket), brackets and the
-- marks after a number (!, ², ³). It's read by precedence when shown and
-- on =; brackets left open are closed at the end.
local sci = { toks = {}, done = false, ans = 0, inv = false,
deg = saved.degrees ~= false }
local sci_shown, sci_above, sci_angle, sci_fn_buttons = nil, nil, nil, {}
local FN = {
sin = "sin(", cos = "cos(", tan = "tan(",
asin = "sin⁻¹(", acos = "cos⁻¹(", atan = "tan⁻¹(",
ln = "ln(", log = "log(", exp = "e^(", pow10 = "10^(",
sqrt = "√(", cbrt = "∛(", recip = "1/(", abs = "abs(",
}
local OPS = { ["+"] = "+", ["-"] = "−", ["*"] = "×", ["/"] = "÷",
["^"] = "^", root = "ʸ√", mod = "mod" }
local POST = { ["!"] = "!", sq = "²", cube = "³", pct = "%" }
local function text_of(t)
if t.kind == "num" then return (t.v:gsub("^%-", "−"))
elseif t.kind == "const" then return t.v == "pi" and "π" or t.v == "e" and "e" or "Ans"
elseif t.kind == "op" then return " " .. OPS[t.v] .. " "
elseif t.kind == "fn" then return FN[t.v]
elseif t.kind == "post" then return POST[t.v]
end
return t.v -- a bracket
end
local function expr_text()
local parts = {}
for i, t in ipairs(sci.toks) do
local s = text_of(t)
-- A minus that starts a number reads closed up: 2 × −3
if t.kind == "op" and t.v == "-" and (i == 1 or sci.toks[i - 1].kind
== "op" or sci.toks[i - 1].kind == "fn" or sci.toks[i - 1].v == "(") then
s = "−"
end
parts[#parts + 1] = s
end
return (table.concat(parts):gsub("^ ", ""))
end
local function nan() return 0 / 0 end
local function fact(x)
if x < 0 or x ~= math.floor(x) or x > 170 then
return nan()
end
local r = 1
for i = 2, x do r = r * i end
return r
end
-- Sine and the rest give 1.2e-16 for sin 180°; such dust is 0
local function tidy(x)
return math.abs(x) < 1e-15 and 0 or x
end
local function call(f, x)
local to = sci.deg and math.rad or function(v) return v end
local from = sci.deg and math.deg or function(v) return v end
if f == "sin" then return tidy(math.sin(to(x)))
elseif f == "cos" then return tidy(math.cos(to(x)))
elseif f == "tan" then
if sci.deg and x % 180 == 90 then return nan() end
return tidy(math.tan(to(x)))
elseif f == "asin" then return math.abs(x) > 1 and nan() or from(math.asin(x))
elseif f == "acos" then return math.abs(x) > 1 and nan() or from(math.acos(x))
elseif f == "atan" then return from(math.atan(x))
elseif f == "ln" then return x <= 0 and nan() or math.log(x)
elseif f == "log" then return x <= 0 and nan() or math.log(x, 10)
elseif f == "exp" then return math.exp(x)
elseif f == "pow10" then return 10 ^ x
elseif f == "sqrt" then return x < 0 and nan() or math.sqrt(x)
elseif f == "cbrt" then return x < 0 and -((-x) ^ (1 / 3)) or x ^ (1 / 3)
elseif f == "recip" then return x == 0 and nan() or 1 / x
elseif f == "abs" then return math.abs(x)
end
return nan()
end
-- The y-th root of x; odd roots of negatives are real
local function root(x, y)
if y == 0 then return nan() end
if x < 0 then
if y == math.floor(y) and y % 2 == 1 then
return -((-x) ^ (1 / y))
end
return nan()
end
return x ^ (1 / y)
end
-- Reads tokens by precedence: + − under × ÷ mod under a minus in front
-- under ^ and ʸ√ (from the right) under the marks after a number.
-- A number straight after another, or after a bracket, multiplies (2π).
-- Returns nil for something unfinished.
local function evaluate(toks)
local pos = 1
local function peek() return toks[pos] end
local function next_tok()
pos = pos + 1
return toks[pos - 1]
end
local expr, unary_
local function primary()
local t = next_tok()
if not t then return nil end
if t.kind == "num" then return tonumber(t.v)
elseif t.kind == "const" then
return t.v == "pi" and math.pi or t.v == "e" and math.exp(1) or t.n
elseif t.kind == "fn" or (t.kind == "paren" and t.v == "(") then
local v = expr()
if not v then return nil end
local c = peek()
if c and c.kind == "paren" and c.v == ")" then
pos = pos + 1
elseif c then
return nil
end
return t.kind == "fn" and call(t.v, v) or v
end
return nil
end
local function postfix()
local v = primary()
while v do
local t = peek()
if not (t and t.kind == "post") then break end
pos = pos + 1
if t.v == "!" then v = fact(v)
elseif t.v == "sq" then v = v * v
elseif t.v == "cube" then v = v * v * v
else v = v / 100 end
end
return v
end
local function power()
local v = postfix()
local t = peek()
if v and t and t.kind == "op" and (t.v == "^" or t.v == "root") then
pos = pos + 1
local r = unary_()
if not r then return nil end
return t.v == "^" and v ^ r or root(v, r)
end
return v
end
function unary_()
local t = peek()
if t and t.kind == "op" and (t.v == "-" or t.v == "+") then
pos = pos + 1
local v = unary_()
return v and (t.v == "-" and -v or v)
end
return power()
end
local function starts_value(t)
return t and (t.kind == "num" or t.kind == "const" or t.kind == "fn"
or (t.kind == "paren" and t.v == "("))
end
local function term()
local v = unary_()
while v do
local t = peek()
if t and t.kind == "op" and (t.v == "*" or t.v == "/" or t.v == "mod") then
pos = pos + 1
local r = unary_()
if not r then return nil end
if t.v == "*" then v = v * r
elseif t.v == "/" then v = r == 0 and nan() or v / r
else v = r == 0 and nan() or math.fmod(v, r) end
elseif starts_value(t) then
local r = unary_()
if not r then return nil end
v = v * r
else
break
end
end
return v
end
function expr()
local v = term()
while v do
local t = peek()
if not (t and t.kind == "op" and (t.v == "+" or t.v == "-")) then break end
pos = pos + 1
local r = term()
if not r then return nil end
v = t.v == "+" and v + r or v - r
end
return v
end
if #toks == 0 then return nil end
local v = expr()
if pos <= #toks then return nil end
return v
end
local function last() return sci.toks[#sci.toks] end
local function open_count()
local n = 0
for _, t in ipairs(sci.toks) do
if t.kind == "fn" or t.v == "(" then n = n + 1
elseif t.v == ")" then n = n - 1 end
end
return n
end
local function sci_show()
local text = expr_text()
local v = evaluate(sci.toks)
if sci.done then
sci_above:set(sci.done)
else
sci_above:set(text ~= "" and text or " ")
end
if v then
sci_shown:set(fmt(v))
elseif #sci.toks == 0 then
sci_shown:set("0")
end
-- Unfinished (3 + ): the last value stays up
end
-- After =, a number starts again; anything else goes on from the answer
local function sci_fresh(continuing)
if sci.done then
sci.toks = continuing and { { kind = "const", v = "ans", n = sci.ans } }
or {}
sci.done = false
end
end
local function ends_value(t)
return t and (t.kind == "num" or t.kind == "const" or t.kind == "post"
or t.v == ")")
end
local function sci_digit(d)
sci_fresh(false)
local t = last()
if t and t.kind == "num" then
if d == "." and t.v:find(".", 1, true) or #t.v >= 16 then
return
end
if t.v == "0" and d ~= "." then t.v = d
elseif t.v == "-" then t.v = d == "." and "-0." or "-" .. d
else t.v = t.v .. d end
else
sci.toks[#sci.toks + 1] = { kind = "num", v = d == "." and "0." or d }
end
sci_show()
end
local function sci_const(c)
sci_fresh(false)
sci.toks[#sci.toks + 1] = { kind = "const", v = c }
sci_show()
end
local function sci_op(o)
sci_fresh(true)
local t = last()
-- A minus may start a number; other operators need something before
if o ~= "-" and not ends_value(t) then
if t and t.kind == "op" then
t.v = o
sci_show()
end
return
end
if o == "-" and t and t.kind == "op" and t.v == "-" then
return
end
sci.toks[#sci.toks + 1] = { kind = "op", v = o }
sci_show()
end
local function sci_post(p)
sci_fresh(true)
if ends_value(last()) then
sci.toks[#sci.toks + 1] = { kind = "post", v = p }
sci_show()
end
end
-- A function after a number takes that number (9 √ is √(9)); otherwise
-- it opens its bracket for what's typed next
local function sci_fn(f)
sci_fresh(true)
local t = last()
if t and (t.kind == "num" or t.kind == "const") then
sci.toks[#sci.toks] = { kind = "fn", v = f }
sci.toks[#sci.toks + 1] = t
sci.toks[#sci.toks + 1] = { kind = "paren", v = ")" }
else
sci.toks[#sci.toks + 1] = { kind = "fn", v = f }
end
sci_show()
end
local function sci_paren(p)
sci_fresh(p == ")")
if p == ")" then
if open_count() <= 0 or not ends_value(last()) then
return
end
end
sci.toks[#sci.toks + 1] = { kind = "paren", v = p }
sci_show()
end
local function sci_equals()
if sci.done or #sci.toks == 0 then
return
end
for _ = 1, open_count() do
sci.toks[#sci.toks + 1] = { kind = "paren", v = ")" }
end
local v = evaluate(sci.toks)
if not v then
sci_shown:set("Not finished")
return
end
local text = expr_text()
remember(text .. " = " .. fmt(v))
if v == v and v ~= math.huge and v ~= -math.huge then
sci.ans = v
end
sci.done = text .. " ="
sci_show()
end
local function sci_clear()
sci.toks, sci.done = {}, false
sci_show()
end
local function sci_back()
if sci.done then
return sci_clear()
end
local t = last()
if not t then return end
if t.kind == "num" and #t.v > 1 then
t.v = t.v:sub(1, -2)
else
sci.toks[#sci.toks] = nil
end
sci_show()
end
-- CE: away with the number being typed
local function sci_clear_entry()
if sci.done then
return sci_clear()
end
local t = last()
if t and (t.kind == "num" or t.kind == "const") then
sci.toks[#sci.toks] = nil
end
sci_show()
end
local function sci_negate()
sci_fresh(true)
local t = last()
if t and t.kind == "num" then
t.v = t.v:sub(1, 1) == "-" and t.v:sub(2) or "-" .. t.v
if t.v == "" then sci.toks[#sci.toks] = nil end
elseif ends_value(t) then
-- A bracket, constant or x³: turn the whole of it round, −(…)
local i = #sci.toks
while i > 1 and sci.toks[i].kind == "post" do i = i - 1 end
if sci.toks[i].v == ")" then
local depth = 0
repeat
local k = sci.toks[i]
if k.v == ")" then depth = depth + 1
elseif k.kind == "fn" or k.v == "(" then depth = depth - 1 end
i = i - 1
until depth == 0 or i < 1
i = i + 1
end
table.insert(sci.toks, i, { kind = "paren", v = "(" })
table.insert(sci.toks, i, { kind = "op", v = "-" })
sci.toks[#sci.toks + 1] = { kind = "paren", v = ")" }
else
-- Nothing to turn round yet: the number typed next is negative
sci.toks[#sci.toks + 1] = { kind = "num", v = "-" }
end
sci_show()
end
-- The keys that Inv turns into their opposites
local INV = {
sin = { "sin", "sin⁻¹", "sin", "asin" }, cos = { "cos", "cos⁻¹", "cos", "acos" },
tan = { "tan", "tan⁻¹", "tan", "atan" }, ln = { "ln", "eˣ", "ln", "exp" },
log = { "log", "10ˣ", "log", "pow10" }, sqrt = { "√", "∛", "sqrt", "cbrt" },
}
local function inv_key(name)
return function()
local k = INV[name]
sci_fn(sci.inv and k[4] or k[3])
end
end
local function set_inv(on)
sci.inv = on
for name, b in pairs(sci_fn_buttons) do
b:set(on and INV[name][2] or INV[name][1])
end
end
local function scientific()
sci_shown = c8.label { text = "0", style = "header", align = "end" }
sci_above = c8.label { text = " ", color = "secondary", align = "end" }
local grid = c8.grid { columns = 5, column_spacing = 4, row_spacing = 4,
expand_columns = { 1, 2, 3, 4, 5 }, fill = true }
local function key(label, fn, opts)
local b = c8.button { label = label, fill = true, height = 44,
on_click = fn, primary = opts and opts.primary,
tooltip = opts and opts.tip }
grid:add(b)
return b
end
local inv
inv = c8.toggle_button { label = "Inv", fill = true, height = 44,
tooltip = "The opposite functions",
on_change = function(_, on) set_inv(on) end }
grid:add(inv)
sci_angle = key(sci.deg and "Deg" or "Rad", function()
sci.deg = not sci.deg
saved.degrees = sci.deg
keep()
sci_angle:set(sci.deg and "Deg" or "Rad")
if not sci.done then sci_show() end
end, { tip = "Angles in degrees or radians" })
key("C", sci_clear)
key("CE", sci_clear_entry)
key("⌫", sci_back)
sci_fn_buttons.sin = key("sin", inv_key("sin"))
sci_fn_buttons.cos = key("cos", inv_key("cos"))
sci_fn_buttons.tan = key("tan", inv_key("tan"))
key("π", function() sci_const("pi") end)
key("e", function() sci_const("e") end)
sci_fn_buttons.ln = key("ln", inv_key("ln"))
sci_fn_buttons.log = key("log", inv_key("log"))
key("x²", function() sci_post("sq") end)
key("xʸ", function() sci_op("^") end)
sci_fn_buttons.sqrt = key("√", inv_key("sqrt"))
key("n!", function() sci_post("!") end)
key("1/x", function() sci_fn("recip") end)
key("(", function() sci_paren("(") end)
key(")", function() sci_paren(")") end)
key("÷", function() sci_op("/") end)
key("x³", function() sci_post("cube") end)
key("7", function() sci_digit("7") end)
key("8", function() sci_digit("8") end)
key("9", function() sci_digit("9") end)
key("×", function() sci_op("*") end)
key("ʸ√x", function() sci_op("root") end, { tip = "The y-th root of x" })
key("4", function() sci_digit("4") end)
key("5", function() sci_digit("5") end)
key("6", function() sci_digit("6") end)
key("−", function() sci_op("-") end)
key("mod", function() sci_op("mod") end, { tip = "What's left over" })
key("1", function() sci_digit("1") end)
key("2", function() sci_digit("2") end)
key("3", function() sci_digit("3") end)
key("+", function() sci_op("+") end)
key("|x|", function() sci_fn("abs") end)
key("±", sci_negate)
key("0", function() sci_digit("0") end)
key(".", function() sci_digit(".") end)
key("=", sci_equals, { primary = true })
sci_show()
return c8.column { spacing = 8, fill = true, padding = { 0, 12, 0, 12 },
sci_above, sci_shown, c8.spacer { height = 4 }, grid }
end
local function sci_key(t, k)
if t and t:match("^[0-9.]$") then sci_digit(t)
elseif t == "," then sci_digit(".")
elseif t == "+" or t == "-" or t == "*" or t == "/" or t == "^" then sci_op(t)
elseif t == "(" or t == ")" then sci_paren(t)
elseif t == "!" then sci_post("!")
elseif t == "%" then sci_post("pct")
elseif t == "p" then sci_const("pi")
elseif t == "e" then sci_const("e")
elseif t == "s" then inv_key("sin")()
elseif t == "c" then inv_key("cos")()
elseif t == "t" then inv_key("tan")()
elseif t == "l" then inv_key("ln")()
elseif t == "g" then inv_key("log")()
elseif t == "r" then inv_key("sqrt")()
elseif t == "=" or k == "Return" or k == "KP_Enter" then sci_equals()
elseif k == "BackSpace" then sci_back()
elseif k == "Escape" then sci_clear()
elseif k == "Delete" then sci_clear_entry()
else
return false
end
return true
end
-- Converter ----------------------------------------------------------
-- Each unit is its size in the kind's first unit with a factor of 1;
-- temperatures are worked out apart
local KINDS = {
{ "Length", {
{ "Millimetres", 0.001 }, { "Centimetres", 0.01 }, { "Metres", 1 },
{ "Kilometres", 1000 }, { "Inches", 0.0254 }, { "Feet", 0.3048 },
{ "Yards", 0.9144 }, { "Miles", 1609.344 }, { "Nautical miles", 1852 } } },
{ "Weight", {
{ "Milligrams", 1e-6 }, { "Grams", 0.001 }, { "Kilograms", 1 },
{ "Tonnes", 1000 }, { "Ounces", 0.028349523125 }, { "Pounds", 0.45359237 },
{ "Stone", 6.35029318 }, { "US tons", 907.18474 } } },
{ "Temperature", {
{ "Celsius", "C" }, { "Fahrenheit", "F" }, { "Kelvin", "K" } } },
{ "Volume", {
{ "Millilitres", 0.001 }, { "Litres", 1 }, { "Cubic metres", 1000 },
{ "Teaspoons (US)", 0.00492892159375 },
{ "Tablespoons (US)", 0.01478676478125 },
{ "Fluid ounces (US)", 0.0295735295625 }, { "Cups (US)", 0.2365882365 },
{ "Pints (US)", 0.473176473 }, { "Gallons (US)", 3.785411784 },
{ "Pints (UK)", 0.56826125 }, { "Gallons (UK)", 4.54609 } } },
{ "Area", {
{ "Square centimetres", 1e-4 }, { "Square metres", 1 },
{ "Hectares", 1e4 }, { "Square kilometres", 1e6 },
{ "Square inches", 0.00064516 }, { "Square feet", 0.09290304 },
{ "Square yards", 0.83612736 }, { "Acres", 4046.8564224 },
{ "Square miles", 2589988.110336 } } },
{ "Speed", {
{ "Metres per second", 1 }, { "Kilometres per hour", 1 / 3.6 },
{ "Miles per hour", 0.44704 }, { "Feet per second", 0.3048 },
{ "Knots", 1852 / 3600 } } },
{ "Time", {
{ "Milliseconds", 0.001 }, { "Seconds", 1 }, { "Minutes", 60 },
{ "Hours", 3600 }, { "Days", 86400 }, { "Weeks", 604800 },
{ "Years (365 days)", 31536000 } } },
{ "Data", {
{ "Bits", 0.125 }, { "Bytes", 1 }, { "Kilobytes", 1e3 },
{ "Kibibytes", 2 ^ 10 }, { "Megabytes", 1e6 }, { "Mebibytes", 2 ^ 20 },
{ "Gigabytes", 1e9 }, { "Gibibytes", 2 ^ 30 }, { "Terabytes", 1e12 },
{ "Tebibytes", 2 ^ 40 } } },
{ "Energy", {
{ "Joules", 1 }, { "Kilojoules", 1000 }, { "Calories", 4.184 },
{ "Kilocalories", 4184 }, { "Watt hours", 3600 },
{ "Kilowatt hours", 3.6e6 }, { "BTUs", 1055.05585262 },
{ "Electron volts", 1.602176634e-19 } } },
{ "Power", {
{ "Watts", 1 }, { "Kilowatts", 1000 }, { "Horsepower", 745.69987158227 },
{ "BTUs per hour", 0.29307107017 } } },
{ "Pressure", {
{ "Pascals", 1 }, { "Kilopascals", 1000 }, { "Bars", 1e5 },
{ "Atmospheres", 101325 }, { "PSI", 6894.757293168 },
{ "Millimetres of mercury", 133.322387415 } } },
{ "Angle", {
{ "Degrees", 1 }, { "Radians", 180 / math.pi }, { "Gradians", 0.9 },
{ "Turns", 360 } } },
}
local function to_kelvin(u, v)
if u == "C" then return v + 273.15
elseif u == "F" then return (v - 32) * 5 / 9 + 273.15 end
return v
end
local function from_kelvin(u, v)
if u == "C" then return v - 273.15
elseif u == "F" then return (v - 273.15) * 9 / 5 + 32 end
return v
end
local function convert(units, from, to, v)
local a, b = units[from][2], units[to][2]
if type(a) == "string" then
return from_kelvin(b, to_kelvin(a, v))
end
return v * a / b
end
local function cfmt(n)
if n ~= n then return "–" end
return string.format("%.10g", n)
end
local function names(units)
local list = {}
for i, u in ipairs(units) do list[i] = u[1] end
return list
end
local function converter()
local conv = saved.converter or {}
saved.converter = conv
local kind = math.min(conv.kind or 1, #KINDS)
local units = KINDS[kind][2]
local from = math.min(conv.from or 3, #units)
local to = math.min(conv.to or (from == 1 and 2 or 1), #units)
local amount = conv.amount or "1"
local result = c8.label { text = " ", style = "header" }
local all
local entry, from_box, to_box
local function number()
local text = (entry and entry:get() or amount):gsub(",", ".")
return tonumber(text)
end
local function update()
local v = number()
result:set(v and cfmt(convert(units, from, to, v)) or "–")
all:count(#units)
all:redraw()
conv.kind, conv.from, conv.to = kind, from, to
conv.amount = entry and entry:get() or amount
keep()
end
entry = c8.entry { header = "From", text = amount, fill = true,
on_change = function() update() end }
from_box = c8.combo { items = names(units), selected = from, fill = true,
on_change = function(_, n)
from = n
update()
end }
to_box = c8.combo { items = names(units), selected = to, fill = true,
on_change = function(_, n)
to = n
update()
end }
local kinds = {}
for i, k in ipairs(KINDS) do kinds[i] = k[1] end
local kind_box = c8.combo { header = "Convert", items = kinds,
selected = kind, fill = true,
on_change = function(_, n)
kind, units = n, KINDS[n][2]
from, to = 1, 2
from_box:items(names(units), from)
to_box:items(names(units), to)
update()
end }
local swap = c8.button { label = "⇅ Swap", on_click = function()
local v = number()
from, to = to, from
from_box:set(from)
to_box:set(to)
-- The answer becomes what's converted, so swapping twice is no change
if v then
entry:set(cfmt(convert(units, to, from, v)))
end
update()
end }
-- What the number is in every unit of its kind; one picked is the To
all = c8.list { count = #units,
item = function(i)
local v = number()
return { title = v and cfmt(convert(units, from, i, v)) or "–",
subtitle = units[i][1] }
end,
on_open = function(_, i)
to = i
to_box:set(i)
update()
end }
local page = c8.row { spacing = 32, fill = true, expand = true,
narrow_vertical = true, narrow_spacing = 16,
c8.column { spacing = 12, width = 320, fill = true,
kind_box, entry, from_box, swap,
c8.label { text = "To", color = "secondary" },
result, to_box },
c8.column { spacing = 8, expand = true, fill = true,
c8.label { text = "In every unit", style = "subheader" },
c8.scroll { all, expand = true, fill = true } } }
update()
-- Room on the right for the scroll bar
return c8.scroll { c8.column { fill = true, padding = { 0, 12, 16, 12 },
page }, expand = true, fill = true }
end
-- The window ---------------------------------------------------------
local function on_tab(n)
saved.tab = n
keep()
-- The history is for working things out, not converting
side.hidden = n == 3
end
local function build()
history_list = c8.list {
count = #history,
item = function(i) return { title = history[i] } end,
on_open = function(_, i)
local r = history[i]:match("= (.*)$") or "0"
if not tonumber(r) then return end
if tabs:get() == 2 then
sci_fresh(false)
local t = last()
if ends_value(t) then
sci.toks[#sci.toks + 1] = { kind = "op", v = "*" }
end
sci.toks[#sci.toks + 1] = { kind = "num", v = r }
sci_show()
else
std.entry, std.fresh = r, true
std_show()
end
end,
}
-- The history goes when the window is narrow (the keys need the room)
-- and on the Converter. Two boxes: the narrow setter would show a
-- box hidden by hand again as the window widens
side = c8.column { spacing = 12, width = 300, fill = true, expand = true,
padding = { 28, 0, 0, 0 },
c8.label { text = "History", style = "subheader" },
c8.scroll { history_list, expand = true, fill = true },
c8.link { label = "Clear history", on_click = function()
for i = #history, 1, -1 do history[i] = nil end
keep()
history_list:count(0)
end },
}
tabs = c8.pivot { expand = true, fill = true,
on_change = function(_, n) on_tab(n) end,
tabs = {
{ title = "Standard", widget = standard() },
{ title = "Scientific", widget = scientific() },
{ title = "Converter", widget = converter() },
} }
local tab = saved.tab or 1
if tab ~= 1 then
tabs:set(tab)
end
side.hidden = tab == 3
-- Smaller margins narrow: the box changes them by itself
return c8.column { padding = { 28, 20, 0, 24 },
narrow_padding = { 12, 8, 12, 16 },
c8.row { expand = true, fill = true, tabs,
c8.column { fill = true, narrow_hidden = true, side } } }
end
local function on_key(_, ev)
if ev.ctrl or ev.alt then
return false
end
local n = tabs:get()
if n == 1 then return std_key(ev.text, ev.key)
elseif n == 2 then return sci_key(ev.text, ev.key) end
return false
end
c8.app {
id = "org.cont8nuum.Calculator",
open = function()
if not (win and win.open) then
win = c8.window { title = "Calculator", width = 880, height = 720,
build(), on_key = on_key }
end
win:present()
end,
}