Merge guacamole-common-js.

This commit is contained in:
Michael Jumper
2013-06-05 16:26:01 -07:00
14 changed files with 6485 additions and 0 deletions

2
guacamole-common-js/.gitignore vendored Normal file
View File

@@ -0,0 +1,2 @@
target/
*~

View File

@@ -0,0 +1,57 @@
2013-05-29 Michael Jumper <zhangmaike@users.sourceforge.net>
* Fix support for AltGr and modifiers
* Handle bad source rect sizes in copy
2012-10-24 Michael Jumper <zhangmaike@users.sourceforge.net>
* Implement base audio support
* Implement audio instruction
* Add width/height getters to client
* Add onresize event to client
2012-10-16 Michael Jumper <zhangmaike@users.sourceforge.net>
* Fix stream inefficiency bug (ticket #201)
2012-09-27 Michael Jumper <zhangmaike@users.sourceforge.net>
* Fix variable naming conflict (ticket #191)
2012-08-11 Michael Jumper <zhangmaike@users.sourceforge.net>
* Improve documentation
2012-08-02 Michael Jumper <zhangmaike@users.sourceforge.net>
* Fix keyboard event handling
2012-08-01 Michael Jumper <zhangmaike@users.sourceforge.net>
* Implement absolute touch device emulation
2012-05-04 Michael Jumper <zhangmaike@users.sourceforge.net>
* Improved iPad and touch device support
* Improved touch support
* Implemented new drawing instructions
* Nestable layers
2011-12-11 Michael Jumper <zhangmaike@users.sourceforge.net>
* Implemented improved instruction format
* Fixed errors in IE in on-screen keyboard
* Relicensed as Mozilla/LGPL/GPL
* Touch support (emulates touchpad control of mouse pointer)
* "rect" and "clip" instructions
2011-07-13 Michael Jumper <zhangmaike@users.sourceforge.net>
* "sync" instruction
* Channel masks (alpha compositing)
* Multiple tunnel support
2011-03-02 Michael Jumper <zhangmaike@users.sourceforge.net>
* Initial release

470
guacamole-common-js/LICENSE Normal file
View File

@@ -0,0 +1,470 @@
MOZILLA PUBLIC LICENSE
Version 1.1
---------------
1. Definitions.
1.0.1. "Commercial Use" means distribution or otherwise making the
Covered Code available to a third party.
1.1. "Contributor" means each entity that creates or contributes to
the creation of Modifications.
1.2. "Contributor Version" means the combination of the Original
Code, prior Modifications used by a Contributor, and the Modifications
made by that particular Contributor.
1.3. "Covered Code" means the Original Code or Modifications or the
combination of the Original Code and Modifications, in each case
including portions thereof.
1.4. "Electronic Distribution Mechanism" means a mechanism generally
accepted in the software development community for the electronic
transfer of data.
1.5. "Executable" means Covered Code in any form other than Source
Code.
1.6. "Initial Developer" means the individual or entity identified
as the Initial Developer in the Source Code notice required by Exhibit
A.
1.7. "Larger Work" means a work which combines Covered Code or
portions thereof with code not governed by the terms of this License.
1.8. "License" means this document.
1.8.1. "Licensable" means having the right to grant, to the maximum
extent possible, whether at the time of the initial grant or
subsequently acquired, any and all of the rights conveyed herein.
1.9. "Modifications" means any addition to or deletion from the
substance or structure of either the Original Code or any previous
Modifications. When Covered Code is released as a series of files, a
Modification is:
A. Any addition to or deletion from the contents of a file
containing Original Code or previous Modifications.
B. Any new file that contains any part of the Original Code or
previous Modifications.
1.10. "Original Code" means Source Code of computer software code
which is described in the Source Code notice required by Exhibit A as
Original Code, and which, at the time of its release under this
License is not already Covered Code governed by this License.
1.10.1. "Patent Claims" means any patent claim(s), now owned or
hereafter acquired, including without limitation, method, process,
and apparatus claims, in any patent Licensable by grantor.
1.11. "Source Code" means the preferred form of the Covered Code for
making modifications to it, including all modules it contains, plus
any associated interface definition files, scripts used to control
compilation and installation of an Executable, or source code
differential comparisons against either the Original Code or another
well known, available Covered Code of the Contributor's choice. The
Source Code can be in a compressed or archival form, provided the
appropriate decompression or de-archiving software is widely available
for no charge.
1.12. "You" (or "Your") means an individual or a legal entity
exercising rights under, and complying with all of the terms of, this
License or a future version of this License issued under Section 6.1.
For legal entities, "You" includes any entity which controls, is
controlled by, or is under common control with You. For purposes of
this definition, "control" means (a) the power, direct or indirect,
to cause the direction or management of such entity, whether by
contract or otherwise, or (b) ownership of more than fifty percent
(50%) of the outstanding shares or beneficial ownership of such
entity.
2. Source Code License.
2.1. The Initial Developer Grant.
The Initial Developer hereby grants You a world-wide, royalty-free,
non-exclusive license, subject to third party intellectual property
claims:
(a) under intellectual property rights (other than patent or
trademark) Licensable by Initial Developer to use, reproduce,
modify, display, perform, sublicense and distribute the Original
Code (or portions thereof) with or without Modifications, and/or
as part of a Larger Work; and
(b) under Patents Claims infringed by the making, using or
selling of Original Code, to make, have made, use, practice,
sell, and offer for sale, and/or otherwise dispose of the
Original Code (or portions thereof).
(c) the licenses granted in this Section 2.1(a) and (b) are
effective on the date Initial Developer first distributes
Original Code under the terms of this License.
(d) Notwithstanding Section 2.1(b) above, no patent license is
granted: 1) for code that You delete from the Original Code; 2)
separate from the Original Code; or 3) for infringements caused
by: i) the modification of the Original Code or ii) the
combination of the Original Code with other software or devices.
2.2. Contributor Grant.
Subject to third party intellectual property claims, each Contributor
hereby grants You a world-wide, royalty-free, non-exclusive license
(a) under intellectual property rights (other than patent or
trademark) Licensable by Contributor, to use, reproduce, modify,
display, perform, sublicense and distribute the Modifications
created by such Contributor (or portions thereof) either on an
unmodified basis, with other Modifications, as Covered Code
and/or as part of a Larger Work; and
(b) under Patent Claims infringed by the making, using, or
selling of Modifications made by that Contributor either alone
and/or in combination with its Contributor Version (or portions
of such combination), to make, use, sell, offer for sale, have
made, and/or otherwise dispose of: 1) Modifications made by that
Contributor (or portions thereof); and 2) the combination of
Modifications made by that Contributor with its Contributor
Version (or portions of such combination).
(c) the licenses granted in Sections 2.2(a) and 2.2(b) are
effective on the date Contributor first makes Commercial Use of
the Covered Code.
(d) Notwithstanding Section 2.2(b) above, no patent license is
granted: 1) for any code that Contributor has deleted from the
Contributor Version; 2) separate from the Contributor Version;
3) for infringements caused by: i) third party modifications of
Contributor Version or ii) the combination of Modifications made
by that Contributor with other software (except as part of the
Contributor Version) or other devices; or 4) under Patent Claims
infringed by Covered Code in the absence of Modifications made by
that Contributor.
3. Distribution Obligations.
3.1. Application of License.
The Modifications which You create or to which You contribute are
governed by the terms of this License, including without limitation
Section 2.2. The Source Code version of Covered Code may be
distributed only under the terms of this License or a future version
of this License released under Section 6.1, and You must include a
copy of this License with every copy of the Source Code You
distribute. You may not offer or impose any terms on any Source Code
version that alters or restricts the applicable version of this
License or the recipients' rights hereunder. However, You may include
an additional document offering the additional rights described in
Section 3.5.
3.2. Availability of Source Code.
Any Modification which You create or to which You contribute must be
made available in Source Code form under the terms of this License
either on the same media as an Executable version or via an accepted
Electronic Distribution Mechanism to anyone to whom you made an
Executable version available; and if made available via Electronic
Distribution Mechanism, must remain available for at least twelve (12)
months after the date it initially became available, or at least six
(6) months after a subsequent version of that particular Modification
has been made available to such recipients. You are responsible for
ensuring that the Source Code version remains available even if the
Electronic Distribution Mechanism is maintained by a third party.
3.3. Description of Modifications.
You must cause all Covered Code to which You contribute to contain a
file documenting the changes You made to create that Covered Code and
the date of any change. You must include a prominent statement that
the Modification is derived, directly or indirectly, from Original
Code provided by the Initial Developer and including the name of the
Initial Developer in (a) the Source Code, and (b) in any notice in an
Executable version or related documentation in which You describe the
origin or ownership of the Covered Code.
3.4. Intellectual Property Matters
(a) Third Party Claims.
If Contributor has knowledge that a license under a third party's
intellectual property rights is required to exercise the rights
granted by such Contributor under Sections 2.1 or 2.2,
Contributor must include a text file with the Source Code
distribution titled "LEGAL" which describes the claim and the
party making the claim in sufficient detail that a recipient will
know whom to contact. If Contributor obtains such knowledge after
the Modification is made available as described in Section 3.2,
Contributor shall promptly modify the LEGAL file in all copies
Contributor makes available thereafter and shall take other steps
(such as notifying appropriate mailing lists or newsgroups)
reasonably calculated to inform those who received the Covered
Code that new knowledge has been obtained.
(b) Contributor APIs.
If Contributor's Modifications include an application programming
interface and Contributor has knowledge of patent licenses which
are reasonably necessary to implement that API, Contributor must
also include this information in the LEGAL file.
(c) Representations.
Contributor represents that, except as disclosed pursuant to
Section 3.4(a) above, Contributor believes that Contributor's
Modifications are Contributor's original creation(s) and/or
Contributor has sufficient rights to grant the rights conveyed by
this License.
3.5. Required Notices.
You must duplicate the notice in Exhibit A in each file of the Source
Code. If it is not possible to put such notice in a particular Source
Code file due to its structure, then You must include such notice in a
location (such as a relevant directory) where a user would be likely
to look for such a notice. If You created one or more Modification(s)
You may add your name as a Contributor to the notice described in
Exhibit A. You must also duplicate this License in any documentation
for the Source Code where You describe recipients' rights or ownership
rights relating to Covered Code. You may choose to offer, and to
charge a fee for, warranty, support, indemnity or liability
obligations to one or more recipients of Covered Code. However, You
may do so only on Your own behalf, and not on behalf of the Initial
Developer or any Contributor. You must make it absolutely clear than
any such warranty, support, indemnity or liability obligation is
offered by You alone, and You hereby agree to indemnify the Initial
Developer and every Contributor for any liability incurred by the
Initial Developer or such Contributor as a result of warranty,
support, indemnity or liability terms You offer.
3.6. Distribution of Executable Versions.
You may distribute Covered Code in Executable form only if the
requirements of Section 3.1-3.5 have been met for that Covered Code,
and if You include a notice stating that the Source Code version of
the Covered Code is available under the terms of this License,
including a description of how and where You have fulfilled the
obligations of Section 3.2. The notice must be conspicuously included
in any notice in an Executable version, related documentation or
collateral in which You describe recipients' rights relating to the
Covered Code. You may distribute the Executable version of Covered
Code or ownership rights under a license of Your choice, which may
contain terms different from this License, provided that You are in
compliance with the terms of this License and that the license for the
Executable version does not attempt to limit or alter the recipient's
rights in the Source Code version from the rights set forth in this
License. If You distribute the Executable version under a different
license You must make it absolutely clear that any terms which differ
from this License are offered by You alone, not by the Initial
Developer or any Contributor. You hereby agree to indemnify the
Initial Developer and every Contributor for any liability incurred by
the Initial Developer or such Contributor as a result of any such
terms You offer.
3.7. Larger Works.
You may create a Larger Work by combining Covered Code with other code
not governed by the terms of this License and distribute the Larger
Work as a single product. In such a case, You must make sure the
requirements of this License are fulfilled for the Covered Code.
4. Inability to Comply Due to Statute or Regulation.
If it is impossible for You to comply with any of the terms of this
License with respect to some or all of the Covered Code due to
statute, judicial order, or regulation then You must: (a) comply with
the terms of this License to the maximum extent possible; and (b)
describe the limitations and the code they affect. Such description
must be included in the LEGAL file described in Section 3.4 and must
be included with all distributions of the Source Code. Except to the
extent prohibited by statute or regulation, such description must be
sufficiently detailed for a recipient of ordinary skill to be able to
understand it.
5. Application of this License.
This License applies to code to which the Initial Developer has
attached the notice in Exhibit A and to related Covered Code.
6. Versions of the License.
6.1. New Versions.
Netscape Communications Corporation ("Netscape") may publish revised
and/or new versions of the License from time to time. Each version
will be given a distinguishing version number.
6.2. Effect of New Versions.
Once Covered Code has been published under a particular version of the
License, You may always continue to use it under the terms of that
version. You may also choose to use such Covered Code under the terms
of any subsequent version of the License published by Netscape. No one
other than Netscape has the right to modify the terms applicable to
Covered Code created under this License.
6.3. Derivative Works.
If You create or use a modified version of this License (which you may
only do in order to apply it to code which is not already Covered Code
governed by this License), You must (a) rename Your license so that
the phrases "Mozilla", "MOZILLAPL", "MOZPL", "Netscape",
"MPL", "NPL" or any confusingly similar phrase do not appear in your
license (except to note that your license differs from this License)
and (b) otherwise make it clear that Your version of the license
contains terms which differ from the Mozilla Public License and
Netscape Public License. (Filling in the name of the Initial
Developer, Original Code or Contributor in the notice described in
Exhibit A shall not of themselves be deemed to be modifications of
this License.)
7. DISCLAIMER OF WARRANTY.
COVERED CODE IS PROVIDED UNDER THIS LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
WITHOUT LIMITATION, WARRANTIES THAT THE COVERED CODE IS FREE OF
DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE OR NON-INFRINGING.
THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE COVERED CODE
IS WITH YOU. SHOULD ANY COVERED CODE PROVE DEFECTIVE IN ANY RESPECT,
YOU (NOT THE INITIAL DEVELOPER OR ANY OTHER CONTRIBUTOR) ASSUME THE
COST OF ANY NECESSARY SERVICING, REPAIR OR CORRECTION. THIS DISCLAIMER
OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. NO USE OF
ANY COVERED CODE IS AUTHORIZED HEREUNDER EXCEPT UNDER THIS DISCLAIMER.
8. TERMINATION.
8.1. This License and the rights granted hereunder will terminate
automatically if You fail to comply with terms herein and fail to cure
such breach within 30 days of becoming aware of the breach. All
sublicenses to the Covered Code which are properly granted shall
survive any termination of this License. Provisions which, by their
nature, must remain in effect beyond the termination of this License
shall survive.
8.2. If You initiate litigation by asserting a patent infringement
claim (excluding declatory judgment actions) against Initial Developer
or a Contributor (the Initial Developer or Contributor against whom
You file such action is referred to as "Participant") alleging that:
(a) such Participant's Contributor Version directly or indirectly
infringes any patent, then any and all rights granted by such
Participant to You under Sections 2.1 and/or 2.2 of this License
shall, upon 60 days notice from Participant terminate prospectively,
unless if within 60 days after receipt of notice You either: (i)
agree in writing to pay Participant a mutually agreeable reasonable
royalty for Your past and future use of Modifications made by such
Participant, or (ii) withdraw Your litigation claim with respect to
the Contributor Version against such Participant. If within 60 days
of notice, a reasonable royalty and payment arrangement are not
mutually agreed upon in writing by the parties or the litigation claim
is not withdrawn, the rights granted by Participant to You under
Sections 2.1 and/or 2.2 automatically terminate at the expiration of
the 60 day notice period specified above.
(b) any software, hardware, or device, other than such Participant's
Contributor Version, directly or indirectly infringes any patent, then
any rights granted to You by such Participant under Sections 2.1(b)
and 2.2(b) are revoked effective as of the date You first made, used,
sold, distributed, or had made, Modifications made by that
Participant.
8.3. If You assert a patent infringement claim against Participant
alleging that such Participant's Contributor Version directly or
indirectly infringes any patent where such claim is resolved (such as
by license or settlement) prior to the initiation of patent
infringement litigation, then the reasonable value of the licenses
granted by such Participant under Sections 2.1 or 2.2 shall be taken
into account in determining the amount or value of any payment or
license.
8.4. In the event of termination under Sections 8.1 or 8.2 above,
all end user license agreements (excluding distributors and resellers)
which have been validly granted by You or any distributor hereunder
prior to termination shall survive termination.
9. LIMITATION OF LIABILITY.
UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, WHETHER TORT
(INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL YOU, THE INITIAL
DEVELOPER, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF COVERED CODE,
OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO ANY PERSON FOR
ANY INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES OF ANY
CHARACTER INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF GOODWILL,
WORK STOPPAGE, COMPUTER FAILURE OR MALFUNCTION, OR ANY AND ALL OTHER
COMMERCIAL DAMAGES OR LOSSES, EVEN IF SUCH PARTY SHALL HAVE BEEN
INFORMED OF THE POSSIBILITY OF SUCH DAMAGES. THIS LIMITATION OF
LIABILITY SHALL NOT APPLY TO LIABILITY FOR DEATH OR PERSONAL INJURY
RESULTING FROM SUCH PARTY'S NEGLIGENCE TO THE EXTENT APPLICABLE LAW
PROHIBITS SUCH LIMITATION. SOME JURISDICTIONS DO NOT ALLOW THE
EXCLUSION OR LIMITATION OF INCIDENTAL OR CONSEQUENTIAL DAMAGES, SO
THIS EXCLUSION AND LIMITATION MAY NOT APPLY TO YOU.
10. U.S. GOVERNMENT END USERS.
The Covered Code is a "commercial item," as that term is defined in
48 C.F.R. 2.101 (Oct. 1995), consisting of "commercial computer
software" and "commercial computer software documentation," as such
terms are used in 48 C.F.R. 12.212 (Sept. 1995). Consistent with 48
C.F.R. 12.212 and 48 C.F.R. 227.7202-1 through 227.7202-4 (June 1995),
all U.S. Government End Users acquire Covered Code with only those
rights set forth herein.
11. MISCELLANEOUS.
This License represents the complete agreement concerning subject
matter hereof. If any provision of this License is held to be
unenforceable, such provision shall be reformed only to the extent
necessary to make it enforceable. This License shall be governed by
California law provisions (except to the extent applicable law, if
any, provides otherwise), excluding its conflict-of-law provisions.
With respect to disputes in which at least one party is a citizen of,
or an entity chartered or registered to do business in the United
States of America, any litigation relating to this License shall be
subject to the jurisdiction of the Federal Courts of the Northern
District of California, with venue lying in Santa Clara County,
California, with the losing party responsible for costs, including
without limitation, court costs and reasonable attorneys' fees and
expenses. The application of the United Nations Convention on
Contracts for the International Sale of Goods is expressly excluded.
Any law or regulation which provides that the language of a contract
shall be construed against the drafter shall not apply to this
License.
12. RESPONSIBILITY FOR CLAIMS.
As between Initial Developer and the Contributors, each party is
responsible for claims and damages arising, directly or indirectly,
out of its utilization of rights under this License and You agree to
work with Initial Developer and Contributors to distribute such
responsibility on an equitable basis. Nothing herein is intended or
shall be deemed to constitute any admission of liability.
13. MULTIPLE-LICENSED CODE.
Initial Developer may designate portions of the Covered Code as
"Multiple-Licensed". "Multiple-Licensed" means that the Initial
Developer permits you to utilize portions of the Covered Code under
Your choice of the NPL or the alternative licenses, if any, specified
by the Initial Developer in the file described in Exhibit A.
EXHIBIT A -Mozilla Public License.
``The contents of this file are subject to the Mozilla Public License
Version 1.1 (the "License"); you may not use this file except in
compliance with the License. You may obtain a copy of the License at
http://www.mozilla.org/MPL/
Software distributed under the License is distributed on an "AS IS"
basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
License for the specific language governing rights and limitations
under the License.
The Original Code is ______________________________________.
The Initial Developer of the Original Code is ________________________.
Portions created by ______________________ are Copyright (C) ______
_______________________. All Rights Reserved.
Contributor(s): ______________________________________.
Alternatively, the contents of this file may be used under the terms
of the _____ license (the "[___] License"), in which case the
provisions of [______] License are applicable instead of those
above. If you wish to allow use of your version of this file only
under the terms of the [____] License and not to allow others to use
your version of this file under the MPL, indicate your decision by
deleting the provisions above and replace them with the notice and
other provisions required by the [___] License. If you do not delete
the provisions above, a recipient may use your version of this file
under either the MPL or the [___] License."
[NOTE: The text of this Exhibit A may differ slightly from the text of
the notices in the Source Code files of the Original Code. You should
use the text of this Exhibit A rather than the text found in the
Original Code Source Code for Your Modifications.]

View File

@@ -0,0 +1,78 @@
------------------------------------------------------------
About this README
------------------------------------------------------------
This README is intended to provide quick and to-the-point documentation for
technical users intending to compile parts of Guacamole themselves.
Distribution-specific packages are available from the files section of the main
project page:
http://sourceforge.net/projects/guacamole/files/
Distribution-specific documentation is provided on the Guacamole wiki:
http://guac-dev.org/
------------------------------------------------------------
What is guacamole-common-js?
------------------------------------------------------------
guacamole-common-js is the core JavaScript library used by the Guacamole web
application.
guacamole-common-js provides an efficient HTTP tunnel for transporting
protocol data between JavaScript and the web application, as well as an
implementation of a Guacamole protocol client and abstract synchronized
drawing layers.
------------------------------------------------------------
Compiling and installing guacamole-common-js
------------------------------------------------------------
guacamole-common-js is built using Maven. Note that this is JavaScript code
and not actually compiled. "Building" guacamole-common-js actually simply
packages it into a redistributable .zip file. This .zip file can be easily
included and expanded into other Maven-based projects (like Guacamole).
Note that prebuilt versions of guacamole-common-js are available from the
main guac-dev.org Maven repository which is referenced in all Maven
projects in Guacamole. Unless you want to make changes to guacamole-common-js
or you want to use a newer, unreleased version (such as the unstable branch),
you do not need to build this manually. You can let Maven download it for
you when you build Guacamole.
1) Run mvn package
$ mvn package
Maven will download any needed dependencies for building the .zip file.
Once all dependencies have been downloaded, the .zip file will be
created in the target/ subdirectory of the current directory.
2) Run mvn install
$ mvn install
DO NOT RUN THIS AS ROOT!
Maven will install guacamole-common-js to your user's local Maven
repository where it can be used in future builds. It will not install
into a system-wide repository and does not require root privileges.
Once installed, building other Maven projects that depend on
guacamole-common-js (such as Guacamole) will be possible.
------------------------------------------------------------
Reporting problems
------------------------------------------------------------
Please report any bugs encountered by opening a new ticket at the Trac system
hosted at:
http://guac-dev.org/trac/

