Development/Tutorials/Plasma4/JavaScript/API
Introduction to the Plasmoid JavaScript API
This document provides an overview/reference of the Simplified JavaScript API for Plasmoids. The "Simplified" refers to the fact that it isn't a full binding to all of Qt or KDE's libraries, but a highly focused set of bindings designed to make writing Plasmoids fast and easy, while remaining powerful.
The API in this documentation covers the JavaScript API as it appears in the KDE Software Compilation as of version 4.4, unless otherwise noted. This API ships as part of the KDE Base Runtime package, so can be relied on being there by any application that is Powered By KDE.
If you have not done so already, please read the "plasmoid" design document first.
What Is A Simplified JavaScript Plasmoid?
This document describes the native Plasma API available to Simplified JavaScript Plasmoids. What makes them "Simplified" is that they do not have access to the entire C++ API in the Plasma, KDE and Qt libraries (let alone things lower in the API stack). This helps ensure that these Plasmoids are more likely to work properly between releases as changes in underlying API don't affect them as well as allowing Plasma to offer stronger security guarantees around them.
To denote that this Plasmoid is a Simplified JavaScript widget, ensure that in the metadata.desktop file there is this line:
X-Plasma-API=javascript
What follows is a description of the runtime environment available to a Simplified JavaScript Plasmoid.
QtScript
The Simplified JavaScript API is powered by Qt's QtScript system which provides access to a full featured ECMA Script interpreter. If it works in ECMA Script, it will work in a Simplified JavaScript Plasmoid. As an interesting implementation note, QtScript uses the high performance ECMA Script interpreter from WebKit and shares this code with QtWebKit.
On top of the ECMA Script language, QtScript provides Qt integration features. Probably the most useful one in this context is the use of signals and slots which is Qt's callback mechanism. Signals may be emitted in QtScript by calling the signal method in question, a signal can be connected to a slot by using the connect() method (and disconnected with disconnect()) and any function defined in the Plasmoid may be used as a slot. For example:
function onClick()
{
print("We got clicked!")
}
function onFirstClick()
{
print("First click!")
button.clicked.disconnect(onFirstClick)
}
button = new PushButton
button.clicked.connect(onClick)
button.clicked.connect(onFirstClick)
button.clicked()
This will print out:
We got clicked!
First click!
on the console when the Plasmoid starts, and the "We got clicked!" again whenever the button is clicked by the user.
The object that emitted the signal that caused a slot to be called can be retrieved using the QObject sender read-only property of the global plasmoid object.
Events (API v2)
Starting in API v2, it is possible register functions as event handlers. To register an event handler, use:
- addEventListener(String event, Function listener)
The event parameter is the name of the event (see list at end of section for known events) and the handler parameter is the function that will be called whenever the event occurs. Event names are not case sensitive. An event object will be passed into the handler, and the type and behavior of that object is event specific.
Any number of event handlers may be added to a given event, and one handler may be registered to any number of events. The order of execution of event handlers is not guaranteed.
To remove an event handler, use:
- removeEventListener(String event, Function listener)
The function passed in will no longer be called as a result of the event occurring. Any currently pending calls to the listener are still made, however.
If an event handler is registered using addEventListener, then any callback in the global plasmoid object that may be related to the same event will be suppressed. For instance, if an event handler is registered using addEventListener for the paintInterface event, then plasmoid.paintInterface will not be called.
Input Events (API v2)
Following are the input events which are recognized on the Plasmoid along with the type of event object passed in to registered event listeners:
- HoverEnter: HoverEvent Object
- HoverLeave: HoverEvent Object
- HoverMove: HoverEvent Object
- KeyPress: KeyEvent Object
- KeyRelease: KeyEvent Object
- MouseDoubleClick: MouseEvent Object
- MouseMove: MouseEvent Object
- MousePress: MouseEvent Object
- MouseRelease: MouseEvent Object
- Wheel: WheelEvent Object
Example:
// anonymous function as a listener on KeyPress
plasmoid.addEventListener('KeyPress', function(a) { print(a.key) })
function output()
{
print('Hover Event!')
}
function hovered(event)
{
plasmoid.busy = true
plasmoid.removeEventListener('HoverEnter', output)
}
function unhovered(event)
{
plasmoid.busy = false
}
plasmoid.addEventListener('HoverEnter', hovered)
plasmoid.addEventListener('HoverLeave', unhovered)
plasmoid.addEventListener('HoverEnter', output)
plasmoid.addEventListener('HoverLeave', output)
HoverEvent (API v2)
KeyEvent (API v2)
MouseEvent (API v2)
WheelEvent (API v2)
Addon Events (API v3)
The following two events are used in conjuction with Addons. See the Addons section for more information on Addons.
- addonCreated: Object addOn
- newAddonsAvailable
The Global plasmoid Object
There is a global object available to the Plasmoid called, appropriately, "plasmoid". It has a number of useful properties (some of which are read only, but many of which are read/write), functions, constant values and callbacks. Each are enumerated below.
Callbacks
See the section on Events above.
There are some events that are generated by Plasma for the Plasmoid. These can often be caught by providing a function assigned to a specific name in the plasmoid object. For instance, to get notified of form factor changes, one would provide a formFactorChanged method as follows:
plasmoid.formFactorChanged = function() {
print("the form factor has changed to: " + plasmoid.formFactor())
}
The following callbacks are used to notify the Plasmoid of changes in its running environment:
- configChanged()
- currentActivityChanged()
- formFactorChanged()
- immutabilityChanged()
- locationChanged()
- sizeChanged()
Other callbacks include:
- dataUpdated(String source, Map[String, Any] data): used to pass in DataEngine updates
- activate(): called when the widget is activated by the user, e.g. by a keyboard shortcut. Useful for setting the focus on a specific input widget, for instance. (API v2)
- initExtenderItem(Extender extender): Called when an Extender should be set up. (API v2)
- popupEvent(boolean shown): called on PopupApplets when the popup is shown or hidden. (API v2)
In API v2, all of these callbacks can also be used as events. So, for instance, instead of implementing plasmoid.popupEvent, one could also write:
plasmoid.addEventListener('popupEvent', function(shown) { print('shown? ' + shown) } )
This would also suppress any calls to plasmoid.popupEvent.
Further documentation on these callbacks can be found in the relevant sections below.
Environment
A set of read-only properties (and in most cases notification functions) that tell the Plasmoid about its current environment:
- apiVersion: the integer version of the Simplified JavaScript API in the current execution environment; can be used to change behaviour or usage of functions depending on the version number.
- formFactor: one of Planar (e.g. on a desktop or in an application main view), Horizontal, Vertical or MediaCenter. When the form factor changes, the plasmoid.formFactorChanged function, if defined in the Plasmoid, is called.
- size: the size of the Plasmoid, expressed in QSizeF (explained below). when it changes, plasmoid.sizeChanged() will be called.
- location: one of Floating (no specific location), Desktop (on the application's main view are), FullScreen, LeftEdge, RightEdge, TopEdge or ButtomEdge. When the location changes, the plasmoid.locationChanged function, if defined in the Plasmoid, is called.
- immutable: this property is set to true when the Plasmoid is set to not be movable or otherwise changeable, and false otherwise. Configuration is still usually allowed in this state. When the immutability changes, the plasmoid.immutabilityChanged function, if defined in the Plasmoid, is called.
- currentActivity: the current contextual activity name. When the current activity changes, the plasmoid.currentActivityChanged function, if defined in the Plasmoid, is called.
- shouldConserveResources: true if the plasmoid should not be doing anything that would create too much draw on power, e.g. when on a device with low battery power it may be a good idea not to run a computationally expensive but optional animation
- userConfiguring: true if the user configuration interface is currently being displayed.
Properties
A set of read/write properties that allow the Plasmoid to set various visual or functional properties:
- AspectRatioMode aspectRatioMode: defines how to treat the aspect ratio of a Plasmoid when resizing it. See the AspectRatioMode documentation for values and their meaning.
- BackgroundHints backgroundHints: defines how the background of the widget is rendered. See the BackgroundHints documentation for values and their meaning.
- boolean busy: set to true when the Plasmoid is currently processing or waiting for data and the user interface should be blocked while doing so; will generally show a full-Plasmoid animated overlay to denote business
Geometry
Read Only Properties:
- QRectF rect: the current rect of the Plasmoid; note that the top left may be not be the origin point (0,0)
Functions:
- resize(width, height)
- setMinimumSize(width, height)
- setPreferredSize(width, height)
- setBackgroundHints(background) - use NoBackground as value if you want to remove the default plasmoid background box.
Painting and Layout
To paint directly on to the canvas, a widget may implement the paintInterface function in the plasmoid object:
plasmoid.paintInterface = function(painter) { /* painting code goes here*/ }
See the Painting section below for information about helpful classes and functions that can be used when implementing a paintInterface function.
Read/Write Properties:
- Layout layout: the QGraphicsLayout associated with the Plasmoid for laying out top level items; this property is read-write, though the property is not usually set as one can simply do "new LinearLayout" (or one of the other layout classes provided) and it will be automatically associated with the Plasmoid.
Functions:
- update(): triggers a full repaint of the Plasmoid.
- update(QRectF rect) triggers a repaint of the rect area of the Plasmoid.
- failedToLaunch(bool failed[, string reason]) sets the launch status of the Plasmoid; if set to true, the script will stop executing and the reason message, if any, will be displayed to the user.
Access To Packaged Files
Functions:
- string file(string type[, string fileName]): returns the path to a file in the Plasmoid package of the given type, optionally with a file name to match, e.g.
var path = plasmoid.file("mainscript")
orvar pm = new QPixmap(plasmoid.file("images", "mypixmap.png"))
- bool include(string filename): attempts to include the script defined from the package's code directory
Configuration Data
Configuration values can be defined using KConfig XT XML files in the contents/config/ directory of the Plasmoid's package. The default file that is looked for and used is contents/config/main.xml.
Accessing Configuration Data
Read-write properties:
- String activeConfig: The current active configuration description. For instance, setting it to "foo" would cause the Plasmoid to try and reference the contents/config/foo.xml KConfigXT file. Setting this to an empty string will switch to the main.xml file.
Functions:
- any readConfig(String key): reads the value from the configuration data for the given key as defined by the currently active configuration.
- writeConfig(String key, any value) : writes a value to the configuration store under the given key
User Customization
User customization can be offered by providing a Qt Designer file called contents/ui/config.ui in the Plasmoid's package.
Callbacks:
- configChanged(): callback function called when the configuration is changed external to the Plasmoid, e.g. when the user changes settings in a configuration dialog.
It's possible to add some items to the popup menu of the Plasmoid.
Functions:
- setAction(name, text, icon, shortcut): adds an item to the context menu with the given text and icon; you need to define plasmoid.action_<name> function, where <name> is the first argument for setAction call, and this function will be called each time user clicks the item
- removeAction(name): removes the item
Global Enumerations
In the global namespace are a set of useful enumerations that can be used with various classes in the Simplified Javascript Plasmoid API. These include:
AspectRatioMode
- IgnoreAspectRatio: The Plasmoid can be freely resized
- KeepAspectRatio: The Plasmoid keeps a fixed aspect ratio
- Square: The Plasmoid is always a square
- ConstrainedSquare: The Plasmoid is no wider (in horizontal formfactors) or no higher (in vertical ones) than a square
- FixedSize: The Plasmoid cannot be resized
FormFactor
- Planar: The Plasmoid lives in a plane and has two degrees of freedom to grow. Optimize for desktop, laptop or tablet usage: a high resolution screen 1-3 feet distant from the viewer.
- MediaCenter: As with Plasmoid the applet lives in a but the interface should be optimized for medium-to-high resolution screens that 5-15 feet distant from the viewer. Sometimes referred to as a "ten foot interface".
- Horizontal: The Plasmoid is constrained vertically, but can expand horizontally.
- Vertical: The Plasmoid is constrained horizontally, but can expand vertically.
Location
- Floating: Free floating. Neither geometry or z-ordering is described precisely by this value.
- Desktop: On the planar desktop layer, extending across the full screen from edge to edge
- FullScreen
- TopEdge
- BottomEdge
- LeftEdge
- RightEdge
AnimationDirection
- AnimationForward
- AnimationBackward
BackgroundHints
- NoBackground
- StandardBackground
- TranslucentBackground
- DefaultBackground
QtAlignment
- QtAlignLeft
- QtAlignRight
- QtAlignHCenter
- QtAlignJustify
- QtAlignTop
- QtAlignBottom
- QtAlignVCenter
If you need to align something in the center (both horizontally and vertically) you can sum the constans.
QtAnchorPoint
- QtAnchorLeft
- QtAnchorRight
- QtAnchorBottom
- QtAnchorTop
- QtAnchorHorizontalCenter
- QtAnchorVerticalCenter
QtCorner
- QtTopLeftCorner
- QtTopRightCorner
- QtBottomLeftCorner
- QtBottomRightCorner
QtMouseButton
- QtNoButton
- QtLeftButton
- QtRightButton
- QtMidButton
- QtXButton1
- QtXButton2
QtOrientation
- QtHorizontal
- QtVertical
QtScrollBarPolicy
- QtScrollBarAsNeeded
- QtScrollBarAlwaysOff
- QtScrollBarAlwaysOn
QtSizePolicy
- QSizePolicyFixed
- QSizePolicyMinimum
- QSizePolicyMaximum
- QSizePolicyPreferred
- QSizePolicyExpanding
- QSizePolicyMinimumExpanding
- QSizePolicyIgnored
Theme Colors (API v3)
- TextColor
- HighlightColor
- BackgroundColor
- ButtonTextColor
- ButtonBackgroundColor
- LinkColor
- VisitedLinkColor
Status
- UnknownStatus The status is unknown
- PassiveStatus The Item is passive
- ActiveStatus The Item is active
- NeedsAttentionStatus The Item needs attention
- AcceptingInputStatus The Item is accepting input
User Interface Elements
Plasma Widgets
The Plasma framework provides a set of standard user interface elements such as pushbuttons and checkboxes for use in Plasmoids, and these are available from the Simplified Javascript API as well. These elements follow the Plasma style and other conventions so that widgets blend well both visually and functionally with other Plasma elements.
Note that some UI elements have functions that are synonymous with a read-write property. In those cases, the function can serve as a slot and be connected to signals for easy setting of the property.
DataEngine-Aware UI Elements
Some of the UI elements are able to accept data directly from DataEngines. These widgets will have a dataUpdated function and can be passed into the DataEngine::connectSource method successfully.
DataEngine-aware UI elements include:
- Label
- TextEdit
- Meter
Common Properties
By default, all of the Plasma user interface elements have the following properties:
- String objectName
- number opacity
- boolean enabled
- boolean visible
- QPointF pos
- number x
- number y
- number z
- number rotation
- number scale
- QPointF transformOriginPoint
- QPalette palette
- QFont font
- QSizeF size
- QtFocusPolicy focusPolicy
- QRectF geometry
Common Signals
- opacityChanged()
- visibleChanged()
- enabledChanged()
- xChanged()
- yChanged()
- zChanged()
- rotationChanged()
- scaleChanged()
UI Element Gallery
CSS Styleable UI Elements
Most UI Elements are able to have their appearance adjust using a CSS stylesheet. All of these elements have the following read/write property:
- String styleSheet: A CSS stylesheet describing visual properties to apply to the widget; see the Qt Documentation for more information
CheckBox
Read-write properties:
- String text
- String image
- boolean checked
- toggled(bool)
ComboBox
Read-only properties:
- number count: (API v 3) the number of items in the combobox
Read-write properties:
- String text: the text of the currently selected item in the combobox
- number currentIndex: (API v 3) the index of the current item
Funtions:
- clear()
Signals:
- activated(String)
- textChanged(String)
- currentIndexChanged(number)
Frame
Read-write properties:
- Shadow frameShadow
- String text
- String image
Enumerations:
- Shadow
- Plain
- Raised
- Sunken
GroupBox
Read-write properties:
- String text
Label
Read-write properties:
- String text
- String image
- number alignment (see #QtAlignment for the valid values)
- boolean hasScaledContents
- boolean textIsSelectable (since 4.4.1)
- boolean wordWrap (API v2)
Functions:
- dataUpdated(String, Data)
Signals:
- linkActivated(String): emitted when a link is clicked; includes the URL of link that is clicked; this is only available when textIsSelectable
- linkHovered(String): emitted when a link is hovered
LineEdit
Read-write properties:
- String text
- boolean clearButtonShown
Signals:
- editingFinished()
- returnPressed()
- textEdited(String)
- textChanged(String)
PushButton
Read-write properties:
- String text
- String image
- QAction action
- QIcon icon
- boolean checkable
- boolean checked
- boolean down
Signals:
- pressed()
- released()
- clicked()
- toggled(bool)
RadioButton
Read-write properties:
- String text
- String image
- boolean checked
Signals:
- toggled(bool)
ScrollWidget
Read-write properties:
- QGraphicsWidget widget
- number horizontalScrollBarPolicy
- number verticalScrollBarPolicy
- QPointF scrollPosition
- QSizeF contentsSize
- QRectF viewportGeometry
Functions:
- ensureRectVisible(QRectF)
- ensureItemVisible(QGraphicsItem)
- registerAsDragHandle(QGraphicsWidget)
- unregisterAsDragHandle(QGraphicsWidget)
ScrollBar
Read-write properties:
- number singleStep
- number pageStep
- number value
- number minimum
- number maximum
- QtOrientation setOrientation
Functions:
- setValue(number)
- setOrientation(QtOrientation)
Signals:
- valueChanged(number)
Slider
Read-write properties:
- number maximum
- number minimum
- number value
- number orientation
Signals:
- sliderMoved(number)
- valueChanged(number)
Functions:
- setMaximum(number)
- setMinimum(number)
- setRange(number, number)
- setValue(number)
- setOrientation(QtOrientation)
SpinBox
Read-write properties:
- number maximum
- number minimum
- number value
Functins:
- setMaximum(number)
- setMinimum(number)
- setRange(number, number)
- setValue(number)
Signals:
- sliderMoved(number)
- valueChanged(number)
- editingFinished()
TabBar
Read-write properties:
- number currentIndex
- number count
- boolean tabBarShown
Functions:
- setCurrentIndex(number)
- insertTab(number, QIcon,String,QGraphicsLayoutItem)
- insertTab(number, QIcon,String)
- insertTab(number, String,QGraphicsLayoutItem)
- insertTab(number, String)
- addTab(QIcon,String,QGraphicsLayoutItem)
- addTab(QIcon,String)
- addTab(String,QGraphicsLayoutItem)
- addTab(String)
- removeTab(number)
- takeTab(number)
- tabAt(number)
- setTabText(number, String)
- tabText(number)
- setTabIcon(number, QIcon)
- tabIcon(number)
Signals:
- currentChanged(number)
TextEdit
Read-write properties:
- String text
- boolean readOnly
Functions:
- dataUpdated(String, Data)
Signals:
- textChanged()
ToolButton
- Read-write properties:
- ''QAction action: the action associated with this ToolButton
- 'boolean autoRaise: whether or not the ToolButton should raise automatically when the user interacts with it
- ''String image: path to an icon or image (e.g. in the widget's Package) to show on the ToolButton
- ''String text: the text shown on the ToolButton
API v2 adds:
- ''boolean down: whether or not the ToolButton is in the down position (since protocol version 2)
- Signals:
- clicked()
- pressed()
- released()
TreeView
Read-write properties:
- QAbstractModel model
VideoWidget
Read-writeproperties:
- String url
- number currentTime
- number totalTime
- number remainingTime
- Controls usedControls
- boolean controlsVisible
Functions:
- play()
- pause()
- stop()
- seek(number)
Signals:
- tick(number)
- aboutToFinish()
- nextRequested()
- previousRequested()
Enumerations:
- Controls
- NoControls
- Play
- Pause
- Stop
- PlayPause
- Previous
- Next
- Progress
- Volume
- OpenFile
- DefaultControls
Other UI Elements
BusyWidget
Read-write properties:
- boolean running
- String label
Signals:
- clicked()
FlashingLabel
Read-write properties:
- boolean autohide
- QColor color
- number duration
Functins:
- kill()
- fadeIn()
- fadeOut()
- flash(String, number, QTextOption)
- flash(String ,number)
- flash(String)
- flash(QPixmap, number, QtAlignment)
- flash(QPixmap, number)
- flash(QPixmap)
GraphicsWidget (API v3)
This is just a plain element with no painting or other features. It is useful primarily as a place holder, especially to contain layouts for other elements.
IconWidget
Read-only properties:
- QSizeF iconSize - the actual size of the icon given the size of the IconWidget, space reserved (if any) for text displayed, etc.
Read-write properties:
- String text
- String infoText
- QIcon icon
- QColor textBackgroundColor
- String svg
- QAction action
- QtOrientation orientation
- number numDisplayLines
Functions:
- setPressed(boolean)
- setUnpressed()
- setIcon(String)
Signals:
- pressed(bool)
- clicked()
- doubleClicked()
- activated()
- changed()
ItemBackground
Read-write properties:
- QRectF target
- QGraphicsItem targetItem
Signals:
- appearanceChanged()
- animationStep(qreal)
- targetReached(QRectF)
- targetItemReached(QGraphicsItem)
Meter
Read-write properties:
- number minimum
- number maximum
- number value
- String svg
- MeterType meterType
Functions:
- dataUpdated(String, Data)
Enumerations:
- MeterType
- BarMeterHorizontal
- BarMeterVertical
- AnalogMeter
Separator
Read-write properties:
- QtOrientation orientation
SignalPlotter
Read-write properties:
- String title
- String unit
- boolean useAutoRange
- number horizontalScale
- boolean showVerticalLines
- QColor verticalLinesColor
- number verticalLinesDistance
- boolean verticalLinesScroll
- boolean showHorizontalLines
- QColor horizontalLinesColor
- QColor fontColor
- number horizontalLinesCount
- boolean showLabels
- boolean showTopBar
- QColor backgroundColor
- String svgBackground
- boolean thinFrame
- boolean stackPlots
SvgWidget
Read-write properties:
- Svg svg
- String elementID
Signals:
- clicked(QtMouseButton)
WebView
Read-only properties:
- QSizeF contentsSize
- QRectF viewportGeometry
Read-write properties:
- Url url
- String html
- boolean dragToScroll
- QPointF scrollPosition
Signals:
- loadProgress(number)
- loadFinished(bool)
Layouts
LinearLayout
- number spacing
- QtOrientation orientation (QtVertical or QtHorizontal)
- function removeAt
- function addStretch
- function setStretchFactor
- function setAlignment
- function insertStretch
- function setItemSpacing
- function setContentsMargins
- function addItem
- function removeItem
- function insertItem
- function toString
- function activate (API v3)
AnchorLayout
- number horizontalSpacing
- number verticalSpacing
- function setSpacing
- function removeAt
- function addAnchor
- function anchor
- function addAnchors
- function addCornerAnchors
- function toString
- function activate (API v3)
GridLayout
- number horizontalSpacing
- number verticalSpacing
- function rowSpacing
- function setRowSpacing
- function columnSpacing
- function setColumnSpacing
- function rowMinimumHeight
- function setRowMinimumHeight
- function rowPreferredHeight
- function setRowPreferredHeight
- function rowMaximumHeight
- function setRowMaximumHeight
- function rowFixedHeight
- function setRowFixedHeight
- function columnMinimumWidth
- function setColumnMinimumWidth
- function columnPreferredWidth
- function setColumnPreferredWidth
- function columnMaximumWidth
- function setColumnMaximumWidth
- function columnFixedWidth
- function setColumnFixedWidth
- function remoteAt
- function setAlignment
- function setSpacing
- function setContentsMargins
- function addItem
- function toString
- function activate (API v3)
Undocumented Properties and Functions
There are a handful of other undocumented properties and functions available to UI elements. These are not supported or guaranteed to exist in future versions however, and as such should not be used or relied upon.
Animations
Creating Animation Objects
An Animation object can be retrieved by calling the Animation animation(string type) function. The string corresponds to the type of animation, which are listed below.
New Animation objects are associated with (and therefore will animate) the Plasmoid by default. By setting the widgetToAnimate property, however, it can be assigned to animate any QGraphicsWidget desired (e.g. Plasma widgets such as push buttons, sliders, etc) .
Enumerations
All Animation objects have the following enumerations:
MovementDirection
- MoveUp
- MoveUpRight
- MoveRight
- MoveDownRight
- MoveDown
- MoveDownLeft
- MoveLeft
- MoveUpLeft
Reference
The reference point, relative to the target widget, for the animation.
- Center
- Up
- Down
- Left
- Right
State
- Paused
- Running
- Stopped
Common API
With the exception of Pause and Property animations, all animations support the following read/write properties:
- AnimationDirection direction: the direction the animation should play: AnimationForward or AnimationBackward
- int duration: length of the animation in ms.
- EasingCurveType easingCurveType: The easing curve to use in the animation
- QGraphicsWidget targetWidget: the QGraphicsWidget (e.g. a Plasma::Widget) that this animation should operate on
Animation Groups
Animations may be put into groups for convenient sequential or parallel running. Sequential groups, where the animations run one after the other, are handled by the AnimationGroup class. Parallel aniations, where the animations run simultaneously, are handled the ParallelAnimationGroup class.
Animations are added to a group by calling add(Animation) on the group object. Groups may also be added to other groups.
Custom Animations
Custom animation types can be defined using Javascript files that are included as part of the Plasmoid's package in the contents/animations/ directory. To learn how to create such animations and access them from your Plasmoid, visit the Javascript Animations tutorial.
Standard Animation Types
Below is a list of all current standard animation types and their particular read/write properties:
Fade
- number startOpacity: the opacity, between 0 and 1, that the target widget starts at when the animation begins
- number targetOpacity: the opacity, between 0 and 1, that the target widget will be at the end of the animation
Geometry
- QRectF startGeometry: the geometry that the target widget should start with
- QRectF targetGeometry: the geometry the target widget will have at the end of the animation
Grow
- number factor: the factor by which the target widget will grow to by the end of the animation
Pause
- number duration: the number of milliseconds to pause for
Property
Animates an object (must be a QObject internally, which includes all Plasma Widgets) by manipulating one of its properties. Property animations have the following read/write properties:
- any startValue
- any endValue
- ByteArray propertyName
- QObject targetObject
- number duration
- EasingCurve easingCurve
Pulser
- number targetScale: the maximum scale of the pulse-shadow item, relative to the target widget
Rotate
- QtAxis axis: the axis along which to rotate the item
- Reference reference: the reference point around which to rotate the target widget
- number angle: the number of degrees to rotate the item
RotateStacked
- MovementDirection movementDirection: the direction to rotate the widgets in the stack around
- QGraphicsLayoutItem layout
- Reference reference: the reference point around which to rotate the target widget
- QGraphicsWidget backingWidget: the widget in the "back" to rotate to the front of the target widget
Slide
- MovementDirection movementDirection: the direction to slide the widget
- number distance: the distance to slide the widget
Zoom
- number zoom: the factor by which to zoom the target widget
QEasingCurve
Used to set the progress shape of Animation objects, this class has the following read-only properties:
- string toString
- number valueForProgress(number progress): returns effective progress for the easing curve at progress. While progress must be between 0 and 1, the returned effective progress can be outside those bounds.
as well as the following read/write property:
- EasingCurveType type: the shape of this easing curve
and the following enumeration:
- EasingCurveType
- Linear
- InQuad
- OutQuad
- InOutQuad
- OutInQuad
- InCubic
- OutCubic
- InOutCubic
- OutInCubic
- InQuart
- OutQuart
- InOutQuart
- OutInQuart
- InQuint
- OutQuint
- InOutQuint
- OutInQuint
- InSize
- OutSine
- InOutSine
- OutInSine
- InExpo
- OutExpo
- InOutExpo
- OutInExpo
- InCirc
- OutCirc
- InOutCirc
- InOutCirc
- OutInCirc
- InElastic
- OutElastic
- InOutElastic
- OutInElastic
- InBack
- OutBack
- InOutBack
- OutInBack
- InBounc
- OutBounce
- InOutBounce
- OutInBounce
- InCurve
- OutCurve
- SineCurve
- CosineCurve
Painting
See the "Painting and Layout" section, part of the Global Plasmoid object chapter, for information on using these classes within a widget.
Pixmaps
The QPixmap object allows widgets to use pixmaps for painting. Widgets may include pixmaps in various common formats (PNG, JPEG, GIF, etc.) in the contents/images/ directory of the Plasmoid package and load them by passing the name of the file into the pixmap constructor:
var pixmap = new QPixmap("myimage.png")
In addition to being used as a file load, some objects return or take pixmaps and the QPixmap object facilitates that as well.
Read-only properties:
- boolean null: true if the pixmap is empty
- QRectF rect: the rect of the pixmap
Functions:
- QPixmap scaled(number width, number height);;: returns a scaled version of the pixmap with width and height dimensions.
Icons
(Since 4.4.1)
The QIcon object provides simple access to icons. They can be constructed using a String or a QPixmap, with the String version either loading a file from disk if given an absolute path (useful for loading icons from the Plasmoid's package) or from the desktop icon theme if given just a name (e.g. "file-open").
Read-only properties:
- boolean null: true if the icon is empty
Functions:
- addPixmap(QPixmap): adds another pixmap to this icon
- addFile(String): adds another file to this icon
SVG Images
Plasma makes heavy usage of SVG images. More information on this industry standard scalable vector format can be found here:
Free and Open Source Software tools for creating SVGs include Inkscape and Karbon13. Widgets may include their own SVG files in the contents/images/ directory or may use SVG images that are part of the standard Plasma Desktop Theme as documented here:
Two classes are provide: Svg and FrameSvg. Svg allows loading and painting entire SVG documents or individual elements in an SVG document. FrameSvg extends Svg with methods to paint bordered frames from specially crafted SVG documents (see the Plasma Desktop Theme documentation for more information on this).
Svg
Constructors:
- Svg(string fileName)': fileName can be a file in the desktop theme or the plasmoid package
Read-only properties:
- QSizeF size: the current size of the svg
Read-write properties:
- boolean multipleImages: whether or not the svg contains multiple separate images
- string imagePath: the file path, including name of the svg
- boolean 'usingRenderingCache: whether or not to cache rendered pixmaps; improves performance (at the cost of some disk and memory usage) for SVG data that is repeatedly rendered
Functions:
- QSizeF elementSize(String svgElemen)
- QRectF elementRect(String svgElemen)
- boolean hasElement(String svgElement)
- elementAtPoint(QPoint pos)
- boolean isValid()
- QPixmap pixmap(String svgElement): a pixmap of the element in the svg rendered to the current size
- QPixmap pixmap(): a pixmap of the entire svg rendered to the current size
- paint(QPainter painter, QPointF point)
- paint(QPainter painter, QPointF point, String svgElement)
- paint(QPainter painter, number x, number y)
- paint(QPainter painter, number x, number y, String svgElement)
- paint(QPainter painter, QRectF destination)
- paint(QPainter painter, QRectF destination, String svgElement)
- paint(QPainter painter, number y, number width, number height)
- paint(QPainter painter, number x, number y, number width, number height, QString svgElement)
- resize(number width, number height)
- resize(QSizeF size)
- resize(): resizes the SVG to the document size defined in the SVG itself
Signals:
- repaintNeeded(): emitted when the SVG is in need of a repaint, such as when the theme changes and the SVG has reloaded its data
FrameSvg
Constructors:
- FrameSvg(String fileName): fileName can be a file in the desktop theme or the plasmoid package
Read-only properties:
- boolean multipleImages: whether or not the svg contains multiple separate images
Functions:
- setEnabledBorders(EnabledBorders borders): sets which borders are enabled when painting
- EnabledBorders enabledBorders(): the borders which are enabled when painting
- resizeFrame(QSizeF size): resizes the frame to size
- QSizeF frameSize(): the size of the current frame
- number marginSize(MarginEdge margin): the size of the margin for a given edge
- getMargins(number left, number top, number right, number bottom): stores the margin values in the variables passed in
- QRectF contentsRect(): the rect containing the contents, e.g. the size of the SVG minus the space required by the enabled borders
- setElementPrefix(Location): sets the frame element for the given location if it exists
- setElementPrefix(String prefix): sets the element prefix
- boolean hasElementPrefix(String prefix): returns true if the SVG contains a frame with the given prefix
- boolean hasElementPrefix(Location location): true if the SVG contains a frame element for the given location
- prefix()
- mask()
- setCacheAllRenderedFrames(bool)
- cacheAllRenderedFrames()
- QPixmap framePixmap(): a pixmap containing the current frame at the current size
- paintFrame(QPainter painter)
- paintFrame(QPainter painter, QPointF target)
- paintFrame(QPainter painter, QRectF target)
- paintFrame(QPainter painter, QRectF target, QRectF source)
Enumerations
- EnabledBorder
- NoBorder
- TopBorder
- BottomBorder
- LeftBorder
- RightBorder
- AllBorders
Painting on the Canvas
QColor
- Constructors:
- QColor
- QColor(string colorName)
- QColor(number red, number green, number blue, number alpha)
Functions:
- setThemeColor(ThemeColor color): sets the color to the appropriate ThemeColor
Read/write properties:
- number red
- number green
- number blue
- number alpha
- boolean valid
QFont
- Constructors:
- QFont
- QFont(string fontName)
- QFont(string fontName, number pointSize)
- QFont(string fontName, number pointSize, number weight)
- QFont(string fontName, number pointSize, number weight, boolean italic)
- string key
- string lastResortFamily
- string lastResortFont
- string defaultFamily
- boolean exactMatch
- string toString
- boolean bold
- string family
- boolean fixedPitch
- undefined fromString
- boolean italic
- boolean kerning
- boolean overline
- number pixelSize
- number pointSize
- number pointSizeF
- boolean strikeOut
- number stretch
- boolean underline
- number weight
- function isCopyOf
- function resolve
QPainter
- Constructors
- QPainter
- QPainter(object paintDevice): used to start a painter on a specific QWidget; rarely if ever needed in a JavaScript Plasmoid
- object background
- number backgroundMode
- object brush
- undefined setBrush
- object brushOrigin
- undefined clipping
- object clipPath
- object clipRegion
- number compositionMode
- object font
- number layoutDirection
- number opacity
- object pen
- number renderHints
- undefined transform
- object viewport
- boolean viewTransformEnabled
- object window
- object worldMatrix
- object worldTransform
- boolean worldMatrixEnabled
- object combinedMatrix
- object combinedTransform
- boolean active
- function begin
- function end
- function boundingRect
- function drawChord
- function drawConvexPolygon
- function drawArc
- function drawEllipse
- function drawImage
- function drawLine
- function drawLines
- function drawPath
- function drawPicture
- function drawPie
- function drawPixmap
- function drawPoint
- function drawPoints
- function drawPolygon
- function drawPolyline
- function drawRect
- function drawRects
- function drawRoundRect
- function drawText
- function drawTiledPixmap
- function eraseRect
- function fillPath
- function fillRect
- function resetMatrix
- function resetTransform
- function restore
- function rotate
- function save
- function scale
- function setClipRect
- function setRenderHint
- function shear
- function strokePath
- function testRenderHint
- function toString
- function translate
QPen
- Constructors:
- QPen
- object brush
- object color
- number capStyle
- number joinStyle
- number style
- number dashOffset
- number miterLimit
- number width
- boolean solid
- number red
- number green
- number blue
- number alpha
- boolean valid
QRectF
Read-only properties:
- boolean empty: true if the rectangle's width or height is less than, or equal to, 0; an empty rectangle is also invalid
- boolean null: true if the rectangle has both the width and the height set to 0; a null rectangle is also empty and not valid
- boolean valid: true if the rectangle has a width > 0 and height 0.
Read-write properties:
- number left
- number top
- number bottom
- number right
- number height
- number width
- number x
- number y
Constructors:
- QRectF
- QRectF(number x, number y, number width, number height): Sets the coordinates of the rectangle's top-left corner to (x, y), and its size to the given width and height.
Functions:
- adjust(number dx1, number dy1, number dx2, number dy2): adds dx1, dy1, dx2 and dy2 respectively to the existing coordinates of the rectangle
- QRectF adjusted(number dx1, number dy1, number dx2, number dy2): returns a new QRectF with dx1, dy1, dx2 and dy2 added respectively to the existing coordinates of the rectangle
- translate(number dx, number dy): translates the rect by dx, dy
- setCoords(number x1, number y1, number x2, number y2): sets the coordinates of the rectangle's top-left corner to (x1, y1), and the coordinates of its bottom-right corner to (x2, y2).
- setRect(number x, number y, number width, number height): sets the coordinates of the rectangle's top-left corner to (x, y), and its size to the given width and height.
- boolean contains(number x, number y): returns true if the rect contains the point (x, y)
- 'moveBottom(number delta): moves the bottom by delta pixels
- moveLeft(number delta): moves the left by delta pixels
- moveRight(number delta): moves the right by delta pixels
- moveTo(number x, number y): moves the top left of the rect to point (x, y)
- moveTop(number delta): moves the top by delta pixels
QSizeF
- Constructors:
- QSizeF
- QSizeF(number width, number height)
- number height
- number width
QPoint
Constructors:
- QPoint
- QPoint(number x, number y)
Read-only properties:
- bool null
- number manhattanLength
Read-write propertie:
- number x
- number y
Accessing Sources of Data
See the JavaScript Plasmoid DataEngine tutorials
Global Functions to Access DataEngines and Services
- dataEngine(string name): returns a DataEngine object
- service(string dataEngineName, string sourceName): returns a ServiceObject, see also DataEngine::serviceForSource
DataEngine
Read-only properties:
- Array[String] sources
- boolean valid
- String icon
- String name
Signals:
- sourceAdded(String sourceName)
- sourceRemoved(String sourceName)
Functions:
- serviceForSource(String sourceName)
- connectSource(String sourceName, Object connectTo[, number interval[, IntervalAlignment alignment] ]): if the object passed in as the object to connect to is the plasmoid object, then the plasmoid.dataUpdated(String source, Map[String, Any] data) callback will be called if it exists
- connectAllSources(Object connectTo[, number interval[, IntervalAlignment alignment] ]): if the object passed in as the object to connect to is the plasmoid object, then the plasmoid.dataUpdated(String source, Map[String, Any] data) callback will be called if it exists
- disconnectSource(String sourceName, Object connectedTo): if the object passed in as the object to connect to is the plasmoid object, then the plasmoid.dataUpdated(String source, Map[String, Any] data) callback will be called if it exists
- Data query(String sourceName)
The following functions are only of interest to DataEngine reimplementations (e.g. JavaScript DataEngines):
- scheduleSourcesUpdated()
- removeSource(String)
- updateAllSources()
- forceImmediateUpdateOfAllVisualizations()
- DataContainer containerForSource(String)
Service
- function finished(Plasma::ServiceJob*)
- function operationsChanged()
- function serviceReady(Plasma::Service*)
- function setDestination(QString)
- function destination()
- function operationNames()
- function operationDescription(QString)
- function startOperationCall(KConfigGroup,QObject*)
- function startOperationCall(KConfigGroup)
- function isOperationEnabled(QString)
- function name()
- function associateWidget(QWidget*,QString)
- function disassociateWidget(QWidget*)
- function associateWidget(QGraphicsWidget*,QString)
- function disassociateWidget(QGraphicsWidget*)
- function parametersFromDescription(KConfigGroup)
Other Functions and Classes
Print and Debug
- print(string message): prints message to console
- debug(string message): print message to console if it is running in a KDE debug build
GraphicsItem
This class represents an item on the canvas. Support is only provided so that GraphicsItem objects returned or taken by other objects work. There is no meaningful API provided directly in the JavaScript runtime for these objects and they should not need to be used directly.
QSizePolicy
The QSizePolicy class is a layout attribute describing horizontal and vertical resizing policy. This can be set on any graphics widget that you have using the enums provided for this (QtSizePolicy ), for example:
button = new PushButton(); button.sizePolicy = QSizePolicy(QSizePolicyMaximum, QSizePolicyFixed);
This is useful when your widgets are being laid out by a layout (specially the anchor layout).
- QtSizePolicy horizontalPolicy: The horizontal component of the size policy.
- QtSizePolicy verticalPolicy: The vertical component of the size policy.
- number horizontalStretch: The horizontal stretch factor of the size policy.
- number verticalStretch: The vertical stretch factor of the size policy.
IOJob
This object is returned by input/output access for asynchronous file and data access (see the section on Extensions for documentation on getUrl). It is used by connecting Javascript functions in your code to the relevant signals.
Functions:
- kill()
- suspend()
- resume()
Signals:
- data(IOJob job, ByteArray data): emitted whenever data arrives. If data is empty (data.length == 0) then the transmission has completed.
- dataReq(IOJob job, ByteArray data): when sending data, this signal is emitted when data is requested; add the data to be sent ot the data member, or leave it empty to signal that the process is complete and there is no more data to send
- finished(IOJob job): emitted when the transmission has completed
- suspended(IOJob job): emitted when the job has been suspeneded
- resumed(IOJob job)
- canceled(IOJob job)
- connected(IOJob job)
- redirection(IOJob job, Url to)
- permanentRedirection(IOJob job, Url from, Url to)
- mimetype(IOJob job, String mimetype)
QTimer
Read-write properties:
- boolean active: true if active, false if not
- boolean singleShot: true if the timer will fire once when started, false if it will fire repeatedly until stopped
- boolean interval: the interval in milliseconds that the timer will trigger
Functions:
- start(int msec): starts the timer with msec as the interval
- start(): starts the timer with the default interval
- stop(): stops the timer
Signals:
- timeout(): this signal is emitted whenever the timer interval is reached
Url
Represents a local or remote address. To create a new Url (or assign to an existing one), use the following syntax:
var url = new Url("http://kde.org")
Read-only properties:
- string toString: the URL as a String object
Read-write properties (each representing a portion of the full URL):
- string protocol
- string host
- string path
- string user
- string password
ByteArray
This class provides an array of bytes. This is often used by data centric objects, such as the Job classes returned by getUrl.
Read-only properties:
- number length: the size of the array (number of bytes)
Functions:
- chop(number numBytes): chops numBytes from the end of the array
- bool equals(ByteArray other)
- ByteArray left(number len): return len bytes from the left of the array
- ByteArray mid(number pos, number len): returns an array of bytes starting a post and length len (if len is -1, it returns all remaining bytes)
- ByteArray remove(number pos, number len): removes len bytes starting at index pos from the array and returns it
- ByteArray right(number len): returns len bytes from the right of the array
- ByteArray simplified(): returns a byte array that has whitespace removed from the start and the end, and which has each sequence of internal whitespace replaced with a single space
- ByteArray toBase64(): returns the array encoded in base64
- ByteArray toLower(): returns a lowercased copy of the array
- ByteArray toUpper(): returns an uppercased copy of the array
- ByteArray trimmed(): returns a copy of the array with whitespace remove from the start and end
- truncate(number pos): truncates the array at index pos
- String toLatin1String(): returns a Latin1-ized string based on the array
- String toUtf8(): (API v3) returns a string from the contents of the array using a Utf8 conversation
- String valueOf(): returns the raw data in the array as a string
Addons (API V3)
Plasmoids may also have plugins of their own, also written in Javascript, and which are shipped separately to the Plasmoid. These are referred to as "Addons" and are packaged similarly to a Plasmoid. For more information on creating Javascript Addons, visit the Javascript Addons tutorial.
It is possible to list, load and be notified of new Addons having been installed for your Plasmoid.
- Array[AddonInformation] listAddons(string type): an array of available addons of the provided type. The type name maps to the X-KDE-PluginInfo-Category entry in the Addon's metadata.desktop file.
- boolean loadAddon(String type, String id): load the addon with the given id and type, return true on success. In order to be notified when the addon is successfully created, add an event listener to the "addCreated" event.
The following are the Addon events which are recognized by the Plasmoid along with the type of event objects (if any) that are passed to registered event listeners that are registered with addEventListener:
- addonCreated: Object addOn
- newAddonsAvaiable
AddonInformation (API V3)
The AddonInformation object contains the following read-only properties:
- String id: the id of the Addon. Can be used with loadAddon
- String name: a string suitable for showing the user, such as in a configuration dialog
Extensions
An API extension is a security controlled set of functions and objects that are loaded on demand. These extensions are requested by the widget by listing the required and the optional extensions (if any) it wants loaded in its metadata.desktop file. This way, even prior to the widget being loaded, Plasma can know what it will want.
Required extensions are requested using the X-Plasma-RequiredExtensions key, and optional extensions with the X-Plasma-OptionalExtensions. For example:
X-Plasma-RequiredExtensions=FileDialog,MyCustomQScriptExtension
X-Plasma-OptionalExtensions=LaunchApp,HTTP
The Simplified Javascript Engine then decides if the widget will actually get that extension or not. Failure to load a required extension will result in script execution being aborted.
Each of the built-in extensions provided are described below.
FileDialog
Provides access to open and save dialog classes: OpenFileDialog and SaveFileDialog. Both are non-modal and run asynchronously, so the signals must be used. Other than the name difference (and resulting UI variance) the API for each is identical:
- Constructors
- OpenFileDialog
- SaveFileDialog
- Properties
- Read Only
- array(Url) urls: the selected file, as a Url object
- Url baseUrl, the current path (minus filename) as a Url
- string file: the selected file, as a string
- array(string) files: selected files (plural), as an array of strings
- Read/Write
- Url url: the current Url, can be read from when the user is done or assigned before to set the starting path
- string filter: a string representing the mimetype filter; e.g. "*.cpp|C++ Source Files\n*.h|Header files" or "*.cpp" or "*.cpp|*h"
- boolean localOnly: true to show only local files, false if network locations are Ok as well
- boolean directoriesOnly: true to only allow selection of a directory (not a file)
- boolean existingOnly: true if only existing files/directories may be selected
- Read Only
- Functions
- show(): when called, the dialog will be shown to the user
- Signals
- accepted(FileDialogProxy)': emitted when the file dialog has been successfully accepted by the user with one or more files/directories.
- finished(FileDialogProxy): emitted when the file dialog closes, included when cancelled/closed without being accepted
LocalIO
This extension allows access to local files.
Functions:
- IOJob getUrl(Url url): attempts to fetch the file using an IOJob
- IOJob getUrl(String url): attempts to fetch the file using an IOJob
NetworkIO
This extensions allows access to network addresses.
Functions:
- IOJob getUrl(Url url): attempts to fetch the file using an IOJob
- IOJob getUrl(String url): attempts to fetch the file using an IOJob
HTTP
This extension allows access to data and files via http and https.
Functions:
- IOJob getUrl(Url url): attempts to fetch the file using an IOJob
- IOJob getUrl(String url): attempts to fetch the file using an IOJob
- bool openUrl([string|Url] url): (API v4) Opens the url in the default application (or asks the user if there is no default application for the file). The url parameter may be either a string or a Url. Returns true on success, false on failure.
LaunchApp
Adds methods to the global plasmoid object that allow launching applications, running commands and opening files and urls.
- bool runApplication(string application[, array files])
Runs an application by name (can reference an installed .desktop file as well as an executable in the user's $PATH) with an optional array of files. The file array may contain either Urls or strings. Returns true on success, false on failure. - bool runCommand(string exe[, array args])
Runs the executable with the given arguments. Returns true on success, false on failure. - bool openUrl([string|Url] url):
Opens the url in the default application (or asks the user if there is no default application for the file). The url parameter may be either a string or a Url. Returns true on success, false on failure.