import "launchpad.net/go-unityscopes/v2"
Package scopes is used to write Unity scopes in Go.
Scopes are implemented through types that conform to the Scope interface.
type MyScope struct {}
The scope has access to a ScopeBase instance, which can be used to access various pieces of information about the scope, such as its settings:
func (s *MyScope) SetScopeBase(base *scopes.ScopeBase) {
}
If the scope needs access to this information, it should save the provided instance for later use. Otherwise, it the method body can be left blank.
The shell may ask the scope for search results, which will cause the Search method to be invoked:
func (s *MyScope) Search(query *scopes.CannedQuery, metadata *scopes.SearchMetadata, reply *scopes.SearchReply, cancelled <-chan bool) error {
category := reply.RegisterCategory("cat_id", "category", "", "")
result := scopes.NewCategorisedResult(category)
result.SetTitle("Result for " + query.QueryString())
reply.Push(result)
return nil
}
In general, scopes will:
* Register result categories via reply.RegisterCategory()
* Create new results via NewCategorisedResult(), and push them with reply.Push(result)
* Check for cancellation requests via the provided channel.
The Search method will be invoked with an empty query when surfacing results are wanted.
The shell may ask the scope to provide a preview of a result, which causes the Preview method to be invoked:
func (s *MyScope) Preview(result *scopes.Result, metadata *scopes.ActionMetadata, reply *scopes.PreviewReply, cancelled <-chan bool) error {
widget := scopes.NewPreviewWidget("foo", "text")
widget.AddAttributeValue("text", "Hello")
reply.PushWidgets(widget)
return nil
}
The scope should push one or more slices of PreviewWidgets using reply.PushWidgets. PreviewWidgets can be created with NewPreviewWidget.
Additional data for the preview can be pushed with reply.PushAttr.
If any of the preview widgets perform actions that the scope should respond to, the scope should implement the PerformAction method:
func (s *MyScope) PerformAction(result *Result, metadata *ActionMetadata, widgetId, actionId string) (*ActivationResponse, error) {
// handle the action and then tell the dash what to do next
// through an ActivationResponse.
resp := NewActivationResponse(ActivationHideDash) return resp, nil
}
The PerformAction method is not part of the main Scope interface, so the feature need only be implemented for scopes that use the feature.
Finally, the scope can be exported in the main function:
func main() {
if err := scopes.Run(&MyScope{}); err != nil {
log.Fatalln(err)
}
}
The scope executable can be deployed to a scope directory named like:
/usr/lib/${arch}/unity-scopes/${scope_name}
In addition to the scope executable, a scope configuration file named ${scope_name}.ini should be placed in the directory. Its contents should look something like:
[ScopeConfig]
DisplayName = Short name for the scope
Description = Long description of scope
Author =
ScopeRunner = ${scope_executable} --runtime %R --scope %S
accounts.go activationresponse.go childscope.go column_layout.go department.go doc.go filters_base.go helpers.go metadata.go option_selector_filter.go previewwidget.go query.go radio_buttons_filter.go range_input_filter.go rating_filter.go reply.go result.go switch_filter.go testing.go unityscope.go value_slider_filter.go
const (
PostLoginDoNothing
PostLoginInvalidateResults
PostLoginContinueActivation
)func RegisterAccountLoginResult(result *CategorisedResult, query *CannedQuery, serviceName, serviceType, providerName string, passedAction, failedAction PostLoginAction) error
RegisterAccountLoginResult configures a result such that the dash will attempt to log in to the account identified by (serviceName, serviceType, providerName).
On success, the dash will perform the action specified by passedAction. On failure, it will use failedAction.
func RegisterAccountLoginWidget(widget *PreviewWidget, serviceName, serviceType, providerName string, passedAction, failedAction PostLoginAction)
RegisterAccountLoginWidget configures a widget such that the dash will attempt to log in to the account identified by (serviceName, serviceType, providerName).
On success, the dash will perform the action specified by passedAction. On failure, it will use failedAction.
Run will initialise the scope runtime and make a scope availble. It is intended to be called from the program's main function, and will run until the program exits.
type ActionMetadata struct {
// contains filtered or unexported fields
}ActionMetadata holds additional metadata about the preview request or result activation.
func NewActionMetadata(locale, form_factor string) *ActionMetadata
NewActionMetadata creates a new ActionMetadata with the given locale and form_factor
FormFactor returns the form factor for the search request.
func (metadata *ActionMetadata) Hint(key string, value interface{}) error
Hint returns a hint. Returns error if the hint does not exist or if we got an error unmarshaling
func (metadata *ActionMetadata) Hints(value interface{}) error
Hints gets all hints.
func (metadata *ActionMetadata) InternetConnectivity() ConnectivityStatus
InternetConnectivity gets internet connectivity status.
Locale returns the expected locale for the search request.
func (metadata *ActionMetadata) ScopeData(v interface{}) error
ScopeData decodes the stored scope data into the given variable.
Scope data is either set by the shell when calling a preview action, or set by the scope through an ActivationResponse object.
func (metadata *ActionMetadata) SetHint(key string, value interface{}) error
SetHint sets a hint.
func (metadata *ActionMetadata) SetInternetConnectivity(status ConnectivityStatus)
SetInternetConnectivity indicates the internet connectivity status.
func (metadata *ActionMetadata) SetScopeData(v interface{}) error
SetScopeData attaches arbitrary data to this ActionMetadata.
type ActivationResponse struct {
Status ActivationStatus
Query *CannedQuery
Result *Result
Widgets []PreviewWidget
ScopeData interface{}
}ActivationResponse is used as the result of a Activate() or PerformAction() call on the scope to instruct the dash on what to do next.
func NewActivationResponse(status ActivationStatus) *ActivationResponse
NewActivationResponse creates an ActivationResponse with the given status
This function should not be used to create an ActivationPerformQuery response: use NewActivationResponseForQuery instead.
func NewActivationResponseForQuery(query *CannedQuery) *ActivationResponse
NewActivationResponseForQuery creates an ActivationResponse that performs the given query.
func NewActivationResponseUpdatePreview(widgets ...PreviewWidget) *ActivationResponse
func NewActivationResponseUpdateResult(result *Result) *ActivationResponse
func (r *ActivationResponse) SetScopeData(v interface{})
SetScopeData stores data that will be passed through to the preview for ActivationShowPreview type responses.
const (
ActivationNotHandled ActivationStatus = iota
ActivationShowDash
ActivationHideDash
ActivationShowPreview
ActivationPerformQuery
ActivationUpdateResult
ActivationUpdatePreview
)type Activator interface {
Scope
Activate(result *Result, metadata *ActionMetadata) (*ActivationResponse, error)
}Activator is an interface that should be implemented by scopes that need to handle result activation directly.
type AggregatedScope interface {
Scope
FindChildScopes() []*ChildScope
}type CannedQuery struct {
// contains filtered or unexported fields
}CannedQuery represents a search query from the user.
func NewCannedQuery(scopeID, queryString, departmentID string) *CannedQuery
NewCannedQuery creates a new CannedQuery with the given scope ID, query string and department ID.
func (query *CannedQuery) DepartmentID() string
DepartmentID returns the department ID for this canned query.
func (query *CannedQuery) FilterState() FilterState
FilterState returns the state of the filters for this canned query.
func (query *CannedQuery) QueryString() string
QueryString returns the query string for this canned query.
func (query *CannedQuery) ScopeID() string
ScopeID returns the scope ID for this canned query.
func (query *CannedQuery) SetDepartmentID(departmentID string)
SetDepartmentID changes the department ID for this canned query.
func (query *CannedQuery) SetQueryString(queryString string)
SetQueryString changes the query string for this canned query.
func (query *CannedQuery) ToURI() string
ToURI formats the canned query as a URI.
CategorisedResult represents a result linked to a particular category.
CategorisedResult embeds Result, so all of its attribute manipulation methods can be used on variables of this type.
func NewCategorisedResult(category *Category) *CategorisedResult
NewCategorisedResult creates a new empty result linked to the given category.
type Category struct {
// contains filtered or unexported fields
}Category represents a search result category.
type ChildScope struct {
// contains filtered or unexported fields
}func NewChildScope(id string, metadata *ScopeMetadata, enabled bool, keywords []string) *ChildScope
NewChildScope creates a new ChildScope with the given id, metadata, enabled state and keywords
func (childscope *ChildScope) Id() string
Id returns the identifier of the child scope
type ColumnLayout struct {
// contains filtered or unexported fields
}ColumnLayout is used represent different representations of a widget. Depending on the device your applications runs you can have several predefined column layouts in order to represent your view in the way it fits better the aspect ratio.
func NewColumnLayout(num_columns int) *ColumnLayout
NewColumnLayout Creates a layout definition that expects num_of_columns columns to be added with ColumnLayout.AddColumn.
func (layout *ColumnLayout) AddColumn(widgetIds ...string) error
AddColumn adds a new column and assigns widgets to it. ColumnLayout expects exactly the number of columns passed to the constructor to be created with the AddColumn method.
func (layout *ColumnLayout) Column(column int) ([]string, error)
Column retrieves the list of widgets for given column.
func (layout *ColumnLayout) NumberOfColumns() int
NumberOfColumns gets the number of columns expected by this layout as specified in the constructor.
func (layout *ColumnLayout) Size() int
Size gets the current number of columns in this layout.
const (
ConnectivityStatusUnknown ConnectivityStatus = 0
ConnectivityStatusConnected ConnectivityStatus = 1
ConnectivityStatusDisconnected ConnectivityStatus = 2
)type Department struct {
// contains filtered or unexported fields
}Department represents a section of the a scope's results. A department can have sub-departments.
func NewDepartment(departmentID string, query *CannedQuery, label string) (*Department, error)
NewDepartment creates a new department using the given canned query.
func (dept *Department) AddSubdepartment(child *Department)
AddSubdepartment adds a new child department to this department.
func (dept *Department) AlternateLabel() string
AlternateLabel gets the alternate label for this department.
This should express the plural form of the normal label. For example, if the normal label is "Books", then the alternate label should be "All Books".
func (dept *Department) HasSubdepartments() bool
HasSubdepartments checks if this department has subdepartments or has_subdepartments flag is set
func (dept *Department) Id() string
Id gets the identifier of this department.
func (dept *Department) Label() string
Label gets the label of this department.
func (dept *Department) Query() *CannedQuery
Query gets the canned query associated with this department.
func (dept *Department) SetAlternateLabel(label string)
SetAlternateLabel sets the alternate label for this department.
This should express the plural form of the normal label. For example, if the normal label is "Books", then the alternate label should be "All Books".
The alternate label only needs to be provided for the current department.
func (dept *Department) SetHasSubdepartments(subdepartments bool)
SetHasSubdepartments sets whether this department has subdepartments.
It is not necessary to call this if AddSubdepartment has been called. It intended for cases where subdepartments have not been specified but the shell should still act as if it has them.
func (dept *Department) SetSubdepartments(subdepartments []*Department)
SetSubdepartments sets sub-departments of this department.
func (dept *Department) Subdepartments() []*Department
Subdepartments gets list of sub-departments of this department.
type Filter interface {
// contains filtered or unexported methods
}Filter is implemented by all scope filter types.
const (
FilterDisplayDefault FilterDisplayHints = 0
FilterDisplayPrimary FilterDisplayHints = 1 << iota
)type FilterOption struct {
Id string `json:"id"`
Label string `json:"label"`
Default bool `json:"default"`
}FilterState represents the current state of a set of filters.
type Location struct {
Latitude float64 `json:"latitude"`
Longitude float64 `json:"longitude"`
Altitude float64 `json:"altitude"`
AreaCode string `json:"area_code"`
City string `json:"city"`
CountryCode string `json:"country_code"`
CountryName string `json:"country_name"`
HorizontalAccuracy float64 `json:"horizontal_accuracy"`
VerticalAccuracy float64 `json:"vertical_accuracy"`
RegionCode string `json:"region_code"`
RegionName string `json:"region_name"`
ZipPostalCode string `json:"zip_postal_code"`
}type OptionSelectorFilter struct {
Label string
MultiSelect bool
// contains filtered or unexported fields
}OptionSelectorFilter is used to implement single-select or multi-select filters.
func NewOptionSelectorFilter(id, label string, multiSelect bool) *OptionSelectorFilter
NewOptionSelectorFilter creates a new option filter.
func (f *OptionSelectorFilter) ActiveOptions(state FilterState) []string
ActiveOptions returns the filter's active options from the filter state.
AddOption adds a new option to the filter.
func (f *OptionSelectorFilter) HasActiveOption(state FilterState) bool
HasActiveOption returns true if any of the filters options are active.
func (f *OptionSelectorFilter) UpdateState(state FilterState, optionId string, active bool)
UpdateState updates the value of a particular option in the filter state.
type PerformActioner interface {
Scope
PerformAction(result *Result, metadata *ActionMetadata, widgetId, actionId string) (*ActivationResponse, error)
}PerformActioner is an interface that should be implemented by scopes that need to handle preview actions directly.
type PreviewReply struct {
// contains filtered or unexported fields
}PreviewReply is used to send result previews to the client.
func (reply *PreviewReply) Error(err error)
Error is called to indicate that the preview generation could not be completed successfully.
This is called automatically if a scope's Preview method completes with an error.
func (reply *PreviewReply) Finished()
Finished is called to indicate that no further widgets or attributes will be pushed to this reply.
This is called automatically if a scope's Preview method completes without error.
func (reply *PreviewReply) PushAttr(attr string, value interface{}) error
PushAttr pushes a preview attribute to the client.
This will augment the set of attributes in the result available to be mapped by preview widgets. This allows a widget to be sent to the client early, and then fill it in later when the information is available.
func (reply *PreviewReply) PushWidgets(widgets ...PreviewWidget) error
PushWidgets sends one or more preview widgets to the client.
func (reply *PreviewReply) RegisterLayout(layout ...*ColumnLayout) error
RegisterLayout registers a list of column layouts for the current preview.
Layouts must be registered before pushing a unity::scopes::PreviewWidgetList, and must be registered only once. Returns an error if RegisterLayout() is called more than once.
func NewPreviewWidget(id, widgetType string) PreviewWidget
NewPreviewWidget creates a preview widget with the given name and type.
Widget type specific attributes can be set directly with AddAttributeValue(), or mapped to result attributes with AddAttributeMapping().
A list of available widget types and their associated attributes is available here:
http://developer.ubuntu.com/api/scopes/sdk-14.10/previewwidgets/
func (widget PreviewWidget) AddAttributeMapping(key, fieldName string)
AddAttributeMapping maps a widget attribute to a named result attribute.
func (widget PreviewWidget) AddAttributeValue(key string, value interface{})
AddAttributeValue sets a widget attribute to a particular value.
func (widget PreviewWidget) AddWidget(child PreviewWidget)
AddWidget adds a child widget to this widget. This only makes sense for expandable type widgets.
func (widget PreviewWidget) Id() string
Id returns the name of this widget.
func (widget PreviewWidget) WidgetType() string
WidgetType returns the type of this widget.
type ProxyScopeMetadata struct {
Identity string `json:"identity"`
EndPoint string `json:"endpoint"`
}RadioButtonsFilter is a filter that displays mutually exclusive list of options
func NewRadioButtonsFilter(id, label string) *RadioButtonsFilter
NewRadioButtonsFilter creates a new radio button filter.
func (f *RadioButtonsFilter) ActiveOptions(state FilterState) []string
ActiveOptions returns the filter's active options from the filter state.
AddOption adds a new option to the filter.
func (f *RadioButtonsFilter) HasActiveOption(state FilterState) bool
HasActiveOption returns true if any of the filters options are active.
func (f *RadioButtonsFilter) UpdateState(state FilterState, optionId string, active bool)
UpdateState updates the value of a particular option in the filter state.
type RangeInputFilter struct {
DefaultStartValue interface{}
DefaultEndValue interface{}
StartPrefixLabel string
StartPostfixLabel string
EndPrefixLabel string
EndPostfixLabel string
CentralLabel string
// contains filtered or unexported fields
}RangeInputFilter is a range filter which allows a start and end value to be entered by user, and any of them is optional.
func NewRangeInputFilter(id string, defaultStartValue, defaultEndValue interface{}, startPrefixLabel, startPostfixLabel, endPrefixLabel, endPostfixLabel, centralLabel string) *RangeInputFilter
NewRangeInputFilter creates a new range input filter.
func (f *RangeInputFilter) EndValue(state FilterState) (float64, bool)
EndValue gets the end value of this filter from filter state object. If the value is not set for the filter it returns false as the second return statement, it returns true otherwise
func (f *RangeInputFilter) StartValue(state FilterState) (float64, bool)
StartValue gets the start value of this filter from filter state object. If the value is not set for the filter it returns false as the second return statement, it returns true otherwise
func (f *RangeInputFilter) UpdateState(state FilterState, start, end interface{}) error
UpdateState updates the value of the filter
type RatingFilter struct {
Label string
OnIcon string
OffIcon string
// contains filtered or unexported fields
}RatingFilter is a filter that allows for rating-based selection
func NewRatingFilter(id, label string) *RatingFilter
NewRatingFilter creates a new rating filter.
func (f *RatingFilter) ActiveOptions(state FilterState) []string
ActiveOptions returns the filter's active options from the filter state.
func (f *RatingFilter) ActiveRating(state FilterState) (string, bool)
ActiveRating gets active option from an instance of FilterState for this filter.
AddOption adds a new option to the filter.
func (f *RatingFilter) HasActiveOption(state FilterState) bool
HasActiveOption returns true if any of the filters options are active.
func (f *RatingFilter) UpdateState(state FilterState, optionId string, active bool)
UpdateState updates the value of a particular option in the filter state.
type Result struct {
// contains filtered or unexported fields
}Result represents a result from the scope
Art returns the "art" attribute of the result if set, or an empty string.
DndURI returns the "dnd_uri" attribute of the result if set, or an empty string.
Get returns the named result attribute.
The value is decoded into the variable pointed to by the second argument. If the types do not match, an error will be returned.
If the attribute does not exist, an error is returned.
Set sets the named result attribute.
An error may be returned if the value can not be stored, or if there is any other problems updating the result.
SetArt sets the "art" attribute of the result.
SetDndURI sets the "dnd_uri" attribute of the result.
SetInterceptActivation marks this result as needing custom activation handling.
By default, results are activated by the client directly (e.g. by running the application associated with the result URI). For results with this flag set though, the scope will be asked to perform activation and should implement the Activate method.
SetTitle sets the "title" attribute of the result.
SetURI sets the "uri" attribute of the result.
Title returns the "title" attribute of the result if set, or an empty string.
URI returns the "uri" attribute of the result if set, or an empty string.
type Scope interface {
SetScopeBase(base *ScopeBase)
Search(query *CannedQuery, metadata *SearchMetadata, reply *SearchReply, cancelled <-chan bool) error
Preview(result *Result, metadata *ActionMetadata, reply *PreviewReply, cancelled <-chan bool) error
}Scope defines the interface that scope implementations must implement
type ScopeBase struct {
// contains filtered or unexported fields
}ScopeBase exposes information about the scope including settings and various directories available for use.
CacheDirectory returns a directory the scope can use to store cache files
func (b *ScopeBase) ChildScopes() []*ChildScope
ChildScopes list all the child scopes
func (b *ScopeBase) ListRegistryScopes() map[string]*ScopeMetadata
ListRegistryScopes lists all the scopes existing in the registry
ScopeDirectory returns the directory where the scope has been installed
Settings returns the scope's settings. The settings will be decoded into the given value according to the same rules used by json.Unmarshal().
TmpDirectory returns a directory the scope can use to store temporary files
type ScopeMetadata struct {
Art string `json:"art"`
Author string `json:"author"`
Description string `json:"description"`
DisplayName string `json:"display_name"`
Icon string `json:"icon"`
Invisible bool `json:"invisible"`
IsAggregator bool `json:"is_aggregator"`
LocationDataNeeded bool `json:"location_data_needed"`
ScopeDir string `json:"scope_dir"`
ScopeId string `json:"scope_id"`
Version int `json:"version"`
Proxy ProxyScopeMetadata `json:"proxy"`
AppearanceAttributes map[string]interface{} `json:"appearance_attributes"`
SettingsDefinitions []interface{} `json:"settings_definitions"`
Keywords []string `json:"keywords"`
// contains filtered or unexported fields
}ScopeMetadata holds scope attributes such as name, description, icon etc.
The information stored by ScopeMetadata comes from the .ini file for the given scope (for local scopes) or is fetched from the remote server (for scopes running on Smart Scopes Server). Use ListRegistryScopes from ScopeBase to get the metadata for all scopes.
type SearchMetadata struct {
// contains filtered or unexported fields
}SearchMetadata holds additional metadata about the search request.
func NewSearchMetadata(cardinality int, locale, form_factor string) *SearchMetadata
NewSearchMetadata creates a new SearchMetadata with the given locale and form_factor
func (metadata *SearchMetadata) AggregatedKeywords() []string
func (metadata *SearchMetadata) Cardinality() int
Cardinality returns the desired number of results for the search request.
FormFactor returns the form factor for the search request.
func (metadata *SearchMetadata) InternetConnectivity() ConnectivityStatus
InternetConnectivity gets internet connectivity status.
func (metadata *SearchMetadata) IsAggregated() bool
Locale returns the expected locale for the search request.
func (metadata *SearchMetadata) Location() *Location
func (metadata *SearchMetadata) SetAggregatedKeywords(keywords []string) error
func (metadata *SearchMetadata) SetInternetConnectivity(status ConnectivityStatus)
SetInternetConnectivity indicates the internet connectivity status.
func (metadata *SearchMetadata) SetLocation(l *Location) error
SetLocation sets the location
type SearchReply struct {
// contains filtered or unexported fields
}SearchReply is used to send results of search queries to the client.
func (reply *SearchReply) Error(err error)
Error is called to indicate that search query could not be completed successfully.
This is called automatically if a scope's Search method completes with an error.
func (reply *SearchReply) Finished()
Finished is called to indicate that no further results will be pushed to this reply.
This is called automatically if a scope's Search method completes without error.
func (reply *SearchReply) Push(result *CategorisedResult) error
Push sends a search result to the client.
func (reply *SearchReply) PushFilters(filters []Filter, state FilterState) error
PushFilters sends the set of filters and their state to the client.
func (reply *SearchReply) RegisterCategory(id, title, icon, template string) *Category
RegisterCategory registers a new results category with the client.
The template parameter should either be empty (to use the default rendering template), or contain a JSON template as described here:
http://developer.ubuntu.com/api/scopes/sdk-14.10/unity.scopes.CategoryRenderer/#details
Categories can be passed to NewCategorisedResult in order to construct search results.
func (reply *SearchReply) RegisterDepartments(parent *Department)
RegisterDepartments registers the department set to display with the search results.
The parent department of the current search should be provided here, with the current department identified among its children by a matching department ID.
SwitchFilter is a simple on/off switch filter.
func NewSwitchFilter(id, label string) *SwitchFilter
NewSwitchFilter creates a new switch filter.
func (f *SwitchFilter) IsOn(state FilterState) bool
func (f *SwitchFilter) UpdateState(state FilterState, value bool)
UpdateState updates the value of the filter to on/off
type ValueSliderFilter struct {
DefaultValue float64
Min float64
Max float64
Labels ValueSliderLabels
// contains filtered or unexported fields
}ValueSliderFilter is a value slider filter that allows for selecting a value within a given range.
func NewValueSliderFilter(id string, min, max, defaultValue float64, labels ValueSliderLabels) *ValueSliderFilter
NewValueSliderFilter creates a new value slider filter.
func (f *ValueSliderFilter) UpdateState(state FilterState, value float64) error
UpdateState updates the value of the filter to the given value
func (f *ValueSliderFilter) Value(state FilterState) float64
Value gets value of this filter from filter state object. If the value is not set for the filter it returns false as the second return statement, it returns true otherwise
type ValueSliderLabels struct {
MinLabel string
MaxLabel string
ExtraLabels []ValueSliderExtraLabel
}Package scopes imports 12 packages (graph). Updated 2016-11-03. Refresh now. Tools for package owners.