View File

@@ -0,0 +1,32 @@
<!--
<!DOCTYPE keyboard PUBLIC
"-//Guacamole/Guacamole Onscreen Keyboard DTD 0.6.0//EN"
"http://guac-dev.org/pub/dtd/guacamole-osk-0.6.0.dtd">
-->
<!ELEMENT keyboard ((row|column)*)>
<!ATTLIST keyboard size CDATA #REQUIRED>
<!ATTLIST keyboard lang CDATA #REQUIRED>
<!ATTLIST keyboard layout CDATA #REQUIRED>
<!ELEMENT column (row*)>
<!ATTLIST column align (left|center|right) "left">
<!ELEMENT row ((column|gap|key)*)>
<!ELEMENT gap EMPTY>
<!ATTLIST gap size CDATA #IMPLIED>
<!ELEMENT key (cap*)>
<!ATTLIST key size CDATA #IMPLIED>
<!ATTLIST key class CDATA #IMPLIED>
<!ELEMENT cap ANY>
<!ATTLIST cap if CDATA #IMPLIED>
<!ATTLIST cap modifier CDATA #IMPLIED>
<!ATTLIST cap keysym CDATA #IMPLIED>
<!ATTLIST cap sticky (true|false) "false">
<!ATTLIST cap class CDATA #IMPLIED>

