Compare commits

...

55 Commits

Author SHA1 Message Date
bee1e30e12 Revert prev commit 2026-05-12 23:07:49 +03:00
2da2866862 Refactoring 2026-05-12 21:39:13 +03:00
075052dd3f Merge pull request 'Fix bug 81448' (#760) from fix/big-81448 into release/v9.4.0
Reviewed-on: https://git.onlyoffice.com/ONLYOFFICE/core/pulls/760
2026-05-12 10:29:29 +00:00
4207d697fa Fix bug 81448 2026-05-12 13:26:39 +03:00
8a4e115384 Merge pull request 'fix bug #75103' (#758) from fix/bug75103 into release/v9.4.0
Reviewed-on: https://git.onlyoffice.com/ONLYOFFICE/core/pulls/758
2026-05-08 12:52:14 +00:00
f4b2184985 fix bug #75103
(cherry picked from commit 1c9ce65ba9)
2026-05-08 15:49:45 +03:00
25b30b3a73 Fix bug 81335 2026-05-04 13:23:09 +03:00
8c2c4060a7 Fix bug 81273 2026-05-04 11:40:24 +03:00
f5a0278d4b Move files to data repo 2026-04-30 19:59:28 +03:00
764a8e4cd9 Fix bug 81335 2026-04-29 18:10:44 +03:00
6a45740f98 Fix mac|ios build 2026-04-28 18:53:14 +03:00
dfe6d300d8 Fixes with rand 2026-04-28 18:17:32 +03:00
cce7058d46 Merge branch 'release/v9.4.0' of https://git.onlyoffice.com/ONLYOFFICE/core into release/v9.4.0 2026-04-28 18:12:13 +03:00
71a8a22d2e Add security rand function 2026-04-28 18:11:51 +03:00
7c7ebd5f2a Merge pull request 'Fix Embedded font use in pushbutton' (#756) from fix/pdf-pushbutton into release/v9.4.0
Reviewed-on: https://git.onlyoffice.com/ONLYOFFICE/core/pulls/756
2026-04-28 11:52:06 +00:00
7890f5b87f Fix Embedded font use in pushbutton 2026-04-28 14:49:38 +03:00
69a066fac9 Merge pull request 'Fix bug 80336' (#755) from fix/bug-80336 into release/v9.4.0
Reviewed-on: https://git.onlyoffice.com/ONLYOFFICE/core/pulls/755
2026-04-28 09:27:58 +00:00
1a94960abf Fix bug 80336 2026-04-28 12:20:59 +03:00
00bee83d0e Merge pull request 'fix bug #81283' (#754) from fix/bug81283 into release/v9.4.0
Reviewed-on: https://git.onlyoffice.com/ONLYOFFICE/core/pulls/754
2026-04-27 17:01:14 +00:00
37d83faffd fix bug #81283 2026-04-27 19:46:31 +03:00
5b15d9b77b Fix bug 81149 2026-04-27 18:12:54 +03:00
c5a040c807 For bug 81147 2026-04-27 16:52:52 +03:00
bb9e3a2a7e Add readme 2026-04-27 16:45:46 +03:00
e2c560d5ad For bug 81146 2026-04-27 16:37:38 +03:00
2ed3521355 Merge pull request 'fix bugs' (#752) from fix/fix-bugs into release/v9.4.0
Reviewed-on: https://git.onlyoffice.com/ONLYOFFICE/core/pulls/752
2026-04-24 15:51:37 +00:00
1c1947459d fix bug #81251 2026-04-24 18:50:20 +03:00
29b2b2e086 Merge pull request 'Fix bug 81148' (#751) from fix/bug-81148 into release/v9.4.0
Reviewed-on: https://git.onlyoffice.com/ONLYOFFICE/core/pulls/751
2026-04-24 14:45:31 +00:00
2761614b8d Fix bug 81148 2026-04-24 17:42:29 +03:00
2deb6b8c42 fix bug #81241 2026-04-24 16:48:47 +03:00
59e4d02f01 Merge pull request 'fix bug #81216' (#750) from fix/bug81216 into release/v9.4.0
Reviewed-on: https://git.onlyoffice.com/ONLYOFFICE/core/pulls/750
2026-04-24 08:18:34 +00:00
99b31a46f7 fix bug #81216 2026-04-24 11:10:57 +03:00
5a0bc5a19d Merge pull request 'fix bugs' (#749) from fix/fix-bugs into release/v9.4.0
Reviewed-on: https://git.onlyoffice.com/ONLYOFFICE/core/pulls/749
2026-04-23 09:02:45 +00:00
38bbe37f40 fix bug #81042 2026-04-23 11:50:35 +03:00
eb4c5cfc2a fix bug #81038 2026-04-23 11:26:25 +03:00
6262048e75 fix bug #81038 2026-04-23 11:13:49 +03:00
7877f542b3 fix bug #81037 2026-04-23 10:56:59 +03:00
f00581fd1d fix bug #81039 2026-04-23 10:52:25 +03:00
bd3dd15a4f fix bug #81040 2026-04-23 10:41:30 +03:00
a796e92fe1 fix bug #81215 2026-04-23 10:32:30 +03:00
3d7381dc68 Merge pull request 'Fix bug 81092' (#748) from fix/bug-81092 into release/v9.4.0
Reviewed-on: https://git.onlyoffice.com/ONLYOFFICE/core/pulls/748
2026-04-21 13:46:39 +00:00
e33e3d6b42 Fix bug 81092 2026-04-21 16:13:34 +03:00
c03fd25b6d Fix build 2026-04-21 16:06:19 +03:00
c7c98d3f69 Merge pull request 'fix bug #81148' (#747) from fix/bug81148- into release/v9.4.0
Reviewed-on: https://git.onlyoffice.com/ONLYOFFICE/core/pulls/747
2026-04-21 10:00:55 +00:00
d9d7ffef26 fix bug #81148 2026-04-21 12:50:49 +03:00
b0efeafd27 Merge pull request 'Add patch for fix build Xcode 26+ Clang treats enum-constexpr-conversion as hard error' (#742) from fix/boost-integral-wrapper-xcode into release/v9.4.0
Reviewed-on: https://git.onlyoffice.com/ONLYOFFICE/core/pulls/742
2026-04-16 07:18:21 +00:00
8a3a922dba Merge pull request 'Fix bug 81029' (#744) from fix/bug-81029 into release/v9.4.0
Reviewed-on: https://git.onlyoffice.com/ONLYOFFICE/core/pulls/744
2026-04-14 13:20:10 +00:00
b78bcb10dc Fix bug 81029 2026-04-14 16:16:38 +03:00
653ff24c0e Merge pull request 'Fix AP removal for modified annotations' (#743) from fix/pdf-bugs into release/v9.4.0
Reviewed-on: https://git.onlyoffice.com/ONLYOFFICE/core/pulls/743
2026-04-14 07:52:40 +00:00
a62f97627b Fix AP removal for modified annotations 2026-04-14 10:50:07 +03:00
612c26cf6c Add patch for fix build Xcode 26+ Clang treats enum-constexpr-conversion as hard error 2026-04-09 11:07:45 +03:00
2873418d74 Merge pull request 'Fix bug 80951' (#741) from fix/bug-80951 into release/v9.4.0
Reviewed-on: https://git.onlyoffice.com/ONLYOFFICE/core/pulls/741
2026-04-08 12:52:43 +00:00
77346270a4 Fix bug 80951 2026-04-08 15:07:22 +03:00
5f39acbe51 Merge pull request 'For bug 80374' (#740) from fix/forbug80374 into release/v9.4.0
Reviewed-on: https://git.onlyoffice.com/ONLYOFFICE/core/pulls/740
2026-04-08 08:34:04 +00:00
6badba384c For bug 80374 2026-04-08 11:27:44 +03:00
c96df4e62e Fix bugs in fromUnicode method 2026-04-07 22:11:37 +03:00
153 changed files with 645 additions and 10672 deletions

View File

@ -0,0 +1,36 @@
<<<<<<<
#if BOOST_WORKAROUND(__EDG_VERSION__, <= 243)
private:
BOOST_STATIC_CONSTANT(AUX_WRAPPER_VALUE_TYPE, next_value = BOOST_MPL_AUX_STATIC_CAST(AUX_WRAPPER_VALUE_TYPE, (N + 1)));
BOOST_STATIC_CONSTANT(AUX_WRAPPER_VALUE_TYPE, prior_value = BOOST_MPL_AUX_STATIC_CAST(AUX_WRAPPER_VALUE_TYPE, (N - 1)));
public:
typedef AUX_WRAPPER_INST(next_value) next;
typedef AUX_WRAPPER_INST(prior_value) prior;
#elif BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x561)) \
|| BOOST_WORKAROUND(__IBMCPP__, BOOST_TESTED_AT(502)) \
|| (BOOST_WORKAROUND(__HP_aCC, <= 53800) && (BOOST_WORKAROUND(__hpxstd98, != 1)))
typedef AUX_WRAPPER_INST( BOOST_MPL_AUX_STATIC_CAST(AUX_WRAPPER_VALUE_TYPE, (N + 1)) ) next;
typedef AUX_WRAPPER_INST( BOOST_MPL_AUX_STATIC_CAST(AUX_WRAPPER_VALUE_TYPE, (N - 1)) ) prior;
#else
typedef AUX_WRAPPER_INST( BOOST_MPL_AUX_STATIC_CAST(AUX_WRAPPER_VALUE_TYPE, (value + 1)) ) next;
typedef AUX_WRAPPER_INST( BOOST_MPL_AUX_STATIC_CAST(AUX_WRAPPER_VALUE_TYPE, (value - 1)) ) prior;
#endif
=======
#if BOOST_WORKAROUND(__EDG_VERSION__, <= 243) \
|| defined(__clang__)
private:
BOOST_STATIC_CONSTANT(AUX_WRAPPER_VALUE_TYPE, next_value = BOOST_MPL_AUX_STATIC_CAST(AUX_WRAPPER_VALUE_TYPE, (N + 1)));
BOOST_STATIC_CONSTANT(AUX_WRAPPER_VALUE_TYPE, prior_value = BOOST_MPL_AUX_STATIC_CAST(AUX_WRAPPER_VALUE_TYPE, (N - 1)));
public:
typedef AUX_WRAPPER_INST(next_value) next;
typedef AUX_WRAPPER_INST(prior_value) prior;
#elif BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x561)) \
|| BOOST_WORKAROUND(__IBMCPP__, BOOST_TESTED_AT(502)) \
|| (BOOST_WORKAROUND(__HP_aCC, <= 53800) && (BOOST_WORKAROUND(__hpxstd98, != 1)))
typedef AUX_WRAPPER_INST( BOOST_MPL_AUX_STATIC_CAST(AUX_WRAPPER_VALUE_TYPE, (N + 1)) ) next;
typedef AUX_WRAPPER_INST( BOOST_MPL_AUX_STATIC_CAST(AUX_WRAPPER_VALUE_TYPE, (N - 1)) ) prior;
#else
typedef AUX_WRAPPER_INST( BOOST_MPL_AUX_STATIC_CAST(AUX_WRAPPER_VALUE_TYPE, (value + 1)) ) next;
typedef AUX_WRAPPER_INST( BOOST_MPL_AUX_STATIC_CAST(AUX_WRAPPER_VALUE_TYPE, (value - 1)) ) prior;
#endif
>>>>>>>

View File

@ -1,5 +1,2 @@
emsdk/
hunspell/
deploy/
o
hunspell.data

View File

@ -1,49 +0,0 @@
{
"name": "spell",
"res_folder": "./deploy/spell",
"wasm": true,
"asm": true,
"embed_mem_file": true,
"run_before": "before.py",
"run_after": "import sys;sys.path.append(\"../../../../build_tools/scripts\");import base;base.configure_common_apps();base.replaceInFile(\"./deploy/spell/spell.js\", \"__ATPOSTRUN__=[];\", \"__ATPOSTRUN__=[function(){self.onEngineInit();}];\");base.replaceInFile(\"./deploy/spell/spell.js\", \"function getBinaryPromise(){\", \"function getBinaryPromise2(){\");base.replaceInFile(\"./deploy/spell/spell_ie.js\", \"__ATPOSTRUN__=[];\", \"__ATPOSTRUN__=[function(){self.onEngineInit();}];\");base.replaceInFile(\"./deploy/spell/spell_ie.js\", \"function getBinaryPromise(){\", \"function getBinaryPromise2(){\");base.copy_file(\"./wasm/js/code.js\", \"./deploy/spell.js\");base.copy_file(\"./wasm/js/index.html\", \"./deploy/index.html\")",
"base_js_content": "./wasm/js/spell.js",
"compiler_flags": [
"-O3",
"-fno-exceptions",
"-fno-rtti",
"-Wno-unused-command-line-argument",
"-s ALLOW_MEMORY_GROWTH=1",
"-s FILESYSTEM=0",
"-s ENVIRONMENT='web,worker'"
],
"exported_functions": [
"_malloc",
"_free",
"_Spellchecker_Malloc",
"_Spellchecker_Free",
"_Spellchecker_Create",
"_Spellchecker_Destroy",
"_Spellchecker_AddDictionary",
"_Spellchecker_RemoveDicrionary",
"_Spellchecker_Load",
"_Spellchecker_Spell",
"_Spellchecker_Suggest",
"_Spellchecker_RemoveEngine",
"_Spellchecker_TotalAllocatedMemory"
],
"include_path": ["./hunspell/src/hunspell", "./wasm/src"],
"define": ["WIN32", "NDEBUG", "HUNSPELL_STATIC", "BUILDING_LIBHUNSPELL", "HUNSPELL_WASM_MODULE"],
"compile_files_array": [
{
"name": "h",
"folder": "./hunspell/src/hunspell/",
"files": ["affentry.cxx", "affixmgr.cxx", "csutil.cxx", "hashmgr.cxx", "hunspell.cxx", "hunzip.cxx", "phonet.cxx", "replist.cxx", "suggestmgr.cxx"]
},
{
"name": "s",
"folder": "./wasm/src/",
"files": ["filemgr_wrapper_new.cxx", "base.cpp"]
}
]
}

View File

@ -1,125 +0,0 @@
function CSpellchecker(settings)
{
useWasm = false;
var webAsmObj = window["WebAssembly"];
if (typeof webAsmObj === "object")
{
if (typeof webAsmObj["Memory"] === "function")
{
if ((typeof webAsmObj["instantiateStreaming"] === "function") || (typeof webAsmObj["instantiate"] === "function"))
useWasm = true;
}
}
var enginePath = "./spell/";
if (settings && settings.enginePath)
{
enginePath = settings.enginePath;
if (enginePath.substring(enginePath.length - 1) != "/")
enginePath += "/";
}
var dictionariesPath = "./../dictionaries";
if (settings && settings.dictionariesPath)
{
dictionariesPath = settings.dictionariesPath;
if (dictionariesPath.substring(dictionariesPath.length - 1) == "/")
dictionariesPath = dictionariesPath.substr(0, dictionariesPath.length - 1);
}
var isUseSharedWorker = !!window.SharedWorker;
if (isUseSharedWorker && (false === settings.useShared))
isUseSharedWorker = false;
var worker_src = useWasm ? "spell.js" : "spell_ie.js";
worker_src = enginePath + worker_src;
var _worker = this;
var _port = null;
if (isUseSharedWorker)
{
this.worker = new SharedWorker(worker_src, "onlyoffice-spellchecker");
_port = this.worker.port;
}
else
{
this.worker = new Worker(worker_src);
_port = this.worker;
}
this.languages = {
"1068" : "az_Latn_AZ",
"1026" : "bg_BG",
"1027" : "ca_ES",
"2051" : "ca_ES_valencia",
"1029" : "cs_CZ",
"1030" : "da_DK",
"3079" : "de_AT",
"2055" : "de_CH",
"1031" : "de_DE",
"1032" : "el_GR",
"3081" : "en_AU",
"4105" : "en_CA",
"2057" : "en_GB",
"1033" : "en_US",
"7177" : "en_ZA",
"3082" : "es_ES",
"1069" : "eu_ES",
"1036" : "fr_FR",
"1110" : "gl_ES",
"1050" : "hr_HR",
"1038" : "hu_HU",
"1057" : "id_ID",
"1040" : "it_IT",
"1087" : "kk_KZ",
"1042" : "ko_KR",
"1134" : "lb_LU",
"1063" : "lt_LT",
"1062" : "lv_LV",
"1104" : "mn_MN",
"1044" : "nb_NO",
"1043" : "nl_NL",
"2068" : "nn_NO",
"1045" : "pl_PL",
"1046" : "pt_BR",
"2070" : "pt_PT",
"1048" : "ro_RO",
"1049" : "ru_RU",
"1051" : "sk_SK",
"1060" : "sl_SI",
"10266" : "sr_Cyrl_RS",
"9242" : "sr_Latn_RS",
"1053" : "sv_SE",
"1055" : "tr_TR",
"1058" : "uk_UA",
"1066" : "vi_VN",
"2067" : "nl_NL" // nl_BE
};
_port.onmessage = function(message) {
_worker.oncommand && _worker.oncommand(message.data);
};
_port.postMessage({ "type" : "init", "dictionaries_path" : dictionariesPath, "languages" : this.languages });
this.stop = function()
{
this.worker.terminate();
this.worker = null;
};
this.command = function(message)
{
_port && _port.postMessage(message);
};
this.oncommand = function(message) { console.log(message); };
this.checkDictionary = function(lang) {
return (undefined !== this.languages["" + lang]) ? true : false;
};
this.getLanguages = function() {
var ret = [];
for (var lang in this.languages)
ret.push(lang);
return ret;
};
}

View File

@ -1,33 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Demo of spellchecker</title>
<meta name="viewport" content="width=device-width">
<script src="./spell.js"></script>
<script type="text/javascript">
window.spellcheck = new CSpellchecker({
enginePath : "./spell",
dictionariesPath : "./../dictionaries"
});
window.spellcheck.oncommand = function(message) {
console.log(message);
};
window.spellcheck.command({
"type" : "spell",
"usrLang" : [1033, 1033, 1049],
"usrWords" : ["hello", "hellop", "привет"]
});
window.spellcheck.command({
"type" : "suggest",
"usrLang" : [1033],
"usrWords" : ["hellop"]
});
</script>
</head>
<body>
</body>
</html>

View File

@ -1,546 +0,0 @@
var printErr = undefined;
var FS = undefined;
var print = undefined;
var fetch = self.fetch;
var getBinaryPromise = null;
if (self.AscDesktopEditor && document.currentScript && 0 == document.currentScript.src.indexOf("file:///"))
{
fetch = undefined; // fetch not support file:/// scheme
getBinaryPromise = function() {
var wasmPath = "ascdesktop://fonts/" + wasmBinaryFile.substr(8);
return new Promise(function (resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open('GET', wasmPath, true);
xhr.responseType = 'arraybuffer';
if (xhr.overrideMimeType)
xhr.overrideMimeType('text/plain; charset=x-user-defined');
else
xhr.setRequestHeader('Accept-Charset', 'x-user-defined');
xhr.onload = function () {
if (this.status == 200) {
resolve(new Uint8Array(this.response));
}
};
xhr.send(null);
});
}
}
else
{
getBinaryPromise = function() {
return getBinaryPromise2();
}
}
//polyfill
//module
self.spellchecker = null;
function onMessageEvent(data, port)
{
if (data.type == "init")
{
if (self.spellchecker)
return;
self.spellchecker = new Spellchecker();
self.spellchecker.languagesPath = data.dictionaries_path;
var languages = data.languages;
for (var i in languages)
self.spellchecker.addDefaultLanguage(i, languages[i]);
self.spellchecker.init();
return;
}
if (!self.spellchecker)
return;
self.spellchecker.messages.push(data);
if (port)
self.spellchecker.ports.push(port);
if (1 < self.spellchecker.messages.length)
{
// means we're still loading something
return;
}
self.spellchecker.checkMessage();
}
self.onconnect = function(e)
{
var port = e.ports[0];
port.onmessage = function(e) {
onMessageEvent(e.data, port);
}
};
self.onmessage = function(e)
{
onMessageEvent(e.data);
};
self.engineInit = false;
self.onEngineInit = function()
{
self.engineInit = true;
if (self.spellchecker)
{
self.spellchecker.init();
self.spellchecker.checkMessage();
}
};
function Dictionary()
{
this.dataAff = null;
this.dataDic = null;
this.status = 0;
this.id = 0;
this.language = null;
this.load_file = function(src, params)
{
var xhr = new XMLHttpRequest();
xhr.sender = this;
xhr.params = params;
xhr.open('GET', src, true);
xhr.responseType = 'arraybuffer';
if (xhr.overrideMimeType)
xhr.overrideMimeType('text/plain; charset=x-user-defined');
else
xhr.setRequestHeader('Accept-Charset', 'x-user-defined');
xhr.onload = function()
{
if (xhr.sender.status >= 2)
return;
if (this.response && this.status == 200)
{
var uintData = new Uint8Array(this.response);
switch (this.params)
{
case "aff":
{
this.sender.dataAff = uintData;
break;
}
case "dic":
{
this.sender.dataDic = uintData;
break;
}
default:
break;
}
xhr.sender.status++;
}
if (xhr.sender.status == 2)
{
self.spellchecker.onLoadDictionary(this.sender);
}
};
xhr.onerror = function()
{
xhr.sender.status = 2;
self.spellchecker.onLoadDictionary(this.sender);
};
xhr.send(null);
};
this.load = function()
{
if (!this.language)
{
this.status = 2;
self.spellchecker.onLoadDictionary(this);
return;
}
this.load_file(self.spellchecker.languagesPath + "/" + this.language.aff, "aff");
this.load_file(self.spellchecker.languagesPath + "/" + this.language.dic, "dic");
};
this.freeUnusedData = function()
{
this.dataAff = null;
this.dataDic = null;
};
}
function Spellchecker()
{
this.languagesPath = "";
this.languages = {};
this.readyLanguages = {};
this.messages = [];
this.ports = [];
this.tmpStrings = new ArrayBuffer(1000);
this.engine = 0;
this.maxEngines = 3;
this.maxDictionaries = 5;
this.languageQueue = [];
this.maxDictionariesHandler = function()
{
if (this.languageQueue.length > this.maxDictionaries)
{
var toDelete = this.languageQueue.length - this.maxDictionaries;
for (let i = 0; i < toDelete; i++)
{
var lk = this.languageQueue[0];
this.deleteDictionaty(lk);
delete this.readyLanguages[lk];
this.languageQueue.shift();
}
}
};
this.deleteDictionaty = function(lk)
{
if (!lk)
return;
var affID = lk + ".aff";
var dicID = lk + ".dic"
var engineID = affID + dicID;
var engineIDptr = this.allocString(engineID);
var langAffptr = this.allocString(affID);
var langDicptr = this.allocString(dicID);
Module._Spellchecker_RemoveDicrionary(this.engine, langAffptr);
Module._Spellchecker_RemoveDicrionary(this.engine, langDicptr);
Module._Spellchecker_RemoveEngine(this.engine, engineIDptr);
this.freeString(engineIDptr);
this.freeString(langAffptr);
this.freeString(langDicptr);
};
this.init = function()
{
if (0 == this.engine && self.engineInit)
this.engine = this.createEngine();
};
this.addDefaultLanguage = function(id, path)
{
this.languages["" + id] = {
aff : path + "/" + path + ".aff",
dic : path + "/" + path + ".dic"
};
};
this.onLoadDictionary = function(dictionary)
{
if (!dictionary.dataAff || !dictionary.dataDic)
{
this.checkMessage();
return;
}
var aff_path = this.allocString(dictionary.id + ".aff");
var dic_path = this.allocString(dictionary.id + ".dic");
var pointerAff = Module._Spellchecker_Malloc(dictionary.dataAff.length);
Module.HEAP8.set(dictionary.dataAff, pointerAff);
var pointerDic = Module._Spellchecker_Malloc(dictionary.dataDic.length);
Module.HEAP8.set(dictionary.dataDic, pointerDic);
Module._Spellchecker_AddDictionary(this.engine, aff_path, pointerAff, dictionary.dataAff.length);
Module._Spellchecker_AddDictionary(this.engine, dic_path, pointerDic, dictionary.dataDic.length);
this.freeString(aff_path);
this.freeString(dic_path);
dictionary.freeUnusedData();
this.checkMessage();
};
this.checkMessage = function()
{
if (0 == this.messages.length || !self.engineInit)
return;
var m = this.messages[0];
var isReady = true;
for (var indexLang = 0, lenLangs = m.usrLang.length; indexLang < lenLangs; indexLang++)
{
var lang_key = "" + m.usrLang[indexLang];
var readyLang = this.readyLanguages[lang_key];
if (!readyLang)
{
// start loading
var langToReady = new Dictionary();
langToReady.id = lang_key;
langToReady.language = this.languages[lang_key];
this.readyLanguages[lang_key] = langToReady;
this.languageQueue.push(lang_key); // push lang info into the queue
langToReady.load();
isReady = false;
break;
}
else if (readyLang.status != 2)
{
// waiting
isReady = false;
break;
}
else
{
// all ready.
continue;
}
}
if (!isReady)
{
// waiting
return;
}
switch (m.type)
{
case "spell":
{
this.Spell(m);
break;
}
case "suggest":
{
this.Suggest(m);
break;
}
default:
break;
}
this.maxDictionariesHandler();
this.messages.shift();
};
this.allocString = function(string)
{
var inputLen = string.length;
var testLen = 6 * inputLen + 1;
if (testLen > this.tmpStrings.byteLength)
this.tmpStrings = new ArrayBuffer(testLen);
var code = 0;
var index = 0;
var outputIndex = 0;
var outputDataTmp = new Uint8Array(this.tmpStrings);
var outputData = outputDataTmp;
while (index < inputLen)
{
code = string.charCodeAt(index++);
if (code >= 0xD800 && code <= 0xDFFF && index < inputLen)
{
code = 0x10000 + (((code & 0x3FF) << 10) | (0x03FF & string.charCodeAt(index++)));
}
if (code < 0x80)
{
outputData[outputIndex++] = code;
}
else if (code < 0x0800)
{
outputData[outputIndex++] = 0xC0 | (code >> 6);
outputData[outputIndex++] = 0x80 | (code & 0x3F);
}
else if (code < 0x10000)
{
outputData[outputIndex++] = 0xE0 | (code >> 12);
outputData[outputIndex++] = 0x80 | ((code >> 6) & 0x3F);
outputData[outputIndex++] = 0x80 | (code & 0x3F);
}
else if (code < 0x1FFFFF)
{
outputData[outputIndex++] = 0xF0 | (code >> 18);
outputData[outputIndex++] = 0x80 | ((code >> 12) & 0x3F);
outputData[outputIndex++] = 0x80 | ((code >> 6) & 0x3F);
outputData[outputIndex++] = 0x80 | (code & 0x3F);
}
else if (code < 0x3FFFFFF)
{
outputData[outputIndex++] = 0xF8 | (code >> 24);
outputData[outputIndex++] = 0x80 | ((code >> 18) & 0x3F);
outputData[outputIndex++] = 0x80 | ((code >> 12) & 0x3F);
outputData[outputIndex++] = 0x80 | ((code >> 6) & 0x3F);
outputData[outputIndex++] = 0x80 | (code & 0x3F);
}
else if (code < 0x7FFFFFFF)
{
outputData[outputIndex++] = 0xFC | (code >> 30);
outputData[outputIndex++] = 0x80 | ((code >> 24) & 0x3F);
outputData[outputIndex++] = 0x80 | ((code >> 18) & 0x3F);
outputData[outputIndex++] = 0x80 | ((code >> 12) & 0x3F);
outputData[outputIndex++] = 0x80 | ((code >> 6) & 0x3F);
outputData[outputIndex++] = 0x80 | (code & 0x3F);
}
}
outputData[outputIndex++] = 0;
var tmpBuffer = new Uint8Array(this.tmpStrings, 0, outputIndex);
var pointer = Module._Spellchecker_Malloc(outputIndex);
Module.HEAP8.set(tmpBuffer, pointer);
return pointer;
};
this.freeString = function(stringPointer)
{
Module._Spellchecker_Free(stringPointer);
};
this.readFromUtf8 = function(buffer, start, len)
{
var result = "";
var index = start;
var end = start + len;
while (index < end)
{
var u0 = buffer[index++];
if (!(u0 & 128))
{
result += String.fromCharCode(u0);
continue;
}
var u1 = buffer[index++] & 63;
if ((u0 & 224) == 192)
{
result += String.fromCharCode((u0 & 31) << 6 | u1);
continue;
}
var u2 = buffer[index++] & 63;
if ((u0 & 240) == 224)
{
u0 = (u0 & 15) << 12 | u1 << 6 | u2;
}
else
{
u0 = (u0 & 7) << 18 | u1 << 12 | u2 << 6 | buffer[index++] & 63;
}
if (u0 < 65536)
{
result += String.fromCharCode(u0);
}
else
{
var ch = u0 - 65536;
result += String.fromCharCode(55296 | ch >> 10, 56320 | ch & 1023);
}
}
return result;
};
this.readSuggests = function(pointer)
{
if (0 == pointer)
return [];
var lenArray = new Int32Array(Module["HEAP8"].buffer, pointer, 4);
var len = lenArray[0];
len -= 4;
var buffer = new Uint8Array(Module["HEAP8"].buffer, pointer + 4, len);
var index = 0;
var ret = [];
while (index < len)
{
var lenRec = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24;
index += 4;
ret.push(this.readFromUtf8(buffer, index, lenRec));
index += lenRec;
}
return ret;
};
this.createEngine = function()
{
return Module._Spellchecker_Create(this.maxEngines);
};
this.destroyEngine = function()
{
Module._Spellchecker_Destroy();
};
this.Spell = function(data)
{
var len = Math.min(data.usrLang.length, data.usrWords.length);
if (0 == len)
return;
data.usrCorrect = new Array(len);
var curLang = "";
for (var i = 0; i < len; i++)
{
if (curLang != ("" + data.usrLang[i]))
{
curLang = "" + data.usrLang[i];
var aff = this.allocString(curLang + ".aff");
var dic = this.allocString(curLang + ".dic");
ret = Module._Spellchecker_Load(this.engine, aff, dic);
this.freeString(aff);
this.freeString(dic);
}
var word = this.allocString(data.usrWords[i]);
data.usrCorrect[i] = (1 == Module._Spellchecker_Spell(this.engine, word)) ? true : false;
this.freeString(word);
}
this.sendAnswer(data);
};
this.Suggest = function(data)
{
var len = Math.min(data.usrLang.length, data.usrWords.length);
if (0 == len)
return;
data.usrSuggest = new Array(len);
var curLang = "";
for (var i = 0; i < len; i++)
{
if (curLang != ("" + data.usrLang[i]))
{
curLang = "" + data.usrLang[i];
var aff = this.allocString(curLang + ".aff");
var dic = this.allocString(curLang + ".dic");
ret = Module._Spellchecker_Load(this.engine, aff, dic);
this.freeString(aff);
this.freeString(dic);
}
var word = this.allocString(data.usrWords[i]);
var pointerSuggests = Module._Spellchecker_Suggest(this.engine, word);
data.usrSuggest[i] = this.readSuggests(pointerSuggests);
this.freeString(word);
}
this.sendAnswer(data);
};
this.sendAnswer = function(data)
{
if (self.spellchecker.ports.length == 0)
{
self.postMessage(data);
}
else
{
var port = self.spellchecker.ports.shift();
port.postMessage(data);
}
setTimeout(function(){
self.spellchecker.checkMessage();
}, 1);
};
}

View File

@ -1,61 +0,0 @@
#include "base.h"
#include "engine.h"
std::map<std::string, CFileMemory*> CSpellchecker::g_dictionaries;
void* Spellchecker_Malloc(unsigned int size)
{
return ::malloc(size);
}
void Spellchecker_Free(void* p)
{
if (p)
::free(p);
}
CSpellchecker* Spellchecker_Create(size_t max_engine_number)
{
return new CSpellchecker(max_engine_number);
}
void Spellchecker_Destroy(CSpellchecker* p)
{
delete p;
}
int Spellchecker_AddDictionary(CSpellchecker* p, const char* id, unsigned char* data, unsigned int size)
{
if (!p)
return 0;
return p->AddDictionary(id, data, size);
}
void Spellchecker_RemoveDicrionary(CSpellchecker* p, const char* id)
{
if (!p)
return;
p->RemoveDictionary(id);
}
int Spellchecker_Load(CSpellchecker* p, const char* aff_id, const char* dic_id)
{
if (!p) return 0;
return p->Load(aff_id, dic_id);
}
int Spellchecker_Spell(CSpellchecker* p, const char* word_utf8)
{
return p->Spell(word_utf8);
}
unsigned char* Spellchecker_Suggest(CSpellchecker* p, const char* word_utf8)
{;
return p->Suggest(word_utf8);
}
void Spellchecker_RemoveEngine(CSpellchecker* p, const char* sid)
{
p->RemoveEngine(sid);
}
double Spellchecker_TotalAllocatedMemory()
{
struct mallinfo a;
a = mallinfo(); // Debug
return (double)a.uordblks / 1000. / 1000.;
}

View File

@ -1,22 +0,0 @@
#include <memory>
#include <malloc.h>
class CSpellchecker;
extern "C"
{
void* Spellchecker_Malloc(unsigned int size);
void Spellchecker_Free(void* p);
CSpellchecker* Spellchecker_Create(size_t max_engine_number);
void Spellchecker_Destroy(CSpellchecker*);
int Spellchecker_AddDictionary(CSpellchecker* p, const char* sid, unsigned char* data, unsigned int size);
void Spellchecker_RemoveDicrionary(CSpellchecker* p, const char* sid);
int Spellchecker_Load(CSpellchecker* p, const char* aff_id, const char* dic_id);
int Spellchecker_Spell(CSpellchecker* p, const char* word_utf8);
void Spellchecker_RemoveEngine(CSpellchecker* p, const char* sid);
unsigned char* Spellchecker_Suggest(CSpellchecker* p, const char* word_utf8);
double Spellchecker_TotalAllocatedMemory(); //Debug
}

View File

@ -1,355 +0,0 @@
#include "hunspell.h"
#include <iostream>
#include <stdlib.h>
#include "base.h"
#include <map>
#include <queue>
#include <string>
#include <memory.h>
//#define WASM_LOGGING fprintf
class CFileMemory
{
public:
unsigned char* data;
unsigned int len;
public:
CFileMemory(unsigned char* _data = NULL, unsigned int _len = 0)
{
data = _data;
len = _len;
}
~CFileMemory()
{
if (data)
{
Spellchecker_Free(data);
data = NULL;
}
}
};
class CSuggests
{
protected:
char* m_pData;
size_t m_lSize;
char* m_pDataCur;
size_t m_lSizeCur;
public:
CSuggests()
{
m_pData = NULL;
m_lSize = 0;
m_pDataCur = m_pData;
m_lSizeCur = m_lSize;
}
CSuggests(const size_t& nLen)
{
m_lSize = nLen;
m_pData = (char*)malloc(m_lSize * sizeof(char));
m_lSizeCur = 0;
m_pDataCur = m_pData;
}
virtual ~CSuggests()
{
Clear();
}
inline void AddSize(const size_t& nSize)
{
if (NULL == m_pData)
{
m_lSize = 1000;
if (nSize > m_lSize)
m_lSize = nSize;
m_pData = (char*)malloc(m_lSize * sizeof(char));
m_lSizeCur = 0;
m_pDataCur = m_pData;
return;
}
if ((m_lSizeCur + nSize) > m_lSize)
{
while ((m_lSizeCur + nSize) > m_lSize)
{
m_lSize *= 2;
}
char* pRealloc = (char*)realloc(m_pData, m_lSize * sizeof(char));
if (NULL != pRealloc)
{
// realloc succeeded
m_pData = pRealloc;
m_pDataCur = m_pData + m_lSizeCur;
}
else
{
char* pMalloc = (char*)malloc(m_lSize * sizeof(char));
memcpy(pMalloc, m_pData, m_lSizeCur * sizeof(char));
free(m_pData);
m_pData = pMalloc;
m_pDataCur = m_pData + m_lSizeCur;
}
}
}
public:
void AddInt(const unsigned int& value)
{
AddSize(4);
memcpy(m_pDataCur, &value, sizeof(unsigned int));
m_pDataCur += 4;
m_lSizeCur += 4;
}
void WriteString(const char* value, const unsigned int& len)
{
AddSize(len + 4);
memcpy(m_pDataCur, &len, sizeof(unsigned int));
m_pDataCur += 4;
m_lSizeCur += 4;
memcpy(m_pDataCur, value, len);
m_pDataCur += len;
m_lSizeCur += len;
}
unsigned char* GetBuffer()
{
return (unsigned char*)m_pData;
}
void Clear()
{
free(m_pData);
m_pData = NULL;
m_lSize = 0;
m_pDataCur = m_pData;
m_lSizeCur = 0;
}
void ClearNoAttack()
{
m_pDataCur = m_pData;
m_lSizeCur = 0;
}
unsigned int GetSize()
{
return (unsigned int)m_lSizeCur;
}
void SkipLen()
{
AddInt(0);
}
void WriteLen()
{
unsigned int len = (unsigned int)m_lSizeCur;
memcpy(m_pData, &len, sizeof(unsigned int));
}
};
class LimitedEngineMap
{
public:
LimitedEngineMap(size_t _maxEngineNumer)
{
m_nMaxEngineNumber = _maxEngineNumer;
}
~LimitedEngineMap()
{
for (std::pair<const std::string, Hunhandle*> &i : m_mapDictionariesEngines)
{
Hunspell_destroy(i.second);
}
m_mapDictionariesEngines.clear();
}
std::map<std::string, Hunhandle*>::iterator find(const std::string &to_find)
{
return m_mapDictionariesEngines.find(to_find);
}
std::map<std::string, Hunhandle*>::iterator end()
{
return m_mapDictionariesEngines.end();
}
std::pair<std::map<std::string, Hunhandle*>::iterator,bool> insert(const std::pair<std::string, Hunhandle*> &data)
{
if (m_qEngineQueue.size() == m_nMaxEngineNumber)
{
if (m_mapDictionariesEngines.find(m_qEngineQueue.front()) !=
m_mapDictionariesEngines.end())
{
Hunspell_destroy(m_mapDictionariesEngines[m_qEngineQueue.front()]);
m_mapDictionariesEngines.erase(m_qEngineQueue.front());
m_qEngineQueue.pop();
}
}
m_qEngineQueue.push(data.first);
return m_mapDictionariesEngines.insert(data);
}
void RemoveEngine(const char* id)
{
if (m_mapDictionariesEngines.find(id) == m_mapDictionariesEngines.end())
{
return;
}
std::queue<std::string> new_queue;;
Hunspell_destroy(m_mapDictionariesEngines[id]);
m_mapDictionariesEngines.erase(id);
while (!m_qEngineQueue.empty())
{
if (m_qEngineQueue.front() != id)
{
new_queue.push(m_qEngineQueue.front());
}
m_qEngineQueue.pop();
}
m_qEngineQueue = new_queue;
}
private:
std::map<std::string, Hunhandle*> m_mapDictionariesEngines;
std::queue<std::string> m_qEngineQueue;
size_t m_nMaxEngineNumber;
};
class CSpellchecker
{
public:
static std::map<std::string, CFileMemory*> g_dictionaries;
public:
LimitedEngineMap m_oDictionariesEngines;
std::string m_sCurrentDictionaryId;
Hunhandle* m_pCurrentDictionary;
CSuggests m_oSuggests;
public:
CSpellchecker(size_t _MaxEngineNumber) :
m_oDictionariesEngines(_MaxEngineNumber)
{
m_sCurrentDictionaryId = "";
m_pCurrentDictionary = NULL;
}
~CSpellchecker()
{
m_pCurrentDictionary = NULL;
for (std::pair<const std::string, CFileMemory*> &i : g_dictionaries)
{
delete i.second;
}
g_dictionaries.clear();
}
public:
int AddDictionary(const char*& id, unsigned char* data, unsigned int size)
{
#ifdef WASM_LOGGING
WASM_LOGGING(stderr, "add dictionary: [%s, %d]\n", id, (int)size);
#endif
RemoveDictionary(id);
g_dictionaries.insert(std::pair<std::string, CFileMemory*>(std::string(id), new CFileMemory(data, size)));
return 1;
}
void RemoveDictionary(const char*& id)
{
std::string sid(id);
std::map<std::string, CFileMemory*>::iterator iter = g_dictionaries.find(sid);
if (iter != g_dictionaries.end())
{
CFileMemory* file = iter->second;
g_dictionaries.erase(iter);
delete file;
}
}
static CFileMemory* Get(const char*& id)
{
std::map<std::string, CFileMemory*>::iterator iter = g_dictionaries.find(std::string(id));
if (iter == g_dictionaries.end())
return NULL;
return iter->second;
}
int Load(const char*& aff_id, const char*& dic_id)
{
#ifdef WASM_LOGGING
WASM_LOGGING(stderr, "load: [%s, %s]\n", aff_id, dic_id);
#endif
return (NULL != SetLanguage(aff_id, dic_id)) ? 1 : 0;
}
int Spell(const char*& word)
{
#ifdef WASM_LOGGING
WASM_LOGGING(stderr, "spell: [%s]\n", word);
#endif
if (!m_pCurrentDictionary)
return 0;
return Hunspell_spell(m_pCurrentDictionary, word);
}
unsigned char* Suggest(const char*& word)
{
#ifdef WASM_LOGGING
WASM_LOGGING(stderr, "suggest: [%s]\n", word);
#endif
if (!m_pCurrentDictionary)
return NULL;
char** pSuggest;
int nSuggestCount = Hunspell_suggest(m_pCurrentDictionary, &pSuggest, word);
m_oSuggests.ClearNoAttack();
m_oSuggests.SkipLen();
for (int i = 0; i < nSuggestCount; ++i)
{
m_oSuggests.WriteString(pSuggest[i], (unsigned int)strlen(pSuggest[i]));
}
m_oSuggests.WriteLen();
if (0 < nSuggestCount)
Hunspell_free_list(m_pCurrentDictionary, &pSuggest, nSuggestCount);
return m_oSuggests.GetBuffer();
}
void RemoveEngine(const char* id)
{
m_oDictionariesEngines.RemoveEngine(id);
if (m_sCurrentDictionaryId == id)
{
m_sCurrentDictionaryId = "";
m_pCurrentDictionary = NULL;
}
}
protected:
Hunhandle* SetLanguage(const std::string& aff_id, const std::string& dic_id)
{
if ((aff_id + dic_id) == m_sCurrentDictionaryId)
return m_pCurrentDictionary;
m_sCurrentDictionaryId = aff_id + dic_id;
m_pCurrentDictionary = NULL;
std::map<std::string, Hunhandle*>::iterator iterEngine = m_oDictionariesEngines.find(m_sCurrentDictionaryId);
if (iterEngine != m_oDictionariesEngines.end())
{
m_pCurrentDictionary = iterEngine->second;
return m_pCurrentDictionary;
}
Hunhandle* pDictionary = Hunspell_create(aff_id.c_str(), dic_id.c_str());
m_oDictionariesEngines.insert(std::pair<std::string, Hunhandle*>(m_sCurrentDictionaryId, pDictionary));
m_pCurrentDictionary = pDictionary;
return m_pCurrentDictionary;
}
};

View File

@ -1,58 +0,0 @@
#include "license.hunspell"
#include "license.myspell"
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "filemgr.hxx"
#include "csutil.hxx"
#include "./engine.h"
int FileMgr::fail(const char * err, const char * par) {
fprintf(stderr, err, par);
return -1;
}
FileMgr::FileMgr(const char * file, const char * key)
: hin(NULL), fin(NULL), linenum(0)
{
in[0] = '\0';
CFileMemory* file_memory = CSpellchecker::Get(file);
if (!file_memory)
{
fail(MSG_OPEN, file);
}
else
{
index = 0;
size = file_memory->len;
memory = (char*)file_memory->data;
}
}
FileMgr::~FileMgr()
{
if (fin) fclose(fin);
if (hin) delete hin;
}
char * FileMgr::getline() {
if(index >= size)
return NULL;
int i = 0,
l = BUFSIZE -1;
for(;index < size && memory[index] != '\n' && memory[index] != EOF && i <= l; index++, i++)
in[i] = memory[index];
in[i] = '\0';
index++;
if(index < size)
linenum++;
return strdup(in);
}
int FileMgr::getlinenum() {
return linenum;
}

View File

@ -1,52 +0,0 @@
//#include "license.hunspell"
//#include "license.myspell"
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "./filemgr.hxx"
#include "csutil.hxx"
#include "./engine.h"
int FileMgr::fail(const char *err, const char *par)
{
fprintf(stderr, err, par);
return -1;
}
FileMgr::FileMgr(const char *file, const char *key)
: hin(NULL), linenum(0), memin(NULL)
{
in[0] = '\0';
CFileMemory *file_memory = CSpellchecker::Get(file);
if (!file_memory)
{
fail(MSG_OPEN, file);
}
else
{
memin.from_buffer((char *)file_memory->data, file_memory->len);
}
}
FileMgr::~FileMgr()
{
if (hin)
delete hin;
}
bool FileMgr::getline(std::string &dest)
{
bool ret = memin.get_line(dest);
if (ret)
++linenum;
return ret;
}
int FileMgr::getlinenum()
{
return linenum;
}

View File

@ -1,37 +0,0 @@
#include "./base.h"
#include <iostream>
int main()
{
CSpellchecker* spell = Spellchecker_Create(100);
FILE* fAff = fopen("en_GB.aff", "rb");
fseek(fAff, 0, SEEK_END);
unsigned int nAffSize = (unsigned int)ftell(fAff);
fseek(fAff, 0, SEEK_SET);
unsigned char* pAffData = (unsigned char*)Spellchecker_Malloc(nAffSize);
size_t nAffSizeRead = fread((void*)pAffData, 1, (size_t)nAffSize, fAff);
fclose(fAff);
FILE* fDic = fopen("en_GB.dic", "rb");
fseek(fDic, 0, SEEK_END);
unsigned int nDicSize = (unsigned int)ftell(fDic);
fseek(fDic, 0, SEEK_SET);
unsigned char* pDicData = (unsigned char*)Spellchecker_Malloc(nDicSize);
size_t nDicSizeRead = fread((void*)pDicData, 1, (size_t)nDicSize, fDic);
fclose(fDic);
int bIsAdd1 = Spellchecker_AddDictionary(spell, "en_US.aff", pAffData, nAffSize);
int bIsAdd2 = Spellchecker_AddDictionary(spell, "en_US.dic", pDicData, nDicSize);
while(1) {
Spellchecker_Load(spell, "en_US.aff", "en_US.dic");
Spellchecker_RemoveEngine(spell, "en_US.affen_US.dic");
std::cout << Spellchecker_Debug() << std::endl;
}
// int nCheck1 = Spellchecker_Spell(spell, "hello");
// int nCheck2 = Spellchecker_Spell(spell, "hellop");
// unsigned char* pSuggestData = Spellchecker_Suggest(spell, "hellop");
Spellchecker_Destroy(spell);
return 0;
}

View File

@ -1,50 +0,0 @@
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
class string_buffer_stream
{
private:
char* m_buffer;
unsigned int m_pos;
unsigned int m_size;
public:
string_buffer_stream(char* buf = NULL, unsigned int len = 0)
{
m_buffer = buf;
m_pos = 0;
m_size = len;
}
void from_buffer(char* buf, unsigned int len)
{
m_buffer = buf;
m_pos = 0;
m_size = len;
}
// emulate
// https://en.cppreference.com/w/cpp/string/basic_string/getline
bool get_line(std::string& data)
{
data.erase();
if (m_pos >= m_size)
return false;
while (m_pos < m_size)
{
char c = m_buffer[m_pos++];
if (c == '\n')
break;
if (c == '\r')
{
if (m_pos < m_size && m_buffer[m_pos] == '\n')
++m_pos;
break;
}
data += c;
}
return true;
}
};

View File

@ -1,14 +0,0 @@
import sys
sys.path.append("../../../../../../build_tools/scripts")
import base
base.configure_common_apps()
base.replaceInFile("../deploy/engine/hyphen.js", "__ATPOSTRUN__=[];", "__ATPOSTRUN__=[onLoadModule];")
base.replaceInFile("../deploy/engine/hyphen_ie.js", "__ATPOSTRUN__=[];", "__ATPOSTRUN__=[onLoadModule];")
base.replaceInFile("../deploy/engine/hyphen.js", "__ATPOSTRUN__ = [];", "__ATPOSTRUN__=[onLoadModule];")
base.replaceInFile("../deploy/engine/hyphen_ie.js", "__ATPOSTRUN__ = [];", "__ATPOSTRUN__=[onLoadModule];")
base.replaceInFile("../deploy/engine/hyphen.js", "function getBinaryPromise()", "function getBinaryPromise2()")
base.replaceInFile("../deploy/engine/hyphen_ie.js", "function getBinaryPromise()", "function getBinaryPromise2()")
base.copy_file("../library.js", "../deploy/hyphen.js")

View File

@ -1,40 +0,0 @@
{
"name": "hyphen",
"res_folder": "../deploy/engine",
"wasm": true,
"asm": true,
"embed_mem_file": true,
"run_before": "",
"run_after": "after.py",
"base_js_content": "../module.js",
"compiler_flags": [
"-O3",
"-fno-exceptions",
"-fno-rtti",
"-Wno-unused-command-line-argument",
"-sALLOW_MEMORY_GROWTH"
],
"exported_functions": [
"_malloc",
"_free",
"_hyphenCreateApplication",
"_hyphenDestroyApplication",
"_hyphenLoadDictionary",
"_hyphenWord"
],
"include_path": ["../src"],
"define": ["GRAPHICS_NO_USE_DYNAMIC_LIBRARY", "HYPHEN_ENGINE_DISABLE_FILESYSTEM"],
"compile_files_array": [
{
"name": "h_e",
"folder": "../../../../../DesktopEditor/fontengine",
"files": ["TextHyphen.cpp"]
},
{
"name": "h_m",
"folder": "../src",
"files": ["hyphen.cpp"]
}
]
}

View File

@ -1,43 +0,0 @@
(function(window) {
window.hyphen = window.hyphen || {};
window.hyphen.isReady = false;
var not_ready = function() {
console.log('Module is not ready');
}
window.hyphen.destroyApplication = not_ready;
window.hyphen.loadDictionary = not_ready;
window.hyphen.hyphenWord = not_ready;
window.hyphen.onLoadModule = function(exports) {
window.hyphen.isReady = true;
window.hyphen.destroyApplication = exports.destroyApplication;
window.hyphen.loadDictionary = exports.loadDictionary;
window.hyphen.hyphenWord = exports.hyphenWord;
};
window.hyphen.loadModule = function() {
var path = '../deploy/engine/';
// wasm support check
var useWasm = false;
const webAsmObj = window['WebAssembly'];
if (typeof webAsmObj === 'object') {
if (typeof webAsmObj['Memory'] === 'function') {
if ((typeof webAsmObj['instantiateStreaming'] === 'function') || (typeof webAsmObj['instantiate'] === 'function')) {
useWasm = true;
}
}
}
path += (useWasm ? 'hyphen.js' : 'hyphen_ie.js');
const script = document.createElement('script');
script.type = 'text/javascript';
script.src = path;
document.head.appendChild(script);
}
})(self);

View File

@ -1,81 +0,0 @@
(function(window) {
var isModuleLoaded = false;
var application;
function onLoadModule() {
isModuleLoaded = true;
application = Module._hyphenCreateApplication();
if (window.hyphen) {
window.hyphen.onLoadModule && window.hyphen.onLoadModule({
destroyApplication: function() {
Module._hyphenDestroyApplication(application);
},
loadDictionary: hyphenLoadDictionary,
hyphenWord: hyphenWord
});
}
};
//desktop_fetch
//polyfill
//string_utf8
//module
/**
*
* @param {Number} app
* @param {Number} lang
* @param {arraybuffer} dict
* @returns {Boolean} isSuccess
*/
function hyphenLoadDictionary(lang, dict)
{
if (!isModuleLoaded)
return;
let dictSize = dict.byteLength;
let dictPointer = Module._malloc(dictSize);
Module.HEAP8.set(new Uint8ClampedArray(dict), dictPointer);
let result = Module._hyphenLoadDictionary(application, lang, dictPointer, dictSize);
Module._free(dictPointer);
return (result === 0) ? true : false;
}
/**
*
* @param {Number} lang
* @param {String} word
* @returns {Array}
* Returns hyphen vector of word
*/
function hyphenWord(lang, word)
{
if (!isModuleLoaded)
return;
let wordPointer = word.toUtf8Pointer();
let wordLen = wordPointer.length;
let hyphens = [];
if (wordPointer)
{
const ptr = Module._hyphenWord(application, lang, wordPointer.ptr, wordLen);
wordPointer.free();
let vector = new Uint8ClampedArray(Module.HEAP8.buffer, ptr, wordLen + 5);
for (let i = 0; vector[i] != 0; i++)
{
if (1 == (vector[i] & 1))
hyphens.push((i + 1));
}
}
return hyphens;
}
})(self);

View File

@ -1,68 +0,0 @@
/*
* (c) Copyright Ascensio System SIA 2010-2023
*
* This program is a free software product. You can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License (AGPL)
* version 3 as published by the Free Software Foundation. In accordance with
* Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
* that Ascensio System SIA expressly excludes the warranty of non-infringement
* of any third-party rights.
*
* This program is distributed WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For
* details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
*
* You can contact Ascensio System SIA at 20A-6 Ernesta Birznieka-Upish
* street, Riga, Latvia, EU, LV-1050.
*
* The interactive user interfaces in modified source and object code versions
* of the Program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU AGPL version 3.
*
* Pursuant to Section 7(b) of the License you must retain the original Product
* logo when distributing the program. Pursuant to Section 7(e) we decline to
* grant you any rights under trademark law for use of our trademarks.
*
* All the Product's GUI elements, including illustrations and icon sets, as
* well as technical writing content are licensed under the terms of the
* Creative Commons Attribution-ShareAlike 4.0 International. See the License
* terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
*
*/
#include "../../../../../DesktopEditor/fontengine/TextHyphen.h"
#ifdef _WIN32
#define WASM_EXPORT __declspec(dllexport)
#else
#define WASM_EXPORT __attribute__((visibility("default")))
#endif
#ifdef __cplusplus
extern "C" {
#endif
WASM_EXPORT NSHyphen::CEngine* hyphenCreateApplication()
{
return new NSHyphen::CEngine();
}
WASM_EXPORT void hyphenDestroyApplication(NSHyphen::CEngine* app)
{
delete app;
}
WASM_EXPORT int hyphenLoadDictionary(NSHyphen::CEngine* app, const int lang, const char *dict, const unsigned int dict_size)
{
return app->LoadDictionary(lang, (const unsigned char*)dict, dict_size);
}
WASM_EXPORT int hyphenCheckDictionary(NSHyphen::CEngine* app, const int lang)
{
return app->IsDictionaryExist(lang) ? 1 : 0;
}
WASM_EXPORT char* hyphenWord(NSHyphen::CEngine* app, const int lang, const char *word, const int word_len)
{
return app->Process(lang, word, word_len);
}
#ifdef __cplusplus
}
#endif

View File

@ -1,52 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>test</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<form>
<textarea id = "textarea"></textarea>
<button type = "submit">OK</button>
<select name = "combobox" id = "combobox">
<option></option>
<option value = "bg_BG">bg_BG</option>
<option value = "ca_ES">ca_ES</option>
<option value = "da_DK">da_DK</option>
<option value = "de_AT">de_AT</option>
<option value = "de_CH">de_CH</option>
<option value = "de_DE">de_DE</option>
<option value = "el_GR">el_GR</option>
<option value = "en_AU">en_AU</option>
<option value = "en_GB">en_GB</option>
<option value = "en_US">en_US</option>
<option value = "es_ES">es_ES</option>
<option value = "fr_FR">fr_FR</option>
<option value = "gl_ES">gl_ES</option>
<option value = "hr_HR">hr_HR</option>
<option value = "hu_HU">hu_HU</option>
<option value = "id_ID">id_ID</option>
<option value = "it_IT">it_IT</option>
<option value = "lv_LV">lv_LV</option>
<option value = "mn_MN">mn_MN</option>
<option value = "nb_NO">nb_NO</option>
<option value = "nl_NL">nl_NL</option>
<option value = "nn_NO">nn_NO</option>
<option value = "pl_PL">pl_PL</option>
<option value = "pt_BR">pt_BR</option>
<option value = "pt_PT">pt_PT</option>
<option value = "ro_RO">ro_RO</option>
<option value = "ru_RU">ru_RU</option>
<option value = "sk_SK">sk_SK</option>
<option value = "sl_SI">sl_SI</option>
<option value = "sr_Cyrl_RS">sr_Cyrl_RS</option>
<option value = "sr_Latn_RS">sr_Latn_RS</option>
<option value = "sv_SE">sv_SE</option>
<option value = "uk_UA">uk_UA</option>
</select>
</form>
<script src = "../deploy/hyphen.js"></script>
<script src = "main.js"></script>
</body>
</html>

View File

@ -1,117 +0,0 @@
(function (window, undefined) {
window.hyphen.loadModule();
var langs = {
"az_Latn_AZ" : 1068,
"bg_BG" : 1026,
"ca_ES" : 1027,
"ca_ES_valencia" : 2051,
"cs_CZ" : 1029,
"da_DK" : 1030,
"de_AT" : 3079,
"de_CH" : 2055,
"de_DE" : 1031,
"el_GR" : 1032,
"en_AU" : 3081,
"en_CA" : 4105,
"en_GB" : 2057,
"en_US" : 1033,
"en_ZA" : 7177,
"es_ES" : 3082,
"eu_ES" : 1069,
"fr_FR" : 1036,
"gl_ES" : 1110,
"hr_HR" : 1050,
"hu_HU" : 1038,
"id_ID" : 1057,
"it_IT" : 1040,
"kk_KZ" : 1087,
"ko_KR" : 1042,
"lb_LU" : 1134,
"lt_LT" : 1063,
"lv_LV" : 1062,
"mn_MN" : 1104,
"nb_NO" : 1044,
"nl_NL" : 1043,
"nn_NO" : 2068,
"oc_FR" : 1154,
"pl_PL" : 1045,
"pt_BR" : 1046,
"pt_PT" : 2070,
"ro_RO" : 1048,
"ru_RU" : 1049,
"sk_SK" : 1051,
"sl_SI" : 1060,
"sr_Cyrl_RS" : 10266,
"sr_Latn_RS" : 9242,
"sv_SE" : 1053,
"tr_TR" : 1055,
"uk_UA" : 1058,
"uz_Cyrl_UZ" : 2115,
"uz_Latn_UZ" : 1091,
"vi_VN" : 1066,
"nl_NL" : 2067
};
var textarea = document.getElementById("textarea");
var form = document.querySelector("form");
var combobox = document.getElementById("combobox");
combobox.value = "en_US";
textarea.value = "expedition";
form.onsubmit = function(event)
{
if(combobox.value == "")
return;
var lang = combobox.value;
var text = textarea.value.split("\n").join(" ").split(" ");
var request = new XMLHttpRequest();
var path = '../../../../../../dictionaries/' + lang + '/' + 'hyph_' + lang + '.dic';
request.responseType = 'arraybuffer';
if (request.overrideMimeType) {
request.overrideMimeType('text/plain; charset=x-user-defined');
} else {
request.setRequestHeader('Accept-Charset', 'x-user-defined');
}
request.open('GET', path, true);
request.send(null);
request.onload = function ()
{
var dict = request.response;
var langInt = langs[lang];
window.hyphen.loadDictionary(langInt, dict);
for (var i = 0; i < text.length; i++)
{
var hyphens = window.hyphen.hyphenWord(langInt, text[i].toLowerCase());
let itemUtf8 = text[i].toUtf8(true);
let start = 0;
let hword = "";
for (let j = 0, len = hyphens.length; j < len; j++)
{
hword += "".fromUtf8(itemUtf8, start, hyphens[j] - start);
hword += "=";
start = hyphens[j];
}
if (start < itemUtf8.length)
{
hword += "".fromUtf8(itemUtf8, start);
hword += "=";
}
console.log(hword);
}
}
event.preventDefault();
}
})(self);

View File

@ -1,10 +0,0 @@
button {
width: 60px;
height: 30px;
}
#textarea{
display: block;
width: 300px;
height: 300px;
}

View File

@ -30,7 +30,7 @@ if False:
build_func()
else:
if not base.is_file("./build.7z"):
base.download("http://d2ettrnqo7v976.cloudfront.net/v8/android/build.7z", "./build.7z")
base.download("https://github.com/ONLYOFFICE-data/build_tools_data/raw/refs/heads/master/android/v8.7z", "./build.7z")
base.extract("./build.7z", "./")
base.copy_dir("./build/v8", "./v8")
base.delete_dir("./build/v8")

View File

@ -1578,25 +1578,31 @@ namespace NSFile
std::wstring CFileBinary::CreateTempFileWithUniqueName(const std::wstring& strFolderPathRoot, const std::wstring& Prefix)
{
#if defined(_WIN32) || defined(_WIN32_WCE) || defined(_WIN64)
wchar_t pBuffer[MAX_PATH + 1];
::GetTempFileNameW(strFolderPathRoot.c_str(), Prefix.c_str(), 0, pBuffer);
std::wstring sRet(pBuffer);
return sRet;
wchar_t pBuffer[MAX_PATH + 1] = {0};
if (0 == ::GetTempFileNameW(strFolderPathRoot.c_str(), Prefix.c_str(), 0, pBuffer))
return std::wstring();
return std::wstring(pBuffer);
#else
char pcRes[MAX_PATH];
BYTE* pData = (BYTE*)pcRes;
std::wstring sPrefix = strFolderPathRoot + L"/" + Prefix + L"_XXXXXX";
LONG lLen = 0;
NSFile::CUtf8Converter::GetUtf8StringFromUnicode(sPrefix.c_str(), (LONG)sPrefix.length(), pData, lLen);
pcRes[lLen] = '\0';
int res = mkstemp(pcRes);
LONG lLen = 0;
BYTE* pcRes = NULL;
NSFile::CUtf8Converter::GetUtf8StringFromUnicode(sPrefix.c_str(), (LONG)sPrefix.length(), pcRes, lLen);
if (lLen <= 0)
{
delete[] pcRes;
return std::wstring();
}
int res = mkstemp((char*)pcRes);
if (-1 != res)
close(res);
std::string sRes = pcRes;
return NSFile::CUtf8Converter::GetUnicodeStringFromUTF8((BYTE*)sRes.c_str(), sRes.length());
std::wstring sResult = NSFile::CUtf8Converter::GetUnicodeStringFromUTF8((BYTE*)pcRes, (LONG)lLen);
delete[] pcRes;
return sResult;
#endif
}
bool CFileBinary::OpenTempFile(std::wstring *pwsName, FILE **ppFile, wchar_t *wsMode, wchar_t *wsExt, wchar_t *wsFolder, wchar_t* wsName)

View File

@ -1520,6 +1520,9 @@ public:
++nIndexCur;
pImageDataAlpha += 4;
if (nIndexCur >= nIndexCurLimit)
break;
if (0 != *pImageDataAlpha)
break;
}

View File

@ -1 +0,0 @@
deploy/

View File

@ -1,18 +0,0 @@
#!/usr/bin/env python
import sys
sys.path.append("../../../../build_tools/scripts")
import base
import os
base.configure_common_apps()
base.replaceInFile("./deploy/fonts.js", "__ATPOSTRUN__=[];", "__ATPOSTRUN__=[function(){window[\"AscFonts\"].onLoadModule();}];")
base.replaceInFile("./deploy/fonts.js", "__ATPOSTRUN__ = [];", "__ATPOSTRUN__=[function(){window[\"AscFonts\"].onLoadModule();}];")
base.replaceInFile("./deploy/fonts.js", "function getBinaryPromise(", "function getBinaryPromise2(")
base.replaceInFile("./deploy/fonts_ie.js", "__ATPOSTRUN__=[];", "__ATPOSTRUN__=[function(){window[\"AscFonts\"].onLoadModule();}];")
base.replaceInFile("./deploy/fonts_ie.js", "__ATPOSTRUN__ = [];", "__ATPOSTRUN__=[function(){window[\"AscFonts\"].onLoadModule();}];")
base.replaceInFile("./deploy/fonts_ie.js", "function getBinaryPromise(", "function getBinaryPromise2(")
base.cmd_in_dir("../../../Common/js", "python", ["./min.py", "./../../DesktopEditor/fontengine/js/deploy/fonts.js", "WHITESPACE_ONLY"])
base.cmd_in_dir("../../../Common/js", "python", ["./min.py", "./../../DesktopEditor/fontengine/js/deploy/fonts_ie.js", "WHITESPACE_ONLY"])

View File

@ -1,11 +0,0 @@
#!/usr/bin/env python
import sys
sys.path.append("../../../../../build_tools/scripts")
import base
import os
base.configure_common_apps()
base.copy_file("./index.html", "./deploy/index.html")
#base.cmd_in_dir("../../../../Common/js", "python", ["./min.py", "./../../DesktopEditor/fontengine/js/allfonts/deploy/allfonts.js", "WHITESPACE_ONLY"])

View File

@ -1,9 +0,0 @@
#!/usr/bin/env python
import sys
import os
sys.path.append("../../../../../build_tools/scripts")
import base
base.configure_common_apps()
print("before...")

View File

@ -1,11 +0,0 @@
<!doctype html>
<html style="width:100%;height:100%;margin:0;padding:0;">
<head>
<title>ONLYOFFICE Fonts</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=IE8">
<script src="./allfonts.js"></script>
</head>
<body>
</body>
</html>

View File

@ -1,41 +0,0 @@
{
"name": "allfonts",
"res_folder": "./deploy",
"wasm": true,
"asm": false,
"run_before": "before.py",
"run_after": "after.py",
"base_js_content": "./module.js",
"compiler_flags": [
"-O3",
"-fexceptions",
"-Wno-unused-command-line-argument",
"-s ALLOW_MEMORY_GROWTH=1",
"-s FILESYSTEM=0",
"-s ENVIRONMENT='web'",
"-s LLD_REPORT_UNDEFINED",
"-s ASYNCIFY"
],
"exported_functions": [
"_malloc",
"_free",
"_parseSystemFonts",
"_createFontBinary",
"_deleteFontBinary"
],
"include_path": [
],
"define": [
"__linux__", "_LINUX", "UNIX", "_QT"
],
"compile_files_array": [
{
"folder": "./src",
"files": [
"main.cpp"
]
}
]
}

View File

@ -1,74 +0,0 @@
/*
* (c) Copyright Ascensio System SIA 2010-2024
*
* This program is a free software product. You can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License (AGPL)
* version 3 as published by the Free Software Foundation. In accordance with
* Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
* that Ascensio System SIA expressly excludes the warranty of non-infringement
* of any third-party rights.
*
* This program is distributed WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For
* details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
*
* You can contact Ascensio System SIA at 20A-6 Ernesta Birznieka-Upish
* street, Riga, Latvia, EU, LV-1050.
*
* The interactive user interfaces in modified source and object code versions
* of the Program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU AGPL version 3.
*
* Pursuant to Section 7(b) of the License you must retain the original Product
* logo when distributing the program. Pursuant to Section 7(e) we decline to
* grant you any rights under trademark law for use of our trademarks.
*
* All the Product's GUI elements, including illustrations and icon sets, as
* well as technical writing content are licensed under the terms of the
* Creative Commons Attribution-ShareAlike 4.0 International. See the License
* terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
*
*/
(function(window, undefined) {
window['AscFonts'] = window['AscFonts'] || {};
let AscFonts = window['AscFonts'];
//string_utf8
//module
AscFonts.checkSystemFonts = async function()
{
self.queryLocalFonts()
.then(async function (fonts) {
AscFonts.systemFonts = fonts;
Module["_parseSystemFonts"](fonts.length);
})
.catch(function (err) {
console.error(err.name, err.message);
});
};
AscFonts.getSystemFont = async function(index)
{
let buffer = await (await AscFonts.systemFonts[index].blob()).arrayBuffer();
let array8 = new Uint8Array(buffer);
var pointer = Module["_malloc"](array8.length);
Module["HEAP8"].set(array8, pointer);
return Module["_createFontBinary"](index, pointer, array8.length);
AscFonts.systemFonts[index].blob()
.then(async function (blob) {
let buffer = await blob.arrayBuffer();
let array8 = new Uint8Array(buffer);
var pointer = Module["_malloc"](array8.length);
Module["HEAP8"].set(array8, pointer);
return Module["_createFontBinary"](index, pointer, array8.length);
});
};
})(window, undefined);

View File

@ -1,69 +0,0 @@
#include <malloc.h>
#include <stdio.h>
#ifdef _WIN32
#define WASM_EXPORT __declspec(dllexport)
#else
#define WASM_EXPORT __attribute__((visibility("default")))
#endif
class CFontBinary
{
public:
unsigned char* Data = NULL;
int Size = 0;
int Index = 0;
public:
CFontBinary()
{
}
~CFontBinary()
{
if (NULL != Data)
delete [] Data;
}
};
#include "emscripten.h"
//EM_JS
EM_ASYNC_JS(CFontBinary*, js_get_system_font, (int index), {
return AscFonts.getSystemFont(index);
});
#ifdef __cplusplus
extern "C" {
#endif
WASM_EXPORT CFontBinary* createFontBinary(int index, unsigned char* data, int size)
{
CFontBinary* pFont = new CFontBinary();
pFont->Index = index;
pFont->Data = data;
pFont->Size = size;
return pFont;
}
WASM_EXPORT void deleteFontBinary(CFontBinary* pFont)
{
delete pFont;
}
WASM_EXPORT void parseSystemFonts(int size)
{
printf("[native] fonts: %d\n", size);
for (int i = 0; i < size; ++i)
{
CFontBinary* pFont = js_get_system_font(i);
printf("[native] %d, %d\n", pFont->Index, pFont->Size);
delete pFont;
}
}
#ifdef __cplusplus
}
#endif

View File

@ -1,10 +0,0 @@
#!/usr/bin/env python
import sys
import os
sys.path.append("../../../../build_tools/scripts")
import base
base.configure_common_apps()
base.cmd_in_dir("./../../graphics/pro/js", "./before.py")

View File

@ -1,674 +0,0 @@
/*
* (c) Copyright Ascensio System SIA 2010-2024
*
* This program is a free software product. You can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License (AGPL)
* version 3 as published by the Free Software Foundation. In accordance with
* Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
* that Ascensio System SIA expressly excludes the warranty of non-infringement
* of any third-party rights.
*
* This program is distributed WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For
* details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
*
* You can contact Ascensio System SIA at 20A-6 Ernesta Birznieka-Upish
* street, Riga, Latvia, EU, LV-1050.
*
* The interactive user interfaces in modified source and object code versions
* of the Program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU AGPL version 3.
*
* Pursuant to Section 7(b) of the License you must retain the original Product
* logo when distributing the program. Pursuant to Section 7(e) we decline to
* grant you any rights under trademark law for use of our trademarks.
*
* All the Product's GUI elements, including illustrations and icon sets, as
* well as technical writing content are licensed under the terms of the
* Creative Commons Attribution-ShareAlike 4.0 International. See the License
* terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
*
*/
#include "../../TextShaper_p.h"
#ifdef _WIN32
#define WASM_EXPORT __declspec(dllexport)
#else
#define WASM_EXPORT __attribute__((visibility("default")))
#endif
#ifdef __cplusplus
extern "C" {
#endif
// LIBRARY ----------------------------------------------------
WASM_EXPORT void* ASC_FT_Malloc(unsigned int size)
{
return ft_smalloc((size_t)size);
}
WASM_EXPORT void ASC_FT_Free(void* p)
{
ft_sfree(p);
}
WASM_EXPORT FT_Library ASC_FT_Init()
{
FT_Library library = NULL;
FT_Init_FreeType(&library);
FT_Library_SetLcdFilter(library, FT_LCD_FILTER_DEFAULT);
return library;
}
WASM_EXPORT void ASC_FT_Done_FreeType(FT_Library library)
{
FT_Done_FreeType(library);
}
WASM_EXPORT int ASC_FT_Set_TrueType_HintProp(FT_Library library, unsigned int interpreter_version)
{
FT_UInt _interpreter_version = interpreter_version;
return FT_Property_Set(library, "truetype", "interpreter-version", &_interpreter_version);
}
// ------------------------------------------------------------
// FACE -------------------------------------------------------
WASM_EXPORT FT_Face ASC_FT_Open_Face(FT_Library library, unsigned char* memory, unsigned int size, int face_index)
{
FT_Open_Args oOpenArgs;
oOpenArgs.flags = FT_OPEN_MEMORY | FT_OPEN_PARAMS;
oOpenArgs.memory_base = memory;
oOpenArgs.memory_size = (FT_Long)size;
FT_Parameter *pParams = (FT_Parameter *)ft_smalloc( sizeof(FT_Parameter) * 4 );
pParams[0].tag = FT_MAKE_TAG( 'i', 'g', 'p', 'f' );
pParams[0].data = NULL;
pParams[1].tag = FT_MAKE_TAG( 'i', 'g', 'p', 's' );
pParams[1].data = NULL;
pParams[2].tag = FT_PARAM_TAG_IGNORE_PREFERRED_FAMILY;
pParams[2].data = NULL;
pParams[3].tag = FT_PARAM_TAG_IGNORE_PREFERRED_SUBFAMILY;
pParams[3].data = NULL;
oOpenArgs.params = pParams;
oOpenArgs.num_params = 4;
FT_Face face;
int error = FT_Open_Face( library, &oOpenArgs, face_index, &face );
ft_sfree(pParams);
if (error)
return NULL;
return face;
}
WASM_EXPORT void ASC_FT_Done_Face(FT_Face face)
{
FT_Done_Face(face);
}
WASM_EXPORT unsigned int ASC_FT_SetCMapForCharCode(FT_Face face, unsigned int unicode)
{
if (!face)
return 0;
if ( 0 == face->num_charmaps )
return 0;
unsigned int nCharIndex = 0;
for ( int nIndex = 0; nIndex < face->num_charmaps; ++nIndex )
{
FT_CharMap pCharMap = face->charmaps[nIndex];
if ( FT_Set_Charmap( face, pCharMap ) )
continue;
FT_Encoding pEncoding = pCharMap->encoding;
if ( FT_ENCODING_UNICODE == pEncoding )
{
nCharIndex = FT_Get_Char_Index( face, unicode );
if ( nCharIndex )
{
return nCharIndex;
}
}
else if ( FT_ENCODING_NONE == pEncoding || FT_ENCODING_MS_SYMBOL == pEncoding || FT_ENCODING_APPLE_ROMAN == pEncoding )
{
#if 0
FT_ULong charcode;
FT_UInt gindex;
charcode = FT_Get_First_Char( face, &gindex );
while ( gindex != 0 )
{
charcode = FT_Get_Next_Char( face, charcode, &gindex );
if ( charcode == unicode )
{
nCharIndex = gindex;
break;
}
}
#endif
nCharIndex = FT_Get_Char_Index( face, unicode );
}
}
return nCharIndex;
}
WASM_EXPORT int* ASC_FT_GetFaceInfo(FT_Face face)
{
if (!face)
return NULL;
//face->units_per_EM
//face->ascender
//face->descender
//face->height
//face->face_flags
//face->num_faces
//face->num_glyphs
//face->num_charmaps
//face->style_flags
//face->face_index
//face->family_name
//face->style_name
TT_OS2* os2 = (TT_OS2*)FT_Get_Sfnt_Table( face, ft_sfnt_os2 );
//os2->version
//os2->usWeightClass
//os2->fsSelection
//os2->usWinAscent
//os2->usWinDescent
//os2->usDefaultChar
//os2->sTypoAscender;
//os2->sTypoDescender;
//os2->sTypoLineGap;
//os2->ulUnicodeRange1
//os2->ulUnicodeRange2
//os2->ulUnicodeRange3
//os2->ulUnicodeRange4
//os2->ulCodePageRange1
//os2->ulCodePageRange2
int isSymbolic = -1;
if (os2 && 0xFFFF != os2->version)
{
FT_ULong ulCodePageRange1 = os2->ulCodePageRange1;
FT_ULong ulCodePageRange2 = os2->ulCodePageRange2;
if ((ulCodePageRange1 & 0x80000000) || (ulCodePageRange1 == 0 && ulCodePageRange2 == 0))
{
for( int nIndex = 0; nIndex < face->num_charmaps; nIndex++ )
{
if (0 == face->charmaps[nIndex]->encoding_id && 3 == face->charmaps[nIndex]->platform_id)
{
isSymbolic = nIndex;
break;
}
}
}
}
int nHeader_yMin = face->descender;
int nHeader_yMax = face->ascender;
if (face && FT_IS_SFNT(face))
{
TT_Face ttface = (TT_Face)face;
nHeader_yMin = ttface->header.yMin;
nHeader_yMax = ttface->header.yMax;
}
//isSymbolic
int* family_name = NULL;
unsigned int family_name_len = 0;
CheckUnicodeFaceName(face, family_name, family_name_len);
unsigned int nLen1 = (unsigned int)family_name_len;
unsigned int nLen2 = (unsigned int)strlen(face->style_name);
unsigned int nLen = 28 + nLen1 + 1 + nLen2 + 1 + 1 + (int)face->num_fixed_sizes;
int* res = (int*)ASC_FT_Malloc(nLen * sizeof(int));
int* resTmp = res;
*resTmp++ = (int)face->units_per_EM;
*resTmp++ = (int)face->ascender;
*resTmp++ = (int)face->descender;
*resTmp++ = (int)face->height;
*resTmp++ = (int)face->face_flags;
*resTmp++ = (int)face->num_faces;
*resTmp++ = (int)face->num_glyphs;
*resTmp++ = (int)face->num_charmaps;
*resTmp++ = (int)face->style_flags;
*resTmp++ = (int)face->face_index;
for (unsigned int i = 0; i < nLen1; ++i)
*resTmp++ = family_name[i];
*resTmp++ = 0;
for (unsigned int i = 0; i < nLen2; ++i)
*resTmp++ = face->style_name[i];
*resTmp++ = 0;
if (os2)
{
*resTmp++ = (int)os2->version;
*resTmp++ = (int)os2->usWeightClass;
*resTmp++ = (int)os2->fsSelection;
*resTmp++ = (int)os2->usWinAscent;
*resTmp++ = (int)os2->usWinDescent;
*resTmp++ = (int)os2->usDefaultChar;
*resTmp++ = (int)os2->sTypoAscender;
*resTmp++ = (int)os2->sTypoDescender;
*resTmp++ = (int)os2->sTypoLineGap;
*resTmp++ = (int)os2->ulUnicodeRange1;
*resTmp++ = (int)os2->ulUnicodeRange2;
*resTmp++ = (int)os2->ulUnicodeRange3;
*resTmp++ = (int)os2->ulUnicodeRange4;
*resTmp++ = (int)os2->ulCodePageRange1;
*resTmp++ = (int)os2->ulCodePageRange2;
}
else
{
*resTmp++ = (int)0xFFFF;
*resTmp++ = (int)0;
*resTmp++ = (int)0;
*resTmp++ = (int)0;
*resTmp++ = (int)0;
*resTmp++ = (int)0;
*resTmp++ = (int)0;
*resTmp++ = (int)0;
*resTmp++ = (int)0;
*resTmp++ = (int)0;
*resTmp++ = (int)0;
*resTmp++ = (int)0;
*resTmp++ = (int)0;
*resTmp++ = (int)0;
*resTmp++ = (int)0;
}
*resTmp++ = (int)isSymbolic;
*resTmp++ = (int)nHeader_yMin;
*resTmp++ = (int)nHeader_yMax;
*resTmp++ = (int)face->num_fixed_sizes;
for (int i = 0; i < face->num_fixed_sizes; ++i)
*resTmp++ = (int)face->available_sizes[i].size;
if (family_name)
delete [] family_name;
return res;
}
WASM_EXPORT int ASC_FT_GetFaceMaxAdvanceX(FT_Face face)
{
if (!face || !face->size)
return 0;
return (int)face->size->metrics.max_advance;
}
WASM_EXPORT int ASC_FT_GetKerningX(FT_Face face, unsigned int prev_gid, unsigned int gid)
{
FT_Vector vec;
vec.x = 0;
vec.y = 0;
FT_Get_Kerning(face, prev_gid, gid, 0, &vec);
return vec.x;
}
WASM_EXPORT void ASC_FT_Set_Transform(FT_Face face, int xx, int yx, int xy, int yy)
{
FT_Matrix m;
m.xx = xx;
m.yx = yx;
m.xy = xy;
m.yy = yy;
FT_Set_Transform(face, &m, NULL);
}
WASM_EXPORT int ASC_FT_Set_Char_Size(FT_Face face, FT_F26Dot6 char_width, FT_F26Dot6 char_height, FT_UInt horz_resolution, FT_UInt vert_resolution)
{
return FT_Set_Char_Size(face, char_width, char_height, horz_resolution, vert_resolution);
}
// ------------------------------------------------------------
// GLYPH ------------------------------------------------------
WASM_EXPORT int ASC_FT_Load_Glyph(FT_Face face, FT_UInt glyph_index, FT_Int32 load_flags)
{
return FT_Load_Glyph(face, glyph_index, load_flags);
}
WASM_EXPORT int* ASC_FT_Glyph_Get_CBox(FT_Glyph glyph, FT_UInt bbox_mode)
{
FT_BBox bbox;
FT_Glyph_Get_CBox(glyph, bbox_mode, &bbox);
int* res = (int*)ASC_FT_Malloc(4 * sizeof(int));
res[0] = bbox.xMin;
res[1] = bbox.yMin;
res[2] = bbox.xMax;
res[3] = bbox.yMax;
return res;
}
// outline
typedef struct FT_Decompose_Outline_Buffer_
{
FT_Pos* buffer;
FT_Int size;
FT_Int pos;
} FT_Decompose_Outline_Buffer;
void FT_Decompose_Outline_Buffer_Init(FT_Decompose_Outline_Buffer* buffer)
{
buffer->buffer = NULL;
buffer->size = 0;
buffer->pos = 0;
}
void FT_Decompose_Outline_Buffer_Check(FT_Decompose_Outline_Buffer* buffer, FT_Int add)
{
if ((buffer->pos + add) < buffer->size)
return;
if (NULL == buffer->buffer)
{
buffer->buffer = (FT_Pos*)ft_smalloc(200 * sizeof(FT_Pos));
buffer->size = 200;
buffer->pos = 0;
return;
}
FT_Int sizeNew = 2 * buffer->size;
FT_Pos* bufferNew = (FT_Pos*)ft_smalloc((size_t)sizeNew * sizeof(FT_Pos));
memcpy(bufferNew, buffer->buffer, (size_t)buffer->pos * sizeof(FT_Pos));
ft_sfree(buffer->buffer);
buffer->buffer = bufferNew;
buffer->size = sizeNew;
// pos
}
int GlyphPathMoveTo(const FT_Vector *point, void *user)
{
FT_Decompose_Outline_Buffer* buffer = (FT_Decompose_Outline_Buffer*)user;
FT_Decompose_Outline_Buffer_Check(buffer, 3);
buffer->buffer[buffer->pos++] = 0;
buffer->buffer[buffer->pos++] = point->x;
buffer->buffer[buffer->pos++] = point->y;
return 0;
}
int GlyphPathLineTo(const FT_Vector *point, void *user)
{
FT_Decompose_Outline_Buffer* buffer = (FT_Decompose_Outline_Buffer*)user;
FT_Decompose_Outline_Buffer_Check(buffer, 3);
buffer->buffer[buffer->pos++] = 1;
buffer->buffer[buffer->pos++] = point->x;
buffer->buffer[buffer->pos++] = point->y;
return 0;
}
int GlyphPathConicTo(const FT_Vector *pControlPoint, const FT_Vector *pEndPoint, void *user)
{
FT_Decompose_Outline_Buffer* buffer = (FT_Decompose_Outline_Buffer*)user;
FT_Decompose_Outline_Buffer_Check(buffer, 5);
buffer->buffer[buffer->pos++] = 2;
buffer->buffer[buffer->pos++] = pControlPoint->x;
buffer->buffer[buffer->pos++] = pControlPoint->y;
buffer->buffer[buffer->pos++] = pEndPoint->x;
buffer->buffer[buffer->pos++] = pEndPoint->y;
return 0;
}
int GlyphPathCubicTo(const FT_Vector *pFirstControlPoint, const FT_Vector *pSecondControlPoint, const FT_Vector *pEndPoint, void *user)
{
FT_Decompose_Outline_Buffer* buffer = (FT_Decompose_Outline_Buffer*)user;
FT_Decompose_Outline_Buffer_Check(buffer, 7);
buffer->buffer[buffer->pos++] = 3;
buffer->buffer[buffer->pos++] = pFirstControlPoint->x;
buffer->buffer[buffer->pos++] = pFirstControlPoint->y;
buffer->buffer[buffer->pos++] = pSecondControlPoint->x;
buffer->buffer[buffer->pos++] = pSecondControlPoint->y;
buffer->buffer[buffer->pos++] = pEndPoint->x;
buffer->buffer[buffer->pos++] = pEndPoint->y;
return 0;
}
WASM_EXPORT int* ASC_FT_Get_Glyph_Measure_Params(FT_Face face, int isVector)
{
FT_GlyphSlot slot = face->glyph;
if (!isVector && slot->bitmap.buffer != NULL && slot->format == FT_GLYPH_FORMAT_BITMAP)
{
int* res = (int*)ASC_FT_Malloc(15 * sizeof(int));
res[0] = 15;
res[1] = 0;
res[2] = 0;
res[3] = slot->metrics.width;
res[4] = slot->metrics.height;
res[5] = slot->metrics.width;
res[6] = slot->metrics.height;
res[7] = slot->metrics.horiAdvance;
res[8] = slot->metrics.horiBearingX;
res[9] = slot->metrics.horiBearingY;
res[10] = slot->metrics.vertAdvance;
res[11] = slot->metrics.vertBearingX;
res[12] = slot->metrics.vertBearingY;
res[13] = slot->linearHoriAdvance;
res[14] = slot->linearVertAdvance;
return res;
}
FT_Glyph glyph;
FT_Get_Glyph(slot, &glyph);
if (!glyph)
return NULL;
FT_Decompose_Outline_Buffer buffer;
FT_Decompose_Outline_Buffer_Init(&buffer);
FT_Decompose_Outline_Buffer_Check(&buffer, 15);
FT_Pos* _buffer = buffer.buffer;
_buffer[0] = 0;
FT_BBox bbox;
FT_Glyph_Get_CBox(glyph, 1, &bbox);
_buffer[1] = bbox.xMin;
_buffer[2] = bbox.yMin;
_buffer[3] = bbox.xMax;
_buffer[4] = bbox.yMax;
_buffer[5] = slot->metrics.width;
_buffer[6] = slot->metrics.height;
_buffer[7] = slot->metrics.horiAdvance;
_buffer[8] = slot->metrics.horiBearingX;
_buffer[9] = slot->metrics.horiBearingY;
_buffer[10] = slot->metrics.vertAdvance;
_buffer[11] = slot->metrics.vertBearingX;
_buffer[12] = slot->metrics.vertBearingY;
_buffer[13] = slot->linearHoriAdvance;
_buffer[14] = slot->linearVertAdvance;
buffer.pos = 15;
if (isVector)
{
static FT_Outline_Funcs pOutlineFuncs =
{
&GlyphPathMoveTo,
&GlyphPathLineTo,
&GlyphPathConicTo,
&GlyphPathCubicTo,
0, 0
};
FT_Outline_Decompose(&((FT_OutlineGlyph)glyph)->outline, &pOutlineFuncs, &buffer);
}
buffer.buffer[0] = buffer.pos;
FT_Done_Glyph(glyph);
return (int*)buffer.buffer;
}
WASM_EXPORT int* ASC_FT_Get_Glyph_Render_Params(FT_Face face, int render_mode)
{
FT_GlyphSlot slot = face->glyph;
if (FT_Render_Glyph(slot, (FT_Render_Mode)render_mode))
return NULL;
int* res = (int*)ASC_FT_Malloc(6 * sizeof(int));
res[0] = slot->bitmap_left;
res[1] = slot->bitmap_top;
res[2] = (int)slot->bitmap.width;
res[3] = (int)slot->bitmap.rows;
res[4] = slot->bitmap.pitch;
res[5] = slot->bitmap.pixel_mode;
return res;
}
WASM_EXPORT unsigned char* ASC_FT_Get_Glyph_Render_Buffer(FT_Face face)
{
return face->glyph->bitmap.buffer;
}
// ------------------------------------------------------------
// HARFBUZZ
#include <hb.h>
#include <hb-ft.h>
#include <hb-ot.h>
#define g_userfeatures_count 5
hb_feature_t g_userfeatures[g_userfeatures_count];
bool g_userfeatures_init = false;
WASM_EXPORT void* ASC_HB_LanguageFromString(char* language_bcp_47)
{
return (void*)hb_language_from_string(language_bcp_47, strlen(language_bcp_47));
}
WASM_EXPORT unsigned char* ASC_HB_ShapeText(FT_Face pFace, hb_font_t* pFont, char* pText,
unsigned int nFeatures, unsigned int nScript, unsigned int nDirection, unsigned char* nLanguage)
{
// init features
if (!g_userfeatures_init)
{
hb_tag_t tags[] = {
HB_TAG('l','i','g','a'),
HB_TAG('c','l','i','g'),
HB_TAG('h','l','i','g'),
HB_TAG('d','l','i','g'),
HB_TAG('k','e','r','n')
};
for (int nTag = 0; nTag < g_userfeatures_count; ++nTag)
{
g_userfeatures[nTag].tag = tags[nTag];
g_userfeatures[nTag].value = 0;
g_userfeatures[nTag].start = HB_FEATURE_GLOBAL_START;
g_userfeatures[nTag].end = HB_FEATURE_GLOBAL_END;
}
g_userfeatures_init = true;
}
// Turn on ligatures on arabic script
if (nScript == HB_SCRIPT_ARABIC ||
nScript == HB_SCRIPT_SYRIAC)
{
nFeatures |= 1;
}
// font
if (NULL == pFont)
{
pFont = hb_ft_font_create(pFace, NULL);
hb_ft_font_set_funcs(pFont);
}
// features
for (int nTag = 0; nTag < g_userfeatures_count; ++nTag)
g_userfeatures[nTag].value = (nFeatures & (1 << nTag)) ? 1 : 0;
// buffer
hb_buffer_t* hbBuffer = hb_buffer_create();
hb_buffer_set_direction(hbBuffer, (hb_direction_t)nDirection);
hb_buffer_set_script(hbBuffer, (hb_script_t)nScript);
hb_buffer_set_language(hbBuffer, (hb_language_t)nLanguage);
hb_buffer_set_cluster_level(hbBuffer, HB_BUFFER_CLUSTER_LEVEL_MONOTONE_GRAPHEMES);
int text_len = (int)strlen(pText);
hb_buffer_add_utf8(hbBuffer, pText, text_len, 0, text_len);
hb_buffer_guess_segment_properties(hbBuffer);
// shape
hb_shape(pFont, hbBuffer, g_userfeatures, g_userfeatures_count);
unsigned int glyph_count;
hb_glyph_info_t* glyph_info = hb_buffer_get_glyph_infos(hbBuffer, &glyph_count);
hb_glyph_position_t* glyph_pos = hb_buffer_get_glyph_positions(hbBuffer, &glyph_count);
int nSize = 4 + 8 + glyph_count * (1 + 1 + 4 * 6);
unsigned char* pBuffer = (unsigned char*)ASC_FT_Malloc(nSize);
memset(pBuffer, 0, nSize);
int nSizeofInt = sizeof(int);
unsigned char* pBufferCurrent = pBuffer;
memcpy(pBufferCurrent, &nSize, nSizeofInt); pBufferCurrent += nSizeofInt;
uint64_t pFontPointer = (uint64_t)pFont;
memcpy(pBufferCurrent, &pFontPointer, sizeof(uint64_t));
pBufferCurrent += 8;
for (unsigned i = 0; i < glyph_count; ++i)
{
unsigned char nGlyphType = (unsigned char)hb_ot_layout_get_glyph_class(hb_font_get_face(pFont), glyph_info[i].codepoint);
unsigned char nGlyphFlags = (unsigned char)hb_glyph_info_get_glyph_flags(&glyph_info[i]);
memcpy(pBufferCurrent, &nGlyphType, nSizeofInt); pBufferCurrent++;
memcpy(pBufferCurrent, &nGlyphFlags, nSizeofInt); pBufferCurrent++;
memcpy(pBufferCurrent, &glyph_info[i].codepoint, nSizeofInt); pBufferCurrent += nSizeofInt;
memcpy(pBufferCurrent, &glyph_info[i].cluster, nSizeofInt); pBufferCurrent += nSizeofInt;
memcpy(pBufferCurrent, &glyph_pos[i].x_advance, nSizeofInt); pBufferCurrent += nSizeofInt;
memcpy(pBufferCurrent, &glyph_pos[i].y_advance, nSizeofInt); pBufferCurrent += nSizeofInt;
memcpy(pBufferCurrent, &glyph_pos[i].x_offset, nSizeofInt); pBufferCurrent += nSizeofInt;
memcpy(pBufferCurrent, &glyph_pos[i].y_offset, nSizeofInt); pBufferCurrent += nSizeofInt;
}
hb_buffer_destroy(hbBuffer);
return pBuffer;
}
WASM_EXPORT void ASC_HB_FontFree(hb_font_t* font)
{
hb_font_destroy(font);
}
#ifdef __cplusplus
}
#endif

View File

@ -1,27 +0,0 @@
#!/usr/bin/env python
import sys
sys.path.append("../../../../build_tools/scripts")
import base
import os
base.configure_common_apps()
base.cmd_in_dir("./../../../../core/Common/js", "make.py", ["./../../DesktopEditor/fontengine/js/libfont.json"])
src_dir = "./deploy/"
dst_dir = "./../../../../sdkjs/common/libfont/engine/"
base.delete_file(dst_dir + "fonts.js")
base.delete_file(dst_dir + "fonts_ie.js")
base.delete_file(dst_dir + "fonts_native.js")
base.delete_file(dst_dir + "fonts.wasm")
base.delete_file(dst_dir + "../engine.js")
base.copy_file(src_dir + "fonts.js", dst_dir + "fonts.js")
base.copy_file(src_dir + "fonts_ie.js", dst_dir + "fonts_ie.js")
base.copy_file(src_dir + "../engine/module_native.js", dst_dir + "fonts_native.js")
base.copy_file(src_dir + "fonts.wasm", dst_dir + "fonts.wasm")
base.copy_file(src_dir + "../module.js", dst_dir + "../engine.js")
base.replaceInFileUtf8(dst_dir + "../engine.js", "// BASE FILE FOR GENERATION", "// THIS FILE WAS GENERATED AUTOMATICALLY. DO NOT CHANGE IT!")

View File

@ -1,654 +0,0 @@
/*
* (c) Copyright Ascensio System SIA 2010-2024
*
* This program is a free software product. You can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License (AGPL)
* version 3 as published by the Free Software Foundation. In accordance with
* Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
* that Ascensio System SIA expressly excludes the warranty of non-infringement
* of any third-party rights.
*
* This program is distributed WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For
* details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
*
* You can contact Ascensio System SIA at 20A-6 Ernesta Birznieka-Upish
* street, Riga, Latvia, EU, LV-1050.
*
* The interactive user interfaces in modified source and object code versions
* of the Program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU AGPL version 3.
*
* Pursuant to Section 7(b) of the License you must retain the original Product
* logo when distributing the program. Pursuant to Section 7(e) we decline to
* grant you any rights under trademark law for use of our trademarks.
*
* All the Product's GUI elements, including illustrations and icon sets, as
* well as technical writing content are licensed under the terms of the
* Creative Commons Attribution-ShareAlike 4.0 International. See the License
* terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
*
*/
(function(window, undefined) {
var AscFonts = window['AscFonts'];
if (window["NATIVE_EDITOR_ENJINE"])
{
var immediateArray = [];
window.setImmediate = function(fn) {
if (immediateArray)
immediateArray.push(fn);
else
fn();
};
window.immediateRun = function() {
for (var i = 0; i < immediateArray.length; i++)
immediateArray[i]();
immediateArray = undefined;
};
}
var setImmediate = window.setImmediate;
//desktop_fetch
//polyfill
//string_utf8
//module
function CReturnObject()
{
this.error = 0;
this.freeObj = 0;
}
CReturnObject.prototype.free = function()
{
Module["_ASC_FT_Free"](this.freeObj);
};
let g_return_obj = new CReturnObject();
let g_return_obj_count = new CReturnObject();
g_return_obj_count.count = 0;
AscFonts.CopyStreamToMemory = function(data, size)
{
var fontStreamPointer = Module["_ASC_FT_Malloc"](size);
Module["HEAP8"].set(data, fontStreamPointer);
return fontStreamPointer;
};
AscFonts.GetUint8ArrayFromPointer = function(pointer, size)
{
return new Uint8Array(Module["HEAP8"].buffer, pointer, size);
};
function CShapeString(size)
{
this.size = size;
this.pointer = Module["_malloc"](size);
}
CShapeString.prototype.getBuffer = function()
{
return new Uint8Array(Module["HEAPU8"].buffer, this.pointer, this.size);
};
CShapeString.prototype.free = function()
{
Module["_free"](this.pointer);
};
CShapeString.prototype.set = function(index, value)
{
Module["HEAPU8"][this.pointer + index] = value;
};
AscFonts.AllocString = function(size)
{
return new CShapeString(size);
};
AscFonts.FT_CreateLibrary = Module["_ASC_FT_Init"];
AscFonts.FT_Done_Library = Module["_ASC_FT_Done_FreeType"];
AscFonts.FT_Set_TrueType_HintProp = Module["_ASC_FT_Set_TrueType_HintProp"];
AscFonts.FT_Open_Face = Module["_ASC_FT_Open_Face"];
AscFonts.FT_Done_Face = Module["_ASC_FT_Done_Face"];
AscFonts.FT_SetCMapForCharCode = Module["_ASC_FT_SetCMapForCharCode"];
AscFonts.FT_GetKerningX = Module["_ASC_FT_GetKerningX"];
AscFonts.FT_GetFaceMaxAdvanceX = Module["_ASC_FT_GetFaceMaxAdvanceX"];
AscFonts.FT_Set_Transform = Module["_ASC_FT_Set_Transform"];
AscFonts.FT_Set_Char_Size = Module["_ASC_FT_Set_Char_Size"];
AscFonts.FT_GetFaceInfo = function(face, reader)
{
let pointer = Module["_ASC_FT_GetFaceInfo"](face);
if (!pointer)
{
g_return_obj.error = 1;
return g_return_obj;
}
var len_buffer = Math.min((Module["HEAP8"].length - pointer), 1000); //max 230 symbols on name & style
reader.init(new Uint8Array(Module["HEAP8"].buffer, pointer, len_buffer));
g_return_obj.freeObj = pointer;
g_return_obj.error = 0;
return g_return_obj;
};
AscFonts.FT_Load_Glyph = Module["_ASC_FT_Load_Glyph"];
AscFonts.FT_SetCMapForCharCode = Module["_ASC_FT_SetCMapForCharCode"];
AscFonts.FT_Get_Glyph_Measure_Params = function(face, vector_worker, reader)
{
let pointer = Module["_ASC_FT_Get_Glyph_Measure_Params"](face, vector_worker ? 1 : 0);
if (!pointer)
{
g_return_obj_count.error = 1;
return g_return_obj_count;
}
let len = !vector_worker ? 15 : Module["HEAP32"][pointer >> 2];
if (vector_worker)
len = Module["HEAP32"][pointer >> 2];
reader.init(new Uint8Array(Module["HEAP8"].buffer, pointer + 4, 4 * (len - 1)));
g_return_obj_count.freeObj = pointer;
g_return_obj_count.count = len;
g_return_obj_count.error = 0;
return g_return_obj_count;
};
AscFonts.FT_Get_Glyph_Render_Params = function(face, render_mode, reader)
{
let pointer = Module["_ASC_FT_Get_Glyph_Render_Params"](face, render_mode);
if (!pointer)
{
g_return_obj_count.error = 1;
return g_return_obj_count;
}
reader.init(new Uint8Array(Module["HEAP8"].buffer, pointer, 4 * 6));
g_return_obj.freeObj = pointer;
g_return_obj.error = 0;
return g_return_obj;
};
AscFonts.FT_Get_Glyph_Render_Buffer = function(face, size)
{
var pointer = Module["_ASC_FT_Get_Glyph_Render_Buffer"](face);
return new Uint8Array(Module["HEAP8"].buffer, pointer, size);
};
let hb_cache_languages = {};
AscFonts.HB_FontFree = Module["ASC_HB_FontFree"];
AscFonts.HB_ShapeText = function(fontFile, text, features, script, direction, language, reader)
{
if (!hb_cache_languages[language])
{
let langBuffer = language.toUtf8();
var langPointer = Module["_malloc"](langBuffer.length);
Module["HEAP8"].set(langBuffer, langBuffer);
hb_cache_languages[language] = Module["_ASC_HB_LanguageFromString"](langPointer);
Module["_free"](langPointer);
}
let pointer = Module["_ASC_HB_ShapeText"](fontFile["GetFace"](), fontFile["GetHBFont"](), text.pointer, features, script, direction, hb_cache_languages[language]);
if (!pointer)
{
g_return_obj_count.error = 1;
return g_return_obj_count;
}
let buffer = Module["HEAP8"];
let len = (buffer[pointer + 3] & 0xFF) << 24 | (buffer[pointer + 2] & 0xFF) << 16 | (buffer[pointer + 1] & 0xFF) << 8 | (buffer[pointer] & 0xFF);
reader.init(buffer, pointer + 4, len - 4);
fontFile["SetHBFont"](reader.readPointer64());
g_return_obj_count.freeObj = pointer;
g_return_obj_count.count = (len - 12) / 26;
g_return_obj_count.error = 0;
return g_return_obj_count;
};
/**
* Class representing a zip archive creator/reader.
* @constructor
*/
function ZLib()
{
this.engine = 0; // pointer to native Zlib class
this.files = {};
}
/**
* Check loaded wasm/asmjs module
*/
ZLib.prototype.isModuleInit = false;
/**
* Open archive from bytes
* @param {Uint8Array | ArrayBuffer} buf
* @returns {boolean} success or not
*/
ZLib.prototype.open = function(buf)
{
if (!this.isModuleInit)
return false;
if (this.engine)
this.close();
if (!buf)
return false;
var arrayBuffer = (undefined !== buf.byteLength) ? new Uint8Array(buf) : buf;
// TODO: opened the archive and filled this.files
// with objects { path : null }
// copy memory to webasm memory
var FileRawDataSize = arrayBuffer.length;
var FileRawData = Module["_Zlib_Malloc"](FileRawDataSize);
if (0 == FileRawData)
return false;
Module["HEAP8"].set(arrayBuffer, FileRawData);
// load data
this.engine = Module["_Zlib_Open"](FileRawData, FileRawDataSize);
if (0 == this.engine)
{
Module["_Zlib_Free"](FileRawData);
return false;
}
// get paths in archive
var pointer = Module["_Zlib_GetPaths"](this.engine);
if (0 == pointer)
{
Module["_Zlib_Close"](this.engine);
Module["_Zlib_Free"](FileRawData);
return false;
}
var lenArray = new Int32Array(Module["HEAP8"].buffer, pointer, 4);
var len = lenArray[0];
len -= 4;
var buffer = new Uint8Array(Module["HEAP8"].buffer, pointer + 4, len);
var index = 0;
while (index < len)
{
var lenRec = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24;
index += 4;
var _path = "".fromUtf8(buffer, index, lenRec);
this.files[_path] = null;
index += lenRec;
}
Module["_Zlib_Free"](FileRawData);
Module["_Zlib_Free"](pointer);
return true;
};
/**
* Create new archive
* @returns {boolean} success or not
*/
ZLib.prototype.create = function()
{
if (!this.isModuleInit)
return false;
if (this.engine)
this.close();
this.engine = Module["_Zlib_Create"]();
return !!this.engine;
};
/**
* Save archive from current files
* @returns {Uint8Array | null} zip-archive bytes, or null if error
*/
ZLib.prototype.save = function()
{
if (!this.isModuleInit || !this.engine)
return null;
var pointerZip = Module["_Zlib_Save"](this.engine);
if (0 == pointerZip)
return null;
var _lenFile = new Int32Array(Module["HEAP8"].buffer, pointerZip, 4);
var len = _lenFile[0];
var zip = new Uint8Array(Module["HEAP8"].buffer, pointerZip + 4, len);
return zip;
};
/**
* Get all file paths in archive
* @returns {Array}
*/
ZLib.prototype.getPaths = function()
{
var retFiles = [];
if (!this.files)
return retFiles;
for (var path in this.files)
{
if (this.files.hasOwnProperty(path))
retFiles.push(path);
}
return retFiles;
};
/**
* Get uncomressed file from archive
* @param {string} path
* @returns {Uint8Array | null} bytes of uncompressed data, or null if error
*/
ZLib.prototype.getFile = function(path)
{
if (!this.isModuleInit || !this.engine)
return null;
// check if the file exists at all
if (undefined === this.files[path])
return null;
// check if we have already decompressed it
if (null !== this.files[path])
{
if (this.files[path].l > 0)
{
return new Uint8Array(Module["HEAP8"].buffer, this.files[path].p, this.files[path].l);
}
else
{
var _lenFile = new Int32Array(Module["HEAP8"].buffer, this.files[path].p, 4);
var len = _lenFile[0];
return new Uint8Array(Module["HEAP8"].buffer, this.files[path].p + 4, len);
}
}
var tmp = path.toUtf8();
var pointer = Module["_Zlib_Malloc"](tmp.length);
if (0 == pointer)
return null;
Module["HEAP8"].set(tmp, pointer);
var pointerFile = Module["_Zlib_GetFile"](this.engine, pointer);
if (0 == pointerFile)
{
Module["_Zlib_Free"](pointer);
return null;
}
var _lenFile = new Int32Array(Module["HEAP8"].buffer, pointerFile, 4);
var len = _lenFile[0];
Module["_Zlib_Free"](pointer);
this.files[path] = { p : pointerFile, l : 0};
return new Uint8Array(Module["HEAP8"].buffer, pointerFile + 4, len);
};
/**
* Add uncomressed file to archive
* @param {string} path
* @param {Uint8Array} new file in archive
* @returns {boolean} success or not
*/
ZLib.prototype.addFile = function(path, data)
{
if (!this.isModuleInit || !this.engine)
return false;
if (!data)
return false;
// check if such file already exists - then we need to delete it first
if (undefined !== this.files[path])
this.removeFile(path);
var tmp = path.toUtf8();
var pointer = Module["_Zlib_Malloc"](tmp.length);
if (0 == pointer)
return false;
Module["HEAP8"].set(tmp, pointer);
var arrayBuffer = (undefined !== data.byteLength) ? new Uint8Array(data) : data;
var FileRawDataSize = arrayBuffer.length;
var FileRawData = Module["_Zlib_Malloc"](FileRawDataSize);
if (0 == FileRawData)
{
Module["_Zlib_Free"](pointer);
return false;
}
Module["HEAP8"].set(arrayBuffer, FileRawData);
Module["_Zlib_AddFile"](this.engine, pointer, FileRawData, FileRawDataSize);
this.files[path] = { p : FileRawData, l : FileRawDataSize};
Module["_Zlib_Free"](pointer);
return true;
};
/**
* Remove file from archive
* @param {string} path
* @returns {boolean} success or not
*/
ZLib.prototype.removeFile = function(path)
{
if (!this.isModuleInit || !this.engine)
return false;
// check if such file doesn't exist
if (undefined === this.files[path])
return false;
var tmp = path.toUtf8();
var pointer = Module["_Zlib_Malloc"](tmp.length);
if (0 == pointer)
return false;
Module["HEAP8"].set(tmp, pointer);
Module["_Zlib_RemoveFile"](this.engine, pointer);
if (this.files[path] && this.files[path].p)
{
Module["_Zlib_Free"](this.files[path].p);
delete this.files[path];
}
Module["_Zlib_Free"](pointer);
return true;
};
/**
* Close & remove all used memory in archive
* @returns {undefined}
*/
ZLib.prototype.close = function()
{
if (!this.isModuleInit || !this.engine)
return;
for (var i in this.files)
{
if (this.files[i] && this.files[i].p)
Module["_Zlib_Free"](this.files[i].p);
}
this.files = {};
if (this.engine)
Module["_Zlib_Free"](this.engine);
this.engine = 0;
};
/**
* Get image type
* @returns {Number}
*/
ZLib.prototype.getImageType = function(path)
{
let fileData = this.getFile(path);
return Module["_Image_GetFormat"](this.files[path].p + 4, fileData.length);
};
/**
* Get image in needed format
* @returns {Uint8Array}
*/
ZLib.prototype.getImageAsFormat = function(path, format)
{
let fileData = this.getFile(path);
let encodedData = Module["_Raster_Encode"](this.files[path].p + 4, fileData.length, format);
let encodedSize = Module["_Raster_GetEncodedSize"](encodedData);
let encodedBuffer = Module["_Raster_GetEncodedBuffer"](encodedData);
let copyData = new Uint8Array(encodedSize);
copyData.set(new Uint8Array(Module["HEAP8"].buffer, encodedBuffer, encodedSize));
Module["_Raster_DestroyEncodedData"](encodedData);
return copyData;
};
/**
* Get image as svg (for simple test)
* @returns {string}
*/
ZLib.prototype.getImageAsSvg = function(path)
{
let fileData = this.getFile(path);
let encodedData = Module["_Raster_Encode"](this.files[path].p + 4, fileData.length, 24);
let encodedSize = Module["_Raster_GetEncodedSize"](encodedData);
let encodedBuffer = Module["_Raster_GetEncodedBuffer"](encodedData);
let string = String.prototype.fromUtf8(new Uint8Array(Module["HEAP8"].buffer, encodedBuffer, encodedSize));
Module["_Raster_DestroyEncodedData"](encodedData);
return string;
};
/**
* Get image file raw data. this memory was copied and detach from archive.
* @returns {Uint8Array}
*/
ZLib.prototype.getImageBuffer = function(path)
{
let result = {
type : 0,
data : null
};
result.type = this.getImageType(path);
if (result.type === 0)
return null;
let fileData = this.getFile(path);
result.data = new Uint8Array(fileData.length);
result.data.set(fileData);
if (result.type != 10 &&
result.type != 21)
{
return result;
}
result.type = 24;
// Source was saved as result.data for using original image in native convertations.
// But for js we need svg for metafiles.
let encodedData = Module["_Raster_Encode"](this.files[path].p + 4, fileData.length, 24);
let encodedSize = Module["_Raster_GetEncodedSize"](encodedData);
let encodedBuffer = Module["_Raster_GetEncodedBuffer"](encodedData);
let fileDataEnc = new Uint8Array(Module["HEAP8"].buffer, encodedBuffer, encodedSize);
result.dataBlob = new Uint8Array(fileDataEnc.length);
result.dataBlob.set(fileDataEnc);
Module["_Raster_DestroyEncodedData"](encodedData);
return result;
};
/**
* Get image blob for browser
* @returns {Blob}
*/
ZLib.prototype.getImageBlob = function(path)
{
let imageType = this.getImageType(path);
if (imageType != 10 && imageType != 21)
{
return new Blob([this.getFile(path)], {type:AscCommon.openXml.GetMimeType(AscCommon.GetFileExtension(path))});
}
let fileData = this.getFile(path);
let encodedData = Module["_Raster_Encode"](this.files[path].p + 4, fileData.length, 24);
let encodedSize = Module["_Raster_GetEncodedSize"](encodedData);
let encodedBuffer = Module["_Raster_GetEncodedBuffer"](encodedData);
let blob = new Blob([new Uint8Array(Module["HEAP8"].buffer, encodedBuffer, encodedSize)], {type : AscCommon.openXml.GetMimeType("svg")});
Module["_Raster_DestroyEncodedData"](encodedData);
return blob;
};
window.AscCommon = window.AscCommon || {};
window.AscCommon.CZLibEngineJS = ZLib;
var hyphenApplication = 0;
AscFonts.Hyphen_Init = function()
{
hyphenApplication = Module["_hyphenCreateApplication"]();
};
AscFonts.Hyphen_Destroy = function()
{
Module["_hyphenDestroyApplication"](hyphenApplication);
};
AscFonts.Hyphen_CheckDictionary = function(lang)
{
return false;
};
AscFonts.Hyphen_LoadDictionary = function(lang, data)
{
let dictSize = data.byteLength;
let dictPointer = Module["_malloc"](dictSize);
Module["HEAP8"].set(new Uint8ClampedArray(data), dictPointer);
let result = Module["_hyphenLoadDictionary"](hyphenApplication, lang, dictPointer, dictSize);
Module["_free"](dictPointer);
return (result === 0) ? true : false;
};
AscFonts.Hyphen_Word = function(lang, word)
{
let wordPointer = word.toUtf8Pointer(true);
let wordLen = wordPointer.length;
let hyphens = [];
if (wordPointer)
{
let ptr = Module._hyphenWord(hyphenApplication, lang, wordPointer.ptr, wordLen);
let vector = new Uint8ClampedArray(Module["HEAP8"].buffer, ptr, wordLen + 5);
let pos = 0;
while (vector[pos] != 0)
{
if (1 === (vector[pos] & 1))
hyphens.push(pos+1);
pos++;
}
wordPointer.free();
}
return hyphens;
};
if (window["NATIVE_EDITOR_ENJINE"])
window.immediateRun();
AscFonts.onLoadModule();
})(window, undefined);

View File

@ -1,241 +0,0 @@
/*
* (c) Copyright Ascensio System SIA 2010-2024
*
* This program is a free software product. You can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License (AGPL)
* version 3 as published by the Free Software Foundation. In accordance with
* Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
* that Ascensio System SIA expressly excludes the warranty of non-infringement
* of any third-party rights.
*
* This program is distributed WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For
* details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
*
* You can contact Ascensio System SIA at 20A-6 Ernesta Birznieka-Upish
* street, Riga, Latvia, EU, LV-1050.
*
* The interactive user interfaces in modified source and object code versions
* of the Program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU AGPL version 3.
*
* Pursuant to Section 7(b) of the License you must retain the original Product
* logo when distributing the program. Pursuant to Section 7(e) we decline to
* grant you any rights under trademark law for use of our trademarks.
*
* All the Product's GUI elements, including illustrations and icon sets, as
* well as technical writing content are licensed under the terms of the
* Creative Commons Attribution-ShareAlike 4.0 International. See the License
* terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
*
*/
(function(window, undefined) {
window['AscFonts'] = window['AscFonts'] || {};
var AscFonts = window['AscFonts'];
var g_native_engine = null;
function CReturnObject()
{
this.error = 0;
}
CReturnObject.prototype.free = function()
{
};
let g_return_obj = new CReturnObject();
let g_return_obj_count = new CReturnObject();
g_return_obj_count.count = 0;
AscFonts.CopyStreamToMemory = function(data, size)
{
return data;
};
AscFonts.GetUint8ArrayFromPointer = function(pointer, size)
{
return pointer;
};
function CShapeString(size)
{
this.size = size;
this.pointer = new Uint8Array(size);
}
CShapeString.prototype.getBuffer = function()
{
return this.pointer;
};
CShapeString.prototype.free = function()
{
// GC
};
CShapeString.prototype.set = function(index, value)
{
this.pointer[index] = value;
};
AscFonts.AllocString = function(size)
{
return new CShapeString(size);
};
AscFonts.FT_CreateLibrary = function(library)
{
return g_native_engine["FT_Init"](library);
};
AscFonts.FT_Done_Library = function(face)
{
if (face)
g_native_engine.FT_Free(face);
};
AscFonts.FT_Set_TrueType_HintProp = function(library, tt_interpreter)
{
return g_native_engine["FT_Set_TrueType_HintProp"](library, tt_interpreter);
};
AscFonts.FT_Open_Face = function(library, memory, len, face_index)
{
return g_native_engine["FT_Open_Face2"](library, memory, face_index);
};
AscFonts.FT_Done_Face = function(face)
{
if (face)
g_native_engine["FT_Free"](face);
};
AscFonts.FT_SetCMapForCharCode = function(face, unicode)
{
return g_native_engine["FT_SetCMapForCharCode"](face, unicode);
};
AscFonts.FT_GetKerningX = function(face, gid1, gid2)
{
return g_native_engine["FT_GetKerningX"](face, gid1, gid2);
};
AscFonts.FT_GetFaceMaxAdvanceX = function(face)
{
return g_native_engine["FT_GetFaceMaxAdvanceX"](face);
};
AscFonts.FT_Set_Transform = function(face, xx, yx, xy, yy)
{
return g_native_engine["FT_Set_Transform"](face, xx, yx, xy, yy);
};
AscFonts.FT_Set_Char_Size = function(face, cw, ch, hres, vres)
{
return g_native_engine["FT_Set_Char_Size"](face, cw, ch, hres, vres);
};
AscFonts.FT_GetFaceInfo = function(face, reader)
{
var data = g_native_engine["FT_GetFaceInfo"](face);
if (!data)
{
g_return_obj.error = 1;
return g_return_obj;
}
g_return_obj.error = 0;
reader.init(data, 0, data.length);
return g_return_obj;
};
AscFonts.FT_Load_Glyph = function(face, gid, mode)
{
return g_native_engine["FT_Load_Glyph"](face, gid, mode);
};
AscFonts.FT_SetCMapForCharCode = function(face, unicode)
{
return g_native_engine["FT_SetCMapForCharCode"](face, unicode);
}
AscFonts.FT_Get_Glyph_Measure_Params = function(face, vector_worker, reader)
{
var data = g_native_engine["FT_Get_Glyph_Measure_Params"](face, vector_worker ? true : false);
if (!data)
{
g_return_obj_count.error = 1;
return g_return_obj_count;
}
reader.init(new Uint8Array(data, 0, data.length));
g_return_obj_count.count = reader.readInt();
g_return_obj_count.error = 0;
return g_return_obj_count;
};
AscFonts.FT_Get_Glyph_Render_Params = function(face, render_mode, reader)
{
var data = g_native_engine["FT_Get_Glyph_Render_Params"](face, render_mode);
if (!data)
{
g_return_obj.error = 1;
return g_return_obj;
}
g_return_obj.error = 0;
reader.init(data, 0, data.length);
return g_return_obj;
};
AscFonts.FT_Get_Glyph_Render_Buffer = function(face, size)
{
return g_native_engine["FT_Get_Glyph_Render_Buffer"](face, size);
};
let hb_cache_languages = {};
AscFonts.HB_FontFree = function(font)
{
if (font)
g_native_engine["FT_Free"](font);
}
AscFonts.HB_ShapeText = function(fontFile, text, features, script, direction, language, reader)
{
if (!hb_cache_languages[language])
{
hb_cache_languages[language] = g_native_engine["HB_LanguageFromString"]();
}
if (!fontFile["GetHBFont"]())
fontFile["SetHBFont"](g_native_engine["HB_FontMalloc"]());
let data = g_native_engine["HB_ShapeText"](fontFile["GetFace"](), fontFile["GetHBFont"](), text.pointer, features, script, direction, hb_cache_languages[language]);
if (!data)
{
g_return_obj_count.error = 1;
return g_return_obj_count;
}
reader.init(new Uint8Array(data, 0, data.length));
let len = reader.readUInt();
let fontPointer = reader.readPointer64(); // just skip
g_return_obj_count.count = (len - 12) / 26;
g_return_obj_count.error = 0;
return g_return_obj_count;
};
AscFonts.Hyphen_Init = function()
{
// none
};
AscFonts.Hyphen_Destroy = function()
{
// GC
};
AscFonts.Hyphen_CheckDictionary = function(lang)
{
return g_native_engine["Hyphen_IsDictionaryExist"](lang);
};
AscFonts.Hyphen_LoadDictionary = function(lang, data)
{
return false;
};
AscFonts.Hyphen_Word = function(lang, word)
{
let ret = g_native_engine["Hyphen_Word"](lang, word);
return ret ? ret : [];
};
AscFonts.onLoadModule();
AscFonts.onLoadModule();
window["InitNativeTextMeasurer"] = function() { g_native_engine = CreateEmbedObject("CTextMeasurerEmbed"); };
})(window, undefined);

View File

@ -1,377 +0,0 @@
{
"name": "fonts",
"res_folder": "./deploy",
"wasm": true,
"asm": true,
"run_before": "before.py",
"run_after": "after.py",
"embed_mem_file": true,
"base_js_content": "./engine/module_js.js",
"compiler_flags": [
"-O3",
"-fexceptions",
"-Wno-unused-command-line-argument",
"-s ALLOW_MEMORY_GROWTH=1",
"-s FILESYSTEM=0",
"-s ENVIRONMENT='web'",
"-s LLD_REPORT_UNDEFINED"
],
"exported_functions": [
"_malloc",
"_free",
"_ASC_FT_Malloc",
"_ASC_FT_Free",
"_ASC_FT_Init",
"_ASC_FT_Done_FreeType",
"_ASC_FT_Set_TrueType_HintProp",
"_ASC_FT_Open_Face",
"_ASC_FT_Done_Face",
"_ASC_FT_SetCMapForCharCode",
"_ASC_FT_GetFaceInfo",
"_ASC_FT_GetFaceMaxAdvanceX",
"_ASC_FT_GetKerningX",
"_ASC_FT_Set_Transform",
"_ASC_FT_Set_Char_Size",
"_ASC_FT_Load_Glyph",
"_ASC_FT_Glyph_Get_CBox",
"_ASC_FT_Get_Glyph_Measure_Params",
"_ASC_FT_Get_Glyph_Render_Params",
"_ASC_FT_Get_Glyph_Render_Buffer",
"_ASC_HB_LanguageFromString",
"_ASC_HB_ShapeText",
"_ASC_HB_FontFree",
"_hyphenCreateApplication",
"_hyphenDestroyApplication",
"_hyphenLoadDictionary",
"_hyphenCheckDictionary",
"_hyphenWord",
"_Zlib_Malloc",
"_Zlib_Free",
"_Zlib_Create",
"_Zlib_Open",
"_Zlib_Close",
"_Zlib_AddFile",
"_Zlib_RemoveFile",
"_Zlib_GetPaths",
"_Zlib_GetFile",
"_Zlib_Save",
"_Raster_DecodeFile",
"_Raster_GetDecodedBuffer",
"_Raster_GetHeight",
"_Raster_GetWidth",
"_Raster_GetStride",
"_Raster_Destroy",
"_Raster_EncodeImageData",
"_Raster_Encode",
"_Raster_GetEncodedBuffer",
"_Raster_GetEncodedSize",
"_Raster_DestroyEncodedData",
"_Image_GetFormat"
],
"include_path": [
"./../../graphics/pro/js/freetype-2.10.4/include",
"./../../graphics/pro/js/freetype-2.10.4/include/freetype",
"./../../graphics/pro/js/freetype-2.10.4/include/freetype/internal",
"./../../graphics/pro/js/wasm/src/lib",
"./../../../Common/3dParty/harfbuzz/harfbuzz/src",
"./../../../Common/3dParty/brotli/brotli/c/include",
"./../../../OfficeUtils/src",
"./../../../OfficeUtils/src/zlib-1.2.11",
"./../../cximage/jasper/include",
"./../../cximage/jpeg",
"./../../cximage/png",
"./../../agg-2.4/include"
],
"define": [
"__linux__", "_LINUX", "UNIX", "_QT",
"NDEBUG", "_LIB", "_CRT_SECURE_NO_WARNINGS",
"FT2_BUILD_LIBRARY",
"HAVE_FREETYPE",
"FT_CONFIG_OPTION_SYSTEM_ZLIB",
"GRAPHICS_NO_USE_DYNAMIC_LIBRARY",
"HYPHEN_ENGINE_DISABLE_FILESYSTEM",
"METAFILE_DISABLE_FILESYSTEM",
"HAVE_UNISTD_H", "HAVE_FCNTL_H", "_ARM_ALIGN_",
"METAFILE_SUPPORT_WMF_EMF",
"CXIMAGE_DISABLE_SUPPORT_MNG",
"CXIMAGE_DISABLE_SUPPORT_ADDITIONS",
"_tcsnicmp=strncmp",
"_lseek=lseek",
"_getcwd=getcwd",
"NO_CONSOLE_IO",
"BUILD_ZLIB_AS_SOURCES",
"IMAGE_CHECKER_DISABLE_XML",
"FT_CONFIG_OPTION_USE_BROTLI",
"BUILDING_WASM_MODULE"
],
"compile_files_array": [
{
"folder": "./../../graphics/pro/js/freetype-2.10.4/src",
"files": [
"base/ftdebug.c",
"autofit/autofit.c",
"bdf/bdf.c",
"cff/cff.c",
"base/ftbase.c",
"base/ftbitmap.c",
"base/ftfstype.c",
"base/ftgasp.c",
"cache/ftcache.c",
"base/ftglyph.c",
"gzip/ftgzip.c",
"base/ftinit.c",
"lzw/ftlzw.c",
"base/ftstroke.c",
"base/ftsystem.c",
"smooth/smooth.cpp",
"base/ftbbox.c",
"base/ftbdf.c",
"base/ftcid.c",
"base/ftmm.c",
"base/ftpfr.c",
"base/ftsynth.c",
"base/fttype1.c",
"base/ftwinfnt.c",
"base/ftgxval.c",
"base/ftotval.c",
"base/ftpatent.c",
"pcf/pcf.c",
"pfr/pfr.c",
"psaux/psaux.c",
"pshinter/pshinter.c",
"psnames/psmodule.c",
"raster/raster.c",
"sfnt/sfnt.cpp",
"truetype/truetype.c",
"type1/type1.c",
"cid/type1cid.c",
"type42/type42.c",
"winfonts/winfnt.c"
]
},
{
"folder": "./../../../Common/3dParty/harfbuzz/harfbuzz/src",
"files": [
"hb-aat-layout.cc",
"hb-aat-map.cc",
"hb-blob.cc",
"hb-buffer-serialize.cc",
"hb-buffer-verify.cc",
"hb-buffer.cc",
"hb-cairo-utils.cc",
"hb-cairo.cc",
"hb-common.cc",
"hb-coretext.cc",
"hb-directwrite.cc",
"hb-draw.cc",
"hb-face-builder.cc",
"hb-face.cc",
"hb-fallback-shape.cc",
"hb-font.cc",
"hb-ft.cc",
"hb-gdi.cc",
"hb-glib.cc",
"hb-gobject-structs.cc",
"hb-graphite2.cc",
"hb-icu.cc",
"hb-map.cc",
"hb-number.cc",
"hb-ot-cff1-table.cc",
"hb-ot-cff2-table.cc",
"hb-ot-color.cc",
"hb-ot-face.cc",
"hb-ot-font.cc",
"hb-ot-layout.cc",
"hb-ot-map.cc",
"hb-ot-math.cc",
"hb-ot-meta.cc",
"hb-ot-metrics.cc",
"hb-ot-name.cc",
"hb-ot-shape-fallback.cc",
"hb-ot-shape-normalize.cc",
"hb-ot-shape.cc",
"hb-ot-shaper-arabic.cc",
"hb-ot-shaper-default.cc",
"hb-ot-shaper-hangul.cc",
"hb-ot-shaper-hebrew.cc",
"hb-ot-shaper-indic-table.cc",
"hb-ot-shaper-indic.cc",
"hb-ot-shaper-khmer.cc",
"hb-ot-shaper-myanmar.cc",
"hb-ot-shaper-syllabic.cc",
"hb-ot-shaper-thai.cc",
"hb-ot-shaper-use.cc",
"hb-ot-shaper-vowel-constraints.cc",
"hb-ot-tag.cc",
"hb-ot-var.cc",
"hb-outline.cc",
"hb-paint-extents.cc",
"hb-paint.cc",
"hb-set.cc",
"hb-shape-plan.cc",
"hb-shape.cc",
"hb-shaper.cc",
"hb-static.cc",
"hb-style.cc",
"hb-subset-cff-common.cc",
"hb-subset-cff1.cc",
"hb-subset-cff2.cc",
"hb-subset-input.cc",
"hb-subset-instancer-solver.cc",
"hb-subset-plan.cc",
"hb-subset-repacker.cc",
"hb-subset.cc",
"hb-ucd.cc",
"hb-unicode.cc",
"hb-uniscribe.cc",
"hb-wasm-api.cc",
"hb-wasm-shape.cc",
"graph/gsubgpos-context.cc"
]
},
{
"folder": "../../../OfficeUtils/src/zlib-1.2.11/",
"files": ["adler32.c", "crc32.c", "deflate.c", "infback.c", "inffast.c", "inflate.c", "inftrees.c", "trees.c", "zutil.c", "compress.c"]
},
{
"folder": "cpp",
"files": ["text.cpp"]
},
{
"folder": "./../../graphics/pro/js/wasm/src/lib",
"files": ["wasm_jmp.cpp"]
},
{
"folder": "../../../OfficeUtils/src/zlib-1.2.11/contrib/minizip/",
"files": ["unzip.c", "ioapi.c", "zip.c", "ioapibuf.c"]
},
{
"folder": "../../../OfficeUtils/js",
"files": ["../src/ZipBuffer.cpp", "wasm/src/base.cpp", "../src/zlib_addon.c"]
},
{
"folder": "../../",
"files": ["graphics/Image.cpp", "raster/BgraFrame.cpp", "raster/ImageFileFormatChecker.cpp", "graphics/Matrix.cpp", "graphics/GraphicsPath.cpp"]
},
{
"folder": "../../agg-2.4/src/",
"files": ["agg_trans_affine.cpp", "agg_bezier_arc.cpp"]
},
{
"folder": "../../raster/",
"files": ["PICT/PICFile.cpp"]
},
{
"folder": "../../graphics/pro/js/qt/raster",
"files": ["pro_Fonts_empty.cpp", "pro_Graphics_empty.cpp", "raster.cpp"]
},
{
"folder": "../../cximage/CxImage/",
"files": ["ximaenc.cpp", "ximaexif.cpp", "ximage.cpp", "ximainfo.cpp", "ximajpg.cpp", "ximalpha.cpp", "ximapal.cpp", "ximasel.cpp", "xmemfile.cpp", "ximapng.cpp", "ximabmp.cpp", "ximatran.cpp", "ximatif.cpp", "tif_xfile.cpp", "ximajas.cpp", "ximagif.cpp", "ximaico.cpp", "ximatga.cpp", "ximapcx.cpp", "ximawbmp.cpp", "ximamng.cpp", "ximapsd.cpp", "ximaska.cpp", "ximaraw.cpp"]
},
{
"folder": "../../cximage/jpeg/",
"files": ["jerror.c", "jdmarker.c", "jdapimin.c", "jdmaster.c", "jdapistd.c", "jcomapi.c", "jutils.c", "jdinput.c", "jdmainct.c", "jmemmgr.c", "jquant1.c", "jquant2.c", "jdmerge.c", "jdcolor.c", "jdsample.c", "jdpostct.c", "jddctmgr.c", "jdarith.c", "jdhuff.c", "jdcoefct.c", "jmemnobs.c", "jidctint.c", "jidctfst.c", "jidctflt.c", "jaricom.c", "jcapimin.c", "jcparam.c", "jcapistd.c", "jcinit.c", "jcmaster.c", "jccolor.c", "jcmarker.c", "jcsample.c", "jcprepct.c", "jcdctmgr.c", "jcarith.c", "jchuff.c", "jccoefct.c", "jcmainct.c", "jfdctint.c", "jfdctfst.c", "jfdctflt.c"]
},
{
"folder": "../../cximage/png/",
"files": ["pngread.c", "pngmem.c", "pngerror.c", "png.c", "pngrio.c", "pngtrans.c", "pngget.c", "pngrutil.c", "pngrtran.c", "pngset.c", "pngwrite.c", "pngwio.c", "pngwutil.c", "pngwtran.c"]
},
{
"folder": "../../cximage/tiff/",
"files": ["tif_close.c", "tif_dir.c", "tif_aux.c", "tif_getimage.c", "tif_strip.c", "tif_open.c", "tif_tile.c", "tif_error.c", "tif_read.c", "tif_flush.c", "tif_dirinfo.c", "tif_compress.c", "tif_warning.c", "tif_swab.c", "tif_color.c", "tif_dirread.c", "tif_write.c", "tif_codec.c", "tif_luv.c", "tif_dirwrite.c", "tif_dumpmode.c", "tif_fax3.c", "tif_ojpeg.c", "tif_jpeg.c", "tif_next.c", "tif_thunder.c", "tif_packbits.c", "tif_lzw.c", "tif_zip.c", "tif_fax3sm.c", "tif_predict.c"]
},
{
"folder": "../../raster/Metafile/",
"files": [
"MetaFile.cpp",
"Common/MetaFileTypes.cpp",
"Common/MetaFileUtils.cpp",
"Common/CPathConverter.cpp",
"Common/CPath.cpp",
"Common/CClip.cpp"
]
},
{
"folder": "../../raster/Metafile/Emf/",
"files": [
"EmfInterpretator/CEmfInterpretator.cpp",
"EmfInterpretator/CEmfInterpretatorArray.cpp",
"EmfInterpretator/CEmfInterpretatorRender.cpp",
"EmfInterpretator/CEmfInterpretatorSvg.cpp",
"EmfParser/CEmfParser.cpp",
"EmfParser/CEmfParserBase.cpp",
"EmfParser/CEmfPlusParser.cpp",
"EmfObjects.cpp",
"EmfPlusObjects.cpp",
"EmfPlayer.cpp",
"EmfFile.cpp"
]
},
{
"folder": "../../raster/Metafile/Wmf/",
"files": [
"WmfInterpretator/CInterpretatorSvgBase.cpp",
"WmfInterpretator/CWmfInterpretatorSvg.cpp",
"WmfInterpretator/CWmfInterpretatorRender.cpp",
"WmfInterpretator/CWmfInterpretator.cpp",
"WmfParser/CWmfParser.cpp",
"WmfParser/CWmfParserBase.cpp",
"WmfObjects.cpp",
"WmfPlayer.cpp"
]
},
{
"folder": "../../common/",
"files": [
"File.cpp",
"Base64.cpp",
"StringExt.cpp",
"StringBuilder.cpp",
"../xml/src/xmlwriter.cpp"
]
},
{
"folder": "./..",
"files": ["TextHyphen.cpp"]
},
{
"folder": "./../../../Common/3dParty/hyphen/js/src",
"files": ["hyphen.cpp"]
},
{
"folder": "./../../../Common/3dParty/brotli/brotli/c/common",
"files": [
"constants.c",
"context.c",
"dictionary.c",
"platform.c",
"shared_dictionary.c",
"transform.c"
]
},
{
"folder": "./../../../Common/3dParty/brotli/brotli/c/dec",
"files": [
"bit_reader.c",
"decode.c",
"huffman.c",
"state.c"
]
}
]
}

View File

@ -1,981 +0,0 @@
/*
* (c) Copyright Ascensio System SIA 2010-2024
*
* This program is a free software product. You can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License (AGPL)
* version 3 as published by the Free Software Foundation. In accordance with
* Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
* that Ascensio System SIA expressly excludes the warranty of non-infringement
* of any third-party rights.
*
* This program is distributed WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For
* details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
*
* You can contact Ascensio System SIA at 20A-6 Ernesta Birznieka-Upish
* street, Riga, Latvia, EU, LV-1050.
*
* The interactive user interfaces in modified source and object code versions
* of the Program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU AGPL version 3.
*
* Pursuant to Section 7(b) of the License you must retain the original Product
* logo when distributing the program. Pursuant to Section 7(e) we decline to
* grant you any rights under trademark law for use of our trademarks.
*
* All the Product's GUI elements, including illustrations and icon sets, as
* well as technical writing content are licensed under the terms of the
* Creative Commons Attribution-ShareAlike 4.0 International. See the License
* terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
*
*/
// BASE FILE FOR GENERATION
function onLoadFontsModule(window, undefined)
{
var AscFonts = window['AscFonts'];
AscFonts.TT_INTERPRETER_VERSION_35 = 35;
AscFonts.TT_INTERPRETER_VERSION_38 = 38;
AscFonts.TT_INTERPRETER_VERSION_40 = 40;
AscFonts.CopyStreamToMemory = AscFonts["CopyStreamToMemory"];
AscFonts.GetUint8ArrayFromPointer = AscFonts["GetUint8ArrayFromPointer"];
AscFonts.AllocString2 = AscFonts["AllocString"];
AscFonts.AllocString = function(size)
{
var pointer = AscFonts.AllocString2(size);
pointer.pointer = pointer["pointer"];
pointer.getBuffer = pointer["getBuffer"];
pointer.free = pointer["free"];
pointer.set = pointer["set"];
return pointer;
};
AscFonts.FT_CreateLibrary = AscFonts["FT_CreateLibrary"];
AscFonts.FT_Done_Library = AscFonts["FT_Done_Library"];
AscFonts.FT_Set_TrueType_HintProp = AscFonts["FT_Set_TrueType_HintProp"];
AscFonts.FT_Open_Face2 = AscFonts["FT_Open_Face"];
AscFonts.FT_Done_Face = AscFonts["FT_Done_Face"];
AscFonts.FT_SetCMapForCharCode = AscFonts["FT_SetCMapForCharCode"];
AscFonts.FT_GetKerningX = AscFonts["FT_GetKerningX"];
AscFonts.FT_GetFaceMaxAdvanceX = AscFonts["FT_GetFaceMaxAdvanceX"];
AscFonts.FT_Set_Transform = AscFonts["FT_Set_Transform"];
AscFonts.FT_Set_Char_Size = AscFonts["FT_Set_Char_Size"];
AscFonts.FT_GetFaceInfo = AscFonts["FT_GetFaceInfo"];
AscFonts.FT_Load_Glyph = AscFonts["FT_Load_Glyph"];
AscFonts.FT_SetCMapForCharCode = AscFonts["FT_SetCMapForCharCode"];
AscFonts.FT_Get_Glyph_Measure_Params = AscFonts["FT_Get_Glyph_Measure_Params"];
AscFonts.FT_Get_Glyph_Render_Params = AscFonts["FT_Get_Glyph_Render_Params"];
AscFonts.FT_Get_Glyph_Render_Buffer2 = AscFonts["FT_Get_Glyph_Render_Buffer"];
AscFonts.HB_FontFree = AscFonts["HB_FontFree"];
AscFonts.HB_ShapeText = AscFonts["HB_ShapeText"];
AscFonts["Hyphen_Init"]();
AscFonts.Hyphen_Destroy = AscFonts["Hyphen_Destroy"];
AscFonts.Hyphen_LoadDictionary = AscFonts["Hyphen_LoadDictionary"];
AscFonts.Hyphen_CheckDictionary = AscFonts["Hyphen_CheckDictionary"];
AscFonts.Hyphen_Word = AscFonts["Hyphen_Word"];
AscFonts.CreateNativeStreamByIndex = function(stream_index)
{
let stream = AscFonts.g_fonts_streams[stream_index];
if (stream && true !== stream.asc_marker)
{
AscFonts.g_fonts_streams[stream_index] = {
asc_marker: true,
data: AscFonts.CopyStreamToMemory(stream.data, stream.size),
len: stream.size
};
}
};
function CBinaryReader(data, start, size)
{
this.data = data;
this.pos = (undefined === start) ? 0 : start;
this.limit = this.pos + ((undefined === size) ? data.length : size);
}
CBinaryReader.prototype.init = CBinaryReader.prototype["init"] = function(data, start, size)
{
this.data = data;
this.pos = (undefined === start) ? 0 : start;
this.limit = this.pos + ((undefined === size) ? data.length : size);
}
CBinaryReader.prototype.readInt = CBinaryReader.prototype["readInt"] = function()
{
var val = (this.data[this.pos] & 0xFF) | (this.data[this.pos + 1] & 0xFF) << 8 | (this.data[this.pos + 2] & 0xFF) << 16 | (this.data[this.pos + 3] & 0xFF) << 24;
this.pos += 4;
return val;
};
CBinaryReader.prototype.readUInt = CBinaryReader.prototype["readUInt"] = function()
{
var val = (this.data[this.pos] & 0xFF) | (this.data[this.pos + 1] & 0xFF) << 8 | (this.data[this.pos + 2] & 0xFF) << 16 | (this.data[this.pos + 3] & 0xFF) << 24;
this.pos += 4;
return (val < 0) ? val + 4294967296 : val;
};
CBinaryReader.prototype.readByte = CBinaryReader.prototype["readByte"] = function()
{
return (this.data[this.pos++] & 0xFF);
};
CBinaryReader.prototype.readPointer64 = CBinaryReader.prototype["readPointer64"] = function()
{
let i1 = this.readUInt();
let i2 = this.readUInt();
if (i2 === 0)
return i1;
return i2 * 4294967296 + i1;
};
CBinaryReader.prototype.isValid = CBinaryReader.prototype["isValid"] = function()
{
return (this.pos < this.limit) ? true : false;
};
const READER = new CBinaryReader(null, 0, 0);
function CFaceInfo()
{
this.units_per_EM = 0;
this.ascender = 0;
this.descender = 0;
this.height = 0;
this.face_flags = 0;
this.num_faces = 0;
this.num_glyphs = 0;
this.num_charmaps = 0;
this.style_flags = 0;
this.face_index = 0;
this.family_name = "";
this.style_name = "";
this.os2_version = 0;
this.os2_usWeightClass = 0;
this.os2_fsSelection = 0;
this.os2_usWinAscent = 0;
this.os2_usWinDescent = 0;
this.os2_usDefaultChar = 0;
this.os2_sTypoAscender = 0;
this.os2_sTypoDescender = 0;
this.os2_sTypoLineGap = 0;
this.os2_ulUnicodeRange1 = 0;
this.os2_ulUnicodeRange2 = 0;
this.os2_ulUnicodeRange3 = 0;
this.os2_ulUnicodeRange4 = 0;
this.os2_ulCodePageRange1 = 0;
this.os2_ulCodePageRange2 = 0;
this.os2_nSymbolic = 0;
this.header_yMin = 0;
this.header_yMax = 0;
this.monochromeSizes = [];
}
CFaceInfo.prototype.load = function(face)
{
let errorObj = AscFonts.FT_GetFaceInfo(face, READER);
if (errorObj["error"])
return;
this.units_per_EM = READER.readUInt();
this.ascender = READER.readInt();
this.descender = READER.readInt();
this.height = READER.readInt();
this.face_flags = READER.readInt();
this.num_faces = READER.readInt();
this.num_glyphs = READER.readInt();
this.num_charmaps = READER.readInt();
this.style_flags = READER.readInt();
this.face_index = READER.readInt();
var c = READER.readInt();
while (c)
{
this.family_name += (c < 0x10000) ? String.fromCharCode(c) : (String.fromCharCode(0xD800 | (c >> 10)) + String.fromCharCode(0xDC00 | (c & 0x3FF)));
c = READER.readInt();
}
c = READER.readInt();
while (c)
{
this.style_name += String.fromCharCode(c);
c = READER.readInt();
}
this.os2_version = READER.readInt();
this.os2_usWeightClass = READER.readInt();
this.os2_fsSelection = READER.readInt();
this.os2_usWinAscent = READER.readInt();
this.os2_usWinDescent = READER.readInt();
this.os2_usDefaultChar = READER.readInt();
this.os2_sTypoAscender = READER.readInt();
this.os2_sTypoDescender = READER.readInt();
this.os2_sTypoLineGap = READER.readInt();
this.os2_ulUnicodeRange1 = READER.readUInt();
this.os2_ulUnicodeRange2 = READER.readUInt();
this.os2_ulUnicodeRange3 = READER.readUInt();
this.os2_ulUnicodeRange4 = READER.readUInt();
this.os2_ulCodePageRange1 = READER.readUInt();
this.os2_ulCodePageRange2 = READER.readUInt();
this.os2_nSymbolic = READER.readInt();
this.header_yMin = READER.readInt();
this.header_yMax = READER.readInt();
var fixedSizesCount = READER.readInt();
for (var i = 0; i < fixedSizesCount; i++)
this.monochromeSizes.push(READER.readInt());
errorObj["free"]();
};
function CGlyphMetrics()
{
this.bbox_xMin = 0;
this.bbox_yMin = 0;
this.bbox_xMax = 0;
this.bbox_yMax = 0;
this.width = 0;
this.height = 0;
this.horiAdvance = 0;
this.horiBearingX = 0;
this.horiBearingY = 0;
this.vertAdvance = 0;
this.vertBearingX = 0;
this.vertBearingY = 0;
this.linearHoriAdvance = 0;
this.linearVertAdvance = 0;
}
function CGlyphBitmapImage()
{
this.left = 0;
this.top = 0;
this.width = 0;
this.rows = 0;
this.pitch = 0;
this.mode = 0;
}
AscFonts.CFaceInfo = CFaceInfo;
AscFonts.CGlyphMetrics = CGlyphMetrics;
AscFonts.CGlyphBitmapImage = CGlyphBitmapImage;
AscFonts.FT_Open_Face = function(library, stream, face_index)
{
return AscFonts.FT_Open_Face2(library, stream.data, stream.len, face_index);
};
AscFonts.FT_Glyph_Get_Measure = function(face, vector_worker, painter)
{
let errorObj = AscFonts.FT_Get_Glyph_Measure_Params(face, vector_worker ? 1 : 0, READER);
if (errorObj["error"])
return null;
let len = errorObj.count;
var info = new CGlyphMetrics();
info.bbox_xMin = READER.readInt();
info.bbox_yMin = READER.readInt();
info.bbox_xMax = READER.readInt();
info.bbox_yMax = READER.readInt();
info.width = READER.readInt();
info.height = READER.readInt();
info.horiAdvance = READER.readInt();
info.horiBearingX = READER.readInt();
info.horiBearingY = READER.readInt();
info.vertAdvance = READER.readInt();
info.vertBearingX = READER.readInt();
info.vertBearingY = READER.readInt();
info.linearHoriAdvance = READER.readInt();
info.linearVertAdvance = READER.readInt();
if (vector_worker)
{
painter.start(vector_worker);
let pos = 15;
while (pos < len)
{
pos++;
switch (READER.readInt())
{
case 0:
{
painter._move_to(READER.readInt(), READER.readInt(), vector_worker);
pos += 2;
break;
}
case 1:
{
painter._line_to(READER.readInt(), READER.readInt(), vector_worker);
pos += 2;
break;
}
case 2:
{
painter._conic_to(READER.readInt(), READER.readInt(), READER.readInt(), READER.readInt(), vector_worker);
pos += 4;
break;
}
case 3:
{
painter._cubic_to(READER.readInt(), READER.readInt(), READER.readInt(), READER.readInt(), READER.readInt(), READER.readInt(), vector_worker);
pos += 6;
break;
}
default:
break;
}
}
painter.end(vector_worker);
}
errorObj["free"]();
return info;
};
AscFonts.FT_Glyph_Get_Raster = function(face, render_mode)
{
let errorObj = AscFonts.FT_Get_Glyph_Render_Params(face, render_mode, READER);
if (errorObj["error"])
return null;
var info = new CGlyphBitmapImage();
info.left = READER.readInt();
info.top = READER.readInt();
info.width = READER.readInt();
info.rows = READER.readInt();
info.pitch = READER.readInt();
info.mode = READER.readInt();
errorObj["free"]();
return info;
};
AscFonts.FT_Get_Glyph_Render_Buffer = function(face, rasterInfo, isCopyToRasterMemory)
{
let buffer = AscFonts.FT_Get_Glyph_Render_Buffer2(face, rasterInfo.pitch * rasterInfo.rows);
if (!isCopyToRasterMemory)
return buffer;
AscFonts.raster_memory.CheckSize(rasterInfo.width, rasterInfo.rows);
let offsetSrc = 0;
let offsetDst = 3;
let dstData = AscFonts.raster_memory.m_oBuffer.data;
if (rasterInfo.pitch >= rasterInfo.width)
{
for (let j = 0; j < rasterInfo.rows; ++j, offsetSrc += rasterInfo.pitch)
{
offsetDst = 3 + j * AscFonts.raster_memory.pitch;
for (let i = 0; i < rasterInfo.width; i++, offsetDst += 4)
{
dstData[offsetDst] = buffer[offsetSrc + i];
}
}
}
else
{
var bitNumber = 0;
var byteNumber = 0;
for (let j = 0; j < rasterInfo.rows; ++j, offsetSrc += rasterInfo.pitch)
{
offsetDst = 3 + j * AscFonts.raster_memory.pitch;
bitNumber = 0;
byteNumber = 0;
for (let i = 0; i < rasterInfo.width; i++, offsetDst += 4, bitNumber++)
{
if (8 === bitNumber)
{
bitNumber = 0;
byteNumber++;
}
dstData[offsetDst] = (buffer[offsetSrc + byteNumber] & (1 << (7 - bitNumber))) ? 255 : 0;
}
}
}
};
const FONTSIZE = 576;
const STRING_MAX_LEN = 1024;
const COEF = 25.4 / 72 / 64 / FONTSIZE;
let STRING_POINTER = null;
let STRING_LEN = 0;
const CLUSTER = new Uint8Array(STRING_MAX_LEN);
let CLUSTER_LEN = 0;
let CLUSTER_MAX = 0;
const LIGATURE = 2;
const CODEPOINTS = new Uint32Array(STRING_MAX_LEN);
AscFonts.MEASURE_FONTSIZE = FONTSIZE;
AscFonts.GRAPHEME_STRING_MAX_LEN = STRING_MAX_LEN;
AscFonts.GRAPHEME_COEF = COEF;
AscFonts.HB_STRING_MAX_LEN = STRING_MAX_LEN;
function CCodePointsCalculator(codePointsBuffer, clusterBuffer)
{
this.currentCluster = 0;
this.currentCodePoint = 0;
this.clusterBuffer = clusterBuffer;
this.codePoints = codePointsBuffer;
this.codePointsCount = 0
}
CCodePointsCalculator.prototype.start = function(startCluster)
{
this.currentCluster = startCluster;
this.currentCodePoint = 0;
this.codePointsCount = 0;
}
CCodePointsCalculator.prototype.calculate = function(cluster)
{
this.currentCodePoint += this.codePointsCount;
let nCodePointsCount = 0;
if (cluster < this.currentCluster)
{
while (this.currentCluster > cluster)
{
this.currentCluster -= this.clusterBuffer[this.currentCodePoint + nCodePointsCount];
++nCodePointsCount;
}
}
else
{
while (this.currentCluster < cluster)
{
this.currentCluster += this.clusterBuffer[this.currentCodePoint + nCodePointsCount];
nCodePointsCount++;
}
}
this.codePointsCount = nCodePointsCount;
}
CCodePointsCalculator.prototype.getCount = function()
{
return this.codePointsCount;
};
CCodePointsCalculator.prototype.get = function(nPos)
{
return this.codePoints[this.currentCodePoint + nPos];
};
const CODEPOINTS_CALCULATOR = new CCodePointsCalculator(CODEPOINTS, CLUSTER);
AscFonts.HB_StartString = function()
{
if (!STRING_POINTER)
STRING_POINTER = AscFonts.AllocString(6 * STRING_MAX_LEN + 1);
STRING_LEN = 0;
CLUSTER_LEN = 0;
CLUSTER_MAX = 0;
};
AscFonts.HB_AppendToString = function(code)
{
let arrBuffer = STRING_POINTER.getBuffer();
let nClusterLen = -1;
if (code < 0x80)
{
arrBuffer[STRING_LEN++] = code;
nClusterLen = 1;
}
else if (code < 0x0800)
{
arrBuffer[STRING_LEN++] = (0xC0 | (code >> 6));
arrBuffer[STRING_LEN++] = (0x80 | (code & 0x3F));
nClusterLen = 2;
}
else if (code < 0x10000)
{
arrBuffer[STRING_LEN++] = (0xE0 | (code >> 12));
arrBuffer[STRING_LEN++] = (0x80 | ((code >> 6) & 0x3F));
arrBuffer[STRING_LEN++] = (0x80 | (code & 0x3F));
nClusterLen = 3;
}
else if (code < 0x1FFFFF)
{
arrBuffer[STRING_LEN++] = (0xF0 | (code >> 18));
arrBuffer[STRING_LEN++] = (0x80 | ((code >> 12) & 0x3F));
arrBuffer[STRING_LEN++] = (0x80 | ((code >> 6) & 0x3F));
arrBuffer[STRING_LEN++] = (0x80 | (code & 0x3F));
nClusterLen = 4;
}
else if (code < 0x3FFFFFF)
{
arrBuffer[STRING_LEN++] = (0xF8 | (code >> 24));
arrBuffer[STRING_LEN++] = (0x80 | ((code >> 18) & 0x3F));
arrBuffer[STRING_LEN++] = (0x80 | ((code >> 12) & 0x3F));
arrBuffer[STRING_LEN++] = (0x80 | ((code >> 6) & 0x3F));
arrBuffer[STRING_LEN++] = (0x80 | (code & 0x3F));
nClusterLen = 5;
}
else if (code < 0x7FFFFFFF)
{
arrBuffer[STRING_LEN++] = (0xFC | (code >> 30));
arrBuffer[STRING_LEN++] = (0x80 | ((code >> 24) & 0x3F));
arrBuffer[STRING_LEN++] = (0x80 | ((code >> 18) & 0x3F));
arrBuffer[STRING_LEN++] = (0x80 | ((code >> 12) & 0x3F));
arrBuffer[STRING_LEN++] = (0x80 | ((code >> 6) & 0x3F));
arrBuffer[STRING_LEN++] = (0x80 | (code & 0x3F));
nClusterLen = 6;
}
if (-1 !== nClusterLen)
{
CODEPOINTS[CLUSTER_LEN] = code;
CLUSTER[CLUSTER_LEN++] = nClusterLen;
CLUSTER_MAX += nClusterLen;
}
};
AscFonts.HB_EndString = function()
{
STRING_POINTER.set(STRING_LEN++, 0);
};
AscFonts.HB_GetStringLength = function()
{
return STRING_LEN;
};
AscFonts.HB_ShapeString = function(textShaper, fontId, fontStyle, fontFile, features, script, direction, language)
{
if (!STRING_POINTER)
return;
let retObj = AscFonts.HB_ShapeText(fontFile, STRING_POINTER, features, script, direction, language, READER);
if (retObj["error"])
return;
let isRtl = direction === AscFonts.HB_DIRECTION.HB_DIRECTION_RTL;
CODEPOINTS_CALCULATOR.start(isRtl ? CLUSTER_MAX : 0);
let prevCluster = -1;
let type, flags, gid, cluster, x_advance, y_advance, x_offset, y_offset;
let isLigature = false;
let nWidth = 0;
let reader = READER;
let glyphsCount = retObj.count;
for (let i = 0; i < glyphsCount; i++)
{
type = reader.readByte();
flags = reader.readByte();
gid = reader.readInt();
cluster = reader.readInt();
x_advance = reader.readInt();
y_advance = reader.readInt();
x_offset = reader.readInt();
y_offset = reader.readInt();
if (cluster !== prevCluster && -1 !== prevCluster)
{
CODEPOINTS_CALCULATOR.calculate(isRtl ? prevCluster : cluster);
textShaper.FlushGrapheme(AscFonts.GetGrapheme(CODEPOINTS_CALCULATOR), nWidth, CODEPOINTS_CALCULATOR.getCount(), isLigature);
nWidth = 0;
}
if (cluster !== prevCluster)
{
prevCluster = cluster;
isLigature = LIGATURE === type;
AscFonts.InitGrapheme(fontId, fontStyle);
}
AscFonts.AddGlyphToGrapheme(gid, x_advance, y_advance, x_offset, y_offset);
nWidth += x_advance * COEF;
}
CODEPOINTS_CALCULATOR.calculate(isRtl ? 0 : CLUSTER_MAX);
textShaper.FlushGrapheme(AscFonts.GetGrapheme(CODEPOINTS_CALCULATOR), nWidth, CODEPOINTS_CALCULATOR.getCount(), isLigature);
retObj["free"]();
};
AscFonts.HB_Shape = function(fontFile, text, features, script, direction, language)
{
if (text.length === 0)
return null;
AscFonts.HB_StartString();
for (let iter = text.getUnicodeIterator(); iter.check(); iter.next())
{
AscFonts.HB_AppendToString(iter.value());
}
AscFonts.HB_EndString();
let retObj = AscFonts.HB_ShapeText(fontFile, STRING_POINTER, features, script, direction, language, READER);
if (retObj.error)
return;
let reader = READER;
let glyphs = [];
let glyphsCount = retObj.count;
for (let i = 0; i < glyphsCount; i++)
{
let glyph = {};
glyph.type = reader.readByte();
glyph.flags = reader.readByte();
glyph.gid = reader.readInt();
glyph.cluster = reader.readInt();
glyph.x_advance = reader.readInt();
glyph.y_advance = reader.readInt();
glyph.x_offset = reader.readInt();
glyph.y_offset = reader.readInt();
glyphs.push(glyph);
}
let utf8_start = 0;
let utf8_end = 0;
let arBuffer = STRING_POINTER.getBuffer();
if (direction === AscFonts.HB_DIRECTION.HB_DIRECTION_RTL)
{
for (let i = glyphsCount - 1; i >= 0; i--)
{
if (i === 0)
utf8_end = CLUSTER_MAX;
else
utf8_end = glyphs[i - 1].cluster;
glyphs[i].text = String.prototype.fromUtf8(arBuffer, utf8_start, utf8_end - utf8_start);
utf8_start = utf8_end;
}
}
else
{
for (let i = 0; i < glyphsCount; i++)
{
if (i === (glyphsCount - 1))
utf8_end = CLUSTER_MAX;
else
utf8_end = glyphs[i + 1].cluster;
glyphs[i].text = String.prototype.fromUtf8(arBuffer, utf8_start, utf8_end - utf8_start);
utf8_start = utf8_end;
}
}
retObj["free"]();
return glyphs;
};
// ZLIB
function ZLib()
{
/** @suppress {checkVars} */
this.engine = window["NATIVE_EDITOR_ENJINE"] ? CreateEmbedObject("CZipEmbed") : new AscCommon["CZLibEngineJS"]();
this.files = [];
}
/**
* Open archive from bytes
* @param {Uint8Array | ArrayBuffer} buf
* @returns {boolean} success or not
*/
ZLib.prototype.open = function(buf)
{
if (this.engine.open(buf))
this.files = this.engine["getPaths"]();
return (this.files.length > 0) ? true : false;
};
/**
* Create new archive
* @returns {boolean} success or not
*/
ZLib.prototype.create = function()
{
return this.engine["create"]();
};
/**
* Save archive from current files
* @returns {Uint8Array | null} zip-archive bytes, or null if error
*/
ZLib.prototype.save = function()
{
return this.engine["save"]();
};
/**
* Get uncomressed file from archive
* @param {string} path
* @returns {Uint8Array | null} bytes of uncompressed data, or null if error
*/
ZLib.prototype.getFile = function(path)
{
return this.engine["getFile"](path);
};
/**
* Add uncomressed file to archive
* @param {string} path
* @param {Uint8Array | ArrayBuffer} new file in archive
* @returns {boolean} success or not
*/
ZLib.prototype.addFile = function(path, data)
{
return this.engine["addFile"](path, (undefined !== data.byteLength) ? new Uint8Array(data) : data);
};
/**
* Remove file from archive
* @param {string} path
* @returns {boolean} success or not
*/
ZLib.prototype.removeFile = function(path)
{
return this.engine["removeFile"](path);
};
/**
* Close & remove all used memory in archive
* @returns {undefined}
*/
ZLib.prototype.close = function()
{
return this.engine["close"]();
};
/**
* Get image blob for browser
* @returns {Blob}
*/
ZLib.prototype.getImageBlob = function(path)
{
return this.engine["getImageBlob"](path);
};
/**
* Get image file raw data. this memory was copied and detach from archive.
* @returns {Uint8Array}
*/
ZLib.prototype.getImageBuffer = function(path)
{
return this.engine["getImageBuffer"](path);
};
/**
* Get all file paths in archive
* @returns {Array}
*/
ZLib.prototype.getPaths = function()
{
return this.engine["getPaths"]();
};
AscCommon.ZLib = ZLib;
function ZlibImageBlobs()
{
this.url2BlobUrl = {};
this.blobUrl2Data = {};
this.url2Base64 = {};
this.nativeBlobCounter = 1;
}
ZlibImageBlobs.prototype.getBlobUrl = function(path, zip)
{
if (this.url2BlobUrl[path])
return this.url2BlobUrl[path];
let result = zip.getImageBuffer(path);
if (result == null)
return "";
let blobUrl = "";
let blobType = AscCommon.openXml.GetMimeType((24 !== result["type"]) ? AscCommon.GetFileExtension(path) : "svg");
if (window["NATIVE_EDITOR_ENJINE"])
{
blobUrl = "blob:internal-image" + this.nativeBlobCounter++;
}
else
{
try
{
let blob = new Blob([result["dataBlob"] ? result["dataBlob"] : result["data"]], {type: blobType});
blobUrl = window.URL.createObjectURL(blob);
}
catch (e)
{
blobUrl = "error";
AscCommon.consoleLog("ERROR: Image blob was not loaded");
}
}
this.blobUrl2Data[blobUrl] = result;
this.url2BlobUrl[path] = blobUrl;
return blobUrl;
};
ZlibImageBlobs.prototype.getImageBase64 = function(url)
{
if (this.url2Base64[url])
return this.url2Base64[url];
let obj = this.blobUrl2Data[url];
if (!obj)
return url;
let header = "";
switch (obj.type)
{
case 3:
header = "data:image/jpeg;base64,";
break;
case 24:
header = "data:image/svg+xml;base64,";
break;
case 4:
default:
header = "data:image/png;base64,";
}
this.url2Base64[url] = header + AscCommon.Base64.encode(obj.data);
return this.url2Base64[url];
};
window["AscCommon"].g_oDocumentBlobUrls = new ZlibImageBlobs();
if (AscCommon["CZLibEngineJS"])
AscCommon["CZLibEngineJS"].prototype["isModuleInit"] = true;
if (window["NATIVE_EDITOR_ENJINE"])
window["InitNativeZLib"] = function() { window.nativeZlibEngine = new ZLib(); };
else
window.nativeZlibEngine = new ZLib();
function Hyphenation()
{
this._value = "";
this._lang = 0;
this._dictionaries = {};
this._mapToNames = null;
this.addCodePoint = function(codePoint)
{
this._value += String.fromCodePoint(codePoint);
};
this.clear = function()
{
this._value = "";
};
this.setLang = function(langCode, callback)
{
this._lang = langCode;
let _langKey = "" + langCode;
if (this._dictionaries[_langKey] !== undefined)
return this._dictionaries[_langKey];
if (window["NATIVE_EDITOR_ENJINE"])
{
this._dictionaries[_langKey] = AscFonts.Hyphen_CheckDictionary(this._lang);
return this._dictionaries[_langKey];
}
else if (callback)
{
if (!this._mapToNames)
this._mapToNames = AscCommon.spellcheckGetLanguages();
if (undefined !== this._mapToNames["" + langCode])
this.loadDictionary(langCode, callback);
}
return false;
};
this.hyphenate = function()
{
if ("" === this._value)
return [];
return AscFonts.Hyphen_Word(this._lang, this._value);
};
this.loadDictionary = function(lang, callback)
{
if (window["NATIVE_EDITOR_ENJINE"])
{
callback();
return;
}
if (!this._mapToNames)
this._mapToNames = AscCommon.spellcheckGetLanguages();
let _langKey = "" + lang;
let _langObj = this._mapToNames[_langKey];
if (!_langObj || !_langObj["hyphen"] || !_langObj["name"])
{
this._dictionaries[_langKey] = false;
callback();
return;
}
this._loadDictionaryAttemt(_langKey, _langObj["name"], callback);
};
this._loadDictionaryAttemt = function(langKey, langName, callback, currentAttempt)
{
var xhr = new XMLHttpRequest();
let urlDictionaries = "../../../../dictionaries/";
if (window["AscDesktopEditor"] && window["AscDesktopEditor"]["getDictionariesPath"])
{
let urlDesktop = window["AscDesktopEditor"]["getDictionariesPath"]();
if ("" !== urlDesktop)
urlDictionaries = urlDesktop;
}
let url = urlDictionaries + langName + "/hyph_" + langName + ".dic";
xhr.open('GET', url, true);
xhr.responseType = 'arraybuffer';
xhr.currentAttempt = currentAttempt || 0;
if (xhr.overrideMimeType)
xhr.overrideMimeType('text/plain; charset=x-user-defined');
else
xhr.setRequestHeader('Accept-Charset', 'x-user-defined');
var _t = this;
xhr.onload = function()
{
if (this.status === 200 || location.href.indexOf("file:") === 0)
{
_t._dictionaries[langKey] = true;
AscFonts.Hyphen_LoadDictionary(parseInt(langKey), this.response);
callback();
}
};
xhr.onerror = function()
{
let _currentAttempt = xhr.currentAttempt + 1;
if (_currentAttempt > 3)
{
_t._dictionaries[langKey] = false;
callback();
return;
}
_t._loadDictionaryAttemt(langKey, langName, callback, _currentAttempt);
};
xhr.send(null);
};
}
window["AscHyphenation"] = new Hyphenation();
}

View File

@ -2062,7 +2062,10 @@ namespace Aggplus
double dX = 0.72, dY = 0.72;
agg::trans_affine invert = ~m_oFullTransform.m_internal->m_agg_mtx;
invert.transform_2x2(&dX, &dY);
dWidth = std::min(abs(dX), abs(dY));
if (dX < 0) dX = -dX;
if (dY < 0) dY = -dY;
dWidth = (dX > dY) ? dY : dX;
}
else if (0 != dSqrtDet && dWidth < (dWidthMinSize = 1.0 / dSqrtDet))
dWidth = dWidthMinSize;

View File

@ -210,6 +210,7 @@ namespace NSOnlineOfficeBinToPdf
oRenderer.CreateFromBgraFrame(&oFrame);
oRenderer.SetTileImageDpi(96.0);
oRenderer.SetSwapRGB(false);
oRenderer.CommandLong(c_nPenWidth0As1px, 1);
this->m_pRenderer = &oRenderer;
BYTE* pBufferPage = oInfo.arSizes[nPageIndex].data;

View File

@ -897,6 +897,7 @@ CAnnotFieldInfo::CWidgetAnnotPr::CButtonWidgetPr* CAnnotFieldInfo::CWidgetAnn
CAnnotFieldInfo::CWidgetAnnotPr::CTextWidgetPr* CAnnotFieldInfo::CWidgetAnnotPr::GetTextWidgetPr() { return m_pTextPr; }
CAnnotFieldInfo::CWidgetAnnotPr::CChoiceWidgetPr* CAnnotFieldInfo::CWidgetAnnotPr::GetChoiceWidgetPr() { return m_pChoicePr; }
CAnnotFieldInfo::CWidgetAnnotPr::CSignatureWidgetPr* CAnnotFieldInfo::CWidgetAnnotPr::GetSignatureWidgetPr() { return m_pSignaturePr; }
void CAnnotFieldInfo::CWidgetAnnotPr::SetFontName(const std::wstring& sName) { m_wsFN = sName; }
CAnnotFieldInfo::CWidgetAnnotPr::CWidgetAnnotPr(BYTE nType)
{
m_pButtonPr = NULL;

View File

@ -203,6 +203,8 @@ public:
const std::vector<double>& GetBG();
const std::vector<CActionFieldPr*>& GetActions();
void SetFontName(const std::wstring& sName);
CButtonWidgetPr* GetButtonWidgetPr();
CTextWidgetPr* GetTextWidgetPr();
CChoiceWidgetPr* GetChoiceWidgetPr();

View File

@ -233,20 +233,98 @@ namespace NSHtmlRenderer
NSWasm::CHChar* pLastChar = m_oLine.GetTail();
if (dOffsetX > (pLastChar->width + 0.5))
{
// insert space. Our space will not be a regular space. But a specific one
NSWasm::CHChar* pSpaceChar = m_oLine.AddTail();
pLastChar = &m_oLine.m_pChars[m_oLine.m_lCharsTail - 2];
pSpaceChar->x = pLastChar->width;
pSpaceChar->width = dOffsetX - pLastChar->width;
pSpaceChar->unicode = 0xFFFF;
dOffsetX -= pLastChar->width;
if (pLastChar->unicode == 32 || pLastChar->unicode == 9)
{
pLastChar->width = dOffsetX;
}
else
{
// insert space. Our space will not be a regular space. But a specific one
NSWasm::CHChar* pSpaceChar = m_oLine.AddTail();
pLastChar = &m_oLine.m_pChars[m_oLine.m_lCharsTail - 2];
pSpaceChar->x = pLastChar->width;
pSpaceChar->width = dOffsetX - pLastChar->width;
pSpaceChar->unicode = 0xFFFF;
dOffsetX -= pLastChar->width;
}
}
}
else
{
// letter is shifted left relative to previous letter
// we react to this situation simply - just start a new line,
// after dumping the old one
// check if new glyph lands inside a synthetic space (0xFFFF) in current line
double sx = _x1 - m_oLine.m_dX;
double sy = _y1 - m_oLine.m_dY;
double newGlyphOffset = sx * m_oLine.m_ex + sy * m_oLine.m_ey;
// walk through chars accumulating offset to find which char we hit
double charOffset = 0;
LONG nCount = m_oLine.GetCountChars();
LONG nSplitIndex = -1;
for (LONG i = 0; i < nCount; ++i)
{
NSWasm::CHChar* pCh = &m_oLine.m_pChars[i];
if (i > 0)
charOffset += pCh->x; // x here is offset from previous char
if (pCh->unicode == 0xFFFF &&
newGlyphOffset >= charOffset &&
newGlyphOffset < charOffset + pCh->width)
{
nSplitIndex = i;
break;
}
}
if (nSplitIndex >= 0)
{
NSWasm::CHLine oSaved;
oSaved = m_oLine;
// --- Dump head: chars [0 .. nSplitIndex - 1] ---
m_oLine.m_lCharsTail = nSplitIndex; // truncate before the 0xFFFF
DumpLine(); // clears m_oLine
// --- Dump tail: chars [nSplitIndex + 1 .. nCount - 1] ---
LONG nTailStart = nSplitIndex + 1;
LONG nTailCount = nCount - nTailStart;
if (nTailCount > 0)
{
// Reconstruct baseline origin for the tail.
// Walk offsets up to nTailStart to find its position along baseline.
double tailOffset = 0;
for (LONG i = 1; i <= nTailStart; ++i)
tailOffset += oSaved.m_pChars[i].x;
m_oLine.m_bIsConstX = oSaved.m_bIsConstX;
m_oLine.m_dK = oSaved.m_dK;
m_oLine.m_dB = oSaved.m_dB;
m_oLine.m_ex = oSaved.m_ex;
m_oLine.m_ey = oSaved.m_ey;
m_oLine.m_dAscent = oSaved.m_dAscent;
m_oLine.m_dDescent = oSaved.m_dDescent;
m_oLine.m_bIsSetUpTransform = oSaved.m_bIsSetUpTransform;
m_oLine.m_sx = oSaved.m_sx;
m_oLine.m_sy = oSaved.m_sy;
m_oLine.m_shx = oSaved.m_shx;
m_oLine.m_shy = oSaved.m_shy;
// Origin of tail shifted along baseline
m_oLine.m_dX = oSaved.m_dX + tailOffset * oSaved.m_ex;
m_oLine.m_dY = oSaved.m_dY + tailOffset * oSaved.m_ey;
m_oLine.m_dEndX = m_oLine.m_dX;
m_oLine.m_dEndY = m_oLine.m_dY;
// Copy tail chars; first tail char has x=0 (it's now the line origin)
for (LONG i = 0; i < nTailCount; ++i)
{
NSWasm::CHChar* pDst = m_oLine.AddTail();
*pDst = oSaved.m_pChars[nTailStart + i];
if (i == 0)
pDst->x = 0; // first char offset is always 0
}
}
}
DumpLine();
m_oLine.m_bIsConstX = _isConstX;

View File

@ -424,8 +424,14 @@ namespace NSWasm
m_dX = oLine.m_dX;
m_dY = oLine.m_dY;
m_dEndX = oLine.m_dEndX;
m_dEndY = oLine.m_dEndY;
m_dK = oLine.m_dK;
m_dB = oLine.m_dB;
m_ex = oLine.m_ex;
m_ey = oLine.m_ey;
m_bIsConstX = oLine.m_bIsConstX;
m_lSizeChars = oLine.m_lSizeChars;
m_lCharsTail = oLine.m_lCharsTail;

View File

@ -30,6 +30,16 @@
*
*/
/*
* Test utility. NOT used in production builds.
*
* This code is intended solely for local debugging and verification
* of internal components by developers. Security concerns
* (error handling, input validation, protection against race conditions,
* buffer overflows, etc.) are intentionally not addressed in this file
* and are not applicable.
*/
#include <iostream>
#include <fstream>
#include <sstream>

View File

@ -1,3 +0,0 @@
oform_plugin/module/deploy
hash/deploy
all/deploy

View File

@ -1,2 +0,0 @@
openssl
xml

View File

@ -1,39 +0,0 @@
import sys
sys.path.append("../../../../../../build_tools/scripts")
sys.path.append("../../../../../Common/js")
import base
import os
import codecs
import common
def run_as_bash(file, commands):
if base.is_file(file):
base.delete_file(file)
file_bash = codecs.open(file, "w", "utf-8")
file_bash.write("#!/bin/bash\n")
file_bash.write("\n".join(commands))
file_bash.close()
base.cmd("chmod", ["+x", file])
base.cmd(file)
return
if "windows" == base.host_platform():
print("Windows system not supported. Please use Linux or MacOS")
exit(0)
# fetch openssl
if not base.is_dir("./openssl"):
base.print_info("Fetching openssl...")
base.cmd("git", ["clone", "--depth=1", "--branch", "OpenSSL_1_1_1f", "https://github.com/openssl/openssl.git"])
# correct for wasm builds
common.apply_patch("./openssl/crypto/rand/rand_lib.c", "./patches/openssl1.patch")
base.copy_file("../../../../../Common/3dParty/openssl/openssl/apps/progs.h", "./openssl/apps/progs.h")
# compile openssl
if not base.is_file("./openssl/libcrypto.a"):
base.print_info("Compile openssl...")
os.chdir("./openssl")
#run_as_bash("./compile_openssl.sh", ["./config no-shared no-asm no-ssl2 no-ssl3", "source ./../emsdk/emsdk_env.sh", "export CC=emcc", "export CXX=emcc", "make"])
run_as_bash("./compile_openssl.sh", ["source ./../../../../../../Common/js/emsdk/emsdk_env.sh", "emconfigure ./config no-shared no-asm no-threads no-dso", "sed -i 's|^CROSS_COMPILE.*$|CROSS_COMPILE=|g' Makefile", "emmake make build_generated libssl.a libcrypto.a"])
os.chdir("./..")
common.apply_patch("./openssl/include/openssl/opensslconf.h", "./patches/openssl2.patch")

View File

@ -1,49 +0,0 @@
<<<<<<<
/*
* This function is not part of RAND_METHOD, so if we're not using
* the default method, then just call RAND_bytes(). Otherwise make
* sure we're instantiated and use the private DRBG.
*/
int RAND_priv_bytes(unsigned char *buf, int num)
{
const RAND_METHOD *meth = RAND_get_rand_method();
RAND_DRBG *drbg;
if (meth != NULL && meth != RAND_OpenSSL())
return RAND_bytes(buf, num);
drbg = RAND_DRBG_get0_private();
if (drbg != NULL)
return RAND_DRBG_bytes(drbg, buf, num);
return 0;
}
int RAND_bytes(unsigned char *buf, int num)
{
const RAND_METHOD *meth = RAND_get_rand_method();
if (meth != NULL && meth->bytes != NULL)
return meth->bytes(buf, num);
RANDerr(RAND_F_RAND_BYTES, RAND_R_FUNC_NOT_IMPLEMENTED);
return -1;
}
=======
#include "emscripten.h"
EM_JS(int, js_random, (unsigned char* buf, int num), {
var byteArray = new Uint8Array(num);
var engine = self.crypto || self.msCrypto;
engine.getRandomValues(byteArray);
Module["HEAP8"].set(byteArray, buf);
return 1;
});
int RAND_priv_bytes(unsigned char *buf, int num)
{
return js_random(buf, num);
}
int RAND_bytes(unsigned char *buf, int num)
{
return js_random(buf, num);
}
>>>>>>>

View File

@ -1,11 +0,0 @@
<<<<<<<
#ifndef OPENSSL_NO_MD2
# define OPENSSL_NO_MD2
#endif
=======
#ifndef OPENSSL_MD2_ENABLED
#ifndef OPENSSL_NO_MD2
# define OPENSSL_NO_MD2
#endif
#endif
>>>>>>>

View File

@ -1,11 +0,0 @@
import sys;
sys.path.append("../../../../../../build_tools/scripts");
import base;
base.replaceInFile("./deploy/openssl.js", "__ATPOSTRUN__=[];", "__ATPOSTRUN__=[function(){self.onEngineInit();}];");
base.replaceInFile("./deploy/openssl.js", "__ATPOSTRUN__ = [];", "__ATPOSTRUN__=[function(){self.onEngineInit();}];");
base.replaceInFile("./deploy/openssl.js", "function getBinaryPromise()", "function getBinaryPromise2()");
base.replaceInFile("./deploy/openssl_ie.js", "__ATPOSTRUN__=[];", "__ATPOSTRUN__=[function(){self.onEngineInit();}];");
base.replaceInFile("./deploy/openssl_ie.js", "__ATPOSTRUN__ = [];", "__ATPOSTRUN__=[function(){self.onEngineInit();}];");
base.replaceInFile("./deploy/openssl_ie.js", "function getBinaryPromise()", "function getBinaryPromise2()");

View File

@ -1,14 +0,0 @@
import sys
sys.path.append("../../../../../../build_tools/scripts")
import base
base.cmd_in_dir("./../3rdParty", "python", ["openssl.py"])
if not base.is_dir("./../3rdPartyxml"):
base.print_info("Copy xml...")
base.copy_dir("./../../../../xml", "./../3rdParty/xml")
base.replaceInFile("./../3rdParty/xml/libxml2/libxml.h", "xmlNop(void)", "xmlNop(void* context, char* buffer, int len)")
base.replaceInFile("./../3rdParty/xml/libxml2/xmlIO.c", "xmlNop(void)", "xmlNop(void* context, char* buffer, int len)")
base.replaceInFile("./../3rdParty/xml/src/xmllight_private.h", "#include \"../../common/", "#include \"../../../../../../common/")
base.replaceInFile("./../3rdParty/xml/include/xmlutils.h", "#include \"../../common/", "#include \"../../../../../../common/")
base.replaceInFile("./../3rdParty/xml/include/xmlwriter.h", "#include \"../../common/", "#include \"../../../../../../common/")

View File

@ -1,134 +0,0 @@
window.onload = function()
{
var xmlCertificate = new window.XmlSignature();
var XmlError = window.XmlSignatureError;
function loadCert(data, password)
{
window.certFileData = data;
var err = xmlCertificate.loadCert(window.certFileData, password);
switch (err)
{
case XmlError.OPEN_SSL_WARNING_ERR:
{
alert("error");
break;
}
case XmlError.OPEN_SSL_WARNING_ALL_OK:
{
document.getElementById("key").style.display = "none";
document.getElementById("password").style.display = "none";
break;
}
case XmlError.OPEN_SSL_WARNING_OK:
{
document.getElementById("key").style.display = "";
document.getElementById("password").style.display = "none";
break;
}
case XmlError.OPEN_SSL_WARNING_PASS:
{
document.getElementById("key").style.display = "none";
document.getElementById("password").style.display = "";
break;
}
default:
break;
}
}
function loadKey(data, password)
{
window.keyFileData = data;
var err = xmlCertificate.loadKey(window.keyFileData, password);
switch (err)
{
case XmlError.OPEN_SSL_WARNING_ERR:
{
alert("error");
break;
}
case XmlError.OPEN_SSL_WARNING_ALL_OK:
case XmlError.OPEN_SSL_WARNING_OK:
{
document.getElementById("password").style.display = "none";
break;
}
case XmlError.OPEN_SSL_WARNING_PASS:
{
document.getElementById("password").style.display = "";
break;
}
default:
break;
}
}
document.getElementById('button_certificate').onchange = function() {
var reader = new FileReader();
reader.onload = function() {
loadCert(this.result);
};
reader.readAsArrayBuffer(this.files[0]);
};
document.getElementById('button_key').onchange = function() {
var reader = new FileReader();
reader.onload = function() {
loadKey(this.result);
};
reader.readAsArrayBuffer(this.files[0]);
};
document.getElementById('file_select').onchange = function() {
var reader = new FileReader();
reader.onload = function() {
window.fileFileData = this.result;
};
reader.readAsArrayBuffer(this.files[0]);
};
document.getElementById('button_password').onclick = function() {
if (document.getElementById("key").style.display == "none")
loadCert(window.certFileData, document.getElementById("area_password").value);
else
loadKey(window.keyFileData, document.getElementById("area_password").value);
};
document.getElementById('button_sign').onclick = function() {
if (!window.fileFileData)
{
alert("Please select file");
return;
}
function downloadBlob(data, fileName, mimeType) {
var blob, url;
blob = new Blob([data], {
type: mimeType
});
url = window.URL.createObjectURL(blob);
downloadURL(url, fileName);
setTimeout(function() {
return window.URL.revokeObjectURL(url);
}, 1000);
};
function downloadURL(data, fileName) {
var a;
a = document.createElement('a');
a.href = data;
a.download = fileName;
document.body.appendChild(a);
a.style = 'display: none';
a.click();
a.remove();
};
var result = xmlCertificate.sign(window.fileFileData);
downloadBlob(result, 'sign_file.docx', 'application/octet-stream');
};
};

View File

@ -1,181 +0,0 @@
(function(window, undefined){
//desktop_fetch
//string_utf8
//module
function NativePointer(buffer)
{
this.data = 0;
this.size = 0;
if (buffer)
this.alloc(buffer);
}
NativePointer.prototype.alloc = function(data_or_size)
{
this.free();
if (typeof data_or_size === "number")
{
this.data = Module["_XmlSignature_Malloc"](data_or_size);
if (0 != this.data)
this.size = data_or_size;
}
else
{
var arrayBuffer = (undefined !== data_or_size.byteLength) ? new Uint8Array(data_or_size) : data_or_size;
this.data = Module["_XmlSignature_Malloc"](arrayBuffer.length);
if (0 != this.data)
{
this.size = arrayBuffer.length;
Module["HEAP8"].set(arrayBuffer, this.data);
}
}
};
NativePointer.prototype.free = function(freeFunc)
{
if (this.data != 0)
{
(freeFunc || Module["_XmlSignature_Free"])(this.data);
}
this.data = 0;
this.size = 0;
};
NativePointer.prototype.isEmpty = function()
{
return (0 == this.data);
};
var XmlSignatureError = {
OPEN_SSL_WARNING_OK : 0,
OPEN_SSL_WARNING_ERR : 1,
OPEN_SSL_WARNING_ALL_OK : 2,
OPEN_SSL_WARNING_PASS : 4,
OPEN_SSL_WARNING_NOVERIFY : 8
};
function XmlSignature()
{
this._certFilePtr = new NativePointer();
this._keyFilePtr = new NativePointer();
this.certificate = 0;
}
XmlSignature.prototype.isModuleInit = false;
XmlSignature.prototype.loadCert = function(data, password)
{
if (!this.isModuleInit || !data)
return XmlSignatureError.OPEN_SSL_WARNING_ERR;
if (!this.create())
return XmlSignatureError.OPEN_SSL_WARNING_ERR;
this._certFilePtr.alloc(data);
if (this._certFilePtr.isEmpty())
return XmlSignatureError.OPEN_SSL_WARNING_ERR;
var _password = new NativePointer();
if (password)
_password.alloc(password.toUtf8());
var retError = Module["_XmlSignature_LoadCert"](this.certificate, this._certFilePtr.data, this._certFilePtr.size, _password.data);
_password.free();
return retError;
};
XmlSignature.prototype.loadKey = function(data, password)
{
if (!this.isModuleInit || !this.certificate || !data)
return XmlSignatureError.OPEN_SSL_WARNING_ERR;
this._keyFilePtr.alloc(data);
if (this._keyFilePtr.isEmpty())
return XmlSignatureError.OPEN_SSL_WARNING_ERR;
var _password = new NativePointer();
if (password)
_password.alloc(password.toUtf8());
var retError = Module["_XmlSignature_LoadKey"](this.certificate, this._keyFilePtr.data, this._keyFilePtr.size, _password.data);
_password.free();
return retError;
};
XmlSignature.prototype.sign = function(data)
{
if (!this.isModuleInit || !this.certificate || !data)
return null;
var _filePtr = new NativePointer(data);
if (_filePtr.isEmpty())
return null;
var _file = Module["_XmlSignature_CreateFile"](_filePtr.data, _filePtr.size);
// data will be deleted when the file is deleted
_filePtr.data = 0;
_filePtr.size = 0;
if (0 == _file)
return null;
var result = Module["_XmlSignature_Sign"](_file, this.certificate);
if (0 == result)
return null;
Module["_XmlSignature_DestroyFile"](_file);
if (0 == result)
return null;
var dst= null;
var resultSize = Module["_XmlSignature_GetFileSize"](result);
if (0 != resultSize)
{
var resultRaw = Module["_XmlSignature_GetFileRaw"](result);
var fileData = new Uint8Array(Module["HEAP8"].buffer, resultRaw, resultSize);
dst = new Uint8Array(resultSize);
dst.set(fileData);
}
Module["_XmlSignature_DestroyFile"](result);
return dst;
};
XmlSignature.prototype.create = function()
{
if (!this.isModuleInit)
return false;
if (0 != this.certificate)
this.close();
this.certificate = Module["_XmlSignature_CreateCertificate"]();
return (0 != this.certificate) ? true : false;
};
XmlSignature.prototype.close = function()
{
if (!this.isModuleInit)
return;
if (this.certificate)
{
Module["_XmlSignature_DestroyCertificate"](this.certificate);
this.certificate = 0;
}
this._certFilePtr.free();
this._keyFilePtr.free();
};
window.XmlSignature = XmlSignature;
window.XmlSignatureError = XmlSignatureError;
window.onEngineInit = function()
{
window.XmlSignature.prototype.isModuleInit = true;
};
})(window, undefined);

View File

@ -1,42 +0,0 @@
<!doctype html>
<html style="width:100%;height:100%;margin:0;padding:0;">
<head>
<title>ONLYOFFICE Documents</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=IE8">
<script src="./code.js"></script>
<script src="./openssl.js"></script>
<style>
div {
margin: 10px;
}
</style>
</head>
<body style="width:100%;height:100%;margin:50;padding:0;overflow:hidden;">
<div id="certificate">
<label for="button_certificate">Select Certificate</label>
<input type="file" id="button_certificate">
</div>
<div id="key" style="display:none;">
<label for="button_key">Select Private Key</label>
<input type="file" id="button_key" value="load key">
</div>
<div id="password" style="display:none;">
<textarea id="area_password" placeholder="password..."></textarea>
<input type="button" id="button_password" value="setup password">
</div>
<div id="file">
<label for="file_select">Select OOXML File</label>
<input type="file" id="file_select" value="load file">
</div>
<div id="sign">
<input type="button" id="button_sign" value="Sign">
</div>
</body>
</html>

View File

@ -1,213 +0,0 @@
#include "../../../../common/File.h"
#include "../../include/Certificate.h"
#include "../../include/CertificateCommon.h"
#include "../../include/OOXMLSigner.h"
#include "../../include/OOXMLVerifier.h"
#ifdef _WIN32
#define WASM_EXPORT __declspec(dllexport)
#else
#define WASM_EXPORT __attribute__((visibility("default")))
#endif
#ifdef __cplusplus
extern "C" {
#endif
WASM_EXPORT void* XmlSignature_Malloc(unsigned int size)
{
return ::malloc(size);
}
WASM_EXPORT void XmlSignature_Free(void* p)
{
if (p) ::free(p);
}
class CMemoryFile
{
public:
unsigned int Length;
BYTE* Data;
public:
CMemoryFile(BYTE* data = NULL, unsigned int len = 0) { Length = len; Data = data; }
~CMemoryFile() { if (Data) delete [] Data; }
};
class CCertificate
{
public:
ICertificate* m_pCert;
private:
unsigned char* m_key;
unsigned int m_keyLen;
std::string m_keyPass;
unsigned char* m_cert;
unsigned int m_certLen;
std::string m_certPass;
public:
CCertificate()
{
m_pCert = NULL;
}
~CCertificate()
{
delete m_pCert;
}
public:
int LoadCert(unsigned char* data, unsigned int len, char* pass)
{
m_cert = NULL; m_certLen = 0; m_certPass = "";
int nRes = NSOpenSSL::LoadCertRaw(data, len, (NULL != pass) ? std::string(pass) : "");
if (OPEN_SSL_WARNING_ALL_OK == nRes || OPEN_SSL_WARNING_OK == nRes)
{
m_cert = data;
m_certLen = len;
m_certPass = (NULL != pass) ? std::string(pass) : "";
}
if (OPEN_SSL_WARNING_ALL_OK == nRes)
{
m_key = m_cert;
m_keyLen = m_certLen;
m_keyPass = m_certPass;
}
return nRes;
}
int LoadKey(unsigned char* data, unsigned int len, char* pass)
{
m_key = NULL; m_keyLen = 0; m_keyPass = "";
int nRes = NSOpenSSL::LoadKeyRaw(data, len, (NULL != pass) ? std::string(pass) : "");
if (OPEN_SSL_WARNING_ALL_OK == nRes || OPEN_SSL_WARNING_OK == nRes)
{
m_key = data;
m_keyLen = len;
m_keyPass = (NULL != pass) ? std::string(pass) : "";
}
if (OPEN_SSL_WARNING_ALL_OK == nRes)
{
m_cert = m_key;
m_certLen = m_keyLen;
m_certPass = m_keyPass;
}
return nRes;
}
void Load()
{
m_pCert = NSCertificate::FromFilesRaw(m_key, m_keyLen, m_keyPass, m_cert, m_certLen, m_certPass);
}
ICertificate* GetCertificate()
{
return m_pCert;
}
};
WASM_EXPORT void* XmlSignature_CreateCertificate()
{
return new CCertificate();
}
WASM_EXPORT int XmlSignature_LoadCert(void* cert, unsigned char* data, unsigned int len, char* pass)
{
CCertificate* pCert = (CCertificate*)cert;
return pCert->LoadCert(data, len, pass);
}
WASM_EXPORT int XmlSignature_LoadKey(void* cert, unsigned char* data, unsigned int len, char* pass)
{
CCertificate* pCert = (CCertificate*)cert;
return pCert->LoadKey(data, len, pass);
}
WASM_EXPORT void XmlSignature_DestroyCertificate(void* cert)
{
CCertificate* pCert = (CCertificate*)cert;
delete pCert;
}
WASM_EXPORT void* XmlSignature_CreateFile(unsigned char* file, unsigned int len)
{
return new CMemoryFile(file, len);
}
WASM_EXPORT unsigned int XmlSignature_GetFileSize(void* file)
{
CMemoryFile* pZipFile = (CMemoryFile*)file;
return pZipFile->Length;
}
WASM_EXPORT void* XmlSignature_GetFileRaw(void* file)
{
CMemoryFile* pZipFile = (CMemoryFile*)file;
return pZipFile->Data;
}
WASM_EXPORT void XmlSignature_DestroyFile(void* file)
{
CMemoryFile* pZipFile = (CMemoryFile*)file;
delete pZipFile;
}
WASM_EXPORT void* XmlSignature_Sign(void* file, void* cert)
{
CCertificate* pCert = (CCertificate*)cert;
CMemoryFile* pZipFile = (CMemoryFile*)file;
pCert->Load();
COOXMLSigner oSigner(pZipFile->Data, pZipFile->Length, pCert->GetCertificate());
CMemoryFile* pFile = new CMemoryFile();
unsigned long lDataDstLen = 0;
oSigner.Sign(pFile->Data, lDataDstLen);
pFile->Length = (unsigned int)lDataDstLen;
return pFile;
}
#ifdef __cplusplus
}
#endif
#ifdef TEST_AS_EXECUTABLE
int main()
{
std::wstring sTestDir = NSFile::GetProcessDirectory() + L"/../../../../test/";
void* cert = XmlSignature_CreateCertificate();
BYTE* pCertData = NULL;
DWORD nCertLen = 0;
NSFile::CFileBinary::ReadAllBytes(sTestDir + L"keys/cert.crt", &pCertData, nCertLen);
XmlSignature_LoadCert(cert, pCertData, nCertLen, NULL);
BYTE* pKeyData = NULL;
DWORD nKeyLen = 0;
NSFile::CFileBinary::ReadAllBytes(sTestDir + L"keys/key.key", &pKeyData, nKeyLen);
XmlSignature_LoadKey(cert, pKeyData, nKeyLen, NULL);
BYTE* pData = NULL;
DWORD nLen = 0;
NSFile::CFileBinary::ReadAllBytes(sTestDir + L"file.docx", &pData, nLen);
CMemoryFile* file = (CMemoryFile*)XmlSignature_CreateFile(pData, nLen);
CMemoryFile* res = (CMemoryFile*)XmlSignature_Sign(file, cert);
NSFile::CFileBinary oFileDst;
oFileDst.CreateFileW(sTestDir + L"/file2.docx");
oFileDst.WriteFile(res->Data, (DWORD)res->Length);
oFileDst.CloseFile();
XmlSignature_DestroyFile(file); // RELEASEARRAYOBJECTS(pData);
XmlSignature_DestroyFile(res);
XmlSignature_DestroyCertificate(cert);
RELEASEARRAYOBJECTS(pCertData);
RELEASEARRAYOBJECTS(pKeyData);
return 0;
}
#endif

View File

@ -1,190 +0,0 @@
#!/usr/bin/env python
import sys
sys.path.append('../../../../../../build_tools/scripts')
import base
import os
import codecs
def apply_patch(file, patch):
file_content = base.readFile(file)
patch_content = base.readFile(patch)
index1 = patch_content.find("<<<<<<<")
index2 = patch_content.find("=======")
index3 = patch_content.find(">>>>>>>")
file_content_old = patch_content[index1 + 7:index2]
file_content_new = "#if 0" + file_content_old + "#else" + patch_content[index2 + 7:index3] + "#endif"
base.replaceInFile(file, file_content_old, file_content_new)
return
def run_as_bash(file, commands):
if base.is_file(file):
base.delete_file(file)
file_bash = codecs.open(file, "w", "utf-8")
file_bash.write("#!/bin/bash\n")
file_bash.write("\n".join(commands))
file_bash.close()
base.cmd("chmod", ["+x", file])
base.cmd(file)
return
if ("windows" == base.host_platform()):
print("Windows system not supported. Please use Linux or MacOS")
exit(0)
base.configure_common_apps()
base_dir = os.getcwd()
# fetch emsdk
if not base.is_dir("emsdk"):
base.print_info("Fetching emsdk...")
base.cmd("git", ["clone", "https://github.com/emscripten-core/emsdk.git"])
os.chdir(base_dir + "/emsdk")
base.cmd("./emsdk", ["install", "latest"])
base.cmd("./emsdk", ["activate", "latest"])
os.chdir(base_dir)
# fetch openssl
if not base.is_dir("openssl"):
base.print_info("Fetching openssl...")
base.cmd("git", ["clone", "--depth=1", "--branch", "OpenSSL_1_1_1f", "https://github.com/openssl/openssl.git"])
# correct for wasm builds
apply_patch("./openssl/crypto/rand/rand_lib.c", "./patches/openssl1.patch")
if not base.is_dir("xml"):
base.print_info("Copy xml...")
base.copy_dir("./../../../../xml", "./xml")
base.replaceInFile("./xml/libxml2/libxml.h", "xmlNop(void)", "xmlNop(void* context, char* buffer, int len)")
base.replaceInFile("./xml/libxml2/xmlIO.c", "xmlNop(void)", "xmlNop(void* context, char* buffer, int len)")
base.replaceInFile("./xml/src/xmllight_private.h", "#include \"../../common/", "#include \"../../../../../../common/")
base.replaceInFile("./xml/include/xmlutils.h", "#include \"../../common/", "#include \"../../../../../../common/")
# compile openssl
if not base.is_file(base_dir + "/openssl/libcrypto.a"):
base.print_info("Compile openssl...")
os.chdir(base_dir + "/openssl")
#run_as_bash("./compile_openssl.sh", ["./config no-shared no-asm no-ssl2 no-ssl3", "source ./../emsdk/emsdk_env.sh", "export CC=emcc", "export CXX=emcc", "make"])
run_as_bash("./compile_openssl.sh", ["source ./../emsdk/emsdk_env.sh", "emconfigure ./config no-shared no-asm no-threads", "sed -i 's|^CROSS_COMPILE.*$|CROSS_COMPILE=|g' Makefile", "emmake make build_generated libssl.a libcrypto.a"])
os.chdir(base_dir)
# compile wasm module with bindings
compiler_flags = ["-o openssl.js",
"-O3",
#"-fno-exceptions", because xml/src/xmldom.cpp:691:17
"-fno-rtti",
"-s WASM=1",
"-s ALLOW_MEMORY_GROWTH=1",
"-s FILESYSTEM=0",
"-s ENVIRONMENT='web'"]
#"-s LLD_REPORT_UNDEFINED"]
exported_functions = ["_malloc",
"_free",
"_XmlSignature_Malloc",
"_XmlSignature_Free",
"_XmlSignature_CreateCertificate",
"_XmlSignature_LoadCert",
"_XmlSignature_LoadKey",
"_XmlSignature_DestroyCertificate",
"_XmlSignature_CreateFile",
"_XmlSignature_DestroyFile",
"_XmlSignature_GetFileSize",
"_XmlSignature_GetFileRaw",
"_XmlSignature_Sign"]
# XML
compiler_flags.append("-DHAVE_VA_COPY -DLIBXML_READER_ENABLED -DLIBXML_PUSH_ENABLED -DLIBXML_HTML_ENABLED -DLIBXML_XPATH_ENABLED -DLIBXML_OUTPUT_ENABLED -DLIBXML_C14N_ENABLED -DLIBXML_SAX1_ENABLED -DLIBXML_TREE_ENABLED -DLIBXML_XPTR_ENABLED -DIN_LIBXML -DLIBXML_STATIC")
compiler_flags.append("-I./xml/libxml2/include -I./xml/libxml2/include/libxml -I./xml/build/qt")
input_xml_sources = ["./xml/build/qt/libxml2_all.c", "./xml/build/qt/libxml2_all2.c", "./xml/src/xmllight.cpp", "./xml/src/xmldom.cpp"]
# KERNEL
libKernel_src_parh = "../../../../common/"
input_kernel_sources = ["StringBuilder.cpp", "Base64.cpp", "Path.cpp", "File.cpp", "Directory.cpp"]
# ZIP
compiler_flags.append("-DBUILD_ZLIB_AS_SOURCES")
compiler_flags.append("-I../../../../../OfficeUtils/src/zlib-1.2.11/contrib/minizip -I../../../../../OfficeUtils/src/zlib-1.2.11")
libOfficeUtils_src_parh = "../../../../../OfficeUtils/src/"
input_officeutils_sources = ["OfficeUtils.cpp", "ZipBuffer.cpp", "ZipUtilsCP.cpp"]
libMinizip_src_parh = "../../../../../OfficeUtils/src/zlib-1.2.11/contrib/minizip/"
input_minizip_sources = ["ioapi.c", "miniunz.c", "minizip.c", "mztools.c", "unzip.c", "zip.c", "ioapibuf.c"]
libZlib_src_parh = "../../../../../OfficeUtils/src/zlib-1.2.11/"
input_zlib_sources = ["adler32.c", "crc32.c", "deflate.c", "infback.c", "inffast.c", "inflate.c", "inftrees.c", "trees.c", "zutil.c"]
# SIGN
libSign_src_parh = "../../../../xmlsec/src/src/"
input_sign_sources = ["XmlTransform.cpp", "XmlCertificate.cpp", "OOXMLSigner.cpp", "OOXMLVerifier.cpp", "XmlSigner_openssl.cpp"]
# OPENSSL
compiler_flags.append("-Iopenssl/include -Iopenssl -Iemsdk/node/14.15.5_64bit/include/node/openssl/archs/linux-x86_64/no-asm/include")
compiler_flags.append("-D__linux__ -D_LINUX")
# sources
sources = []
for item in input_xml_sources:
sources.append(item)
for item in input_kernel_sources:
sources.append(libKernel_src_parh + item)
for item in input_officeutils_sources:
sources.append(libOfficeUtils_src_parh + item)
for item in input_minizip_sources:
sources.append(libMinizip_src_parh + item)
for item in input_zlib_sources:
sources.append(libZlib_src_parh + item)
for item in input_sign_sources:
sources.append(libSign_src_parh + item)
sources.append("./openssl/libcrypto.a ./openssl/apps/openssl.c")
sources.append("../main.cpp")
# arguments
arguments = ""
for item in compiler_flags:
arguments += (item + " ")
arguments += "-s EXPORTED_FUNCTIONS=\"["
for item in exported_functions:
arguments += ("'" + item + "',")
arguments = arguments[:-1]
arguments += "]\" "
for item in sources:
arguments += (item + " ")
run_as_bash("./compile_module.sh", ["source ./emsdk/emsdk_env.sh", "emcc " + arguments])
# finalize
base.replaceInFile("./openssl.js", "__ATPOSTRUN__=[];", "__ATPOSTRUN__=[function(){self.onEngineInit();}];")
base.replaceInFile("./openssl.js", "__ATPOSTRUN__ = [];", "__ATPOSTRUN__=[function(){self.onEngineInit();}];")
base.replaceInFile("./openssl.js", "function getBinaryPromise()", "function getBinaryPromise2()")
openssl_js_content = base.readFile("./openssl.js")
engine_base_js_content = base.readFile("./engine.js")
desktop_fetch_content = base.readFile("./../../../../../Common/js/desktop_fetch.js")
string_utf8_content = base.readFile("./../../../../../Common/js/string_utf8.js")
engine_js_content = engine_base_js_content.replace("//desktop_fetch", desktop_fetch_content)
engine_js_content = engine_js_content.replace("//string_utf8", string_utf8_content)
engine_js_content = engine_js_content.replace("//module", openssl_js_content)
if not base.is_dir("./deploy"):
base.create_dir("./deploy")
# remove previous version
if base.is_file("./deploy/openssl.js"):
base.delete_file("./deploy/openssl.js")
if base.is_file("./deploy/openssl.wasm"):
base.delete_file("./deploy/openssl.wasm")
# write new version
base.writeFile("./deploy/openssl.js", engine_js_content)
base.copy_file("./index.html", "./deploy/index.html")
base.copy_file("./code.js", "./deploy/code.js")
base.copy_file("./openssl.wasm", "./deploy/openssl.wasm")
base.delete_file("./openssl.js")
base.delete_file("./openssl.wasm")

View File

@ -1,84 +0,0 @@
{
"name": "openssl",
"res_folder": "./deploy",
"wasm": true,
"asm": true,
"embed_mem_file": true,
"run_before": "before.py",
"run_after": "after.py",
"base_js_content": "./engine.js",
"compiler_flags": [
"-O3",
"-fno-rtti",
"-Wno-unused-command-line-argument",
"-s ALLOW_MEMORY_GROWTH=1",
"-s FILESYSTEM=0",
"-s ENVIRONMENT='web'"
],
"exported_functions": [
"_malloc",
"_free",
"_XmlSignature_Malloc",
"_XmlSignature_Free",
"_XmlSignature_CreateCertificate",
"_XmlSignature_LoadCert",
"_XmlSignature_LoadKey",
"_XmlSignature_DestroyCertificate",
"_XmlSignature_CreateFile",
"_XmlSignature_DestroyFile",
"_XmlSignature_GetFileSize",
"_XmlSignature_GetFileRaw",
"_XmlSignature_Sign"
],
"include_path": [
"./../3rdParty/openssl/include", "./../3rdParty/openssl",
"./../../../../../OfficeUtils/src/zlib-1.2.11/contrib/minizip", "./../../../../../OfficeUtils/src/zlib-1.2.11", "./../../../../../OfficeUtils/src",
"./../3rdParty/xml/libxml2/include", "./../3rdParty/xml/libxml2/include/libxml", "./../3rdParty/xml/build/qt",
"emsdk/node/14.15.5_64bit/include/node/openssl/archs/linux-x86_64/no-asm/include"
],
"define": [
"HAVE_VA_COPY", "LIBXML_READER_ENABLED", "LIBXML_PUSH_ENABLED", "LIBXML_HTML_ENABLED", "LIBXML_XPATH_ENABLED", "LIBXML_OUTPUT_ENABLED",
"LIBXML_C14N_ENABLED", "LIBXML_SAX1_ENABLED", "LIBXML_TREE_ENABLED", "LIBXML_XPTR_ENABLED", "IN_LIBXML", "LIBXML_STATIC",
"BUILD_ZLIB_AS_SOURCES",
"__linux__", "_LINUX"
],
"compile_files_array": [
{
"name": "x",
"folder": "./../3rdParty/xml/",
"files": ["build/qt/libxml2_all.c", "build/qt/libxml2_all2.c", "src/xmllight.cpp", "src/xmldom.cpp"]
},
{
"name": "k",
"folder": "../../../../common/",
"files": ["StringBuilder.cpp", "StringExt.cpp", "Base64.cpp", "Path.cpp", "File.cpp", "Directory.cpp"]
},
{
"name": "of",
"folder": "../../../../../OfficeUtils/src/",
"files": ["OfficeUtils.cpp", "ZipBuffer.cpp", "ZipUtilsCP.cpp", "zlib_addon.c"]
},
{
"name": "mz",
"folder": "../../../../../OfficeUtils/src/zlib-1.2.11/contrib/minizip/",
"files": ["ioapi.c", "miniunz.c", "minizip.c", "mztools.c", "unzip.c", "zip.c", "ioapibuf.c"]
},
{
"name": "z",
"folder": "../../../../../OfficeUtils/src/zlib-1.2.11/",
"files": ["adler32.c", "crc32.c", "deflate.c", "infback.c", "inffast.c", "inflate.c", "inftrees.c", "trees.c", "zutil.c"]
},
{
"name": "s",
"folder": "../../../../xmlsec/src/src/",
"files": ["XmlTransform.cpp", "CertificateCommon.cpp", "OOXMLSigner.cpp", "OOXMLVerifier.cpp"]
},
{
"name": "a",
"folder": "./",
"files": ["main.cpp"]
}
],
"sources": ["./../3rdParty/openssl/libcrypto.a"]
}

View File

@ -1,121 +0,0 @@
QT -= core gui
TARGET = wasm
TEMPLATE = app
CONFIG += console
CONFIG -= app_bundle
DEFINES += TEST_AS_EXECUTABLE
CORE_ROOT_DIR = $$PWD/../../../../..
PWD_ROOT_DIR = $$PWD
include($$CORE_ROOT_DIR/Common/base.pri)
DEFINES += KERNEL_NO_USE_DYNAMIC_LIBRARY
DEFINES += COMMON_OPENSSL_BUILDING_INTERNAL
ADD_DEPENDENCY(UnicodeConverter)
# XML
DEFINES += \
HAVE_VA_COPY \
LIBXML_READER_ENABLED \
LIBXML_PUSH_ENABLED \
LIBXML_HTML_ENABLED \
LIBXML_XPATH_ENABLED \
LIBXML_OUTPUT_ENABLED \
LIBXML_C14N_ENABLED \
LIBXML_SAX1_ENABLED \
LIBXML_TREE_ENABLED \
LIBXML_XPTR_ENABLED \
IN_LIBXML \
LIBXML_STATIC
INCLUDEPATH += \
$$CORE_ROOT_DIR/DesktopEditor/xml/libxml2/include \
$$CORE_ROOT_DIR/DesktopEditor/xml/libxml2/include/libxml \
$$CORE_ROOT_DIR/DesktopEditor/xml/build/qt
SOURCES += \
$$CORE_ROOT_DIR/DesktopEditor/xml/build/qt/libxml2_all.c \
$$CORE_ROOT_DIR/DesktopEditor/xml/build/qt/libxml2_all2.c \
$$CORE_ROOT_DIR/DesktopEditor/xml/src/xmllight.cpp \
$$CORE_ROOT_DIR/DesktopEditor/xml/src/xmldom.cpp
# KERNEL
SOURCES += \
$$CORE_ROOT_DIR/DesktopEditor/common/StringBuilder.cpp \
$$CORE_ROOT_DIR/DesktopEditor/common/StringExt.cpp \
$$CORE_ROOT_DIR/DesktopEditor/common/Base64.cpp \
$$CORE_ROOT_DIR/DesktopEditor/common/Path.cpp \
$$CORE_ROOT_DIR/DesktopEditor/common/File.cpp \
$$CORE_ROOT_DIR/DesktopEditor/common/Directory.cpp
# ZIP
DEFINES += BUILD_ZLIB_AS_SOURCES
INCLUDEPATH += \
$$CORE_ROOT_DIR/OfficeUtils/src/zlib-1.2.11/contrib/minizip \
$$CORE_ROOT_DIR/OfficeUtils/src/zlib-1.2.11 \
$$CORE_ROOT_DIR/OfficeUtils/src
SOURCES += \
$$CORE_ROOT_DIR/OfficeUtils/src/OfficeUtils.cpp \
$$CORE_ROOT_DIR/OfficeUtils/src/ZipBuffer.cpp \
$$CORE_ROOT_DIR/OfficeUtils/src/ZipUtilsCP.cpp \
$$CORE_ROOT_DIR/OfficeUtils/src/zlib_addon.c \
$$CORE_ROOT_DIR/OfficeUtils/src/zlib-1.2.11/contrib/minizip/ioapi.c \
$$CORE_ROOT_DIR/OfficeUtils/src/zlib-1.2.11/contrib/minizip/miniunz.c \
$$CORE_ROOT_DIR/OfficeUtils/src/zlib-1.2.11/contrib/minizip/minizip.c \
$$CORE_ROOT_DIR/OfficeUtils/src/zlib-1.2.11/contrib/minizip/mztools.c \
$$CORE_ROOT_DIR/OfficeUtils/src/zlib-1.2.11/contrib/minizip/unzip.c \
$$CORE_ROOT_DIR/OfficeUtils/src/zlib-1.2.11/contrib/minizip/zip.c \
$$CORE_ROOT_DIR/OfficeUtils/src/zlib-1.2.11/contrib/minizip/ioapibuf.c
core_windows:SOURCES += $$CORE_ROOT_DIR/OfficeUtils/src/zlib-1.2.11/contrib/minizip/iowin32.c
SOURCES += \
$$CORE_ROOT_DIR/OfficeUtils/src/zlib-1.2.11/adler32.c \
$$CORE_ROOT_DIR/OfficeUtils/src/zlib-1.2.11/compress.c \
$$CORE_ROOT_DIR/OfficeUtils/src/zlib-1.2.11/crc32.c \
$$CORE_ROOT_DIR/OfficeUtils/src/zlib-1.2.11/deflate.c \
$$CORE_ROOT_DIR/OfficeUtils/src/zlib-1.2.11/gzclose.c \
$$CORE_ROOT_DIR/OfficeUtils/src/zlib-1.2.11/gzlib.c \
$$CORE_ROOT_DIR/OfficeUtils/src/zlib-1.2.11/gzread.c \
$$CORE_ROOT_DIR/OfficeUtils/src/zlib-1.2.11/gzwrite.c \
$$CORE_ROOT_DIR/OfficeUtils/src/zlib-1.2.11/infback.c \
$$CORE_ROOT_DIR/OfficeUtils/src/zlib-1.2.11/inffast.c \
$$CORE_ROOT_DIR/OfficeUtils/src/zlib-1.2.11/inflate.c \
$$CORE_ROOT_DIR/OfficeUtils/src/zlib-1.2.11/inftrees.c \
$$CORE_ROOT_DIR/OfficeUtils/src/zlib-1.2.11/trees.c \
$$CORE_ROOT_DIR/OfficeUtils/src/zlib-1.2.11/uncompr.c \
$$CORE_ROOT_DIR/OfficeUtils/src/zlib-1.2.11/zutil.c
# SIGN
SOURCES += \
$$CORE_ROOT_DIR/DesktopEditor/xmlsec/src/src/XmlTransform.cpp \
$$CORE_ROOT_DIR/DesktopEditor/xmlsec/src/src/CertificateCommon.cpp \
$$CORE_ROOT_DIR/DesktopEditor/xmlsec/src/src/OOXMLSigner.cpp \
$$CORE_ROOT_DIR/DesktopEditor/xmlsec/src/src/OOXMLVerifier.cpp
core_windows {
LIBS += -lcrypt32
LIBS += -lcryptui
LIBS += -lAdvapi32
LIBS += -lws2_32
LIBS += -lUser32
LIBS += -lRpcrt4
LIBS += -lShell32
}
core_linux {
LIBS += -ldl
}
DEFINES += SUPPORT_OPENSSL
# OPENSSL
include($$CORE_ROOT_DIR/Common/3dParty/openssl/openssl.pri)
# WASM EXPORT
SOURCES += main.cpp

View File

@ -1,30 +0,0 @@
import sys
sys.path.append('../../../../../../build_tools/scripts')
import base
import os
base.configure_common_apps()
contentHeader = base.readFile("./deploy/engine.js")
headerLast = contentHeader.find("*/")
contentHeader = contentHeader[:headerLast+2]
base.replaceInFile("./deploy/engine.js", contentHeader, "")
base.replaceInFile("./deploy/engine_ie.js", contentHeader, "")
base.replaceInFile("./deploy/engine.js", "__ATPOSTRUN__=[];", "__ATPOSTRUN__=[function(){self.onEngineInit();}];")
base.replaceInFile("./deploy/engine.js", "__ATPOSTRUN__ = [];", "__ATPOSTRUN__=[function(){self.onEngineInit();}];")
base.replaceInFile("./deploy/engine.js", "function getBinaryPromise()", "function getBinaryPromise2()")
base64_js_content = base.readFile("./../../../../../../../sdkjs/common/stringserialize.js")
base64_js_content = base64_js_content.replace("(window);", "(self);")
base.replaceInFile("./deploy/engine.js", "&&window===this?this", "?window")
base.replaceInFile("./deploy/engine.js", "//base64", base64_js_content)
base.replaceInFile("./deploy/engine_ie.js", "__ATPOSTRUN__=[];", "__ATPOSTRUN__=[function(){self.onEngineInit();}];")
base.replaceInFile("./deploy/engine_ie.js", "__ATPOSTRUN__ = [];", "__ATPOSTRUN__=[function(){self.onEngineInit();}];")
base.replaceInFile("./deploy/engine_ie.js", "function getBinaryPromise()", "function getBinaryPromise2()")
base.replaceInFile("./deploy/engine_ie.js", "&&window===this?this", "?window")
base.replaceInFile("./deploy/engine_ie.js", "//base64", base64_js_content)

View File

@ -1,5 +0,0 @@
import sys
sys.path.append("../../../../../../build_tools/scripts")
import base
base.cmd_in_dir("./../3rdParty", "python", ["openssl.py"])

View File

@ -1,78 +0,0 @@
{
"name": "engine",
"res_folder": "./deploy",
"wasm": true,
"asm": true,
"run_before": "before.py",
"run_after": "after.py",
"base_js_content": "./hash_base.js",
"embed_mem_file": true,
"compiler_flags": [
"-O3",
"-fno-exceptions",
"-fno-rtti",
"-Wno-unused-command-line-argument",
"-s ALLOW_MEMORY_GROWTH=1",
"-s FILESYSTEM=0",
"-s ENVIRONMENT='worker'",
"-s TOTAL_STACK=1MB",
"-s TOTAL_MEMORY=2MB"
],
"exported_functions": [
"_malloc",
"_free",
"_hash",
"_hash2"
],
"include_path": [
"./", "./../3rdParty/openssl/include"
],
"define": [
"WIN32", "DNDEBUG", "OPENSSL_MD2_ENABLED"
],
"compile_files_array": [
{
"name": "a1",
"folder": "./../3rdParty/openssl/crypto/sha/",
"files": ["keccak1600.c", "sha1_one.c", "sha1dgst.c", "sha256.c", "sha512.c"]
},
{
"name": "a2",
"folder": "./../3rdParty/openssl/crypto/md2/",
"files": ["md2_dgst.c", "md2_one.c"]
},
{
"name": "a3",
"folder": "./../3rdParty/openssl/crypto/md4/",
"files": ["md4_dgst.c", "md4_one.c"]
},
{
"name": "a4",
"folder": "./../3rdParty/openssl/crypto/md5/",
"files": ["md5_dgst.c", "md5_one.c"]
},
{
"name": "a5",
"folder": "./../3rdParty/openssl/crypto/ripemd/",
"files": ["rmd_dgst.c", "rmd_one.c"]
},
{
"name": "a6",
"folder": "./../3rdParty/openssl/crypto/whrlpool/",
"files": ["wp_block.c", "wp_dgst.c"]
},
{
"name": "a7",
"folder": "./../3rdParty/openssl/crypto/",
"files": ["mem_clr.c"]
},
{
"name": "m",
"folder": "./",
"files": ["main.cpp"]
}
]
}

View File

@ -1,64 +0,0 @@
QT -= core gui
TARGET = wasm
TEMPLATE = app
CONFIG += console
CONFIG -= app_bundle
DEFINES += \
TEST_AS_EXECUTABLE \
OPENSSL_MD2_ENABLED
OPENSSL_DIR = $$PWD/../3rdParty/openssl
INCLUDEPATH += \
$$OPENSSL_DIR/include \
$$PWD
SOURCES += \
$$OPENSSL_DIR/crypto/sha/keccak1600.c \
$$OPENSSL_DIR/crypto/sha/sha1_one.c \
$$OPENSSL_DIR/crypto/sha/sha1dgst.c \
$$OPENSSL_DIR/crypto/sha/sha256.c \
$$OPENSSL_DIR/crypto/sha/sha512.c
SOURCES += \
$$OPENSSL_DIR/crypto/md2/md2_dgst.c \
$$OPENSSL_DIR/crypto/md2/md2_one.c
SOURCES += \
$$OPENSSL_DIR/crypto/md4/md4_dgst.c \
$$OPENSSL_DIR/crypto/md4/md4_one.c
SOURCES += \
$$OPENSSL_DIR/crypto/md5/md5_dgst.c \
$$OPENSSL_DIR/crypto/md5/md5_one.c
SOURCES += \
$$OPENSSL_DIR/crypto/ripemd/rmd_dgst.c \
$$OPENSSL_DIR/crypto/ripemd/rmd_one.c
SOURCES += \
$$OPENSSL_DIR/crypto/whrlpool/wp_block.c \
$$OPENSSL_DIR/crypto/whrlpool/wp_dgst.c
SOURCES += \
$$OPENSSL_DIR/crypto/mem_clr.c
#CONFIG += openssl_sha3
openssl_sha3 {
DEFINES += OOXML_SUPPORT_SHA3_512
SOURCES += \
$$OPENSSL_DIR/crypto/evp/digest.c \
$$OPENSSL_DIR/crypto/mem.c
INCLUDEPATH += $$OPENSSL_DIR/include
INCLUDEPATH += $$OPENSSL_DIR/include/openssl
}
# WASM EXPORT
SOURCES += main.cpp

View File

@ -1,222 +0,0 @@
/*
* (c) Copyright Ascensio System SIA 2010-2019
*
* This program is a free software product. You can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License (AGPL)
* version 3 as published by the Free Software Foundation. In accordance with
* Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
* that Ascensio System SIA expressly excludes the warranty of non-infringement
* of any third-party rights.
*
* This program is distributed WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For
* details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
*
* You can contact Ascensio System SIA at 20A-12 Ernesta Birznieka-Upisha
* street, Riga, Latvia, EU, LV-1050.
*
* The interactive user interfaces in modified source and object code versions
* of the Program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU AGPL version 3.
*
* Pursuant to Section 7(b) of the License you must retain the original Product
* logo when distributing the program. Pursuant to Section 7(e) we decline to
* grant you any rights under trademark law for use of our trademarks.
*
* All the Product's GUI elements, including illustrations and icon sets, as
* well as technical writing content are licensed under the terms of the
* Creative Commons Attribution-ShareAlike 4.0 International. See the License
* terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
*
*/
//base64
(function(window, undefined) {
window.messageData = null;
window.messagePort = null;
function onMessageEvent(data, port)
{
if (data.type == "hash")
{
window.messageData = data.value;
window.messagePort = port;
if (!window.engineInit)
return;
checkMessage();
}
}
window.onconnect = function(e)
{
var port = e.ports[0];
port.onmessage = function(e) {
onMessageEvent(e.data, port);
}
};
window.onmessage = function(e)
{
onMessageEvent(e.data);
};
window.engineInit = false;
window.onEngineInit = function()
{
window.engineInit = true;
if (window.messageData)
checkMessage();
};
function checkMessage()
{
var data = window.messageData;
var res = [];
for (var i = 0, len = data.length; i < len; i++)
{
res.push(AscCommon.Hash.hashOffice(data[i].password, data[i].salt, data[i].spinCount, data[i].alg).base64());
}
var sender = window.messagePort || window;
sender.postMessage({ hashValue : res });
}
//desktop_fetch
//polyfill
//string_utf8
//module
var HashAlgs = {
MD2 : 0,
MD4 : 1,
MD5 : 2,
RMD160 : 3,
SHA1 : 4,
SHA256 : 5,
SHA384 : 6,
SHA512 : 7,
WHIRLPOOL : 8
};
var HashSizes = [
16,
16,
16,
20,
20,
32,
48,
64,
64
];
window["AscCommon"] = window.AscCommon = (window["AscCommon"] || {});
window.AscCommon["Hash"] = window.AscCommon.Hash = {};
window.AscCommon.Hash["HashAlgs"] = window.AscCommon.Hash.HashAlgs = HashAlgs;
window.AscCommon.Hash["HashSizes"] = window.AscCommon.Hash.HashSizes = HashSizes;
function HashObj() { this.buf; }
HashObj.prototype["buffer"] = HashObj.prototype.buffer = function() { return this.buf; };
HashObj.prototype["base64"] = HashObj.prototype.base64 = function() { return window.AscCommon.Base64.encode(this.buf); };
HashObj.prototype["hex"] = HashObj.prototype.hex = function() { return window.AscCommon.Hex.encode(this.buf); };
window.AscCommon.Hash["hash"] = window.AscCommon.Hash.hash = function(data, alg)
{
if (typeof alg === "string")
{
switch (alg)
{
case "md2" : alg = HashAlgs.MD2; break;
case "md4" : alg = HashAlgs.MD4; break;
case "md5" : alg = HashAlgs.MD5; break;
case "rmd160" : alg = HashAlgs.RMD160; break;
case "sha1" : alg = HashAlgs.SHA1; break;
case "sha256" : alg = HashAlgs.SHA256; break;
case "sha384" : alg = HashAlgs.SHA384; break;
case "sha512" : alg = HashAlgs.SHA512; break;
case "whirlpool" : alg = HashAlgs.WHIRLPOOL; break;
default:
alg = HashAlgs.SHA256;
}
}
var arrayData = null;
if (typeof data === "string")
arrayData = data.toUtf8(true);
else
arrayData = data;
var dataPointer = Module["_malloc"](arrayData.length);
Module["HEAPU8"].set(arrayData, dataPointer);
var resultPointer = Module["_hash"](dataPointer, arrayData.length, alg);
Module["_free"](dataPointer);
var result = new HashObj();
if (0 != resultPointer)
{
var tmp = new Uint8Array(Module["HEAPU8"].buffer, resultPointer, HashSizes[alg]);
result.buf = new Uint8Array(tmp.length);
result.buf.set(tmp, 0);
Module["_free"](resultPointer);
}
else
{
result.buf = [];
}
return result;
};
window.AscCommon.Hash["hashOffice"] = window.AscCommon.Hash.hash = function(password, salt, spinCount, alg)
{
if (typeof alg === "string")
{
switch (alg)
{
case "md2" : alg = HashAlgs.MD2; break;
case "md4" : alg = HashAlgs.MD4; break;
case "md5" : alg = HashAlgs.MD5; break;
case "rmd160" : alg = HashAlgs.RMD160; break;
case "sha1" : alg = HashAlgs.SHA1; break;
case "sha256" : alg = HashAlgs.SHA256; break;
case "sha384" : alg = HashAlgs.SHA384; break;
case "sha512" : alg = HashAlgs.SHA512; break;
case "whirlpool" : alg = HashAlgs.WHIRLPOOL; break;
default:
alg = HashAlgs.SHA256;
}
}
var passwordData = password.toUtf8();
var passwordPointer = Module["_malloc"](passwordData.length);
Module["HEAPU8"].set(passwordData, passwordPointer);
var saltData = salt.toUtf8();
var saltPointer = Module["_malloc"](saltData.length);
Module["HEAPU8"].set(saltData, saltPointer);
var resultPointer = Module["_hash2"](passwordPointer, saltPointer, spinCount, alg);
Module["_free"](passwordPointer);
Module["_free"](saltPointer);
var result = new HashObj();
if (0 != resultPointer)
{
var tmp = new Uint8Array(Module["HEAPU8"].buffer, resultPointer, HashSizes[alg]);
result.buf = new Uint8Array(tmp.length);
result.buf.set(tmp, 0);
Module["_free"](resultPointer);
}
else
{
result.buf = [];
}
return result;
};
})(self, undefined);

View File

@ -1,150 +0,0 @@
#include <cstddef>
#ifdef _WIN32
#define WASM_EXPORT __declspec(dllexport)
#else
#define WASM_EXPORT __attribute__((visibility("default")))
#endif
// BASE64
namespace NSBase64
{
int DecodeBase64Char(unsigned int ch)
{
// returns -1 if the character is invalid
// or should be skipped
// otherwise, returns the 6-bit code for the character
// from the encoding table
if (ch >= 'A' && ch <= 'Z')
return ch - 'A' + 0; // 0 range starts at 'A'
if (ch >= 'a' && ch <= 'z')
return ch - 'a' + 26; // 26 range starts at 'a'
if (ch >= '0' && ch <= '9')
return ch - '0' + 52; // 52 range starts at '0'
if (ch == '+')
return 62;
if (ch == '/')
return 63;
return -1;
}
bool Base64Decode(const char* szSrc, int nSrcLen, unsigned char *pbDest, int *pnDestLen)
{
// walk the source buffer
// each four character sequence is converted to 3 bytes
// CRLFs and =, and any characters not in the encoding table
// are skiped
if (szSrc == NULL || pnDestLen == NULL)
return false;
const char* szSrcEnd = szSrc + nSrcLen;
size_t nWritten = 0;
bool bOverflow = (pbDest == NULL) ? true : false;
while (szSrc < szSrcEnd &&(*szSrc) != 0)
{
unsigned int dwCurr = 0;
int i;
int nBits = 0;
for (i=0; i<4; i++)
{
if (szSrc >= szSrcEnd)
break;
int nCh = DecodeBase64Char(*szSrc);
szSrc++;
if (nCh == -1)
{
// skip this char
i--;
continue;
}
dwCurr <<= 6;
dwCurr |= nCh;
nBits += 6;
}
if(!bOverflow && nWritten + (nBits/8) > (*pnDestLen))
bOverflow = true;
// dwCurr has the 3 bytes to write to the output buffer
// left to right
dwCurr <<= 24-nBits;
for (i=0; i<nBits/8; i++)
{
if(!bOverflow)
{
*pbDest = (unsigned char) ((dwCurr & 0x00ff0000) >> 16);
pbDest++;
}
dwCurr <<= 8;
nWritten++;
}
}
*pnDestLen = nWritten;
if(bOverflow)
{
return false;
}
return true;
}
}
#define OWN_BASE_64
#define DOCTRENDERER_NO_USE_DYNAMIC_LIBRARY
#include "../../../../doctrenderer/hash.cpp"
#ifdef __cplusplus
extern "C" {
#endif
WASM_EXPORT unsigned char* hash(const unsigned char* data, int size, int alg)
{
return CHash(malloc).hash(data, size, alg);
}
WASM_EXPORT unsigned char* hash2(const char* password, const char* salt, int spinCount, int alg)
{
return CHash(malloc).hash2(password, salt, spinCount, alg);
}
#ifdef __cplusplus
}
#endif
#ifdef TEST_AS_EXECUTABLE
#include <string>
#include <iostream>
int main()
{
std::string data = "test";
CHash::HashAlgs alg1 = CHash::haMD2;
unsigned char* result1 = hash((unsigned char*)data.c_str(), (int)data.length(), alg1);
for (int i = 0; i < CHash::getDigestLength(alg1); i++)
{
std::cout << std::hex << static_cast<unsigned>(result1[i]);
}
std::cout << std::endl;
std::string password = "oleg";
std::string salt = "yrGivlyCImiWnryRee1OJw==";
CHash::HashAlgs alg2 = CHash::haSHA512;
unsigned char* result2 = hash2((char*)password.c_str(), (char*)salt.c_str(), 100000, alg2);
for (int i = 0; i < CHash::getDigestLength(alg2); i++)
{
std::cout << std::hex << static_cast<unsigned>(result2[i]);
}
std::cout << std::endl;
return 0;
}
#endif

View File

@ -1,201 +0,0 @@
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
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
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.

View File

@ -1,3 +0,0 @@
## Overview
Keychain plugin

View File

@ -1,86 +0,0 @@
{
"name": "Keychain",
"guid": "asc.{CC4E881A-FBAF-4ED0-A646-18592D1A5723}",
"version": "1.0.0",
"variations": [
{
"description": "Keychain",
"url": "index.html",
"icons": [ "resources/light/icon.png", "resources/light/icon@2x.png" ],
"icons2": [
{
"style" : "light",
"100%": {
"normal": "resources/light/icon.png"
},
"125%": {
"normal": "resources/light/icon@1.25x.png"
},
"150%": {
"normal": "resources/light/icon@1.5x.png"
},
"175%": {
"normal": "resources/light/icon@1.75x.png"
},
"200%": {
"normal": "resources/light/icon@2x.png"
}
},
{
"style" : "dark",
"100%": {
"normal": "resources/dark/icon.png"
},
"125%": {
"normal": "resources/dark/icon@1.25x.png"
},
"150%": {
"normal": "resources/dark/icon@1.5x.png"
},
"175%": {
"normal": "resources/dark/icon@1.75x.png"
},
"200%": {
"normal": "resources/dark/icon@2x.png"
}
}
],
"isViewer": false,
"isDisplayedInViewer": false,
"EditorsSupport": [ "word", "cell", "slide" ],
"isVisual": true,
"isModal": true,
"isInsideMode": false,
"initDataType": "sign",
"initData": "",
"isUpdateOleOnResize": false,
"buttons": [
{
"text": "Ok",
"primary": true
},
{
"text": "Cancel",
"primary": false,
"isViewer": false,
"textLocale": {
"ru": "Отмена",
"fr": "Annuler",
"es": "Cancelar",
"de": "Abbrechen"
}
}
],
"size": [ 500, 110 ]
}
]
}

View File

@ -1,133 +0,0 @@
<!--
(c) Copyright Ascensio System SIA 2020
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.
-->
<!DOCTYPE html>
<html style="height:100%;">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>keychain</title>
<script type="text/javascript" src="https://onlyoffice.github.io/sdkjs-plugins/v1/plugins.js"></script>
<script type="text/javascript" src="https://onlyoffice.github.io/sdkjs-plugins/v1/plugins-ui.js"></script>
<link rel="stylesheet" href="https://onlyoffice.github.io/sdkjs-plugins/v1/plugins.css">
<script type="text/javascript" src="scripts/code.js"></script>
<style>
.input_error {
display: none;
float: left;
position: relative;
}
.input_error:before {
content: '';
position: absolute;
right: 3px;
top: 3px;
width: 16px;
height: 16px;
background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAYdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuNWWFMmUAAACvSURBVDhPrZNRDoIwEER7COA6HgJPpAnHM4oXQdFE/VDfNrsfpQvGhkneT2dmky40rK77pq6ggx4eyhF2UGnMF4EWBvjMcIFW46nEgLcGl5BMOoSDGmR6EjZNz0GyjdbjALlfFjR5HnRajwNkSVnI5HnQaz0OkE1nIZPnwVPrxQNGrc9f4Qcnra+zxAbKP6OIg/IfyYSxhasGPcTzyyYC9pjO8IIbHGAPy4/pf4XwBSVejZ5wzd0zAAAAAElFTkSuQmCC);
}
.tab_mode {
position: absolute;
top: 0px;
left: 0px;
width: 33%;
height: 100%;
margin: 0px;
padding: 10px;
text-align: center;
box-sizing: border-box;
cursor: pointer;
opacity:0.8;
}
.tab_mode:hover {
opacity: 1;
}
.tab_mode_select {
opacity: 1;
}
.tab_separator {
position: absolute;
top:5px;
bottom:10px;
width:1px;
padding:0;
margin:0;
background:black;
box-sizing: border-box;
display: none;
}
.tab_select {
position: absolute;
top:27px;
width:20%;
height:2px;
left:0px;
padding:0;
margin:0;
background:black;
box-sizing: border-box;
transform-origin: 0 0;
transition: transform .25s;
}
</style>
</head>
<body style="-ms-touch-action: none;-moz-user-select:none;-khtml-user-select:none;user-select:none;width:100%;height:100%;margin:0;padding:0;overflow:hidden;box-sizing:border-box;">
<div id="id_header" style="position:absolute;left:0;top:0;width:100%;height:40px;margin:0px;padding:0px;">
<div id="id_mode_sign" class="tab_mode defaultlable" style="left:0px;">
<div id="id_text_sign">Signerergergwerg</div>
</div>
<div class="tab_separator" style="left:33%;"></div>
<div id="id_mode_generate" class="tab_mode defaultlable" style="left:33%;">
<div id="id_text_generate">Generate</div>
</div>
<div class="tab_separator" style="left:66%;"></div>
<div id="id_mode_change" class="tab_mode defaultlable" style="left:66%;">
<div id="id_text_change">Change Password</div>
</div>
<div class="tab_select" id="id_tab_select"></div>
</div>
<div id="id_old_password" style="position:absolute;left:15px;top:45px;right:15px;height:20px;margin:0;padding:0;" class="defaultlable">Password</div>
<div style="position:absolute;left:15px;top:65px;right:15px;height:40px;margin:0;padding:0;">
<div style="position:absolute;left:0px;top:0px;right:0px;height:100%;margin:0;padding:0;">
<input type="text" class="form-control" style="left:0px;top:0px;width:100%;" id="old_password_value" autofocus="autofocus" autocomplete="off">
<div id="old_input_error_id" class="input_error" style="position:absolute; top:0px; right:0px; width: 0px; height: 16px; display: none;"></div>
</div>
</div>
<div id="id_new_password" style="position:absolute;left:15px;top:95px;right:15px;height:20px;margin:0;padding:0;display:none;" class="defaultlable">New Password</div>
<div id="id_new_password_div" style="position:absolute;left:15px;top:115px;right:15px;height:40px;margin:0;padding:0;display:none;">
<div style="position:absolute;left:0px;top:0px;right:0px;height:100%;margin:0;padding:0;">
<input type="text" class="form-control" style="left:0px;top:0px;width:100%;" id="new_password_value" autofocus="autofocus" autocomplete="off">
<div id="new_input_error_id" class="input_error" style="position:absolute; top:0px; right:0px; width: 0px; height: 16px; display: none;"></div>
</div>
</div>
</body>
</html>

View File

@ -1,11 +0,0 @@
import sys;
sys.path.append("../../../../../../../build_tools/scripts");
import base;
base.replaceInFile("./deploy/engine.js", "__ATPOSTRUN__=[];", "__ATPOSTRUN__=[function(){window.cryptoJS.onLoad();}];");
base.replaceInFile("./deploy/engine.js", "__ATPOSTRUN__ = [];", "__ATPOSTRUN__=[function(){window.cryptoJS.onLoad();}];");
base.replaceInFile("./deploy/engine.js", "function getBinaryPromise()", "function getBinaryPromise2()");
base.replaceInFile("./deploy/engine_ie.js", "__ATPOSTRUN__=[];", "__ATPOSTRUN__=[function(){window.cryptoJS.onLoad();}];");
base.replaceInFile("./deploy/engine_ie.js", "__ATPOSTRUN__ = [];", "__ATPOSTRUN__=[function(){window.cryptoJS.onLoad();}];");
base.replaceInFile("./deploy/engine_ie.js", "function getBinaryPromise()", "function getBinaryPromise2()");

View File

@ -1,5 +0,0 @@
import sys
sys.path.append("../../../../../../../build_tools/scripts")
import base
base.cmd_in_dir("./../../3rdParty", "python", ["openssl.py"])

View File

@ -1,18 +0,0 @@
window.onload = function()
{
let url = "./deploy/engine";
let useWasm = false;
let webAsmObj = window["WebAssembly"];
if (typeof webAsmObj === "object" && typeof webAsmObj["Memory"] === "function")
{
if ((typeof webAsmObj["instantiateStreaming"] === "function") || (typeof webAsmObj["instantiate"] === "function"))
useWasm = true;
}
url += (useWasm ? ".js" : "_ie.js");
let script = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
document.head.appendChild(script);
};

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -1,53 +0,0 @@
{
"name": "engine",
"res_folder": "./deploy",
"wasm": true,
"asm": true,
"embed_mem_file": true,
"run_before": "before.py",
"run_after": "after.py",
"base_js_content": "./engine_base.js",
"compiler_flags": [
"-O3",
"-Wno-unused-command-line-argument",
"-s ALLOW_MEMORY_GROWTH=1",
"-s FILESYSTEM=0",
"-s ENVIRONMENT='web'",
"-s ASSERTIONS",
"-s LLD_REPORT_UNDEFINED"
],
"exported_functions": [
"_malloc",
"_free",
"_Crypto_Malloc",
"_Crypto_Free",
"_Crypto_CreateKeys",
"_Crypto_Sign",
"_Crypto_ChangePassword"
],
"include_path": [
"./../../3rdParty/openssl/include", "./../../3rdParty/openssl", "emsdk/node/14.15.5_64bit/include/node/openssl/archs/linux-x86_64/no-asm/include"
],
"define": [
"__linux__", "_LINUX", "DISABLE_XMLSEC"
],
"compile_files_array": [
{
"name": "a",
"folder": "../../../../../common/",
"files": ["Base64.cpp", "File.cpp"]
},
{
"name": "b",
"folder": "../../../../../../Common/3dParty/openssl/common/",
"files": ["common_openssl.cpp"]
},
{
"name": "c",
"folder": "./",
"files": ["main.cpp"]
}
],
"sources": ["./../../3rdParty/openssl/libcrypto.a"]
}

View File

@ -1,209 +0,0 @@
(function(window, undefined){
//desktop_fetch
//polyfill
//string_utf8
function toBase64(buf)
{
if(typeof buf === "string")
{
let old = buf;
buf = [];
for (let i = 0, len = old.length; i < len; i++)
buf.push(old.charCodeAt(i));
}
const chars = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
const chars_map = [
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, -1, -1, -1, -1, -1, -1,
-1, 9, 10, 11, 12, 13, 14, 15, 16, -1, 17, 18, 19, 20, 21, -1,
22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, -1, -1, -1, -1, -1,
-1, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, -1, 44, 45, 46,
47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
];
let result = [];
for (let i = 0, len = buf.length; i < len; i++)
{
let carry = buf[i];
for (let j = 0; j < result.length; ++j)
{
const x = (chars_map[result[j]] << 8) + carry;
result[j] = chars.charCodeAt(x % 58);
carry = (x / 58) >> 0;
}
while (carry)
{
result.push(chars.charCodeAt(carry % 58));
carry = (carry / 58) >> 0;
}
}
let char1 = "1".charCodeAt(0);
for (let i = 0, len = buf.length; i < len; i++)
{
if (buf[i])
break;
else
result.push(char1);
}
result.reverse();
return String.fromCharCode.apply(null, result);
}
function random(length)
{
let byteArray = new Uint8Array(length);
let engine = window.crypto || window.msCrypto;
if (engine)
engine.getRandomValues(byteArray);
else
{
for (let i = 0; i < length; i++)
byteArray[i] = (Math.random() * 256) >> 0;
}
return byteArray;
}
function CryptoJS()
{
this.isModuleInit = false;
};
CryptoJS.prototype.onLoad = function()
{
this.isModuleInit = true;
};
CryptoJS.prototype.generateKeys = function(password, salt)
{
if (!this.isModuleInit)
return null;
if (!salt)
salt = toBase64(random(32));
let algPtr = "ed25519".toUtf8Pointer();
let passwordPtr = password.toUtf8Pointer();
let saltPtr = salt.toUtf8Pointer();
let keys = Module["_Crypto_CreateKeys"](algPtr.ptr, passwordPtr.ptr, saltPtr.ptr);
algPtr.free();
passwordPtr.free();
saltPtr.free();
if (keys === 0)
return null;
let heap = Module["HEAP8"];
let currentStart = keys;
let currentEnd = currentStart;
while (heap[currentEnd] != 0)
currentEnd++;
let publicKey = "".fromUtf8(heap, currentStart, currentEnd - currentStart);
currentStart = currentEnd + 1;
currentEnd = currentStart;
while (heap[currentEnd] != 0)
currentEnd++;
let privateKey = "".fromUtf8(heap, currentStart, currentEnd - currentStart);
Module["_Crypto_Free"](keys);
return {
"salt" : salt,
"privateKey" : privateKey,
"publicKey" : publicKey
};
};
CryptoJS.prototype.sign = function(privateKey, password, salt, xml)
{
if (!this.isModuleInit)
return null;
let privateKeyPtr = privateKey.toUtf8Pointer();
let passwordPtr = password.toUtf8Pointer();
let saltPtr = salt.toUtf8Pointer();
let xmlPtr = xml.toUtf8Pointer();
let signData = Module["_Crypto_Sign"](privateKeyPtr.ptr, passwordPtr.ptr, saltPtr.ptr,
xmlPtr.ptr, xmlPtr.length);
privateKeyPtr.free();
passwordPtr.free();
saltPtr.free();
xmlPtr.free();
if (signData === 0)
return null;
let heap = Module["HEAP8"];
let currentStart = signData;
let currentEnd = currentStart;
while (heap[currentEnd] != 0)
currentEnd++;
let signString = "".fromUtf8(heap, currentStart, currentEnd - currentStart);
Module["_Crypto_Free"](signData);
return signString;
};
CryptoJS.prototype.changePassword = function(privateKey, passwordOld, passwordNew, salt)
{
if (!this.isModuleInit)
return null;
let privateKeyPtr = privateKey.toUtf8Pointer();
let passwordOldPtr = passwordOld.toUtf8Pointer();
let passwordNewPtr = passwordNew.toUtf8Pointer();
let saltPtr = salt.toUtf8Pointer();
let privateKeyEnc = Module["_Crypto_ChangePassword"](privateKeyPtr.ptr,
passwordOldPtr.ptr, passwordNewPtr.ptr, saltPtr.ptr);
privateKeyPtr.free();
passwordOldPtr.free();
passwordNewPtr.free();
saltPtr.free();
if (privateKeyEnc === 0)
return null;
let heap = Module["HEAP8"];
let currentStart = privateKeyEnc;
let currentEnd = currentStart;
while (heap[currentEnd] != 0)
currentEnd++;
let privateKeyString = "".fromUtf8(heap, currentStart, currentEnd - currentStart);
Module["_Crypto_Free"](privateKeyEnc);
return privateKeyString;
};
window.cryptoJS = new CryptoJS();
//module
})(window, undefined);

View File

@ -1,10 +0,0 @@
<!doctype html>
<html style="width:100%;height:100%;margin:0;padding:0;">
<head>
<title>ONLYOFFICE Documents</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=IE8">
<script src="./code.js"></script>
</head>
<body></body>
</html>

View File

@ -1,380 +0,0 @@
#include "../../../../../common/File.h"
#include "../../../../../../Common/3dParty/openssl/common/common_openssl.h"
#ifndef DISABLE_XMLSEC
#include "../../../include/Certificate.h"
#include "../../../include/CertificateCommon.h"
#endif
#ifdef _WIN32
#define WASM_EXPORT __declspec(dllexport)
#else
#define WASM_EXPORT __attribute__((visibility("default")))
#endif
namespace NSInternal
{
int CheckEncryptedVersion(const std::string& input, int& offset)
{
offset = 0;
// VER%NUMBER%; version from 100 to 999
if (input.length() > 7)
{
const char* input_ptr = input.c_str();
if (input_ptr[0] == 'V' && input_ptr[1] == 'E' && input_ptr[2] == 'R')
{
input_ptr += 3;
int nVersion = 0;
for (int i = 0; i < 4; ++i)
{
if (*input_ptr == ';')
{
offset = 3 + i + 1;
return nVersion;
}
nVersion *= 10;
nVersion += (*input_ptr - '0');
++input_ptr;
}
return nVersion;
}
}
return 1;
}
std::string DecodePrivateKey(const std::string& sPrivateKeyEnc, const std::string& sPassword, const std::string& sSalt)
{
int nHeaderLen = 0;
int nVersion = CheckEncryptedVersion(sPrivateKeyEnc, nHeaderLen);
std::string sPrivateKey;
bool bIsSuccess = false;
if (nVersion == 2)
bIsSuccess = NSOpenSSL::AES_Decrypt_desktop_GCM(sPassword, sPrivateKeyEnc, sPrivateKey, sSalt, nHeaderLen);
else
bIsSuccess = NSOpenSSL::AES_Decrypt_desktop(sPassword, sPrivateKeyEnc, sPrivateKey, sSalt);
if (!bIsSuccess)
return "";
return sPrivateKey;
}
}
#ifdef __cplusplus
extern "C" {
#endif
// Memory
WASM_EXPORT void* Crypto_Malloc(unsigned int size)
{
return ::malloc(size);
}
WASM_EXPORT void Crypto_Free(void* p)
{
if (p) ::free(p);
}
#ifndef DISABLE_XMLSEC
class CMemoryFile
{
public:
unsigned int Length;
BYTE* Data;
public:
CMemoryFile(BYTE* data = NULL, unsigned int len = 0) { Length = len; Data = data; }
~CMemoryFile() { if (Data) delete [] Data; }
};
class CCertificate
{
public:
ICertificate* m_pCert;
private:
unsigned char* m_key;
unsigned int m_keyLen;
std::string m_keyPass;
unsigned char* m_cert;
unsigned int m_certLen;
std::string m_certPass;
public:
CCertificate()
{
m_pCert = NULL;
}
~CCertificate()
{
delete m_pCert;
}
public:
int LoadCert(unsigned char* data, unsigned int len, char* pass)
{
m_cert = NULL; m_certLen = 0; m_certPass = "";
int nRes = NSOpenSSL::LoadCertRaw(data, len, (NULL != pass) ? std::string(pass) : "");
if (OPEN_SSL_WARNING_ALL_OK == nRes || OPEN_SSL_WARNING_OK == nRes)
{
m_cert = data;
m_certLen = len;
m_certPass = (NULL != pass) ? std::string(pass) : "";
}
if (OPEN_SSL_WARNING_ALL_OK == nRes)
{
m_key = m_cert;
m_keyLen = m_certLen;
m_keyPass = m_certPass;
}
return nRes;
}
int LoadKey(unsigned char* data, unsigned int len, char* pass)
{
m_key = NULL; m_keyLen = 0; m_keyPass = "";
int nRes = NSOpenSSL::LoadKeyRaw(data, len, (NULL != pass) ? std::string(pass) : "");
if (OPEN_SSL_WARNING_ALL_OK == nRes || OPEN_SSL_WARNING_OK == nRes)
{
m_key = data;
m_keyLen = len;
m_keyPass = (NULL != pass) ? std::string(pass) : "";
}
if (OPEN_SSL_WARNING_ALL_OK == nRes)
{
m_cert = m_key;
m_certLen = m_keyLen;
m_certPass = m_keyPass;
}
return nRes;
}
void Load()
{
m_pCert = NSCertificate::FromFilesRaw(m_key, m_keyLen, m_keyPass, m_cert, m_certLen, m_certPass);
}
ICertificate* GetCertificate()
{
return m_pCert;
}
};
// X509/RSA
WASM_EXPORT void* Crypto_CreateCertificate()
{
return new CCertificate();
}
WASM_EXPORT int Crypto_LoadCert(void* cert, unsigned char* data, unsigned int len, char* pass)
{
CCertificate* pCert = (CCertificate*)cert;
return pCert->LoadCert(data, len, pass);
}
WASM_EXPORT int Crypto_LoadKey(void* cert, unsigned char* data, unsigned int len, char* pass)
{
CCertificate* pCert = (CCertificate*)cert;
return pCert->LoadKey(data, len, pass);
}
WASM_EXPORT void Crypto_DestroyCertificate(void* cert)
{
CCertificate* pCert = (CCertificate*)cert;
delete pCert;
}
#endif
// methods for oform signatures
// create keys, encrypt private key with password, result - two base64 strings
WASM_EXPORT char* Crypto_CreateKeys(const char* alg, const char* password, const char* salt)
{
std::string publicKey;
std::string privateKey;
if (!NSOpenSSL::GenerateKeysByAlgs(alg, publicKey, privateKey))
return NULL;
std::string privateKeyEnc;
NSOpenSSL::AES_Encrypt_desktop_GCM(password, privateKey, privateKeyEnc, salt);
char* pDataPublicBase64 = NULL;
int nDataPublicBase64Len = 0;
NSFile::CBase64Converter::Encode((BYTE*)publicKey.c_str(), (int)publicKey.length(), pDataPublicBase64, nDataPublicBase64Len, NSBase64::B64_BASE64_FLAG_NOCRLF);
publicKey = std::string(pDataPublicBase64, (size_t)nDataPublicBase64Len);
RELEASEARRAYOBJECTS(pDataPublicBase64);
size_t public_len = publicKey.length();
size_t private_len = privateKeyEnc.length();
char* result = (char*)Crypto_Malloc((unsigned int)(public_len + private_len + 2));
memcpy(result, publicKey.c_str(), public_len);
result[public_len] = '\0';
memcpy(result + public_len + 1, privateKeyEnc.c_str(), private_len);
result[public_len + private_len + 1] = '\0';
return result;
}
WASM_EXPORT char* Crypto_Sign(const char* privateKeyEnc, const char* password, const char* salt, const char* data, int dataLen)
{
std::string sPrivateKey = NSInternal::DecodePrivateKey(std::string(privateKeyEnc), std::string(password), std::string(salt));
if (sPrivateKey.empty())
return NULL;
if (0 == dataLen)
dataLen = (int)strlen(data);
NSOpenSSL::CMemoryData dataSign = NSOpenSSL::Sign((const unsigned char*)data, dataLen, sPrivateKey);
int nDataSignBase64Len = NSBase64::Base64EncodeGetRequiredLength((int)dataSign.Size, NSBase64::B64_BASE64_FLAG_NOCRLF);
char* pDataSignBase64 = (char*)Crypto_Malloc(nDataSignBase64Len + 1);
memset(pDataSignBase64, 0, nDataSignBase64Len + 1);
if (FALSE == NSBase64::Base64Encode(dataSign.Data, (int)dataSign.Size, (BYTE*)pDataSignBase64, &nDataSignBase64Len, NSBase64::B64_BASE64_FLAG_NOCRLF))
{
dataSign.Free();
Crypto_Free((void*)pDataSignBase64);
return NULL;
}
dataSign.Free();
return pDataSignBase64;
}
WASM_EXPORT char* Crypto_ChangePassword(const char* privateKeyEnc, const char* passwordOld, const char* passwordNew, const char* salt)
{
std::string sPrivateKey = NSInternal::DecodePrivateKey(std::string(privateKeyEnc), std::string(passwordOld), std::string(salt));
if (sPrivateKey.empty())
return NULL;
std::string sPrivateKeyEnc = "";
NSOpenSSL::AES_Encrypt_desktop_GCM(std::string(passwordNew), sPrivateKey, sPrivateKeyEnc, std::string(salt));
size_t nEncLen = sPrivateKeyEnc.length();
char* result = (char*)Crypto_Malloc((unsigned int)(nEncLen + 1));
memcpy(result, sPrivateKeyEnc.c_str(), nEncLen);
result[nEncLen] = '\0';
return result;
}
#ifdef __cplusplus
}
#endif
#ifdef TEST_AS_EXECUTABLE
#include <iostream>
int main()
{
// oform module --------------------------------
if (true)
{
std::string sSalt = "123546789";
std::string sPassword = "qwerty";
std::string sPasswordNew = "qwerty2";
char* pGeneratedKeys = Crypto_CreateKeys("ed25519", sPassword.c_str(), sSalt.c_str());
if (NULL == pGeneratedKeys)
return 1;
size_t nLen = 0;
while (pGeneratedKeys[nLen] != 0)
nLen++;
std::string sPublicKey = std::string(pGeneratedKeys, nLen);
size_t nLen2 = nLen + 1;
while (pGeneratedKeys[nLen2] != 0)
nLen2++;
std::string sPrivateKeyEnc = std::string(pGeneratedKeys + nLen + 1, nLen2 - nLen - 1);
Crypto_Free(pGeneratedKeys);
std::string sSignData = "hello world!";
char* pSignData = Crypto_Sign(sPrivateKeyEnc.c_str(), sPassword.c_str(), sSalt.c_str(), sSignData.c_str(), (int)sSignData.length());
std::string sSignature(pSignData);
Crypto_Free(pSignData);
char* pNewPrivateKey = Crypto_ChangePassword(sPrivateKeyEnc.c_str(), sPassword.c_str(), sPasswordNew.c_str(), sSalt.c_str());
std::string sPrivateKeyEncNew(pNewPrivateKey);
Crypto_Free(pNewPrivateKey);
return 0;
}
// ---------------------------------------------
std::string publicKey;
std::string privateKey;
NSOpenSSL::GenerateKeysByAlgs("ed25519", publicKey, privateKey);
if (true)
{
std::string sTestData = "hello";
std::string sTestData2 = "Hello";
NSOpenSSL::CMemoryData data = NSOpenSSL::Sign((const unsigned char*)sTestData.c_str(), (int)sTestData.length(), privateKey);
bool isVerify = NSOpenSSL::Verify((const unsigned char*)sTestData.c_str(), (int)sTestData.length(), publicKey, data.Data, (int)data.Size);
bool isVerify2 = NSOpenSSL::Verify((const unsigned char*)sTestData2.c_str(), (int)sTestData2.length(), publicKey, data.Data, (int)data.Size);
data.Free();
}
publicKey = "";
privateKey = "";
NSOpenSSL::GenerateKeysByAlgs("x25519", publicKey, privateKey);
if (true)
{
std::string sTestData = "hello";
NSOpenSSL::CMemoryData data = NSOpenSSL::Enrypt((const unsigned char*)sTestData.c_str(), (int)sTestData.length(), publicKey);
if (data.Data)
{
NSOpenSSL::CMemoryData data2 = NSOpenSSL::Decrypt(data.Data, (int)data.Size, privateKey);
if (data2.Data)
{
std::string sTestDataDecrypt = data2.Serialize(OPENSSL_SERIALIZE_TYPE_ASCII);
std::cout << sTestDataDecrypt << std::endl;
}
data.Free();
}
data.Free();
}
#ifndef DISABLE_XMLSEC
std::wstring sTestDir = NSFile::GetProcessDirectory() + L"/../../../../test/";
void* cert = Crypto_CreateCertificate();
BYTE* pCertData = NULL;
DWORD nCertLen = 0;
NSFile::CFileBinary::ReadAllBytes(sTestDir + L"keys/cert.crt", &pCertData, nCertLen);
Crypto_LoadCert(cert, pCertData, nCertLen, NULL);
BYTE* pKeyData = NULL;
DWORD nKeyLen = 0;
NSFile::CFileBinary::ReadAllBytes(sTestDir + L"keys/key.key", &pKeyData, nKeyLen);
Crypto_LoadKey(cert, pKeyData, nKeyLen, NULL);
Crypto_DestroyCertificate(cert);
RELEASEARRAYOBJECTS(pCertData);
RELEASEARRAYOBJECTS(pKeyData);
#endif
return 0;
}
#endif

View File

@ -1,56 +0,0 @@
QT -= core gui
TARGET = wasm
TEMPLATE = app
CONFIG += console
CONFIG -= app_bundle
DEFINES += TEST_AS_EXECUTABLE
CONFIG += oform_only
oform_only {
DEFINES += DISABLE_XMLSEC
}
CORE_ROOT_DIR = $$PWD/../../../../../..
PWD_ROOT_DIR = $$PWD
include($$CORE_ROOT_DIR/Common/base.pri)
DEFINES += KERNEL_NO_USE_DYNAMIC_LIBRARY
DEFINES += COMMON_OPENSSL_BUILDING_INTERNAL
SOURCES += \
$$CORE_ROOT_DIR/DesktopEditor/common/File.cpp \
$$CORE_ROOT_DIR/DesktopEditor/common/Base64.cpp
oform_only {
HEADERS += \
$$CORE_ROOT_DIR/DesktopEditor/xmlsec/src/include/Certificate.h \
$$CORE_ROOT_DIR/DesktopEditor/xmlsec/src/include/CertificateCommon.h
SOURCES += \
$$CORE_ROOT_DIR/DesktopEditor/xmlsec/src/src/CertificateCommon.cpp
DEFINES += SUPPORT_OFORM
HEADERS += $$CORE_ROOT_DIR/DesktopEditor/xmlsec/src/src/Certificate_oform.h
}
# OPENSSL
CONFIG += open_ssl_common
include($$CORE_ROOT_DIR/Common/3dParty/openssl/openssl.pri)
core_windows {
LIBS += -lcrypt32
LIBS += -lcryptui
LIBS += -lAdvapi32
LIBS += -lws2_32
LIBS += -lUser32
}
core_linux {
LIBS += -ldl
}
# WASM EXPORT
SOURCES += main.cpp

Binary file not shown.

Before

Width:  |  Height:  |  Size: 576 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 683 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 778 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 888 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1022 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 515 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 617 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 707 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 788 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 902 B

View File

@ -1,433 +0,0 @@
/**
*
* (c) Copyright Ascensio System SIA 2020
*
* 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(window, undefined)
{
(function()
{
let url = "./engine/engine";
let useWasm = false;
let webAsmObj = window["WebAssembly"];
if (typeof webAsmObj === "object" && typeof webAsmObj["Memory"] === "function")
{
if ((typeof webAsmObj["instantiateStreaming"] === "function") || (typeof webAsmObj["instantiate"] === "function"))
useWasm = true;
}
url += (useWasm ? ".js" : "_ie.js");
let script = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
document.head.appendChild(script);
})();
var CurrentModeType = {
Sign: 0,
Generate: 1,
Change: 2
}
var currentMode = CurrentModeType.Sign;
var currentSignData = "";
function CKeyChainInfo()
{
// object:
// { "id1" : {"type" : "rec_type", "value" : "rec_value"}, "id2" : {...}, ... }
this.value = {};
}
CKeyChainInfo.prototype.set = function(value)
{
this.value = value ? value : {};
};
CKeyChainInfo.prototype.getSignInfo = function()
{
let keyInfo = null;
for (let prop in this.value)
{
if (!this.value.hasOwnProperty(prop))
continue;
let rec = this.value[prop];
if (rec.key === "keySign" && rec.value && rec.value.date)
{
if (!keyInfo)
keyInfo = rec.value;
else
{
let dateOld = new Date(keyInfo.date);
let dateNew = new Date(rec.value.date);
if (dateNew > dateOld)
keyInfo = rec.value;
}
}
}
return keyInfo;
};
CKeyChainInfo.prototype.getCurrentPassword = function()
{
let elem = document.getElementById("old_password_value");
if (!elem || elem.value === "")
return "";
return elem.value;
};
CKeyChainInfo.prototype.getNewPassword = function()
{
let elem = document.getElementById("new_password_value");
if (!elem || elem.value === "")
return "";
return elem.value;
};
CKeyChainInfo.prototype.changePassword = function(oldPassword, newPassword)
{
let newValue = {};
for (let prop in this.value)
{
if (!this.value.hasOwnProperty(prop))
continue;
let rec = this.value[prop];
switch (rec.key)
{
case "keySign":
case "keyCrypt":
{
let newKeyEnc = window.cryptoJS.changePassword(rec.value.privateKey,
oldPassword, newPassword, rec.value.salt);
if (!newKeyEnc)
return null;
rec.value.privateKey = newKeyEnc;
newValue[prop] = rec;
break;
}
default:
{
//newValue[prop] = rec;
break;
}
}
}
return newValue;
};
CKeyChainInfo.prototype.checkPassword = function(password)
{
for (let prop in this.value)
{
if (!this.value.hasOwnProperty(prop))
continue;
let rec = this.value[prop];
switch (rec.key)
{
case "keySign":
case "keyCrypt":
{
let newKeyEnc = window.cryptoJS.changePassword(rec.value.privateKey,
password, "test", rec.value.salt);
if (!newKeyEnc)
return false;
break;
}
default:
{
//newValue[prop] = rec;
break;
}
}
}
return true;
};
var currentKeychain = new CKeyChainInfo();
window.Asc.plugin.init = function(text)
{
currentSignData = text;
onTabSelect(CurrentModeType.Sign);
document.getElementById("id_mode_sign").onclick = function()
{
onTabSelect(0);
};
document.getElementById("id_mode_generate").onclick = function()
{
onTabSelect(1);
};
document.getElementById("id_mode_change").onclick = function()
{
onTabSelect(2);
};
this.executeMethod("GetKeychainStorageInfo", [{ type: "get", value: ["keySign", "keyCrypt"] }], function(obj)
{
currentKeychain.set(obj);
if (!currentKeychain.getSignInfo())
onTabSelect(CurrentModeType.Generate);
});
};
window.Asc.plugin.button = function(id)
{
if (!window.cryptoJS.isModuleInit)
{
// TODO: wait...
console.log("please wait when the module will be loaded...");
this.executeCommand("close", "");
return;
}
if (0 !== id)
{
this.executeMethod("OnSignWithKeychain", [undefined], function()
{
this.executeCommand("close", "");
});
return;
}
switch (currentMode)
{
case CurrentModeType.Sign:
{
let password = currentKeychain.getCurrentPassword();
if ("" === password)
{
document.getElementById("old_input_error_id").style.display = "block";
console.log("check password!");
return;
}
document.getElementById("old_input_error_id").style.display = "none";
let currentKey = currentKeychain.getSignInfo();
if (!currentKey)
{
onTabSelect(CurrentModeType.Generate);
console.log("please generate one key pair!");
return;
}
let signData = window.cryptoJS.sign(currentKey.privateKey, password, currentKey.salt, currentSignData);
if (!signData)
{
document.getElementById("old_input_error_id").style.display = "block";
console.log("check password!");
return;
}
let signDataReturn = {
data: signData,
key: "pem:" + currentKey.publicKey
};
this.executeMethod("OnSignWithKeychain", [signDataReturn], function(isOK)
{
window.Asc.plugin.executeCommand("close", "");
});
break;
}
case CurrentModeType.Generate:
{
let password = currentKeychain.getCurrentPassword();
if ("" === password || false === currentKeychain.checkPassword(password))
{
document.getElementById("old_input_error_id").style.display = "block";
console.log("check password!");
return;
}
document.getElementById("old_input_error_id").style.display = "none";
let keyItem = window.cryptoJS.generateKeys(password);
let item = {
type: "add",
value : [{
key : "keySign",
value : {
privateKey: keyItem.privateKey,
publicKey: keyItem.publicKey,
salt: keyItem.salt,
private: ["privateKey"]
}
}],
callback : ["keySign"]
};
this.executeMethod("SetKeychainStorageInfo", [item], function(obj)
{
currentKeychain.set(obj);
if (currentKeychain.getSignInfo())
onTabSelect(CurrentModeType.Sign);
else
{
console.log("storage error");
}
});
break;
}
case CurrentModeType.Change:
{
if (!currentKeychain.getSignInfo())
{
onTabSelect(CurrentModeType.Generate);
console.log("please generate one key pair!");
return;
}
let oldPassword = currentKeychain.getCurrentPassword();
let newPassword = currentKeychain.getNewPassword();
if (oldPassword === "")
{
document.getElementById("old_input_error_id").style.display = "block";
return;
}
if (newPassword === "")
{
document.getElementById("new_input_error_id").style.display = "block";
return;
}
document.getElementById("old_input_error_id").style.display = "none";
document.getElementById("new_input_error_id").style.display = "none";
replaceItems = currentKeychain.changePassword(oldPassword, newPassword);
if (replaceItems)
{
this.executeMethod("SetKeychainStorageInfo", [{type: "replace", value : replaceItems, callback : ["keySign"]}], function(obj)
{
currentKeychain.set(obj);
if (currentKeychain.getSignInfo())
onTabSelect(CurrentModeType.Sign);
else
{
console.log("storage error");
}
});
}
else
{
document.getElementById("old_input_error_id").style.display = "block";
console.log("wrong password!");
}
break;
}
default:
break;
}
};
function _translateElem(id, text)
{
let _elem = document.getElementById(id);
if (_elem) _elem.innerHTML = window.Asc.plugin.tr(text);
}
window.Asc.plugin.onTranslate = function()
{
_translateElem("id_text_sign", "Sign");
_translateElem("id_text_generate", "Generate");
_translateElem("id_text_change", "Change Password");
_translateElem("id_old_password", "Password");
_translateElem("id_new_password", "New Password");
};
window.Asc.plugin.onThemeChanged = function(theme)
{
window.Asc.plugin.onThemeChangedBase(theme);
let separators = document.getElementsByClassName("tab_separator");
for (let i = 0, len = separators.length; i < len; i++)
separators[i].style.backgroundColor = window.Asc.plugin.theme["text-normal"];
let setections = document.getElementsByClassName("tab_select");
for (let i = 0, len = setections.length; i < len; i++)
setections[i].style.backgroundColor = window.Asc.plugin.theme["text-normal"];
};
function onTabSelect(mode)
{
document.getElementById("old_input_error_id").style.display = "none";
document.getElementById("new_input_error_id").style.display = "none";
currentMode = mode;
switch (currentMode)
{
case CurrentModeType.Sign:
document.getElementById("id_mode_sign").classList.add("tab_mode_select");
document.getElementById("id_mode_generate").classList.remove("tab_mode_select");
document.getElementById("id_mode_change").classList.remove("tab_mode_select");
document.getElementById("id_tab_select").style.transform = "translateX(calc(6.5%*5))";
break;
case CurrentModeType.Generate:
document.getElementById("id_mode_sign").classList.remove("tab_mode_select");
document.getElementById("id_mode_generate").classList.add("tab_mode_select");
document.getElementById("id_mode_change").classList.remove("tab_mode_select");
document.getElementById("id_tab_select").style.transform = "translateX(calc(39.5%*5))";
break;
case CurrentModeType.Change:
document.getElementById("id_mode_sign").classList.remove("tab_mode_select");
document.getElementById("id_mode_generate").classList.remove("tab_mode_select");
document.getElementById("id_mode_change").classList.add("tab_mode_select");
document.getElementById("id_tab_select").style.transform = "translateX(calc(72.5%*5))";
break;
default:
break;
}
switch (mode)
{
case CurrentModeType.Sign:
case CurrentModeType.Generate:
document.getElementById("id_new_password").style.display = "none";
document.getElementById("id_new_password_div").style.display = "none";
window.Asc.plugin.resizeWindow(500, 110, 500, 110, 0, 0);
break;
case CurrentModeType.Change:
document.getElementById("id_new_password").style.display = "block";
document.getElementById("id_new_password_div").style.display = "block";
window.Asc.plugin.resizeWindow(500, 160, 500, 160, 0, 0);
break;
default:
break;
}
};
})(window, undefined);

View File

@ -1,9 +0,0 @@
{
"Sign" : "Sign",
"Generate" : "Generate",
"Change Password" : "Change Password",
"Password" : "Password",
"Old Password" : "Old Password",
"New Password" : "New Password",
"OK" : "OK"
}

View File

@ -1,9 +0,0 @@
{
"Sign" : "Sign",
"Generate" : "Generate",
"Change Password" : "Change Password",
"Password" : "Password",
"Old Password" : "Old Password",
"New Password" : "New Password",
"OK" : "OK"
}

View File

@ -1,9 +0,0 @@
{
"Sign" : "Sign",
"Generate" : "Generate",
"Change Password" : "Change Password",
"Password" : "Password",
"Old Password" : "Old Password",
"New Password" : "New Password",
"OK" : "OK"
}

View File

@ -1,9 +0,0 @@
{
"Sign" : "Sign",
"Generate" : "Generate",
"Change Password" : "Change Password",
"Password" : "Password",
"Old Password" : "Old Password",
"New Password" : "New Password",
"OK" : "OK"
}

View File

@ -1,7 +0,0 @@
[
"cs-CS",
"de-DE",
"es-ES",
"fr-FR",
"ru-RU"
]

View File

@ -1,7 +0,0 @@
{
"Sign" : "Sign",
"Generate" : "Generate",
"Change Password" : "Change Password",
"Password" : "Password",
"New Password" : "New Password"
}

View File

@ -367,7 +367,8 @@ namespace NSDocxRenderer
bForcedBold,
m_bUseDefaultFont,
m_bWriteStyleRaw,
m_bCollectMetaInfo
m_bCollectMetaInfo,
m_bFontSubstitution
);
}

View File

@ -47,7 +47,7 @@ const double c_dSHAPE_TROUGH_MAX_MM = 80.0;
const double c_dLINE_SPLIT_DISTANCE_MM = 10.0;
const double c_dSHAPE_X_OFFSET_MM = 1.5;
const double c_dAVERAGE_SPACE_WIDTH_COEF = 0.9;
const double c_dSPACE_WIDTH_COEF = 0.4;
const double c_dSPACE_WIDTH_COEF = 0.39;
const double c_dMIN_ROTATION = 0.01;
const double c_dMAX_FIRST_LINE_INDENT = 20.0;

Some files were not shown because too many files have changed in this diff Show More