23 kB 336 lines
5e0408d4
⋯
toolkit/lua/README.md
download raw history
at main Markdown

c8-lua #

Apps and live tiles for cont8nuum, written in Lua 5.4. No build step: a script, and c8-lua to run it.

c8-lua-new app org.example.Notes "Notes"   # an app, added to All apps
c8-lua-new tile my-tile "My tile"          # a live tile, added to Live tiles

Each makes a folder in ~/.local/share/c8-lua/ with a script to change. examples/ has more to read: hello/ (the smallest app), demo.lua (a tour: controls, a list, drawing, commands, the charms) and load-tile.lua (a tile), and gallery.lua, c8ui's gallery page for page (every widget there is). Whole apps, small enough to read in a sitting, are in apps/ (installed in share/c8-lua/apps/): Calculator, Clock, Notes, Text editor (plain text and RTF, a Markdown preview), and the games Mines, Merge and Reversi (drawn on a canvas).

An app #

local c8 = require "c8"

local win

c8.app {
	id = "org.example.Hello",
	open = function(files)
		if not (win and win.open) then
			local hello = c8.label { text = "Hello", style = "header" }
			win = c8.window { title = "Hello",
				c8.column { spacing = 24, padding = 40,
					hello,
					c8.button { label = "Press me", primary = true,
						on_click = function() hello:set("Hello from Lua") end },
				},
			}
		end
		win:present()
	end,
}

c8-lua main.lua [FILE...] runs it. One copy runs: a second launch hands its files to the first, whose open runs again, and exits.

c8.app { ... } takes:

id A name with a dot in it, org.example.Notes. The same as the .desktop file's name and its StartupWMClass
open(files) Every launch. files is a list of URIs (may be empty). Make the window if there is none, then win:present()
startup(), shutdown() Once, before the first open and after the last window closed
search(query), result(id, query) The Search charm: return a list of { id, title, subtitle, icon }; result opens the one picked
settings The Settings charm: a list of { id, label, build = function(page) end } (a page of controls) and { id, label, action = function() end }
wake(tag, due) A wake the app booked with c8.wake is due (below)

A settings page is filled with page:toggle { id, label, on, on_change }, page:choice { id, label, items, selected, on_change } (buttons = true for side by side), page:slider { id, label, min, max, step, value, on_change }, page:text { id, label, text, on_change }, page:button { id, label, on_click }, page:link, page:heading "..." and page:paragraph "...". on_change gets the new value. c8.settings_changed(id) builds a page again.

c8.quit() ends the app. c8.dir is the folder the script is in, c8.args the arguments after it.

Windows #

c8.window { title, width, height, widget, on_resize, on_key, on_close, can_close }