View File

@@ -0,0 +1,40 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>net.sourceforge.guacamole</groupId>
<artifactId>guacamole-common-js</artifactId>
<packaging>pom</packaging>
<version>0.7.2</version>
<name>guacamole-common-js</name>
<url>http://guac-dev.org/</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<build>
<plugins>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<descriptors>
<descriptor>static.xml</descriptor>
</descriptors>
</configuration>
<executions>
<execution>
<id>make-zip</id>
<phase>package</phase>
<goals>
<goal>attached</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

View File

@@ -0,0 +1,228 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is guacamole-common-js.
*
* The Initial Developer of the Original Code is
* Michael Jumper.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
/**
* Namespace for all Guacamole JavaScript objects.
* @namespace
*/
var Guacamole = Guacamole || {};
/**
* Abstract audio channel which queues and plays arbitrary audio data.
* @constructor
*/
Guacamole.AudioChannel = function() {
/**
* Reference to this AudioChannel.
* @private
*/
var channel = this;
/**
* When the next packet should play.
* @private
*/
var next_packet_time = 0;
/**
* Queues up the given data for playing by this channel once all previously
* queued data has been played. If no data has been queued, the data will
* play immediately.
*
* @param {String} mimetype The mimetype of the data provided.
* @param {Number} duration The duration of the data provided, in
* milliseconds.
* @param {String} data The base64-encoded data to play.
*/
this.play = function(mimetype, duration, data) {
var packet =
new Guacamole.AudioChannel.Packet(mimetype, data);
var now = Guacamole.AudioChannel.getTimestamp();
// If underflow is detected, reschedule new packets relative to now.
if (next_packet_time < now)
next_packet_time = now;
// Schedule next packet
packet.play(next_packet_time);
next_packet_time += duration;
};
};
// Define context if available
if (window.webkitAudioContext) {
Guacamole.AudioChannel.context = new webkitAudioContext();
}
/**
* Returns a base timestamp which can be used for scheduling future audio
* playback. Scheduling playback for the value returned by this function plus
* N will cause the associated audio to be played back N milliseconds after
* the function is called.
*
* @return {Number} An arbitrary channel-relative timestamp, in milliseconds.
*/
Guacamole.AudioChannel.getTimestamp = function() {
// If we have an audio context, use its timestamp
if (Guacamole.AudioChannel.context)
return Guacamole.AudioChannel.context.currentTime * 1000;
// If we have high-resolution timers, use those
if (window.performance) {
if (window.performance.now)
return window.performance.now();
if (window.performance.webkitNow)
return window.performance.webkitNow();
}
// Fallback to millisecond-resolution system time
return new Date().getTime();
};
/**
* Abstract representation of an audio packet.
*
* @constructor
*
* @param {String} mimetype The mimetype of the data contained by this packet.
* @param {String} data The base64-encoded sound data contained by this packet.
*/
Guacamole.AudioChannel.Packet = function(mimetype, data) {
/**
* Schedules this packet for playback at the given time.
*
* @function
* @param {Number} when The time this packet should be played, in
* milliseconds.
*/
this.play = undefined; // Defined conditionally depending on support
// If audio API available, use it.
if (Guacamole.AudioChannel.context) {
var readyBuffer = null;
// By default, when decoding finishes, store buffer for future
// playback
var handleReady = function(buffer) {
readyBuffer = buffer;
};
// Convert to ArrayBuffer
var binary = window.atob(data);
var arrayBuffer = new ArrayBuffer(binary.length);
var bufferView = new Uint8Array(arrayBuffer);
for (var i=0; i<binary.length; i++)
bufferView[i] = binary.charCodeAt(i);
// Get context and start decoding
Guacamole.AudioChannel.context.decodeAudioData(
arrayBuffer,
function(buffer) { handleReady(buffer); }
);
// Set up buffer source
var source = Guacamole.AudioChannel.context.createBufferSource();
source.connect(Guacamole.AudioChannel.context.destination);
var play_when;
function playDelayed(buffer) {
source.buffer = buffer;
source.noteOn(play_when / 1000);
}
/** @ignore */
this.play = function(when) {
play_when = when;
// If buffer available, play it NOW
if (readyBuffer)
playDelayed(readyBuffer);
// Otherwise, play when decoded
else
handleReady = playDelayed;
};
}
else {
// Build data URI
var data_uri = "data:" + mimetype + ";base64," + data;
// Create audio element to house and play the data
var audio = new Audio();
audio.src = data_uri;
/** @ignore */
this.play = function(when) {
// Calculate time until play
var now = Guacamole.AudioChannel.getTimestamp();
var delay = when - now;
// Play now if too late
if (delay < 0)
audio.play();
// Otherwise, schedule later playback
else
window.setTimeout(function() {
audio.play();
}, delay);
};
}
};

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,622 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is guacamole-common-js.
*
* The Initial Developer of the Original Code is
* Michael Jumper.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
/**
* Namespace for all Guacamole JavaScript objects.
* @namespace
*/
var Guacamole = Guacamole || {};
/**
* Provides cross-browser and cross-keyboard keyboard for a specific element.
* Browser and keyboard layout variation is abstracted away, providing events
* which represent keys as their corresponding X11 keysym.
*
* @constructor
* @param {Element} element The Element to use to provide keyboard events.
*/
Guacamole.Keyboard = function(element) {
/**
* Reference to this Guacamole.Keyboard.
* @private
*/
var guac_keyboard = this;
/**
* Fired whenever the user presses a key with the element associated
* with this Guacamole.Keyboard in focus.
*
* @event
* @param {Number} keysym The keysym of the key being pressed.
*/
this.onkeydown = null;
/**
* Fired whenever the user releases a key with the element associated
* with this Guacamole.Keyboard in focus.
*
* @event
* @param {Number} keysym The keysym of the key being released.
*/
this.onkeyup = null;
/**
* Map of known JavaScript keycodes which do not map to typable characters
* to their unshifted X11 keysym equivalents.
* @private
*/
var unshiftedKeysym = {
8: [0xFF08], // backspace
9: [0xFF09], // tab
13: [0xFF0D], // enter
16: [0xFFE1, 0xFFE1, 0xFFE2], // shift
17: [0xFFE3, 0xFFE3, 0xFFE4], // ctrl
18: [0xFFE9, 0xFFE9, 0xFFEA], // alt
19: [0xFF13], // pause/break
20: [0xFFE5], // caps lock
27: [0xFF1B], // escape
32: [0x0020], // space
33: [0xFF55], // page up
34: [0xFF56], // page down
35: [0xFF57], // end
36: [0xFF50], // home
37: [0xFF51], // left arrow
38: [0xFF52], // up arrow
39: [0xFF53], // right arrow
40: [0xFF54], // down arrow
45: [0xFF63], // insert
46: [0xFFFF], // delete
91: [0xFFEB], // left window key (super_l)
92: [0xFF67], // right window key (menu key?)
93: null, // select key
112: [0xFFBE], // f1
113: [0xFFBF], // f2
114: [0xFFC0], // f3
115: [0xFFC1], // f4
116: [0xFFC2], // f5
117: [0xFFC3], // f6
118: [0xFFC4], // f7
119: [0xFFC5], // f8
120: [0xFFC6], // f9
121: [0xFFC7], // f10
122: [0xFFC8], // f11
123: [0xFFC9], // f12
144: [0xFF7F], // num lock
145: [0xFF14] // scroll lock
};
/**
* Map of known JavaScript keyidentifiers which do not map to typable
* characters to their unshifted X11 keysym equivalents.
* @private
*/
var keyidentifier_keysym = {
"AllCandidates": [0xFF3D],
"Alphanumeric": [0xFF30],
"Alt": [0xFFE9, 0xFFE9, 0xFFEA],
"Attn": [0xFD0E],
"AltGraph": [0xFFEA],
"CapsLock": [0xFFE5],
"Clear": [0xFF0B],
"Convert": [0xFF21],
"Copy": [0xFD15],
"Crsel": [0xFD1C],
"CodeInput": [0xFF37],
"Control": [0xFFE3, 0xFFE3, 0xFFE4],
"Down": [0xFF54],
"End": [0xFF57],
"Enter": [0xFF0D],
"EraseEof": [0xFD06],
"Execute": [0xFF62],
"Exsel": [0xFD1D],
"F1": [0xFFBE],
"F2": [0xFFBF],
"F3": [0xFFC0],
"F4": [0xFFC1],
"F5": [0xFFC2],
"F6": [0xFFC3],
"F7": [0xFFC4],
"F8": [0xFFC5],
"F9": [0xFFC6],
"F10": [0xFFC7],
"F11": [0xFFC8],
"F12": [0xFFC9],
"F13": [0xFFCA],
"F14": [0xFFCB],
"F15": [0xFFCC],
"F16": [0xFFCD],
"F17": [0xFFCE],
"F18": [0xFFCF],
"F19": [0xFFD0],
"F20": [0xFFD1],
"F21": [0xFFD2],
"F22": [0xFFD3],
"F23": [0xFFD4],
"F24": [0xFFD5],
"Find": [0xFF68],
"FullWidth": null,
"HalfWidth": null,
"HangulMode": [0xFF31],
"HanjaMode": [0xFF34],
"Help": [0xFF6A],
"Hiragana": [0xFF25],
"Home": [0xFF50],
"Insert": [0xFF63],
"JapaneseHiragana": [0xFF25],
"JapaneseKatakana": [0xFF26],
"JapaneseRomaji": [0xFF24],
"JunjaMode": [0xFF38],
"KanaMode": [0xFF2D],
"KanjiMode": [0xFF21],
"Katakana": [0xFF26],
"Left": [0xFF51],
"Meta": [0xFFE7],
"NumLock": [0xFF7F],
"PageDown": [0xFF55],
"PageUp": [0xFF56],
"Pause": [0xFF13],
"PreviousCandidate": [0xFF3E],
"PrintScreen": [0xFD1D],
"Right": [0xFF53],
"RomanCharacters": null,
"Scroll": [0xFF14],
"Select": [0xFF60],
"Shift": [0xFFE1, 0xFFE1, 0xFFE2],
"Up": [0xFF52],
"Undo": [0xFF65],
"Win": [0xFFEB]
};
/**
* Map of known JavaScript keycodes which do not map to typable characters
* to their shifted X11 keysym equivalents. Keycodes must only be listed
* here if their shifted X11 keysym equivalents differ from their unshifted
* equivalents.
* @private
*/
var shiftedKeysym = {
18: [0xFFE7, 0xFFE7, 0xFFEA] // alt
};
/**
* All keysyms which should not repeat when held down.
* @private
*/
var no_repeat = {
0xFFE1: true, // Left shift
0xFFE2: true, // Right shift
0xFFE3: true, // Left ctrl
0xFFE4: true, // Right ctrl
0xFFE9: true, // Left alt
0xFFEA: true // Right alt (or AltGr)
};
/**
* All modifiers and their states.
*/
this.modifiers = {
/**
* Whether shift is currently pressed.
*/
"shift": false,
/**
* Whether ctrl is currently pressed.
*/
"ctrl" : false,
/**
* Whether alt is currently pressed.
*/
"alt" : false,
/**
* Whether meta (apple key) is currently pressed.
*/
"meta" : false
};
/**
* The state of every key, indexed by keysym. If a particular key is
* pressed, the value of pressed for that keysym will be true. If a key
* is not currently pressed, it will not be defined.
*/
this.pressed = {};
/**
* The keysym associated with a given keycode when keydown fired.
* @private
*/
var keydownChar = [];
/**
* Timeout before key repeat starts.
* @private
*/
var key_repeat_timeout = null;
/**
* Interval which presses and releases the last key pressed while that
* key is still being held down.
* @private
*/
var key_repeat_interval = null;
/**
* Given an array of keysyms indexed by location, returns the keysym
* for the given location, or the keysym for the standard location if
* undefined.
*
* @param {Array} keysyms An array of keysyms, where the index of the
* keysym in the array is the location value.
* @param {Number} location The location on the keyboard corresponding to
* the key pressed, as defined at:
* http://www.w3.org/TR/DOM-Level-3-Events/#events-KeyboardEvent
*/
function get_keysym(keysyms, location) {
if (!keysyms)
return null;
return keysyms[location] || keysyms[0];
}
function keysym_from_key_identifier(shifted, keyIdentifier, location) {
var unicodePrefixLocation = keyIdentifier.indexOf("U+");
if (unicodePrefixLocation >= 0) {
var hex = keyIdentifier.substring(unicodePrefixLocation+2);
var codepoint = parseInt(hex, 16);
var typedCharacter;
// Convert case if shifted
if (shifted == 0)
typedCharacter = String.fromCharCode(codepoint).toLowerCase();
else
typedCharacter = String.fromCharCode(codepoint).toUpperCase();
// Get codepoint
codepoint = typedCharacter.charCodeAt(0);
return keysym_from_charcode(codepoint);
}
return get_keysym(keyidentifier_keysym[keyIdentifier], location);
}
function isControlCharacter(codepoint) {
return codepoint <= 0x1F || (codepoint >= 0x7F && codepoint <= 0x9F);
}
function keysym_from_charcode(codepoint) {
// Keysyms for control characters
if (isControlCharacter(codepoint)) return 0xFF00 | codepoint;
// Keysyms for ASCII chars
if (codepoint >= 0x0000 && codepoint <= 0x00FF)
return codepoint;
// Keysyms for Unicode
if (codepoint >= 0x0100 && codepoint <= 0x10FFFF)
return 0x01000000 | codepoint;
return null;
}
function keysym_from_keycode(keyCode, location) {
var keysyms;
// If not shifted, just return unshifted keysym
if (!guac_keyboard.modifiers.shift)
keysyms = unshiftedKeysym[keyCode];
// Otherwise, return shifted keysym, if defined
else
keysyms = shiftedKeysym[keyCode] || unshiftedKeysym[keyCode];
return get_keysym(keysyms, location);
}
/**
* Marks a key as pressed, firing the keydown event if registered. Key
* repeat for the pressed key will start after a delay if that key is
* not a modifier.
* @private
*/
function press_key(keysym) {
// Don't bother with pressing the key if the key is unknown
if (keysym == null) return;
// Only press if released
if (!guac_keyboard.pressed[keysym]) {
// Mark key as pressed
guac_keyboard.pressed[keysym] = true;
// Send key event
if (guac_keyboard.onkeydown) {
guac_keyboard.onkeydown(keysym);
// Stop any current repeat
window.clearTimeout(key_repeat_timeout);
window.clearInterval(key_repeat_interval);
// Repeat after a delay as long as pressed
if (!no_repeat[keysym])
key_repeat_timeout = window.setTimeout(function() {
key_repeat_interval = window.setInterval(function() {
guac_keyboard.onkeyup(keysym);
guac_keyboard.onkeydown(keysym);
}, 50);
}, 500);
}
}
}
/**
* Marks a key as released, firing the keyup event if registered.
* @private
*/
function release_key(keysym) {
// Only release if pressed
if (guac_keyboard.pressed[keysym]) {
// Mark key as released
delete guac_keyboard.pressed[keysym];
// Stop repeat
window.clearTimeout(key_repeat_timeout);
window.clearInterval(key_repeat_interval);
// Send key event
if (keysym != null && guac_keyboard.onkeyup)
guac_keyboard.onkeyup(keysym);
}
}
function isTypable(keyIdentifier) {
// Find unicode prefix
var unicodePrefixLocation = keyIdentifier.indexOf("U+");
if (unicodePrefixLocation == -1)
return false;
// Parse codepoint value
var hex = keyIdentifier.substring(unicodePrefixLocation+2);
var codepoint = parseInt(hex, 16);
// If control character, not typable
if (isControlCharacter(codepoint)) return false;
// Otherwise, typable
return true;
}
/**
* Given a keyboard event, updates the local modifier state and remote
* key state based on the modifier flags within the event. This function
* pays no attention to keycodes.
*
* @param {KeyboardEvent} e The keyboard event containing the flags to update.
*/
function update_modifier_state(e) {
// Release alt if implicitly released
if (guac_keyboard.modifiers.alt && e.altKey === false) {
release_key(0xFFE9); // Left alt
release_key(0xFFEA); // Right alt (or AltGr)
guac_keyboard.modifiers.alt = false;
}
// Release shift if implicitly released
if (guac_keyboard.modifiers.shift && e.shiftKey === false) {
release_key(0xFFE1); // Left shift
release_key(0xFFE2); // Right shift
guac_keyboard.modifiers.shift = false;
}
// Release ctrl if implicitly released
if (guac_keyboard.modifiers.ctrl && e.ctrlKey === false) {
release_key(0xFFE3); // Left ctrl
release_key(0xFFE4); // Right ctrl
guac_keyboard.modifiers.ctrl = false;
}
}
// When key pressed
element.addEventListener("keydown", function(e) {
// Only intercept if handler set
if (!guac_keyboard.onkeydown) return;
var keynum;
if (window.event) keynum = window.event.keyCode;
else if (e.which) keynum = e.which;
// Get key location
var location = e.location || e.keyLocation || 0;
// Ignore any unknown key events
if (keynum == 0 && !e.keyIdentifier) {
e.preventDefault();
return;
}
// Fix modifier states
update_modifier_state(e);
// Ctrl/Alt/Shift/Meta
if (keynum == 16) guac_keyboard.modifiers.shift = true;
else if (keynum == 17) guac_keyboard.modifiers.ctrl = true;
else if (keynum == 18) guac_keyboard.modifiers.alt = true;
else if (keynum == 91) guac_keyboard.modifiers.meta = true;
// Try to get keysym from keycode
var keysym = keysym_from_keycode(keynum, location);
// By default, we expect a corresponding keypress event
var expect_keypress = true;
// If key is known from keycode, prevent default
if (keysym)
expect_keypress = false;
// Also try to get get keysym from keyIdentifier
if (e.keyIdentifier) {
keysym = keysym ||
keysym_from_key_identifier(guac_keyboard.modifiers.shift,
e.keyIdentifier, location);
// Prevent default if non-typable character or if modifier combination
// likely to be eaten by browser otherwise (NOTE: We must not prevent
// default for Ctrl+Alt, as that combination is commonly used for
// AltGr. If we receive AltGr, we need to handle keypress, which
// means we cannot cancel keydown).
if (!isTypable(e.keyIdentifier)
|| ( guac_keyboard.modifiers.ctrl && !guac_keyboard.modifiers.alt)
|| (!guac_keyboard.modifiers.ctrl && guac_keyboard.modifiers.alt)
|| (guac_keyboard.modifiers.meta))
expect_keypress = false;
}
// If we do not expect to handle via keypress, handle now
if (!expect_keypress) {
e.preventDefault();
// Press key if known
if (keysym != null) {
keydownChar[keynum] = keysym;
press_key(keysym);
// If a key is pressed while meta is held down, the keyup will never be sent in Chrome, so send it now. (bug #108404)
if(guac_keyboard.modifiers.meta) {
release_key(keysym);
}
}
}
}, true);
// When key pressed
element.addEventListener("keypress", function(e) {
// Only intercept if handler set
if (!guac_keyboard.onkeydown && !guac_keyboard.onkeyup) return;
e.preventDefault();
var keynum;
if (window.event) keynum = window.event.keyCode;
else if (e.which) keynum = e.which;
var keysym = keysym_from_charcode(keynum);
// Fix modifier states
update_modifier_state(e);
// If event identified as a typable character, and we're holding Ctrl+Alt,
// assume Ctrl+Alt is actually AltGr, and release both.
if (!isControlCharacter(keynum) && guac_keyboard.modifiers.ctrl && guac_keyboard.modifiers.alt) {
release_key(0xFFE3); // Left ctrl
release_key(0xFFE4); // Right ctrl
release_key(0xFFE9); // Left alt
release_key(0xFFEA); // Right alt
}
// Send press + release if keysym known
if (keysym != null) {
press_key(keysym);
release_key(keysym);
}
}, true);
// When key released
element.addEventListener("keyup", function(e) {
// Only intercept if handler set
if (!guac_keyboard.onkeyup) return;
e.preventDefault();
var keynum;
if (window.event) keynum = window.event.keyCode;
else if (e.which) keynum = e.which;
// Fix modifier states
update_modifier_state(e);
// Ctrl/Alt/Shift/Meta
if (keynum == 16) guac_keyboard.modifiers.shift = false;
else if (keynum == 17) guac_keyboard.modifiers.ctrl = false;
else if (keynum == 18) guac_keyboard.modifiers.alt = false;
else if (keynum == 91) guac_keyboard.modifiers.meta = false;
// Send release event if original key known
var keydown_keysym = keydownChar[keynum];
if (keydown_keysym != null)
release_key(keydown_keysym);
// Clear character record
keydownChar[keynum] = null;
}, true);
};

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,785 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is guacamole-common-js.
*
* The Initial Developer of the Original Code is
* Michael Jumper.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
/**
* Namespace for all Guacamole JavaScript objects.
* @namespace
*/
var Guacamole = Guacamole || {};
/**
* Provides cross-browser mouse events for a given element. The events of
* the given element are automatically populated with handlers that translate
* mouse events into a non-browser-specific event provided by the
* Guacamole.Mouse instance.
*
* @constructor
* @param {Element} element The Element to use to provide mouse events.
*/
Guacamole.Mouse = function(element) {
/**
* Reference to this Guacamole.Mouse.
* @private
*/
var guac_mouse = this;
/**
* The number of mousemove events to require before re-enabling mouse
* event handling after receiving a touch event.
*/
this.touchMouseThreshold = 3;
/**
* The current mouse state. The properties of this state are updated when
* mouse events fire. This state object is also passed in as a parameter to
* the handler of any mouse events.
*
* @type Guacamole.Mouse.State
*/
this.currentState = new Guacamole.Mouse.State(
0, 0,
false, false, false, false, false
);
/**
* Fired whenever the user presses a mouse button down over the element
* associated with this Guacamole.Mouse.
*
* @event
* @param {Guacamole.Mouse.State} state The current mouse state.
*/
this.onmousedown = null;
/**
* Fired whenever the user releases a mouse button down over the element
* associated with this Guacamole.Mouse.
*
* @event
* @param {Guacamole.Mouse.State} state The current mouse state.
*/
this.onmouseup = null;
/**
* Fired whenever the user moves the mouse over the element associated with
* this Guacamole.Mouse.
*
* @event
* @param {Guacamole.Mouse.State} state The current mouse state.
*/
this.onmousemove = null;
/**
* Counter of mouse events to ignore. This decremented by mousemove, and
* while non-zero, mouse events will have no effect.
* @private
*/
var ignore_mouse = 0;
function cancelEvent(e) {
e.stopPropagation();
if (e.preventDefault) e.preventDefault();
e.returnValue = false;
}
// Block context menu so right-click gets sent properly
element.addEventListener("contextmenu", function(e) {
cancelEvent(e);
}, false);
element.addEventListener("mousemove", function(e) {
cancelEvent(e);
// If ignoring events, decrement counter
if (ignore_mouse) {
ignore_mouse--;
return;
}
guac_mouse.currentState.fromClientPosition(element, e.clientX, e.clientY);
if (guac_mouse.onmousemove)
guac_mouse.onmousemove(guac_mouse.currentState);
}, false);
element.addEventListener("mousedown", function(e) {
cancelEvent(e);
// Do not handle if ignoring events
if (ignore_mouse)
return;
switch (e.button) {
case 0:
guac_mouse.currentState.left = true;
break;
case 1:
guac_mouse.currentState.middle = true;
break;
case 2:
guac_mouse.currentState.right = true;
break;
}
if (guac_mouse.onmousedown)
guac_mouse.onmousedown(guac_mouse.currentState);
}, false);
element.addEventListener("mouseup", function(e) {
cancelEvent(e);
// Do not handle if ignoring events
if (ignore_mouse)
return;
switch (e.button) {
case 0:
guac_mouse.currentState.left = false;
break;
case 1:
guac_mouse.currentState.middle = false;
break;
case 2:
guac_mouse.currentState.right = false;
break;
}
if (guac_mouse.onmouseup)
guac_mouse.onmouseup(guac_mouse.currentState);
}, false);
element.addEventListener("mouseout", function(e) {
// Get parent of the element the mouse pointer is leaving
if (!e) e = window.event;
// Check that mouseout is due to actually LEAVING the element
var target = e.relatedTarget || e.toElement;
while (target != null) {
if (target === element)
return;
target = target.parentNode;
}
cancelEvent(e);
// Release all buttons
if (guac_mouse.currentState.left
|| guac_mouse.currentState.middle
|| guac_mouse.currentState.right) {
guac_mouse.currentState.left = false;
guac_mouse.currentState.middle = false;
guac_mouse.currentState.right = false;
if (guac_mouse.onmouseup)
guac_mouse.onmouseup(guac_mouse.currentState);
}
}, false);
// Override selection on mouse event element.
element.addEventListener("selectstart", function(e) {
cancelEvent(e);
}, false);
// Ignore all pending mouse events when touch events are the apparent source
function ignorePendingMouseEvents() { ignore_mouse = guac_mouse.touchMouseThreshold; }
element.addEventListener("touchmove", ignorePendingMouseEvents, false);
element.addEventListener("touchstart", ignorePendingMouseEvents, false);
element.addEventListener("touchend", ignorePendingMouseEvents, false);
// Scroll wheel support
function mousewheel_handler(e) {
var delta = 0;
if (e.detail)
delta = e.detail;
else if (e.wheelDelta)
delta = -event.wheelDelta;
// Up
if (delta < 0) {
if (guac_mouse.onmousedown) {
guac_mouse.currentState.up = true;
guac_mouse.onmousedown(guac_mouse.currentState);
}
if (guac_mouse.onmouseup) {
guac_mouse.currentState.up = false;
guac_mouse.onmouseup(guac_mouse.currentState);
}
}
// Down
if (delta > 0) {
if (guac_mouse.onmousedown) {
guac_mouse.currentState.down = true;
guac_mouse.onmousedown(guac_mouse.currentState);
}
if (guac_mouse.onmouseup) {
guac_mouse.currentState.down = false;
guac_mouse.onmouseup(guac_mouse.currentState);
}
}
cancelEvent(e);
}
element.addEventListener('DOMMouseScroll', mousewheel_handler, false);
element.addEventListener('mousewheel', mousewheel_handler, false);
};
/**
* Provides cross-browser relative touch event translation for a given element.
*
* Touch events are translated into mouse events as if the touches occurred
* on a touchpad (drag to push the mouse pointer, tap to click).
*
* @constructor
* @param {Element} element The Element to use to provide touch events.
*/
Guacamole.Mouse.Touchpad = function(element) {
/**
* Reference to this Guacamole.Mouse.Touchpad.
* @private
*/
var guac_touchpad = this;
/**
* The distance a two-finger touch must move per scrollwheel event, in
* pixels.
*/
this.scrollThreshold = 20 * (window.devicePixelRatio || 1);
/**
* The maximum number of milliseconds to wait for a touch to end for the
* gesture to be considered a click.
*/
this.clickTimingThreshold = 250;
/**
* The maximum number of pixels to allow a touch to move for the gesture to
* be considered a click.
*/
this.clickMoveThreshold = 10 * (window.devicePixelRatio || 1);
/**
* The current mouse state. The properties of this state are updated when
* mouse events fire. This state object is also passed in as a parameter to
* the handler of any mouse events.
*
* @type Guacamole.Mouse.State
*/
this.currentState = new Guacamole.Mouse.State(
0, 0,
false, false, false, false, false
);
/**
* Fired whenever a mouse button is effectively pressed. This can happen
* as part of a "click" gesture initiated by the user by tapping one
* or more fingers over the touchpad element, as part of a "scroll"
* gesture initiated by dragging two fingers up or down, etc.
*
* @event
* @param {Guacamole.Mouse.State} state The current mouse state.
*/
this.onmousedown = null;
/**
* Fired whenever a mouse button is effectively released. This can happen
* as part of a "click" gesture initiated by the user by tapping one
* or more fingers over the touchpad element, as part of a "scroll"
* gesture initiated by dragging two fingers up or down, etc.
*
* @event
* @param {Guacamole.Mouse.State} state The current mouse state.
*/
this.onmouseup = null;
/**
* Fired whenever the user moves the mouse by dragging their finger over
* the touchpad element.
*
* @event
* @param {Guacamole.Mouse.State} state The current mouse state.
*/
this.onmousemove = null;
var touch_count = 0;
var last_touch_x = 0;
var last_touch_y = 0;
var last_touch_time = 0;
var pixels_moved = 0;
var touch_buttons = {
1: "left",
2: "right",
3: "middle"
};
var gesture_in_progress = false;
var click_release_timeout = null;
element.addEventListener("touchend", function(e) {
e.stopPropagation();
e.preventDefault();
// If we're handling a gesture AND this is the last touch
if (gesture_in_progress && e.touches.length == 0) {
var time = new Date().getTime();
// Get corresponding mouse button
var button = touch_buttons[touch_count];
// If mouse already down, release anad clear timeout
if (guac_touchpad.currentState[button]) {
// Fire button up event
guac_touchpad.currentState[button] = false;
if (guac_touchpad.onmouseup)
guac_touchpad.onmouseup(guac_touchpad.currentState);
// Clear timeout, if set
if (click_release_timeout) {
window.clearTimeout(click_release_timeout);
click_release_timeout = null;
}
}
// If single tap detected (based on time and distance)
if (time - last_touch_time <= guac_touchpad.clickTimingThreshold
&& pixels_moved < guac_touchpad.clickMoveThreshold) {
// Fire button down event
guac_touchpad.currentState[button] = true;
if (guac_touchpad.onmousedown)
guac_touchpad.onmousedown(guac_touchpad.currentState);
// Delay mouse up - mouse up should be canceled if
// touchstart within timeout.
click_release_timeout = window.setTimeout(function() {
// Fire button up event
guac_touchpad.currentState[button] = false;
if (guac_touchpad.onmouseup)
guac_touchpad.onmouseup(guac_touchpad.currentState);
// Gesture now over
gesture_in_progress = false;
}, guac_touchpad.clickTimingThreshold);
}
// If we're not waiting to see if this is a click, stop gesture
if (!click_release_timeout)
gesture_in_progress = false;
}
}, false);
element.addEventListener("touchstart", function(e) {
e.stopPropagation();
e.preventDefault();
// Track number of touches, but no more than three
touch_count = Math.min(e.touches.length, 3);
// Clear timeout, if set
if (click_release_timeout) {
window.clearTimeout(click_release_timeout);
click_release_timeout = null;
}
// Record initial touch location and time for touch movement
// and tap gestures
if (!gesture_in_progress) {
// Stop mouse events while touching
gesture_in_progress = true;
// Record touch location and time
var starting_touch = e.touches[0];
last_touch_x = starting_touch.clientX;
last_touch_y = starting_touch.clientY;
last_touch_time = new Date().getTime();
pixels_moved = 0;
}
}, false);
element.addEventListener("touchmove", function(e) {
e.stopPropagation();
e.preventDefault();
// Get change in touch location
var touch = e.touches[0];
var delta_x = touch.clientX - last_touch_x;
var delta_y = touch.clientY - last_touch_y;
// Track pixels moved
pixels_moved += Math.abs(delta_x) + Math.abs(delta_y);
// If only one touch involved, this is mouse move
if (touch_count == 1) {
// Calculate average velocity in Manhatten pixels per millisecond
var velocity = pixels_moved / (new Date().getTime() - last_touch_time);
// Scale mouse movement relative to velocity
var scale = 1 + velocity;
// Update mouse location
guac_touchpad.currentState.x += delta_x*scale;
guac_touchpad.currentState.y += delta_y*scale;
// Prevent mouse from leaving screen
if (guac_touchpad.currentState.x < 0)
guac_touchpad.currentState.x = 0;
else if (guac_touchpad.currentState.x >= element.offsetWidth)
guac_touchpad.currentState.x = element.offsetWidth - 1;
if (guac_touchpad.currentState.y < 0)
guac_touchpad.currentState.y = 0;
else if (guac_touchpad.currentState.y >= element.offsetHeight)
guac_touchpad.currentState.y = element.offsetHeight - 1;
// Fire movement event, if defined
if (guac_touchpad.onmousemove)
guac_touchpad.onmousemove(guac_touchpad.currentState);
// Update touch location
last_touch_x = touch.clientX;
last_touch_y = touch.clientY;
}
// Interpret two-finger swipe as scrollwheel
else if (touch_count == 2) {
// If change in location passes threshold for scroll
if (Math.abs(delta_y) >= guac_touchpad.scrollThreshold) {
// Decide button based on Y movement direction
var button;
if (delta_y > 0) button = "down";
else button = "up";
// Fire button down event
guac_touchpad.currentState[button] = true;
if (guac_touchpad.onmousedown)
guac_touchpad.onmousedown(guac_touchpad.currentState);
// Fire button up event
guac_touchpad.currentState[button] = false;
if (guac_touchpad.onmouseup)
guac_touchpad.onmouseup(guac_touchpad.currentState);
// Only update touch location after a scroll has been
// detected
last_touch_x = touch.clientX;
last_touch_y = touch.clientY;
}
}
}, false);
};
/**
* Provides cross-browser absolute touch event translation for a given element.
*
* Touch events are translated into mouse events as if the touches occurred
* on a touchscreen (tapping anywhere on the screen clicks at that point,
* long-press to right-click).
*
* @constructor
* @param {Element} element The Element to use to provide touch events.
*/
Guacamole.Mouse.Touchscreen = function(element) {
/**
* Reference to this Guacamole.Mouse.Touchscreen.
* @private
*/
var guac_touchscreen = this;
/**
* The distance a two-finger touch must move per scrollwheel event, in
* pixels.
*/
this.scrollThreshold = 20 * (window.devicePixelRatio || 1);
/**
* The current mouse state. The properties of this state are updated when
* mouse events fire. This state object is also passed in as a parameter to
* the handler of any mouse events.
*
* @type Guacamole.Mouse.State
*/
this.currentState = new Guacamole.Mouse.State(
0, 0,
false, false, false, false, false
);
/**
* Fired whenever a mouse button is effectively pressed. This can happen
* as part of a "mousedown" gesture initiated by the user by pressing one
* finger over the touchscreen element, as part of a "scroll" gesture
* initiated by dragging two fingers up or down, etc.
*
* @event
* @param {Guacamole.Mouse.State} state The current mouse state.
*/
this.onmousedown = null;
/**
* Fired whenever a mouse button is effectively released. This can happen
* as part of a "mouseup" gesture initiated by the user by removing the
* finger pressed against the touchscreen element, or as part of a "scroll"
* gesture initiated by dragging two fingers up or down, etc.
*
* @event
* @param {Guacamole.Mouse.State} state The current mouse state.
*/
this.onmouseup = null;
/**
* Fired whenever the user moves the mouse by dragging their finger over
* the touchscreen element. Note that unlike Guacamole.Mouse.Touchpad,
* dragging a finger over the touchscreen element will always cause
* the mouse button to be effectively down, as if clicking-and-dragging.
*
* @event
* @param {Guacamole.Mouse.State} state The current mouse state.
*/
this.onmousemove = null;
element.addEventListener("touchend", function(e) {
// Ignore if more than one touch
if (e.touches.length + e.changedTouches.length != 1)
return;
e.stopPropagation();
e.preventDefault();
// Release button
guac_touchscreen.currentState.left = false;
// Fire release event when the last touch is released, if event defined
if (e.touches.length == 0 && guac_touchscreen.onmouseup)
guac_touchscreen.onmouseup(guac_touchscreen.currentState);
}, false);
element.addEventListener("touchstart", function(e) {
// Ignore if more than one touch
if (e.touches.length != 1)
return;
e.stopPropagation();
e.preventDefault();
// Get touch
var touch = e.touches[0];
// Update state
guac_touchscreen.currentState.left = true;
guac_touchscreen.currentState.fromClientPosition(element, touch.clientX, touch.clientY);
// Fire press event, if defined
if (guac_touchscreen.onmousedown)
guac_touchscreen.onmousedown(guac_touchscreen.currentState);
}, false);
element.addEventListener("touchmove", function(e) {
// Ignore if more than one touch
if (e.touches.length != 1)
return;
e.stopPropagation();
e.preventDefault();
// Get touch
var touch = e.touches[0];
// Update state
guac_touchscreen.currentState.fromClientPosition(element, touch.clientX, touch.clientY);
// Fire movement event, if defined
if (guac_touchscreen.onmousemove)
guac_touchscreen.onmousemove(guac_touchscreen.currentState);
}, false);
};
/**
* Simple container for properties describing the state of a mouse.
*
* @constructor
* @param {Number} x The X position of the mouse pointer in pixels.
* @param {Number} y The Y position of the mouse pointer in pixels.
* @param {Boolean} left Whether the left mouse button is pressed.
* @param {Boolean} middle Whether the middle mouse button is pressed.
* @param {Boolean} right Whether the right mouse button is pressed.
* @param {Boolean} up Whether the up mouse button is pressed (the fourth
* button, usually part of a scroll wheel).
* @param {Boolean} down Whether the down mouse button is pressed (the fifth
* button, usually part of a scroll wheel).
*/
Guacamole.Mouse.State = function(x, y, left, middle, right, up, down) {
/**
* Reference to this Guacamole.Mouse.State.
* @private
*/
var guac_state = this;
/**
* The current X position of the mouse pointer.
* @type Number
*/
this.x = x;
/**
* The current Y position of the mouse pointer.
* @type Number
*/
this.y = y;
/**
* Whether the left mouse button is currently pressed.
* @type Boolean
*/
this.left = left;
/**
* Whether the middle mouse button is currently pressed.
* @type Boolean
*/
this.middle = middle
/**
* Whether the right mouse button is currently pressed.
* @type Boolean
*/
this.right = right;
/**
* Whether the up mouse button is currently pressed. This is the fourth
* mouse button, associated with upward scrolling of the mouse scroll
* wheel.
* @type Boolean
*/
this.up = up;
/**
* Whether the down mouse button is currently pressed. This is the fifth
* mouse button, associated with downward scrolling of the mouse scroll
* wheel.
* @type Boolean
*/
this.down = down;
/**
* Updates the position represented within this state object by the given
* element and clientX/clientY coordinates (commonly available within event
* objects). Position is translated from clientX/clientY (relative to
* viewport) to element-relative coordinates.
*
* @param {Element} element The element the coordinates should be relative
* to.
* @param {Number} clientX The X coordinate to translate, viewport-relative.
* @param {Number} clientY The Y coordinate to translate, viewport-relative.
*/
this.fromClientPosition = function(element, clientX, clientY) {
guac_state.x = clientX - element.offsetLeft;
guac_state.y = clientY - element.offsetTop;
// This is all JUST so we can get the mouse position within the element
var parent = element.offsetParent;
while (parent && !(parent === document.body)) {
guac_state.x -= parent.offsetLeft - parent.scrollLeft;
guac_state.y -= parent.offsetTop - parent.scrollTop;
parent = parent.offsetParent;
}
// Element ultimately depends on positioning within document body,
// take document scroll into account.
if (parent) {
var documentScrollLeft = document.body.scrollLeft || document.documentElement.scrollLeft;
var documentScrollTop = document.body.scrollTop || document.documentElement.scrollTop;
guac_state.x -= parent.offsetLeft - documentScrollLeft;
guac_state.y -= parent.offsetTop - documentScrollTop;
}
};
};

