open source

This commit is contained in:
lvfulong
2020-11-11 16:17:13 +08:00
parent 4d989f3ecb
commit bc4ca748de
2441 changed files with 623057 additions and 2 deletions
+18
View File
@@ -0,0 +1,18 @@
{
"version": "0.2.0",
"configurations": [
{
"name": "Launch Extension",
"type": "extensionHost",
"request": "launch",
"runtimeExecutable": "${execPath}",
"args": [
"--extensionDevelopmentPath=${workspaceRoot}"
],
"stopOnEntry": false,
"sourceMaps": true,
"outDir": "out",
"preLaunchTask": "npm"
}
]
}
+190
View File
@@ -0,0 +1,190 @@
// Available variables which can be used inside of strings.
// ${workspaceRoot}: the root folder of the team
// ${file}: the current opened file
// ${fileBasename}: the current opened file's basename
// ${fileDirname}: the current opened file's dirname
// ${fileExtname}: the current opened file's extension
// ${cwd}: the current working directory of the spawned process
// A task runner that calls the Typescript compiler (tsc) and
// Compiles a HelloWorld.ts program
{
"version": "0.1.0",
// The command is tsc. Assumes that tsc has been installed using npm install -g typescript
"command": "tsc",
// The command is a shell script
"isShellCommand": true,
// Show the output window only if unrecognized errors occur.
"showOutput": "silent",
// args is the HelloWorld program to compile.
"args": ["-p","."],
// use the standard tsc problem matcher to find compile problems
// in the output.
"problemMatcher": "$tsc"
}
// A task runner that calls the Typescript compiler (tsc) and
// compiles based on a tsconfig.json file that is present in
// the root of the folder open in VSCode
/*
{
"version": "0.1.0",
// The command is tsc. Assumes that tsc has been installed using npm install -g typescript
"command": "tsc",
// The command is a shell script
"isShellCommand": true,
// Show the output window only if unrecognized errors occur.
"showOutput": "silent",
// Tell the tsc compiler to use the tsconfig.json from the open folder.
"args": ["-p", "."],
// use the standard tsc problem matcher to find compile problems
// in the output.
"problemMatcher": "$tsc"
}
*/
// A task runner configuration for gulp. Gulp provides a less task
// which compiles less to css.
/*
{
"version": "0.1.0",
"command": "gulp",
"isShellCommand": true,
"tasks": [
{
"taskName": "less",
// Make this the default build command.
"isBuildCommand": true,
// Show the output window only if unrecognized errors occur.
"showOutput": "silent",
// Use the standard less compilation problem matcher.
"problemMatcher": "$lessCompile"
}
]
}
*/
// Uncomment the following section to use jake to build a workspace
// cloned from https://github.com/Microsoft/TypeScript.git
/*
{
"version": "0.1.0",
// Task runner is jake
"command": "jake",
// Need to be executed in shell / cmd
"isShellCommand": true,
"showOutput": "silent",
"tasks": [
{
// TS build command is local.
"taskName": "local",
// Make this the default build command.
"isBuildCommand": true,
// Show the output window only if unrecognized errors occur.
"showOutput": "silent",
// Use the redefined Typescript output problem matcher.
"problemMatcher": [
"$tsc"
]
}
]
}
*/
// Uncomment the section below to use msbuild and generate problems
// for csc, cpp, tsc and vb. The configuration assumes that msbuild
// is available on the path and a solution file exists in the
// workspace folder root.
/*
{
"version": "0.1.0",
"command": "msbuild",
"args": [
// Ask msbuild to generate full paths for file names.
"/property:GenerateFullPaths=true"
],
"taskSelector": "/t:",
"showOutput": "silent",
"tasks": [
{
"taskName": "build",
// Show the output window only if unrecognized errors occur.
"showOutput": "silent",
// Use the standard MS compiler pattern to detect errors, warnings
// and infos in the output.
"problemMatcher": "$msCompile"
}
]
}
*/
// Uncomment the following section to use msbuild which compiles Typescript
// and less files.
/*
{
"version": "0.1.0",
"command": "msbuild",
"args": [
// Ask msbuild to generate full paths for file names.
"/property:GenerateFullPaths=true"
],
"taskSelector": "/t:",
"showOutput": "silent",
"tasks": [
{
"taskName": "build",
// Show the output window only if unrecognized errors occur.
"showOutput": "silent",
// Use the standard MS compiler pattern to detect errors, warnings
// and infos in the output.
"problemMatcher": [
"$msCompile",
"$lessCompile"
]
}
]
}
*/
// A task runner example that defines a problemMatcher inline instead of using
// a predefined one.
/*
{
"version": "0.1.0",
"command": "tsc",
"isShellCommand": true,
"args": ["HelloWorld.ts"],
"showOutput": "silent",
"problemMatcher": {
// The problem is owned by the typescript language service. Ensure that the problems
// are merged with problems produced by Visual Studio's language service.
"owner": "typescript",
// The file name for reported problems is relative to the current working directory.
"fileLocation": ["relative", "${cwd}"],
// The actual pattern to match problems in the output.
"pattern": {
// The regular expression. Matches HelloWorld.ts(2,10): error TS2339: Property 'logg' does not exist on type 'Console'.
"regexp": "^([^\\s].*)\\((\\d+|\\d+,\\d+|\\d+,\\d+,\\d+,\\d+)\\):\\s+(error|warning|info)\\s+(TS\\d+)\\s*:\\s*(.*)$",
// The match group that denotes the file containing the problem.
"file": 1,
// The match group that denotes the problem location.
"location": 2,
// The match group that denotes the problem's severity. Can be omitted.
"severity": 3,
// The match group that denotes the problem code. Can be omitted.
"code": 4,
// The match group that denotes the problem's message.
"message": 5
}
}
}
*/
+2
View File
@@ -0,0 +1,2 @@
///<reference path="../domsupport/ES6NoDOM.d.ts" />
//开发期间,先直接引用定义文件。
+2
View File
@@ -0,0 +1,2 @@
///<reference path="../domsupport/LayaConchRuntime.d.ts" />
//开发期间,先直接引用定义文件。
File diff suppressed because it is too large Load Diff
+219
View File
@@ -0,0 +1,219 @@
/*
var canv = document.createElement('canvas');
var ctx = canv.getContext('2d');
ctx.save();
ctx.fillStyle = '#ff0000';
var img = new Image();
img.src = 'http://10.10.20.19:7777/a.jpg';
var bload = false;
img.onload = function(e) {
bload = true;
}
img.addEventListener('load', function() {
})
setInterval(() => {
if (bload) {
console.log('kkk');
ctx.drawImage(img._nativeObj, 0, 0, 100, 100, 0, 0, 100, 100);
}
}, 100);
*/
//require('websocket.js');
// downloadGetHeader('http://s0.tx.zxyh5.com/api/zxy/register.php',(buf)=>{
// alert('ok ' +buf);
// },(e,httprec)=>{
// alert('error');
// },100,100);
// class MyWebSocket{
// constructor(url:string){
// ConchWebSocket.call(this,url);
// }
// }
//var w1 = new MyWebSocket('aaa');
//alert(JSON.stringify(w1));
/*
var ws = new WebSocket('ws://10.10.20.241:7060');
ws.onopen=function(ev){
alert('kkk')
}
function md(e){
console.log('--------------');
}
document.body.addEventListener('mousedown',md);
document.body.addEventListener('mousedown',md);
*/
import test = require('./unitTest');
type Test = test.Test;
function AllTest() {
/**
* 1. cloneNode 能正确clone
*/
this.test_clone=function(test: Test) {
try {
var b = document.createElement('audio');
var c = b.cloneNode(false);
c.addEventListener('', null);
} catch (e) {
test.err(`
cloneNode之后,应该有 addEventListener 函数。
`);
}
}
/**
* 测试event事件的派发
*/
this.testEventDispatch=function(test: Test) {
var called = false;
var canv = document.createElement('canvas');
document.body.appendChild(canv);
canv.addEventListener('mmousemove', (evt) => {
called = true;
});
var evt = new MouseEvent('mmousemove');
evt.clientX = 100;
evt.clientY = 100;
canv.dispatchEvent(evt);
test.eq(called, true, '事件应该能正确发送给canvas');
document.removeChild(canv);
test.neq(window.document._topElement, canv, 'removeChild之后,应该维护_topElement');
}
this.testEvent_phase=function(test: Test) {
var canv = document.createElement('canvas');
var result: number[] = [];
document.body.appendChild(canv);
document.addEventListener('mousedown', (evt) => {
result.push(1);
//alert('document capture event');
}, true);
document.body.addEventListener('mousedown', (evt) => {
//alert('body capture event');
result.push(2);
}, true);
canv.addEventListener('mousedown', (evt) => {
//alert('on mousedown');
result.push(3);
});
document.body.addEventListener('mousedown', (evt) => {
//alert('event bubble to body');
result.push(4);
});
document.addEventListener('mousedown', (evt) => {
//alert('event bubble to document');
result.push(5);
});
window.addEventListener('mousedown', (evt) => {
//alert('event bubble to window');
result.push(6);
});
var evt = new MouseEvent('mousedown');
evt.clientX = 100;
evt.clientY = 100;
canv.dispatchEvent(evt);
document.removeChild(canv);
}
this.testRuntimeVersion=function(test: Test) {
var rv = conchConfig.getRuntimeVersion();
var b = rv.indexOf('conch');
}
//测试ArrayBuffer的传递和管理
this.testABToC=function(test: Test) {
/*
while (true) {
var ab = new ArrayBuffer(1000);
var cp = conch.byteCompress(ab);
var ucp = conch.byteUnCompress(cp);
}
*/
}
//所有接口
this.testZip=function(test: Test) {
var zf = new ZipFile();
zf.setSrc('');
zf.forEach((id, name, dir, sz) => {
var ab = zf.readFile(id);
});
zf.close();
}
this.testFile=function(test: Test) {
var abv = new Uint32Array([1, 2, 3]);
fs_writeFileSync('d:/temp/ddd.d', abv.buffer);
var ab = fs_readFileSync('d:/temp/ddd.d');
var v1 = new Uint32Array(ab);
if (v1.byteLength != 12 || v1[0] != 1 || v1[1] != 2 || v1[2] != 3)
alert('error:' + arguments.callee.name);
alert(fs_readdirSync('d:/temp'));
//var ab = readBinFileSync('');
}
this.testWebSocket=function(test: Test) {
var ws = new WebSocket('');
}
this.testMD5=function(test: Test) {
var result = '2a1dd1e1e59d0a384c26951e316cd7e6';
test.eq(result, calcmd5(new Uint32Array([1, 2, 3]).buffer), 'md5计算不正确');
}
this.testPost=function(test: Test) {
var ab = new Uint32Array([0, 1, 2]);
conch._postUrl('http://localhost:8888/testpost', 1, ab.buffer, null, (buf) => {
}, (e) => {
}, () => {
return 0;
})
}
this.testUrlEncode=function(){
//http://115.159.92.56:8107/update/0?4089:21922|%5B%7B%22m%22%3A%22C_GSVR%22%2C%22c%22%3A0%2C%22p%22%3A%5Bnull%2C%22QQ%22%2Cnull%2C%221%2E0.2%22%5D%2C%22st%22%3A1460718545%7D%5D
//结果不能变
}
/*
testFontInfo(test:Test){
var cn = new ConchNode();
cn.font('normal 100 16px Arial b 1 #ff0000 1 #00ff00 ');
test.eq(1,1,'');
cn.font(' ')
test.eq(1,1,'');
cn.font('')
test.eq(1,1,'');
cn.font('normal 100 28px Microsoft_YaHei 1 #444444 0');
cn.font('normal normal 18px 宋体 2 #000000 0 #000000');
test.eq(1,1,'');
}
*/
this.testFileReader=function(test:Test){
var f = new File('file:///d:/temp/test.sh');
var fr = new FileReader();
fr.onload=function(){
alert('ok '+fr.result);
}
fr.readAsText(f);
}
}
test.testall(new AllTest(), "");
+410
View File
@@ -0,0 +1,410 @@
window._conchInfo = { version: '2.1.3.1' };
var _inline =!conchConfig.localizable; //是否是单机版
console.log('====================================================== ');
console.log(' LAYA CONCH ');
console.log(' runtimeversion:' + conchConfig.getRuntimeVersion());
console.log(' jsversion:' + window._conchInfo.version);
console.log(' isplug:' + conchConfig.getIsPlug());
console.log('======================================================');
function log(m) {
console.log(m);
}
if (conchConfig.getOS() == "Conch-ios"){
require('promise');
}
function loadLib(url:string) {
var script = document.createElement("script");
if(url.indexOf("laya.physics3D.js") >= 0 )
{
url = url.replace("laya.physics3D.js","laya.physics3D.runtime.js");
}
script.src = url;
script.onerror=function(){
if(window["onLayaInitError"]){
window["onLayaInitError"]("Load script error");
}
}
document.head.appendChild(script);
}
window['loadLib']=loadLib;
import asyncs = require('async');
async function initFreeType() {
var sOS = conchConfig.getOS();
var bRet = false;
//优先使用包中的字体
var sTempFontPath = conch.getCachePath() + "/runtimeFont/";
if (!fs_exists(sTempFontPath)) {
fs_mkdir(sTempFontPath);
}
sTempFontPath += "layabox.ttf";
bRet = _conchTextCanvas.initFreeTypeDefaultFontFromFile(sTempFontPath);
if(bRet == false){
var assetFontData = conch.readFileFromAsset('font/layabox.ttf','raw');
if( assetFontData ){
fs_writeFileSync(sTempFontPath, assetFontData);
bRet = _conchTextCanvas.initFreeTypeDefaultFontFromFile(sTempFontPath);
}
}
if(!bRet){
if (sOS == "Conch-window") {
bRet = _conchTextCanvas.initFreeTypeDefaultFontFromFile("C:/Windows/Fonts/simhei.ttf");
}
else if (sOS == "Conch-android") {
var fSystemVersion = navigator.sv;
if (fSystemVersion >= 2.0 && fSystemVersion < 5.0) {
//这个步骤为因为HTC部分手机,作出了一个奇葩的决定:将DroidSansFallback架空,引入DFHEIA5A和DFHEIA7A两个字体文件。
bRet = _conchTextCanvas.initFreeTypeDefaultFontFromFile("/system/fonts/DFHEIA5A.ttf");
if (bRet == false) {
bRet = _conchTextCanvas.initFreeTypeDefaultFontFromFile("/system/fonts/DroidSansFallback.ttf");
}
}
else if (fSystemVersion >= 5.0 && fSystemVersion < 6.0) {
var vDefaultStrings = [];
vDefaultStrings.push("/system/fonts/NotoSansHans-Regular.otf");
vDefaultStrings.push("/system/fonts/Roboto-Regular.ttf");
bRet = _conchTextCanvas.initFreeTypeDefaultFontFromFile(vDefaultStrings.join('|'));
}
else if (fSystemVersion >= 6.0 && fSystemVersion < 7.0) {
var vDefaultStrings = [];
vDefaultStrings.push("/system/fonts/NotoSansSC-Regular.otf");
vDefaultStrings.push("/system/fonts/Roboto-Regular.ttf");
bRet = _conchTextCanvas.initFreeTypeDefaultFontFromFile(vDefaultStrings.join('|'));
}
else if (fSystemVersion >= 7.0 && fSystemVersion < 8.0) {
bRet = false;
}
}
else if(sOS=="Conch-ios")
{
bRet = _conchTextCanvas.initFreeTypeDefaultFontFromFile("");
}
}
if (bRet == false) {
log('字体初始化失败,从网络下载字体...');
var data = <ArrayBuffer>(await asyncs.downloadSync(location.fullpath+'/font/simhei.ttf', true, null));
if(!data){
data=<ArrayBuffer>(await asyncs.downloadSync('http://runtime.layabox.com/font/simhei.ttf', true, null));
}
if (!data) {
alert('下载字体失败。 ');
return;
}
fs_writeFileSync(sTempFontPath, data);
bRet = _conchTextCanvas.initFreeTypeDefaultFontFromFile(sTempFontPath);
}
if(!bRet){
log('字体初始化失败。');
}
}
//initFreeType();
function setOrientation(s: string) {
var nameToVal = {
landscape: 0, portrait: 1, user: 2, behind: 3, sensor: 4, nosensor: 5, sensor_landscape: 6,sensorLandscape: 6,
sensor_portrait: 7,sensorPortrait: 7, reverse_landscape: 8,reverseLandscape: 8, reverse_portrait: 9,reversePortrait: 9, full_sensor: 10,fullSensor: 10,
}
var nOri = (function (name: string) {
try {
var n = nameToVal[name];
return n || 0;
} catch (e) {
return 0;
}
})(s);
//if (conchConfig.getScreenOrientation() != nOri) {
conchConfig.setScreenOrientation(nOri);;
//}
}
Object.defineProperty(window,'screenOrientation',{
get:function(){
return (window as any).___screenOri;
},
set:function(v:string){
(window as any).___screenOri = v;
setOrientation(v);
}
});
/**
*
* @param data json字符串
*/
function startApp(data: string) {
var jsonobj:{scripts:string[],screenorientation:string,screenOrientation:string,}=null;
try{
jsonobj = JSON.parse(data);
}catch(e){
console.log("Error:start page parse error! \n "+data);
//TODO 通知全局错误
return;
}
jsonobj.scripts.forEach((v)=>{
var t = document.createElement("script");
t["src"]=v;
t.onerror=function(){
if(window["onLayaInitError"])
{
window["onLayaInitError"]("Load script error");
}
}
document.head.appendChild(t);
});
if (jsonobj.screenOrientation) setOrientation(jsonobj.screenOrientation);
else if (jsonobj.screenorientation) setOrientation(jsonobj.screenorientation);
else setOrientation("sensor_landscape");
document.createElement("script").text="window.onload&&window.onload()";
}
async function loadApp(url: string) {
var urllen = url.length;
if (urllen < 2) return;
url = url.trim();
if(url.substring(urllen-1)==='/') url = url +'runtime.json';
//TODO 用自动把html换成json么。现在的工具会生成html的,所以先替换掉。
url = url.replace(/.html$/i,'.json');
if(url.indexOf('http://stand.alone.version')==0)
_inline=false;
if( !_inline ){
url = 'http://stand.alone.version/index.js';
}
console.log("loadApp:" + url);
if (history.length <= 0) {
history._push(url);
}
if (url.length < 2) return;
location.setHref(url);
var urlpath = location.fullpath + '/';
var cache = window.appcache = new AppCache(urlpath);//这时候会加载资源索引,因此如果更新了索引,必须重新创建。
//为了让启动html也使用缓存,需要在loadUrl刚开始的时候就创建appcache对象。
document.loadCookie();
await initFreeType(); //TODO 如果下载这里相当于会卡住。
try{
require("config");
}
catch(e)
{
}
var isDccOk=true;
async function updateDcc() {
cache.setResourceID('appurl', urlpath);
var curassets = cache.getResourceID('netassetsid');
var assetsidStr =<string>( await asyncs.downloadSync(urlpath + 'update/assetsid.txt?rand=' + Math.random() * Date.now(), false, null));
console.log("assetsid old:"+curassets+" new:"+assetsidStr);
if (!assetsidStr) {
//对于发布版,这个功能还是不要了把。一旦下载错误,就会导致都重新下载,在网络不好的情况下,恶化了实际表现。
//如果没有assetsid,则去掉校验功能。
//cache.saveFileTable('');
//cache.setResourceID('netassetsid', ''); //去掉,保证下次能正确更新
//cache = new AppCache(urlpath);
if(curassets && curassets!="")//如果之前就有dcc,现在下载不到,肯定是网络问题,不能直接进游戏,不然会有问题
{
if(window["onLayaInitError"])
{
isDccOk=false;
window["onLayaInitError"]("Update DCC get assetsid error");
}
}
} else {
if (curassets != assetsidStr) {
log('need update;');
var txtdcc = '';
var bindcc = await asyncs.downloadSync(urlpath + 'update/filetable.bin?' + assetsidStr, true, null);
if (!bindcc || !(bindcc instanceof ArrayBuffer)) {
txtdcc = <string>(await asyncs.downloadSync(urlpath + 'update/filetable.txt?' + assetsidStr, false, null));
} else {
if (bindcc.byteLength % 8 != 0) {
log('下载的的filetable.bin的长度不对。是不是错了。');
} else {
var v = new Uint32Array(bindcc);
if (v[0] != 0xffeeddcc || v[1] != 1) {//需要校验
//onloadfterr();
log('dcc.bin file err!');
} else {
if (v[2] == 0x00ffffff) {
//从v[4]开始是32个字节的md5
var stp = (4 + 8) / 2;
var md5int = v.slice(4, 12);
var md5char = new Uint8Array(md5int.buffer);
var so = String.fromCharCode.apply(null, md5char);
console.log('--------------------------------------------')
console.log('so=' + so);
console.log('netid=' + assetsidStr);
if (so == assetsidStr) {
//一致了
for (var ii = stp, isz = v.length / 2; ii < isz; ii++)
txtdcc += v[ii * 2].toString(16) + ' ' + v[ii * 2 + 1].toString(16) + '\n';
}
} else {
console.log('----------------old format');
for (var ii = 1, isz = v.length / 2; ii < isz; ii++)
txtdcc += v[ii * 2].toString(16) + ' ' + v[ii * 2 + 1].toString(16) + '\n';
}
}
}
}
if (txtdcc&&txtdcc.length > 0) {
cache.saveFileTable(txtdcc);
window.appcache = cache = new AppCache(urlpath);
//设置新的id。只有写完filetable之后才能写这个
cache.setResourceID('netassetsid', assetsidStr);
} else {
//没有得到任何dcc TODO
if(window["onLayaInitError"]){
isDccOk=false;
window["onLayaInitError"]("Update DCC get filetable error");
}
}
}
}
}
//dcc
if(_inline){
await updateDcc();
if(!isDccOk)
{
console.log("init dcc fail");
return;
}
}
var data: string = await asyncs.loadText(url);
for(var n=0; n<3 && !data; n++){
data = await asyncs.loadText(url);
}
if(!data){
if (window["loadingView"]) {
window["loadingView"].setFontColor("#FF0000");
window["loadingView"].setTips(['网络异常,请检查您的网络或与开发商联系。']);
}
data = cache.loadCachedURL(url);
if(!data || data.length <= 0)
if(window["onLayaInitError"])
{
window["onLayaInitError"]("Load start url error");
}
return ;
}
console.log("");//此操作在ios下 能起很大的作用 如果注释掉就会非法 不信你试试 但是最后还是得看看是鸡巴毛原因 TODO
var qpos = url.indexOf('?');
if(qpos<0) qpos = url.length;
if (url.substr(qpos - 3,3) === '.js') {
window.eval(data + `
//@ sourceURL=${url}
`);
document.createElement("script").text="window.onload&&window.onload()";
}
else {//全部当成json处理
startApp(data);
}
if (window["loadingView"] && window["loadingView"].loadingAutoClose) {
window["loadingView"].hideLoadingView();
}
}
window.document.addEventListener('keydown', function (e: KeyboardEvent) {
switch (e.keyCode) {
case 116://F5
reloadJS(true);
break;
case 117://F6
history.back();
break;
case 118://F7
//conch.printAllMemorySurvey("","http://10.10.20.114:8889/upload","layabox");
break;
case 119://F8
break;
case 120:
gc();
break;
}
});
window.loadConchUrl = loadApp;
/**
* 更新。
* @param {string} url zip下载地址
* @param {(event:string,downloadPercent:number,curfile:string)=>boolean} onEvent 事件的回调。
* 事件名称:
* 'downloading' 下载中,这时候downloadPercent有值
* 'downloadError' 下载错误
* 'downloadOK' 下载成功。
* 'updating' 更新中,这时候 curfile有值,表示正在更新的文件
* 'updateError' curfile更新错误。因为curfile不在dcc列表,或者文件内容与dcc内容不一致。少量更新错误可以忽略,因为在实际使用的时候还是会下载
* 'unknownError'
* @param {function(localfile:string):void} onEnd 更新完成的回调
*/
window['updateByZip'] =function(url, onEvent, onEnd){
let cachePath = conch.getCachePath();
let localfile = cachePath+url.substr(url.lastIndexOf('/'));
/**
* 下载文件,保存到localfile中。
*/
downloadBigFile(url,localfile,
//进度回调
(total:number,now:number,speed:number)=>{
onEvent('downloading',Math.floor((now/total)*100),null);
return false;
},
//完成回调
(curlret:number,httpret:number)=>{
if(curlret!=0 || httpret<200||httpret>=300){
onEvent('downloadError');
//throw 'download error';
}else{
onEvent('downloadOK');
//let md5 = calcmd5(fs_readFileSync(localfile));
//console.log('md5='+md5);
let zip = new ZipFile();
if(zip.setSrc(localfile)){
zip.forEach((id,name,dir,sz)=>{
if(!dir){
let buf = zip.readFile(id);
//console.log("update "+name);
let fid = window.appcache.hashstr('/'+name); //TODO 测试
if(window.appcache.updateFile(fid,0,buf,false)){
//更新成功
onEvent('updating',null,name);
}else{
//更新失败。
/**
* 更新失败是指没有对应的dcc信息,或者文件内容与dcc中的不一致。
* 这个可以看做不是致命错误。
*/
onEvent("updateError", null,name);
//console.log("update error :"+name);
}
}
});
zip.close();
if(onEnd) onEnd(localfile);
}else{
console.log( "set zip src error!");
onEvent('unknownError');
}
}
},10,100000000);
}
loadApp(conch.presetUrl || "http://nativetest.layabox.com/layaplayer2.0.1/index.js");
+295
View File
@@ -0,0 +1,295 @@
/*
var canv = document.createElement('canvas');
var ctx = canv.getContext('2d');
ctx.save();
ctx.fillStyle = '#ff0000';
var img = new Image();
img.src = 'http://10.10.20.19:7777/a.jpg';
var bload = false;
img.onload = function(e) {
bload = true;
}
img.addEventListener('load', function() {
})
setInterval(() => {
if (bload) {
console.log('kkk');
ctx.drawImage(img._nativeObj, 0, 0, 100, 100, 0, 0, 100, 100);
}
}, 100);
*/
//require('websocket.js');
// downloadGetHeader('http://s0.tx.zxyh5.com/api/zxy/register.php',(buf)=>{
// alert('ok ' +buf);
// },(e,httprec)=>{
// alert('error');
// },100,100);
// class MyWebSocket{
// constructor(url:string){
// ConchWebSocket.call(this,url);
// }
// }
//var w1 = new MyWebSocket('aaa');
//alert(JSON.stringify(w1));
/*
var ws = new WebSocket('ws://10.10.20.241:7060');
ws.onopen=function(ev){
alert('kkk')
}
function md(e){
console.log('--------------');
}
document.body.addEventListener('mousedown',md);
document.body.addEventListener('mousedown',md);
*/
import test = require('./unitTest');
type Test = test.Test;
class AllTest {
/**
* 1. cloneNode 能正确clone
*/
test_clone(test: Test) {
try {
var b = document.createElement('audio');
var c = b.cloneNode(false);
c.addEventListener('', null);
} catch (e) {
alert('111')
test.err(`
cloneNode之后,应该有 addEventListener 函数。
`);
}
}
/**
* 测试event事件的派发
*/
testEventDispatch(test: Test) {
var called = false;
var canv = document.createElement('canvas');
document.body.appendChild(canv);
canv.addEventListener('mmousemove', (evt) => {
called = true;
});
var evt = new MouseEvent('mmousemove');
evt.clientX = 100;
evt.clientY = 100;
canv.dispatchEvent(evt);
test.eq(called, true, '事件应该能正确发送给canvas');
document.removeChild(canv);
test.neq(window.document._topElement, canv, 'removeChild之后,应该维护_topElement');
}
testEvent_phase(test: Test) {
var canv = document.createElement('canvas');
var result: number[] = [];
document.body.appendChild(canv);
document.addEventListener('mousedown', (evt) => {
result.push(1);
//alert('document capture event');
}, true);
document.body.addEventListener('mousedown', (evt) => {
//alert('body capture event');
result.push(2);
}, true);
canv.addEventListener('mousedown', (evt) => {
//alert('on mousedown');
result.push(3);
});
document.body.addEventListener('mousedown', (evt) => {
//alert('event bubble to body');
result.push(4);
});
document.addEventListener('mousedown', (evt) => {
//alert('event bubble to document');
result.push(5);
});
window.addEventListener('mousedown', (evt) => {
//alert('event bubble to window');
result.push(6);
});
var evt = new MouseEvent('mousedown');
evt.clientX = 100;
evt.clientY = 100;
canv.dispatchEvent(evt);
document.removeChild(canv);
}
testRuntimeVersion(test: Test) {
var rv = conchConfig.getRuntimeVersion();
var b = rv.indexOf('conch');
}
//测试ArrayBuffer的传递和管理
testABToC(test: Test) {
/*
while (true) {
var ab = new ArrayBuffer(1000);
var cp = conch.byteCompress(ab);
var ucp = conch.byteUnCompress(cp);
}
*/
}
//所有接口
testZip(test: Test) {
var zf = new ZipFile();
zf.setSrc('');
zf.forEach((id, name, dir, sz) => {
var ab = zf.readFile(id);
});
zf.close();
}
testFile(test: Test) {
var abv = new Uint32Array([1, 2, 3]);
fs_writeFileSync('d:/temp/ddd.d', abv.buffer);
var ab = fs_readFileSync('d:/temp/ddd.d');
var v1 = new Uint32Array(ab);
if (v1.byteLength != 12 || v1[0] != 1 || v1[1] != 2 || v1[2] != 3)
alert('error:' + arguments.callee.name);
alert(fs_readdirSync('d:/temp'));
//var ab = readBinFileSync('');
}
testWebSocket(test: Test) {
var ws = new WebSocket('');
}
testMD5(test: Test) {
var result = '2a1dd1e1e59d0a384c26951e316cd7e6';
test.eq(result, calcmd5(new Uint32Array([1, 2, 3]).buffer), 'md5计算不正确');
}
testPost(test: Test) {
var ab = new Uint32Array([0, 1, 2]);
conch._postUrl('http://localhost:8888/testpost', 1, ab.buffer, null, (buf) => {
}, (e) => {
}, () => {
return 0;
})
}
testImgErr(test: Test) {
var img = new Image();
img.src = '';
img.onerror = (e) => {
alert('onerror');
}
img.onload = (e) => {
alert('onload');
}
}
testUrlEncode(){
//http://115.159.92.56:8107/update/0?4089:21922|%5B%7B%22m%22%3A%22C_GSVR%22%2C%22c%22%3A0%2C%22p%22%3A%5Bnull%2C%22QQ%22%2Cnull%2C%221%2E0.2%22%5D%2C%22st%22%3A1460718545%7D%5D
//结果不能变
}
testCanvasInterface(){
var c = document.createElement('canvas');
c.width=100;//必须有这个属性,否则夺塔不行
}
testFontInfo(test:Test){
/*
var cn = new ConchNode();
cn.font('normal 100 16px Arial b 1 #ff0000 1 #00ff00 ');
test.eq(1,1,'');
cn.font(' ')
test.eq(1,1,'');
cn.font('')
test.eq(1,1,'');
cn.font('normal 100 28px Microsoft_YaHei 1 #444444 0');
cn.font('normal normal 18px 宋体 2 #000000 0 #000000');
test.eq(1,1,'');
*/
}
testFileReader(test:Test){
var f = new File('file:///d:/temp/test.sh');
var fr = new FileReader();
fr.onload=function(){
alert('ok '+fr.result);
}
fr.readAsText(f);
}
testFileReaderRemote(test:Test){
var f = new File('http://www.layabox.com/statics/images/laya/slider.jpg');
var fr = new FileReader();
fr.onload=function(){
alert('ok');
}
fr.readAsArrayBuffer(f);
}
testImgDecode(test:Test){
var img = new Image();
img.src='http://www.layabox.com/statics/images/laya/slider.jpg';
img.onload=function(){
alert('ok');
}
}
testWebGL1(test:Test){
var canv = document.createElement('canvas');
var gl = canv.getContext('webgl');
var cc=0;
function render(){
cc+=0.001;
gl.clearColor(0,cc,1,1);
gl.clear(0x4100);
gl.flush();
}
setInterval(render,10);
}
}
var xhr = new XMLHttpRequest();
xhr.open('GET','http://dtsg.games.layabox.com/assets/bootstrap/preloading.xml',true);
xhr.onload=function(e){
alert(e);
}
xhr.onerror=function(e){
alert('eee:'+e);
}
//test.testall(AllTest, "");
var canv = new HTMLCanvasElement();
document.body.appendChild(canv);
var gl = canv.getContext('webgl');
function r() {
console.log('kkkkk')
gl.clear(0);
gl.flush();
}
setInterval(r,10);
// // /ws.close(-1,'');
// var f = new conch_File('http://raganwald.com/2014/07/09/javascript-constructor-problem.html');
// var fr = new conch_FileReader();
// fr.onload=()=>{
// alert(fr.result);
// }
// fr.readAsText(f);
+12
View File
@@ -0,0 +1,12 @@
{
"compilerOptions": {
"module": "commonjs",
"noLib": true,
"target": "es6",
"noImplicitAny": false,
"rootDir": ".",
"outDir": "../../../Redist/scripts/",
"removeComments": true,
"sourceMap": false
}
}
+112
View File
@@ -0,0 +1,112 @@
var log = console.log;
export class Test {
desc = '';
constructor(desc: string) {
this.desc = desc;
}
verifyEq(a, b, desc: string) {
if (a instanceof Array && b instanceof Array) {
if (a.length != b.length)
throw desc + ' cant compare array with diffrent length! should:' + b.length + ' actual:' + a.length;
for (var i = 0; i < a.length; i++) {
if (a[i] != b[i])
throw desc + ' the ' + i + 'th data in array not equal';
}
}
else {
if (a == b) { } else { //用==判断是为了防止NaN
throw desc + ' should:' + b + ' actual:' + a;
}
}
}
eq = this.verifyEq;
verifyNEq(a, b, desc: string) {
if (a == b) {
throw desc + ' shouldnot:' + b + ' actual:' + a;
}
}
neq = this.verifyNEq;
err(desc: string) {
throw desc;
}
verifyEqRange(a, b, err: number, desc: string) {
if (typeof (a) == 'number') {
if (Math.abs(a - b) < err) { } else {//用==判断是为了防止NaN
throw desc + ' should:' + b + ' actual:' + a;
}
} else {
if (a.length != b.length)
throw desc + ' wrong data length,should:' + b.length + ' actual:' + a.length;
for (var i = 0; i < a.length; i++) {
if (Math.abs(a[i] - b[i]) > err)
throw desc + ' the ' + i + 'th data not equal';
}
}
}
eqr = this.verifyEqRange;
verifyThrow(func, desc) {
}
testall(all: Object, flag: string) {
var errnum = 0;
var oknum = 0;
var sum = 0;
var ps: string[] = [];
var obj = all;
/*
if( typeof(all)==='function'){
alert(1);
ps = Object.getOwnPropertyNames((<Function>all).prototype);
obj = new (<Function>all).prototype.constructor();
}
else if( typeof(all)==='object')
*/
if (typeof (all) === 'object') {
for (var f in all) {
//ps =<Object>all;// Object.getOwnPropertyNames((<any>all).__proto__);
//ps.forEach((f,i,a)=>{
sum++;
var bIgnore = false;
if (flag) {
bIgnore = true;
if (obj[f][flag])
bIgnore = false;
}
try {
if (!bIgnore)
obj[f].call(obj, this);
oknum++;
} catch (e) {
errnum++;
if (!e.name) //自定义的
log(" ERROR: " + f + " : " + e);
else {
log(e);
//log(e.stack);
}
}
}
}
log(`
======================================
${this.desc}
Test Result:
passed: ${oknum}
error: ${errnum}
`);
}
}
//testpac 是包含所有测试函数的对象
export function testall(testpack: Object, desc: string, flag?: string) {
new Test(desc).testall(testpack, flag);
}