win:set(widget) What the window shows (the old one is destroyed)
win:present() Bring it forward
win.open, win.width, win.height, win.narrow Whether it's still there; its size; under 600 wide
win:set_title(text), win:close(), win:fullscreen(on)
on_resize(win, width, height, narrow) The size changed: for sizes that follow the width (a list's cells), not for building the page again
on_key(win, event) A key nothing took. Return true if used
can_close(win) Closed from outside (Alt+F4): return false to keep the window, ask about unsaved work, then win:close(), which doesn't ask
win:dialog { title, message, buttons = { "Yes", "No" }, done = function(choice) end } A question. choice is the button's number, nil for Escape. A widget in the table goes above the buttons
win:message(title, text) Something to tell
win:menu { items = { ... }, at = widget, done = function(choice) end } A menu under a widget (or at x, y; above = true over it). An item is "Cut", "-" (a line) or { "Word wrap", id = 10, check = true, checked, radio, disabled, shortcut = "Ctrl+W", submenu = { ... } }. choice is the item's id, or its number in reading order (submenus too, from 1) when it has none; nil when dismissed
win:flyout { at = widget, widget, closed = function() end } A box by a widget; :close()
win:open_file { title, multiple, folder, filters = { { name, patterns = "*.png;*.jpg", types = "image/*" } }, done = function(uris) end } The file picker; uris is nil when cancelled. win:save_file { name = "new.txt", ... }
win:settings { title, widget, wide, closed = function() end } The app's settings sliding in from the right, as the Settings charm's pages do
win:appbar() The app bar (the Menu key shows it): bar:add { icon, label, right, toggle, on_click } (toggle = false makes a command that stays down: cmd:get()), bar:show() toggles, bar:show(bool)
win:navbar() The bar of places at the top: bar:place(label [, icon]) returns its number, bar:set(n) marks the current one, bar:show() toggles, bar:colors(bar, tile); bar.on_choose = function(bar, n) end
win:open_uri(uri) Open a file or a link in its app
win:copy(text), win:paste(function(text) end) The clipboard

Every app must work snapped to a quarter of the screen (about 474 px wide). Build each page once and let it reflow: say what changes when the window is narrow (narrow_padding, narrow_spacing, narrow_vertical, narrow_style, narrow_hidden, a hub's narrow_column) and the widgets change by themselves, both ways, as the window crosses 600 px. c8.pages goes one page at a time, a split stacks and a hub becomes a pivot without being asked. Keep on_resize for sizes (a list's cell width), never for building again.

Widgets #

Each is made from one table. In a container the table's list is its children.

Every widget takes these, and they can be set later (w.hidden = true): hidden, disabled, fill (stretch across), expand (take what's left along), align ("start", "center", "end"), width, height, min_width, max_width, narrow_hidden (hidden while the window is narrow, shown again when it isn't), tooltip, scheme ("light", "dark"), background, tilts (sinks in where it's pressed and springs back, as Metro's tiles do: for something pressed as a whole, such as a canvas that takes presses; lists do it by themselves, buttons don't), on_destroy.

Every widget has w:add(child, ...), w:clear() (destroys the children), w:destroy(), w:focus(), w:redraw(), w:get() and w:set(value) for what it holds, w:count_children(), w:enter() (slides in from the right like a Metro page), w:colors() (fg, bg, accent, secondary, dark where it's drawn: for colours written into markup), w:rect() (x, y, width, height in the window, as last laid out), and w.alive. Anything else you set on one is yours (row.note = note).

A widget that has been destroyed (its page was left, its window closed) does nothing and returns nothing when used, so an answer that comes late needs no check.

c8.column { spacing, padding, ... }, c8.row { ..., wrap } Children one under another, or side by side. padding is a number or { left, top, right, bottom }; :padding(n) or :padding(left, top, right, bottom) changes it. Narrow: narrow_padding, narrow_spacing, narrow_vertical = true (a row that goes down when narrow), and :narrow_padding(...), :narrow_spacing(n), :narrow_vertical(bool)
c8.scroll { widget, horizontal, vertical, narrow_horizontal, narrow_vertical } Scrolls one widget. Give it expand = true. The narrow_ pair are its ways when narrow (an article across wide, down narrow). Inside a scroll that goes down it doesn't scroll down itself: it's as tall as what it holds. :scroll_to(y), :scroll_to_x(x), :offset() (x, y)
c8.grid { columns, column_spacing, row_spacing, column_widths = { 120, 0 }, expand_columns = { 2 }, ... } Rows of columns. :span(child, n) adds one across n columns
c8.split { first, second, position, share, vertical, min = { a, b } } Two panes and a bar to drag between; side by side ones go one over the other by themselves when narrow. share = 0.5: the first pane keeps that part of the room as the window changes, instead of position px (a drag keeps the new proportion; :share() reads it, :share(n) sets it). :vertical(bool); get/set the position
c8.flip { dots, ... } One child at a time, flipped sideways (a flip view). on_change(w, n)
c8.zoom { detail, overview, on_change } Semantic zoom: Ctrl+wheel, Ctrl+minus or a pinch goes out to overview. :show(widget) zooms in to a widget of detail; on_change(w, out)
c8.viewbox { widget, grow } Scales one widget down to the room it's given (up too with grow)
c8.item { widget, tap, selectable, selected, on_invoke, on_select } A frame that selects (tap = "select"), invokes ("invoke") or neither ("none") whatever is in it. on_select(w, selected)
c8.stack { ... } One child at a time: :set(n), :push(page), :pop()
c8.pages { title, pages = { "One", "Two" }, build = function(content, index, pages) end } PC settings' layout: a list of pages beside the chosen one. build adds to content. :set(n), :rebuild(), :back(), :sub(title) (a page over the page), :narrow() (whether it shows one at a time: it folds by itself)
c8.hub { title, background, narrow_column, sections = { { header, name, width, widget } } } Sections side by side, scrolled sideways (Metro's panorama). Narrow it turns into a pivot of its named sections (name for one whose header is a widget), or with narrow_column = true into one column going down. background is a picture (c8.picture) behind the whole hub, panning slower than the sections; hub.background = pic or nil changes it later. Text keeps the scheme, so a dark picture wants scheme = "dark". :title(text), :show(n) pans to section n
c8.pivot { title, wrap, tabs = { { title = "One", widget } }, on_change } Tabs. The widget can also be given as widget = w. title: a small line in capitals over the headers (the app's name); wrap = true: the headers go round, the selected one first, as Windows Phone's. :title(text or nil), :wrap(bool) change them
c8.expander { title, expanded, widget } A title that shows or hides what's under it
c8.spacer { width, height }, c8.separator {}
c8.label { text, style, narrow_style, color, lines } style: header, subheader, title, item, body, strong, caption; narrow_style the one when narrow. color: primary, secondary, accent. c8.label "Words" works too. :style(name), :narrow_style(name), :color(name) change them
c8.rich { markup, family, size, justify, line_spacing, color, on_link } Text with Pango markup (<b>, <i>, <span ...>, and <a href="..."> for a link: underlined, in the accent colour; on_link(w, uri) hears a click on one). c8.rich_columns { markup, column_width, gap } lays it out in columns across (give it a height, put it in a sideways scroll); c8.rich_overflow {} is a box for what didn't fit: first:overflow(second)
c8.button { label, primary, on_click }, c8.link { label, on_click }
c8.icon_button { icon, label, toggle, on_click }, c8.back_button { on_click } Round buttons. Alt+Left presses the back button. toggle makes one that stays down
c8.toggle_button { label, on, on_change }, c8.repeat_button { label, on_click } A button that stays down; one that clicks again and again while held
c8.toggle { header, on, on_change }, c8.checkbox { label, checked, on_change } on_change(w, on)
c8.slider { header, min, max, step, value, digits, unit, on_change } on_change(w, value, dragging)
c8.entry { header, text, placeholder, password, search, enter_only, on_enter, on_change } One line. on_enter(w, text), on_change(w, text); :suggest { ... }
c8.text { text, editable, wrap, framed, monospace, placeholder, accepts_tab, rich, on_change, on_move } Many lines. :insert(text) (over the selection), :modified() (:modified(false) after saving), :position() (line, column), :selection() and :select(first, last) (bytes from 1, as string.sub takes them), :find(text, backwards, match_case), :replace_all(text, with, match_case) (how many), :undo(), :redo(), :wrap(bool), :font(family, size). on_move(w): the caret moved. accepts_tab = false: Tab moves on, as in a form. Rich text below
c8.number { header, min, max, step, value, digits, on_change } A number with − and +
c8.rating { max, value, readonly, on_change } Stars
c8.date { header, year, month, day, first_year, last_year }, c8.time { header, hour, minute, clock24, minute_step } Pickers (today and now unless given). get gives year, month, day or hour, minute; on_change gets them too
c8.calendar { year, month, day, marks = function(y, m, d) end, on_change, on_month } A month to pick a day from; marks returns true for a dot under a day
c8.nav { items, selected, menu, on_change } The list of pages down the side. :menu(bool): a narrow page list (arrows move, Enter opens)
c8.tree { on_expand, on_select, on_open, on_context } Folders that open. :add(parent, label [, icon]) returns an item (the top's parent is 0), :remove(item), :clear([item]), :label(item [, text]), :parent(item), :expanded(item [, bool]), :has_children(item [, bool]). The callbacks get the item; get gives the selected one. Fill a folder in on_expand
c8.columns { columns = { { "Name", 220 }, ... }, sort, descending, on_change } Column headers to click for sorting: on_change(w, column, descending). :width(column, px). A list given columns = it draws cells under them
c8.transport { duration, buffered, skip, fullscreen, on_action } Media controls. on_action(w, "play" | "pause" | "previous" | "next" | "seek" | "volume" | "mute" | "fullscreen", value); the app answers with :playing(bool), :position(s), :duration(s), :buffered(0..1), :volume(v, muted), :fullscreen(bool). :live() is true while the seek bar is dragged
c8.combo, c8.choice, c8.radio { header, items, selected, on_change } One of several. on_change(w, number)
c8.progress { value }, c8.ring { active } value 0 to 1; left out, it doesn't know how far
c8.infobar { severity, title, message, closable, on_close } severity: info, success, warning, error. :action(label, fn)
c8.image { image, width, height, fit } A picture from c8.picture(path [, max])
c8.list { ... }, c8.canvas { ... } Below

Rich text #

c8.text { rich = true } keeps a format for every run of its text. A format is a table: family, size (points), color, bold, italic, underline, strike. :format() is what typing would get now (for a bar of buttons, with on_move); :format { bold = true } sets what it names on the selection, as one step to undo, or with nothing selected on what is typed next (false takes a family, size or colour away). :runs() is the text as a list of formats, each with its text, for saving; :append(text, format) adds to the end without undo, for reading a document in after :set(""). :rich(bool) turns it on or off (the text stays, its formats and undo go). Reading and writing a file format is the app's: apps/editor/rtf.lua does RTF.

Lists #

For many items: only those in sight are asked for. Put it in a scroll.

local rows = c8.list {
	count = #notes,
	item = function(i)
		return { title = notes[i].title, subtitle = notes[i].date,
			icon = "text-x-generic" }
	end,
	on_open = function(list, i) show(notes[i]) end,
}

grid = true makes cells (item_width, item_height); spans = function(i) return columns, rows end makes cells of several sizes, as Start's tiles. rows:mode("rows" | "grid" | "spans", width, height) changes it later. item may return { cells = { "Name", { "Type", secondary = true } } } to draw under a c8.columns given as columns. rows:count(n) when the items changed, rows:redraw([i]) when they look different, rows:get() the one selected, rows:is_selected(i), rows:reveal(i) scrolls it into sight. on_select(list, i), on_context(list, i, x, y) (a right click or a hold), multiple, click_opens = false (a double click opens).

To draw the items yourself give draw = function(g, item) end in place of item: item has index, x, y, width, height, selected, hovered, pressed, fg. rows:select_all(bool), rows:selected_count(). With keep = true each item is drawn once and kept as pixels (for pictures); x, y are then 0.

Drawing #

c8.canvas { width, height, draw = function(g, x, y, width, height) end, on_event = function(w, event) end }. g is only good inside draw. Colours are 0xRRGGBB or "#rrggbb"; left out, the text colour.

g:rect(x, y, w, h, color, alpha), g:frame(x, y, w, h, color, alpha, thickness) Filled, outlined
g:line(x1, y1, x2, y2, color, alpha, thickness), g:circle(cx, cy, r, color, alpha)
g:text(text, x, y, { style, size, weight, color, alpha, width, lines }) Returns the height. width wraps or cuts short
g:text(text, x, y, { ..., family }) family for a font of its own. baseline = true puts y on the baseline (cairo's own text, family "sans-serif" unless given) and returns the width
g:measure(text, { ... }) Width and height
g:shape({ x1, y1, x2, y2, ... }, color, alpha), g:paint(color, alpha) A filled polygon; the whole of it
c8.gradient(x1, y1, x2, y2, { { 0, color [, alpha] }, { 1, color } }) A gradient, to give anywhere a colour goes
c8.draw_picture(width, height, function(g) end) Draws a picture once, for c8.image, g:image or a hub's background
g:icon(name, x, y, size), g:image(picture, x, y, w, h, "cover" or "fit" or "stretch")
g.fg, g.bg, g.accent, g.dark The colours where it draws

Draw nothing slow: a draw runs for every frame of a scroll. Events are tables: type (press, release, motion, scroll, key, ...), x, y, button, dx, dy, key ("Escape", "Return", "a"), text, ctrl, shift, alt, super.

Under the UI #

Nothing waits: answers come to a function, later.

c8.after(seconds, fn), c8.every(seconds, fn) Timers; :cancel(). every stops when fn returns false
c8.now() Seconds on a clock that only goes forward, for measuring time
c8.http({ url, method, body, token, accept, dest }, function(status, body) end) Through curl. https only. A table body goes as JSON; dest downloads to a file. status 0: not reached. c8.http(url, fn) for a plain GET
c8.json.decode(text), c8.json.encode(value) A null in a list is c8.null; in an object it is left out
c8.run({ "name", "arg" }, function(status, out, err) end) A command. { input = text } as the second argument feeds it
c8.save(name, value), c8.load(name) Settings kept as ~/.config/cont8nuum/NAME.json
c8.picture(path [, max]) A picture file, for c8.image and g:image; pic:size() gives width and height. nil and why when it can't be read
c8.tile.update(id, fields), c8.tile.badge(id, text), c8.tile.clear(id) The app's own live tile (its id is the app's). A tag in fields makes it one of several updates taking turns; c8.tile.remove(id, tag) drops one

The whole of Lua's standard library is there too (io, os, string, utf8, ...), and require finds other .lua files beside the script. C modules aren't supported.

A live tile #

local c8 = require "c8"

c8.provider {
	tile = c8.args[1] or "my-tile",
	every = 60,
	update = function()
		return { template = "text", heading = "Now", text1 = os.date("%H:%M") }
	end,
}

The shell runs it for the tile, from a .widget file in ~/.local/share/cont8nuum/widgets/:

[Widget]
Name=My tile
Category=Mine
Provider=c8-lua /path/to/tile.lua %i
Size=medium
TryExec=c8-lua

update runs at the start, every every seconds (hidden_every while Start isn't showing, when given) and when the shell starts again. It returns the fields to show (those of c8tile: template, heading, text1..., block, image, color, expires, wide.FIELD, and badge), or a list of them to take turns. For an answer that comes later (c8.http), return nothing and call c8.tile.update(id, fields) when it's there. The provider leaves by itself when the tile is unpinned or the shell goes. After changing the script: c8tile restart ID.

In the background #

An app needn't run to do something later. It books a time with c8.wake, and the shell starts it then, for a moment, without a window: open isn't called, wake is. That is the place for a toast, the tile, and booking the next wake; nothing of the app runs in between.

c8.app {
	id = "org.example.Tea",
	open = function()
		-- ...a button that does:
		c8.wake.at("tea", os.time() + 4 * 60)
	end,
	wake = function(tag, due)
		c8.notify { title = "Tea's ready" }
	end,
}
c8.wake.at(tag, time [, every]) At time (as os.time() gives it), then every every seconds when given (60 or more). The same tag again moves it
c8.wake.every(tag, seconds [, first]) Every so often, the first seconds from now unless first says
c8.wake.cancel(tag)
c8.notify { title, body, icon, urgent } A toast in the app's colour; a click opens the app

A tag is the app's own name for the wake (letters, digits, -, _, .). A wake goes once and is then forgotten; book another from wake if you want one. Wakes are kept by the shell and outlive the app and logging out; one missed while the PC was off comes when it's next on, late (due says when it was meant for). If the app is running when a wake comes, its wake runs there instead, and the window stays.

Started for a wake, the app quits when wake returns, so a toast or a tile sent from it still goes. For an answer that comes later (c8.http), return true and call c8.wake.done() when finished; it quits after 30 seconds either way unless it opened a window. c8.wake works from the app's functions, not the script's first run.

Not there yet #

Drag and drop, thumbnails, more than text on the clipboard, curves in g. Say what you miss.