View File

@@ -0,0 +1,653 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is guac-common-js.
*
* The Initial Developer of the Original Code is
* Michael Jumper.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
/**
* Namespace for all Guacamole JavaScript objects.
* @namespace
*/
var Guacamole = Guacamole || {};
/**
* Dynamic on-screen keyboard. Given the URL to an XML keyboard layout file,
* this object will download and use the XML to construct a clickable on-screen
* keyboard with its own key events.
*
* @constructor
* @param {String} url The URL of an XML keyboard layout file.
*/
Guacamole.OnScreenKeyboard = function(url) {
var on_screen_keyboard = this;
/**
* State of all modifiers. This is the bitwise OR of all active modifier
* values.
*
* @private
*/
var modifiers = 0;
var scaledElements = [];
var modifier_masks = {};
var next_mask = 1;
/**
* Adds a class to an element.
*
* @private
* @function
* @param {Element} element The element to add a class to.
* @param {String} classname The name of the class to add.
*/
var addClass;
/**
* Removes a class from an element.
*
* @private
* @function
* @param {Element} element The element to remove a class from.
* @param {String} classname The name of the class to remove.
*/
var removeClass;
/**
* The number of mousemove events to require before re-enabling mouse
* event handling after receiving a touch event.
*/
this.touchMouseThreshold = 3;
/**
* Counter of mouse events to ignore. This decremented by mousemove, and
* while non-zero, mouse events will have no effect.
* @private
*/
var ignore_mouse = 0;
// Ignore all pending mouse events when touch events are the apparent source
function ignorePendingMouseEvents() { ignore_mouse = on_screen_keyboard.touchMouseThreshold; }
// If Node.classList is supported, implement addClass/removeClass using that
if (Node.classList) {
/** @ignore */
addClass = function(element, classname) {
element.classList.add(classname);
};
/** @ignore */
removeClass = function(element, classname) {
element.classList.remove(classname);
};
}
// Otherwise, implement own
else {
/** @ignore */
addClass = function(element, classname) {
// Simply add new class
element.className += " " + classname;
};
/** @ignore */
removeClass = function(element, classname) {
// Filter out classes with given name
element.className = element.className.replace(/([^ ]+)[ ]*/g,
function(match, testClassname, spaces, offset, string) {
// If same class, remove
if (testClassname == classname)
return "";
// Otherwise, allow
return match;
}
);
};
}
// Returns a unique power-of-two value for the modifier with the
// given name. The same value will be returned for the same modifier.
function getModifierMask(name) {
var value = modifier_masks[name];
if (!value) {
// Get current modifier, advance to next
value = next_mask;
next_mask <<= 1;
// Store value of this modifier
modifier_masks[name] = value;
}
return value;
}
function ScaledElement(element, width, height, scaleFont) {
this.width = width;
this.height = height;
this.scale = function(pixels) {
element.style.width = (width * pixels) + "px";
element.style.height = (height * pixels) + "px";
if (scaleFont) {
element.style.lineHeight = (height * pixels) + "px";
element.style.fontSize = pixels + "px";
}
}
}
// For each child of element, call handler defined in next
function parseChildren(element, next) {
var children = element.childNodes;
for (var i=0; i<children.length; i++) {
// Get child node
var child = children[i];
// Do not parse text nodes
if (!child.tagName)
continue;
// Get handler for node
var handler = next[child.tagName];
// Call handler if defined
if (handler)
handler(child);
// Throw exception if no handler
else
throw new Error(
"Unexpected " + child.tagName
+ " within " + element.tagName
);
}
}
// Create keyboard
var keyboard = document.createElement("div");
keyboard.className = "guac-keyboard";
// Retrieve keyboard XML
var xmlhttprequest = new XMLHttpRequest();
xmlhttprequest.open("GET", url, false);
xmlhttprequest.send(null);
var xml = xmlhttprequest.responseXML;
if (xml) {
function parse_row(e) {
var row = document.createElement("div");
row.className = "guac-keyboard-row";
parseChildren(e, {
"column": function(e) {
row.appendChild(parse_column(e));
},
"gap": function parse_gap(e) {
// Create element
var gap = document.createElement("div");
gap.className = "guac-keyboard-gap";
// Set gap size
var gap_units = 1;
if (e.getAttribute("size"))
gap_units = parseFloat(e.getAttribute("size"));
scaledElements.push(new ScaledElement(gap, gap_units, gap_units));
row.appendChild(gap);
},
"key": function parse_key(e) {
// Create element
var key_element = document.createElement("div");
key_element.className = "guac-keyboard-key";
// Append class if specified
if (e.getAttribute("class"))
key_element.className += " " + e.getAttribute("class");
// Position keys using container div
var key_container_element = document.createElement("div");
key_container_element.className = "guac-keyboard-key-container";
key_container_element.appendChild(key_element);
// Create key
var key = new Guacamole.OnScreenKeyboard.Key();
// Set key size
var key_units = 1;
if (e.getAttribute("size"))
key_units = parseFloat(e.getAttribute("size"));
key.size = key_units;
parseChildren(e, {
"cap": function parse_cap(e) {
// TODO: Handle "sticky" attribute
// Get content of key cap
var content = e.textContent || e.text;
// If read as blank, assume cap is a single space.
if (content.length == 0)
content = " ";
// Get keysym
var real_keysym = null;
if (e.getAttribute("keysym"))
real_keysym = parseInt(e.getAttribute("keysym"));
// If no keysym specified, try to get from key content
else if (content.length == 1) {
var charCode = content.charCodeAt(0);
if (charCode >= 0x0000 && charCode <= 0x00FF)
real_keysym = charCode;
else if (charCode >= 0x0100 && charCode <= 0x10FFFF)
real_keysym = 0x01000000 | charCode;
}
// Create cap
var cap = new Guacamole.OnScreenKeyboard.Cap(content, real_keysym);
if (e.getAttribute("modifier"))
cap.modifier = e.getAttribute("modifier");
// Create cap element
var cap_element = document.createElement("div");
cap_element.className = "guac-keyboard-cap";
cap_element.textContent = content;
key_element.appendChild(cap_element);
// Append class if specified
if (e.getAttribute("class"))
cap_element.className += " " + e.getAttribute("class");
// Get modifier value
var modifierValue = 0;
if (e.getAttribute("if")) {
// Get modifier value for specified comma-delimited
// list of required modifiers.
var requirements = e.getAttribute("if").split(",");
for (var i=0; i<requirements.length; i++) {
modifierValue |= getModifierMask(requirements[i]);
addClass(cap_element, "guac-keyboard-requires-" + requirements[i]);
addClass(key_element, "guac-keyboard-uses-" + requirements[i]);
}
}
// Store cap
key.modifierMask |= modifierValue;
key.caps[modifierValue] = cap;
}
});
scaledElements.push(new ScaledElement(key_container_element, key_units, 1, true));
row.appendChild(key_container_element);
// Set up click handler for key
function press() {
// Press key if not yet pressed
if (!key.pressed) {
addClass(key_element, "guac-keyboard-pressed");
// Get current cap based on modifier state
var cap = key.getCap(modifiers);
// Update modifier state
if (cap.modifier) {
// Construct classname for modifier
var modifierClass = "guac-keyboard-modifier-" + cap.modifier;
var modifierMask = getModifierMask(cap.modifier);
// Toggle modifier state
modifiers ^= modifierMask;
// Activate modifier if pressed
if (modifiers & modifierMask) {
addClass(keyboard, modifierClass);
// Send key event
if (on_screen_keyboard.onkeydown && cap.keysym)
on_screen_keyboard.onkeydown(cap.keysym);
}
// Deactivate if not pressed
else {
removeClass(keyboard, modifierClass);
// Send key event
if (on_screen_keyboard.onkeyup && cap.keysym)
on_screen_keyboard.onkeyup(cap.keysym);
}
}
// If not modifier, send key event now
else if (on_screen_keyboard.onkeydown && cap.keysym)
on_screen_keyboard.onkeydown(cap.keysym);
// Mark key as pressed
key.pressed = true;
}
}
function release() {
// Release key if currently pressed
if (key.pressed) {
// Get current cap based on modifier state
var cap = key.getCap(modifiers);
removeClass(key_element, "guac-keyboard-pressed");
// Send key event if not a modifier key
if (!cap.modifier && on_screen_keyboard.onkeyup && cap.keysym)
on_screen_keyboard.onkeyup(cap.keysym);
// Mark key as released
key.pressed = false;
}
}
function touchPress(e) {
e.preventDefault();
ignore_mouse = on_screen_keyboard.touchMouseThreshold;
press();
}
function touchRelease(e) {
e.preventDefault();
ignore_mouse = on_screen_keyboard.touchMouseThreshold;
release();
}
function mousePress(e) {
e.preventDefault();
if (ignore_mouse == 0)
press();
}
function mouseRelease(e) {
e.preventDefault();
if (ignore_mouse == 0)
release();
}
key_element.addEventListener("touchstart", touchPress, true);
key_element.addEventListener("touchend", touchRelease, true);
key_element.addEventListener("mousedown", mousePress, true);
key_element.addEventListener("mouseup", mouseRelease, true);
key_element.addEventListener("mouseout", mouseRelease, true);
}
});
return row;
}
function parse_column(e) {
var col = document.createElement("div");
col.className = "guac-keyboard-column";
if (col.getAttribute("align"))
col.style.textAlign = col.getAttribute("align");
// Columns can only contain rows
parseChildren(e, {
"row": function(e) {
col.appendChild(parse_row(e));
}
});
return col;
}
// Parse document
var keyboard_element = xml.documentElement;
if (keyboard_element.tagName != "keyboard")
throw new Error("Root element must be keyboard");
// Get attributes
if (!keyboard_element.getAttribute("size"))
throw new Error("size attribute is required for keyboard");
var keyboard_size = parseFloat(keyboard_element.getAttribute("size"));
parseChildren(keyboard_element, {
"row": function(e) {
keyboard.appendChild(parse_row(e));
},
"column": function(e) {
keyboard.appendChild(parse_column(e));
}
});
}
// Do not allow selection or mouse movement to propagate/register.
keyboard.onselectstart =
keyboard.onmousemove =
keyboard.onmouseup =
keyboard.onmousedown =
function(e) {
// If ignoring events, decrement counter
if (ignore_mouse)
ignore_mouse--;
e.stopPropagation();
return false;
};
/**
* Fired whenever the user presses a key on this Guacamole.OnScreenKeyboard.
*
* @event
* @param {Number} keysym The keysym of the key being pressed.
*/
this.onkeydown = null;
/**
* Fired whenever the user releases a key on this Guacamole.OnScreenKeyboard.
*
* @event
* @param {Number} keysym The keysym of the key being released.
*/
this.onkeyup = null;
/**
* Returns the element containing the entire on-screen keyboard.
* @returns {Element} The element containing the entire on-screen keyboard.
*/
this.getElement = function() {
return keyboard;
};
/**
* Resizes all elements within this Guacamole.OnScreenKeyboard such that
* the width is close to but does not exceed the specified width. The
* height of the keyboard is determined based on the width.
*
* @param {Number} width The width to resize this Guacamole.OnScreenKeyboard
* to, in pixels.
*/
this.resize = function(width) {
// Get pixel size of a unit
var unit = Math.floor(width * 10 / keyboard_size) / 10;
// Resize all scaled elements
for (var i=0; i<scaledElements.length; i++) {
var scaledElement = scaledElements[i];
scaledElement.scale(unit)
}
};
};
/**
* Basic representation of a single key of a keyboard. Each key has a set of
* caps associated with tuples of modifiers. The cap determins what happens
* when a key is pressed, while it is the state of modifier keys that determines
* what cap is in effect on any particular key.
*
* @constructor
*/
Guacamole.OnScreenKeyboard.Key = function() {
var key = this;
/**
* Whether this key is currently pressed.
*/
this.pressed = false;
/**
* Width of the key, relative to the size of the keyboard.
*/
this.size = 1;
/**
* An associative map of all caps by modifier.
*/
this.caps = {};
/**
* Bit mask with all modifiers that affect this key set.
*/
this.modifierMask = 0;
/**
* Given the bitwise OR of all active modifiers, returns the key cap
* which applies.
*/
this.getCap = function(modifier) {
return key.caps[modifier & key.modifierMask];
};
};
/**
* Basic representation of a cap of a key. The cap is the visible part of a key
* and determines the active behavior of a key when pressed. The state of all
* modifiers on the keyboard determines the active cap for all keys, thus
* each cap is associated with a set of modifiers.
*
* @constructor
* @param {String} text The text to be displayed within this cap.
* @param {Number} keysym The keysym this cap sends when its associated key is
* pressed or released.
* @param {String} modifier The modifier represented by this cap.
*/
Guacamole.OnScreenKeyboard.Cap = function(text, keysym, modifier) {
/**
* Modifier represented by this keycap
*/
this.modifier = null;
/**
* The text to be displayed within this keycap
*/
this.text = text;
/**
* The keysym this cap sends when its associated key is pressed/released
*/
this.keysym = keysym;
// Set modifier if provided
if (modifier) this.modifier = modifier;
};

