Documentation ¶
Overview ¶
Package cdtype defines main types and constants for Cairo-Dock applets.
External applets are small programs spawned by the dock to manage dedicated icons. Once started, the program can use his icon to display informations and receive user interactions like mouse events and keyboard shortcuts.
This API now covers all the dock external features, and most common applets needs, like the automatic config loading, a menu builder, with a really short and simple code.
I tried to make this applet API as straightforward and simple to use as I could so feel free to test it and post your comments on the forum.
Applet lifecycle ¶
The applet loading is handled by the dock, then it's up the applet to act upon events received to work as expected and quit when needed. Be aware that you don't control your applet, the dock does. Most of your work is to define config keys, connect events and make them useful with your config options.
Automatic applet creation steps, and their effect, when the dock icon is enabled:
- Create the applet object with its dock backend (DBus or gldi) and events: app := NewApplet(base, events)
- Connect the applet backend to cairo-dock to activate events callbacks.
- Load config, fill the data struct and prepare a Defaults object for Init.
- Initialize applet with the filled Defaults: app.Init(def, true).
- Defaults are applied, restoring icons defaults to missing fields.
- Start and run the polling loop if needed with a first instant check.
At this point, the applet is alive and running ¶
Init (and PreInit) will be triggered again (with a load config or not) on some more or less mysterious occasions, from an applet or dock config save, to a dock move, or even a system package install.
While alive the applet can:
- Act on icon to display informations.
- Receive user/dock events.
- Regular polling if set.
Stops when End event is received from the dock to close the applet.
Register applet in the dock ¶
To register our "demo" applet in the dock, we have to link it as "demo" in the external applets dir.
~/.config/cairo-dock/third-party/demo This can be done easily once you have configured the SOURCE location in the Makefile with the "make link" command.
or use the external system directory
/usr/share/cairo-dock/plug-ins/Dbus/third-party/
Notes ¶
A lot more tips are to be found for each method, but here are a few to help you start:
*The applet activation requires some arguments provided by the dock with the command line options. They will be parsed and used by the backend before the creation. *Only a few applet methods are available at creation (before Init) like Log and file access (Name, FileLocation, FileDataDir...). Others like icon actions can be set in callbacks that will only be used later when the backend is running. *The current directory by default is the applet directory, but to be safe don't rely on it and use chdir or absolute paths for all your file operations. *If you want to publish the package or ask for help, it would be easier if the applet is located in a "go gettable" directory (just use the same location in GOPATH as you have in your public repo, like this API). *The default Reload event will launch an Init call and restart the poller if any (but this can be overridden, see cdapplet.SetEvents).
Backends ¶
Applets can use two different backends to interact with the dock:
gldi: This require the applet to be compiled and launched with the rework version of the dock. For brave testers, but can have great rewards as this unlock all dock and applets capabilities.
DBus: As external applets, they will be limited to basic dock features but are easy to make and deploy.
We have two loaders for the DBus backend: *StandAlone: Great to work on the applet as it can be reloaded easily. This is the default mode for most external applets but can take some disk space if you install a lot of applets with big dependencies. *Applet service: Packing multiple applets in the same executable reduce CPU, memory and disk usage when you have some of them enabled, but it leads to a binary choice (the big pack or nothing). see the launcher forwarder replacing applet binary: cmd/cdc/data/tocdc
Service registration ¶
When in StandAlone mode, we need to create the binary in the applet data dir. We're using a minimal main package there to start as external applet.
func main() { appdbus.StandAlone(Mem.NewApplet) }
When not in StandAlone mode, we need to register the applet with a go init. This allow the different backends to start the applet on demand.
func init() { cdtype.Applets.Register("demo", NewApplet) }
Services are enabled with build tags in the services/allapps package. They are just declared to load them and trigger the registration. The build tag 'all' is used to enable all known services at once.
Evolutions ¶
All the base actions and callbacks are provided by Cairo-Dock, and are in stable state for years, so everything provided will remain in almost the same format.
We now reached a point where a few evolutions will be made to extend some methods to get more benefit from the gldi backend, with a fallback as best as possible on the DBus backend (like shortkeys registered as expected on gldi). The goal here will be to reduce the gap between internal C applets and go applets as we have numerous options still unavailable (ex on gauge/graph). One of those method will set renderers label formating functions for vertical and horizontal dock modes.
We could still introduce minor API changes to fix some issues you may encounter while using it, but this should be mostly cosmetic to improve readability when needed.
Real applets code and data ¶
You can see real applets code and configuration in applets and services subdirs.
Code repository (real applets) http://github.com/sqp/godock/tree/master/services Data repository (config files) http://github.com/sqp/godock/tree/master/applets
Small examples ¶
For easier maintenance, sources for the applet will be separated from the data, So we're creating 2 directories for each applet. You can use a src subdir to keep them grouped.
In the examples we will use demo and demo/src.
The applet management file: demo/src/demo.go The applet configuration file: demo/src/config.go
Example (Applet) ¶
package main import ( "github.com/sqp/godock/libs/cdtype" // Applet types. ) // //-------------------------------------------------------------[ src/demo.go ]-- // Applet defines a dock applet. // // We start with the applet declaration with at least two mandatory items: // // -Extend an AppBase. // -Provide the config struct (see the config example). type Applet struct { cdtype.AppBase // Extends applet base and dock connection. conf *appletConf // Applet configuration data. } // NewApplet create a new applet instance. // // It will be trigered remotely by the dock when the applet icon is created. // Only called once for each running instance. // // The goal is to: // // -Create and fill the applet struct. // -Set the config pointer, and maybe some actions. // -Register (dock to) applet events (See cdtype.Events for the full list). // -Declare and load permanent items required during all the applet lifetime. // (those who do not require a config setting, unless it's in a callback). func NewApplet(base cdtype.AppBase, events *cdtype.Events) cdtype.AppInstance { app := &Applet{AppBase: base} app.SetConfig(&app.conf) // Events. // Forward click events to the defined command launcher. events.OnClick = app.Command().Callback(cmdClickLeft) events.OnMiddleClick = app.Command().Callback(cmdClickMiddle) // For simple callbacks event, use a closure. events.OnDropData = func(data string) { app.Log().Info("dropped", data) } events.OnBuildMenu = func(menu cdtype.Menuer) { // Another closure. menu.AddEntry("disabled entry", "icon-name", nil) menu.AddSeparator() menu.AddEntry("my action", "system-run", func() { app.Log().Info("clicked") }) } events.OnScroll = app.myonScroll // Or use another function with the same args. // // Create and set your other permanent items here... return app } // Applet init // // Then we will have to declare the mandatory Init(loadConf bool) method: // // Init is called at startup and every time the applet is moved or asked to // reload by the dock. // When called, the config struct has already been filled from the config file, // and some Defaults fields may already be set. // You may still have to set the poller interval, some commands or declare // shortkeys callbacks. // // Defaults fields not set will be reset to icon defaults (apply even if blank). // // -The config data isn't available before the first Init. // -Use PreInit event if you need to act on the previous config before deletion. // -cdtype.ConfGroupIconBoth sets those def fields: Label, Icon and Debug. // -Don't forget that you may have to clean up some old display or data. func (app *Applet) Init(def *cdtype.Defaults, confLoaded bool) { // Set defaults to dock icon: display and controls. def.Commands = cdtype.Commands{ cmdClickLeft: cdtype.NewCommandStd( app.conf.LeftAction, app.conf.LeftCommand, app.conf.LeftClass), cmdClickMiddle: cdtype.NewCommandStd( app.conf.MiddleAction, app.conf.MiddleCommand), } // Set your other variable settings here... } // //------------------------------------------------------------[ doc and test ]-- // This is an event callback function to be filled with your on scroll actions. func (app *Applet) myonScroll(scrollUp bool) { // ... } // //------------------------------------------------------------[ doc and test ]-- func main() { testApplet(NewApplet) }
Output: true
Example (Config) ¶
package main // The configuration loading can be fully handled by LoadConfig if the config // struct is created accordingly. // // Main conf struct: one nested struct for each config page with its name // referred to in the "group" tag. // // Sub conf structs: one field for each setting you need with the keys and types // referring to those in your .conf file loaded by the dock. As fields are // filled by reflection, they must be public and start with an uppercase letter. // // If the name of your field is the same as in the config file, just declare it. // // If you have different names, or need to refer to a lowercase field in the file, // you must add a "conf" tag with the name of the field to match in the file. // // The applet source config file will be demo/src/config.go // // The matching configuration file will better be created by copying an existing // applet config, and adapting it to your needs. // More documentation about the dock config file can be found there: // // cftype keys: http://godoc.org/github.com/sqp/godock/widgets/cfbuild/cftype#KeyType // config test file: https://raw.githubusercontent.com/sqp/godock/master/test/test.conf // cairo-dock wiki: http://www.glx-dock.org/ww_page.php?p=Documentation&lang=en#27-Building%20the%20Applet%27s%20Configuration%20Window // //-----------------------------------------------------------[ src/config.go ]-- import ( "github.com/sqp/godock/libs/cdapplet" "github.com/sqp/godock/libs/cdtype" "fmt" ) // //---------------------------------------------------------------[ constants ]-- // Emblem position for polling activity. const emblemAction = cdtype.EmblemTopRight // Define a list of commands references. const ( cmdClickLeft = iota cmdClickMiddle ) // Define a list of actions references. const ( ActionNone = iota ActionOpenThing ActionEditThing ) // LocalId defines an int like used as constant reference, parsed by the conf. type LocalId int // //------------------------------------------------------------------[ config ]-- type appletConf struct { cdtype.ConfGroupIconBoth `group:"Icon"` groupConfiguration `group:"Configuration"` } type groupConfiguration struct { GaugeName string Devices []string LeftAction int LeftCommand string LeftClass string MiddleAction int MiddleCommand string // We can parse an int like type, used with iota definitions lists. LocalId LocalId // With a Duration, we can provide a default, set the unit and a min value. UpdateInterval cdtype.Duration `default:"5"` // this one is in second. // // Another duration value with a default every hour and 10 minutes minimum. OtherInterval cdtype.Duration `default:"60" min:"10" unit:"minute"` // The template is loaded from appletDir/cdtype.TemplateDir // or an absolute path. // The .tmpl ext is optional in config, it will be matched with or without. DialogTemplate cdtype.Template `default:"myfile"` // Shortkey: The callback can be set directly with the tag action. // This action number must match your applet defined actions numbers. // Otherwise, set Call or CallE on your config shortkey at Init. // // (Note when in external applet mode (known dock TODO): // shortkey desc is not forwarded to the "all shortkeys page". // ShortkeyOpenThing cdtype.Shortkey `action:"1"` ShortkeyEditThing cdtype.Shortkey `action:"2"` } // //---------------------------------------------------------------------[ doc ]-- func main() {} func testApplet(callnew cdtype.NewAppletFunc) { // This is not a valid way to start an applet. // Only used here to trigger the loading and output check. base := cdapplet.New() app := cdapplet.Start(callnew, base) fmt.Println(app != nil, app.Name()) }
Output:
Example (Files) ¶
package main // Files needed in the "demo" directory // // demo the executable binary or script, without extension (use the shebang on the first line). // demo.conf the default config file (see above for the options syntax). // auto-load.conf the file describing our applet. // applet.go source to load and start the applet as standalone. // // Files naming convention: // // demo must match the directory name, this is used as applet name. // demo.conf same as applet name with extension .conf. // auto-load.conf constant. // applet.go only used by convention, can be customized. // //----------------------------------------------------------[ auto-load.conf ]-- const AutoLoadDotConf = ` [Register] # Author of the applet author = AuthorName # A short description of the applet and how to use it. description = This is the description of the applet.\nIt can be on several lines. # Category of the applet : 2 = files, 3 = internet, 4 = Desktop, 5 = accessory, 6 = system, 7 = fun category = 5 # Version of the applet; change it every time you change something in the config file. Don't forget to update the version both in this file and in the config file. version = 0.0.1 # Default icon to use if no icon has been defined by the user. If not specified, or if the file is not found, the "icon" file will be used. icon = # Whether the applet will act as a launcher or not (like Pidgin or Transmission) act as launcher = false ` // //---------------------------------------------------------------[ applet.go ]-- const AppletDotGo = ` package main import ( demo "demo/src" // Package with your applet source. "github.com/sqp/godock/libs/appdbus" // Connection to cairo-dock. ) func main() { appdbus.StandAlone(demo.NewApplet) } ` // //----------------------------------------------------------------[ OPTIONAL ]-- // Files optional in the "demo" directory: // // icon the default icon of the applet (without extension, can be any image format). // preview an image preview of the applet (without extension, can be any image format). // Makefile shortcuts to build and link the applet. // //----------------------------------------------------------------[ Makefile ]-- // A Makefile with a default build is only required if you want to use the // build applet action of the Update applet (really helpful to build/restart). const Makefile = ` TARGET=demo SOURCE=github.com/sqp/godock/applets # Default is standard build for current arch. %: build build: go build -o $(TARGET) $(SOURCE)/$(TARGET) # make a link to the user external directory for easy install. link: ln -s $(GOPATH)/src/$(SOURCE)/$(TARGET) $(HOME)/.config/cairo-dock/third-party/$(TARGET) ` // //---------------------------------------------------------------------[ doc ]-- func main() {}
Output:
Example (Poller) ¶
package main import ( "github.com/sqp/godock/libs/cdtype" // Applet types. ) // //-------------------------------------------------------------[ src/demo.go ]-- // The applet main loop can handle a polling service to help you update data on a // regular basis. The poller will be agnostic of what's happening, he will just // trigger the provided call at the end of timer or in case of manual reset with // app.Poller().Restart(). // Define an applet with a polling service. type PollerApplet struct { cdtype.AppBase // Extends applet base and dock connection. conf *appletConf // Applet configuration data. service *pollingService // The action triggered by the poller. } // Create your poller with the applet. func NewPollerApplet(base cdtype.AppBase, events *cdtype.Events) cdtype.AppInstance { app := &PollerApplet{AppBase: base} app.SetConfig(&app.conf) // Events. // ... // Polling service. app.service = newService(app) // This will depend on your applet polling service. poller := app.Poller().Add(app.service.Check) // Create poller and set action callback. // The poller can trigger other actions before and after the real call. // // This can be used for example to display an activity emblem on the icon. // imgPath := "/usr/share/cairo-dock/icons/icon-bubble.png" poller.SetPreCheck(func() { app.SetEmblem(imgPath, emblemAction) }) poller.SetPostCheck(func() { app.SetEmblem("none", emblemAction) }) // The example use constant paths, but you can get a path relative to your applet: // imgPath := app.FileLocation("icon", "iconname.png") // Or you can define custom calls. // app.Poller().SetPreCheck(app.service.onStarted) // app.Poller().SetPostCheck(app.service.onFinished) // Create and set your other permanent items here... return app } // Init is called after load config. We'll set the poller interval. func (app *PollerApplet) Init(def *cdtype.Defaults, confLoaded bool) { // In Init, we'll use the Defaults as it's already provided. def.PollerInterval = app.conf.UpdateInterval.Value() // But you can also set a poller interval directly anytime. app.Poller().SetInterval(app.conf.UpdateInterval.Value()) // Set your other defaults here... // Set your other variable settings here... } // //---------------------------------------------------------[ Polling Service ]-- // appletControl defines methods needed on the applet by the polling service. // It's better to declare an interface to restrict the polling usage and keep // the rest of this service as agnostic of the others as possible. type appletControl interface { SetIcon(string) error Log() cdtype.Logger } // pollingService defines a polling service skelton. type pollingService struct { app appletControl // polling services often need to interact with the applet. } // newService creates a polling service skelton. func newService(app appletControl) *pollingService { return &pollingService{app} } // Check is the real polling action // // It's doing its routinely task, display or forward its result, and that's all. func (p *pollingService) Check() { // This is where the polling service action takes place. p.app.Log().Info("checked") } // //------------------------------------------------------------[ doc and test ]-- func main() { testApplet(NewPollerApplet) }
Output: true
Example (WithActions) ¶
package main import ( "github.com/sqp/godock/libs/cdtype" // Applet types. ) // //-------------------------------------------------------------[ src/demo.go ]-- // Applet data and controlers. type AppletWithAction struct { cdtype.AppBase // Extends applet base and dock connection. conf *appletConf // Applet configuration data. } // NewApplet create a new applet instance. func NewAppletWithAction(base cdtype.AppBase, events *cdtype.Events) cdtype.AppInstance { app := &AppletWithAction{AppBase: base} app.SetConfig(&app.conf, app.actions()...) // Actions are added here. // Events. // ... return app } // Set interval in Init with your config values. func (app *AppletWithAction) Init(def *cdtype.Defaults, confLoaded bool) { // Defaults. // You can assign shortkeys callbacks manually. // This is only needed when the "action" tag is not set in the conf. app.conf.ShortkeyOpenThing.Call = func() { // ... } // A second version of the callback can return an error that will be logged. // CallE is the only one used if set. app.conf.ShortkeyEditThing.CallE = func() error { // ... return nil } // Shortkeys should have been found in the conf, listed in def.Shortkeys. // They will be added or refreshed at the SetDefaults after Init. } // //-------------------------------------------------------[ action definition ]-- // Define applet actions. // Actions order in this list must match the order of defined actions numbers. func (app *AppletWithAction) actions() []*cdtype.Action { return []*cdtype.Action{ { ID: ActionNone, Menu: cdtype.MenuSeparator, }, { ID: ActionOpenThing, Name: "Open that thing", Icon: "icon-name", Call: app.askText, }, { ID: ActionEditThing, Name: "Edit that thing", Icon: "other-icon", Call: app.askText, }, } } // //--------------------------------------------------------[ action callbacks ]-- // This is used as action (no arg) to popup a string entry dialog. func (app *AppletWithAction) askText() { app.PopupDialog(cdtype.DialogData{ Message: "Enter some text", Buttons: "ok;cancel", Widget: cdtype.DialogWidgetText{}, Callback: cdtype.DialogCallbackValidString(func(data string) { app.Log().Info("user validated with ok or enter", data) }), }) } // //------------------------------------------------------------[ doc and test ]-- func main() { testApplet(NewAppletWithAction) }
Output: true
Index ¶
- Constants
- Variables
- func Categories() []string
- func DialogCallbackValidInt(call func(data int)) func(int, interface{})
- func DialogCallbackValidNoArg(call func()) func(int, interface{})
- func DialogCallbackValidString(call func(data string)) func(int, interface{})
- func DownloadPack(log Logger, hintDist, dir, name string) (string, error)
- func InitConf(log Logger, orig, dest string) error
- type Action
- type AppAction
- type AppBackend
- type AppBase
- type AppCommand
- type AppIcon
- type AppInstance
- type AppPoller
- type CategoryType
- type Command
- type Commands
- type ConfGroupIconBoth
- type ConfKeyer
- type ConfUpdater
- type ContainerPosition
- type ContainerType
- type Defaults
- type DeskletVisibility
- type DialogData
- type DialogWidgetList
- type DialogWidgetScale
- type DialogWidgetText
- type Duration
- type EmblemPosition
- type Events
- type GetFieldKey
- type IconBase
- type IconProperties
- type IconProperty
- type IconRenderer
- type IconWindow
- type InfoPosition
- type ListApps
- type LogFmt
- type LogLevel
- type LogMsg
- type LogOut
- type Logger
- type MenuItemType
- type MenuWidgeter
- type Menuer
- type NewAppletFunc
- type PackageType
- type RenderSimple
- type RendererGraphType
- type Shortkey
- type Template
- type ThemeExtra
- type ToDefaultser
Examples ¶
Constants ¶
const ( // SubDirTemplate defines the default templates dir name in applets dir. SubDirTemplate = "templates" // SubDirThemeExtra defines the default theme extra dir name in applets dir. SubDirThemeExtra = "themes" )
Applets resources paths, inside their data folder.
const ( DialogButtonFirst = 0 // Answer when the user press the first button (will often be ok). DialogKeyEnter = -1 // Answer when the user press enter. DialogKeyEscape = -2 // Answer when the user press escape. )
Dialog answer keys.
Variables ¶
var Applets = make(ListApps)
Applets stores registered applets creation calls.
Functions ¶
func Categories ¶
func Categories() []string
Categories returns the list of CategoryType as translated text.
func DialogCallbackValidInt ¶
DialogCallbackValidInt checks user answer of a dialog to launch the callback with the value asserted as an int. Will be triggered only by the first button pressed or the enter key.
func DialogCallbackValidNoArg ¶
func DialogCallbackValidNoArg(call func()) func(int, interface{})
DialogCallbackValidNoArg prepares a dialog callback launched only on user confirmation. The provided call is triggerred if the user pressed the enter key or the first button.
func DialogCallbackValidString ¶
DialogCallbackValidString checks user answer of a dialog to launch the callback with the value asserted as a string. Will be triggered only by the first button pressed or the enter key.
func DownloadPack ¶
DownloadPack downloads a dock package from the remote server.
Types ¶
type Action ¶
type Action struct { ID int Name string Call func() Icon string Menu MenuItemType Bool *bool // reference to active value for checkitems. Group int // Radio item group. Tooltip string // Entry tooltip. // in fact all actions are threaded in the go version, but we could certainly // use this as a "add to actions queue" to prevent problems with settings // changed while working, or double launch. // Threaded bool }
Action is an applet internal actions that can be used for callbacks or menu.
type AppAction ¶
type AppAction interface { // Add adds actions to the list. // Add(acts ...*Action) // Len returns the number of actions defined. // Len() int // Callback returns a callback to the given action ID. // Callback(ID int) func() // CallbackInt returns a callback to the given action ID with an int input, // for left click events. // CallbackInt(ID int) func(int) // Count returns the number of started actions. // Count() int // ID finds the ID matching given action name. // ID(name string) int // Launch starts the desired action by ID. // Launch(ID int) // SetBool sets the pointer to the boolean value for a checkentry menu field. // SetBool(ID int, boolPointer *bool) // SetMax sets the maximum number of actions that can be started at the same time. // SetMax(max int) // SetIndicators set the pre and post action callbacks. // SetIndicators(onStart, onStop func()) // BuildMenu fills the menu with the given actions list. // // MenuCheckBox: If Call isn't set, a default toggle callback will be used. // BuildMenu(menu Menuer, actionIds []int) // CallbackMenu provides a fill menu callback with the given actions list. // CallbackMenu(actionIds ...int) func(menu Menuer) }
AppAction defines a launcher of manageable actions for applets.
type AppBackend ¶
AppBackend extends AppIcon with SetOnEvent used for internal connection.
type AppBase ¶
type AppBase interface { // Extends AppIcon, for all interactions with the dock icon. // AppIcon // --- Common --- // // Name returns the applet name as known by the dock. As an external app = dir name. // Name() string // Name returns the applet name as known by the dock. As an external app = dir name. // Translate translates a string in the applet domain. // Translate(str string) string // SetDefaults set basic defaults icon settings in one call. // Empty fields will be reset, so this is better used in the Init() call. // SetDefaults(def Defaults) // SetConfig sets the applet config pointer and can add actions. // SetConfig(confPtr interface{}, actions ...*Action) // --- Files --- // // FileLocation returns the full path to a file in the applet data dir. // FileLocation(filename ...string) string // FileDataDir returns the path to the config root dir (~/.config/cairo-dock). // FileDataDir(filename ...string) string // RootDataDir. // --- Config --- // // LoadConfig will try to create and fill the given config struct with data from // the configuration file. // // Won't do anything if loadConf is false. // If an error is returned, the backend is expected to unload the applet // (or crash in a standalone mode). // LoadConfig(loadConf bool) (Defaults, error) // UpdateConfig opens the applet config file for edition. // // You must ensure that Save or Cancel is called, and fast to prevent memory // leaks and deadlocks. // UpdateConfig() (ConfUpdater, error) // --- Grouped Interfaces --- // // Action returns a manager of launchable actions for applets // Action() AppAction // Command returns a manager of launchable commands for applets // Command() AppCommand // Poller returns the applet poller if any. // Poller() AppPoller // Log gives access to the applet logger. // Log() Logger // contains filtered or unexported methods }
AppBase groups methods provided to the applet with methods needed on start.
type AppCommand ¶
type AppCommand interface { // Add adds a command to the list. // Add(key int, cmd *Command) // Callback returns a callback to the given command ID. // To bind with event OnClick or OnMiddleClick. // Callback(ID int) func() // CallbackInt returns a callback to the given command ID with an int input, // To bind with event OnClickMod. // CallbackInt(ID int) func(int) // Launch executes one of the configured command by its reference. // Launch(ID int) // FindMonitor return the configured window class for the command. // FindMonitor() string // Clear clears the commands list. // Clear() }
AppCommand defines a launcher of manageable commands for applets.
type AppIcon ¶
type AppIcon interface { // Extends IconBase. The main icon also has the same actions as subicons, // so subicons are used the same way as the main icon. // IconBase // DemandsAttention is like the Animate method, but will animate the icon // endlessly, and the icon will be visible even if the dock is hidden. If the // animation is an empty string, or "default", the animation used when an // application demands the attention will be used. // The first argument is true to start animation, or false to stop it. // DemandsAttention(start bool, animation string) error // PopupDialog opens a dialog box. // The dialog can contain a message, an icon, some buttons, and a widget the // user can act on. // // Adding buttons will trigger the provided callback when the user use them. // // See DialogData for the list of options. // PopupDialog(DialogData) error // DataRenderer manages the graphic data renderer of the icon. // // You must add a renderer (Gauge, Graph, Progress) before you can Render // a list of floats values (from 0 lowest, to 1 highest). // DataRenderer() IconRenderer // Window gives access to actions on the controlled window. // Window() IconWindow // BindShortkey binds any number of keyboard shortcuts to your applet. // BindShortkey(shortkeys ...*Shortkey) error // IconProperties gets all applet icon properties at once. // IconProperties() (IconProperties, error) // IconProperty gets applet icon properties one by one. // IconProperty() IconProperty // AddSubIcon adds subicons by pack of 3 strings : label, icon, ID. // AddSubIcon(fields ...string) error // RemoveSubIcon only need the ID to remove the SubIcon. // The option to remove all icons is "any". // RemoveSubIcon(id string) error // RemoveSubIcons removes all subicons from the subdock. // RemoveSubIcons() error // SubIcon returns the subicon object you can act on for the given key. // SubIcon(key string) IconBase }
AppIcon defines all methods that can be used on a dock icon (with IconBase too).
type AppInstance ¶
type AppInstance interface { // Need to be defined in user applet. Init(def *Defaults, confLoaded bool) // Provided by extending AppBase }
AppInstance defines methods an applet must implement to use StartApplet.
type AppPoller ¶
type AppPoller interface { // Exists returns true if the poller exists (isn't nil). // Exists() bool // Add adds a poller to handle in the main loop. Only one can be active. // Multiple calls will just override the action called. // Add(call func()) AppPoller // SetPreCheck callback actions to launch before the polling job. // SetPreCheck(onStarted func()) // SetPostCheck callback actions to launch after the polling job. // SetPostCheck(onFinished func()) // SetInterval sets the polling interval time, in seconds. You can add a default // value as a second argument to be sure you will have a valid value (> 0). // SetInterval(delay ...int) int // Start enables the polling ticker. // Start() // Restart resets the counter and launch Action in a goroutine. // Safe to use on nil poller. // Restart() // Stop disables the polling ticker. // Stop() // Wait return a channel that will be triggered after the defined poller interval. // You will have to call it on every loop as it not a real ticker. // It's just a single use chan. // Wait() <-chan time.Time // Plop increase the counter and launch the action if it reached the interval. // The counter is also reset if the action is launched. // Safe to use on nil poller. // Plop() bool }
AppPoller defines an optional applet regular polling actions.
type CategoryType ¶
type CategoryType int
CategoryType defines the applet category (group like desktop or network).
const ( CategoryBehavior CategoryType = iota // Behavior and theme are not for applets CategoryTheme // except if its about internal dock use. CategoryFiles CategoryInternet CategoryDesktop CategoryAccessory CategorySystem CategoryFun CategoryNB // The number of defined categories. )
Source of package to load (applet or theme).
func (CategoryType) Color ¶
func (ct CategoryType) Color() string
Color returns the RBG color to display for the category.
func (CategoryType) String ¶
func (ct CategoryType) String() string
func (CategoryType) Translated ¶
func (ct CategoryType) Translated() string
Translated returns the translated name for the category.
type Command ¶
type Command struct { Name string // Command or location to open. UseOpen bool // If true, open with the cdglobal.CmdOpen command. Monitored bool // If true, the window will be monitored by the dock. (don't work wit UseOpen) Class string // Window class if needed. }
Command is the description of a standard command launcher.
func NewCommand ¶
NewCommand creates a standard command launcher.
type ConfGroupIconBoth ¶
ConfGroupIconBoth defines a common config struct for the Icon tab.
func (ConfGroupIconBoth) ToDefaults ¶
func (g ConfGroupIconBoth) ToDefaults(def *Defaults)
ToDefaults fills defaults fields from the Icon group: Name, Icon, Debug.
type ConfUpdater ¶
type ConfUpdater interface { // Save saves the edited config to disk, and releases the file locks. // Save() error // Cancel releases the file locks. // Cancel() // Set sets a new value for the group/key reference. // Set(group, key string, value interface{}) error // SetComment sets the comment for the key. // SetComment(group, key, comment string) error // GetComment gets the comment for the key. // GetComment(group, key string) (string, error) // Valuer returns the valuer for the given group/key combo. // Valuer(group, key string) valuer.Valuer // ParseGroups calls the given func for every group with its list of keys. // ParseGroups(func(group string, keys []ConfKeyer)) // MarshalGroup fills the config with data from the struct provided. // MarshalGroup(value interface{}, group string, fieldKey GetFieldKey) error // UnmarshalGroup parse a config group to fill the ptr to struct provided. // // The group param must match a group in the file with the format [MYGROUP] // UnmarshalGroup(v interface{}, group string, fieldKey GetFieldKey) []error // SetNewVersion replaces the version in a config file. // The given group must represent the first group of the file. // SetNewVersion(group, oldver, newver string) error }
ConfUpdater updates a config file.
You must ensure that Save or Cancel is called, and fast to prevent memory leaks and deadlocks.
type ContainerPosition ¶
type ContainerPosition int
ContainerPosition refers to the border of the screen the dock is attached to.
A desklet has always an orientation of BOTTOM.
const ( ContainerPositionBottom ContainerPosition = iota // Dock in the bottom. ContainerPositionTop // Dock in the top. ContainerPositionRight // Dock in the right. ContainerPositionLeft // Dock in the left. )
Dock position on screen.
type ContainerType ¶
type ContainerType int
ContainerType is the type of container that manages the icon.
const ( ContainerUnknown ContainerType = iota // just in case. ContainerDock // Applet in a dock. ContainerDesklet // Applet in a desklet. ContainerDialog ContainerFlying )
Icon container type.
type Defaults ¶
type Defaults struct { // Those are provided by ConfGroupIconBoth. Icon string // Icon path. Label string // Text label. Debug bool // Enable debug flood. // Gathered by LoadConfig. Shortkeys []*Shortkey // Others to fill. QuickInfo string PollerInterval int Commands Commands AppliClass string // Monitored application window class. }
Defaults settings that can be set in one call with something like:
app.SetDefaults(cdtype.Defaults{ Label: "This is my great applet", QuickInfo: "+1", })
type DeskletVisibility ¶
type DeskletVisibility int
DeskletVisibility defines the visibility of a desklet.
const ( DeskletVisibilityNormal DeskletVisibility = iota // Normal, like normal window DeskletVisibilityKeepAbove // always above DeskletVisibilityKeepBelow // always below DeskletVisibilityWidgetLayer // on the Compiz widget layer DeskletVisibilityReserveSpace // prevent other windows form overlapping it )
Desklet visibility settings.
type DialogData ¶
type DialogData struct { // Dialog box text. Message string // Icon displayed next to the message (default=applet icon). Icon string // Duration of the dialog, in second (0=unlimited). TimeLength int // True to force the dialog above. Use it with parcimony. ForceAbove bool // True to use Pango markup to add text decorations. UseMarkup bool // Images of the buttons, separated by comma ";". // "ok" and "cancel" are used as keywords defined by the dock. Buttons string // Callback when buttons are used. // // The type of data depends on the widget provided: // nil if no widget is provided. // string for a DialogWidgetText. // float64 for a DialogWidgetScale. // int for a DialogWidgetList with Editable=false. // string for a DialogWidgetList with Editable=true. // // Callback can be tested and asserted with one of the following functions. // The callback will be triggered only if the first button or the enter key // is pressed. // DialogCallbackValidNoArg callback without arguments. // DialogCallbackValidInt callback with an int. // DialogCallbackValidString callback with a string. // Callback func(button int, data interface{}) // Optional custom widget. // Can be of type DialogWidgetText, DialogWidgetScale, DialogWidgetList. Widget interface{} }
DialogData defines options for a dialog popup.
type DialogWidgetList ¶
type DialogWidgetList struct { // Editable represents whether the user can enter a custom choice or not. // false: InitialValue and returned value are int. // true: InitialValue and returned value are string. Editable bool // Values represents the combo list values. // Note that values separator will be a semicolon ";" on the DBus backend. Values []string // InitialValue defines the default value, presented to the user. // Type: int if Editable=false or string if Editable=true. InitialValue interface{} }
DialogWidgetList defines options for the string list widget of a dialog.
type DialogWidgetScale ¶
type DialogWidgetScale struct { MinValue float64 // Lower value. MaxValue float64 // Upper value. NbDigit int // Number of digits after the dot. InitialValue float64 // Value initially set to the scale. MinLabel string // Label displayed on the left of the scale. MaxLabel string // Label displayed on the right of the scale. }
DialogWidgetScale defines options for the scale widget of a dialog.
type DialogWidgetText ¶
type DialogWidgetText struct { MultiLines bool // true to have a multi-lines text-entry, ie a text-view. Locked bool // false if the user can modify the text. Hidden bool // false if the input text is visible (set to true for passwords). NbChars int // Maximum number of chars (the current number of chars will be displayed next to the entry) (0=infinite). InitialValue string // Text initially contained in the entry. }
DialogWidgetText defines options for the text widget of a dialog.
type Duration ¶
type Duration struct {
// contains filtered or unexported fields
}
Duration converts a time duration to seconds.
Really basic, so you have to recreate one every time. Used by the auto config parser with tags "unit", "default" and "min".
func NewDuration ¶
NewDuration creates an time duration helper.
func (*Duration) SetDefault ¶
SetDefault sets a default duration value.
type EmblemPosition ¶
type EmblemPosition int
EmblemPosition is the location where an emblem is displayed.
const ( EmblemTopLeft EmblemPosition = iota // Emblem in top left. EmblemBottomLeft // Emblem in bottom left. EmblemBottomRight // Emblem in bottom right. EmblemTopRight // Emblem in top right. EmblemMiddle // Emblem in the middle. EmblemBottom // Emblem in the bottom. EmblemTop // Emblem in the top. EmblemRight // Emblem in the right. EmblemLeft // Emblem in the left. EmblemCount // Number of emblem positions. )
Applet emblem position.
type Events ¶
type Events struct { // Action when the user clicks on the icon. OnClick func() // Action when the user clicks on the icon. // Same as OnClick with the key modifier state (ctrl, shift...). OnClickMod func(btnState int) // Action when the user use the middle-click on the icon. OnMiddleClick func() // Action when the user use the right-click on the icon, opening the menu with full options. OnBuildMenu func(Menuer) // Action when the user use the mouse wheel on the icon. OnScroll func(scrollUp bool) // Action when the user drop data on the icon. OnDropData func(data string) // Action when the focus of the managed window change. OnChangeFocus func(active bool) // Action on default reload, called before Init. // Can be used when you need to act on the previous config before its reset. PreInit func(loadConf bool) // Action when a reload applet event is triggered from the dock. // A default callback is provided that calls Init. (See cdapplet.SetEvents) Reload func(bool) // Action when the quit applet event is triggered from the dock. End func() // SubEvents actions work the same as main event with an additional argument // for the id of the clicked icon. // // Action when the user clicks on the subicon. OnSubClick func(icon string) // Action when the user clicks on the subicon. // Same as OnSubClick with the key modifier state (ctrl, shift...). OnSubClickMod func(icon string, btnState int) // Action when the user use the middle-click on the subicon. OnSubMiddleClick func(icon string) // Action when the user use the right-click on the subicon, opening the menu. OnSubBuildMenu func(icon string, menu Menuer) // Action when the user use the mouse wheel on the subicon. OnSubScroll func(icon string, scrollUp bool) // Action when the user drop data on the subicon. OnSubDropData func(icon string, data string) }
Events represents the list of events you can receive as a cairo-dock applet.
They must be set in the pointer received at applet creation.
All those events are optional but it's better to find something meaningful to assign to them to improve your applet utility.
Use with something like:
app.Events.OnClick = func app.myActionLeftClick app.Events.OnDropData = func (data string) {app.openWebpage(data, ...)}
type GetFieldKey ¶
type GetFieldKey func(reflect.StructField) string
GetFieldKey is method to match config key name and struct field.
type IconBase ¶
type IconBase interface { // SetQuickInfo change the quickinfo text displayed on the subicon. // SetQuickInfo(info string) error // SetLabel change the text label next to the subicon. // SetLabel(label string) error // SetIcon set the image of the icon, overwriting the previous one. // A lot of image formats are supported, including SVG. // You can refer to the image by either its name if it's an image from a icon theme, or by a path. // app.SetIcon("gimp") // app.SetIcon("go-up") // app.SetIcon("/path/to/image") // SetIcon(icon string) error // SetEmblem set an emblem image on the icon. // To remove it, you have to use SetEmblem again with an empty string. // // app.SetEmblem(app.FileLocation("img", "emblem-work.png"), cdtype.EmblemBottomLeft) // SetEmblem(iconPath string, position EmblemPosition) error // Animate animates the icon for a given number of rounds. // Animate(animation string, rounds int) error // ShowDialog pops up a simple dialog bubble on the icon. // The dialog can be closed by clicking on it. // ShowDialog(message string, duration int) error }
IconBase defines common actions for icons and subicons.
type IconProperties ¶
type IconProperties interface { // X gets the position of the icon's on the horizontal axis. // X() int // Y gets the position of the icon's on the vertical axis. // Y() int // Width gets the width of the icon, in pixels. // Width() int // Height gets the height of the icon, in pixels. // Height() int //ContainerPosition gets the position of the container on the screen. // ContainerPosition() ContainerPosition // ContainerType gets the type of the applet's container (DOCK, DESKLET). // ContainerType() ContainerType // Xid gets the ID of the application's window controlled by the applet, // Xid() uint64 // HasFocus gets whether the application's window has the focus or not. // HasFocus() bool }
IconProperties defines basic informations about a dock icon.
type IconProperty ¶
type IconProperty interface { // X gets the position of the icon's on the horizontal axis. // Starting from 0 on the left. // X() (int, error) // Y gets the position of the icon's on the vertical axis. // Starting from 0 at the top of the screen. // Y() (int, error) // Width gets the width of the icon, in pixels. // This is the maximum width, when the icon is zoomed. // Width() (int, error) // Height gets the height of the icon, in pixels. // This is the maximum height, when the icon is zoomed. // Height() (int, error) //ContainerPosition gets the position of the container on the screen. // (bottom, top, right, left). A desklet has always an orientation of bottom. // ContainerPosition() (ContainerPosition, error) // ContainerType gets the type of the applet's container (DOCK, DESKLET). // ContainerType() (ContainerType, error) // Xid gets the ID of the application's window controlled by the applet, // or 0 if none (this parameter can only be non nul if you used the method // ControlAppli beforehand). // Xid() (uint64, error) // HasFocus gets whether the application's window which is controlled by the // applet is the current active window (it has the focus) or not. // HasFocus() (bool, error) }
IconProperty defines properties of an applet icon.
type IconRenderer ¶
type IconRenderer interface { Gauge(nbval int, themeName string) error // sets a gauge data renderer. Progress(nbval int) error // sets a progress data renderer. Graph(nbval int, typ RendererGraphType) error // sets a graph data renderer. GraphLine(nbval int) error // sets a graph of type RendererGraphLine. GraphPlain(nbval int) error // sets a graph of type RendererGraphPlain. GraphBar(nbval int) error // sets a graph of type RendererGraphBar. GraphCircle(nbval int) error // sets a graph of type RendererGraphCircle. GraphPlainCircle(nbval int) error // sets a graph of type RendererGraphPlainCircle. Remove() error // removes the data renderer. // Render renders new values on the icon. // // * You must have set a data renderer before. // * The number of values sent must match the number declared before. // * Values are given between 0 and 1. // Render(values ...float64) error }
IconRenderer defines interactions with the graphic data renderer of the icon.
type IconWindow ¶
type IconWindow interface { // SetAppliClass allow your applet to control the window of an external // application and to steal its icon from the Taskbar. // // *Use the xprop command find the class of the window you want to control. // *Use "none" if you want to reset application control. // *Controlling an application enables the OnChangeFocus callback. // SetAppliClass(applicationClass string) error // Sets the monitored class name. IsOpened() bool // Returns true if the monitored application is opened. Minimize() error // Hide the window. Show() error // Show the window and give it focus. SetVisibility(show bool) error // Set the visible state of the window. ToggleVisibility() error // Send Show or Minimize. Maximize() error // Sets the window in full size. Restore() error // Removes the maximized size of the window. ToggleSize() error // Send Maximize or Restore. Close() error // Close the window (some programs will just hide in the systray). Kill() error // Kill the X window. }
IconWindow defines interactions with the controlled window.
type InfoPosition ¶
type InfoPosition int
InfoPosition is the location to render text data for an applet.
const ( InfoNone InfoPosition = iota // don't display anything. InfoOnIcon // display info on the icon (as quick-info). InfoOnLabel // display on the label of the icon. )
Applet text info position.
type ListApps ¶
type ListApps map[string]NewAppletFunc
ListApps defines a list of applet creation func, indexed by applet name.
func (ListApps) GetNewFunc ¶
func (l ListApps) GetNewFunc(name string) NewAppletFunc
GetNewFunc gets the applet creation func for the name.
func (ListApps) Register ¶
func (l ListApps) Register(name string, callnew NewAppletFunc)
Register registers an applet name with its new func.
func (ListApps) Unregister ¶
Unregister unregisters an applet name.
type LogFmt ¶
type LogFmt interface { FormatMsg(level LogLevel, sender, msg string, more ...interface{}) string FormatErr(e error, level LogLevel, sender string, msg ...interface{}) string SetTimeFormat(format string) SetColorName(func(string) string) SetColorInfo(func(string) string) SetColorDebug(func(string) string) SetColorDEV(func(string) string) SetColorWarn(func(string) string) SetColorError(func(string) string) }
LogFmt defines the log formater display options.
type LogOut ¶
type LogOut interface { LogFmt // extends the log formater. Raw(sender, msg string) Msg(level LogLevel, sender, msg string, more ...interface{}) Err(e error, level LogLevel, sender, msg string) List() []LogMsg }
LogOut defines the interface for log forwarding.
type Logger ¶
type Logger interface { LogFmt // extends the log formater. // SetDebug change the debug state of the logger. // Only enable or disable messages send with the Debug command. // SetDebug(debug bool) Logger // GetDebug gets the debug state of the logger. // GetDebug() bool // SetName set the displayed and forwarded name for the logger. // SetName(name string) Logger // SetLogOut connects the optional forwarder to the logger. // SetLogOut(LogOut) Logger // LogOut returns the optional forwarder of the logger. // LogOut() LogOut // Debug is to be used every time a useful step is reached in your module // activity. It will display the flood to the user only when the debug flag is // enabled. // Debug(msg string, more ...interface{}) // Debugf log a new debug message with arguments formatting. // Debugf(msg, format string, args ...interface{}) // Info displays normal informations on the standard output, with the first param in green. // Info(msg string, more ...interface{}) // Infof log a new info message with arguments formatting. // Infof(msg, format string, args ...interface{}) // Warn test and log the error as warning type. Return true if an error was found. // Warn(e error, msg ...interface{}) (fail bool) // NewWarn log a new warning. // NewWarn(msg string, args ...interface{}) // Warnf log a new warning with arguments formatting. // Warnf(msg, format string, args ...interface{}) // Err test and log the error as Error type. Return true if an error was found. // Err(e error, msg ...interface{}) (fail bool) // NewErr log a new error. // NewErr(e string, msg ...interface{}) // Errorf log a new error with arguments formatting. // Errorf(msg, format string, args ...interface{}) // ExecShow run a command with output forwarded to console and wait. // ExecShow(command string, args ...string) error // ExecSync run a command with and grab the output to return it when finished. // ExecSync(command string, args ...string) (string, error) // ExecAsync run a command with output forwarded to console but don't wait for its completion. // Errors will be logged. // ExecAsync(command string, args ...string) error // ExecCmd provides a generic command with output forwarded to console. // ExecCmd(command string, args ...string) *exec.Cmd // ExecShlex parse the command with shlex before returning an ExecCmd. // ExecShlex(command string, args ...string) (*exec.Cmd, error) // PlaySound plays a sound file. // PlaySound(file string) error // Recover from crash. Use with defer before a dangerous action. // Recover() // GoTry launch a secured go routine. Panic will be recovered and logged. // GoTry(call func()) // DEV is like Info, but to be used by the dev for his temporary tests (easier to grep). // DEV(msg string, more ...interface{}) }
Logger defines the interface for reporting information.
type MenuItemType ¶
type MenuItemType int
MenuItemType is the type of menu entry to create.
const ( MenuEntry MenuItemType = iota // Simple menu text entry. MenuSubMenu // Not working for Dbus. MenuSeparator // Menu separator. MenuCheckBox // Menu checkbox. MenuRadioButton // Not working. )
Applet menu entry type.
type MenuWidgeter ¶
type MenuWidgeter interface {
SetTooltipText(string)
}
MenuWidgeter provides a common interface to apply settings on menu entries.
type Menuer ¶
type Menuer interface { // AddSubMenu adds a submenu to the menu. // AddSubMenu(label, iconPath string) Menuer // AddSeparator adds a separator to the menu. // AddSeparator() // AddEntry adds an item to the menu with its callback. // AddEntry(label, iconPath string, call interface{}, userData ...interface{}) MenuWidgeter // AddCheckEntry adds a check entry to the menu. // AddCheckEntry(label string, active bool, call interface{}, userData ...interface{}) MenuWidgeter // AddRadioEntry adds a radio entry to the menu. // AddRadioEntry(label string, active bool, group int, call interface{}, userData ...interface{}) MenuWidgeter }
Menuer provides a common interface to build applets menu.
type NewAppletFunc ¶
type NewAppletFunc func(base AppBase, events *Events) AppInstance
NewAppletFunc defines an applet creation function.
type PackageType ¶
type PackageType int
PackageType defines the type of a package (maybe rename to state?).
const ( PackTypeLocal PackageType = iota // package installed as root on the machine (in a sub-folder /usr). PackTypeUser // package located in the user's home PackTypeDistant // package present on the server PackTypeNew // package newly present on the server (for less than 1 month) PackTypeUpdated // package present locally but with a more recent version on the server, or distant package that has been updated in the past month. PackTypeInDev // package present locally but not on server. It's a user special applet we must not alter. PackTypeGoInternal // package included in the dock binary. PackTypeAny // joker (the search path function will search locally first, and on the server then). )
Types of packages (location).
func PackType ¶
func PackType(name string) (string, PackageType)
PackType finds the package name and type from the config key value.
func (PackageType) String ¶
func (pt PackageType) String() string
String returns a human readable package type.
func (PackageType) Translated ¶
func (pt PackageType) Translated() string
Translated returns the translated package type.
type RenderSimple ¶
type RenderSimple interface { DataRenderer() IconRenderer FileLocation(...string) string SetIcon(string) error SetLabel(string) error SetQuickInfo(string) error }
RenderSimple defines a subset of AppBase for simple renderers like data pollers.
type RendererGraphType ¶
type RendererGraphType int
RendererGraphType defines the type of display for a renderer graph.
const ( RendererGraphLine RendererGraphType = iota RendererGraphPlain RendererGraphBar RendererGraphCircle RendererGraphPlainCircle )
Types of display for renderer graph.
type Shortkey ¶
type Shortkey struct { ConfGroup string ConfKey string Shortkey string // value Desc string // tag "desc" ActionID int // tag "action". Will be converted to Call at SetDefaults. Call func() // Simple callback when triggered. CallE func() error // Error returned callback. If set, used first. }
Shortkey defines mandatory informations to register a shortkey. Can be used in applet config struct with a "desc" tag.
type Template ¶
Template defines a template formatter. Can be used in applet config struct with a "default" tag.
func NewTemplate ¶
NewTemplate creates a template with the given file path.
type ThemeExtra ¶
type ThemeExtra struct {
// contains filtered or unexported fields
}
ThemeExtra defines a custom applet theme.
func NewThemeExtra ¶
func NewThemeExtra(log Logger, themeName, def, confDir, appDir, dirThemeSyst, hintLocal, hintDist string) (*ThemeExtra, error)
NewThemeExtra creates a theme extra with the given file path.
func (*ThemeExtra) Path ¶
func (te *ThemeExtra) Path() string
Path returns the full path to the theme dir.
type ToDefaultser ¶
type ToDefaultser interface {
ToDefaults(*Defaults)
}
ToDefaultser represents a config group that can directly apply its defaults settings.