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
213
gaia/apps/keyboard/js/imes/jspinyin/NOTICE
Executable file
213
gaia/apps/keyboard/js/imes/jspinyin/NOTICE
Executable 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
|
||||
|
||||
27
gaia/apps/keyboard/js/imes/jspinyin/README
Executable file
27
gaia/apps/keyboard/js/imes/jspinyin/README
Executable file
|
|
@ -0,0 +1,27 @@
|
|||
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.
|
||||
|
||||
|
||||
Requirements:
|
||||
|
||||
1. Emscripten (https://github.com/kripken/emscripten)
|
||||
|
||||
|
||||
Emscripten Compiling Steps:
|
||||
|
||||
1. Git clone from https://github.com/luke-chang/Android-PinyinIME.git
|
||||
|
||||
2. Git checkout "empinyin" branch.
|
||||
|
||||
3. Go to "Android-PinyinIME/jni/empinyin" path.
|
||||
|
||||
4. Open "Makefile" and set your own EMSCRIPTEN_HOME
|
||||
|
||||
5. Run "make"
|
||||
|
||||
6. Refer to jni/empinyin/*.patch and modify the corresponding files manually.
|
||||
|
||||
7. Done.
|
||||
|
||||
BIN
gaia/apps/keyboard/js/imes/jspinyin/empinyin_files.data
Executable file
BIN
gaia/apps/keyboard/js/imes/jspinyin/empinyin_files.data
Executable file
Binary file not shown.
132
gaia/apps/keyboard/js/imes/jspinyin/empinyin_files.js
Executable file
132
gaia/apps/keyboard/js/imes/jspinyin/empinyin_files.js
Executable file
|
|
@ -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);
|
||||
});
|
||||
})();
|
||||
|
||||
771
gaia/apps/keyboard/js/imes/jspinyin/jspinyin.js
Executable file
771
gaia/apps/keyboard/js/imes/jspinyin/jspinyin.js
Executable file
|
|
@ -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
gaia/apps/keyboard/js/imes/jspinyin/libpinyin.js
Executable file
28531
gaia/apps/keyboard/js/imes/jspinyin/libpinyin.js
Executable file
File diff suppressed because one or more lines are too long
26
gaia/apps/keyboard/js/imes/jspinyin/tests/index.html
Executable file
26
gaia/apps/keyboard/js/imes/jspinyin/tests/index.html
Executable file
|
|
@ -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>
|
||||
|
||||
192
gaia/apps/keyboard/js/imes/jspinyin/tests/init.js
Executable file
192
gaia/apps/keyboard/js/imes/jspinyin/tests/init.js
Executable file
|
|
@ -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);
|
||||
}
|
||||
};
|
||||
}
|
||||
22
gaia/apps/keyboard/js/imes/jspinyin/tests/style.css
Executable file
22
gaia/apps/keyboard/js/imes/jspinyin/tests/style.css
Executable file
|
|
@ -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;
|
||||
}
|
||||
175
gaia/apps/keyboard/js/imes/jspinyin/worker.js
Executable file
175
gaia/apps/keyboard/js/imes/jspinyin/worker.js
Executable file
|
|
@ -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);
|
||||
}
|
||||
Loading…
Reference in a new issue