View File

@@ -0,0 +1,832 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is guacamole-common-js.
*
* The Initial Developer of the Original Code is
* Michael Jumper.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
/**
* Namespace for all Guacamole JavaScript objects.
* @namespace
*/
var Guacamole = Guacamole || {};
/**
* Core object providing abstract communication for Guacamole. This object
* is a null implementation whose functions do nothing. Guacamole applications
* should use {@link Guacamole.HTTPTunnel} instead, or implement their own tunnel based
* on this one.
*
* @constructor
* @see Guacamole.HTTPTunnel
*/
Guacamole.Tunnel = function() {
/**
* Connect to the tunnel with the given optional data. This data is
* typically used for authentication. The format of data accepted is
* up to the tunnel implementation.
*
* @param {String} data The data to send to the tunnel when connecting.
*/
this.connect = function(data) {};
/**
* Disconnect from the tunnel.
*/
this.disconnect = function() {};
/**
* Send the given message through the tunnel to the service on the other
* side. All messages are guaranteed to be received in the order sent.
*
* @param {...} elements The elements of the message to send to the
* service on the other side of the tunnel.
*/
this.sendMessage = function(elements) {};
/**
* Fired whenever an error is encountered by the tunnel.
*
* @event
* @param {String} message A human-readable description of the error that
* occurred.
*/
this.onerror = null;
/**
* Fired once for every complete Guacamole instruction received, in order.
*
* @event
* @param {String} opcode The Guacamole instruction opcode.
* @param {Array} parameters The parameters provided for the instruction,
* if any.
*/
this.oninstruction = null;
};
/**
* Guacamole Tunnel implemented over HTTP via XMLHttpRequest.
*
* @constructor
* @augments Guacamole.Tunnel
* @param {String} tunnelURL The URL of the HTTP tunneling service.
*/
Guacamole.HTTPTunnel = function(tunnelURL) {
/**
* Reference to this HTTP tunnel.
* @private
*/
var tunnel = this;
var tunnel_uuid;
var TUNNEL_CONNECT = tunnelURL + "?connect";
var TUNNEL_READ = tunnelURL + "?read:";
var TUNNEL_WRITE = tunnelURL + "?write:";
var STATE_IDLE = 0;
var STATE_CONNECTED = 1;
var STATE_DISCONNECTED = 2;
var currentState = STATE_IDLE;
var POLLING_ENABLED = 1;
var POLLING_DISABLED = 0;
// Default to polling - will be turned off automatically if not needed
var pollingMode = POLLING_ENABLED;
var sendingMessages = false;
var outputMessageBuffer = "";
this.sendMessage = function() {
// Do not attempt to send messages if not connected
if (currentState != STATE_CONNECTED)
return;
// Do not attempt to send empty messages
if (arguments.length == 0)
return;
/**
* Converts the given value to a length/string pair for use as an
* element in a Guacamole instruction.
*
* @private
* @param value The value to convert.
* @return {String} The converted value.
*/
function getElement(value) {
var string = new String(value);
return string.length + "." + string;
}
// Initialized message with first element
var message = getElement(arguments[0]);
// Append remaining elements
for (var i=1; i<arguments.length; i++)
message += "," + getElement(arguments[i]);
// Final terminator
message += ";";
// Add message to buffer
outputMessageBuffer += message;
// Send if not currently sending
if (!sendingMessages)
sendPendingMessages();
};
function sendPendingMessages() {
if (outputMessageBuffer.length > 0) {
sendingMessages = true;
var message_xmlhttprequest = new XMLHttpRequest();
message_xmlhttprequest.open("POST", TUNNEL_WRITE + tunnel_uuid);
message_xmlhttprequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Once response received, send next queued event.
message_xmlhttprequest.onreadystatechange = function() {
if (message_xmlhttprequest.readyState == 4) {
// If an error occurs during send, handle it
if (message_xmlhttprequest.status != 200)
handleHTTPTunnelError(message_xmlhttprequest);
// Otherwise, continue the send loop
else
sendPendingMessages();
}
}
message_xmlhttprequest.send(outputMessageBuffer);
outputMessageBuffer = ""; // Clear buffer
}
else
sendingMessages = false;
}
function getHTTPTunnelErrorMessage(xmlhttprequest) {
var status = xmlhttprequest.status;
// Special cases
if (status == 0) return "Disconnected";
if (status == 200) return "Success";
if (status == 403) return "Unauthorized";
if (status == 404) return "Connection closed"; /* While it may be more
* accurate to say the
* connection does not
* exist, it is confusing
* to the user.
*
* In general, this error
* will only happen when
* the tunnel does not
* exist, which happens
* after the connection
* is closed and the
* tunnel is detached.
*/
// Internal server errors
if (status >= 500 && status <= 599) return "Server error";
// Otherwise, unknown
return "Unknown error";
}
function handleHTTPTunnelError(xmlhttprequest) {
// Get error message
var message = getHTTPTunnelErrorMessage(xmlhttprequest);
// Call error handler
if (tunnel.onerror) tunnel.onerror(message);
// Finish
tunnel.disconnect();
}
function handleResponse(xmlhttprequest) {
var interval = null;
var nextRequest = null;
var dataUpdateEvents = 0;
// The location of the last element's terminator
var elementEnd = -1;
// Where to start the next length search or the next element
var startIndex = 0;
// Parsed elements
var elements = new Array();
function parseResponse() {
// Do not handle responses if not connected
if (currentState != STATE_CONNECTED) {
// Clean up interval if polling
if (interval != null)
clearInterval(interval);
return;
}
// Do not parse response yet if not ready
if (xmlhttprequest.readyState < 2) return;
// Attempt to read status
var status;
try { status = xmlhttprequest.status; }
// If status could not be read, assume successful.
catch (e) { status = 200; }
// Start next request as soon as possible IF request was successful
if (nextRequest == null && status == 200)
nextRequest = makeRequest();
// Parse stream when data is received and when complete.
if (xmlhttprequest.readyState == 3 ||
xmlhttprequest.readyState == 4) {
// Also poll every 30ms (some browsers don't repeatedly call onreadystatechange for new data)
if (pollingMode == POLLING_ENABLED) {
if (xmlhttprequest.readyState == 3 && interval == null)
interval = setInterval(parseResponse, 30);
else if (xmlhttprequest.readyState == 4 && interval != null)
clearInterval(interval);
}
// If canceled, stop transfer
if (xmlhttprequest.status == 0) {
tunnel.disconnect();
return;
}
// Halt on error during request
else if (xmlhttprequest.status != 200) {
handleHTTPTunnelError(xmlhttprequest);
return;
}
// Attempt to read in-progress data
var current;
try { current = xmlhttprequest.responseText; }
// Do not attempt to parse if data could not be read
catch (e) { return; }
// While search is within currently received data
while (elementEnd < current.length) {
// If we are waiting for element data
if (elementEnd >= startIndex) {
// We now have enough data for the element. Parse.
var element = current.substring(startIndex, elementEnd);
var terminator = current.substring(elementEnd, elementEnd+1);
// Add element to array
elements.push(element);
// If last element, handle instruction
if (terminator == ";") {
// Get opcode
var opcode = elements.shift();
// Call instruction handler.
if (tunnel.oninstruction != null)
tunnel.oninstruction(opcode, elements);
// Clear elements
elements.length = 0;
}
// Start searching for length at character after
// element terminator
startIndex = elementEnd + 1;
}
// Search for end of length
var lengthEnd = current.indexOf(".", startIndex);
if (lengthEnd != -1) {
// Parse length
var length = parseInt(current.substring(elementEnd+1, lengthEnd));
// If we're done parsing, handle the next response.
if (length == 0) {
// Clean up interval if polling
if (interval != null)
clearInterval(interval);
// Clean up object
xmlhttprequest.onreadystatechange = null;
xmlhttprequest.abort();
// Start handling next request
if (nextRequest)
handleResponse(nextRequest);
// Done parsing
break;
}
// Calculate start of element
startIndex = lengthEnd + 1;
// Calculate location of element terminator
elementEnd = startIndex + length;
}
// If no period yet, continue search when more data
// is received
else {
startIndex = current.length;
break;
}
} // end parse loop
}
}
// If response polling enabled, attempt to detect if still
// necessary (via wrapping parseResponse())
if (pollingMode == POLLING_ENABLED) {
xmlhttprequest.onreadystatechange = function() {
// If we receive two or more readyState==3 events,
// there is no need to poll.
if (xmlhttprequest.readyState == 3) {
dataUpdateEvents++;
if (dataUpdateEvents >= 2) {
pollingMode = POLLING_DISABLED;
xmlhttprequest.onreadystatechange = parseResponse;
}
}
parseResponse();
}
}
// Otherwise, just parse
else
xmlhttprequest.onreadystatechange = parseResponse;
parseResponse();
}
/**
* Arbitrary integer, unique for each tunnel read request.
* @private
*/
var request_id = 0;
function makeRequest() {
// Make request, increment request ID
var xmlhttprequest = new XMLHttpRequest();
xmlhttprequest.open("GET", TUNNEL_READ + tunnel_uuid + ":" + (request_id++));
xmlhttprequest.send(null);
return xmlhttprequest;
}
this.connect = function(data) {
// Start tunnel and connect synchronously
var connect_xmlhttprequest = new XMLHttpRequest();
connect_xmlhttprequest.open("POST", TUNNEL_CONNECT, false);
connect_xmlhttprequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
connect_xmlhttprequest.send(data);
// If failure, throw error
if (connect_xmlhttprequest.status != 200) {
var message = getHTTPTunnelErrorMessage(connect_xmlhttprequest);
throw new Error(message);
}
// Get UUID from response
tunnel_uuid = connect_xmlhttprequest.responseText;
// Start reading data
currentState = STATE_CONNECTED;
handleResponse(makeRequest());
};
this.disconnect = function() {
currentState = STATE_DISCONNECTED;
};
};
Guacamole.HTTPTunnel.prototype = new Guacamole.Tunnel();
/**
* Guacamole Tunnel implemented over WebSocket via XMLHttpRequest.
*
* @constructor
* @augments Guacamole.Tunnel
* @param {String} tunnelURL The URL of the WebSocket tunneling service.
*/
Guacamole.WebSocketTunnel = function(tunnelURL) {
/**
* Reference to this WebSocket tunnel.
* @private
*/
var tunnel = this;
/**
* The WebSocket used by this tunnel.
* @private
*/
var socket = null;
/**
* The WebSocket protocol corresponding to the protocol used for the current
* location.
* @private
*/
var ws_protocol = {
"http:": "ws:",
"https:": "wss:"
};
var status_code = {
1000: "Connection closed normally.",
1001: "Connection shut down.",
1002: "Protocol error.",
1003: "Invalid data.",
1004: "[UNKNOWN, RESERVED]",
1005: "No status code present.",
1006: "Connection closed abnormally.",
1007: "Inconsistent data type.",
1008: "Policy violation.",
1009: "Message too large.",
1010: "Extension negotiation failed."
};
var STATE_IDLE = 0;
var STATE_CONNECTED = 1;
var STATE_DISCONNECTED = 2;
var currentState = STATE_IDLE;
// Transform current URL to WebSocket URL
// If not already a websocket URL
if ( tunnelURL.substring(0, 3) != "ws:"
&& tunnelURL.substring(0, 4) != "wss:") {
var protocol = ws_protocol[window.location.protocol];
// If absolute URL, convert to absolute WS URL
if (tunnelURL.substring(0, 1) == "/")
tunnelURL =
protocol
+ "//" + window.location.host
+ tunnelURL;
// Otherwise, construct absolute from relative URL
else {
// Get path from pathname
var slash = window.location.pathname.lastIndexOf("/");
var path = window.location.pathname.substring(0, slash + 1);
// Construct absolute URL
tunnelURL =
protocol
+ "//" + window.location.host
+ path
+ tunnelURL;
}
}
this.sendMessage = function(elements) {
// Do not attempt to send messages if not connected
if (currentState != STATE_CONNECTED)
return;
// Do not attempt to send empty messages
if (arguments.length == 0)
return;
/**
* Converts the given value to a length/string pair for use as an
* element in a Guacamole instruction.
*
* @private
* @param value The value to convert.
* @return {String} The converted value.
*/
function getElement(value) {
var string = new String(value);
return string.length + "." + string;
}
// Initialized message with first element
var message = getElement(arguments[0]);
// Append remaining elements
for (var i=1; i<arguments.length; i++)
message += "," + getElement(arguments[i]);
// Final terminator
message += ";";
socket.send(message);
};
this.connect = function(data) {
// Connect socket
socket = new WebSocket(tunnelURL + "?" + data, "guacamole");
socket.onopen = function(event) {
currentState = STATE_CONNECTED;
};
socket.onclose = function(event) {
// If connection closed abnormally, signal error.
if (event.code != 1000 && tunnel.onerror)
tunnel.onerror(status_code[event.code]);
};
socket.onerror = function(event) {
// Call error handler
if (tunnel.onerror) tunnel.onerror(event.data);
};
socket.onmessage = function(event) {
var message = event.data;
var startIndex = 0;
var elementEnd;
var elements = [];
do {
// Search for end of length
var lengthEnd = message.indexOf(".", startIndex);
if (lengthEnd != -1) {
// Parse length
var length = parseInt(message.substring(elementEnd+1, lengthEnd));
// Calculate start of element
startIndex = lengthEnd + 1;
// Calculate location of element terminator
elementEnd = startIndex + length;
}
// If no period, incomplete instruction.
else
throw new Error("Incomplete instruction.");
// We now have enough data for the element. Parse.
var element = message.substring(startIndex, elementEnd);
var terminator = message.substring(elementEnd, elementEnd+1);
// Add element to array
elements.push(element);
// If last element, handle instruction
if (terminator == ";") {
// Get opcode
var opcode = elements.shift();
// Call instruction handler.
if (tunnel.oninstruction != null)
tunnel.oninstruction(opcode, elements);
// Clear elements
elements.length = 0;
}
// Start searching for length at character after
// element terminator
startIndex = elementEnd + 1;
} while (startIndex < message.length);
};
};
this.disconnect = function() {
currentState = STATE_DISCONNECTED;
socket.close();
};
};
Guacamole.WebSocketTunnel.prototype = new Guacamole.Tunnel();
/**
* Guacamole Tunnel which cycles between all specified tunnels until
* no tunnels are left. Another tunnel is used if an error occurs but
* no instructions have been received. If an instruction has been
* received, or no tunnels remain, the error is passed directly out
* through the onerror handler (if defined).
*
* @constructor
* @augments Guacamole.Tunnel
* @param {...} tunnel_chain The tunnels to use, in order of priority.
*/
Guacamole.ChainedTunnel = function(tunnel_chain) {
/**
* Reference to this chained tunnel.
* @private
*/
var chained_tunnel = this;
/**
* The currently wrapped tunnel, if any.
* @private
*/
var current_tunnel = null;
/**
* Data passed in via connect(), to be used for
* wrapped calls to other tunnels' connect() functions.
* @private
*/
var connect_data;
/**
* Array of all tunnels passed to this ChainedTunnel through the
* constructor arguments.
* @private
*/
var tunnels = [];
// Load all tunnels into array
for (var i=0; i<arguments.length; i++)
tunnels.push(arguments[i]);
/**
* Sets the current tunnel.
*
* @private
* @param {Guacamole.Tunnel} tunnel The tunnel to set as the current tunnel.
*/
function attach(tunnel) {
// Clear handlers of current tunnel, if any
if (current_tunnel) {
current_tunnel.onerror = null;
current_tunnel.oninstruction = null;
}
// Set own functions to tunnel's functions
chained_tunnel.disconnect = tunnel.disconnect;
chained_tunnel.sendMessage = tunnel.sendMessage;
// Record current tunnel
current_tunnel = tunnel;
// Wrap own oninstruction within current tunnel
current_tunnel.oninstruction = function(opcode, elements) {
// Invoke handler
chained_tunnel.oninstruction(opcode, elements);
// Use handler permanently from now on
current_tunnel.oninstruction = chained_tunnel.oninstruction;
// Pass through errors (without trying other tunnels)
current_tunnel.onerror = chained_tunnel.onerror;
}
// Attach next tunnel on error
current_tunnel.onerror = function(message) {
// Get next tunnel
var next_tunnel = tunnels.shift();
// If there IS a next tunnel, try using it.
if (next_tunnel)
attach(next_tunnel);
// Otherwise, call error handler
else if (chained_tunnel.onerror)
chained_tunnel.onerror(message);
};
try {
// Attempt connection
current_tunnel.connect(connect_data);
}
catch (e) {
// Call error handler of current tunnel on error
current_tunnel.onerror(e.message);
}
}
this.connect = function(data) {
// Remember connect data
connect_data = data;
// Get first tunnel
var next_tunnel = tunnels.shift();
// Attach first tunnel
if (next_tunnel)
attach(next_tunnel);
// If there IS no first tunnel, error
else if (chained_tunnel.onerror)
chained_tunnel.onerror("No tunnels to try.");
};
};
Guacamole.ChainedTunnel.prototype = new Guacamole.Tunnel();

View File

@@ -0,0 +1,12 @@
<assembly>
<baseDirectory>guacamole-common-js</baseDirectory>
<formats>
<format>zip</format>
</formats>
<fileSets>
<fileSet>
<directory>src/main/resources</directory>
<outputDirectory></outputDirectory>
</fileSet>
</fileSets>
</assembly>