]> git.proxmox.com Git - mirror_novnc.git/blobdiff - docs/API.md
Fixed a race condition when attaching to an existing socket
[mirror_novnc.git] / docs / API.md
index a658cadebc11b65ca1b4d026c1a5e252c6740bb5..81b517b13577b536091e203258922b21f34bd4bd 100644 (file)
-# 1. Modules / API
+# noVNC API
+
+The interface of the noVNC client consists of a single RFB object that
+is instantiated once per connection.
+
+## RFB
 
-The noVNC client is a composed of several modular components that handle
-rendering, input, networking, etc. Each of the modules is designed to
-be cross-browser and be useful as a standalone library in other
-projects (see LICENSE.txt).
+The `RFB` object represents a single connection to a VNC server. It
+communicates using a WebSocket that must provide a standard RFB
+protocol stream.
 
+### Constructor
+
+[`RFB()`](#rfb-1)
+  - Creates and returns a new `RFB` object.
+
+### Properties
 
-## 1.1 Module List
+`viewOnly`
+  - Is a `boolean` indicating if any events (e.g. key presses or mouse
+    movement) should be prevented from being sent to the server.
+    Disabled by default.
 
-* __Mouse__ (core/input/mouse.js): Mouse input event handler with
-limited touch support.
+`focusOnClick`
+  - Is a `boolean` indicating if keyboard focus should automatically be
+    moved to the remote session when a `mousedown` or `touchstart`
+    event is received. Enabled by default.
 
-* __Keyboard__ (core/input/keyboard.js): Keyboard input event handler with
-non-US keyboard support. Translates keyDown and keyUp events to X11
-keysym values.
+`clipViewport`
+  - Is a `boolean` indicating if the remote session should be clipped
+    to its container. When disabled scrollbars will be shown to handle
+    the resulting overflow. Disabled by default.
 
-* __Display__ (core/display.js): Efficient 2D rendering abstraction
-layered on the HTML5 canvas element.
+`dragViewport`
+  - Is a `boolean` indicating if mouse events should control the
+    relative position of a clipped remote session. Only relevant if
+    `clipViewport` is enabled. Disabled by default.
 
-* __Websock__ (core/websock.js): Websock client from websockify
-with transparent binary data support.
-[Websock API](https://github.com/novnc/websockify/wiki/websock.js) wiki page.
+`scaleViewport`
+  - Is a `boolean` indicating if the remote session should be scaled
+    locally so it fits its container. When disabled it will be centered
+    if the remote session is smaller than its container, or handled
+    according to `clipViewport` if it is larger. Disabled by default.
 
-* __RFB__ (core/rfb.js): Main class that implements the RFB
-protocol and stitches the other classes together.
+`resizeSession`
+  - Is a `boolean` indicating if a request to resize the remote session
+    should be sent whenever the container changes dimensions. Disabled
+    by default.
 
+`showDotCursor`
+  - Is a `boolean` indicating whether a dot cursor should be shown
+    instead of a zero-sized or fully-transparent cursor if the server
+    sets such invisible cursor. Disabled by default.
 
-## 1.2 Configuration Attributes
+`background`
+  - Is a valid CSS [background](https://developer.mozilla.org/en-US/docs/Web/CSS/background)
+    style value indicating which background style should be applied
+    to the element containing the remote session screen. The default value is `rgb(40, 40, 40)`
+    (solid gray color).
 
-The Mouse, Keyboard, Display and RFB classes have a similar API for
-configuration options. Each configuration option has a default value,
-which can be overridden by a a configuration object passed to the
-constructor. Configuration options can then be read and modified after
-initialization with "get_*" and "set_*" methods respectively. For
-example, the following initializes an RFB object with the 'encrypt'
-configuration option enabled, then confirms it was set, then disables
-it.
+`qualityLevel`
+  - Is an `int` in range `[0-9]` controlling the desired JPEG quality.
+    Value `0` implies low quality and `9` implies high quality.
+    Default value is `6`.
 
-    var rfb = new RFB({'encrypt': true});
-    if (rfb.get_encrypt()) {
-        alert("Encryption is set");
-    }
-    rfb.set_encrypt(false);
+`compressionLevel`
+  - Is an `int` in range `[0-9]` controlling the desired compression
+    level. Value `0` means no compression. Level 1 uses a minimum of CPU
+    resources and achieves weak compression ratios, while level 9 offers
+    best compression but is slow in terms of CPU consumption on the server
+    side. Use high levels with very slow network connections.
+    Default value is `2`.
 
-Some attributes are read-only and cannot be changed. For example, the
-Display 'render_mode' option will throw an exception if an attempt is
-made to set it. The attribute mode is one of the following:
+`capabilities` *Read only*
+  - Is an `Object` indicating which optional extensions are available
+    on the server. Some methods may only be called if the corresponding
+    capability is set. The following capabilities are defined:
 
-    RO - read only
-    RW - read write
-    WO - write once
+    | name     | type      | description
+    | -------- | --------- | -----------
+    | `power`  | `boolean` | Machine power control is available
 
+### Events
 
-## 1.3 Methods
+[`connect`](#connect)
+  - The `connect` event is fired when the `RFB` object has completed
+    the connection and handshaking with the server.
 
-In addition to the getter and setter methods to modify configuration
-attributes, each of the modules has other methods that are available
-in the object instance. For example, the Display module has method
-named 'blitImage' which takes an array of pixel data and draws it to
-the 2D canvas.
+[`disconnect`](#disconnected)
+  - The `disconnect` event is fired when the `RFB` object disconnects.
 
-## 1.4 Callbacks
+[`credentialsrequired`](#credentialsrequired)
+  - The `credentialsrequired` event is fired when more credentials must
+    be given to continue.
 
-Each of the modules has certain events that can be hooked with
-callback functions. For the Mouse, Keyboard, Display and RFB classes
-the callback functions are assigned to configuration attributes. The
-WebSock module has a method named 'on' that takes two parameters: the
-callback event name, and the callback function.
+[`securityfailure`](#securityfailure)
+  - The `securityfailure` event is fired when the security negotiation
+    with the server fails.
 
-## 2. Modules
+[`clipboard`](#clipboard)
+  - The `clipboard` event is fired when clipboard data is received from
+    the server.
 
-## 2.1 Mouse Module
+[`bell`](#bell)
+  - The `bell` event is fired when a audible bell request is received
+    from the server.
 
-### 2.1.1 Configuration Attributes
+[`desktopname`](#desktopname)
+  - The `desktopname` event is fired when the remote desktop name
+    changes.
 
-| name        | type | mode | default  | description
-| ----------- | ---- | ---- | -------- | ------------
-| target      | DOM  | WO   | document | DOM element that captures mouse input
-| touchButton | int  | RW   | 1        | Button mask (1, 2, 4) for which click to send on touch devices. 0 means ignore clicks.
+[`capabilities`](#capabilities)
+  - The `capabilities` event is fired when `RFB.capabilities` is
+    updated.
 
-### 2.1.2 Methods
+### Methods
 
-| name   | parameters | description
-| ------ | ---------- | ------------
-| grab   | ()         | Begin capturing mouse events
-| ungrab | ()         | Stop capturing mouse events
+[`RFB.disconnect()`](#rfbdisconnect)
+  - Disconnect from the server.
 
-### 2.1.2 Callbacks
+[`RFB.sendCredentials()`](#rfbsendcredentials)
+  - Send credentials to server. Should be called after the
+    [`credentialsrequired`](#credentialsrequired) event has fired.
 
-| name          | parameters          | description
-| ------------- | ------------------- | ------------
-| onMouseButton | (x, y, down, bmask) | Handler for mouse button click/release
-| onMouseMove   | (x, y)              | Handler for mouse movement
+[`RFB.sendKey()`](#rfbsendKey)
+  - Send a key event.
 
+[`RFB.sendCtrlAltDel()`](#rfbsendctrlaltdel)
+  - Send Ctrl-Alt-Del key sequence.
 
-## 2.2 Keyboard Module
+[`RFB.focus()`](#rfbfocus)
+  - Move keyboard focus to the remote session.
 
-### 2.2.1 Configuration Attributes
-
-| name    | type | mode | default  | description
-| ------- | ---- | ---- | -------- | ------------
-| target  | DOM  | WO   | document | DOM element that captures keyboard input
-
-### 2.2.2 Methods
+[`RFB.blur()`](#rfbblur)
+  - Remove keyboard focus from the remote session.
 
-| name   | parameters | description
-| ------ | ---------- | ------------
-| grab   | ()         | Begin capturing keyboard events
-| ungrab | ()         | Stop capturing keyboard events
-
-### 2.2.3 Callbacks
-
-| name       | parameters           | description
-| ---------- | -------------------- | ------------
-| onKeyPress | (keysym, code, down) | Handler for key press/release
-
-
-## 2.3 Display Module
-
-### 2.3.1 Configuration Attributes
-
-| name        | type  | mode | default | description
-| ----------- | ----- | ---- | ------- | ------------
-| target      | DOM   | WO   |         | Canvas element for rendering
-| context     | raw   | RO   |         | Canvas 2D context for rendering
-| logo        | raw   | RW   |         | Logo to display when cleared: {"width": width, "height": height, "type": mime-type, "data": data}
-| scale       | float | RW   | 1.0     | Display area scale factor 0.0 - 1.0
-| viewport    | bool  | RW   | false   | Use viewport clipping
-| width       | int   | RO   |         | Display area width
-| height      | int   | RO   |         | Display area height
-| render_mode | str   | RO   | ''      | Canvas rendering mode
-| prefer_js   | str   | RW   |         | Prefer JavaScript over canvas methods
-| cursor_uri  | raw   | RW   |         | Can we render cursor using data URI
-
-### 2.3.2 Methods
-
-| name               | parameters                                              | description
-| ------------------ | ------------------------------------------------------- | ------------
-| viewportChangePos  | (deltaX, deltaY)                                        | Move the viewport relative to the current location
-| viewportChangeSize | (width, height)                                         | Change size of the viewport
-| absX               | (x)                                                     | Return X relative to the remote display
-| absY               | (y)                                                     | Return Y relative to the remote display
-| resize             | (width, height)                                         | Set width and height
-| flip               | (from_queue)                                            | Update the visible canvas with the contents of the rendering canvas
-| clear              | ()                                                      | Clear the display (show logo if set)
-| pending            | ()                                                      | Check if there are waiting items in the render queue
-| flush              | ()                                                      | Resume processing the render queue unless it's empty
-| fillRect           | (x, y, width, height, color, from_queue)                | Draw a filled in rectangle
-| copyImage          | (old_x, old_y, new_x, new_y, width, height, from_queue) | Copy a rectangular area
-| imageRect          | (x, y, mime, arr)                                       | Draw a rectangle with an image
-| startTile          | (x, y, width, height, color)                            | Begin updating a tile
-| subTile            | (tile, x, y, w, h, color)                               | Update a sub-rectangle within the given tile
-| finishTile         | ()                                                      | Draw the current tile to the display
-| blitImage          | (x, y, width, height, arr, offset, from_queue)          | Blit pixels (of R,G,B,A) to the display
-| blitRgbImage       | (x, y, width, height, arr, offset, from_queue)          | Blit RGB encoded image to display
-| blitRgbxImage      | (x, y, width, height, arr, offset, from_queue)          | Blit RGBX encoded image to display
-| drawImage          | (img, x, y)                                             | Draw image and track damage
-| changeCursor       | (pixels, mask, hotx, hoty, w, h)                        | Change cursor appearance
-| defaultCursor      | ()                                                      | Restore default cursor appearance
-| disableLocalCursor | ()                                                      | Disable local (client-side) cursor
-| clippingDisplay    | ()                                                      | Check if the remote display is larger than the client display
-| autoscale          | (containerWidth, containerHeight, downscaleOnly)        | Scale the display
-
-### 2.3.3 Callbacks
-
-| name    | parameters | description
-| ------- | ---------- | ------------
-| onFlush | ()         | A display flush has been requested and we are now ready to resume FBU processing
-
-
-## 2.4 RFB Module
-
-### 2.4.1 Configuration Attributes
-
-| name              | type | mode | default    | description
-| ----------------- | ---- | ---- | ---------- | ------------
-| target            | DOM  | WO   | null       | Canvas element for rendering (passed to Display, Mouse and Keyboard)
-| encrypt           | bool | RW   | false      | Use TLS/SSL encryption
-| local_cursor      | bool | RW   | false      | Request locally rendered cursor
-| shared            | bool | RW   | true       | Request shared VNC mode
-| view_only         | bool | RW   | false      | Disable client mouse/keyboard
-| xvp_password_sep  | str  | RW   | '@'        | Separator for XVP password fields
-| disconnectTimeout | int  | RW   | 3          | Time (in seconds) to wait for disconnection
-| wsProtocols       | arr  | RW   | ['binary'] | Protocols to use in the WebSocket connection
-| repeaterID        | str  | RW   | ''         | UltraVNC RepeaterID to connect to
-| viewportDrag      | bool | RW   | false      | Move the viewport on mouse drags
-
-### 2.4.2 Methods
-
-| name               | parameters                   | description
-| ------------------ | ---------------------------- | ------------
-| connect            | (host, port, password, path) | Connect to the given host:port/path. Optional password and path.
-| disconnect         | ()                           | Disconnect
-| sendPassword       | (passwd)                     | Send password after onPasswordRequired callback
-| sendCtrlAltDel     | ()                           | Send Ctrl-Alt-Del key sequence
-| xvpOp              | (ver, op)                    | Send a XVP operation (2=shutdown, 3=reboot, 4=reset)
-| xvpShutdown        | ()                           | Send XVP shutdown.
-| xvpReboot          | ()                           | Send XVP reboot.
-| xvpReset           | ()                           | Send XVP reset.
-| sendKey            | (keysym, code, down)         | Send a key press event. If down not specified, send a down and up event.
-| clipboardPasteFrom | (text)                       | Send a clipboard paste event
-| requestDesktopSize | (width, height)              | Send a request to change the remote desktop size.
-
-### 2.4.3 Callbacks
-
-| name               | parameters                 | description
-| ------------------ | -------------------------- | ------------
-| onUpdateState      | (rfb, state, oldstate)     | Connection state change (see details below)
-| onNotification     | (rfb, msg, level, options) | Notification for the UI (optional options)
-| onDisconnected     | (rfb, reason)              | Disconnection finished with an optional reason. No reason specified means normal disconnect.
-| onPasswordRequired | (rfb, msg)                 | VNC password is required (use sendPassword), optionally comes with a message.
-| onClipboard        | (rfb, text)                | RFB clipboard contents received
-| onBell             | (rfb)                      | RFB Bell message received
-| onFBUReceive       | (rfb, fbu)                 | RFB FBU received but not yet processed (see details below)
-| onFBUComplete      | (rfb, fbu)                 | RFB FBU received and processed (see details below)
-| onFBResize         | (rfb, width, height)       | Frame buffer (remote desktop) size changed
-| onDesktopName      | (rfb, name)                | VNC desktop name recieved
-| onXvpInit          | (version)                  | XVP extensions active for this connection.
-
-
-__RFB onUpdateState callback details__
-
-The RFB module has an 'onUpdateState' callback that is invoked after
-the noVNC connection state changes. Here is a list of the states that
-are reported. Note that the RFB module can not transition from the
-disconnected state in any way, a new instance of the object has to be
-created for new connections.
-
-| connection state | description
-| ---------------- | ------------
-| connecting       | starting to connect
-| connected        | connected normally
-| disconnecting    | starting to disconnect
-| disconnected     | disconnected - permanent end-state for this RFB object
-
-__RFB onFBUReceive and on FBUComplete callback details__
-
-The onFBUReceive callback is invoked when a frame buffer update
-message has been received from the server but before the RFB class has
-done any additional handling. The onFBUComplete callback is invoked
-with the same information but after the RFB class has handled the
-message.
-
-The 'fbu' parameter is an object with the following structure:
-
-    {
-        x:            FBU_x_position,
-        y:            FBU_y_position,
-        width:        FBU_width,
-        height:       FBU_height,
-        encoding:     FBU_encoding_number,
-        encodingName: FBU_encoding_string
-    }
+[`RFB.machineShutdown()`](#rfbmachineshutdown)
+  - Request a shutdown of the remote machine.
+
+[`RFB.machineReboot()`](#rfbmachinereboot)
+  - Request a reboot of the remote machine.
+
+[`RFB.machineReset()`](#rfbmachinereset)
+  - Request a reset of the remote machine.
+
+[`RFB.clipboardPasteFrom()`](#rfbclipboardPasteFrom)
+  - Send clipboard contents to server.
+
+### Details
+
+#### RFB()
+
+The `RFB()` constructor returns a new `RFB` object and initiates a new
+connection to a specified VNC server.
+
+##### Syntax
+
+    let rfb = new RFB( target, url [, options] );
+
+###### Parameters
+
+**`target`**
+  - A block [`HTMLElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement)
+    that specifies where the `RFB` object should attach itself. The
+    existing contents of the `HTMLElement` will be untouched, but new
+    elements will be added during the lifetime of the `RFB` object.
+
+**`urlOrDataChannel`**
+  - A `DOMString` specifying the VNC server to connect to. This must be
+    a valid WebSocket URL. This can also be a `WebSocket` or `RTCDataChannel`.
+    If a `DOMString` is supplied then the connection will be delayed until the next tick to
+    allow allow adding event listeners that fire on connection. If an existing object
+    is supplied then the connection logic happens the same tick. For instance if passing
+    in an existing open WebSocket then it will not be possible to listen for the `connect`
+    event. This is to avoid dropping data on a connection that has data as soon as its opened.
+
+**`options`** *Optional*
+  - An `Object` specifying extra details about how the connection
+    should be made.
+
+    Possible options:
+
+    `shared`
+      - A `boolean` indicating if the remote server should be shared or
+        if any other connected clients should be disconnected. Enabled
+        by default.
+
+    `credentials`
+      - An `Object` specifying the credentials to provide to the server
+        when authenticating. The following credentials are possible:
+
+        | name         | type        | description
+        | ------------ | ----------- | -----------
+        | `"username"` | `DOMString` | The user that authenticates
+        | `"password"` | `DOMString` | Password for the user
+        | `"target"`   | `DOMString` | Target machine or session
+
+    `repeaterID`
+      - A `DOMString` specifying the ID to provide to any VNC repeater
+        encountered.
+
+    `wsProtocols`
+      - An `Array` of `DOMString`s specifying the sub-protocols to use
+        in the WebSocket connection. Empty by default.
+
+#### connect
+
+The `connect` event is fired after all the handshaking with the server
+is completed and the connection is fully established. After this event
+the `RFB` object is ready to recieve graphics updates and to send input.
+
+#### disconnect
+
+The `disconnect` event is fired when the connection has been
+terminated. The `detail` property is an `Object` that contains the
+property `clean`. `clean` is a `boolean` indicating if the termination
+was clean or not. In the event of an unexpected termination or an error
+`clean` will be set to false.
+
+#### credentialsrequired
+
+The `credentialsrequired` event is fired when the server requests more
+credentials than were specified to [`RFB()`](#rfb-1). The `detail`
+property is an `Object` containing the property `types` which is an
+`Array` of `DOMString` listing the credentials that are required.
+
+#### securityfailure
+
+The `securityfailure` event is fired when the handshaking process with
+the server fails during the security negotiation step. The `detail`
+property is an `Object` containing the following properties:
+
+| Property | Type        | Description
+| -------- | ----------- | -----------
+| `status` | `long`      | The failure status code
+| `reason` | `DOMString` | The **optional** reason for the failure
+
+The property `status` corresponds to the
+[SecurityResult](https://github.com/rfbproto/rfbproto/blob/master/rfbproto.rst#securityresult)
+status code in cases of failure. A status of zero will not be sent in
+this event since that indicates a successful security handshaking
+process. The optional property `reason` is provided by the server and
+thus the language of the string is not known. However most servers will
+probably send English strings. The server can choose to not send a
+reason and in these cases the `reason` property will be omitted.
+
+#### clipboard
+
+The `clipboard` event is fired when the server has sent clipboard data.
+The `detail` property is an `Object` containing the property `text`
+which is a `DOMString` with the clipboard data.
+
+#### bell
+
+The `bell` event is fired when the server has requested an audible
+bell.
+
+#### desktopname
+
+The `desktopname` event is fired when the name of the remote desktop
+changes. The `detail` property is an `Object` with the property `name`
+which is a `DOMString` specifying the new name.
+
+#### capabilities
+
+The `capabilities` event is fired whenever an entry is added or removed
+from `RFB.capabilities`. The `detail` property is an `Object` with the
+property `capabilities` containing the new value of `RFB.capabilities`.
+
+#### RFB.disconnect()
+
+The `RFB.disconnect()` method is used to disconnect from the currently
+connected server.
+
+##### Syntax
+
+    RFB.disconnect( );
+
+#### RFB.sendCredentials()
+
+The `RFB.sendCredentials()` method is used to provide the missing
+credentials after a `credentialsrequired` event has been fired.
+
+##### Syntax
+
+    RFB.sendCredentials( credentials );
+
+###### Parameters
+
+**`credentials`**
+  - An `Object` specifying the credentials to provide to the server
+    when authenticating. See [`RFB()`](#rfb-1) for details.
+
+#### RFB.sendKey()
+
+The `RFB.sendKey()` method is used to send a key event to the server.
+
+##### Syntax
+
+    RFB.sendKey( keysym, code [, down] );
+
+###### Parameters
+
+**`keysym`**
+  - A `long` specifying the RFB keysym to send. Can be `0` if a valid
+    **`code`** is specified.
+
+**`code`**
+  - A `DOMString` specifying the physical key to send. Valid values are
+    those that can be specified to
+    [`KeyboardEvent.code`](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/code).
+    If the physical key cannot be determined then `null` shall be
+    specified.
+
+**`down`** *Optional*
+  - A `boolean` specifying if a press or a release event should be
+    sent. If omitted then both a press and release event are sent.
+
+#### RFB.sendCtrlAltDel()
+
+The `RFB.sendCtrlAltDel()` method is used to send the key sequence
+*left Control*, *left Alt*, *Delete*. This is a convenience wrapper
+around [`RFB.sendKey()`](#rfbsendkey).
+
+##### Syntax
+
+    RFB.sendCtrlAltDel( );
+
+#### RFB.focus()
+
+The `RFB.focus()` method sets the keyboard focus on the remote session.
+Keyboard events will be sent to the remote server after this point.
+
+##### Syntax
+
+    RFB.focus( );
+
+#### RFB.blur()
+
+The `RFB.blur()` method remove keyboard focus on the remote session.
+Keyboard events will no longer be sent to the remote server after this
+point.
+
+##### Syntax
+
+    RFB.blur( );
+
+#### RFB.machineShutdown()
+
+The `RFB.machineShutdown()` method is used to request to shut down the
+remote machine. The capability `power` must be set for this method to
+have any effect.
+
+##### Syntax
+
+    RFB.machineShutdown( );
+
+#### RFB.machineReboot()
+
+The `RFB.machineReboot()` method is used to request a clean reboot of
+the remote machine. The capability `power` must be set for this method
+to have any effect.
+
+##### Syntax
+
+    RFB.machineReboot( );
+
+#### RFB.machineReset()
+
+The `RFB.machineReset()` method is used to request a forced reset of
+the remote machine. The capability `power` must be set for this method
+to have any effect.
+
+##### Syntax
+
+    RFB.machineReset( );
+
+#### RFB.clipboardPasteFrom()
+
+The `RFB.clipboardPasteFrom()` method is used to send clipboard data
+to the remote server.
+
+##### Syntax
+
+    RFB.clipboardPasteFrom( text );
+
+###### Parameters
+
+**`text`**
+  - A `DOMString` specifying the clipboard data to send.