Jive Lua source code conventions
From SqueezeboxWiki
Squeezeplay Coding Styleguide
Jive Code Style Guide
This document describes the conventions used in the Jive Lua source code. Coherence has more value than minimal improvements in readability, so all developers should strive to check in code that adheres to these guidelines when appropriate.
Code lay-out
Indentation
Use TABs to indent the code. Tabs worth 4 spaces work best.
Do NOT use tabs to make columns (for example, when aligning = signs). This just breaks on everyone else's terminal. Use spaces instead.
local oo......spaces...= require("loop.simple") local table...spaces...= require("table")
Line Length
No maximum value is provided, but long lines should be broken up at natural boundaries. With Lua you can pretty much break the line wherever you want, no special line continuation mark is required.
menuItem:addListener(EVENT_ACTION, function() local window, r = self:openWindow(appletName, method, menuItem, unpack(args)) return r end )
Blank Lines
Separate functions by 2 blank lines, and use 2 blank lines to distinguish any group (like between requires and module(...), or from the last function in the file to the Logitech license at the end of the file)
Use blank lines in functions to indicate logical sections.
Encodings
Code files should use UTF-8.
requires
Modules should require what they need from global space before the module(...) declaration. First copy global functions from Lua:
local pairs, ipairs = pairs, ipairs
then any Lua or external module:
local debug = require("debug") local socket = require("socket")
then Jive modules/classes:
local Window = require("jive.ui.Window")
ending with the log if used:
local log = require("jive.utils.log").logger("ui")
finally, Jive globals or identifiers:
local EVENT_UNUSED = jive.ui.EVENT_UNUSED local jnt = jnt
Identifiers
General convention
Identifiers (for variables, functions and methods) start with a lower case letter and words are concatenated using a capital letter.
function getSelected() local likeThisConvention
Private variables and functions
Lua has very few privacy restrictions. Instance variables of objects, for example, can be easily accessed the outside of the objet code. Functions and variables starting with an underscore denote privacy, they should not be used outside of the core code that uses it.
local _privateVariable local function _doTheWork()
In general, identifiers starting with an underscore should be declared local.
Threads
Jive uses a separate thread for networking I/O. Functions and variables with are designed to be called from code running in the network thread use a prefix of t_. Mutual exclusion should be addressed when using or writing code identified as network thread side.
function t_getHeaders()
jive.Applet
jive.Applet
jive.Applet - The applet base class.
DESCRIPTION
jive.Applet is the base class for all Jive applets. In Jive, applets are very flexible in the methods they implement; this class implements a very simple framework to manage localization, settings and memory management.
FUNCTIONS
self:init()
Called to initialize the Applet.
In the object __init method the applet settings and localized strings are not available.
self:free()
This is called when the Applet will be freed. It must make sure all data is unreferenced to allow for garbage collection. The method should return true if the applet can be freed, or false if it should be left loaded into memory. The default return value in jive.Applet is true.
self:tieWindow(window)
Tie the window to this applet. When all tied windows are poped from the window stack then this applet is freed.
self:tieWindow(window, ...)
Tie the window to this applet, and then show the window. When all tied windows are poped from the window stack then this applet is freed. The varargs are passed to the windows show() method.
jive.Applet:setSettings(settings)
Sets the applet settings to settings.
jive.Applet:getSettings()
Returns a table with the applet settings
jive.Applet:string(token)
Returns a localised version of token
jive.AppletManager
jive.AppletManager
jive.AppletManager - The applet manager.
DESCRIPTION
The applet manager discovers applets and loads and unloads them from memory dynamically.
SYNOPSIS
TODO
FUNCTIONS
jive.AppletManager.getAppletInstance(appletName)
Returns the loaded instance of applet appletName, if any.
jive.AppletMeta
jive.AppletMeta
jive.AppletMeta - The applet meta base class.
DESCRIPTION
This is a base class for the applet meta, a small class that is loaded at boot to perform (a) versioning verification and (b) hook the applet into the menu system or whatever so that it can be accessed and loaded on demand.
FUNCTIONS
self:jiveVersion()
Should return the min and max version of Jive supported by the applet. Jive does not load applets incompatible with itself. Required.
self:registerApplet()
Should register the applet as a screensaver, or add it to a menu, or otherwise do something that makes the applet accessible or useful. If the meta determines the applet cannot run in the current environment, it should simply not register the applet in anything. Required.
self:configureApplet()
Called after all applets have been registered, this can be used to configure the applet.
self:defaultSettings()
Returns a table with the default settings for this applet, or nil if not settings are used.
self:upgradeSettings()
Returns a table with the upgraded settings for this applet, or the existing settings
self:getSettings()
Returns the settings for this applet.
Convenience method that returns a MenuItem to be used in the SimpleMenu to open an applet. label is a string token, and closure is the function executed when the MenuItem is selected.
jive.audio.Playback
jive.Iconbar
jive.Iconbar
jive.Iconbar - icon raw at the bottom of the screen
DESCRIPTION
The Iconbar class implements the Jive iconbar at the bottom of the screen. It refreshes itself every second.
SYNOPSIS
-- Create the iconbar (this done for you in JiveMain) iconbar = Iconbar() -- Update playmode icon iconbar:setPlaymode('stop') -- force iconbar update iconbar:update()
FUNCTIONS
Iconbar:setPlaymode(val)
Set the playmode icon of the iconbar. Values are nil (off), "stop", "play" or "pause".
Iconbar:setPlaylistMode(val)
Set the playlistmode of the iconbar. Values are nil (no mode), 1 for playlist mode and 2 for party mode. When not 1 or 2, setRepeat()
Iconbar:setRepeat(val)
Set the repeat icon of the iconbar. Values are nil (no repeat), 1 for repeat single track and 2 for repeat all playlist tracks.
Iconbar:setShuffle(val)
Set the shuffle icon of the iconbar. Values are nil (no shuffle), 1 for shuffle by track and 2 for shuffle by album.
Iconbar:setBattery(val)
Set the state of the battery icon of the iconbar. Values are nil (no battery), CHARGING, AC or 0-4.
Iconbar:setWirelessSignal(val)
Set the state of the network icon of the iconbar. Values are nil (no network), ERROR or 1-3.
Iconbar:setServerError(val)
Set the state of the SqueezeCenter connection. Values are nil, OK or ERROR.
Iconbar:update()
Updates the iconbar.
Iconbar()
Creates the iconbar.
jive.JiveMain
jive.JiveMain
jive.JiveMain - Main Jive application.
DESCRIPTION
TODO
SYNOPSIS
TODO
FUNCTIONS
JiveMainMenu notifies any change with mainMenuUpdate
jive.net.Comet
jive.net.Comet
jive.net.Comet - An HTTP socket that implements the Cometd Bayeux protocol.
DESCRIPTION
This class implements a HTTP socket running in a jive.net.NetworkThread.
SYNOPSIS
-- create a Comet socket to communicate with http://192.168.1.1:9000/ local comet = jive.net.Comet(jnt, "192.168.1.1", 9000, "/cometd", "slimserver") -- subscribe to an event -- will callback to func whenever there is an event -- playerid may be nil comet:subscribe('/slim/serverstatus', func, playerid, {'serverstatus', 0, 50, 'subscribe:60'}) -- unsubscribe from an event comet:unsubscribe('/slim/serverstatus', func) -- or unsubscribe all callbacks comet:unsubscribe('/slim/serverstatus') -- send a non-subscription request -- playerid may be nil -- request is a table (array) containing the raw request to pass to SlimServer comet:request(func, playerid, request) -- add a callback function for an already-subscribed event comet:addCallback('/slim/serverstatus', func) -- remove a callback function comet:removeCallback('/slim/serverstatus', func) -- start! comet:connect() -- disconnect comet:disconnect() -- batch a set of calls together into one request comet:startBatch() comet:subscribe(...) comet:request(...) comet:endBatch()
FUNCTIONS
jive.net.Comet(jnt, ip, port, path, name)
Creates A Comet socket named name to interface with the given jnt (a jive.net.NetworkThread instance). name is used for debugging and defaults to "".
Notifications:
cometConnected(self) cometDisconnected(self)
jive.net.CometRequest
jive.net.CometRequest
jive.net.CometRequest - A Comet request over HTTP.
DESCRIPTION
jive.net.CometRequest encapsulates a Comet HTTP request over POST HTTP. It is a subclass of jive.net.RequestHttp.
Note the implementation uses the source and sink concept of luasocket.
SYNOPSIS
-- create a sink to receive the JSON response local function mySink(chunk, err) if err then print("error!: " .. err) elseif chunk then print("received: " .. chunk.id) end end -- create a CometRequest, passing in the full URI and data to encode into JSON local req = CometRequest(mySink, uri, data) -- use a Comet socket to fetch comet:fetch(myRequest)
FUNCTIONS
jive.net.CometRequest(sink, uri, data, options)
Creates a CometRequest. Parameters:
sink : a main thread sink that accepts a table built from the JSON data returned by the server
uri : the URI of the Comet service
data : data to encode as JSON in the request
options : options to pass to jive.net.RequestHttp
jive.net.DNS
jive.net.DNS
jive.net.DNS - non-blocking dns queries.
DESCRIPTION
Implements non-block dns queries using the same api a luasocket. These functions must be called in a Task.
--]]
local assert = assert
local oo = require("loop.base") local table = require("table") local string = require("string")
local Framework = require("jive.ui.Framework") local Task = require("jive.ui.Task")
local debug = require("jive.utils.debug") local log = require("jive.utils.log").logger("net.socket")
local jive_dns = require("jive.dns")
-- jive.net.DNS is a base class module(..., oo.class)
-- singleton instance local _instance = false
function __init(self, jnt) if _instance then return _instance end
local obj = oo.rawnew(self, {}) obj.sock = jive_dns:open() obj.dnsQueue = {} jnt:t_addRead(obj.sock, Task("DNS", obj, function() while true do Task:yield(false) -- read host entry local hostent, err = obj.sock:read() -- wake up requesting task local task = table.remove(obj.dnsQueue, 1) if task then task:addTask(hostent, err) end end end), 0) -- no timeout _instance = obj return obj
end function isip(self, address) -- XXXX crude check return string.match(address, "%d+%.%d+%.%d+%.%d+") end
-- Converts from IP address to host name. See socket.dns.tohostname. function tohostname(self, address) local task = Task:running() assert(task, "DNS:tohostname must be called in a Task")
-- queue request _instance.sock:write(address) -- wait for reply table.insert(_instance.dnsQueue, task) local _, hostent, err = Task:yield(false) if err then return nil, err else return hostent.name, hostent end
end -- Coverts from host name to IP address. See socket.dns.toip. function toip(self, address) local task = Task:running() assert(task, "DNS:toip must be called in a Task")
-- queue request _instance.sock:write(address) -- wait for reply table.insert(_instance.dnsQueue, task) local _, hostent, err = Task:yield(false) if err then return nil, err else return hostent.ip[1], hostent end
end
jive.net.HttpPool
jive.net.HttpPool
jive.net.HttpPool - Manages a set of HTTP sockets.
DESCRIPTION
This class manages 2 queues of a requests, processed using a number of HTTP sockets (see jive.net.SocketHttp). The sockets are opened dynamically as the queue size grows, and are closed once all requests have been serviced.
SYNOPSIS
-- create a pool for http://192.168.1.1:9000 -- with a max of 4 connections, threshold of 2 requests local pool = HttpPool(jnt, "192.168.1.1", 9000, 4, 2, 'slimserver'), -- queue a request pool:queue(aRequest)
FUNCTIONS
jive.net.HttpPool(jnt, name, ip, port, quantity, threshold, priority)
Creates an HTTP pool named name to interface with the given jnt (a jive.net.NetworkThread instance). name is used for debugging and defaults to "". ip and port are the IP address and port of the HTTP server.
quantity is the maximum number of connections to open, depending on the number of requests waiting for service. This is controlled using the threshold parameter which indicates the ratio of requests to connections. For example, if threshold is 2, a single connection is used until 2 requests are pending, at which point a second connection is used. A third connection will be opened as soon as the number of queued requests reaches 6. priority identifies the pool for processing at lower priority.
jive.net.HttpPool:free()
Frees the pool, close and free all connections.
jive.net.HttpPool:close()
Close all connects to the server.
jive.net.HttpPool:queue(request)
Queues request, a jive.net.RequestHttp instance. All previously queued requests will be serviced before this one.
tostring(aPool)
if aPool is a jive.net.HttpPool, prints HttpPool {name}
jive.net.NetworkThread
jive.net.NetworkThread
jive.net.NetworkThread - thread for network IO
DESCRIPTION
Implements a separate thread (using luathread) for network functions. The base class for network protocols is Socket. Messaging from/to the thread uses mutexed queues. The queues contain functions executed once they leave the queue in the respective thread. The network thread queue is polled repeatedly. The main thread queue shall serviced by the main code; currently, an event EVENT_SERVICE_JNT exists for this purpose.
FIXME: Subscribe description
SYNOPSIS
-- Create a NetworkThread (done for you in JiveMain stored in global jnt) jnt = NetworkThread() -- Create an HTTP socket that uses this jnt local http = SocketHttp(jnt, '192.168.1.1', 80)
FUNCTIONS
getUUID()
Returns the UUID and Mac address of this device.
setUUID(uuid, mac)
Sets the UUID and Mac address of this device.
getSNHostname()
Retreive the hostname to be used to connect to SqueezeNetwork
arp(host)
Look up hardware address for host. This is async and the sink function is called when the hardware address is known, or with an error.
__init()
Creates a new NetworkThread. The thread starts immediately.
jive.net.Process
jive.net.RequestHttp
jive.net.RequestHttp
jive.net.RequestHttp - An HTTP request.
DESCRIPTION
jive.net.RequestHttp implements an HTTP request to be processed by a jive.net.SocketHttp.
SYNOPSIS
-- create a sink to receive XML local function sink(chunk, err) if err then print("error!: " .. err) elseif chunk then print("received: " .. chunk) end end -- create a HTTP socket (see L<jive.net.SocketHttp>) local http = jive.net.SocketHttp(jnt, "192.168.1.1", 9000, "slimserver") -- create a request to GET http://192.168.1.1:9000/xml/status.xml local req = RequestHttp(sink, 'GET', 'http://192.168.1.1:9000/xml/status.xml') -- go get it! http:fetch(req)
FUNCTIONS
jive.net.RequestHttp(sink, method, uri, options)
Creates a RequestHttp. Parameters:
sink : a main thread lnt12 sink. Will be called with nil when data is complete, in order to be compatible with filters and other ltn12 stuff. However for performance reasons, data is concatenated on the network thread side.
method : the HTTP method to use, 'POST' or 'GET'. If POST, a POST body source must be provided in options.
uri : the URI to GET/POST to
options : table with optional parameters: t_bodySource is a lnt12 source required for POST operation; headers is a table with aditional headers to use for the request.
tostring(aRequest)
If aRequest is a jive.net.RequestHttp, prints RequestHttp {name}
jive.net.RequestJsonRpc
jive.net.RequestJsonRpc
jive.net.RequestJsonRpc - A JSON request over HTTP.
DESCRIPTION
jive.net.RequestJsonRpc implements the JSON-RPC protocol over POST HTTP. It is a subclass of jive.net.RequestHttp.
Note the implementation uses the source and sink concept of luasocket.
SYNOPSIS
-- create a sink to receive JSON local function mySink(chunk, err) if err then print("error!: " .. err) elseif chunk then print("received: " .. chunk.id) end end -- create a RequestJsonRpc local myRequest = RequestJsonRpc(mySink, '/jsonservice.js', 'secretmethod', {1, 2 , 3}) -- use a SocketHttp to fetch http:fetch(myRequest)
FUNCTIONS
jive.net.RequestJsonRpc(sink, uri, method, params, options)
Creates a RequestJsonRpc. Parameters:
sink : a main thread sink that accepts a table built from the JSON data returned by the server
uri : the URI of the JSON service (on the HTTP server pointed by the jive.net.SocketHttp this request will be sent to)
method : the method field of JSON
params : the params field of JSON (a table that this class will convert to JSON)
options : options as defined by jive.net.RequestHttp. This class defines the request body.
Note the class calculates a JSON ID.
getJsonId()
Returns the JsonId assigned to this request
tostring(aRequest)
If aRequest is a jive.net.RequestJsonRpc, prints RequestJsonRpc {id}
jive.net.SlimProto
jive.net.SlimProto
jive.net.SlimProto - A TCP socket that implements the slimproto.
DESCRIPTION
This class implements a TCP socket running in a jive.net.NetworkThread.
SYNOPSIS
-- create a Comet socket to communicate with http://192.168.1.1:9000/ local comet = jive.net.Comet(jnt, "192.168.1.1", 9000, "/cometd", "slimserver") -- subscribe to an event -- will callback to func whenever there is an event -- playerid may be nil comet:subscribe('/slim/serverstatus', func, playerid, {'serverstatus', 0, 50, 'subscribe:60'}) -- unsubscribe from an event comet:unsubscribe('/slim/serverstatus', func) -- or unsubscribe all callbacks comet:unsubscribe('/slim/serverstatus') -- send a non-subscription request -- playerid may be nil -- request is a table (array) containing the raw request to pass to SlimServer comet:request(func, playerid, request) -- add a callback function for an already-subscribed event comet:addCallback('/slim/serverstatus', func) -- remove a callback function comet:removeCallback('/slim/serverstatus', func) -- start! comet:connect() -- disconnect comet:disconnect() -- batch a set of calls together into one request comet:startBatch() comet:subscribe(...) comet:request(...) comet:endBatch()
FUNCTIONS
jive.net.Socket
jive.net.Socket
jive.net.Socket - An abstract socket that sends/receives data using a NetworkThread.
DESCRIPTION
An abstract socket that sends/receives data using a NetworkThread. It proposes services to close/free sockets and interface with the main thread, along with convenient proxy functions.
SYNOPSIS
-- jive.net.Socket is abstract so this is not a useful example local mySocket = Socket(jnt, "mySocket") -- information about the socket log:debug("Freeing: ", mySocket) -- print Freeing: Socket {mySocket} -- free the socket mySocket:free()
FUNCTIONS
jive.net.Socket(jnt, name)
Creates a socket named name to interface with the given jnt (a jive.net.NetworkThread instance). name is used for debugging and defaults to "". Must be called by subclasses.
setPriority(priority)
Sets the socket priority.
--]] function setPriority(self, priority) self.priority = priority end
function socketActive(self) if not self.active then self.active = true self.jnt:networkActive(self) end end
function socketInactive(self) if self.active then self.active = false self.jnt:networkInactive(self) end end
--[[
tostring(aSocket)
if aSocket is a jive.net.Socket, prints Socket {name}
jive.net.SocketHttp
jive.net.SocketHttp
jive.net.SocketHttp - An HTTP socket.
DESCRIPTION
This class implements a HTTP socket running in a jive.net.NetworkThread.
SYNOPSIS
-- create a HTTP socket to communicate with http://192.168.1.1:9000/ local http = jive.net.SocketHttp(jnt, "192.168.1.1", 9000, "slimserver") -- create a request (see L<jive.net.RequestHttp) local req = RequestHttp(sink, 'GET', '/xml/status.xml') -- go get it! http:fetch(req)
FUNCTIONS
jive.net.SocketHttp(jnt, host, port, name)
Creates an HTTP socket named name to interface with the given jnt (a jive.net.NetworkThread instance). name is used for debugging and defaults to "". host and port are the hostname/IP host and port of the HTTP server.
jive.net.SocketHttp:fetch(request)
Use the socket to fetch an HTTP request. request must be an instance of class jive.net.RequestHttp. The class maintains an internal queue of requests to fetch.
tostring(aSocket)
if aSocket is a jive.net.SocketHttp, prints SocketHttp {name}
jive.net.SocketHttpQueue
jive.net.SocketHttpQueue
jive.net.SocketHttpQueue - A SocketHttp that uses an external queue
DESCRIPTION
jive.net.SocketHttpQueue is a subclass of jive.net.SocketHttp designed to use an external request queue, such as the one proposed by jive.net.HttpPool.
SYNOPSIS
None provided.
FUNCTIONS
jive.net.SocketHttpQueue(jnt, address, port, queueObj, name)
Same as jive.net.SocketHttp, save for the queueObj parameter which must refer to an object implementing a t_dequeue function that returns a request from its queue and a boolean indicating if the connection must close.
tostring(aSocket)
if aSocket is a jive.net.SocketHttpQueue, prints SocketHttpQueue {name}
jive.net.SocketTcp
jive.net.SocketTcp
jive.net.SocketTcp - A TCP socket to send/recieve data using a NetworkThread
DESCRIPTION
Implements a tcp socket that sends/receive data using a NetworkThread. jive.net.SocketTcp is a subclass of jive.net.Socket and therefore inherits its methods. This class is mainly designed as a superclass for jive.net.SocketHttp and therefore is not fully useful as is.
SYNOPSIS
-- create a jive.net.SocketTcp local mySocket = jive.net.SocketTcp(jnt, "192.168.1.1", 9090, "cli") -- print the connected state if mySocket:connected() then print(tostring(mySocket) .. " is connected") end
FUNCTIONS
jive.net.SocketTcp(jnt, address, port, name)
Creates a TCP/IP socket named name to interface with the given jnt (a jive.net.NetworkThread instance). name is used for debugging and defaults to "". address and port are the hostname/IP address and port to send/receive data from/to. Must be called by subclasses.
jive.net.SocketTcp:connected()
Returns the connected state of the socket. This is mutexed to enable querying the state from the main thread while operations on the socket occur network thread-side.
tostring(aSocket)
if aSocket is a jive.net.SocketTcp, prints SocketTcp {name}
jive.net.SocketUdp
jive.net.SocketUdp
jive.net.SocketUdp - A socket for UDP.
DESCRIPTION
Implements a socket that sends udp packets and returns packets obtained in response. This is used to discover slimservers on the network. jive.net.SocketUdb is a subclass of jive.net.Socket to be used with a jive.net.NetworkSocket.
Note the implementation uses the source and sink concept of luasocket.
SYNOPSIS
-- create a source to send some data local function mySource() return "Hello" end -- create a sink to receive data from the network local function mySink(chunk, err) if err then print("error!: " .. err) elseif chunk then print("received: " .. chunk.data .. " from " .. chunk.ip) end end -- create a SocketUdp local mySocket = jive.net.SocketUdp(jnt, mySink) -- send some data to address 10.0.0.1 on port 3333 mySocket:send(mySource, "10.0.0.1", 3333)
FUNCTIONS
jive.net.SocketUdp(jnt, sink, name)
Creates a UDP socket named name to interface with the given jnt (a jive.net.NetworkThread instance). name is used for debugging and defaults to "". sink is the main thread ltn12 sink that will receive the data. Must be called by subclasses.
The sink receives chunks that are tables. NIL is never sent as the network source cannot determine the "end" of the stream. The table contains the following members: =over
data : the data.
ip : the source ip address.
port : the source port
jive.net.SocketUdp:send(t_source, address, port)
Sends the data obtained through t_source to the given address and port. t_source is a ltn12 source called from the network thread.
tostring(aSocket)
if aSocket is a jive.net.SocketUdp, prints SocketUdp {name}
jive.net.Udap
jive.net.WakeOnLan
jive.slim.ArtworkCache
jive.slim.ArtworkCache
jive.slim.ArtworkCache - Size bounded LRU cache for artwork
--]]
local pairs, setmetatable = pairs, setmetatable
local os = require("os") local oo = require("loop.base")
local debug = require("jive.utils.debug") local log = require("jive.utils.log").logger("slimserver.cache")
-- ArtworkCache is a base class module(..., oo.class)
-- Limit artwork cache to 15 Mbytes local ARTWORK_LIMIT = 15 * 1024 * 1024
function __init(self) local obj = oo.rawnew(self, {})
-- initialise state obj:free() return obj
end function free(self) -- artwork cache self.cache = {}
-- most and least recently used links self.mru = nil self.lru = nil -- total size in bytes self.total = 0
end function dump(self) local citems = 0 for k, v in pairs(self.cache) do citems = citems + 1 end
local items = 0 local v = self.lru while v do items = items + 1 --log:debug("\t", v.key, " next=", v.next and v.next.key) v = v.prev end log:debug("artworkThumbCache items=", items, " citems=", citems, " bytes=", self.total, " fullness=", (self.total / ARTWORK_LIMIT) * 100)
end function set(self, key, value) -- clear entry if value === nil then self.cache[key] = nil return end
-- mark as loading if value === true then self.cache[key] = { value = true } return end -- loaded artwork local bytes = #value self.total = self.total + bytes local entry = { key = key, value = value, bytes = bytes, } self.cache[key] = entry -- link into mru list entry.prev = nil entry.next = self.mru if self.mru then self.mru.prev = entry end self.mru = entry if not self.lru or entry.next === nil then self.lru = entry end -- keep cache under artwork limit while self.total > ARTWORK_LIMIT do local entry = self.lru log:debug("Free artwork entry=", entry.key, " total=", self.total) self.cache[entry.key] = nil if entry.prev then entry.prev.next = nil end self.lru = entry.prev self.total = self.total - #entry.value end if log:isDebug() then self:dump() end
end function get(self, key) local entry = self.cache[key]
if not entry then return nil end -- loading or already most recently used entry? if entry.value === true or self.mru === entry then return entry.value end -- unlink from list if entry.prev then entry.prev.next = entry.next end if entry.next then entry.next.prev = entry.prev end -- link to head entry.prev = nil entry.next = self.mru if self.mru then self.mru.prev = entry end self.mru = entry if entry.next === nil then self.lru = entry end if log:isDebug() then self:dump() end return entry.value
end --[[
jive.slim.LocalPlayer
jive.slim.Player
jive.slim.Player
jive.slim.Player - Squeezebox/Transporter player.
DESCRIPTION
TODO
SYNOPSIS
Notifications:
playerConnected: playerNewName: playerDisconnected: playerPower: playerNew (performed by SlimServer) playerDelete (performed by SlimServer) playerTrackChange playerModeChange playerPlaylistChange playerPlaylistSize playerNeedsUpgrade
FUNCTIONS
jive.slim.Player(server, jnt, playerId)
Create a Player object with playerId.
jive.slim.Player:updatePlayerInfo(squeezeCenter, playerInfo)
Updates the player with fresh data from SS.
jive.slim.Player:free(slimServer)
Deletes the player, if connect to the given slimServer
jive.slim.Player:getTrackElapsed()
Returns the amount of time elapsed on the current track, and the track duration (if known). eg:
local elapsed, duration = player:getTrackElapsed() local remaining if duration then remaining = duration - elapsed end
jive.slim.Player:getModel()
returns the model of player
jive.slim.Player:getPlaylistTimestamp()
returns the playlist timestamp for a given player object the timestamp is an indicator of the last time the playlist changed it serves as a good check to see whether playlist items should be refreshed
jive.slim.Player:getPlaylistSize()
returns the playlist size for a given player object
jive.slim.Player:getPlayerMode()
returns the playerMode for a given player object
jive.slim.Player:getPlayerStatus()
returns the playerStatus information for a given player object
tostring(aPlayer)
if aPlayer is a jive.slim.Player, prints Player {name}
jive.slim.Player:getName()
Returns the player name
jive.slim.Player:isPowerOn()
Returns true if the player is powered on
jive.slim.Player:getId()
Returns the player id (in general the MAC address)
jive.slim.Player:getUuid()
Returns the player uuid.
jive.slim.Player:getMacAddress()
Returns the player mac address, or nil for http players.
jive.slim.Player:getPin()
Returns the SqueezeNetwork PIN for this player, if it needs to be registered
jive.slim.Player:getSlimServer()
Returns the player SlimServer (a jive.slim.SlimServer).
jive.slim.SlimServer
jive.slim.SlimServer
jive.slim.SlimServer - SlimServer object
DESCRIPTION
Represents and interfaces with a real SlimServer on the network.
SYNOPSIS
-- Create a SlimServer local myServer = SlimServer(jnt, '192.168.1.1', 'Raoul') -- Allow some time here for newtork IO to occur -- Get the SlimServer version local myServerVersion = myServer:getVersion()
Notifications:
serverNew (performed by SlimServers) serverDelete (performed by SlimServers) serverConnected(self) serverDisconnected(self, numUserRequests)
FUNCTIONS
jive.slim.SlimServer(jnt, ip, name)
Create a SlimServer object at IP address ip with name name. Once created, the object will immediately connect to slimserver to discover players and other attributes of the server.
jive.slim.SlimServer:updateAddress(ip, port)
Called to update (or initially set) the ip address and port for SqueezeCenter
jive.slim.SlimServer:free()
Deletes a SlimServer object, frees memory and closes connections with the server.
jive.slim.SlimServer:getPin()
Returns the PIN for SqueezeNetwork, if it needs to be registered
jive.slim.SlimServer:linked(pin)
Called once the server or player are linked on SqueezeNetwork.
jive.slim.SlimServer:artworkThumbCached(iconId, size)
Returns true if artwork for iconId and size are in the cache. This may be used to decide whether to display the thumb straight away or wait before fetching it.
jive.slim.SlimServer:cancelArtworkThumb(icon)
Cancel loading the artwork for icon.
jive.slim.SlimServer:cancelArtworkThumb(icon)
Cancel loading the artwork for icon.
jive.slim.SlimServer:fetchArtworkThumb(iconId, icon, size, imgFormat)
The SlimServer object maintains an artwork cache. This function either loads from the cache or gets from the network the thumb for iconId. A jive.ui.Surface is used to perform icon:setValue(). This function computes the URI to request the artwork from the server from iconId. imgFormat is an optional argument to control the image format.
jive.slim.SlimServer:fetchArtworkURL(url, icon, size)
Same as fetchArtworkThumb except it fetches the artwork from a remote URL. This method is in the SlimServer class so it can reuse the other artwork code.
tostring(aSlimServer)
if aSlimServer is a jive.slim.SlimServer, prints SlimServer {name}
jive.slim.SlimServer:getVersion()
Returns the server version
jive.slim.SlimServer:getIpPort()
Returns the server IP address and HTTP port
jive.slim.SlimServer:getName()
Returns the server name
jive.slim.SlimServer:getLastSeen()
Returns the time at which the last indication the server is alive happened, either data from the server or response to discovery. This is used by jive.slim.SlimServers to delete old servers.
jive.slim.SlimServer:isConnected()
Returns the state of the long term connection with the server. This is used by jive.slim.SlimServers to delete old servers.
jive.slim.SlimServer:allPlayers()
Returns all players iterator
for id, player in allPlayers() do xxx end
jive.ui.Audio
jive.ui.Audio
jive.ui.Audio - Audio effects and playback
DESCRIPTION
An class for audio effects and playback.
SYNOPSIS
-- Load wav file in channel 1 local wav = jive.ui.Audio:loadSound(filename, 1) -- Play sound wav:play()
METHODS
jive.ui.Audio:loadSound(file, mixer)
jive.ui.Audio:effectsEnable(enable)
jive.ui.Audio:isEffectsEnabled()
jive.ui.Sound METHODS
jive.ui.Audio:play()
jive.ui.Audio:enable(enable)
jive.ui.Audio:isEnabled()
jive.ui.Button
jive.ui.Checkbox
jive.ui.Checkbox
jive.ui.Checkbox - A checkbox widget
DESCRIPTION
A checkbox widget, extends jive.ui.Widget.
SYNOPSIS
-- New checkbox local checkbox = jive.ui.Checkbox( "checkbox", function(object, isSelected) print("Checkbox is selected: " .. tostring(isSelected)) end, true) -- Change checkbox state checkbox:setSelected(false)
STYLE
The Checkbox includes the following style parameters in addition to the widgets basic parameters.
- imgOn : the image when the checkbox is checked.
- imgOff : the image when the checkbox is not checked.
METHODS
jive.ui.Checkbox(style, closure, isSelected)
Constructs a Checkbox widget. style is the widgets style. isSelected is true if the checkbox is selected, false otherwise (default). closure is a function that will get called whenever the checkbox value changes; the function prototype is: function(checkboxObject, isSelected)
jive.ui.Checkbox:isSelected()
Returns true if the checkbox is selected, or false otherwise.
jive.ui.Checkbox:setSelected(isSelected)
Sets the state of the checkbox. selected true if the checkbox is selected, false otherwise.
Note that using this function calls the defined closure.
jive.ui.Choice
jive.ui.Choice
jive.ui.Choice - A widget to select an item from a list.
DESCRIPTION
A choice widget, extends jive.ui.Widget. This widget lets the user select a value from a set of options.
SYNOPSIS
-- New choice with options On and Off, Off is selected local choice = jive.ui.Choice( "choice", { "On", "Off" }, function(object, selectedIndex) print("Choice is " .. tostring(selectedIndex)) end, 2 ) -- Change checkbox state choice:setSelectedIndex(1)
STYLE
The Choice includes the following style parameters in addition to the widgets basic parameters.
- bg : the background color, defaults to no background color.
- fg : the foreground color, defaults to black.
- bg_img : the background image.
- font : the text font, a jive.ui.Font object.
- line_height : the line height to use, defaults to the font ascend height. =back
- text_align : the text alignment.
- icon_align : the icon alignment.
METHODS
jive.ui.Choice(style, options, closure, selectedIndex)
Constructs a Choice widget. style is the widgets style. options is a table containing the list of options. selectedIndex is the index of the selected option, this defaults to 1 (i.e. the first option in the list). closure is a function that will get called whenever the selected value is changed by the user; the function prototype is: function(choiceObject, selectedIndex)
jive.ui.Choice:getSelectedIndex()
Returns the selected option index.
jive.ui.Choice:getSelected()
Returns the selected option.
jive.ui.Choice:setSelectedIndex(selectedIndex)
Sets the selected option index. selectedIndex is the index of the option to select; it is coerced to the next option if out of bounds (i.e. setSelectedIndex(#options + 1) selects the first option).
Note that using this function calls the closure.
jive.ui.Event
jive.ui.Event
jive.ui.Event - An event.
DESCRIPTION
An event object.
SYNOPSIS
-- Create a new event local event = jive.ui.Event:new(EVENT_ACTION) jive.ui.Framework:pushEvent(event) -- Get event properties event:getType() event:getValue()
METHODS
jive.ui.Event:new(type)
FIXME make the constructor consistant with loop objects.
Creates a new Event. type is the event type.
This event can be processed using jive.ui.Framework:dispatchEvent or appended to the event queue using jive.ui.Framework:pushEvent.
jive.ui.Event:getType()
Returns the event type.
jive.ui.Event:getScroll()
Returns the scroll amount for EVENT_SCROLL_* events.
jive.ui.Event:getKeycode()
Returns the keycode for EVENT_KEY_* events.
jive.ui.Event:getMouse()
Returns the mouse x,y position for EVENT_MOUSE_* events.
EVENTS
EVENT_SCROLL
Scroll event.
EVENT_ACTION
Action event, sent when a menu item is selected.
EVENT_KEY_DOWN
A key down event, sent when the key is pressed. Normally the application should use a EVENT_KEY_PRESS or EVENT_KEY_HOLD event.
EVENT_KEY_UP
A key up event, sent when the key is released. Normally the application should use a EVENT_KEY_PRESS or EVENT_KEY_HOLD event.
EVENT_KEY_PRESS
A key press event, sent when a key press is detected.
EVENT_KEY_HOLD
A key hold event, sent when a key hold is detected.
EVENT_MOUSE_DOWN
A mouse down event, sent when the mouse button is pressed. Normally the application should use a EVENT_MOUSE_PRESS or EVENT_MOUSE_HOLD event.
EVENT_MOUSE_UP
A mouse down event, sent when the mouse button is released. Normally the application should use a EVENT_MOUSE_PRESS or EVENT_MOUSE_HOLD event.
EVENT_MOUSE_PRESS
A mouse press event, sent when a mouse button press is detected.
EVENT_MOUSE_HOLD
A mouse hold event, sent when a mouse button hold is detected.
EVENT_WINDOW_PUSH
A window push event, sent when a window is pushed on to stage.
EVENT_WINDOW_POP
A window push event, sent when a window is poped from the stage.
EVENT_WINDOW_ACTIVE
A window active event, sent when the window is raised to the top of the window stack.
EVENT_WINDOW_INACTIVE
A window inactive event, sent when the window is no longer at the top of the window stack.
EVENT_WINDOW_RESIZE
A window resize event, sent whtn the window is resized.
EVENT_SHOW
A widget show event, sent when the widget is visible.
EVENT_HIDE
A widget hide event, sent when the widget is no longer visible.
EVENT_FOCUS_GAINED
A focuse gained event, sent when the widget has gained focus.
EVENT_FOCUS_LOST
A focuse lost event, sent when the widget has lost focus.
EVENT_SERVICE_JNT
Used internally.
EVENT_KEY_ALL
Any EVENT_KEY_* event.
EVENT_MOUSE_ALL
Any EVENT_MOUSE_* event.
EVENT_VISIBLE_ALL
Any widget visibility event.
EVENT_ALL
Any event.
KEYS
The following keys are used in EVENT_KEY_* events. Multiple key detection is supported. For example you can use KEY_PLAY | KEY_PAUSE to detect when the play and pause keys are both pressed.
KEY_NONE
KEY_GO
KEY_UP
KEY_DOWN
KEY_LEFT
KEY_RIGHT
KEY_BACK
KEY_HOME
KEY_PLAY
KEY_ADD
KEY_PAUSE
KEY_REW
KEY_FWD
KEY_VOLUME_UP
KEY_VOLUME_DOWN
jive.ui.Font
jive.ui.Font
jive.ui.Font - A truetype font.
DESCRIPTION
A font object. Fonts are used for drawing text on jive.ui.Surface's.
SYNOPSIS
-- Load a 12pt font local font = jive.ui.Font:load("FreeSans.ttf", 12) -- Measure font width and height local w = font:width("A string") local h = font:height()
METHODS
jive.ui.Font:load(name, size)
Load the font. name is the filename for the font, if this is a relative filename the lua path is searched for the font file. size is the size of the font.
jive.ui.Font:width(str)
Returns the number of pixels used to render str in this font.
jive.ui.Font:height()
Returns the height of the font.
jive.ui.Font:ascend()
Return the ascend height of the font.
jive.ui.Framework
jive.ui.Framework
jive.ui.Framework - User interface framework
DESCRIPTION
User interface framework
SYNOPSIS
-- Called from the mail application jive.ui.Framework:init() jive.ui.Framework:run() jive.ui.Framework:quit() -- Add a global event listener jive.ui.Framework:addListener(jive.ui.EVENT_KEY_PRESS, function(event) print("key pressed:" .. event.getKeyCode() end)
METHODS
jive.ui.Framework.init()
Initialise the ui.
jive.ui.Framework.quit()
Free all ui resources.
jive.ui.Framework.run()
The main display and event loop.
jive.ui.Framework.reDraw(r)
Mark an area of the screen for redrawing, of the while screen if r is nil.
jive.ui.Framework.pushEvent(event)
Push an event onto the event queue for later processing. This can be called from any thread.
jive.ui.Framework.dispatchEvent(widget, event)
Dispatch an event event to the listeners of the widget widget. Any global event listeners are called first. If widget is nil then the event will be sent to the top most window. This can only be called from the main thread.
jive.ui.Framework.findFile(path)
Find a file on the lua path. Returns the full path of the file, or nil if it was not found.
jive.ui.Framework:getTicks()
Return the number of milliseconds since the Jive initialization.
jive.ui.Framework:getMacAddress()
Return the first Mac address found on the current system.
jive.ui.Framework:getUserPath()
Return the user-specific path that holds settings, 3rd-party applets, wallpaper, etc. THe path is aprt of the overall Lua path.
jive.ui.Framework:threadTicks()
Return the number of milliseconds spent in current thread. Note this is lower resolution than getTicks().
jive.ui.Framework:getBackground()
Returns the current background image.
jive.ui.Framework:setBackground(image)
Sets the background image image.
jive.ui.Framework:styleChanged()
Indicates the style parameters have changed, this clears any caching of the style values used.
jive.ui.Framework:constants()
Import constants into a module.
jive.ui.Framework:eventLoop(netTask)
Main event loop.
jive.ui.Framework:setEmulation(w, h, bpp)
Sets the screen size w, h, and bbp bpp. This must be called before jive.ui.Framework:init(). This has no effect on a hardware platform.
jive.ui.Framework:getScreenSize()
Returns w, h the current screen size.
jive.ui.Framework:wakeup()
Power management wakeup.
jive.ui.Framework:registerWakeup()
Register a power management wakeup function.
jive.ui.Framework:addWidget(widget)
Add a global widget widget to the screen. The global widgets are shown on all windows.
jive.ui.Framework:removeWidget(widget)
Remove the global widget widget from the screen.
jive.ui.Framework:loadSound(file, name, channel)
Load the wav file file to play on the mixer channel channel. Currently two channels are supported.
jive.ui.Framework:enableSound(name, enabled)
Enables or disables the sound name.
jive.ui.Framework:isEnableSound(name)
Returns true if the sound name is enabled.
jive.ui.Framework:playSound(name)
Play sound.
jive.ui.Framework:getSounds()
Returns the table of available sounds.
jive.ui.Framework:addListener(mask, listener, priority)
Add a global event listener listener. The listener is called for events that match the event mask mask. By default the listener is called before any widget event listeners, and can stop event processing by returned EVENT_CONSUME. If priority is negative then it is called before any other listeners, otherwise if it is posible then the listener is only called after the widget listeners have processed the event. Returns a handle to use in removeEventListener().
jive.ui.Framework:removeListener(handle)
Removes the listener handle from the widget.
jive.ui.Framework:getGlobalSetting(key)
Get the value of a given Global Settings key
jive.ui.Framework:setGlobalSetting(key, value)
Change the value of the Global Setting indicated by key
jive.ui.Group
jive.ui.Group
jive.ui.Group - A group widget.
DESCRIPTION
A group widget, extends jive.ui.Widget, it is a container for other widgets. The widgets are arranged horizontally.
SYNOPSIS
-- Create a new group local group = jive.ui.Group("item", { text = Label("text", "Hello World"), icon = Icon("icon") })
STYLE
The Group includes the following style parameters in addition to the widgets basic parameters.
- order : a table specifing the order of the widgets, by key. For example { "text", "icon" }
METHODS
jive.ui.Group(style, widgets)
Constructs a new Group widget. style is the widgets style. widgets is a table with the widgets in this group.
jive.ui.Widget:getWidget(key)
Returns a widget in this group.
jive.ui.Widget:setWidget(key, widget)
Sets or replaces a widget in this group.
jive.ui.Widget:getWidgetValue(widget)
Returns the value of a widget in this Group.
jive.ui.Widget:setWidgetValue(widget, value)
Set the value of a widget in this Group.
jive.ui.HomeMenu
jive.ui.Icon
jive.ui.Icon
jive.ui.Icon - An icon widget
DESCRIPTION
An icon widget, extends jive.ui.Widget. This widget displays an image.
SYNOPSIS
-- New 'play' icon local right = jive.ui.Icon("icon_playmode_play") -- Load icon from URL local icon = jive.ui.Icon("image") local http = SocketHttp(jnt, host, port, "example") local req = RequestHttp(icon:getSink()) http:fetch(req)
STYLE
The Label includes the following style parameters in addition to the widgets basic parameters.
- img : the icon image. This can be replaced by the image set in lua.
- frameWidth : if this is an animated icon this is the width of each frame.
- frameRate : if this is an animated icon this is the desired frame rate.
METHODS
jive.ui.Icon(style, image)
Constructs a Icon widget. style is the Icon style. image is an option jive.ui.Surface to display, if not given the icon image is supplied by the active style.
jive.ui.Icon:getImage()
Returns the jive.ui.Surface displayed by this icon, or nil if the style image is being used.
jive.ui.Icon:setValue(image)
Sets the jive.ui.Surface displayed by the icon.
jive.ui.Icon:sink()
Returns a LTN12 sink that can be used with the jive.net classes for loading images from the network.
jive.ui.Label
jive.ui.Label
jive.ui.Label - A label widget.
DESCRIPTION
A label widget, extends jive.ui.Widget. A label displays multi-line text.
Any lua value can be set as Label value, tostring() is used to convert the value to a string before it is displayed.
SYNOPSIS
-- Create a new label to display 'Hello World' local label = jive.ui.Label("label", "Hello World") -- Update the label to multi-line text label.setValue("Multi-line\ntext")
STYLE
The Label includes the following style parameters in addition to the widgets basic parameters.
- bg : the background color, defaults to no background color.
- fg : the foreground color, defaults to black.
- bgImg : the background image.
- font : the text font, a jive.ui.Font object.
- lineHeight : the line height to use, defaults to the font ascend height. =back
- align : the text alignment.
- line : optionally an array of font, lineHeight, fg and sh attribtues foreach line in the Label.
METHODS
jive.ui.Label(style, value)
Constructs a new Label widget. style is the widgets style. value is the text displayed in the widget.
jive.ui.Label:getValue()
Returns the text displayed in the label.
jive.ui.Label:setValue(value)
Sets the text displayed in the label.
jive.ui.Menu
jive.ui.Menu
jive.ui.Menu - A menu widget.
DESCRIPTION
A menu widget, extends jive.ui.Widget.
SYNOPSIS
-- Create a new menu local menu = jive.ui.Menu("menu") -- Add widgets to the menu menu:addItem(jive.ui.Label("One")) menu:addItem(jive.ui.Label("Two")) menu:addItem(jive.ui.Label("Three"))
STYLE
The Label includes the following style parameters in addition to the widgets basic parameters.
- itemHeight : the height of each menu item.
METHODS
jive.ui.Menu(style)
Constructs a new Menu object. style is the widgets style.
jive.ui.Menu:setItems(list, listSize, min, max)
Set the items in the menu. list is the data structure containing the menu data in a format suitable for the itemRenderer and itemListener. listSize is the total number of items in the menu. Optionally min and max indicate the range of menu items that have changed.
jive.ui.Menu:setCloseable(isCloseable)
Sets if this menu is closeable. A closeable menu will pop from the window stack on the left button, if it is not closeable the menu will bump instead.
jive.ui.Menu:getVisibleIndices()
Returns the indicies of the top and bottom visible items.
jive.ui.Menu:isScrollable()
Returns true if the menu is scrollable, otherwise it returns false.
jive.ui.Menu:getSelectedIndex()
Returns the index of the selected item.
jive.ui.Menu:getSelectedItem()
Returns the widget of the selected item.
jive.ui.Menu:getItems()
Returns the list items from a menu
jive.ui.Menu:setSelectedIndex(index)
Sets index as the selected menu item.
jive.ui.Menu:lock(self, cancel)
Lock the menu. Pressing back unlocks it and calls the cancel closure. The style of the selected menu item is changed. This can be used for a loading animation.
jive.ui.Menu:lock(self, cancel)
Unlock the menu.
jive.ui.Menu:scrollBy(scroll, allowMultiple)
Scroll the menu by scroll items. If scroll is negative the menu scrolls up, otherwise the menu scrolls down. By default, restricts to scrolling one item unless at the edge of the visible list. If allowMultiple is non-nil, ignore that behavior and scroll the requested scroll amount.
jive.ui.Popup
jive.ui.Popup
jive.ui.Popup - A popup window widget.
DESCRIPTION
The popup widget, extends jive.ui.Window. This is a container for other widgets on the screen.
SYNOPSIS
-- Create a popup window with title "Boo!" local popup = jive.ui.Popup("popup", "Boo1") -- Show the window on the screen popup:show() -- Hide the window from the screen popup:hide()
STYLE
The Popup includes the following style parameters in addition to the Window basic parameters.
- maskImg : Tile painted over any parts of the lower window that are visible behind the popup.
METHODS
jive.ui.RadioButton
jive.ui.RadioButton
jive.ui.RadioButton - A radio button widget.
DESCRIPTION
A radio button widget, extends jive.ui.Widget. The radio button must be a member of a jive.ui.RadioGroup. Only one radio button in the radio group may be selected at any time.
SYNOPSIS
-- Create a new radio group local group = jive.ui.RadioGroup() -- Create buttons in the group local button1 = jive.ui.RadioButton( "radio1", group, function(object) print("radio1 selected") end, false) local button2 = jive.ui.RadioButton( "radio2", group, function(object) print("radio2 selected") end, true) -- Set button as selected button1:setSelected()
STYLE
The Radio Button includes the following style parameters in addition to the widgets basic parameters.
- imgOn : the image when the Radio Button is selected.
- imgOff : the image when the Radio Button is not selected.
METHODS
jive.ui.RadioButton(style, group, selected)
Constructs a new RadioButton widget. style is the widgets style. The RadioButton belongs to the jive.ui.RadioGroup group. selected is an optional boolean to set if this RadioButton is selected, it defaults to false. closure is a function that will get called whenever this RadioButton is selected by the user; the function prototype is: function(radioButtonObject)
jive.ui.RadioButton:isSelected()
Returns true if this radio button is selected, otherwise return false.
jive.ui.RadioButton:setSelected()
Sets this radio button. The closure is called.
jive.ui.RadioGroup
jive.ui.RadioGroup
jive.ui.RadioGroup - A container for jive.ui.RadioButtons.
DESCRIPTION
A container for jive.ui.RadioButtons. Only one radio button in the radio group may be selected at any time.
SYNOPSIS
METHODS
jive.ui.RadioGroup()
Constructs a new RadioGroup object.
jive.ui.RadioGroup:getSelected()
Returns the jive.ui.RadioButton currently selected.
jive.ui.RadioGroup:setSelected(selected)
Sets the jive.ui.RadioButton selected in this RadioGroup.
jive.ui.ScrollAccel
jive.ui.ScrollAccel
jive.ui.ScrollAccel
DESCRIPTION
Class to handle scroll events with acceleration.
--]]
local oo = require("loop.simple") local math = require("math")
local ScrollWheel = require("jive.ui.ScrollWheel")
local debug = require("jive.utils.debug") local log = require("jive.utils.log").logger("ui")
-- our class module(...) oo.class(_M, ScrollWheel)
--[[ =head2 ScrollAccel(itemAvailable)
Creates a filter for accelerated scroll events.
itemAvailable is a function that returns a true if the items in a range of indexes are loaded. This is optional, by default it is assumed that all items are loaded.
self:event(event, listTop, listIndex, listVisible, listSize)
Called with a scroll event event. Returns how far the selection should move by.
listTop is the index of the list item at the top of the screen. listIndex is the selected list item. listVisible is the number of items on the screen. listSize is the total number of items in the list.
jive.ui.Scrollbar
jive.ui.Scrollbar
jive.ui.Scrollbar - A scrollbar widget.
DESCRIPTION
A scrollbar widget, extends jive.ui.Widget.
SYNOPSIS
-- Create a new label to display 'Hello World' local scrollbar = jive.ui.Scrollbar("label") -- Set the scrollbar range, 10 items bubble is in the middle scrollbar:setScroll(1, 10, 5)
STYLE
The Scrollbar includes the following style parameters in addition to the widgets basic parameters.
- bg_img : the background image tile.
- img : the bar image tile.
- horizontal : true if the scrollbar is horizontal, otherwise the scrollbar is vertial (defaults to horizontal).
METHODS
jive.ui.Scrollbar:setScrollbar(min, max, pos, size)
Set the scrollbar range min to max, the bar position to pos and the bar size to size. This method can be used when using this widget as a scrollbar.
jive.ui.ScrollWheel
jive.ui.ScrollWheel
jive.ui.ScrollWheel
DESCRIPTION
Class to handle scroll events.
--]]
local oo = require("loop.base")
local math = require("math")
local debug = require("jive.utils.debug") local log = require("jive.utils.log").logger("ui")
-- our class module(..., oo.class)
--[[ =head2 ScrollWheel(itemAvailable)
Creates a filter for non-accelerated scroll events.
itemAvailable is a function that returns a true if the items in a range of indexes are loaded. This is optional, by default it is assumed that all items are loaded.
self:event(event, listTop, listIndex, listVisible, listSize)
Called with a scroll event event. Returns how far the selection should move by.
listTop is the index of the list item at the top of the screen. listIndex is the selected list item. listVisible is the number of items on the screen. listSize is the total number of items in the list.
jive.ui.SimpleMenu
jive.ui.SimpleMenu
jive.ui.SimpleMenu - A simple menu widget.
DESCRIPTION
A simple menu widget, extends jive.ui.Menu.
SYNOPSIS
-- Create a new menu local menu = jive.ui.Menu("menu", { { id = 'uniqueString', text = "Item 1", sound = "WINDOWSHOW", icon = widget1, callback = function1 ), { id = 'anotherUniqueString', text = "Item 2", sound = "WINDOWSHOW", icon = widget2, callback = function2 ), }) -- Sort the menu alphabetically menu:setComparator(SimpleMenu.itemComparatorAlpha)
STYLE
The Label includes the following style parameters in addition to the widgets basic parameters.
itemHeight : the height of each menu item.
METHODS
jive.ui.Menu:setComparator(comp)
Sets the menu comparator to comp used to sort the menu items. By default the menu is not sorted and elements will be displayed in the order they are added.
jive.ui.Menu.itemComparatorAlpha
Item comparator to sort items alphabetically (i.e. using item.text).
jive.ui.Menu.itemComparatorWeightAlpha
Item comparator to sort items using item.weight as a primary key, and item.text as a secondary key.
jive.ui.Menu.itemComparatorKeyWeightAlpha
Item comparator to sort items using item.sortKey as a primary key, item.weight as a secondary key, and item.text as a tertiary key.
jive.ui.Menu.itemComparatorComplexWeightAlpha
Item comparator to sort items using a complex a.b.c...n-style item.weights (table) as a primary key, and item.text as a secondary key.
jive.ui.Menu:numItems()
Returns the top number of items in the menu.
jive.ui.Menu:getItem(index)
Returns the item at the index index.
jive.ui.Menu:iterator()
Returns an interator over all items in the menu.
jive.ui.Menu:getIndex(item)
Returns the index of item item, or nil if it is not in this menu.
jive.ui.Menu:getIdIndex(id)
Returns the index of item given by id, or nil if it is not in this menu.
jive.ui.Menu:getTextIndex(item)
Returns the index of item given by text, or nil if it is not in this menu.
jive.ui.Menu:setItems(items)
Efficiently replaces the current menu items, with items.
jive.ui.Menu:addItem(item)
Add item to the end of the menu. Returns the index of the item added.
item is a table with the following keys: - id (optional), a unique key for this menu item - text, - icon (optional), - weight (optional), see jive.ui.Menu.itemComparatorWeightAlpha, - callback (optional), a function performing whatever the menu is supposed to do, having prototype: function(event, item) returning nil/jive.ui.EVENT_CONSUME/QUIT/UNUSED
For convenience, EVENT_CONSUME is assumed if the function returns nothing
jive.ui.Menu:insertItem(item, index)
Insert item into the menu at index. Returns the index of the item added. See addItem for the definition of item.
jive.ui.Menu:replaceIndex(item, index)
Replace the item at index with item.
jive.ui.Menu:removeIndex(index)
Remove the item at index from the menu. Returns the item removed from the menu.
jive.ui.Menu:removeItem(item)
Remove item from the menu. Returns the item removed from the menu.
jive.ui.Menu:removeItemById(id)
Remove item given by id from the menu. Returns the item removed from the menu.
jive.ui.Menu:updatedIndex(index)
Notifies the menu with the items at index has changed. If neccessary this will cause the menu to be redrawn.
jive.ui.Menu:updatedItem(item)
Notifies the menu with the item item has changed. If neccessary this will cause the menu to be redrawn.
jive.ui.Slider
jive.ui.Slider
jive.ui.Slider - A slider widget.
DESCRIPTION
A slider widget, extends jive.ui.Widget.
SYNOPSIS
-- Create a new label to display 'Hello World' local slider = jive.ui.Slider("label") -- Set the slider range, 10 items bubble is in the middle slider:setScroll(1, 10, 5)
STYLE
The Slider includes the following style parameters in addition to the widgets basic parameters.
- bg_img : the background image tile.
- img : the bar image tile.
- horizontal : true if the slider is horizontal, otherwise the slider is vertial (defaults to horizontal).
METHODS
jive.ui.Slider:setScrollbar(min, max, pos, size)
Set the slider range min to max, the bar position to pos and the bar size to size. This method can be used when using this widget as a slider.
jive.ui.Slider:setRange(min, max, value)
Set the slider range min to max, and the bar size to value. This method can be used when using this widget as a scrollbar.
jive.ui.Slider:setValue(value)
Set the slider value to value.
jive.ui.Slider:getValue()
Returns the value of the slider.
jive.ui.Surface
jive.ui.Surface
jive.ui.Surface - A graphic surface
DESCRIPTION
A graphic surface. Can be used for drawing or images.
All colors used in the api are given as 32bit RGBA values.
SYNOPSIS
-- Drawing local srf = jive.ui.Surface:newRGBA(100, 100) srf:rectangle(10, 10, 90, 90, 0xFFFFFFFF) -- Images local img = jive.ui.Surface:loadImage("example.png")
METHODS
newRGB(w, h)
Constructs a new RGB surface of width and height w and h.
newRGBA(w, h)
Constructs a new RGBA surface of width and height w and h. The surface is filled with transparency.
loadImage(path)
Load an image from path. If path is relative the lua path is searched for the image. Returns the loaded image.
loadImageData(data, len)
Load an image from data using len bytes. Returns the loaded image.
drawText(font, color, str)
Draw text str in font font, in color color. Returns a new surface containing the text.
setOffset(x, y)
Sets a surface offset. This offset is used by all blitting and drawing methods.
setClip(x, y, w, h)
Sets x, y, w, h as the surface clip rectangle. This offset is used by all blitting and drawing methods.
getClip()
Returns x, y, w, h the surface clip rectangle.
blit(dst, dx, dy)
Blits this surface to the dst surface at dx, dy.
blitClip(sx, sy, sw, sh, dst, dx, dy)
Blits a subset this surface sx, sy, sw, sh to the dst surface at dx, dy.
blitAlpha(dst, dx, dy, alpha)
Blits this surface to the dst surface at dx, dy using a per surface alpha value. Only works with RGB surfaces.
getSize()
Returns w, h, the surface size.
DRAWING METHODS
The following methods are from the SDL_gfx package. See http://www.ferzkopp.net/joomla/content/view/19/14/ for more details.
rotozoom(angle, zoom, smooth)
zoom(zoomx, zoomy, smooth)
shrink(factorx, factory)
pixel(x, y, color)
hline(x1, x2, y, color)
vline(x, y1, y2, color)
rectangle(x1, y1, x2, y2, color)
filledRectangle(x1, y1, x2, y2, color)
line(x1, y1, x2, y2, color)
aaline(x1, y1, x2, y2, color)
circle(x, y, r, color)
aacircle(x, y, r, color)
filledCircle(x, y, r, color)
ellipse(x, y, rx, ry, color)
aaellipse(x, y, rx, ry, color)
filledEllipse(x, y, rx, ry, color)
pie(x, y, rad, start, end, color)
filledPie(x, y, rad, start, end, color)
trigon(x1, y1, x2, y2, x3, y3, color)
aatrigon(x1, y1, x2, y2, x3, y3, color)
filledTrigon(x1, y1, x2, y2, x3, y3, color)
jive.ui.Task
jive.ui.Textarea
jive.ui.Textarea
jive.ui.Textarea - A text area widget.
DESCRIPTION
A text area widget, extends jive.ui.Widget.
SYNOPSIS
-- Create a new text area local textarea = jive.ui.Textarea("text", "This is some\ntext that spans\nseveral lines") -- Scroll the text down by 2 lines textarea:scroll(2) -- Set the text textarea:setValue("Different text")
STYLE
The Label includes the following style parameters in addition to the widgets basic parameters.
- bg : the background color, defaults to no background color.
- fg : the foreground color, defaults to black.
- bg_img : the background image.
- font : the text font, a jive.ui.Font object.
- line_height : the line height to use, defaults to the font ascend height. =back
- text_align : the text alignment.
METHODS
jive.ui.Textarea(style, text)
Construct a new Textarea widget. style is the widgets style. text is the initial text displayed.
jive.ui.Textarea:getText()
Returns the text contained in this Textarea.
jive.ui.Textarea:setValue(text)
Sets the text in the Textarea to text.
jive.ui.Textarea:isScrollable()
Returns true if the textarea is scrollable, otherwise it returns false.
jive.ui.Textarea:scrollBy(scroll)
Scroll the Textarea by scroll items. If scroll is negative the text scrolls up, otherwise the text scrolls down.
jive.ui.Textinput
jive.ui.Textinput:getValue()
Returns the text displayed in the label.
jive.ui.Textinput:setValue(value)
Sets the text displayed in the label.
jive.ui.Textinput:init(style, value, closure, allowedChars)
Creates a new Textinput widget with initial value value. The closure is a function that will be called at the end of the text input. This function should return false if the text is invalid (the window will then bump right) or return true when the text is valid. allowedChars is an optional parameter containing the list of chars to propose.
jive.ui.Textinput.textValue(default, min, max)
Returns a value that can be used for entering a length bounded text string
jive.ui.Textinput.timeValue(default)
Returns a value that can be used for entering time setting
jive.ui.Textinput.hexValue(default)
Returns a value that can be used for entering an hexadecimal value.
jive.ui.Textinput.ipAddressValue(default)
Returns a value that can be used for entering an ip address.
jive.ui.Tile
jive.ui.Tile
jive.ui.Tile - A tiled image.
DESCRIPTION
A tiled image used to fill an area.
SYNOPSIS
-- Fill with a transparnet red local tile = jive.ui.Tile:fillColor(0xff00007f) -- Horizontal bar filled with images tile = Tile:loadHTiles({ "iconbar_l.png", "iconbar.png", "iconbar_r.png", }) -- Blit tile
METHODS
jive.ui.Tile:fillColor(color)
Create a tile with a fill colour.
jive.ui.Tile:loadImage(path)
Create a tile with a single image, this is repeated to fill the area if required.
jive.ui.Tile:loadTiles({ p1, p2, p3, p4, p5, ... })
Create a rectangular tile with nine images:
---------------- | p2 | p3 | p4 | ---------------- | p9 | p1 | p5 | ---------------- | p8 | p7 | p6 | ----------------
jive.ui.Tile:loadVTiles({ p1, p2, p3 })
Create a vertical tile with three images:
------ | p1 | ------ | p2 | ------ | p3 | ------
jive.ui.Tile:loadHTiles({ p1, p2, p3 })
Create a horizontal tile with three images:
---------------- | p1 | p2 | p3 | ----------------
tile:blit(srf, x, y, w, h)
Blit the tile to surface at x, y, the area w, h is filled.
tile:getMinSize()
Returns the minimum width,height the tile can be painted.
jive.ui.Timer
jive.ui.Timer
jive.ui.Time - A timer.
DESCRIPTION
A timer object.
SYNOPSIS
-- Create a timer that prints "hi" every second local timer = jive.ui.Timer(1000, function() print "hi" end) -- stop the timer timer:stop()
METHODS
jive.ui.Timer(interval, closure, once)
Constructs a new timer. The closure is called every interval milliseconds. If <once> is true then the closure is only called once each time the timer is started.
The closure is called with a single argument, the Timer object.
jive.ui.Timer:start()
Starts the timer.
jive.ui.Timer:stop()
Stops the timer.
jive.ui.Timer:restart(interval)
Restarts the timer. Optionally the timer interval can be modified to interval, otherwise the interval is unchanged.
jive.ui.Timer:setInterval(interval)
Sets the timers interval to interval and restarts the timer if it is already running.
jive.ui.Timer:isRunning()
Returns true if the timer is running.
jive.ui.Widget
jive.ui.Widget
jive.ui.Widget - Base class for UI widgets.
DESCRIPTION
Base class for UI widgets.
SYNOPSIS
See examples in subclasses.
STYLE
All widgets support the following style parameters that can be set in the skin.
- x : absolute x co-ordinate in pixels
- y : absolute y co-ordinate in pixels
- w : width in pixels, or WH_FILL to fill the available space.
- h : height in pixels
- padding : padding around the widget content in pixels. Defaults to 0.
- padding-left : padding on the left of the widget in pixels. Overrides padding is specified.
- padding-top : padding on the top of the widget in pixels. Overrides padding is specified.
- padding-right : padding on the right of the widget in pixels. Overrides padding is specified.
- padding-bottom : padding on the bottom of the widget in pixels. Overrides padding is specified.
- layer : the layer can be one of the following values.
- LAYER_FRAME
- Widgets in the Frame layer are not animated during window transitions.
- LAYER_CONTENT
- Widgets in the Content layer are animated during window transitions. This is the default value.
- LAYER_CONTENT_OFF_STAGE
- Widgets in the Content Off Stage layer are only animated when moving off stage. These widgets are not drawn when moving on stage.
- LAYER_CONTENT_ON_STAGE
- Widgets in the Content On Stage layer are only animated when moving on stage. These widgets are not drawn when moving off stage.
METHODS
jive.ui.Widget:iterate(closure)
Calls the function closure for all widgets contained by this widget. This is overridden by subclasses.
jive.ui.Widget:getPosition()
Returns x, y the widgets position.
jive.ui.Widget:setBounds(x, y, w, h)
Sets the widgets bounds to x, y, w, h
jive.ui.Widget:getSize()
Returns w, h the widgets size.
jive.ui.Widget:setSize(w, h)
Sets the widgets size to w, h
jive.ui.Widget:getPosition()
Returns the widgets x,y position.
jive.ui.Widget:setPosition(x, y)
Sets the widgets x,y position.
jive.ui.Widget:getStyle()
Returns the widgets style.
jive.ui.Widget:setStyle(style)
Sets the widgets style.
jive.ui.Widget:setStyle(styleModifier)
Sets the widgets style modifier.
jive.ui.Widget:isVisible()
Returns true if the widget is visible, otherwise returns false.
jive.ui.Widget:hide()
Hides the window containing this widget.
jive.ui.Widget:getParent()
Returns the widgets parent.
jive.ui.Widget:getWindow()
Returns the window containing this widget, or nil if the widget is not in a window.
jive.ui.Widget:reSkin()
Called when the widget content or appearence has changed. This will make sure the widget is packed and any layout updated before it is redrawn.
jive.ui.Widget:reLayout()
Called when the widget has change position or size. This will make sure the widget is layout is updated before it is redrawn.
jive.ui.Widget:reDraw()
Marks the bounding box of this widget for redrawing.
jive.ui.Widget:checkSkin()
Updates the widgets skin if required.
jive.ui.Widget:checkLayout()
Prepares the widgets contents and performs layout if required. Also calls do layout on any child widgets.
jive.ui.Widget:addListener(mask, listener)
Add a listener listener to the widget. The listener is called for events that match the event mask mask. Returns a handle to use in removeListener().
jive.ui.Widget:removeListener(handle)
Removes the listener handle from the widget.
jive.ui.Widget:addAnimation(animation, frameRate)
Add an animation function animation to the widget. This function will be called before the frame is drawn at the requested frameRate. Returns a handle to use in removeAnimation().
jive.ui.Widget:removeAnimation(handle)
Remove the animation function handle from the widget.
jive.ui.Widget:dispatchNewEvent(eventType, ...)
Send a new event of type type with value value to this widgets listeners. The additional args are event specific.
jive.ui.Widget:dispatchUpdateEvent(value)
Send an EVENT_UPDATE with value value to this widgets listeners.
jive.ui.Widget:addTimer(interval, closure, once)
Add a timer to this timer that calls closure in interval milliseconds. The timer is only called while the widget is shown on the screen.
jive.ui.Widget:removeTimer(timer)
Remove timer timer from this Widget.
jive.ui.Widget:setAccelKey(key)
Sets the key letter displayed in an accelerated menu.
jive.ui.Widget:getAccelKey()
Returns the key letter displayed in an accelerated menu.
jive.ui.Widget:playSound(sound)
Play the sound when the widget is visible.
jive.ui.Window
jive.ui.Window
jive.ui.Window - The window widget.
DESCRIPTION
The window widget, extends jive.ui.Widget. This is a container for other widgets on the screen.
SYNOPSIS
-- Create a new window with title "Jive" and title style "hometitle" local window = jive.ui.Window("window", "Jive", "hometitle") -- Show the window on the screen window:show() -- Hide the window from the screen window:hide()
STYLE
The Window includes the following style parameters in addition to the widgets basic parameters.
- bgImg : the windows background image.
METHODS
jive.ui.Window(style, title, titleStyle)
Constructs a new window widget. style is the widgets style. The window can have an optional title, and an optional titleStyle titleStyle
jive.ui.Window:show(transition)
Show this window, adding it to the top of the window stack. The transition is used to move the window on stage.
jive.ui.Window:showInstead(transition)
Shows this window as a replacement for the window at the top of the window stack. The transition is used to move the window on stage.
jive.ui.Window:replace(toReplace, transition)
Replaces toReplace window with a new window object
jive.ui.Window:showBriefly(msecs, closure, pushTransition, popTransition)
Shows this window briefly for msecs milliseconds. When the timeout occurs, or a key has been pressed then window is hidden and the closure is called. The pushTransition and popTransition transitions are used to move the window on and off stage.
If the window has already been displayed with showBriefly then the timer is restarted with the new msecs value.
jive.ui.Window:hide(transition)
Hides this window. It it is currently at the top of the window stack then the transition is used to move the window off stage.
jive.ui.Window:hideToTop(transition)
Hide from this window to the top if the window stack.
jive.ui.Window:autoHide(enabled)
If autoHide is enabled then the window is automatically hidden when another window is shown above it. This is useful for hiding popup windows so they do not appear if the user moves back.
===cut --]] function setAutoHide(self, enabled) self.autoHide = enabled and true or nil end
--[[
jive.ui.Window:bumpLeft()
Makes the window bump left.
jive.ui.Window:bumpRight()
Makes the window bump right.
jive.ui.Window:hideAll()
Hides all windows, removing them from the window stack.
jive.ui.Window:getTitle()
Returns the text of the title widget.
jive.ui.Window:getTitleWidget()
Returns the window's title widget.
jive.ui.Window:getTitleStyle()
Returns the style of the title widget.
jive.ui.Window:setTitle(title)
Sets the windows title to title.
jive.ui.Window:setTitleStyle(style)
Sets the windows title style to style.
jive.ui.Window:setTitleWidget(titleWidget)
Sets the windows title to titleWidget.
jive.ui.Window:getWindow()
Returns self.
jive.ui.Window:lowerWindow(self)
Returns the window beneath this window in the window stack.
jive.ui.Window:addWidget(widget)
Add the widget widget to the window.
jive.ui.Window:removeWidget(widget)
Remove the widget widget from the window.
jive.ui.Window:focusWidget(widget)
Make the widget have the focus. This widget will be forwarded events from the window, and should animate (if applicable).
jive.ui.Window:transitionNone()
Returns an empty window transition. i.e. the window is just displayed without any animations.
jive.ui.Window:transitionBumpLeft()
Returns a bump left window transition.
jive.ui.Window:transitionBumpRight()
Returns a bump right window transition.
jive.ui.Window:transitionPushLeft(newWindow)
Returns a push left window transition.
jive.ui.Window:transitionPushRight(newWindow)
Returns a push right window transition.
jive.ui.Window:transitionFadeIn(newWindow)
Returns a fade in window transition.
jive.ui.Window:transitionPushPopupUp(newWindow)
Returns a push up window transition for use with popup windows.
jive.ui.Window:transitionPushPopupDown(newWindow)
Returns a push down window transition for use with popup windows.
jive.ui.Window:noLayout()
Layout function that does not modify the window layout
jive.ui.Window:borderLayout(window)
Layout function similar to the Java Border Layout.
jive.utils.autotable
jive.utils.autotable
jive.util.autotable - magic Lua tables
DESCRIPTION
Creates a table that automatically creates any subtable.
SYNOPSIS
-- Create an autotable local harry = jive.util.autotable:new() -- Automatically add subtables "potter" and "magic" harry.potter.magic.wand = 33
FUNCTIONS
new()
Creates and returns the autotable.
jive.utils.coxpcall
jive.utils.datetime
jive.utils.datetime
jive.utils.datetime - stores datetime settings for use in all the applets
DESCRIPTION
This object should provide all Date/Time related functions - Timezone info - Locale Based Date and Time formats
FUNCTIONS
getAllDateFormats(self) setWeekstart(self, day) getWeekstart(self) setDateFormat(self, dateformat) getDateFormat(self) getCurrentTime(self) getTimeZone(self, timezone) getAllTimeZones(self) setTimeZone(self, timezone) setHours(self, hours) getHours(self) secondsFromMidnight(self, hhmm) timeFromSFM(self, secondsFromMidnight)
getAllDateFormats(self)
Returns all available Date Formats defined in the local table DateFormat
setWeekstart(self, day)
Sets the day with which the week starts. Usualy Monday in Europe and Sunday in the USA
getWeekstart(self)
Returns the current setting for the first day in the week.
setDateFormat(self, dateformat)
Set the default date format.
getDateFormat(self)
Return the default date format.
getCurrentTime(self)
Returns a date string using the set date format.
getTimeZone
Returns the current time zone.
getAllTimeZones(self)
Returns all available time zones defined in the table TimeZones.
setTimeZone(self, timezone)
Set the current time zone. The function checks if the timezone is available. Returns true if the timezone could be set.
setHours(self, hours)
Sets the Hours used in the clock. 24h or AM,PM (12h)
getLocale()
Returns the current setting for hours. 24h or AM,PM (12h)
secondsFromMidnight()
Takes hhmm format and returns seconds from midnight
timeFromSFM()
Takes seconds from midnight and returns time format (24h for now)
getCurrentTime()
Returns the current, formatted time.
Example: 21:57 (24h format) 9:57PM (AM/PM)
jive.utils.debug
jive.utils.debug
jive.utils.debug - Debug utilities.
DESCRIPTION
Provides a utility to trace lua functions and another to dump tables. This modules extends the lua debug module.
SYNOPSIS
-- require us local debug = require("jive.utils.debug") -- Turn on line tracing debug.trace() -- Dump a table local aTable = {a = 'bla', c = {}} debug.dump(aTable) -- print: { --table: 0x11aedd0 a = "bla", c = { --table: 0x11aee30 }, } -- Trackback (from lua debug module) debug.traceback()
FUNCTIONS
traceon()
Traces Lua calls, line by line. Use traceoff() to turn off tracing. This is very verbose, but can help trace performance or strange behavioral issues. It also gives a glimpse on the inner working of the Lua engine.
traceff()
Turns off tracing Lua calls, line by line.
dump(table, depth)
Dumps a table. Default depth is 2. Quick and dirty way of using loop.debug.Viewer, which offers many more options.
jive.utils.dumper
jive.utils.jsonfilters
jive.utils.jsonfilters
jive.util.jsonfilters - json filters
DESCRIPTION
A set of ltn12 filters that encode/decode JSON.
SYNOPSIS
-- transform a source returning Lua arrays (luasource) in json local jsonsource = ltn12.source.chain( luasource, jive.utils.jsonfilters.encode) -- transform a sink accepting Lua arrays (luasink) into one that accepts json local jsonsink = ltn12.sink.chain( jive.utils.jsonfilters.decode, luasink)
FUNCTIONS
decode(chunk)
Decodes a JSON chunk (string) into a Lua array
encode(chunk)
Encodes a Lua array into JSON chunk (string)
jive.utils.locale
jive.utils.locale
jive.utils.locale - Deliver strings based on locale (defaults to EN) and path
DESCRIPTION
Parses strings.txt from appropriate directory and sends it back as a table
FUNCTIONS
setLocale(locale)
readStringsFile(thisPath)
Set a new locale. All strings already loaded are reloaded from the strings file for the new locale.
getLocale()
Returns the current locale.
getAllLocales()
Returns all locales.
readStringsFile(self, fullPath, stringsTable)
Parse strings.txt file and put all locale translations into a lua table that is returned. The strings are for the current locale.
loadAllStrings(self, filePath)
Parse strings.txt file and put all locale translations into a lua table that is returned. Strings for all locales are returned.
jive.utils.log
jive.utils.log
jive.util.log - logging facility
DESCRIPTION
A basic logging facility by category and level. Functionality based on improved lualogging.
SYNOPSIS
-- create a log of a given category (screensaver.flickr) and at a given level (DEBUG) local log = jive.utils.log.addCategory("screensaver.flickr", jive.utils.log.DEBUG) -- get the logger for a category that should exist local log = jive.utils.log.logger("net.http") -- typically at the top of a module, you'd do local log = require("jive.utils.log").logger("net.http") -- log something log:debug("hello world") -- prints 161845:39202 DEBUG (somefile.lua:45) - Hello world -- format is -- Time (HHMMSS) : ticks (ms) LEVEL (source file:line) - message
The logging functions concatenate data more efficiently than operator .. does, so for best performance, do
log:debug("Welcome ", first_name, ", thanks for visiting us ", time_of_day)
rather than
log:debug("Welcome " .. first_name .. ", thanks for visiting us " .. time_of_day)
If the first parameter is a table, it is rendered as a string.
LEVELS
The following levels are defined: DEBUG, INFO, WARN and ERROR. They are defined in the module and can therefore be accessed using jive.utils.log.LEVEL, for example jive.utils.log.DEBUG.
CATEGORIES
Categories are strings. The following are the default categories:
-- applets.setup -- applets.browser -- applets.games -- applets.screensavers -- applets.misc -- jive.main -- slimserver -- slimserver.cache -- player -- net.cli -- net.thread -- net.socket -- net.http -- ui
FUNCTIONS
logger(category)
Returns the logger of the given category. It is an error if the category does not exist and a default logger is returned in that case.
addCategory(category, initialLevel)
Creates and returns a logger of the given category. Returns the category if it already exists.
logger:log(level, message, ...)
Logs a message at the given level in the given logger. message and ... are concatenated before output. If message is a table, it is rendered as string; tables that refer to themselves are not supported however.
logger:<level>(message, ...)
Utility functions that call log(<level>, message, ...), for example
log:debug("bla")
This are defined dynamically depending on the current log level, so are faster than log(level, messsage).
logger:getLevel()
Returns the level of the logger (one of jive.log.DEBUG, etc.)
logger:isDebug()
Returns true if the level of the logger is DEBUG, this enables diagnostic code to be run only when in debug. Particularly useful if the code is expensive.
getCategories()
Returns all loggers in an array with categories as keys.
jive.utils.strings
jive.utils.strings
jive.util.strings - string utilities
DESCRIPTION
Assorted utility functions for strings
SYNOPSIS
-- trim a string at the first 0x00 local trimmed = jive.util.strings.trim(some_string)
FUNCTIONS
str2hex(s)
Returns a string where each char of s is replaced by its ASCII hex value.
trim(s)
Returns s trimmed down at the first 0x00 found.
split(self, inSplitPattern, myString, returnTable)
Takes a string pattern and string as arguments, and an optional third argument of a returnTable
Splits myString on inSplitPattern and returns elements in returnTable (appending to returnTable if returnTable is given)
jive.utils.table
jive.utils.table
jive.util.table - table utilities
DESCRIPTION
Assorted utility functions for tables. This extends the lua built-in table.* functions.
SYNOPSIS
local table = require("jive.utils.table") -- Iterator over a table in the order of its keys for name, line in table.pairsByKeys(lines) do print(name, line) end -- Sort table (from lua table module) table.sort(t1)
FUNCTIONS
table.pairsByKeys(t, f)
Returns an iterator that traverses a table t following the order of its keys. An option parameter f allows the specifiction of an alternative order.
Taken from Programming in LUA page 173.
table.delete(table, value)
Deletes an element from the table, shifting down any other elements.
Returns true if an element was deleted.
table.contains(table, value)
Returns true if the table contains the value, otherwise returns false
applets.AboutJive.AboutJiveApplet
applets.AboutJive.AboutJiveMeta
applets.BlankScreen.BlankScreenApplet
applets.BlankScreen.BlankScreenApplet
applets.BlankScreen.BlankScreenApplet - A screensaver displaying a BlankScreen photo stream.
DESCRIPTION
This screensaver applet blanks the screen
FUNCTIONS
Applet related methods are described in jive.Applet. BlankScreenApplet overrides the following methods:
applets.BlankScreen.BlankScreenMeta
applets.BlankScreen.BlankScreenMeta
applets.BlankScreen.BlankScreenMeta - BlankScreen meta-info
DESCRIPTION
See applets.BlankScreen.BlankScreenApplet.
FUNCTIONS
See jive.AppletMeta for a description of standard applet meta functions.
applets.Bounce.BounceApplet
applets.Bounce.BounceApplet
applets.Bounce.BounceApplet - Demonstration screensaver featuring a bouncing Squeezebox!
DESCRIPTION
Bounce is a screen saver for Jive. It is an applet that implements a screen saver performing simple animations.
FUNCTIONS
Applet related methods are described in jive.Applet. BounceApplet overrides the following methods:
applets.Bounce.BounceMeta
applets.Bounce.BounceMeta
applets.Bounce.BounceMeta - Bounce meta-info
DESCRIPTION
See applets.Bounce.BounceApplet.
FUNCTIONS
See jive.AppletMeta for a description of standard applet meta functions.
applets.ChooseMusicSource.ChooseMusicSourceApplet
applets.ChooseMusicSource.ChooseMusicSourceApplet
applets.SlimServers.SlimServersApplet - Menus to edit the Slimserver address
DESCRIPTION
This applet allows users to define IP addresses for their slimserver. This is useful if the automatic discovery process does not work - normally because the server and jive are on different subnets meaning that UDP broadcasts probing for servers do not get through.
Users may add one or more slimserver IP addresses, these will be probed by the server discovery mechanism implemented in SlimDiscover. Removing all explicit server IP addresses returns to broadcast discovery.
FUNCTIONS
applets.ChooseMusicSource.ChooseMusicSourceMeta
applets.ChooseMusicSource.ChooseMusicSourceMeta
applets.ChooseMusicSource.ChooseMusicSourceMeta
DESCRIPTION
See applets.ChooseMusicSource.ChooseMusicSourceApplet.
FUNCTIONS
See jive.AppletMeta for a description of standard applet meta functions.
applets.Clock.ClockApplet
applets.Clock.ClockMeta
applets.CustomizeHomeMenu.CustomizeHomeMenuApplet
applets.CustomizeHomeMenu.CustomizeHomeMenuApplet
applets.CustomizeHomeMenu.CustomizeHomeMenuApplet - Customize Home Menu Applet
DESCRIPTION
This applet is to allow for a user to customize what items are displayed/hidden from the home menu
FUNCTIONS
Applet related methods are described in jive.Applet.
applets.CustomizeHomeMenu.CustomizeHomeMenuMeta
applets.DefaultSkin.DefaultSkinApplet
applets.DefaultSkin.DefaultSkinApplet
applets.DefaultSkin.DefaultSkinApplet - The default Jive skin.
DESCRIPTION
This applet implements the default Jive skin. It can be used as a model to provide alternate skins for Jive.
FUNCTIONS
Applet related methods are described in jive.Applet. DefaultSkinApplet overrides the following methods:
applets.DefaultSkin.DefaultSkinMeta
applets.DefaultSkin.DefaultSkinMeta
applets.DefaultSkin.DefaultSkinMeta - DefaultSkin meta-info
DESCRIPTION
See applets.DefaultSkin.DefaultSkinApplet.
FUNCTIONS
See jive.AppletMeta for a description of standard applet meta functions.
applets.DesktopJive.DesktopJiveMeta
applets.DesktopJive.loadPriority
applets.Flickr.FlickrApplet
applets.Flickr.FlickrApplet
applets.Flickr.FlickrApplet - A screensaver displaying a Flickr photo stream.
DESCRIPTION
This screensaver displays random images every 10 seconds from the Flickr picture website. It demonstrates using the network API in addition to applet and screensavers concepts in Jive.
FUNCTIONS
Applet related methods are described in jive.Applet. FlickrApplet overrides the following methods:
applets.Flickr.FlickrMeta
applets.Flickr.FlickrMeta
applets.Flickr.FlickrMeta - Flickr meta-info
DESCRIPTION
See applets.Flickr.FlickrApplet.
FUNCTIONS
See jive.AppletMeta for a description of standard applet meta functions.
applets.FullscreenSkin.FullscreenSkinApplet
applets.FullscreenSkin.FullscreenSkinApplet
applets.FullscreenSkin.FullscreenSkinApplet - The Jive skin for the Fullscreen desktop application
DESCRIPTION
This applet implements the fullscreen Jive skin.
FUNCTIONS
Applet related methods are described in jive.Applet. FullscreenSkin overrides the following methods:
applets.FullscreenSkin.FullscreenSkinMeta
applets.FullscreenSkin.FullscreenSkinMeta
applets.FullscreenSkin.FullscreenSkinMeta - FullscreenSkin meta-info
DESCRIPTION
See applets.FullscreenSkin.FullscreenSkinApplet.
FUNCTIONS
See jive.AppletMeta for a description of standard applet meta functions.
applets.HttpAuth.HttpAuthApplet
applets.HttpAuth.HttpAuthApplet
applets.HttpAuth.HttpAuthApplet - An applet to configure user/password to SqueezeCenter
DESCRIPTION
This applets lets the user configure a username and password to SqueezeCenter
FUNCTIONS
Applet related methods are described in jive.Applet. HttpAuthApplet overrides the following methods:
applets.HttpAuth.HttpAuthMeta
applets.HttpAuth.HttpAuthMeta
applets.HttpAuth.HttpAuthMeta - HttpAuth meta-info
DESCRIPTION
See applets.HttpAuth.HttpAuthMeta.
FUNCTIONS
See jive.AppletMeta for a description of standard applet meta functions.
applets.InfoBrowser.InfoBrowserApplet
applets.InfoBrowser.InfoBrowserApplet
Info Browser Applet
DESCRIPTION
Browser for information sources using the Slimserver InfoBrowser plugin.
applets.InfoBrowser.InfoBrowserMeta
applets.LogSettings.LogSettingsApplet
applets.LogSettings.LogSettingsApplet
applets.LogSettings.LogSettingsApplet - An applet to control Jive log verbosity.
DESCRIPTION
This applets collects the log categories defined in the running Jive program and displays each along with their respective verbosity level. Changing the level is taken into account immediately.
FUNCTIONS
Applet related methods are described in jive.Applet. LogSettingsApplet overrides the following methods:
applets.LogSettings.LogSettingsMeta
applets.LogSettings.LogSettingsMeta
applets.LogSettings.LogSettingsMeta - LogSettings meta-info
DESCRIPTION
See applets.LogSettings.LogSettingsApplet.
FUNCTIONS
See jive.AppletMeta for a description of standard applet meta functions.
applets.MacroPlay.MacroPlayApplet
applets.MacroPlay.MacroPlayApplet
applets.MacroPlay.MarcoPlayApplet - applet to play ui sequences for testing.
DESCRIPTION
This applet will play ui sequences using a lua script for testing.
applets.MacroPlay.MacroPlayMeta
applets.MacroPlay.MacroPlayMeta
applets.AutoFWUpdate.AutoFWUpdateMeta - AutoFWUpdate meta-info
DESCRIPTION
See applets.AutoFWUpdate.AutoFWUpdateApplet.
FUNCTIONS
See jive.AppletMeta for a description of standard applet meta functions.
applets.NowPlaying.NowPlayingApplet
applets.NowPlaying.NowPlayingMeta
applets.Playback.PlaybackApplet
applets.Playback.PlaybackMeta
applets.Quit.QuitMeta
applets.Quit.QuitMeta
applets.Quit.QuitMeta - Quit meta-info
DESCRIPTION
FUNCTIONS
See jive.AppletMeta for a description of standard applet meta functions.
applets.ScreenSavers.ScreenSaversApplet
applets.ScreenSavers.ScreenSaversApplet
applets.ScreenSavers.ScreenSaversApplet - Screensaver manager.
DESCRIPTION
This applets hooks itself into Jive to provide a screensaver service, complete with settings.
FUNCTIONS
Applet related methods are described in jive.Applet. ScreenSaversApplet overrides the following methods:
applets.ScreenSavers.ScreenSaversApplet:free()
Overridden to return always false, this ensure the applet is permanently loaded.
screensaverWindow(window)
Register the window as a screensaver window. This is used to maintain the the screensaver activity, and adds some default listeners for screensaver behaviour.
applets.ScreenSavers.ScreenSaversMeta
applets.ScreenSavers.ScreenSaversMeta
applets.ScreenSavers.ScreenSaversMeta - ScreenSavers meta-info
DESCRIPTION
See applets.ScreenSavers.ScreenSaversApplet.
FUNCTIONS
See jive.AppletMeta for a description of standard applet meta functions.
applets.Screenshot.ScreenshotApplet
applets.Screenshot.ScreenshotApplet
applets.Screenshot.ScreenshotApplet - Screenshot, press and hole Pause and Rew to take a screenshot.
DESCRIPTION
This applet saves screenshots as bmp files using a key combination to lock the Jive screen.
FUNCTIONS
Applet related methods are described in jive.Applet. ScreenshotApplet overrides the following methods:
applets.Screenshot.ScreenshotApplet:free()
Overridden to return always false, this ensure the applet is permanently loaded.
applets.Screenshot.ScreenshotMeta
applets.Screenshot.ScreenshotMeta
applets.Screenshot.ScreenshotMeta - Screenshot meta-info
DESCRIPTION
See applets.Screenshot.ScreenshotApplet.
FUNCTIONS
See jive.AppletMeta for a description of standard applet meta functions.
applets.SelectPlayer.SelectPlayerApplet
applets.SelectPlayer.SelectPlayerApplet
applets.SelectPlayer.SelectPlayerApplet - Applet to select currently active player
DESCRIPTION
Gets list of all available players and displays for selection. Selection should cause main menu to update (i.e., so things like "now playing" are for the selected player)
FUNCTIONS
Applet related methods are described in jive.Applet.
applets.SelectPlayer.SelectPlayerMeta
applets.SelectPlayer.SelectPlayerMeta
applets.SelectPlayer.SelectPlayerMeta - SelectPlayer meta-info
DESCRIPTION
See applets.SelectPlayer.SelectPlayer.
FUNCTIONS
See jive.AppletMeta for a description of standard applet meta functions.
applets.SelectSkin.SelectSkinApplet
applets.SelectSkin.SelectSkinApplet
applets.SelectSkin.SelectSkinApplet - An applet to select different SqueezePlay skins
DESCRIPTION
This applet allows the SqueezePlay skin to be selected.
FUNCTIONS
Applet related methods are described in jive.Applet. SelectSkinApplet overrides the following methods:
applets.SelectSkin.SelectSkinMeta
applets.SelectSkin.SelectSkinMeta
applets.SelectSkin.SelectSkinMeta - Select SqueezePlay skin
DESCRIPTION
See applets.SelectSkin.SelectSkinApplet.
FUNCTIONS
See jive.AppletMeta for a description of standard applet meta functions.
applets.SetupAppletInstaller.SetupAppletInstallerApplet
applets.SetupAppletInstaller.SetupAppletInstallerApplet
applets.SetupAppletInstaller.SetupAppletInsallerApplet
DESCRIPTION
Allows applets to be downloaded from SqueezeCenter to jive
SC responds to a query for 'jiveapplets' with a list of applets including name, version and a url for a zipfile containing the applet. Users may select which applets to download, they will then be downloaded and extracted into the applet directory.
Assumptions: - applet name returned by SC is used as the foldername for the applet - the zip file downloaded contains files but not directories - all files are extracted into the applet directory - the name of the applet returned by SC should match the files contained in the zip file, i.e. <name>Applet.lua and <name>Meta.lua
applets.SetupAppletInstaller.SetupAppletInstallerMeta
applets.SetupAppletInstaller.SetupAppletInstallerMeta
applets.SetupAppletInstaller.SetupAppletInstallerMeta - SetupAppletInstaller meta-info
DESCRIPTION
See applets.SetupAppletInstaller.SetupAppletInstallerApplet.
FUNCTIONS
See jive.AppletMeta for a description of standard applet meta functions.
applets.SetupDateTime.SetupDateTimeApplet
applets.SetupDateTime.SetupDateTimeApplet
applets.SetupDateTime.SetupDateTime - Add a main menu option for setting up date and time formats
DESCRIPTION
Allows user to select different date and time settings
FUNCTIONS
Applet related methods are described in jive.Applet.
applets.SetupDateTime.SetupDateTimeMeta
applets.SetupDateTime.SetupDateTimeMeta
applets.SetupDateTime.SetupDateTimeMeta - SetupDateTime meta-info
DESCRIPTION
See applets.SetupDateTime.SetupDateTimeApplet.
FUNCTIONS
See jive.AppletMeta for a description of standard applet meta functions.
applets.SetupLanguage.SetupLanguageApplet
applets.SetupLanguage.SetupLanguageApplet
applets.SetupLanguage.SetupLanguage - Add a main menu option for setting up language
DESCRIPTION
Allows user to select language used in Jive
FUNCTIONS
Applet related methods are described in jive.Applet.
applets.SetupLanguage.SetupLanguageMeta
applets.SetupLanguage.SetupLanguageMeta
applets.SetupLanguage.SetupLanguageMeta - SetupLanguage meta-info
DESCRIPTION
See applets.SetupLanguage.SetupLanguageApplet.
FUNCTIONS
See jive.AppletMeta for a description of standard applet meta functions.
applets.SetupNetTest.SetupNetTestApplet
applets.SetupNetTest.SetupNetTestApplet
SetupNetTest Applet
DESCRIPTION
Test the network bandwidth between SqueezeCenter and a Player
applets.SetupNetTest.SetupNetTestMeta
applets.SetupSoundEffects.loadPriority
applets.SetupSoundEffects.SetupSoundEffectsApplet
applets.SetupSoundEffects.SetupSoundEffectsApplet
applets.SetupSoundEffects.SetupSoundEffectsApplet - An applet to control Jive sound effects.
DESCRIPTION
This applets lets the user setup what sound effects are played.
FUNCTIONS
Applet related methods are described in jive.Applet. SetupSoundEffectsApplet overrides the following methods:
applets.SetupSoundEffects.SetupSoundEffectsMeta
applets.SetupSoundEffects.SetupSoundEffectsMeta
applets.SetupSoundEffects.SetupSoundEffectsMeta - SetupSoundEffects meta-info
DESCRIPTION
See applets.SetupSoundEffects.SetupSoundEffectsApplet.
FUNCTIONS
See jive.AppletMeta for a description of standard applet meta functions.
applets.SetupSqueezebox.SetupSqueezeboxApplet
applets.SetupSqueezebox.SetupSqueezeboxMeta
applets.SetupWallpaper.SetupWallpaperApplet
applets.SetupWallpaper.SetupWallpaperApplet
applets.SetupWallpaper.SetupWallpaperApplet - Wallpaper selection.
DESCRIPTION
This applet implements selection of the wallpaper for the jive background image.
The applet includes a selection of local wallpapers which are shipped with jive. It also allows wallpapers to be downloaded and selected from the currently attached server.
FUNCTIONS
Applet related methods are described in jive.Applet. SetupWallpaperApplet overrides the following methods:
applets.SetupWallpaper.SetupWallpaperMeta
applets.SetupWallpaper.SetupWallpaperMeta
applets.SetupWallpaper.SetupWallpaperMeta - SetupWallpaper meta-info
DESCRIPTION
See applets.SetupWallpaper.SetupWallpaperApplet.
FUNCTIONS
See jive.AppletMeta for a description of standard applet meta functions.
applets.SetupWelcome.SetupWelcomeApplet
applets.SetupWelcome.SetupWelcomeApplet
applets.SetupWelcome.SetupWelcome - Add a main menu option for setting up language
DESCRIPTION
Allows user to select language used in Jive
FUNCTIONS
Applet related methods are described in jive.Applet.
applets.SetupWelcome.SetupWelcomeMeta
applets.SetupWelcome.SetupWelcomeMeta
applets.SetupWelcome.SetupWelcomeMeta - SetupWelcome meta-info
DESCRIPTION
See applets.SetupWelcome.SetupWelcomeApplet.
FUNCTIONS
See jive.AppletMeta for a description of standard applet meta functions.
applets.SlimBrowser.DB
applets.SlimBrowser.DB
applets.SlimBrowser.DB - Item database.
DESCRIPTION
This object is designed to store and manage the browsing data Jive receives.
Conceptually, this data is a long list of items n1, n2, n3..., which is received by chunks. Each chunk is a table with many properties but of particular interest are: - count: indicates the number of items in the long list - offset: indicates the first index of the data in the item_obj array - item_obj: array of consecutive elements, from offset to offset+#item_obj - playlist_timestamp: timestamp of the data (optional)
If count is 0, then the other fields are optional (and may not even be looked at).
Fresh data always refreshes old data, except if it would be cost prohibitive to do so.
There should be one DB per long list "type". If the count or the timestamp of the long list is different from the existing stored info, the existing info is discarded.
SYNOPSIS
TODO
FUNCTIONS
applets.SlimBrowser.Scanner
applets.SlimBrowser.SlimBrowserApplet
applets.SlimBrowser.SlimBrowserApplet
applets.SlimBrowser.SlimBrowserApplet - Browse music and control players.
DESCRIPTION
TODO
SYNOPSIS
TODO
FUNCTIONS
applets.SlimBrowser.SlimBrowserApplet:free()
Overridden to close our player.
applets.SlimBrowser.SlimBrowserApplet:init()
Overridden to subscribe to events about players
applets.SlimBrowser.SlimBrowserMeta
applets.SlimBrowser.SlimBrowserMeta
applets.SlimBrowser.SlimBrowserMeta - SlimBrowser meta-info
DESCRIPTION
See applets.SlimBrowser.SlimBrowserApplet.
FUNCTIONS
See jive.AppletMeta for a description of standard applet meta functions.
applets.SlimBrowser.Volume
applets.SlimDiscovery.SlimDiscoveryApplet
applets.SlimDiscovery.SlimDiscoveryMeta
applets.SlimDiscovery.SlimDiscoveryMeta
applets.SlimDiscovery.SlimDiscoveryMeta - SlimDiscovery meta-info
DESCRIPTION
See applets.SlimDiscovery.SlimDiscoveryApplet.
FUNCTIONS
See jive.AppletMeta for a description of standard applet meta functions.
applets.SqueezeNetworkPIN.SqueezeNetworkPINApplet
applets.SqueezeNetworkPIN.SqueezeNetworkPINMeta
applets.Test.TestApplet
applets.Test.TestApplet
applets.Test.TestApplet - User Interface Tests
DESCRIPTION
This applets is used to test and demonstrate the jive.ui.* stuff.
FUNCTIONS
Applet related methods are described in jive.Applet. TestApplet overrides the following methods:
applets.Test.TestMeta
applets.Test.TestMeta
applets.Test.TestMeta - Test meta-info
DESCRIPTION
FUNCTIONS
See jive.AppletMeta for a description of standard applet meta functions.