Publish Vulpes Preview 15 sources for desktop, Android and Tundra
Share Gaia assets and adapters, keep private profiles and development documents local, and update both public READMEs.
This commit is contained in:
parent
93e3a48004
commit
b38dea0597
25901 changed files with 9982925 additions and 369 deletions
|
|
@ -0,0 +1,93 @@
|
|||
/* global InputMethods, PromiseStorage*/
|
||||
|
||||
|
||||
'use strict';
|
||||
|
||||
(function() {
|
||||
function RecentKeys() {
|
||||
this._items = [];
|
||||
}
|
||||
|
||||
RecentKeys.prototype.RECENT_KEY_COUNT = 18;
|
||||
|
||||
RecentKeys.prototype.getItems = function() {
|
||||
return this._items || [];
|
||||
};
|
||||
|
||||
RecentKeys.prototype.setItems = function(val) {
|
||||
if (Array.isArray(val) && val.length) {
|
||||
this._items = val.slice(0, this.RECENT_KEY_COUNT);
|
||||
}
|
||||
};
|
||||
|
||||
RecentKeys.prototype.getPanelKeys = function() {
|
||||
if (!this._items) {
|
||||
throw new Error('Emoji:Unable to get recently used keys');
|
||||
}
|
||||
|
||||
return this.getItems().map(function(val) {
|
||||
return { compositeKey: val, type: 'emoji' };
|
||||
});
|
||||
};
|
||||
|
||||
RecentKeys.prototype.add = function(key) {
|
||||
var duplicateKeyIndex = this._items.indexOf(key);
|
||||
|
||||
// splice an element from array can always reduce length by 1.
|
||||
// this ensure that we remove the last element or existent key,
|
||||
// before unshifting clicked key into array.
|
||||
if (this._items.length >= this.RECENT_KEY_COUNT ||
|
||||
duplicateKeyIndex !== -1) {
|
||||
this._items.splice(duplicateKeyIndex, 1);
|
||||
}
|
||||
|
||||
this._items.unshift(key);
|
||||
};
|
||||
|
||||
function EmojiInputMethod() {
|
||||
this._glue = null;
|
||||
this._dbStore = null;
|
||||
this._recentKeys = new RecentKeys();
|
||||
}
|
||||
|
||||
EmojiInputMethod.prototype.EMOJI_DB_NAME = 'Emoji';
|
||||
EmojiInputMethod.prototype.EMOJI_RECENT_STORE_KEY = 'emojiRecentUsedKeys';
|
||||
|
||||
EmojiInputMethod.prototype.init = function(glue) {
|
||||
this._glue = glue;
|
||||
this._dbStore = new PromiseStorage(this.EMOJI_DB_NAME);
|
||||
|
||||
var p = this._dbStore.start()
|
||||
.then(function() {
|
||||
return this._dbStore.getItem(this.EMOJI_RECENT_STORE_KEY);
|
||||
}.bind(this))
|
||||
.then(function(keys) {
|
||||
this._recentKeys.setItems(keys);
|
||||
}.bind(this));
|
||||
|
||||
return p;
|
||||
};
|
||||
|
||||
EmojiInputMethod.prototype.deactivate = function() {
|
||||
return this._dbStore.setItem(
|
||||
this.EMOJI_RECENT_STORE_KEY, this._recentKeys.getItems());
|
||||
};
|
||||
|
||||
EmojiInputMethod.prototype.click = function(key, repeat) {
|
||||
return this._glue.sendKey(key, repeat);
|
||||
};
|
||||
|
||||
EmojiInputMethod.prototype.handleKey = function(key, repeat) {
|
||||
this._recentKeys.add(key.key);
|
||||
|
||||
return this._glue.sendKey(key, repeat);
|
||||
};
|
||||
|
||||
EmojiInputMethod.prototype.updatePageKeys = function(page) {
|
||||
page.panelKeys = this._recentKeys.getPanelKeys();
|
||||
return page;
|
||||
};
|
||||
|
||||
|
||||
InputMethods.emoji = new EmojiInputMethod();
|
||||
}());
|
||||
|
|
@ -0,0 +1,20 @@
|
|||
'use strict';
|
||||
|
||||
/* global InputMethods */
|
||||
|
||||
InputMethods.india = {
|
||||
_glue: null,
|
||||
|
||||
init: function(glue) {
|
||||
this._glue = glue;
|
||||
},
|
||||
|
||||
click: function(keyCode) {
|
||||
this._glue.setUpperCase(false);
|
||||
return this._glue.sendKey(keyCode);
|
||||
},
|
||||
|
||||
displaysCandidates: function() {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
|
@ -0,0 +1,456 @@
|
|||
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 jsAvroPhonetic.
|
||||
|
||||
The Initial Developer of the Original Code is
|
||||
Rifat Nabi <to.rifat@gmail.com>
|
||||
|
||||
Copyright (C) OmicronLab <http://www.omicronlab.com>. All Rights Reserved.
|
||||
|
||||
|
||||
Contributor(s): Mehdi Hasan <mhasan@omicronlab.com>"
|
||||
|
||||
File diff suppressed because it is too large
Load diff
|
|
@ -0,0 +1,299 @@
|
|||
/* -*- Mode: js; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- /
|
||||
/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
|
||||
/* global KeyEvent, InputMethods */
|
||||
'use strict';
|
||||
|
||||
(function() {
|
||||
|
||||
var keyboard, ime, composingText, JangmiIME;
|
||||
|
||||
var BACKSPACE = KeyEvent.DOM_VK_BACK_SPACE;
|
||||
|
||||
/*
|
||||
JangmiIME
|
||||
https://github.com/sangpire/jangmiIME
|
||||
|
||||
Copyright 2013, BYUN Sangpil. All Rights Reserved.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS-IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
(function() {
|
||||
var isCompatibleJamoKeyCode;
|
||||
|
||||
var UTF8_HANGUL_SYLLABLES_START = 0xAC00;
|
||||
var UTF8_HANGUL_COMPATIBILITY_START = 0x3131;
|
||||
var UTF8_CHOSEONG_DIFF = '까'.charCodeAt(0) - '가'.charCodeAt(0);
|
||||
var UTF8_JUNGSEONG_DIFF = '개'.charCodeAt(0) - '가'.charCodeAt(0);
|
||||
|
||||
var COMPATIBILITY_MULTI_JAMO_MAP = {
|
||||
'ㄱㄱ' : 0x1, 'ㄷㄷ' : 0x7, 'ㅂㅂ' : 0x12, 'ㅅㅅ' : 0x15,
|
||||
'ㅈㅈ' : 0x18, 'ㅗㅏ' : 0x27, 'ㅗㅐ' : 0x28, 'ㅗㅣ' : 0x29,
|
||||
'ㅜㅓ' : 0x2C, 'ㅜㅔ' : 0x2E, 'ㅜㅣ' : 0x2E, 'ㅡㅣ' : 0x31
|
||||
};
|
||||
|
||||
var CHO_SEONG_MAP = {
|
||||
'ㄱ' : 0, 'ㄱㄱ' : 1, 'ㄲ' : 1, 'ㄴ' : 2, 'ㄷ' : 3,
|
||||
'ㄷㄷ' : 4, 'ㄸ' : 4, 'ㄹ' : 5, 'ㅁ' : 6, 'ㅂ' : 7,
|
||||
'ㅂㅂ' : 8, 'ㅃ' : 8, 'ㅅ' : 9, 'ㅅㅅ' : 10, 'ㅆ' : 10,
|
||||
'ㅇ' : 11, 'ㅈ' : 12, 'ㅈㅈ' : 13, 'ㅉ' : 13, 'ㅊ' : 14,
|
||||
'ㅋ' : 15, 'ㅌ' : 16, 'ㅍ' : 17, 'ㅎ' : 18
|
||||
};
|
||||
|
||||
var JUNG_SEONG_MAP = {
|
||||
'ㅏ' : 0, 'ㅐ' : 1, 'ㅑ' : 2, 'ㅒ' : 3, 'ㅓ' : 4,
|
||||
'ㅔ' : 5, 'ㅕ' : 6, 'ㅖ' : 7, 'ㅗ' : 8, 'ㅘ' : 9,
|
||||
'ㅗㅏ' : 9, 'ㅙ' : 10, 'ㅗㅐ' : 10, 'ㅚ' : 11, 'ㅗㅣ' : 11,
|
||||
'ㅛ' : 12, 'ㅜ' : 13, 'ㅝ' : 14, 'ㅜㅓ' : 14, 'ㅞ' : 15,
|
||||
'ㅜㅔ' : 15, 'ㅟ' : 16, 'ㅜㅣ' : 16, 'ㅠ' : 17, 'ㅡ' : 18,
|
||||
'ㅢ' : 19, 'ㅡㅣ' : 19, 'ㅣ' : 20
|
||||
};
|
||||
|
||||
var JONG_SEONG_MAP = {
|
||||
'ㄱ' : 1, 'ㄲ' : 2, 'ㄱㅅ' : 3, 'ㄴ' : 4, 'ㄴㅈ' : 5,
|
||||
'ㄴㅎ' : 6, 'ㄷ' : 7, 'ㄹ' : 8, 'ㄹㄱ' : 9, 'ㄹㅁ' : 10,
|
||||
'ㄹㅂ' : 11, 'ㄹㅅ' : 12, 'ㄹㅌ' : 13, 'ㄹㅍ' : 14, 'ㄹㅎ' : 15,
|
||||
'ㅁ' : 16, 'ㅂ' : 17, 'ㅂㅅ' : 18, 'ㅅ' : 19, 'ㅆ' : 20,
|
||||
'ㅇ' : 21, 'ㅈ' : 22, 'ㅊ' : 23, 'ㅋ' : 24, 'ㅌ' : 25,
|
||||
'ㅍ' : 26, 'ㅎ' : 27
|
||||
};
|
||||
|
||||
isCompatibleJamoKeyCode = function(keyCode) {
|
||||
return (0x3131 <= keyCode && keyCode <= 0x318e);
|
||||
};
|
||||
|
||||
JangmiIME = (function() {
|
||||
/*
|
||||
@handler =
|
||||
passed: (keyCode) ->
|
||||
added: (gul) ->
|
||||
changed: (gul) ->
|
||||
*/
|
||||
|
||||
function JangmiIME(handler) {
|
||||
this.handler = handler;
|
||||
this.reset();
|
||||
}
|
||||
|
||||
/*
|
||||
Reset Current State.
|
||||
*/
|
||||
JangmiIME.prototype.reset = function() {
|
||||
this.curJamo = null;
|
||||
this.choSeong = [];
|
||||
this.jungSeong = [];
|
||||
this.jongSeong = [];
|
||||
};
|
||||
|
||||
JangmiIME.prototype.added = function() {
|
||||
var curGul;
|
||||
curGul = this.peep();
|
||||
if (curGul != null) {
|
||||
return this.handler.added(curGul);
|
||||
}
|
||||
};
|
||||
|
||||
JangmiIME.prototype.changed = function() {
|
||||
var curGul;
|
||||
curGul = this.peep();
|
||||
if (curGul != null) {
|
||||
return this.handler.changed(curGul);
|
||||
}
|
||||
};
|
||||
|
||||
JangmiIME.prototype.isEmpty = function() {
|
||||
return (this.choSeong.length +
|
||||
this.jungSeong.length +
|
||||
this.jongSeong.length) === 0;
|
||||
};
|
||||
|
||||
/*
|
||||
Add KeyCode
|
||||
*/
|
||||
JangmiIME.prototype.add = function(keyCode) {
|
||||
var curJamo, jamo, temp;
|
||||
if (!isCompatibleJamoKeyCode(keyCode)) {
|
||||
this.reset();
|
||||
return this.handler.passed(keyCode);
|
||||
} else {
|
||||
jamo = String.fromCharCode(keyCode);
|
||||
if (this.curJamo == null) {
|
||||
if (CHO_SEONG_MAP.hasOwnProperty(jamo)) {
|
||||
this.curJamo = this.choSeong;
|
||||
}
|
||||
if (JUNG_SEONG_MAP.hasOwnProperty(jamo)) {
|
||||
this.curJamo = this.jungSeong;
|
||||
}
|
||||
this.curJamo.push(jamo);
|
||||
return this.added();
|
||||
} else {
|
||||
curJamo = this.curJamo.join('') + jamo;
|
||||
switch (this.curJamo) {
|
||||
case this.choSeong:
|
||||
if (CHO_SEONG_MAP.hasOwnProperty(curJamo)) {
|
||||
this.curJamo.push(jamo);
|
||||
return this.changed();
|
||||
} else {
|
||||
if (JUNG_SEONG_MAP.hasOwnProperty(jamo)) {
|
||||
this.jungSeong.push(jamo);
|
||||
this.curJamo = this.jungSeong;
|
||||
return this.changed();
|
||||
} else {
|
||||
this.reset();
|
||||
return this.add(keyCode);
|
||||
}
|
||||
}
|
||||
break;
|
||||
case this.jungSeong:
|
||||
if (JUNG_SEONG_MAP.hasOwnProperty(curJamo)) {
|
||||
this.curJamo.push(jamo);
|
||||
return this.changed();
|
||||
} else {
|
||||
if (this.choSeong.length > 0 &&
|
||||
JONG_SEONG_MAP.hasOwnProperty(jamo)) {
|
||||
this.jongSeong.push(jamo);
|
||||
this.curJamo = this.jongSeong;
|
||||
return this.changed();
|
||||
} else {
|
||||
this.reset();
|
||||
return this.add(keyCode);
|
||||
}
|
||||
}
|
||||
break;
|
||||
case this.jongSeong:
|
||||
if (JONG_SEONG_MAP.hasOwnProperty(curJamo)) {
|
||||
this.curJamo.push(jamo);
|
||||
return this.changed();
|
||||
} else {
|
||||
if (JUNG_SEONG_MAP.hasOwnProperty(jamo)) {
|
||||
temp = this.curJamo.pop();
|
||||
this.changed();
|
||||
this.reset();
|
||||
this.choSeong.push(temp);
|
||||
this.jungSeong.push(jamo);
|
||||
this.curJamo = this.jungSeong;
|
||||
return this.added();
|
||||
} else {
|
||||
this.reset();
|
||||
this.curJamo = null;
|
||||
return this.add(keyCode);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/*
|
||||
Delete Last Input
|
||||
*/
|
||||
JangmiIME.prototype.back = function() {
|
||||
if (this.curJamo.length > 0) {
|
||||
this.curJamo.pop();
|
||||
return this.changed();
|
||||
} else {
|
||||
switch (this.curJamo) {
|
||||
case this.jungSeong:
|
||||
this.curJamo = this.choSeong;
|
||||
return this.back();
|
||||
case this.jongSeong:
|
||||
this.curJamo = this.jungSeong;
|
||||
return this.back();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/*
|
||||
peep current hangul
|
||||
*/
|
||||
JangmiIME.prototype.peep = function() {
|
||||
var code;
|
||||
if (this.choSeong.length > 0 && this.jungSeong.length > 0) {
|
||||
code = UTF8_HANGUL_SYLLABLES_START +
|
||||
CHO_SEONG_MAP[this.choSeong.join('')] * UTF8_CHOSEONG_DIFF;
|
||||
code += JUNG_SEONG_MAP[this.jungSeong.join('')] * UTF8_JUNGSEONG_DIFF;
|
||||
if (this.jongSeong.length > 0) {
|
||||
code += JONG_SEONG_MAP[this.jongSeong.join('')];
|
||||
}
|
||||
} else {
|
||||
if (this.choSeong.length === 1) {
|
||||
code = this.choSeong[0].charCodeAt(0);
|
||||
} else if (this.choSeong.length > 1) {
|
||||
code = UTF8_HANGUL_COMPATIBILITY_START +
|
||||
COMPATIBILITY_MULTI_JAMO_MAP[this.choSeong.join('')];
|
||||
} else if (this.jungSeong.length === 1) {
|
||||
code = this.jungSeong[0].charCodeAt(0);
|
||||
} else if (this.jungSeong.length > 1) {
|
||||
code = UTF8_HANGUL_COMPATIBILITY_START +
|
||||
COMPATIBILITY_MULTI_JAMO_MAP[this.jungSeong.join('')];
|
||||
} else {
|
||||
return '';
|
||||
}
|
||||
}
|
||||
return String.fromCharCode(code);
|
||||
};
|
||||
return JangmiIME;
|
||||
})();
|
||||
})();
|
||||
|
||||
InputMethods.jshangul = {
|
||||
init: init,
|
||||
click: click,
|
||||
deactivate: deactivate
|
||||
};
|
||||
|
||||
function setComposition(gul) {
|
||||
composingText = gul;
|
||||
keyboard.setComposition(gul);
|
||||
}
|
||||
|
||||
function endComposition() {
|
||||
if (composingText.length > 0) {
|
||||
keyboard.endComposition(composingText);
|
||||
composingText = '';
|
||||
}
|
||||
}
|
||||
|
||||
function init(interfaceObject) {
|
||||
keyboard = interfaceObject;
|
||||
composingText = '';
|
||||
ime = new JangmiIME({
|
||||
passed: function(keyCode) {
|
||||
endComposition();
|
||||
keyboard.sendKey(keyCode);
|
||||
},
|
||||
added: function(gul) {
|
||||
endComposition();
|
||||
setComposition(gul);
|
||||
},
|
||||
changed: function(gul) {
|
||||
setComposition(gul);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function deactivate() {
|
||||
endComposition();
|
||||
ime.reset();
|
||||
}
|
||||
|
||||
function click(keycode, x, y) {
|
||||
if (keycode === BACKSPACE && !ime.isEmpty()) {
|
||||
ime.back();
|
||||
} else {
|
||||
ime.add(keycode);
|
||||
}
|
||||
keyboard.setUpperCase({
|
||||
isUpperCase: false
|
||||
});
|
||||
}
|
||||
})();
|
||||
213
assets/webapps/keyboard.gaiamobile.org/js/imes/jspinyin/NOTICE
Normal file
213
assets/webapps/keyboard.gaiamobile.org/js/imes/jspinyin/NOTICE
Normal file
|
|
@ -0,0 +1,213 @@
|
|||
Jspinyin is a Simplified Chinese input method for gaia and is licensed under
|
||||
the Apache Version 2.0, 2012. The original code is based on the Google
|
||||
PinyinIME project as part of the android project hosted at:
|
||||
http://android.googlesource.com/platform/packages/inputmethods/PinyinIME.
|
||||
|
||||
We use Emscripten (https://github.com/kripken/emscripten) to compile the
|
||||
original code into JavaScript version.
|
||||
|
||||
==========================================================================
|
||||
Copyright notice for jspinyin.
|
||||
|
||||
Copyright (c) 2012, Mozilla Online
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
==========================================================================
|
||||
Copyright notice for PinyinIME.
|
||||
|
||||
Copyright (c) 2009, The Android Open Source Project
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
Binary file not shown.
|
|
@ -0,0 +1,132 @@
|
|||
/* jshint sub: true */
|
||||
/* global Module */
|
||||
'use strict';
|
||||
(function() {
|
||||
if (typeof Module == 'undefined') {
|
||||
/*jshint -W020 */
|
||||
Module = {};
|
||||
/*jshint +W020 */
|
||||
}
|
||||
if (!Module['preRun']) {
|
||||
Module['preRun'] = [];
|
||||
}
|
||||
Module['preRun'].push(function() {
|
||||
function assert(check, msg) {
|
||||
if (!check) {
|
||||
throw msg + new Error().stack;
|
||||
}
|
||||
}
|
||||
|
||||
Module['FS_createPath']('/', 'data', true, true);
|
||||
|
||||
function DataRequest() {}
|
||||
DataRequest.prototype = {
|
||||
requests: {},
|
||||
open: function(mode, name) {
|
||||
this.requests[name] = this;
|
||||
},
|
||||
send: function() {}
|
||||
};
|
||||
var filePreload0 = new DataRequest();
|
||||
filePreload0.open('GET', 'data/dict.data', true);
|
||||
filePreload0.responseType = 'arraybuffer';
|
||||
filePreload0.onload = function() {
|
||||
var arrayBuffer = filePreload0.response;
|
||||
assert(arrayBuffer, 'Loading file data/dict.data failed.');
|
||||
var byteArray = !arrayBuffer.subarray ?
|
||||
new Uint8Array(arrayBuffer) : arrayBuffer;
|
||||
|
||||
Module['FS_createPreloadedFile'](
|
||||
'/data', 'dict.data', byteArray, true, true, function() {
|
||||
Module['removeRunDependency']('fp data/dict.data');
|
||||
}
|
||||
);
|
||||
};
|
||||
Module['addRunDependency']('fp data/dict.data');
|
||||
filePreload0.send(null);
|
||||
|
||||
if (!Module.expectedDataFileDownloads) {
|
||||
Module.expectedDataFileDownloads = 0;
|
||||
Module.finishedDataFileDownloads = 0;
|
||||
}
|
||||
Module.expectedDataFileDownloads++;
|
||||
|
||||
var PACKAGE_NAME = 'empinyin_files.data';
|
||||
var REMOTE_PACKAGE_NAME =
|
||||
(Module['empinyin_files_path'] ? Module['empinyin_files_path'] + '/' : '') +
|
||||
'empinyin_files.data';
|
||||
|
||||
function fetchRemotePackage(packageName, callback, errback) {
|
||||
var xhr = new XMLHttpRequest();
|
||||
xhr.open('GET', packageName, true);
|
||||
xhr.responseType = 'arraybuffer';
|
||||
xhr.onprogress = function(event) {
|
||||
var url = packageName;
|
||||
if (event.loaded && event.total) {
|
||||
if (!xhr.addedTotal) {
|
||||
xhr.addedTotal = true;
|
||||
if (!Module.dataFileDownloads) {
|
||||
Module.dataFileDownloads = {};
|
||||
}
|
||||
Module.dataFileDownloads[url] = {
|
||||
loaded: event.loaded,
|
||||
total: event.total
|
||||
};
|
||||
} else {
|
||||
Module.dataFileDownloads[url].loaded = event.loaded;
|
||||
}
|
||||
var total = 0;
|
||||
var loaded = 0;
|
||||
var num = 0;
|
||||
for (var download in Module.dataFileDownloads) {
|
||||
var data = Module.dataFileDownloads[download];
|
||||
total += data.total;
|
||||
loaded += data.loaded;
|
||||
num++;
|
||||
}
|
||||
total = Math.ceil(total * Module.expectedDataFileDownloads / num);
|
||||
Module['setStatus'](
|
||||
'Downloading data... (' + loaded + '/' + total + ')'
|
||||
);
|
||||
} else if (!Module.dataFileDownloads) {
|
||||
Module['setStatus']('Downloading data...');
|
||||
}
|
||||
};
|
||||
xhr.onload = function(event) {
|
||||
var packageData = xhr.response;
|
||||
callback(packageData);
|
||||
};
|
||||
xhr.send(null);
|
||||
}
|
||||
|
||||
function processPackageData(arrayBuffer) {
|
||||
Module.finishedDataFileDownloads++;
|
||||
assert(arrayBuffer, 'Loading data file failed.');
|
||||
var byteArray = new Uint8Array(arrayBuffer);
|
||||
var curr;
|
||||
|
||||
curr = DataRequest.prototype.requests['data/dict.data'];
|
||||
var data = byteArray.subarray(0, 1068442);
|
||||
var ptr = Module['_malloc'](1068442);
|
||||
Module['HEAPU8'].set(data, ptr);
|
||||
curr.response = Module['HEAPU8'].subarray(ptr, ptr + 1068442);
|
||||
curr.onload();
|
||||
Module['removeRunDependency']('datafile_empinyin_files.data');
|
||||
|
||||
}
|
||||
|
||||
Module['addRunDependency']('datafile_empinyin_files.data');
|
||||
|
||||
function handleError(error) {
|
||||
console.error('package error:', error);
|
||||
}
|
||||
|
||||
if (!Module.preloadResults) {
|
||||
Module.preloadResults = {};
|
||||
}
|
||||
|
||||
Module.preloadResults[PACKAGE_NAME] = {fromCache: false};
|
||||
fetchRemotePackage(REMOTE_PACKAGE_NAME, processPackageData, handleError);
|
||||
});
|
||||
})();
|
||||
|
||||
|
|
@ -0,0 +1,771 @@
|
|||
/* -*- Mode: js; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
|
||||
/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
|
||||
/* global KeyEvent, define, InputMethods */
|
||||
'use strict';
|
||||
|
||||
(function() {
|
||||
var debugging = false;
|
||||
var debug = function jspinyin_debug(str) {
|
||||
if (!debugging) {
|
||||
return;
|
||||
}
|
||||
|
||||
var done = false;
|
||||
if (typeof window != 'undefined' && window.dump) {
|
||||
window.dump('jspinyin: ' + str + '\n');
|
||||
done = true;
|
||||
}
|
||||
if (typeof console != 'undefined' && console.log) {
|
||||
console.log('jspinyin: ' + str);
|
||||
if (arguments.length > 1) {
|
||||
console.log.apply(this, arguments);
|
||||
}
|
||||
done = true;
|
||||
}
|
||||
if (done) {
|
||||
return;
|
||||
}
|
||||
if (typeof Test != 'undefined') {
|
||||
print('jspinyin: ' + str + '\n');
|
||||
}
|
||||
};
|
||||
|
||||
var assert = function jspinyin_assert(condition, msg) {
|
||||
if (!debugging) {
|
||||
return;
|
||||
}
|
||||
if (!condition) {
|
||||
var str = typeof msg === 'undefined' ? assert.caller.toString() : msg;
|
||||
if (typeof alert === 'function') {
|
||||
alert(msg);
|
||||
} else {
|
||||
throw str;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
var IMEngineBase = function engineBase_constructor() {
|
||||
this._glue = {};
|
||||
};
|
||||
|
||||
IMEngineBase.prototype = {
|
||||
/**
|
||||
* Glue ojbect between the IMEngieBase and the IMEManager.
|
||||
*/
|
||||
_glue: {
|
||||
/**
|
||||
* The source code path of the IMEngine
|
||||
* @type String
|
||||
*/
|
||||
path: '',
|
||||
|
||||
/**
|
||||
* Sends candidates to the IMEManager
|
||||
*/
|
||||
sendCandidates: function(candidates) {},
|
||||
|
||||
/**
|
||||
* Sends pending symbols to the IMEManager.
|
||||
*/
|
||||
sendPendingSymbols: function(symbols) {},
|
||||
|
||||
/**
|
||||
* Passes the clicked key to IMEManager for default action.
|
||||
* @param {number} keyCode The key code of an integer.
|
||||
*/
|
||||
sendKey: function(keyCode) {},
|
||||
|
||||
/**
|
||||
* Sends the input string to the IMEManager.
|
||||
* @param {String} str The input string.
|
||||
*/
|
||||
sendString: function(str) {}
|
||||
},
|
||||
|
||||
/**
|
||||
* Initialization.
|
||||
* @param {Glue} glue Glue object of the IMManager.
|
||||
*/
|
||||
init: function engineBase_init(glue) {
|
||||
this._glue = glue;
|
||||
},
|
||||
|
||||
/**
|
||||
* Destruction.
|
||||
*/
|
||||
uninit: function engineBase_uninit() {
|
||||
},
|
||||
|
||||
/**
|
||||
* Notifies when a keyboard key is clicked.
|
||||
* @param {number} keyCode The key code of an integer number.
|
||||
*/
|
||||
click: function engineBase_click(keyCode) {
|
||||
},
|
||||
|
||||
/**
|
||||
* Notifies when pending symbols need be cleared
|
||||
*/
|
||||
empty: function engineBase_empty() {
|
||||
},
|
||||
|
||||
/**
|
||||
* Notifies when a candidate is selected.
|
||||
* @param {String} text The text of the candidate.
|
||||
* @param {Object} data User data of the candidate.
|
||||
*/
|
||||
select: function engineBase_select(text, data) {
|
||||
},
|
||||
|
||||
/**
|
||||
* Notifies when selection changes
|
||||
*/
|
||||
stateChange: function engineBase_stateChange(detail) {
|
||||
},
|
||||
|
||||
/**
|
||||
* Notifies when surrounding text changes
|
||||
*/
|
||||
surroundingtextChange: function engineBase_surroundingtextChange(detail) {
|
||||
},
|
||||
|
||||
/**
|
||||
* Notifies when the IM is shown
|
||||
*/
|
||||
activate: function engineBase_activate(language, state, options) {
|
||||
},
|
||||
|
||||
/**
|
||||
* Called when the keyboard is hidden
|
||||
*/
|
||||
deactivate: function engineBase_deactivate() {
|
||||
}
|
||||
};
|
||||
|
||||
var emEngineWrapper = {
|
||||
_worker: null,
|
||||
_callback: null,
|
||||
_initialized: false,
|
||||
|
||||
post: function(id, param, callback) {
|
||||
if (!this._initialized && id != 'init') {
|
||||
throw 'Database not ready!';
|
||||
}
|
||||
|
||||
if (!this._callback[id]) {
|
||||
this._callback[id] = [];
|
||||
}
|
||||
|
||||
this._callback[id].push(callback);
|
||||
this._worker.postMessage({
|
||||
id: id,
|
||||
param: param
|
||||
});
|
||||
|
||||
return true;
|
||||
},
|
||||
|
||||
init: function(path, byteArray, callback) {
|
||||
if (this._initialized) {
|
||||
callback(true);
|
||||
return;
|
||||
}
|
||||
|
||||
var self = this;
|
||||
|
||||
this._callback = {};
|
||||
this._worker = new Worker(path + '/worker.js');
|
||||
|
||||
this._worker.onmessage = function(e) {
|
||||
var data = e.data;
|
||||
|
||||
switch (data.id) {
|
||||
case 'message':
|
||||
console.log('emEngineWrapper: ' + data.returnValue);
|
||||
break;
|
||||
default:
|
||||
var msgCallback = self._callback[data.id].shift();
|
||||
if (msgCallback) {
|
||||
msgCallback(data.returnValue);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
this.post('init', {
|
||||
userDict: byteArray
|
||||
}, function(isOk) {
|
||||
if (isOk) {
|
||||
self._initialized = true;
|
||||
} else {
|
||||
self.uninit();
|
||||
}
|
||||
callback(isOk);
|
||||
});
|
||||
},
|
||||
|
||||
uninit: function() {
|
||||
if (this._worker) {
|
||||
this._worker.terminate();
|
||||
}
|
||||
this._worker = null;
|
||||
this._callback = null;
|
||||
this._initialized = false;
|
||||
},
|
||||
|
||||
isReady: function() {
|
||||
return this._initialized;
|
||||
}
|
||||
};
|
||||
|
||||
var IMEngine = function engine_constructor() {
|
||||
IMEngineBase.call(this);
|
||||
};
|
||||
|
||||
// We use keycode 65 to represent "'" for pinyin input method
|
||||
var SPECIAL_KEYCODE_FOR_DELIMITER = 65;
|
||||
|
||||
IMEngine.prototype = {
|
||||
// Implements IMEngineBase
|
||||
__proto__: new IMEngineBase(),
|
||||
|
||||
// Buffer limit will force output the longest matching terms
|
||||
// if the length of the syllables buffer is reached.
|
||||
_kBufferLenLimit: 30,
|
||||
|
||||
// Remember the candidate length of last searching result because we don't
|
||||
// want to output all candidates at a time.
|
||||
// Set it to 0 when we don't need the candidates buffer anymore.
|
||||
_candidatesLength: 0,
|
||||
|
||||
_workerTimeout: 600000,
|
||||
|
||||
/**
|
||||
* The last selected text used to generate prediction.
|
||||
* @type string
|
||||
*/
|
||||
_historyText: '',
|
||||
|
||||
_pendingSymbols: '',
|
||||
_firstCandidate: '',
|
||||
_keypressQueue: [],
|
||||
_isWorking: false,
|
||||
|
||||
_isActive: false,
|
||||
_uninitTimer: null,
|
||||
|
||||
_sendPendingSymbols: function engine_sendPendingSymbols() {
|
||||
debug('SendPendingSymbol: ' + this._pendingSymbols);
|
||||
|
||||
if (this._pendingSymbols) {
|
||||
var self = this;
|
||||
|
||||
emEngineWrapper.post(
|
||||
'im_get_pending_symbols_info',
|
||||
{},
|
||||
function(returnValue) {
|
||||
var fixedLen = returnValue.fixedLen;
|
||||
var splStart = returnValue.splStart;
|
||||
var splStartLen = splStart.length;
|
||||
var display = self._firstCandidate.substring(0, fixedLen);
|
||||
|
||||
if (splStartLen > 1) {
|
||||
for (var i = fixedLen; i < splStartLen - 1; i++) {
|
||||
display += self._pendingSymbols.substring(splStart[i],
|
||||
splStart[i + 1]) + ' ';
|
||||
}
|
||||
display +=
|
||||
self._pendingSymbols.substring(splStart[splStartLen - 1]);
|
||||
} else {
|
||||
display += self._pendingSymbols;
|
||||
}
|
||||
|
||||
self._glue.setComposition(display.trim());
|
||||
}
|
||||
);
|
||||
} else {
|
||||
this._glue.endComposition();
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Send candidates list.
|
||||
* @param {Array.<string>} candidates The candidates to be sent.
|
||||
* @return {void} No return value.
|
||||
*/
|
||||
_sendCandidates: function engine_sendCandidates(candidates) {
|
||||
var list = [];
|
||||
var len = candidates.length;
|
||||
for (var id = 0; id < len; id++) {
|
||||
var cand = candidates[id];
|
||||
if (id === 0) {
|
||||
this._firstCandidate = cand;
|
||||
}
|
||||
list.push([cand, id]);
|
||||
}
|
||||
|
||||
this._glue.sendCandidates(list);
|
||||
},
|
||||
|
||||
_start: function engine_start() {
|
||||
if (this._isWorking) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!emEngineWrapper.isReady()) {
|
||||
debug('emEngineWrapper is not ready!');
|
||||
return;
|
||||
}
|
||||
|
||||
this._isWorking = true;
|
||||
debug('Start keyQueue loop.');
|
||||
this._next();
|
||||
},
|
||||
|
||||
_next: function engine_next() {
|
||||
debug('Processing keypress');
|
||||
|
||||
if (!this._keypressQueue.length) {
|
||||
debug('keyQueue emptied.');
|
||||
this._isWorking = false;
|
||||
return;
|
||||
}
|
||||
|
||||
var code = this._keypressQueue.shift();
|
||||
// We use keycode 65 to represent "'" for pinyin input method
|
||||
var realCode = (code === SPECIAL_KEYCODE_FOR_DELIMITER) ? 39 : code;
|
||||
|
||||
if (code === 0) {
|
||||
// This is a select function operation.
|
||||
this._updateCandidatesAndSymbols(this._next.bind(this));
|
||||
return;
|
||||
}
|
||||
|
||||
debug('key code: ' + code);
|
||||
|
||||
// Backspace - delete last input symbol if exists
|
||||
if (code === KeyEvent.DOM_VK_BACK_SPACE) {
|
||||
debug('Backspace key');
|
||||
|
||||
if (!this._pendingSymbols) {
|
||||
if (this._firstCandidate) {
|
||||
debug('Remove candidates.');
|
||||
|
||||
// prevent updateCandidateList from making the same suggestions
|
||||
this.empty();
|
||||
}
|
||||
|
||||
// pass the key to IMEManager for default action
|
||||
debug('Default action.');
|
||||
this._glue.sendKey(realCode);
|
||||
this._next();
|
||||
} else {
|
||||
this._pendingSymbols = this._pendingSymbols.substring(0,
|
||||
this._pendingSymbols.length - 1);
|
||||
|
||||
this._updateCandidatesAndSymbols(this._next.bind(this));
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
// Select the first candidate if needed.
|
||||
if (code === KeyEvent.DOM_VK_RETURN ||
|
||||
!this._isPinyinKey(code) ||
|
||||
this._pendingSymbols.length >= this._kBufferLenLimit) {
|
||||
debug('Non-pinyin key is pressed or the input is too long.');
|
||||
var sendKey = true;
|
||||
if (this._firstCandidate) {
|
||||
if (this._pendingSymbols) {
|
||||
// candidate list exists; output the first candidate
|
||||
debug('Sending first candidate.');
|
||||
this._glue.endComposition(this._firstCandidate);
|
||||
// no return here
|
||||
if (code === KeyEvent.DOM_VK_RETURN) {
|
||||
sendKey = false;
|
||||
}
|
||||
}
|
||||
this._sendCandidates([]);
|
||||
}
|
||||
|
||||
//pass the key to IMEManager for default action
|
||||
debug('Default action.');
|
||||
this.empty();
|
||||
if (sendKey) {
|
||||
this._glue.sendKey(realCode);
|
||||
}
|
||||
this._next();
|
||||
return;
|
||||
}
|
||||
|
||||
debug('Processing symbol: ' + String.fromCharCode(realCode));
|
||||
|
||||
// add symbol to pendingSymbols
|
||||
this._appendNewSymbol(realCode);
|
||||
this._updateCandidatesAndSymbols(this._next.bind(this));
|
||||
},
|
||||
|
||||
_isPinyinKey: function engine_isPinyinKey(code) {
|
||||
// keycode 65 is used to represent "'" for pinyin input method
|
||||
// a-z
|
||||
if ((code >= 97 && code <= 122) ||
|
||||
code === SPECIAL_KEYCODE_FOR_DELIMITER) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
},
|
||||
|
||||
_appendNewSymbol: function engine_appendNewSymbol(code) {
|
||||
var symbol = String.fromCharCode(code);
|
||||
this._pendingSymbols += symbol;
|
||||
},
|
||||
|
||||
_updateCandidatesAndSymbols: function engine_updateCandsAndSymbols(callback) {
|
||||
var self = this;
|
||||
this._updateCandidateList(function() {
|
||||
self._sendPendingSymbols();
|
||||
callback();
|
||||
});
|
||||
},
|
||||
|
||||
_updateCandidateList: function engine_updateCandidateList(callback) {
|
||||
debug('Update Candidate List.');
|
||||
|
||||
var self = this;
|
||||
var numberOfCandidatesPerRow = this._glue.getNumberOfCandidatesPerRow ?
|
||||
this._glue.getNumberOfCandidatesPerRow() : Number.Infinity;
|
||||
|
||||
this._candidatesLength = 0;
|
||||
|
||||
if (!this._pendingSymbols) {
|
||||
// If there is no pending symbols, make prediction with the previous
|
||||
// select words.
|
||||
if (this._historyText) {
|
||||
debug('Buffer is empty; make suggestions based on select term.');
|
||||
|
||||
emEngineWrapper.post('im_search_predicts', {
|
||||
queryString: this._historyText,
|
||||
limit: numberOfCandidatesPerRow + 1
|
||||
}, function(returnValue) {
|
||||
var num = returnValue.length;
|
||||
var predicts = returnValue.results;
|
||||
|
||||
if (num > numberOfCandidatesPerRow + 1) {
|
||||
self._candidatesLength = num;
|
||||
}
|
||||
|
||||
self._sendCandidates(predicts);
|
||||
callback();
|
||||
});
|
||||
} else {
|
||||
this._sendCandidates([]);
|
||||
callback();
|
||||
}
|
||||
} else {
|
||||
// Update the candidates list by the pending pinyin string.
|
||||
this._historyText = '';
|
||||
|
||||
emEngineWrapper.post('im_search', {
|
||||
queryString: this._pendingSymbols,
|
||||
limit: numberOfCandidatesPerRow + 1
|
||||
}, function(returnValue) {
|
||||
var num = returnValue.length;
|
||||
var candidates = returnValue.results;
|
||||
|
||||
if (num > numberOfCandidatesPerRow + 1) {
|
||||
self._candidatesLength = num;
|
||||
}
|
||||
|
||||
self._sendCandidates(candidates);
|
||||
callback();
|
||||
});
|
||||
}
|
||||
},
|
||||
|
||||
_resetKeypressQueue: function engine_abortKeypressQueue() {
|
||||
this._keypressQueue = [];
|
||||
this._isWorking = false;
|
||||
},
|
||||
|
||||
_accessUserDict: function engine_loadUserDict(action, param, callback) {
|
||||
var indexedDB = window.indexedDB;
|
||||
|
||||
if (!indexedDB) {
|
||||
callback(null);
|
||||
return;
|
||||
}
|
||||
|
||||
// Access user_dict.data from IndexedDB
|
||||
var dbVersion = 1;
|
||||
var STORE_NAME = 'files';
|
||||
var USER_DICT = 'user_dict';
|
||||
|
||||
var request = indexedDB.open('EmpinyinDatabase', dbVersion);
|
||||
|
||||
request.onerror = function opendb_onerror(event) {
|
||||
debug('Error occurs when openning database: ' + event.target.errorCode);
|
||||
callback(null);
|
||||
};
|
||||
|
||||
request.onsuccess = function opendb_onsuccess(event) {
|
||||
var db = event.target.result;
|
||||
var request;
|
||||
|
||||
if (action == 'load') {
|
||||
request = db.transaction([STORE_NAME], 'readonly')
|
||||
.objectStore(STORE_NAME).get(USER_DICT);
|
||||
|
||||
request.onsuccess = function readdb_oncomplete(event) {
|
||||
db.close();
|
||||
if (!event.target.result) {
|
||||
callback(null);
|
||||
} else {
|
||||
callback(event.target.result.content);
|
||||
}
|
||||
};
|
||||
|
||||
request.onerror = function readdb_oncomplete(event) {
|
||||
debug('Failed to read file from DB: ' + event.target.result.name);
|
||||
db.close();
|
||||
callback(null);
|
||||
};
|
||||
} else if (action == 'save') {
|
||||
var obj = {
|
||||
name: USER_DICT,
|
||||
content: param
|
||||
};
|
||||
|
||||
request = db.transaction([STORE_NAME], 'readwrite')
|
||||
.objectStore(STORE_NAME).put(obj);
|
||||
|
||||
request.onsuccess = function readdb_oncomplete(event) {
|
||||
db.close();
|
||||
callback(true);
|
||||
};
|
||||
|
||||
request.onerror = function readdb_oncomplete(event) {
|
||||
debug('Failed to write file to DB: ' + event.target.result.name);
|
||||
db.close();
|
||||
callback(false);
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
request.onupgradeneeded = function opendb_onupgradeneeded(event) {
|
||||
var db = event.target.result;
|
||||
|
||||
// Delete the old ObjectStore if present
|
||||
if (db.objectStoreNames.length !== 0) {
|
||||
db.deleteObjectStore(STORE_NAME);
|
||||
}
|
||||
|
||||
db.createObjectStore(STORE_NAME, { keyPath: 'name' });
|
||||
};
|
||||
},
|
||||
|
||||
/**
|
||||
* Override
|
||||
*/
|
||||
init: function engine_init(glue) {
|
||||
IMEngineBase.prototype.init.call(this, glue);
|
||||
debug('init.');
|
||||
},
|
||||
|
||||
/**
|
||||
* Override
|
||||
*/
|
||||
uninit: function engine_uninit() {
|
||||
IMEngineBase.prototype.uninit.call(this);
|
||||
debug('Uninit.');
|
||||
|
||||
if (this._uninitTimer) {
|
||||
clearTimeout(this._uninitTimer);
|
||||
this._uninitTimer = null;
|
||||
}
|
||||
|
||||
if (emEngineWrapper.isReady()) {
|
||||
emEngineWrapper.uninit();
|
||||
}
|
||||
|
||||
this._resetKeypressQueue();
|
||||
this.empty();
|
||||
},
|
||||
|
||||
/**
|
||||
*Override
|
||||
*/
|
||||
click: function engine_click(keyCode) {
|
||||
IMEngineBase.prototype.click.call(this, keyCode);
|
||||
|
||||
this._keypressQueue.push(keyCode);
|
||||
this._start();
|
||||
},
|
||||
|
||||
/**
|
||||
* Override
|
||||
*/
|
||||
select: function engine_select(text, data) {
|
||||
IMEngineBase.prototype.select.call(this, text, data);
|
||||
|
||||
if (!emEngineWrapper.isReady()) {
|
||||
return;
|
||||
}
|
||||
|
||||
var self = this;
|
||||
var nextStep = function(text) {
|
||||
if (text) {
|
||||
if (self._pendingSymbols) {
|
||||
self._pendingSymbols = '';
|
||||
self._glue.endComposition(text);
|
||||
} else {
|
||||
self._glue.setComposition('');
|
||||
self._glue.endComposition(text);
|
||||
}
|
||||
self._historyText = text;
|
||||
self._candidatesLength = 0;
|
||||
}
|
||||
self._keypressQueue.push(0);
|
||||
self._start();
|
||||
};
|
||||
|
||||
if (this._pendingSymbols) {
|
||||
emEngineWrapper.post('im_choose', {
|
||||
candId: parseInt(data)
|
||||
}, nextStep);
|
||||
} else {
|
||||
// A predication candidate is selected.
|
||||
nextStep(text);
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Override
|
||||
*/
|
||||
empty: function engine_empty() {
|
||||
IMEngineBase.prototype.empty.call(this);
|
||||
debug('empty.');
|
||||
this._pendingSymbols = '';
|
||||
this._historyText = '';
|
||||
this._firstCandidate = '';
|
||||
this._sendPendingSymbols();
|
||||
this._sendCandidates([]);
|
||||
},
|
||||
|
||||
/**
|
||||
* Override
|
||||
*/
|
||||
stateChange: function engine_stateChange(detail) {
|
||||
debug('stateChange');
|
||||
|
||||
if (detail.ownAction) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.empty();
|
||||
},
|
||||
|
||||
/**
|
||||
* Override
|
||||
*/
|
||||
activate: function engine_activate(language, state, options) {
|
||||
IMEngineBase.prototype.activate.call(this, language, state, options);
|
||||
|
||||
if (this._uninitTimer) {
|
||||
clearTimeout(this._uninitTimer);
|
||||
this._uninitTimer = null;
|
||||
}
|
||||
|
||||
var inputType = state.type;
|
||||
debug('Activate. Input type: ' + inputType);
|
||||
|
||||
|
||||
if (!emEngineWrapper.isReady()) {
|
||||
var self = this;
|
||||
this._accessUserDict('load', null, function(byteArray) {
|
||||
emEngineWrapper.init(self._glue.path, byteArray, function(isOk) {
|
||||
if (isOk) {
|
||||
self._start();
|
||||
} else {
|
||||
debug('emEngineWrapper initialize failed!!');
|
||||
}
|
||||
});
|
||||
});
|
||||
} else {
|
||||
emEngineWrapper.post('im_flush_cache', {}, null);
|
||||
}
|
||||
|
||||
this._isActive = true;
|
||||
},
|
||||
|
||||
/**
|
||||
* Override
|
||||
*/
|
||||
deactivate: function engine_deactivate() {
|
||||
IMEngineBase.prototype.deactivate.call(this);
|
||||
debug('Deactivate.');
|
||||
|
||||
if (!this._isActive) {
|
||||
return;
|
||||
}
|
||||
|
||||
this._isActive = false;
|
||||
|
||||
this._resetKeypressQueue();
|
||||
this.empty();
|
||||
|
||||
var self = this;
|
||||
emEngineWrapper.post('im_get_user_dict_data', {}, function(byteArray) {
|
||||
if (byteArray) {
|
||||
self._accessUserDict('save', byteArray, function(isOk) {
|
||||
if (isOk) {
|
||||
debug('Saved user dictionary to DB.');
|
||||
} else {
|
||||
debug('Failed to save user dictionary to DB.');
|
||||
}
|
||||
|
||||
if (!self._uninitTimer) {
|
||||
self._uninitTimer =
|
||||
setTimeout(self.uninit.bind(self), self._workerTimeout);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
},
|
||||
|
||||
getMoreCandidates: function engine_getMore(indicator, maxCount, callback) {
|
||||
if (this._candidatesLength === 0) {
|
||||
callback(null);
|
||||
return;
|
||||
}
|
||||
|
||||
var num = this._candidatesLength;
|
||||
maxCount = Math.min((maxCount || num) + indicator, num);
|
||||
|
||||
var msgId = this._pendingSymbols ? 'im_get_candidates' : 'im_get_predicts';
|
||||
|
||||
emEngineWrapper.post(msgId, {
|
||||
start: indicator,
|
||||
count: maxCount
|
||||
}, function(results) {
|
||||
var len = results.length;
|
||||
var list = [];
|
||||
for (var i = 0; i < len; i++) {
|
||||
list.push([results[i], i + indicator]);
|
||||
}
|
||||
callback(list);
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
var jspinyin = new IMEngine();
|
||||
|
||||
// Expose jspinyin as an AMD module
|
||||
if (typeof define === 'function' && define.amd) {
|
||||
define('jspinyin', [], function() { return jspinyin; });
|
||||
}
|
||||
|
||||
// Expose the engine to the Gaia keyboard
|
||||
if (typeof InputMethods !== 'undefined') {
|
||||
InputMethods.jspinyin = jspinyin;
|
||||
}
|
||||
})();
|
||||
28531
assets/webapps/keyboard.gaiamobile.org/js/imes/jspinyin/libpinyin.js
Normal file
28531
assets/webapps/keyboard.gaiamobile.org/js/imes/jspinyin/libpinyin.js
Normal file
File diff suppressed because one or more lines are too long
|
|
@ -0,0 +1,26 @@
|
|||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1">
|
||||
<meta charset="UTF-8">
|
||||
<title>Emscripten Pinyin Engine Test</title>
|
||||
<link rel="stylesheet" type="text/css" href="style.css">
|
||||
</head>
|
||||
<body>
|
||||
<h1>Emscripten Pinyin Engine Test</h1>
|
||||
|
||||
<section>
|
||||
<p><input type="text" value="z" id="pinyin"></p>
|
||||
<p>
|
||||
<input type="button" value="test" id="test">
|
||||
<input type="button" value="test x n" id="test2">
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<div id="status"></div>
|
||||
<div id="log"></div>
|
||||
|
||||
<script type="text/javascript" src="init.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
|
|
@ -0,0 +1,192 @@
|
|||
'use strict';
|
||||
|
||||
const testRepeatCount = 10;
|
||||
|
||||
var emEngineWrapper = {
|
||||
_worker: null,
|
||||
_callback: null,
|
||||
_initialized: false,
|
||||
|
||||
post: function(id, param, callback) {
|
||||
if (!this._initialized && id != 'init') {
|
||||
throw 'Database not ready!';
|
||||
}
|
||||
|
||||
if (!this._callback[id]) {
|
||||
this._callback[id] = [];
|
||||
}
|
||||
|
||||
this._callback[id].push(callback);
|
||||
this._worker.postMessage({
|
||||
id: id,
|
||||
param: param
|
||||
});
|
||||
|
||||
return true;
|
||||
},
|
||||
|
||||
init: function(path, byteArray, callback) {
|
||||
if (this._initialized) {
|
||||
callback(true);
|
||||
}
|
||||
|
||||
var self = this;
|
||||
|
||||
this._callback = {};
|
||||
this._worker = new Worker(path + '/worker.js');
|
||||
|
||||
this._worker.onmessage = function(e) {
|
||||
var data = e.data;
|
||||
|
||||
switch (data.id) {
|
||||
case 'message':
|
||||
console.log('emEngineWrapper: ' + data.returnValue);
|
||||
break;
|
||||
default:
|
||||
var msgCallback = self._callback[data.id].shift();
|
||||
if (msgCallback) {
|
||||
msgCallback(data.returnValue);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
this.post('init', {
|
||||
userDict: byteArray
|
||||
}, function(isOk) {
|
||||
if (isOk) {
|
||||
self._initialized = true;
|
||||
} else {
|
||||
self.uninit();
|
||||
}
|
||||
callback(isOk);
|
||||
});
|
||||
},
|
||||
|
||||
uninit: function() {
|
||||
if (this._worker) {
|
||||
this._worker.terminate();
|
||||
}
|
||||
this._worker = null;
|
||||
this._callback = null;
|
||||
this._initialized = false;
|
||||
},
|
||||
|
||||
isReady: function() {
|
||||
return this._initialized;
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener('load', function() {
|
||||
document.getElementById('status').textContent =
|
||||
'NOTE: please copy "../empinyin_files.*", "../libpinyin.js" and ' +
|
||||
'"worker.js" to this "tests" folder first.';
|
||||
document.getElementById('test2').value = 'test x ' + testRepeatCount;
|
||||
|
||||
emEngineWrapper.init('.', null, function(isOk) {
|
||||
if (isOk) {
|
||||
document.getElementById('status').textContent = '';
|
||||
log('Engine ready!');
|
||||
initTest();
|
||||
} else {
|
||||
log('Load data failed!');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
function log(msg) {
|
||||
var date = new Date();
|
||||
var loggerTime = date.getHours() + ':' + date.getMinutes() + ':' +
|
||||
date.getSeconds() + ':' + date.getMilliseconds();
|
||||
|
||||
var divLog = document.getElementById('log');
|
||||
var p = document.createElement('p');
|
||||
p.innerHTML = loggerTime + ' : ' + msg;
|
||||
divLog.insertBefore(p, divLog.firstChild);
|
||||
}
|
||||
|
||||
function initTest() {
|
||||
document.getElementById('test').onclick = function() {
|
||||
var keyword = document.getElementById('pinyin').value;
|
||||
|
||||
try {
|
||||
log('search keyword ' + keyword);
|
||||
|
||||
var startTime = new Date().getTime();
|
||||
|
||||
emEngineWrapper.post('im_search', {
|
||||
queryString: keyword,
|
||||
limit: -1
|
||||
}, function(returnValue) {
|
||||
var endTime = new Date().getTime();
|
||||
|
||||
log('total cost: ' + (endTime - startTime) + 'ms');
|
||||
|
||||
var size = returnValue.length;
|
||||
var candidates = returnValue.results;
|
||||
|
||||
log('length: ' + size);
|
||||
log('Candidates: ' + candidates.join(' '));
|
||||
|
||||
emEngineWrapper.post('im_choose', {
|
||||
candId: 0
|
||||
}, function(convertedText) {
|
||||
log('Choose: ' + convertedText);
|
||||
|
||||
if (convertedText) {
|
||||
startTime = new Date().getTime();
|
||||
|
||||
emEngineWrapper.post('im_search_predicts', {
|
||||
queryString: convertedText,
|
||||
limit: -1
|
||||
}, function(returnValue) {
|
||||
endTime = new Date().getTime();
|
||||
|
||||
log('total cost: ' + (endTime - startTime) + 'ms');
|
||||
|
||||
var nPredicts = returnValue.length;
|
||||
var predicts = returnValue.results;
|
||||
|
||||
log('length: ' + nPredicts);
|
||||
log('Predicts: ' + predicts.join(' '));
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
} catch (e) {
|
||||
log('error: ' + e);
|
||||
}
|
||||
};
|
||||
|
||||
document.getElementById('test2').onclick = function() {
|
||||
var keyword = document.getElementById('pinyin').value;
|
||||
|
||||
try {
|
||||
log('search ' + testRepeatCount + ' times keyword ' + keyword);
|
||||
|
||||
var startTime = new Date().getTime();
|
||||
var counter = 0;
|
||||
|
||||
var doTest = function() {
|
||||
emEngineWrapper.post('im_search', {
|
||||
queryString: keyword,
|
||||
limit: -1
|
||||
}, function(returnValue) {
|
||||
if (++counter == testRepeatCount) {
|
||||
var endTime = new Date().getTime();
|
||||
var period = endTime - startTime;
|
||||
|
||||
log('total cost: ' + period + 'ms');
|
||||
log('average cost: ' + (period / testRepeatCount) + 'ms');
|
||||
log('length: ' + returnValue.length);
|
||||
} else {
|
||||
doTest();
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
doTest();
|
||||
} catch (e) {
|
||||
log('error: ' + e);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
|
@ -0,0 +1,22 @@
|
|||
input[type="text"] {
|
||||
font-size: 1.5rem;
|
||||
width: 18rem;
|
||||
}
|
||||
|
||||
button, input[type="button"] {
|
||||
width: 9rem;
|
||||
height: 2.5rem;
|
||||
font-size: 1.5rem;
|
||||
}
|
||||
|
||||
#log, #status {
|
||||
margin-top: 1rem;
|
||||
}
|
||||
|
||||
#output {
|
||||
margin-top: 1rem;
|
||||
}
|
||||
|
||||
p {
|
||||
margin: 0.3rem;
|
||||
}
|
||||
|
|
@ -0,0 +1,175 @@
|
|||
/* -*- Mode: js; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
|
||||
/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
|
||||
/* jshint sub: true */
|
||||
'use strict';
|
||||
|
||||
var Module;
|
||||
var emEngine;
|
||||
var procFunction;
|
||||
|
||||
self.onmessage = function(e) {
|
||||
var data = e.data;
|
||||
|
||||
if (data.id == 'init') {
|
||||
initModule(data.id, data.param);
|
||||
} else if (procFunction[data.id]) {
|
||||
var result = procFunction[data.id](data.param);
|
||||
post(data.id, result);
|
||||
} else {
|
||||
log('echo: ' + JSON.stringify(e.data));
|
||||
}
|
||||
};
|
||||
|
||||
function initModule(msgId, param) {
|
||||
Module = {
|
||||
canvas: {},
|
||||
stdout: null,
|
||||
setStatus: log,
|
||||
preRun: [function() {
|
||||
if (param.userDict) {
|
||||
Module['addRunDependency']('fp data/user_dict.data');
|
||||
Module['FS_createPreloadedFile'](
|
||||
'/data', 'user_dict.data', param.userDict, true, true, function() {
|
||||
Module['removeRunDependency']('fp data/user_dict.data');
|
||||
});
|
||||
}
|
||||
}],
|
||||
_main: function() {
|
||||
emEngine = {
|
||||
openDecoder:
|
||||
Module.cwrap('im_open_decoder', 'number', ['string', 'string']),
|
||||
closeDecoder:
|
||||
Module.cwrap('im_close_decoder', '', []),
|
||||
search:
|
||||
Module.cwrap('im_search', 'number', ['string', 'number']),
|
||||
resetSearch:
|
||||
Module.cwrap('im_reset_search', '', []),
|
||||
getCandidateAt:
|
||||
Module.cwrap('im_get_candidate_char', 'string', ['number']),
|
||||
getPredicts:
|
||||
Module.cwrap('im_get_predicts_utf8', 'number', ['string', 'number']),
|
||||
getPredictAt:
|
||||
Module.cwrap('im_get_predict_at', 'string', ['number']),
|
||||
choose:
|
||||
Module.cwrap('im_choose', 'number', ['number']),
|
||||
getSplStart:
|
||||
Module.cwrap('im_get_spl_start', 'number', []),
|
||||
getSplStartAt:
|
||||
Module.cwrap('im_get_spl_start_at', 'number', ['number']),
|
||||
getFixedLen:
|
||||
Module.cwrap('im_get_fixed_len', 'number', []),
|
||||
flushCache:
|
||||
Module.cwrap('im_flush_cache', '', [])
|
||||
};
|
||||
|
||||
if (emEngine.openDecoder('data/dict.data', 'data/user_dict.data')) {
|
||||
initProcFunctions();
|
||||
post(msgId, true);
|
||||
} else {
|
||||
post(msgId, false);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
try {
|
||||
importScripts('empinyin_files.js');
|
||||
importScripts('libpinyin.js');
|
||||
} catch (e) {
|
||||
log(e.toString());
|
||||
post(msgId, false);
|
||||
}
|
||||
}
|
||||
|
||||
function initProcFunctions() {
|
||||
var getSearchResult = function(emEngineGetAt, param) {
|
||||
var start = param.start;
|
||||
var count = param.count;
|
||||
var results = [];
|
||||
for (var i = start; i < count; i++) {
|
||||
results.push(emEngineGetAt(i));
|
||||
}
|
||||
return results;
|
||||
};
|
||||
|
||||
var search = function(emEngineSearch, emEngineGetAt, param) {
|
||||
var query = param.queryString;
|
||||
var numberToReturn = param.limit;
|
||||
var resultLen = emEngineSearch(query, query.length);
|
||||
var results;
|
||||
if (numberToReturn) {
|
||||
if (numberToReturn < 0 || numberToReturn > resultLen) {
|
||||
numberToReturn = resultLen;
|
||||
}
|
||||
results = getSearchResult(emEngineGetAt, {
|
||||
start: 0,
|
||||
count: numberToReturn
|
||||
});
|
||||
}
|
||||
return {
|
||||
length: resultLen,
|
||||
results: results
|
||||
};
|
||||
};
|
||||
|
||||
procFunction = {};
|
||||
|
||||
/*jshint -W040 */
|
||||
procFunction['im_search'] =
|
||||
search.bind(this, emEngine.search, emEngine.getCandidateAt);
|
||||
|
||||
procFunction['im_get_candidates'] =
|
||||
getSearchResult.bind(this, emEngine.getCandidateAt);
|
||||
|
||||
procFunction['im_search_predicts'] =
|
||||
search.bind(this, emEngine.getPredicts, emEngine.getPredictAt);
|
||||
|
||||
procFunction['im_get_predicts'] =
|
||||
getSearchResult.bind(this, emEngine.getPredictAt);
|
||||
/*jshint +W040 */
|
||||
|
||||
procFunction['im_flush_cache'] =
|
||||
emEngine.flushCache;
|
||||
|
||||
procFunction['im_choose'] = function(param) {
|
||||
var candsNum = emEngine.choose(param.candId);
|
||||
if (candsNum == 1 && emEngine.getFixedLen() == emEngine.getSplStart()) {
|
||||
var convertedText = emEngine.getCandidateAt(0);
|
||||
emEngine.resetSearch();
|
||||
return convertedText;
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
procFunction['im_get_pending_symbols_info'] = function() {
|
||||
var fixedLen = emEngine.getFixedLen();
|
||||
var splStartLen = emEngine.getSplStart();
|
||||
var splStart = [];
|
||||
for (var i = 0; i <= splStartLen; i++) {
|
||||
splStart.push(emEngine.getSplStartAt(i));
|
||||
}
|
||||
return {
|
||||
fixedLen: fixedLen,
|
||||
splStart: splStart
|
||||
};
|
||||
};
|
||||
|
||||
procFunction['im_get_user_dict_data'] = function() {
|
||||
if (!Module['FS']) {
|
||||
return null;
|
||||
}
|
||||
|
||||
emEngine.flushCache();
|
||||
return Module['FS'].findObject('data/user_dict.data').contents;
|
||||
};
|
||||
}
|
||||
|
||||
function post(id, returnValue) {
|
||||
postMessage({
|
||||
id: id,
|
||||
returnValue: returnValue
|
||||
});
|
||||
}
|
||||
|
||||
function log(message) {
|
||||
post('message', message);
|
||||
}
|
||||
|
|
@ -0,0 +1,488 @@
|
|||
/* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
|
||||
|
||||
/* global InputMethods */
|
||||
|
||||
(function() {
|
||||
'use strict';
|
||||
|
||||
/* BoGo Engine. https://github.com/lewtds/bogo.js
|
||||
*
|
||||
* Copyright 2014, Trung Ngo <ndtrung4419@gmail.com>
|
||||
*
|
||||
* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
|
||||
function BoGo() {
|
||||
var EffectType = {
|
||||
APPENDING: 0,
|
||||
MARK: 1,
|
||||
TONE: 2
|
||||
};
|
||||
|
||||
var Mark = {
|
||||
NONE: 0,
|
||||
HAT: 1,
|
||||
BREVE: 2,
|
||||
HORN: 3,
|
||||
DASH: 4
|
||||
};
|
||||
|
||||
var Tone = {
|
||||
NONE: 0,
|
||||
GRAVE: 1,
|
||||
ACUTE: 2,
|
||||
HOOK: 3,
|
||||
TILDE: 4,
|
||||
DOT: 5
|
||||
};
|
||||
|
||||
var VOWELS = 'aàáảãạăằắẳẵặâầấẩẫậeèéẻẽẹêềếểễệiìíỉĩị' +
|
||||
'oòóỏõọôồốổỗộơờớởỡợuùúủũụưừứửữựyỳýỷỹỵ';
|
||||
|
||||
var composition = [];
|
||||
var rules = [];
|
||||
|
||||
var MARKS_MAP = {
|
||||
'a': 'aâă__',
|
||||
'â': 'aâă__',
|
||||
'ă': 'aâă__',
|
||||
'e': 'eê___',
|
||||
'ê': 'eê___',
|
||||
'o': 'oô_ơ_',
|
||||
'ô': 'oô_ơ_',
|
||||
'ơ': 'oô_ơ_',
|
||||
'u': 'u__ư_',
|
||||
'ư': 'u__ư_',
|
||||
'd': 'd___đ',
|
||||
'đ': 'd___đ'
|
||||
};
|
||||
|
||||
var MARK_CHARS = {
|
||||
'^': Mark.HAT,
|
||||
'(': Mark.BREVE,
|
||||
'+': Mark.HORN,
|
||||
'-': Mark.DASH
|
||||
};
|
||||
|
||||
var TONE_CHARS = {
|
||||
'~': Tone.TILDE,
|
||||
'\'': Tone.ACUTE,
|
||||
'?': Tone.HOOK,
|
||||
'`': Tone.GRAVE,
|
||||
'.': Tone.DOT
|
||||
};
|
||||
|
||||
function is_vowel(chr) {
|
||||
return VOWELS.indexOf(chr) != -1;
|
||||
}
|
||||
|
||||
function add_mark_to_char(chr, mark) {
|
||||
var result;
|
||||
var tone = get_tone_from_char(chr);
|
||||
chr = add_tone_to_char(chr, Tone.NONE);
|
||||
|
||||
if (chr in MARKS_MAP && MARKS_MAP[chr][mark] != '_') {
|
||||
result = MARKS_MAP[chr][mark];
|
||||
} else {
|
||||
result = chr;
|
||||
}
|
||||
|
||||
result = add_tone_to_char(result, tone);
|
||||
return result;
|
||||
}
|
||||
|
||||
function get_tone_from_char(chr) {
|
||||
var position = VOWELS.indexOf(chr);
|
||||
if (position != -1) {
|
||||
return position % 6;
|
||||
} else {
|
||||
return Tone.NONE;
|
||||
}
|
||||
}
|
||||
|
||||
function add_tone_to_char(chr, tone) {
|
||||
var result;
|
||||
var position = VOWELS.indexOf(chr);
|
||||
|
||||
if (position != -1) {
|
||||
var current_tone = position % 6;
|
||||
var offset = tone - current_tone;
|
||||
result = VOWELS[position + offset];
|
||||
} else {
|
||||
result = chr;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function find_mark_target(rule) {
|
||||
var target;
|
||||
for (var i = composition.length - 1; i > -1; i--) {
|
||||
if (composition[i].rule.key == rule.effective_on) {
|
||||
target = composition[i];
|
||||
}
|
||||
}
|
||||
return target;
|
||||
}
|
||||
|
||||
function find_rightmost_vowels() {
|
||||
var vowels = [];
|
||||
for (var i = composition.length - 1; i >= 0; i--) {
|
||||
var trans = composition[i];
|
||||
|
||||
if (trans.rule.type == EffectType.APPENDING &&
|
||||
is_vowel(trans.rule.key)) {
|
||||
vowels.unshift(trans);
|
||||
}
|
||||
}
|
||||
return vowels;
|
||||
}
|
||||
|
||||
function find_next_appending_trans(trans) {
|
||||
var from_index = composition.indexOf(trans);
|
||||
var next_appending_trans;
|
||||
|
||||
// FIXME: Need not-found guard.
|
||||
for (var i = from_index + 1; i < composition.length; i++) {
|
||||
if (composition[i].rule.type == EffectType.APPENDING) {
|
||||
next_appending_trans = composition[i];
|
||||
}
|
||||
}
|
||||
|
||||
return next_appending_trans;
|
||||
}
|
||||
|
||||
function find_tone_target(rule) {
|
||||
var vowels = find_rightmost_vowels();
|
||||
var target;
|
||||
|
||||
if (vowels.length == 1) {
|
||||
// cá
|
||||
target = vowels[0];
|
||||
} else if (vowels.length == 2) {
|
||||
if (find_next_appending_trans(vowels[1]) !== undefined ||
|
||||
flatten(vowels) == 'uo') {
|
||||
// nước, thuở
|
||||
target = vowels[1];
|
||||
} else {
|
||||
// cáo
|
||||
target = vowels[0];
|
||||
}
|
||||
} else if (vowels.length == 3) {
|
||||
if (flatten(vowels) == 'uye') {
|
||||
// chuyển
|
||||
target = vowels[2];
|
||||
} else {
|
||||
// khuỷu
|
||||
target = vowels[1];
|
||||
}
|
||||
}
|
||||
|
||||
return target;
|
||||
}
|
||||
|
||||
function refresh_last_tone_target() {
|
||||
// Refresh the tone position of the last EffectType.TONE transformation.
|
||||
for (var i = composition.length - 1; i >= 0; i--) {
|
||||
var trans = composition[i];
|
||||
if (trans.rule.type == EffectType.TONE) {
|
||||
var new_target = find_tone_target(trans.rule);
|
||||
trans.target = new_target;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function process_char(chr) {
|
||||
var isUpperCase = chr === chr.toUpperCase();
|
||||
chr = chr.toLowerCase();
|
||||
|
||||
var applicable_rules = [];
|
||||
rules.forEach(function(rule) {
|
||||
if (rule.key == chr) {
|
||||
applicable_rules.push(rule);
|
||||
}
|
||||
});
|
||||
|
||||
// If none of the applicable_rules can actually be applied then this new
|
||||
// transformation fallbacks to an APPENDING one.
|
||||
var trans = {
|
||||
rule: {
|
||||
type: EffectType.APPENDING,
|
||||
key: chr
|
||||
},
|
||||
isUpperCase: isUpperCase
|
||||
};
|
||||
|
||||
for (var i = 0; i < applicable_rules.length; i++) {
|
||||
var rule = applicable_rules[i];
|
||||
var target;
|
||||
|
||||
if (rule.type == EffectType.MARK) {
|
||||
target = find_mark_target(rule);
|
||||
} else if (rule.type == EffectType.TONE) {
|
||||
target = find_tone_target(rule);
|
||||
}
|
||||
|
||||
if (target !== undefined) {
|
||||
// Fix uaw being wrongly processed to muă by skipping
|
||||
// the aw rule. Then the uw rule will be matched later.
|
||||
// Note that this requires the aw rule be placed before
|
||||
// uw in the rule list.
|
||||
if (chr == 'w') {
|
||||
var target_index = composition.indexOf(target);
|
||||
var prev_trans = composition[target_index - 1];
|
||||
if (target.rule.key == 'a' &&
|
||||
prev_trans.rule.key == 'u') {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
trans.rule = rule;
|
||||
trans.target = target;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
composition.push(trans);
|
||||
|
||||
// Implement the uow typing shortcut by creating a virtual
|
||||
// Mark.HORN rule that targets 'u'.
|
||||
//
|
||||
// FIXME: This is a potential slowdown. Perhaps it should be
|
||||
// toggled by a config key.
|
||||
if (flatten().match(/uơ.+$/)) {
|
||||
var vowels = find_rightmost_vowels();
|
||||
var virtual_trans = {
|
||||
rule: {
|
||||
type: EffectType.MARK,
|
||||
key: '', // This is a virtual rule,
|
||||
// it should not appear in the raw string.
|
||||
effect: Mark.HORN
|
||||
},
|
||||
target: vowels[0]
|
||||
};
|
||||
|
||||
composition.push(virtual_trans);
|
||||
}
|
||||
|
||||
// Sometimes, a tone's position in a previous state must be changed to
|
||||
// fit the new state.
|
||||
//
|
||||
// e.g.
|
||||
// prev state: chuyenr -> chuỷen
|
||||
// this state: chuyenre -> chuyển
|
||||
if (trans.rule.type == EffectType.APPENDING) {
|
||||
refresh_last_tone_target();
|
||||
}
|
||||
}
|
||||
|
||||
function flatten() {
|
||||
var canvas = [];
|
||||
|
||||
composition.forEach(function(trans, index) {
|
||||
|
||||
function apply_effect(func, trans) {
|
||||
var index = trans.target.dest;
|
||||
var char_with_effect = func(canvas[index], trans.rule.effect);
|
||||
|
||||
// Double typing an effect key undoes it. Btw, we're playing
|
||||
// fast-and-loose here by relying on the fact that Tone.NONE
|
||||
// equals Mark.None and equals 0.
|
||||
if (char_with_effect == canvas[index]) {
|
||||
canvas[index] = func(canvas[index], Tone.NONE);
|
||||
} else {
|
||||
canvas[index] = char_with_effect;
|
||||
}
|
||||
}
|
||||
|
||||
switch (trans.rule.type) {
|
||||
case EffectType.APPENDING:
|
||||
trans.dest = canvas.length;
|
||||
canvas.push(trans.rule.key);
|
||||
break;
|
||||
case EffectType.MARK:
|
||||
apply_effect(add_mark_to_char, trans);
|
||||
break;
|
||||
case EffectType.TONE:
|
||||
apply_effect(add_tone_to_char, trans);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
});
|
||||
|
||||
composition.forEach(function(trans) {
|
||||
if (trans.rule.type == EffectType.APPENDING) {
|
||||
if (trans.isUpperCase) {
|
||||
canvas[trans.dest] = canvas[trans.dest].toUpperCase();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return canvas.join('');
|
||||
}
|
||||
|
||||
function process_string(string) {
|
||||
for (var i = 0; i < string.length; i++) {
|
||||
process_char(string[i]);
|
||||
}
|
||||
}
|
||||
|
||||
// js > parse_rule('a a a^')
|
||||
// {type: EffectType.MARK, effect: HAT, key: a, effective_on: a}
|
||||
//
|
||||
// js > parse_rule('a w a(')
|
||||
// {type: EffectType.MARK, effect: BREVE, key: w, effective_on: a}
|
||||
//
|
||||
// js > parse_rule('a f a`')
|
||||
// {type: EffectType.MARK, effect: HAT, key: a, effective_on: a}
|
||||
//
|
||||
// js > parse_rule('w u+')
|
||||
// {type: EffectType.APPEND, effect: ư, key: w}
|
||||
function parse_rule(string) {
|
||||
var tokens = string.trim().replace(/\s\s+/, ' ').split(' ');
|
||||
|
||||
var effective_on = tokens[0];
|
||||
var key = tokens[1];
|
||||
var type;
|
||||
var effect;
|
||||
|
||||
var effect_char = tokens[2][1];
|
||||
if (effect_char in MARK_CHARS) {
|
||||
type = EffectType.MARK;
|
||||
effect = MARK_CHARS[effect_char];
|
||||
} else if (effect_char in TONE_CHARS) {
|
||||
type = EffectType.TONE;
|
||||
effect = TONE_CHARS[effect_char];
|
||||
}
|
||||
|
||||
var trans = {
|
||||
type: type,
|
||||
key: key,
|
||||
effect: effect,
|
||||
effective_on: effective_on
|
||||
};
|
||||
|
||||
return trans;
|
||||
}
|
||||
|
||||
function process_backspace() {
|
||||
var indexes_to_remove = [];
|
||||
var last_appending_trans;
|
||||
var i;
|
||||
var trans;
|
||||
|
||||
// Find the last APPENDING transformation and all
|
||||
// the transformations that add effects to it.
|
||||
for (i = composition.length - 1; i >= 0; i--) {
|
||||
trans = composition[i];
|
||||
if (trans.rule.type == EffectType.APPENDING) {
|
||||
last_appending_trans = trans;
|
||||
indexes_to_remove.push(i);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
for (i = indexes_to_remove[0] + 1; i < composition.length; i++) {
|
||||
trans = composition[i];
|
||||
if (trans.hasOwnProperty('target') &&
|
||||
trans.target === last_appending_trans) {
|
||||
indexes_to_remove.push(i);
|
||||
}
|
||||
}
|
||||
|
||||
// Then remove them
|
||||
indexes_to_remove.sort().reverse();
|
||||
indexes_to_remove.forEach(function(index) {
|
||||
composition.splice(index, 1);
|
||||
});
|
||||
}
|
||||
|
||||
function get_raw_input_string() {
|
||||
var raw_input_keys = [];
|
||||
composition.forEach(function(trans) {
|
||||
raw_input_keys.push(trans.rule.key);
|
||||
});
|
||||
return raw_input_keys.join('');
|
||||
}
|
||||
|
||||
function clear_composition() {
|
||||
composition = [];
|
||||
}
|
||||
|
||||
function clear_rules() {
|
||||
rules = [];
|
||||
}
|
||||
|
||||
function has_composition() {
|
||||
return composition.length !== 0;
|
||||
}
|
||||
|
||||
var exports = {
|
||||
add_rule: function(rule_string) {
|
||||
rules.push(parse_rule(rule_string));
|
||||
},
|
||||
clear_rules: clear_rules,
|
||||
process_char: process_char,
|
||||
process_string: process_string,
|
||||
process_backspace: process_backspace,
|
||||
clear_composition: clear_composition,
|
||||
get_processed_string: flatten,
|
||||
get_raw_input_string: get_raw_input_string,
|
||||
has_composition: has_composition
|
||||
};
|
||||
|
||||
return exports;
|
||||
}
|
||||
|
||||
|
||||
var input_context;
|
||||
var engine;
|
||||
|
||||
function init(_input_context) {
|
||||
console.log('KEYBOARD: ' + _input_context);
|
||||
input_context = _input_context;
|
||||
|
||||
engine = new BoGo();
|
||||
engine.add_rule('o w o+');
|
||||
engine.add_rule('u w u+');
|
||||
engine.add_rule('a a a^');
|
||||
engine.add_rule('a w a(');
|
||||
engine.add_rule('e e e^');
|
||||
engine.add_rule('o o o^');
|
||||
engine.add_rule('d d d-');
|
||||
engine.add_rule('_ f _`');
|
||||
engine.add_rule('_ r _?');
|
||||
engine.add_rule('_ x _~');
|
||||
engine.add_rule('_ j _.');
|
||||
engine.add_rule('_ s _\'');
|
||||
}
|
||||
|
||||
function click(keycode, x, y) {
|
||||
if (keycode == 32) {
|
||||
input_context.endComposition(engine.get_processed_string());
|
||||
engine.clear_composition();
|
||||
input_context.sendKey(keycode);
|
||||
} else if (keycode == 8) {
|
||||
if (engine.has_composition()) {
|
||||
engine.process_backspace();
|
||||
input_context.setComposition(engine.get_processed_string());
|
||||
} else {
|
||||
engine.clear_composition();
|
||||
input_context.sendKey(keycode);
|
||||
}
|
||||
} else {
|
||||
var chr = String.fromCharCode(keycode);
|
||||
engine.process_char(chr);
|
||||
input_context.setComposition(engine.get_processed_string());
|
||||
}
|
||||
}
|
||||
|
||||
// Expose the engine to the Gaia keyboard
|
||||
InputMethods.jstelex = {
|
||||
init: init,
|
||||
click: click
|
||||
};
|
||||
})();
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
1274
assets/webapps/keyboard.gaiamobile.org/js/imes/latin/latin.js
Normal file
1274
assets/webapps/keyboard.gaiamobile.org/js/imes/latin/latin.js
Normal file
File diff suppressed because it is too large
Load diff
1019
assets/webapps/keyboard.gaiamobile.org/js/imes/latin/predictions.js
Normal file
1019
assets/webapps/keyboard.gaiamobile.org/js/imes/latin/predictions.js
Normal file
File diff suppressed because it is too large
Load diff
316
assets/webapps/keyboard.gaiamobile.org/js/imes/latin/worker.js
Normal file
316
assets/webapps/keyboard.gaiamobile.org/js/imes/latin/worker.js
Normal file
|
|
@ -0,0 +1,316 @@
|
|||
'use strict';
|
||||
|
||||
/* global Predictions */
|
||||
//
|
||||
// The Latin input method provides word suggestions/auto completions
|
||||
// using the algorithm in predictions.js. For efficiency, however, this code
|
||||
// runs in a different thread. This is the web worker wrapper around
|
||||
// predictions.js. This file defines the code that interfaces predictions.js
|
||||
// with latin.js.
|
||||
//
|
||||
// This worker uses the convention that all messages send or received have
|
||||
// "cmd" and "args" fields. cmd is the message name or command. args is
|
||||
// an array of arguments required by the command, in a form suitable for
|
||||
// passing to Function.apply().
|
||||
//
|
||||
// This worker responds to the following messages:
|
||||
//
|
||||
// setLanguage: the input method uses this message to tell the worker
|
||||
// to load a dictionary for the prediction engine. If no such dictionary
|
||||
// is found or if the dictionary is invalid, the worker responds with
|
||||
// an "error" message.
|
||||
//
|
||||
// setNearbyKeys: the input method uses this message to pass information about
|
||||
// what keys are near each other in the current keyboard layout
|
||||
//
|
||||
// predict: the input method uses this message to ask the prediction
|
||||
// engine to suggestion completions for (or corrections to) the specified
|
||||
// string. The worker responds with a "predictions" message whose argument
|
||||
// is an array of up to 3 predicted words. If the the specified string
|
||||
// is a word in the dictionary, the worker may send a "word" message
|
||||
// first to quickly tell the keyboard that the word is valid.
|
||||
//
|
||||
|
||||
// Load the predictions.js module. This defines the Predictions object.
|
||||
importScripts('predictions.js');
|
||||
|
||||
// We invoke a "null" predictor when user dictionary is empty (incoming dict
|
||||
// blob is "undefined"). This is to avoid modifying the complex predictions.js
|
||||
// to adapt to "undefined" dict blob.
|
||||
|
||||
// The switching mechanism is implemented in ProxyUserDictPredictor depending on
|
||||
// its setDictionary parameter when called. Note that PUDP.setNearByKeys is
|
||||
// always called upon userDictPredictor for setting the predictor up.
|
||||
|
||||
// For pattern conformity in this file we don't use "new" to instantiate the
|
||||
// null and proxy instances.
|
||||
|
||||
var NullPredictions = function(){
|
||||
return {
|
||||
predict: function(input, maxSuggestions, maxCandidates, maxCorrections,
|
||||
callback, onerror) {
|
||||
var status = {
|
||||
state: 'predicting',
|
||||
abort: function nullAbort() {
|
||||
if (this.state !== 'done' && this.state !== 'aborted') {
|
||||
this.state = 'aborting';
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
setTimeout(function nullFinish() {
|
||||
if (status.state === 'aborting') {
|
||||
status.state = 'aborted';
|
||||
}
|
||||
|
||||
if (status.state === 'aborted') {
|
||||
return;
|
||||
}
|
||||
|
||||
status.state = 'done';
|
||||
callback([]);
|
||||
});
|
||||
|
||||
return status;
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
var ProxyUserDictPredictor = function(){
|
||||
var userDictPredictor = Predictions();
|
||||
var nullPredictor = NullPredictions();
|
||||
|
||||
var activePredictor;
|
||||
|
||||
return {
|
||||
setDictionary: function(buffer) {
|
||||
if (buffer === undefined) {
|
||||
activePredictor = nullPredictor;
|
||||
} else {
|
||||
activePredictor = userDictPredictor;
|
||||
userDictPredictor.setDictionary(buffer);
|
||||
}
|
||||
},
|
||||
setNearbyKeys: function(data) {
|
||||
userDictPredictor.setNearbyKeys(data);
|
||||
},
|
||||
// Directly pass arguments to wrapped predictor
|
||||
predict: function(/* args */) {
|
||||
return activePredictor.predict.apply(activePredictor, arguments);
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
var builtInPredictor = Predictions();
|
||||
var userDictPredictor = ProxyUserDictPredictor();
|
||||
|
||||
// Track our current language so we don't load dictionaries more often
|
||||
// than we have to.
|
||||
var currentLanguage;
|
||||
|
||||
// The prediction that is currently running, if any. So that it can be cancelled
|
||||
var pendingBuiltInPrediction;
|
||||
var pendingUserDictPrediction;
|
||||
|
||||
var Commands = {
|
||||
setLanguage: function setLanguage(language, builtInDict, userDict) {
|
||||
var _setLanguage = function(predictor, dict, tag) {
|
||||
try {
|
||||
predictor.setDictionary(dict);
|
||||
postMessage({
|
||||
cmd: 'success',
|
||||
fn: 'setLanguage/' + tag,
|
||||
language: language
|
||||
});
|
||||
} catch (e) {
|
||||
postMessage({
|
||||
cmd: 'error',
|
||||
message: 'setDictionary/' + tag + ' failed: ' + e
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// always set userDict regardless of language change or not
|
||||
_setLanguage(userDictPredictor, userDict, 'User');
|
||||
|
||||
if (language === currentLanguage) {
|
||||
return;
|
||||
}
|
||||
currentLanguage = language;
|
||||
|
||||
_setLanguage(builtInPredictor, builtInDict, 'BuiltIn');
|
||||
},
|
||||
|
||||
setUserDictionary: function setUserDictionary(userDict) {
|
||||
try {
|
||||
userDictPredictor.setDictionary(userDict);
|
||||
postMessage({cmd: 'success', fn: 'setUserDictionary'});
|
||||
}
|
||||
catch (e) {
|
||||
postMessage({cmd: 'error', fn: 'setUserDictionary: ' + e.message});
|
||||
}
|
||||
},
|
||||
|
||||
setNearbyKeys: function setNearbyKeys(nearbyKeys) {
|
||||
var _setNearbyKeys = function(predictor, tag) {
|
||||
try {
|
||||
predictor.setNearbyKeys(nearbyKeys);
|
||||
postMessage({ cmd: 'success', fn: 'setNearbyKeys/' + tag });
|
||||
}
|
||||
catch (e) {
|
||||
postMessage({
|
||||
cmd: 'error', message: 'setNearbyKeys/' + tag + ': ' + e.message});
|
||||
}
|
||||
};
|
||||
|
||||
_setNearbyKeys(builtInPredictor, 'BuiltIn');
|
||||
_setNearbyKeys(userDictPredictor, 'User');
|
||||
},
|
||||
|
||||
predict: function predict(prefix) {
|
||||
// Make sure we're not still running a previous one
|
||||
if (pendingBuiltInPrediction) {
|
||||
pendingBuiltInPrediction.abort();
|
||||
}
|
||||
if (pendingUserDictPrediction) {
|
||||
pendingUserDictPrediction.abort();
|
||||
}
|
||||
|
||||
// We merge predictions from built-in dictionaries and user dictionarys by:
|
||||
// [1] For UserDict, ask for 4 predictions with 40 candidates, and
|
||||
// considering only words with an edit distance of 1 (i.e. make only one
|
||||
// correction per word)
|
||||
// [2] For Built-In dict, everything remains the same (50 candidates if
|
||||
// prefix is short, 24 if not; do a second round:
|
||||
// [a] if there were results but results were bad; if prefix is long,
|
||||
// use 50 candidates.
|
||||
// [b] if there weren't results, use 60 candidates and allow 2
|
||||
// corrections.
|
||||
// As before weget 4 predictions.
|
||||
// [3] Results from [1] and [2] are merged by:
|
||||
// [a] Results from [1] are not discarded even if quality is low.
|
||||
// [b] Results from [1] are annotated to come from user dict.
|
||||
// [c] Results are merged and re-sorted. Duplicated words (case- and
|
||||
// variants-sensitive) are eliminated by:
|
||||
// - Keeping the higher priority.
|
||||
// - Keeping the user dictionary flag.
|
||||
// The rationale is: latin.js will always show at least one user
|
||||
// dictionary word; since user specifically define some dict word,
|
||||
// he probably wants it very much.
|
||||
// [4] latin.js will always retain at least one user dict prediction (unless
|
||||
// it decides to drop the prediction because it equals user input)
|
||||
|
||||
var BUILT_IN_CANDIDATES_LOW = 24;
|
||||
var BUILT_IN_CANDIDATES_HIGH = 50;
|
||||
var BUILT_IN_CANDIDATES_EXTRA = 60;
|
||||
var USER_DICT_CANDIDATES = 40;
|
||||
var BUILT_IN_TOO_LOW_THRESHOLD = 4;
|
||||
|
||||
var builtInPromise = new Promise(function(resolve, reject){
|
||||
var success = function(suggestions) {
|
||||
if (suggestions.length > 0) {
|
||||
// If the quality of the suggestions is very low, up candidates
|
||||
if (prefix.length > 4 &&
|
||||
suggestions[0][1] < BUILT_IN_TOO_LOW_THRESHOLD) {
|
||||
pendingBuiltInPrediction =
|
||||
builtInPredictor.predict(
|
||||
prefix, 4, BUILT_IN_CANDIDATES_HIGH, 1,
|
||||
function(suggestions){resolve(suggestions);},
|
||||
reject);
|
||||
}
|
||||
else {
|
||||
resolve(suggestions);
|
||||
}
|
||||
}
|
||||
else {
|
||||
pendingBuiltInPrediction =
|
||||
builtInPredictor.predict(
|
||||
prefix, 4, BUILT_IN_CANDIDATES_EXTRA, 2,
|
||||
function(suggestions){resolve(suggestions);},
|
||||
reject);
|
||||
}
|
||||
};
|
||||
|
||||
var noOfCandidates = prefix.length >= 2 && prefix.length <= 4 ?
|
||||
BUILT_IN_CANDIDATES_HIGH :
|
||||
BUILT_IN_CANDIDATES_LOW;
|
||||
|
||||
pendingBuiltInPrediction =
|
||||
builtInPredictor.predict(prefix, 4, noOfCandidates, 1, success, reject);
|
||||
});
|
||||
|
||||
var userDictPromise = new Promise(function(resolve, reject){
|
||||
var success = function(suggestions) {
|
||||
suggestions = suggestions.map(
|
||||
function(suggestion){
|
||||
return [
|
||||
suggestion[0],
|
||||
suggestion[1],
|
||||
true // coming from user dictionary
|
||||
];
|
||||
}
|
||||
);
|
||||
|
||||
resolve(suggestions);
|
||||
};
|
||||
|
||||
pendingUserDictPrediction =
|
||||
userDictPredictor.predict(prefix, 4, USER_DICT_CANDIDATES, 1,
|
||||
success, reject);
|
||||
});
|
||||
|
||||
Promise.all([builtInPromise, userDictPromise])
|
||||
.then(function(suggestions2D){
|
||||
// we could do a correct merge sort algorithm here, but since the arrays
|
||||
// are so small (only 4*2 entries), let's just concat and apply sort()
|
||||
|
||||
var suggestions =
|
||||
[].concat(suggestions2D[0]).concat(suggestions2D[1]).sort(
|
||||
function(suggestionA, suggestionB){
|
||||
return suggestionB[1] - suggestionA[1];
|
||||
}
|
||||
);
|
||||
|
||||
// Shortcut on eliminate duplicated entries: "duplicated entries" means
|
||||
// they're coming from both dictionaries; and since our array is sorted,
|
||||
// we'll simply the (higher-priority one's) suggestion[2] as true (= from
|
||||
// user dict) and delete the lower-priority one.
|
||||
|
||||
// map from "word" to the index in suggestions
|
||||
var seenWord = {};
|
||||
|
||||
suggestions = suggestions.reduce(function(prev, curr, index){
|
||||
var word = curr[0];
|
||||
|
||||
// we've seen this word. mark the higher-priority one as from user-dict
|
||||
// and don't push this one to the resulting array.
|
||||
if (seenWord.hasOwnProperty(word)) {
|
||||
prev[seenWord[word]][2] = true;
|
||||
} else {
|
||||
seenWord[word] = index;
|
||||
prev.push(curr);
|
||||
}
|
||||
|
||||
return prev;
|
||||
}, []);
|
||||
|
||||
postMessage({
|
||||
cmd: 'predictions', input: prefix, suggestions: suggestions
|
||||
});
|
||||
}).catch(function(e){
|
||||
log('Error in prediction: ' + e);
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// When we receive messages, translate them into function calls to one
|
||||
// of the functions in the Commands object below.
|
||||
self.onmessage = function(e) {
|
||||
Commands[e.data.cmd].apply(null, e.data.args);
|
||||
};
|
||||
|
||||
// Send console messages back to the main thread with this method
|
||||
function log(msg) {
|
||||
postMessage({cmd: 'log', message: msg});
|
||||
}
|
||||
|
||||
|
|
@ -0,0 +1,242 @@
|
|||
/* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
|
||||
|
||||
/* jshint moz:true */
|
||||
/* jshint unused:true */
|
||||
/* global InputMethods */
|
||||
|
||||
(function() {
|
||||
'use strict';
|
||||
|
||||
var keyboard;
|
||||
var buffer = '';
|
||||
var BACKSPACE = 8;
|
||||
|
||||
var M = {
|
||||
consoTT: new RegExp('^(' +
|
||||
'\u1000|\u1001|\u1002|\u1003|\u1005|\u1006|\u1007|\u1008|' +
|
||||
'\u1009|\u100A|\u100B|\u100C|\u100D|\u100E|\u100F|\u1010|' +
|
||||
'\u1011|\u1012|\u1013|\u1014|\u1015|\u1016|\u1017|\u1018|' +
|
||||
'\u1019|\u101A|\u101B|\u101C|\u101D|\u101E|\u101F|\u1020|' +
|
||||
'\u1021' + ')$'),
|
||||
consoSA: new RegExp('^(' + '\u101E' + ')$'),
|
||||
vowelIA: new RegExp('^(' +
|
||||
'\u102D|\u102E|\u1032|\u1036|\u102F|\u1030|\u102B|\u102C' + ')$'),
|
||||
vowelIU: new RegExp('^(' + '\u102D|\u102E|\u102F|\u1030' + ')$'),
|
||||
vowelSI: new RegExp('^(' + '\u102D|\u102E' + ')$'),
|
||||
vowelIN: new RegExp('^(' + '\u1032|\u1036' + ')$'),
|
||||
vowelUU: new RegExp('^(' + '\u102F|\u1030' + ')$'),
|
||||
vowelAA: new RegExp('^(' + '\u102B|\u102C' + ')$'),
|
||||
vowelSU: new RegExp('^(' + '\u1025' + ')$'),
|
||||
vowelDU: new RegExp('^(' + '\u1026' + ')$'),
|
||||
vowelSO: new RegExp('^(' + '\u1029' + ')$'),
|
||||
vowelSA: new RegExp('^(' + '\u102C' + ')$'),
|
||||
vowelDI: new RegExp('^(' + '\u102E' + ')$'),
|
||||
vowelSE: new RegExp('^(' + '\u1031' + ')$'),
|
||||
vowelAI: new RegExp('^(' + '\u1032' + ')$'),
|
||||
vowelAN: new RegExp('^(' + '\u1036' + ')$'),
|
||||
vowelAU: new RegExp('^(' + '\u1037' + ')$'),
|
||||
vowelVT: new RegExp('^(' + '\u1038|\u103A' + ')$'),
|
||||
vowelVS: new RegExp('^(' + '\u1038' + ')$'),
|
||||
vowelVR: new RegExp('^(' + '\u1039' + ')$'),
|
||||
vowelAT: new RegExp('^(' + '\u103A' + ')$'),
|
||||
mediaYH: new RegExp('^(' + '\u103B|\u103C|\u103D|\u103E' + ')$'),
|
||||
mediaYW: new RegExp('^(' + '\u103B|\u103C|\u103D' + ')$'),
|
||||
mediaYR: new RegExp('^(' + '\u103B|\u103C' + ')$'),
|
||||
mediaYA: new RegExp('^(' + '\u103B' + ')$'),
|
||||
mediaRA: new RegExp('^(' + '\u103C' + ')$'),
|
||||
mediaWA: new RegExp('^(' + '\u103D' + ')$'),
|
||||
mediaHA: new RegExp('^(' + '\u103E' + ')$'),
|
||||
zeroLEN: new RegExp('^(' + '\u200B' + ')$')
|
||||
};
|
||||
|
||||
//==================================================================
|
||||
// \u103D + \u103E + \u1031 + \u103B => $4 + $1 + $2 + $3
|
||||
// \u103D + \u103E + \u1031 + \u103C => $4 + $1 + $2 + $3
|
||||
// \u103D + \u1031 + \u103B => $3 + $1 + $2
|
||||
// \u103D + \u1031 + \u103C => $3 + $1 + $2
|
||||
// \u103D + \u103E + \u103B => $3 + $1 + $2
|
||||
// \u103D + \u103E + \u103C => $3 + $1 + $2
|
||||
// \u103E + \u1031 + \u103B => $3 + $1 + $2
|
||||
// \u103E + \u1031 + \u103C => $3 + $1 + $2
|
||||
// \u103E + \u1031 + \u103D => $3 + $1 + $2
|
||||
// \u1031 + \u1039 + consoTT[*] => $2 + $3 + $1
|
||||
// \u200B + \u1031 + consoTT[*] => $3 + $2
|
||||
// \u1031 + mediaYH[*] => $2 + $1
|
||||
// \u1036 + \u1032 => $2 +$1
|
||||
// \u1037 + vowelSI[*] => $2 + $1
|
||||
// \u1037 + vowelIN[*] => $2 + $1
|
||||
// \u1037 + vowelAA[*] => $2 + $1
|
||||
// \u1037 + vowelUU[*] => $2 + $1
|
||||
// \u1038 + \u1037 => $2 + $1
|
||||
// \u103A + \u1037 => $2 + $1
|
||||
// \u103D + \u103B => $2 + $1
|
||||
// \u103D + \u103C => $2 + $1
|
||||
// \u103E + \u103B => $2 + $1
|
||||
// \u103E + \u103C => $2 + $1
|
||||
// \u103E + \u103D => $2 + $1
|
||||
// vowelUU[*] + vowelSI[*] => $2 + $1
|
||||
// vowelIN[*] + vowelUU[*] => $2 + $1
|
||||
// vowelIN[*] + vowelSI[*] => $2 + $1
|
||||
//==================================================================
|
||||
var SWAP_RULE = [
|
||||
// p1 + p2 + p3 + p4 => p4 + p1 + p2 + p3
|
||||
{ num: 4, out: 4, t:1, p1: M.mediaWA, p2: M.mediaHA, p3: M.vowelSE,
|
||||
p4: M.mediaYR },
|
||||
// p1 + p2 + p3 => p3 + p2
|
||||
{ num: 3, out: 2, t:1, p1: M.zeroLEN, p2: M.vowelSE, p3: M.consoTT },
|
||||
// p1 + p2 + p3 => p3 + p1 + p2
|
||||
{ num: 3, out: 3, t:1, p1: M.mediaWA, p2: M.vowelSE, p3: M.mediaYR },
|
||||
{ num: 3, out: 3, t:1, p1: M.mediaWA, p2: M.mediaHA, p3: M.mediaYR },
|
||||
{ num: 3, out: 3, t:1, p1: M.mediaHA, p2: M.vowelSE, p3: M.mediaYW },
|
||||
// p1 + p2 + p3 => p2 + p3 + p1
|
||||
{ num: 3, out: 3, t:2, p1: M.vowelSE, p2: M.vowelVR, p3: M.consoTT },
|
||||
// p1 + p2 => p2 + p1
|
||||
{ num: 2, out: 2, t:1, p1: M.vowelSE, p2: M.mediaYH },
|
||||
{ num: 2, out: 2, t:1, p1: M.vowelAN, p2: M.vowelAI },
|
||||
{ num: 2, out: 2, t:1, p1: M.vowelAU, p2: M.vowelIA },
|
||||
{ num: 2, out: 2, t:1, p1: M.vowelVT, p2: M.vowelAU },
|
||||
{ num: 2, out: 2, t:1, p1: M.vowelUU, p2: M.vowelSI },
|
||||
{ num: 2, out: 2, t:1, p1: M.vowelIN, p2: M.vowelIU },
|
||||
{ num: 2, out: 2, t:1, p1: M.mediaWA, p2: M.mediaYR },
|
||||
{ num: 2, out: 2, t:1, p1: M.mediaHA, p2: M.mediaYW }
|
||||
];
|
||||
|
||||
//==================================================================
|
||||
// \u1025 + \u102E => \u1026
|
||||
// \u1025 + \u103A => \u1009 + \u103A
|
||||
// \u101E + \u103C + \u1031 + \u102C + \u103A => \u102A
|
||||
//==================================================================
|
||||
var ADD_RULE = [
|
||||
{ num: 2, out: '\u1026', p1: M.vowelSU, p2: M.vowelDI },
|
||||
{ num: 2, out: '\u1009\u103A', p1: M.vowelSU, p2: M.vowelAT },
|
||||
{ num: 5, out: '\u102A', p1: M.consoSA, p2: M.mediaRA, p3: M.vowelSE,
|
||||
p4: M.vowelSA, p5: M.vowelAT }
|
||||
];
|
||||
|
||||
//==================================================================
|
||||
// \u1039 + consoTT[*] + \u1031 + < VK_BACK > => \u1039 + $filler + \u1031
|
||||
// \u200B + consoTT[*] + \u1031 + < VK_BACK > => $filler + \u1031
|
||||
// mediaYH[*] + \u1031 + < VK_BACK > => \u1031
|
||||
// \u1039 + consoTT[*] + < VK_BACK > => NULL
|
||||
// \u200B + \u1031 + < VK_BACK > => NULL
|
||||
//==================================================================
|
||||
var DEL_RULE = [
|
||||
{num: 3, out: '\u1031\u1039', p1: M.vowelVR, p2: M.consoTT, p3: M.vowelSE},
|
||||
{num: 2, out: '\u200B\u1031', p1: M.consoTT, p2: M.vowelSE},
|
||||
{num: 2, out: '\u1031', p1: M.mediaYH, p2: M.vowelSE},
|
||||
{num: 2, out: '', p1: M.vowelVR, p2: M.consoTT},
|
||||
{num: 2, out: '', p1: M.zeroLEN, p2: M.vowelSE}
|
||||
];
|
||||
|
||||
function myanParser(rule, callback) {
|
||||
var idx = ['p0', 'p1', 'p2', 'p3', 'p4', 'p5'];
|
||||
var len = buffer.length;
|
||||
|
||||
if (len < 2) {
|
||||
return null;
|
||||
}
|
||||
|
||||
for (var i = 0; i < rule.length; i++) {
|
||||
if (len < rule[i].num) {
|
||||
continue;
|
||||
}
|
||||
var c = len - 1;
|
||||
for (var j = rule[i].num; j > 0; j--) {
|
||||
if (!buffer[c--].match( rule[i][idx[j]] )) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (j === 0) {
|
||||
return callback(rule[i]);
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function processBuffer(callback) {
|
||||
var swap = myanParser(SWAP_RULE, function(entry) {
|
||||
if (!entry) {
|
||||
return null;
|
||||
}
|
||||
var len = buffer.length;
|
||||
var tail = entry.t;
|
||||
var out = entry.out;
|
||||
var s = {};
|
||||
s.num = entry.num;
|
||||
s.str = buffer.substr(len-tail, tail) +
|
||||
buffer.substr(len-out, out-tail);
|
||||
return s;
|
||||
});
|
||||
|
||||
// After process swap, check if the string need to be merged.
|
||||
var adds = myanParser(ADD_RULE, function(entry) {
|
||||
if (!entry) {
|
||||
return null;
|
||||
}
|
||||
var s = {};
|
||||
s.num = entry.num;
|
||||
s.str = entry.out;
|
||||
return s;
|
||||
});
|
||||
|
||||
return (adds) ? callback(adds) : callback(swap);
|
||||
}
|
||||
|
||||
function doDelete(callback) {
|
||||
var dels = myanParser(DEL_RULE, function(entry) {
|
||||
if (!entry) {
|
||||
return null;
|
||||
}
|
||||
var s = {};
|
||||
s.num = entry.num;
|
||||
s.str = entry.out;
|
||||
return s;
|
||||
});
|
||||
|
||||
return (dels) ? callback(dels) : false;
|
||||
}
|
||||
|
||||
function overrideInput(s) {
|
||||
if(s) {
|
||||
keyboard.replaceSurroundingText(s.str, -s.num, s.num);
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
InputMethods.myanmar = {
|
||||
init: function(interfaceObject) {
|
||||
keyboard = interfaceObject;
|
||||
},
|
||||
|
||||
click: function(keycode) {
|
||||
|
||||
keyboard.setUpperCase({
|
||||
isUpperCase: false
|
||||
});
|
||||
|
||||
if (keycode == BACKSPACE) {
|
||||
if(!doDelete(overrideInput)) {
|
||||
keyboard.sendKey(keycode);
|
||||
}
|
||||
}
|
||||
else {
|
||||
if (String.fromCharCode(keycode) == '\u1031') {
|
||||
// Send an extra zero length space on click of vowel sign E.
|
||||
keyboard.sendKey('\u200B'.charCodeAt(0));
|
||||
}
|
||||
keyboard.sendKey(keycode);
|
||||
}
|
||||
},
|
||||
|
||||
surroundingtextChange: function(detail) {
|
||||
buffer = detail.beforeString;
|
||||
processBuffer(overrideInput);
|
||||
}
|
||||
};
|
||||
|
||||
})();
|
||||
|
|
@ -0,0 +1,423 @@
|
|||
/* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
|
||||
|
||||
/* jshint moz:true */
|
||||
/* jshint unused:true */
|
||||
/* global InputMethods */
|
||||
/* global KeyEvent */
|
||||
|
||||
// ==================================================================
|
||||
// WARNING. THIS FUNCTION USES PRECOMPOSED UNICODE CHARACTERS IN
|
||||
// STRING LITERALS. DO NOT NORMALIZE THIS FILE.
|
||||
// IF YOU NORMALIZE THIS FILE, THE STRINGS WILL CHANGE AND THE
|
||||
// PROGRAM WILL BREAK.
|
||||
//
|
||||
// The use of precomposed Unicode characters is deliberate. This
|
||||
// IM outputs precomposed Vietnamese characters rather than
|
||||
// using combining character sequences because Firefox OS
|
||||
// has trouble rendering Vietnamese combining character sequences.
|
||||
//
|
||||
// I considered using Unicode escape sequences instead of the
|
||||
// actual Vietnamese characters, but that would have made the code
|
||||
// much harder to read, understand, and maintain. Furthermore, I
|
||||
// don't think there's much risk that someone will normalize this
|
||||
// file.
|
||||
//
|
||||
// Existing Javascript standards say that all strings should be
|
||||
// normalized in NFC format. In practice, no Javascript interpreter
|
||||
// does that, and nor should they. There is a proposal to remove
|
||||
// that requirement from the next standard, partly out of consider-
|
||||
// ation for languages like Vietnamese which usually aren't NFC
|
||||
// normalized, and partly to reflect actual practice.
|
||||
//
|
||||
// http://wiki.ecmascript.org/doku.php?id=strawman:unicode_normalization
|
||||
//
|
||||
// ==================================================================
|
||||
|
||||
|
||||
|
||||
// Like pinyin, Vietnam's writing system (Quốc Ngữ) has fixed rules for
|
||||
// what makes a valid syllable.
|
||||
|
||||
// A syllable consists of:
|
||||
// optional initial + vowel cluster + optional final
|
||||
|
||||
// Not all vowel clusters can occur before all finals.
|
||||
// The vowel cluster can optionally carry one of 5 tone marks.
|
||||
|
||||
// The spelling is fairly regular, but it inherits a few irregularities
|
||||
// from Portuguese.
|
||||
// * The /k/ sound can be spelt C or K depending on the
|
||||
// following vowel. (Or Q before a /w/ glide.)
|
||||
// * The initial G becomes GH before E or I (or Ê or Y). Similarly, NG
|
||||
// becomes NGH
|
||||
// * The /w/ sound at the start of a vowel cluster can be spelt O or U
|
||||
// depending on the following vowel. However, after a Q, it is always
|
||||
// spelt U, regardless of the following vowel. Basically, the list of
|
||||
// valid vowel clusters completely changes after a Q.
|
||||
// * The vowel cluster IÊ becomes YÊ at the start of a word. Likewise,
|
||||
// IÊU> becomes YÊU.
|
||||
|
||||
(function() {
|
||||
'use strict';
|
||||
|
||||
var QN = {
|
||||
unmarkedVowels: 'AaĂăÂâEeÊêIiOoÔôƠơUuƯưYy',
|
||||
|
||||
// The elements of this array represent the five marked tones of
|
||||
// Vietnamese. (A sixth tone is unmarked.)
|
||||
markedVowels: [
|
||||
'ÁáẮắẤấÉéẾếÍíÓóỐốỚớÚúỨứÝý', // Sắc Tone
|
||||
'ÀàẰằẦầÈèỀềÌìÒòỒồỜờÙùỪừỲỳ', // Huyền Tone
|
||||
'ẢảẲẳẨẩẺẻỂểỈỉỎỏỔổỞởỦủỬửỶỷ', // Hỏi Tone
|
||||
'ÃãẴẵẪẫẼẽỄễĨĩÕõỖỗỠỡŨũỮữỸỹ', // Ngã Tone
|
||||
'ẠạẶặẬậẸẹỆệỊịỌọỘộỢợỤụỰựỴỵ' // Nặng Tone
|
||||
],
|
||||
|
||||
// All the intials except Q (including the null initial).
|
||||
// (Any usual Vietnamese syllable can be prefixed with an X
|
||||
// when transcribing foreign proper nouns.)
|
||||
initialsNotQ: '(x?(?:b|c|ch|d|đ|g|gh|gi|h|k|kh|l|m|n|' +
|
||||
'ng|ngh|nh|p|ph|r|s|t|th|tr|v)?)',
|
||||
|
||||
// All the initials that start with Q.
|
||||
initialQ: '(x?q)',
|
||||
|
||||
// All the finals
|
||||
finals: '(c|ch|m|n|ng|nh|p|t)',
|
||||
|
||||
// These vowel clusters are valid when there is no final
|
||||
// (except when the intial is Q)
|
||||
nucleusOpen: '(a|e|ê|i|y|o|ô|ơ|u|ư|' + // vowel
|
||||
'ai|ay|ăy|oi|ơi|ôi|ui|ưi|' + // vowel + /j/
|
||||
'ao|au|âu|eo|êu|iu|ưu|' + // vowel + /w/
|
||||
'ia|ua|ưa|' + // diphthong
|
||||
'uơi|ươi|' + // diphthong + /j/
|
||||
'iêu|yêu|ươu|' + // diphthong + /w/
|
||||
'oa|oe|uê|uy|uơ|' + // /w/ + vowel
|
||||
'uya|' + // /w/ + diphthong
|
||||
'oai|oay|uôi|uây)', // /w/ + vowel + /j/
|
||||
|
||||
// These vowel clusters are valid before any final,
|
||||
// (except when the intial is Q)
|
||||
nucleusClosed: '(a|ă|â|e|ê|i|o|ô|ơ|u|ư|' + // vowel
|
||||
'iê|yê|uô|uơ|ươ|' + // diphthong
|
||||
'oa|oă|uâ|oe|uê|uy|uơ|' + // /w/ + vowel
|
||||
'uyê|' + // /w/ + diphthong
|
||||
'oo)', // 'oo' only appears in French loan words
|
||||
// like 'xoong' (casserole). Some Vietnamese
|
||||
// textbooks omit it, but it definitely exists.
|
||||
|
||||
|
||||
// These vowel clusters are valid when there is no final
|
||||
// and the initial is Q.
|
||||
nucleusOpenAfterQ: '(ua|ue|uê|ui|uy|uơ|' + // /w/ + vowel
|
||||
'uya|' + // /w/ + diphthong
|
||||
'uai|uay|uây)', // /w/ + vowel + /j/
|
||||
|
||||
// These vowel clusters are valid before any final,
|
||||
// when the initial is Q.
|
||||
nucleusClosedAfterQ: '(ua|uă|uâ|ue|uê|ui|uy|uơ|' + // /w/ + vowel
|
||||
'uyê)' // /w/ + diphthong
|
||||
};
|
||||
|
||||
var vietWordParser = {
|
||||
p1: new RegExp('^' + QN.initialsNotQ + QN.nucleusOpen + '$'),
|
||||
p2: new RegExp('^' + QN.initialsNotQ + QN.nucleusClosed + QN.finals + '$'),
|
||||
p3: new RegExp('^' + QN.initialQ + QN.nucleusOpenAfterQ + '$'),
|
||||
p4: new RegExp('^' + QN.initialQ + QN.nucleusClosedAfterQ + QN.finals +
|
||||
'$'),
|
||||
|
||||
isValidWord: function(word) {
|
||||
var w = word.toLowerCase();
|
||||
var array = w.match(this.p1) || w.match(this.p2) ||
|
||||
w.match(this.p3) || w.match(this.p4);
|
||||
|
||||
if (!array) {
|
||||
return false;
|
||||
}
|
||||
|
||||
var initialCluster = array[1];
|
||||
var vowelCluster = array[2];
|
||||
var finalCluster = array[3] || '';
|
||||
|
||||
// G -> GH and NG -> NGH before E/Ê or I/Y
|
||||
if (initialCluster.match(/^(g|ng)$/) &&
|
||||
vowelCluster.match(/^(e|ê|i|y)/)) {
|
||||
return false;
|
||||
}
|
||||
if (initialCluster.match(/^(gh|ngh)$/) &&
|
||||
!vowelCluster.match(/^(e|ê|i|y)/)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// GI can't come before I/Y
|
||||
if (initialCluster === 'gi' && vowelCluster.match(/^(i|y)/)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// K before I/Y or E; C otherwise
|
||||
if (initialCluster === 'k' && !vowelCluster.match(/^(e|ê|i|y)/)) {
|
||||
return false;
|
||||
}
|
||||
if (initialCluster === 'c' && vowelCluster.match(/^(e|ê|i|y)/)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// IÊ -> YÊ and IÊU -> YÊU when there's no initial
|
||||
if (initialCluster === '' && vowelCluster.match(/^iê/)) {
|
||||
return false;
|
||||
}
|
||||
if (initialCluster !== '' && vowelCluster.match(/^yê/)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// The vowel clusters UÂ and UYÊ can only come before T or N.
|
||||
if (vowelCluster.match(/^(uâ|uyê)$/) && !finalCluster.match(/^(t|n)$/)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
},
|
||||
|
||||
addToneMarkToVowel: function(vowel, tone) {
|
||||
var vowelIndex = QN.unmarkedVowels.indexOf(vowel);
|
||||
if (vowelIndex >= 0) {
|
||||
return QN.markedVowels[tone][vowelIndex];
|
||||
}
|
||||
},
|
||||
|
||||
findTonePosition: function(word) {
|
||||
var w = word.toLowerCase();
|
||||
|
||||
var array = w.match(this.p1) || w.match(this.p2) ||
|
||||
w.match(this.p3) || w.match(this.p4);
|
||||
|
||||
if (!array) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
var initialCluster = array[1];
|
||||
var vowelCluster = array[2];
|
||||
var finalCluster = array[3] || '';
|
||||
|
||||
// When placing the tone mark, the U in QU should be considered
|
||||
// part of the initial, not part of the vowel cluster.
|
||||
// It never carries the tone mark.
|
||||
if (initialCluster == 'q') {
|
||||
initialCluster = 'qu';
|
||||
vowelCluster = vowelCluster.substr(1);
|
||||
}
|
||||
|
||||
// Here are the traditional rules for where to place the tone mark:
|
||||
// * Vowels with diacritics are preferred over vowels without one.
|
||||
// If that doesn't settle it, use these rules:
|
||||
// * If the word has three vowels, it goes on the middle one.
|
||||
// * If the word has two vowels followed by a consonant, it goes on the
|
||||
// last vowel.
|
||||
// * If the word ends with two vowels, it goes on the first vowel.
|
||||
|
||||
// The only time a word can have more than one diacritic is when it
|
||||
// contains ươ, which has to be followed by a consonant. By the above
|
||||
// rules, that means the ơ gets the diacritic, not the ư.
|
||||
|
||||
return w.search(/(ơ)/) + 1 ||
|
||||
w.search(/(ă|â|ê|ô|ư)/) + 1 ||
|
||||
(vowelCluster.length === 3 ? initialCluster.length + 2 :
|
||||
finalCluster !== '' ? initialCluster.length + vowelCluster.length :
|
||||
initialCluster.length + 1);
|
||||
},
|
||||
|
||||
addHat: function(word) {
|
||||
return word.replace('a', 'â').replace('A', 'Â')
|
||||
.replace('e', 'ê').replace('E', 'Ê')
|
||||
.replace('o', 'ô').replace('O', 'Ô');
|
||||
},
|
||||
|
||||
generateCandidates: function(word) {
|
||||
if (!this.isValidWord(word)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
// Vietnamese has five tone marks. However, if a word ends
|
||||
// in P, T, C, or CH, only the SẮC and NẶNG tones can be used.
|
||||
var stopFinal = !!word.match(/(p|t|c|ch)$/i);
|
||||
var marks = stopFinal ? [0, 4] : [0, 1, 2, 3, 4];
|
||||
|
||||
var tonePos = this.findTonePosition(word);
|
||||
|
||||
var candidates = marks.map((mark) => {
|
||||
return word.substr(0, tonePos - 1) +
|
||||
this.addToneMarkToVowel(word.charAt(tonePos - 1), mark) +
|
||||
word.substr(tonePos);
|
||||
});
|
||||
|
||||
return candidates;
|
||||
}
|
||||
};
|
||||
|
||||
var keyboard, buffer = '';
|
||||
var capitalize = false;
|
||||
var capitalizeNext = false;
|
||||
var tentativeSpace = false;
|
||||
|
||||
var BACKSPACE = 8;
|
||||
var HAT = 94;
|
||||
|
||||
function isBufferEmpty() {
|
||||
return buffer === '';
|
||||
}
|
||||
|
||||
function clearBuffer() {
|
||||
buffer = '';
|
||||
}
|
||||
|
||||
function addToBuffer(keycode) {
|
||||
if (keycode == BACKSPACE) {
|
||||
backspace();
|
||||
}
|
||||
buffer = buffer + String.fromCharCode(keycode);
|
||||
}
|
||||
|
||||
function backspace() {
|
||||
if (!isBufferEmpty()) {
|
||||
buffer = buffer.substring(0, buffer.length -1);
|
||||
keyboard.setComposition(buffer);
|
||||
}
|
||||
else {
|
||||
keyboard.sendKey(KeyEvent.DOM_VK_BACK_SPACE);
|
||||
}
|
||||
}
|
||||
|
||||
function inputDone() {
|
||||
keyboard.endComposition(buffer);
|
||||
clearBuffer();
|
||||
}
|
||||
|
||||
InputMethods.vietnamese = {
|
||||
init: init,
|
||||
activate: activate,
|
||||
deactivate: deactivate,
|
||||
click: click,
|
||||
select: select
|
||||
};
|
||||
|
||||
function init(interfaceObject) {
|
||||
keyboard = interfaceObject;
|
||||
}
|
||||
|
||||
function activate(lang, state) {
|
||||
capitalize = !!state.type.match(/^(text|textarea|search)$/);
|
||||
tentativeSpace = false;
|
||||
|
||||
var cursor = state.selectionStart;
|
||||
var inputText = state.value;
|
||||
|
||||
capitalizeNext = false;
|
||||
if (capitalize) {
|
||||
if (cursor === 0) {
|
||||
capitalizeNext = true;
|
||||
}
|
||||
else {
|
||||
var charBeforeCursor = cursor - 1;
|
||||
while (charBeforeCursor >= 0 && inputText[charBeforeCursor] == ' ') {
|
||||
--charBeforeCursor;
|
||||
}
|
||||
capitalizeNext = !!inputText[charBeforeCursor].match(/[\!\?\.]/);
|
||||
}
|
||||
}
|
||||
keyboard.setUpperCase(capitalizeNext);
|
||||
}
|
||||
|
||||
function deactivate() {
|
||||
if (!isBufferEmpty()) {
|
||||
inputDone();
|
||||
keyboard.sendCandidates([]);
|
||||
}
|
||||
}
|
||||
|
||||
function click(keycode) {
|
||||
var s = String.fromCharCode(keycode);
|
||||
|
||||
var wasTentativeSpace = tentativeSpace;
|
||||
tentativeSpace = false;
|
||||
|
||||
var wasCapitalizeNext = capitalizeNext;
|
||||
capitalizeNext = false;
|
||||
|
||||
// Automatically transform E -> Ê after an I or Y. I find this really handy.
|
||||
// And UO -> UÔ
|
||||
if (s == 'e' && buffer.match(/(y|i)$/i)) {
|
||||
keycode = 'ê'.charCodeAt(0);
|
||||
}
|
||||
else if (s == 'E' && buffer.match(/(y|i)$/i)) {
|
||||
keycode = 'Ê'.charCodeAt(0);
|
||||
} else if (s == 'o' && buffer.match(/u$/i)) {
|
||||
keycode = 'ô'.charCodeAt(0);
|
||||
} else if (s == 'O' && buffer.match(/u$/i)) {
|
||||
keycode = 'Ô'.charCodeAt(0);
|
||||
}
|
||||
|
||||
// Letters
|
||||
if (s.match(/[A-Za-zĂÂĐÊÔƠUƯ]/i)) {
|
||||
addToBuffer(keycode);
|
||||
}
|
||||
// The special hat key.
|
||||
else if (keycode == HAT) {
|
||||
buffer = vietWordParser.addHat(buffer);
|
||||
}
|
||||
// Backspace
|
||||
else if (keycode == BACKSPACE) {
|
||||
backspace();
|
||||
}
|
||||
// Handling tentative space
|
||||
else if (wasTentativeSpace &&
|
||||
(s == '.' || s == ',' || s == '!' || s == '?')) {
|
||||
keyboard.sendKey(KeyEvent.DOM_VK_BACK_SPACE);
|
||||
keyboard.sendKey(keycode);
|
||||
keyboard.sendKey(KeyEvent.DOM_VK_SPACE);
|
||||
if (s == '.' || s == '!' || s == '?') {
|
||||
capitalizeNext = true;
|
||||
}
|
||||
}
|
||||
// Using spacebar to finish input
|
||||
else if (s == ' ' && !isBufferEmpty()) {
|
||||
buffer += s;
|
||||
tentativeSpace = true;
|
||||
inputDone();
|
||||
}
|
||||
// Punctuation, symbols, other.
|
||||
else {
|
||||
if (!isBufferEmpty()) {
|
||||
inputDone();
|
||||
}
|
||||
if (s == '.' || s == '!' || s == '?') {
|
||||
capitalizeNext = true;
|
||||
}
|
||||
if (s == ' ') {
|
||||
capitalizeNext = wasCapitalizeNext;
|
||||
}
|
||||
keyboard.sendKey(keycode);
|
||||
}
|
||||
|
||||
if (!isBufferEmpty()) {
|
||||
keyboard.setComposition(buffer);
|
||||
var candidates = vietWordParser.generateCandidates(buffer);
|
||||
keyboard.sendCandidates(candidates);
|
||||
} else {
|
||||
keyboard.sendCandidates([]);
|
||||
}
|
||||
|
||||
keyboard.setUpperCase(capitalizeNext);
|
||||
}
|
||||
|
||||
function select(s) {
|
||||
buffer = s;
|
||||
buffer += ' ';
|
||||
tentativeSpace = true;
|
||||
inputDone();
|
||||
keyboard.sendCandidates([]);
|
||||
}
|
||||
|
||||
})();
|
||||
Loading…
Reference in a new issue