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
+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
}
}
}
*/
+9
View File
@@ -0,0 +1,9 @@
class WindowBase64{
atob:(encodedString: string)=>string;
btoa:(rawString: string)=> string;
constructor(){
this.atob=function(){return null;};
this.btoa=function(){return null;};
}
}
window["WindowBase64"]=WindowBase64;
+57
View File
@@ -0,0 +1,57 @@
/**
* https://webbluetoothcg.github.io/web-bluetooth/
*/
enum VendorIDSource {
"bluetooth",
"usb"
};
interface BluetoothDeviceEventHandlers{
}
interface CharacteristicEventHandlers{
}
interface ServiceEventHandlers{
}
interface RequestDeviceOptions{
}
interface BluetoothAdvertisingData{
}
interface BluetoothRemoteGATTServer{
}
class BluetoothDevice {
id:string;
name:string;
adData:BluetoothAdvertisingData;
deviceClass:number;
vendorIDSource:VendorIDSource;
vendorID:number;
productID:number;
productVersion:number;
paired:boolean;
gatt:BluetoothRemoteGATTServer;
uuids:string;
connectGATT():Promise<any>{
return null;
}
}
class Bluetooth extends EventTarget implements BluetoothDeviceEventHandlers, CharacteristicEventHandlers, ServiceEventHandlers {
requestDevice(options:RequestDeviceOptions):Promise<BluetoothDevice>{
return null;
}
}
//applyMixins(Bluetooth,[EventTarget]);
+45
View File
@@ -0,0 +1,45 @@
///<reference path="./LayaConchRuntime.d.ts" />
class CanvasRenderingContext
{
private canvas:HTMLCanvasElement;
public gl:LayaGLContext;
public _width:number;
public _height:number;
constructor(c:HTMLCanvasElement) {
this.canvas = c;
this.gl = LayaGLContext.instance;
}
setSize(w:number,h:number){
if (this._width != w || this._height != h) {
this._width = w;
this._height = h;
if(this.canvas._isFirst)
{
this.gl.setMainContextSize(this._width,this._height);
}
}
}
clear():void{
this.gl.clearColor(0, 0, 0, 0);
this.gl.clear(LayaGLContext.COLOR_BUFFER_BIT | LayaGLContext.DEPTH_BUFFER_BIT | LayaGLContext.STENCIL_BUFFER_BIT);
}
toBase64(type:string, encoderOptions:number, callback:(data:string)=>void):void{
}
getImageData(x: number, y: number, w: number, h: number, callBack:(data:ArrayBuffer)=>void):void{
}
drawImage(...args):void
{
}
destroy():void {
this.canvas = null;
this.gl = null;
}
set font(fontName:string) {
window["_conchTextCanvas"].font = fontName;
}
get font():string {
return window["_conchTextCanvas"].font;
}
}
window["CanvasRenderingContext"]=CanvasRenderingContext;
+77
View File
@@ -0,0 +1,77 @@
enum LogLevel
{
Warn,
Error,
Debug,
Info,
Runtime
}
class Console {
constructor(){
}
/**
* 现在的v8不支持...,先去掉吧
*/
assert(test?: boolean, message?: string/*, ...optionalParams: any[]*/): void{
var c = _console;
/*
var optionalParams = [];
for (var _i = 2; _i < arguments.length; _i++) {
optionalParams[_i - 2] = arguments[_i];
}
*/
if(test){
c.log(3,message);//+optionalParams.join())
};
}
clear(): void{}
/**
* 输出执行到该行的次数,可选参数 label 可以输出在次数之前
*/
count(countTitle?: string): void{
}
debug(message?: string/*, ...optionalParams: any[]*/): void{
var c = _console; //这样就不怕别的对象执行这个函数的时候遇到this的问题了
c.log(LogLevel.Debug,message);//+optionalParams.join());
}
/**
* 将传入对象的属性,包括子对象的属性以列表形式输出
*/
dir(value?: any/*, ...optionalParams: any[]*/): void{
}
dirxml(value: any): void{
}
error(message?: any/*, ...optionalParams: any[]*/): void{
var c = _console;
c.log(LogLevel.Error,message);//+optionalParams.join());
}
group(groupTitle?: string): void{}
groupCollapsed(groupTitle?: string): void{}
groupEnd(): void{}
info(message?: any/*, ...optionalParams: any[]*/): void{
var c = _console;
c.log(LogLevel.Info,message);//+optionalParams.join());
}
log(message?: any/*, ...optionalParams: any[]*/): void{
var c = _console;
c.log(LogLevel.Info, message);//+optionalParams.join());
}
//msIsIndependentlyComposed(element: Element): boolean;
profile(reportName?: string): void{
}
profileEnd(): void{}
select(element: Element): void{}
time(timerName?: string): void{}
timeEnd(timerName?: string): void{}
trace(message?: any/*, ...optionalParams: any[]*/): void{
}
warn(message?: any/*, ...optionalParams: any[]*/): void{
var c = _console;
c.log(LogLevel.Warn,message);//+optionalParams.join());
}
}
+60
View File
@@ -0,0 +1,60 @@
interface Algorithm {
name?: string;
}
interface KeyAlgorithm {
name?: string;
}
interface CryptoKey {
algorithm: KeyAlgorithm;
extractable: boolean;
type: string;
usages: string[];
}
class SubtleCrypto {
decrypt(algorithm: string | Algorithm, key: CryptoKey, data: ArrayBufferView): any{
}
deriveBits(algorithm: string | Algorithm, baseKey: CryptoKey, length: number): any{
}
deriveKey(algorithm: string | Algorithm, baseKey: CryptoKey, derivedKeyType: string | Algorithm, extractable: boolean, keyUsages: string[]): any{
}
digest(algorithm: string | Algorithm, data: ArrayBufferView): any{
}
encrypt(algorithm: string | Algorithm, key: CryptoKey, data: ArrayBufferView): any{
}
exportKey(format: string, key: CryptoKey): any{
}
generateKey(algorithm: string | Algorithm, extractable: boolean, keyUsages: string[]): any{
}
importKey(format: string, keyData: ArrayBufferView, algorithm: string | Algorithm, extractable: boolean, keyUsages: string[]): any{
}
sign(algorithm: string | Algorithm, key: CryptoKey, data: ArrayBufferView): any{
}
unwrapKey(format: string, wrappedKey: ArrayBufferView, unwrappingKey: CryptoKey, unwrapAlgorithm: string | Algorithm, unwrappedKeyAlgorithm: string | Algorithm, extractable: boolean, keyUsages: string[]): any{
}
verify(algorithm: string | Algorithm, key: CryptoKey, signature: ArrayBufferView, data: ArrayBufferView): any{
}
wrapKey(format: string, key: CryptoKey, wrappingKey: CryptoKey, wrapAlgorithm: string | Algorithm): any{
}
}
class Crypto{
subtle=new SubtleCrypto();
getRandomValues(array: ArrayBufferView): ArrayBufferView{
return null;
}
}
+18
View File
@@ -0,0 +1,18 @@
/*
假装自己是nodejs
*/
function _process(){
this.pid=0;
this.cwd=function(){
return 'd:/temp';
}
this.mainModule = 'index.js';
this.argv=['conch.exe','index.js'];
this.version='1.3.1';
this._require=function(f){console.log('process require('+f+')');return function nop(){};}; //不能真的load
this._debugObject={};
}
window.process = new _process();
+457
View File
@@ -0,0 +1,457 @@
///<reference path="./LayaConchRuntime.d.ts" />
class NodeList extends Array {
constructor() {
super();
}
item(index: number): Node {
return this[index];
}
}
interface NodeListOf<TNode extends Node> extends NodeList {
length: number;
item(index: number): TNode;
[index: number]: TNode;
}
/**
* 这个是为了生成的.d.ts更方便
*/
interface Document {
createElement(tagName: "div"): HTMLDivElement;
createElement(tagName: "img"): HTMLImageElement;
createElement(tagName: "virtualBitmap"): any;
createElement(tagName: "audio"): HTMLAudioElement;
createElement(tagName: "input"): HTMLInputElement;
createElement(tagName: "textarea"): HTMLInputElement;
createElement(tagName: "canvas"): HTMLCanvasElement;
createElement(tagName: "script"): HTMLScriptElement;
createElement(tagName: "meta"): HTMLMetaElement;
createElement(tagName: string): HTMLElement | any;
}
class HTMLHeadElement extends HTMLElement {
profile: string;
constructor() {
super();
this.tagName='head';
this.__visible=false;
}
}
class HTMLCollection extends Array {
/**
* Sets or retrieves the number of objects in a collection.
*/
length: number;
/**
* Retrieves an object from various collections.
*/
item(nameOrIndex?: any, optionalIndex?: any): Element {
return this[nameOrIndex];
}
/**
* Retrieves a select object or an object from an options collection.
*/
namedItem(name: string): Element {
return null; //TODO
}
//[index: number]: Element;
}
class Document extends Node implements GlobalEventHandlers, NodeSelector, DocumentEvent {
private createMap = new Map<string, Function>();
//private _inputSingleObj: HTMLInputElement;//editbox的话,只允许一个。
private _frameEndEvt=new Event('frameend');
_cookiePath:string;
_topElement: HTMLElement;
body: HTMLElement;
documentElement: HTMLElement;
head: HTMLHeadElement;
location: Location;
defaultView:Window;
referrer:string;
//downloadlist:Array<any>=[];
scriptTextList:Array<any>=[];
private _loading:number=0;
private _evalNum:number=0;
// private _isdownload:boolean;
/**
* 用cache来提高效率,在这个环境下事件的路径基本是不变的。
*/
private _eventPathCache:Node[]=null;
/**
* Returns a reference to the collection of elements contained by the object.
*/
all: HTMLCollection=new HTMLCollection() ;
_elements:Array<any>=[];
querySelector: (selectors: string) => Element; //接口的空函数
querySelectorAll: (selectors: string) => NodeListOf<Element>;//接口的空函数
createEvent: (eventInterface: string) => Event;//为了 DocumentEvent 接口的空函数tes
onpointercancel: (ev: PointerEvent) => any;
onpointerdown: (ev: PointerEvent) => any;
onpointerenter: (ev: PointerEvent) => any;
onpointerleave: (ev: PointerEvent) => any;
onpointermove: (ev: PointerEvent) => any;
onpointerout: (ev: PointerEvent) => any;
onpointerover: (ev: PointerEvent) => any;
onpointerup: (ev: PointerEvent) => any;
constructor() {
super();
window.document=this;
this.defaultView=window;
var cm = this.createMap;
cm.set('div', this.create_div);
cm.set('img', this.create_img);
cm.set('image', this.create_img);
cm.set('canvas', this.create_canvas);
cm.set('audio', this.create_audio);
cm.set('input', this.create_input);
cm.set('textarea', this.create_input);
cm.set('video',this.create_video);
cm.set('script',this.create_script);
cm.set('meta',this.create_meta);
var html = new HTMLElement();
var ww = getInnerWidth();
var wh = getInnerHeight();
html.clientWidth = ww;
html.clientHeight = wh;
html.tagName = "HTML";
html.ownerDocument = this;
this.documentElement = html;
this._topElement = html;
this.appendChild(this.documentElement);
var body = new HTMLBodyElement();
body.ownerDocument = this;
this.body = body;
this.documentElement.appendChild(this.body);
this.head = new HTMLHeadElement();
this.documentElement.appendChild(this.head);
this.dispatchEvent = this._dispatchEvent.bind(this);
this._frameEndEvt.bubbles=false;
this.nodeType=9;
this.location=window.location;
var _t:Document=this;
var temp;
/*this.addEventListener("listDownload",function(e){
if(_t._isdownload)return;
_t._isdownload=true;
if(_t.downloadlist.length==0){
_t._isdownload=false;
return;
}
_t._downloadAysn();
});*/
}
public setReferrer(s):void
{
this.referrer=s;
}
public uploadScript(d:any)
{
var _t:Document=this;
d.i=this._loading;
this._loading++;
if(d.src){
console.log("_downloadAysn:temp.src"+d.src);
window.downloadfile(d.src,false,function(data){
d._stext=data+"\n//@ sourceURL="+d.src;
_t._downloadOk(d);
},function(){
var e:Event=new Event("error");
e.target=e.currentTarget=d.obj;
d.obj.onerror&& d.obj.onerror(e);
//_t._evalNum++;
//_t._downloadOk(d);
});
}
else{
d._stext=d.text;
_t._downloadOk(d);
}
}
private _downloadOk(d:any):void
{
this.scriptTextList[d.i]=d;
for(var i:number=this._evalNum,len:number=this.scriptTextList.length;i<len;i++)
{
var t:any=this.scriptTextList[i];
if(!t) return;
console.log(">>>>>>>>>>>>>>>eval"+t.src);
var t1=Date.now();
window.evalJS(t._stext);
console.log(">>>>>>>>>>>>>>>>>eval take time:"+(Date.now()-t1));
var e:Event=new Event("load");
e.target=e.currentTarget=t.obj;
t.obj.onload&& t.obj.onload(e);
this._evalNum++;
}
if(this._loading==this._evalNum){
this._loading=this._evalNum=0;
this.scriptTextList.length=0;
}
}
/* private _downloadAysn():void
{
console.log(">>>>>>>>"+this.downloadlist.length);
var temp=this.downloadlist.shift();
var _t:Document=this;
if(temp)
{
if(temp.src)
{
console.log("_downloadAysn:temp.src"+temp.src);
window.downloadfile(temp.src,false,function(data){
var e:Event=new Event("load");
e.target=e.currentTarget=temp.obj;
window.eval(data+"\n//@ sourceURL="+temp.src);
temp.obj.onload&& temp.obj.onload(e);
if(_t.downloadlist.length!=0)
_t._downloadAysn();
else{
_t._isdownload=false;
}
},function(){
var e:Event=new Event("error");
e.target=e.currentTarget=temp.obj;
temp.obj.onerror&& temp.obj.onerror(e);
});
}
else
{
window.eval(temp.text);
if(_t.downloadlist.length!=0){
_t._downloadAysn();
}
else{
_t._isdownload=false;
}
}
}
}*/
//addEventListener:(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean)=>void;
pickElement(screenx: number, screeny: number): HTMLElement {
//var top = this._topElement;
//console.log(top.clientLeft+','+top.clientWidth);
return this._topElement;
}
createElement(tagName: string): HTMLElement {
tagName=tagName.toLowerCase();
var f = this.createMap.get(tagName);
var ret: HTMLElement = null;
if (f) {
ret = f.call(this);
} else {
//throw 'unsupported tagname:' + tagName;
return new div();
}
//ret.ownerDocument = this;
return ret;
}
createElementNS(tagName:string):HTMLElement{
return this.createElement(tagName);
}
private create_div(): HTMLDivElement {
var ret = new HTMLDivElement();
ret.ownerDocument = this;
return ret;
}
private create_img(): HTMLImageElement {
var ret = new HTMLImageElement();
ret.ownerDocument = this;
return ret;
}
private create_canvas(): HTMLCanvasElement {
var ret = new HTMLCanvasElement();
ret.ownerDocument = this;
return ret;
}
private create_audio(): HTMLAudioElement {
var ret = new HTMLAudioElement();
ret.ownerDocument = this;
return ret;
}
private create_input(): HTMLInputElement {
var rs=new HTMLInputElement();
rs.ownerDocument = this;
return rs;
}
private create_video():HTMLVideoElement{
var ret=new HTMLVideoElement();
ret.ownerDocument=this;
return ret;
}
private create_script():HTMLScriptElement{
var ret=new HTMLScriptElement();
ret.ownerDocument=this;
return ret;
}
private create_meta():HTMLMetaElement{
var ret=new HTMLMetaElement();
ret.ownerDocument=this;
return ret;
}
createDocumentFragment():HTMLDivElement
{
//TODO
return new HTMLDivElement();
}
onframeend(){
//this._dispatchEvent(this._frameEndEvt);
this._frameEndEvt.eventPhase = Event.AT_TARGET;//只要at
super._fireEventListeners(this._frameEndEvt);
}
_dispatchEvent(evt: Event): boolean{
//
var ancestores: Node[] = null;
if (evt.target)
ancestores = (<Node>evt.target).getAncestorsNode();
if (ancestores == null || ancestores.length == 0) {
//只有document,直接触发。
return super._dispatchEvent(evt);
}
var ancLen = ancestores.length;
//捕获阶段
evt.eventPhase = Event.CAPTURING_PHASE;
var stop = (function(): boolean {
window.dispatchEvent(evt);
if (evt._propagationStopped)
return true;
for (var i = ancLen - 1; i >= 0; i--) {
var cnode = ancestores[i];
evt.currentTarget = cnode;
cnode.fireEventListeners(evt);
if (evt._propagationStopped) {
return true;
}
}
return false;
})();
//at 阶段
if (!stop) {
evt.eventPhase = Event.AT_TARGET;
evt.currentTarget = evt.target;
stop = (function(): boolean {
evt.target.fireEventListeners(evt);
if (evt._propagationStopped)
return true;
return false;
})();
}
//冒泡阶段
if(!stop && !evt.cancelable){
evt.eventPhase = Event.BUBBLING_PHASE;
for (var i = 0; i <ancLen; i++) {
var cnode = ancestores[i];
evt.currentTarget = cnode;
cnode.fireEventListeners(evt);
if (evt._propagationStopped) {
stop = true;
break;
}
}
if( !stop ){
evt.currentTarget=window;
window.dispatchEvent(evt);
}
}
//是否阻止缺省处理
if( evt.preventDefault ){
}
return true;
}
//cookie:string;
set cookie(v: string) {
var t:_Cookie=_Cookie.addCookie(v);
if(t&&_Cookie.pushCookie(t)){
_Cookie.flush();
}
}
get cookie(): string {
return _Cookie.toLocalString();
}
loadCookie(): boolean {
this._cookiePath=window.localStorage.fileNamePre+"_cookie.txt";
var temp=readFileSync(this._cookiePath,"utf8");
//alert(temp);
_Cookie.init(temp);
return true;
}
open(url?: string, name?: string, features?: string, replace?: boolean): Document {
throw 'not implements'
}
getElementsByTagName(tagname: string): NodeListOf<Element> {
var d=new NodeList();
if("body"==tagname)
d.push(this.body);
else if("head"==tagname)
d.push(this.head);
return <NodeListOf<Element>>d;
}
onkeydown(ev: KeyboardEvent): any {
}
onkeypress(ev: KeyboardEvent): any {
}
onkeyup(ev: KeyboardEvent): any {
}
onmousedown(ev: MouseEvent): any {
}
onmousemove(ev: MouseEvent): any { }
onmouseout(ev: MouseEvent): any { }
onmouseover(ev: MouseEvent): any { }
onmouseup(ev: MouseEvent): any { }
onmousewheel(ev: MouseWheelEvent): any { }
ontouchcancel(ev: TouchEvent): any { }
ontouchend(ev: TouchEvent): any { }
ontouchmove(ev: TouchEvent): any { }
ontouchstart(ev: TouchEvent): any { }
getElementById(elementId: string): HTMLElement{
for( var i=0,sz=this.all.length; i<sz; i++){
var c:Element = this.all[i];
if(c.id===elementId)
return <HTMLElement>c;
}
//debugger;
// throw 'not implemented';
return null;
}
getElementsByClassName(classNames: string): NodeListOf<Element>{
throw 'not implemented';
//return null;
}
getElementsByName(name:string):Array<any>
{
return document._elements[name]||[];
}
write(value):void
{
console.log("The document don't support write function!!!");
}
}
applyMixins(Document, [Node, GlobalEventHandlers, NodeSelector, DocumentEvent]);
+171
View File
@@ -0,0 +1,171 @@
class DOMParser
{
private _parser:_DOMParser;
private _src:string;
private _onload:()=>void;
private _onerror:()=>void;
private _result:_jsXmlDocument;
constructor() {
this._parser=new _DOMParser();
}
set src(s)
{
this._src=location.resolve(s);
//this._src = encodeURI(this._src);
this._parser.src=this._src;
}
get src()
{
return this._src;
}
set onload(callback)
{
this._parser._onload=callback;
this._parser.onload=this.nativeObjOnload;
}
private nativeObjOnload()
{
this._onload();
}
get onload()
{
return this._parser._onload;
}
set onerror(callback)
{
this._parser._onerror=callback;
this._parser.onerror=this.nativeObjOnerror;
}
private nativeObjOnerror()
{
this._onerror();
}
get onerror()
{
return this._parser._onerror;
}
private static initXMl(xml:_XmlNode):_jsXmlNode
{
var result:_jsXmlNode;
if(!xml)
{
var temp=new _jsXmlNode();
temp.nodeName="parsererror";
temp.textContent="parsererror error";
result=new _jsXmlNode();
result.childNodes[0]=temp;
return result;
}
result=new _jsXmlNode();
result.nodeName=xml.nodeName;
result.nodeValue=xml.nodeValue;
result.nodeType=1;
if(result.nodeName=="#cdata-section")
{
result.nodeType=3;
result.nodeName="#text";
}
result.textContent=xml.textContent;
var attrs=xml.attributes;
for(var i=0,sz1=attrs.length;i<sz1;i++)
{
var attr=attrs[i];
var key=attr.nodeName;
var tempAttr=new _jsXmlAttr(key,attr.nodeValue);
result.attributes[i]=tempAttr;
result.attributes[key]=tempAttr;
}
var childs=xml.childNodes;
for(var i=0,sz1=childs.length;i<sz1;i++)
{
var chd=childs[i];
var nodeName=chd.nodeName;
result.childNodes[i]=DOMParser.initXMl(chd);
}
return result;
}
parseFromString(s:string,t:string):_jsXmlDocument
{
var xml= this._parser.parseFromString(s,t);
var root=new _jsXmlDocument();
root.childNodes[0]=DOMParser.initXMl(xml.childNodes[0]);
return root;
}
getResult():_jsXmlDocument
{
if(!this._result)
{
this._result=new _jsXmlDocument();
this._result.childNodes[0]=DOMParser.initXMl(this._parser.getResult().childNodes[0]);
}
return this._result;
}
}
window["DOMParser"] =DOMParser;
class _jsXmlAttr
{
nodeName:string;
nodeValue:string;
textContent:string;
constructor(key:string,value:string)
{
this.nodeName=key;
this.nodeValue=this.textContent=value;
}
get value()
{
return this.nodeValue;
}
}
class _jsXmlNode extends _jsXmlAttr
{
childNodes:Array<_jsXmlNode>;
attributes:Array<_jsXmlAttr>;
nodeType:number;
get firstChild()
{
return this.childNodes?this.childNodes[0]:null;
}
constructor()
{
super("","");
this.childNodes=[];
this.childNodes["item"]=function(i:any)
{
return this[i];
}
this.attributes=[];
}
getElementsByTagName(name:string):Array<_jsXmlNode>
{
var result:Array<_jsXmlNode>=[];
if(this.nodeName==name)
result.push(this);
else
{
for(var i=0,n=this.childNodes.length;i<n;i++)
{
var son=this.childNodes[i];
result=result.concat(son.getElementsByTagName(name));
}
}
return result;
}
getAttribute(name:string):string
{
var attr=this.attributes[name];
return attr?attr["nodeValue"]:"";
}
}
class _jsXmlDocument extends _jsXmlNode
{
}
File diff suppressed because it is too large Load Diff
+598
View File
@@ -0,0 +1,598 @@
interface EventListener {
(evt: Event): void;
}
interface EventListenerObject {
handleEvent(evt: Event): void;
}
declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject;
interface EventHandler {
obj: Object;
listener: EventListenerOrEventListenerObject;
useCapture: boolean;
}
interface EventInit {
bubbles?: boolean;
cancelable?: boolean;
}
interface GlobalEventHandlers {
addEventListener(type: "pointercancel", listener: (ev: PointerEvent) => any, useCapture?: boolean): void;
addEventListener(type: "pointerdown", listener: (ev: PointerEvent) => any, useCapture?: boolean): void;
addEventListener(type: "pointerenter", listener: (ev: PointerEvent) => any, useCapture?: boolean): void;
addEventListener(type: "pointerleave", listener: (ev: PointerEvent) => any, useCapture?: boolean): void;
addEventListener(type: "pointermove", listener: (ev: PointerEvent) => any, useCapture?: boolean): void;
addEventListener(type: "pointerout", listener: (ev: PointerEvent) => any, useCapture?: boolean): void;
addEventListener(type: "pointerover", listener: (ev: PointerEvent) => any, useCapture?: boolean): void;
addEventListener(type: "pointerup", listener: (ev: PointerEvent) => any, useCapture?: boolean): void;
addEventListener(type: "wheel", listener: (ev: WheelEvent) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
}
class GlobalEventHandlers implements GlobalEventHandlers {
constructor() {
}
onpointercancel(ev: PointerEvent): any {
return null;
}
onpointerdown(ev: PointerEvent): any {
return null;
}
onpointerenter(ev: PointerEvent): any {
return null;
}
onpointerleave(ev: PointerEvent): any {
return null;
}
onpointermove(ev: PointerEvent): any {
return null;
}
onpointerout(ev: PointerEvent): any {
return null;
}
onpointerover(ev: PointerEvent): any {
return null;
}
onpointerup(ev: PointerEvent): any {
return null;
}
}
class ErrorEvent implements ErrorEvent {
constructor() {
}
initErrorEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, messageArg: string, filenameArg: string, linenoArg: number): void {
//TODO
}
}
class Event {
//TODO 下面的属性应该是只读的。
/**
* 是否允许冒泡
*/
bubbles: boolean;
cancelBubble: boolean; //阻止冒泡
/**
* 如果为false,则不允许cancle
*/
cancelable: boolean;
currentTarget: EventTarget;
defaultPrevented: boolean;
eventPhase: number;
isTrusted: boolean;
returnValue: boolean;
srcElement: Element;
target: EventTarget;
timeStamp: number;
type: string;
_propagationStopped = false;
constructor(type: string, eventInitDict?: EventInit) {
this.type = type;
this.timeStamp = Date.now();
this.bubbles = false;//默认为false
this.cancelable = false;
this.eventPhase = Event.AT_TARGET;
if (eventInitDict) {
this.bubbles = eventInitDict.bubbles;
this.cancelable = eventInitDict.cancelable;
}
}
initEvent(eventTypeArg: string, canBubbleArg: boolean, cancelableArg: boolean): void {
this.type = eventTypeArg;
this.bubbles = canBubbleArg;
this.cancelable = cancelableArg;
}
preventDefault(): void {
if (!this.cancelable)
return;
this.defaultPrevented = true;
}
stopImmediatePropagation(): void {
}
/**
* 阻止事件的传播。但是不阻止在本节点的传播
*/
stopPropagation(): void {
this._propagationStopped = true;
}
static AT_TARGET = 2; //处于目标阶段
static BUBBLING_PHASE = 3; //冒泡阶段
static CAPTURING_PHASE = 1; //捕获阶段
}
var _lbEvent= window['Event'] = Event;
interface _EventTarget {
addEventListener(type: "mousedown", listener: (ev: MouseEvent) => any, useCapture?: boolean): void;
addEventListener(type: "mouseenter", listener: (ev: MouseEvent) => any, useCapture?: boolean): void;
addEventListener(type: "mouseleave", listener: (ev: MouseEvent) => any, useCapture?: boolean): void;
addEventListener(type: "mousemove", listener: (ev: MouseEvent) => any, useCapture?: boolean): void;
addEventListener(type: "mouseout", listener: (ev: MouseEvent) => any, useCapture?: boolean): void;
addEventListener(type: "mouseover", listener: (ev: MouseEvent) => any, useCapture?: boolean): void;
addEventListener(type: "mouseup", listener: (ev: MouseEvent) => any, useCapture?: boolean): void;
addEventListener(type: "mousewheel", listener: (ev: MouseWheelEvent) => any, useCapture?: boolean): void;
addEventListener(type: "pointercancel", listener: (ev: PointerEvent) => any, useCapture?: boolean): void;
addEventListener(type: "pointerdown", listener: (ev: PointerEvent) => any, useCapture?: boolean): void;
addEventListener(type: "pointerenter", listener: (ev: PointerEvent) => any, useCapture?: boolean): void;
addEventListener(type: "pointerleave", listener: (ev: PointerEvent) => any, useCapture?: boolean): void;
addEventListener(type: "pointermove", listener: (ev: PointerEvent) => any, useCapture?: boolean): void;
addEventListener(type: "pointerout", listener: (ev: PointerEvent) => any, useCapture?: boolean): void;
addEventListener(type: "pointerover", listener: (ev: PointerEvent) => any, useCapture?: boolean): void;
addEventListener(type: "pointerup", listener: (ev: PointerEvent) => any, useCapture?: boolean): void;
addEventListener(type: "touchcancel", listener: (ev: TouchEvent) => any, useCapture?: boolean): void;
addEventListener(type: "touchend", listener: (ev: TouchEvent) => any, useCapture?: boolean): void;
addEventListener(type: "touchmove", listener: (ev: TouchEvent) => any, useCapture?: boolean): void;
addEventListener(type: "touchstart", listener: (ev: TouchEvent) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
dispatchEvent(evt: Event): boolean;
removeEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
}
var _lbMap=Map;
class EventTarget implements _EventTarget {
protected _evtMaps = new _lbMap<string, EventHandler[]>();
dispatchEvent:(evt: Event)=>boolean ;
fireEventListeners:(evt: Event)=>void;
constructor(){
this.dispatchEvent = this._dispatchEvent.bind(this);
//this.addEventListener=this._addEventListener.bind(this);
this.fireEventListeners = this._fireEventListeners.bind(this);
}
/**
* TODO
* 没有考虑 useCapture
*/
addEventListener (type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void {
//console.log('addevtlistener:' + type);
var listeners = this._evtMaps.get(type) || [];
listeners.push({ obj: this, listener: listener, useCapture: useCapture });
this._evtMaps.set(type, listeners);
}
/*
addEventListener (type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void{
}
*/
/**
* @param
* @return boolean fase 则不允许触发缺省处理,表示有人曾经调用过 preventDefault.
*/
protected _dispatchEvent(evt: Event): boolean {
this.fireEventListeners(evt);
return !evt.defaultPrevented;
}
/**
* 要考虑一个listener被add了多次的情况
*/
removeEventListener = (type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void => {
var listeners = this._evtMaps.get(type);
if(!listeners)
return;
var newlisteners = [];
for (var i = 0, sz = listeners.length; i < sz; i++) {
if (listeners[i].listener != listener || listeners[i].useCapture != useCapture) {
newlisteners.push(listeners[i]);
}
}
this._evtMaps.set(type, newlisteners);
}
/**
* 需要绑定this
*/
protected _fireEventListeners (evt: Event):void {
var listeners: EventHandler[] = this._evtMaps.get(evt.type);
if (listeners) {
listeners.forEach(function(listener: EventHandler) {
switch (evt.eventPhase) {
case Event.CAPTURING_PHASE:
if (listener.useCapture && listener.listener)
(<any>listener.listener).call(listener.obj, evt);
break;
case Event.AT_TARGET:
if (listener.listener)
(<any>listener.listener).call(listener.obj, evt);
break;
case Event.BUBBLING_PHASE:
if (!listener.useCapture && listener.listener)
(<any>listener.listener).call(listener.obj, evt);
break;
}
});
}
}
}
interface UIEventInit extends EventInit {
view?: any; //window
detail?: number;
}
interface SharedKeyboardAndMouseEventInit extends UIEventInit {
ctrlKey?: boolean;
shiftKey?: boolean;
altKey?: boolean;
metaKey?: boolean;
keyModifierStateAltGraph?: boolean;
keyModifierStateCapsLock?: boolean;
keyModifierStateFn?: boolean;
keyModifierStateFnLock?: boolean;
keyModifierStateHyper?: boolean;
keyModifierStateNumLock?: boolean;
keyModifierStateOS?: boolean;
keyModifierStateScrollLock?: boolean;
keyModifierStateSuper?: boolean;
keyModifierStateSymbol?: boolean;
keyModifierStateSymbolLock?: boolean;
}
class UIEvent extends Event {
constructor(type: string, eventInitDict?: UIEventInit) {
super(type);
this.bubbles = true; //UIEVent的默认为true
if (eventInitDict) {
this.initUIEvent(type, eventInitDict.bubbles, eventInitDict.cancelable, eventInitDict.view, eventInitDict.detail);
}
}
detail: number;
view: Window;
initUIEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number): void {
this.type = typeArg;
this.cancelable = canBubbleArg;
this.cancelable = cancelableArg;
this.view = viewArg;
this.detail = detailArg;
}
}
interface KeyboardEventInit extends SharedKeyboardAndMouseEventInit {
key?: string;
location?: number;
repeat?: boolean;
}
interface MouseEventInit extends SharedKeyboardAndMouseEventInit {
screenX?: number;
screenY?: number;
clientX?: number;
clientY?: number;
button?: number;
buttons?: number;
relatedTarget?: EventTarget;
}
interface PointerEventInit extends MouseEventInit {
pointerId?: number;
width?: number;
height?: number;
pressure?: number;
tiltX?: number;
tiltY?: number;
pointerType?: string;
isPrimary?: boolean;
}
interface WheelEventInit extends MouseEventInit {
deltaX?: number;
deltaY?: number;
deltaZ?: number;
deltaMode?: number;
}
class PointerEvent {
constructor(typeArg: string, eventInitDict?: PointerEventInit) {
}
}
class MouseEvent extends UIEvent {
altKey: boolean;
button: number;
buttons: number;
clientX: number;
clientY: number;
ctrlKey: boolean;
fromElement: Element;
layerX: number;
layerY: number;
metaKey: boolean;
movementX: number;
movementY: number;
offsetX: number;
offsetY: number;
pageX: number;
pageY: number;
relatedTarget: EventTarget;
screenX: number;
screenY: number;
shiftKey: boolean;
toElement: Element;
which: number;
x: number;
y: number;
constructor(typeArg: string, eventInitDict?: MouseEventInit) {
super(typeArg, eventInitDict);
if (eventInitDict) {
for (var v in eventInitDict) {
this[v] = eventInitDict[v];
}
}
}
getModifierState(keyArg: string): boolean {
//not implements
return false;
}
initMouseEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number,
clientXArg: number, clientYArg: number, ctrlKeyArg: boolean, altKeyArg: boolean, shiftKeyArg: boolean, metaKeyArg: boolean,
buttonArg: number, relatedTargetArg: EventTarget): void {
var args = arguments;
['type', 'bubbles', 'cancelable', 'view', 'detail', 'screenX', 'screenY', 'clientX', 'clientY', 'ctrlKey', 'altKey', 'shiftKey', 'metaKey', 'button', 'relatedTarget'].forEach((v, i, a) => {
this[v] = args[i];
});
}
}
var _lbMouseEvent= window['MouseEvent'] = MouseEvent;
class MouseWheelEvent extends MouseEvent {
wheelDelta: number;
wheelDeltaX: number;
wheelDeltaY: number;
initMouseWheelEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, buttonArg: number, relatedTargetArg: EventTarget, modifiersListArg: string, wheelDeltaArg: number): void {
}
constructor() {
super("mousewheel");
}
}
class WheelEvent extends MouseEvent {
deltaMode: number;
deltaX: number;
deltaY: number;
deltaZ: number;
getCurrentPoint(element: Element): void {
}
initWheelEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, buttonArg: number, relatedTargetArg: EventTarget, modifiersListArg: string, deltaXArg: number, deltaYArg: number, deltaZArg: number, deltaMode: number): void {
}
constructor(typeArg: string, eventInitDict?: WheelEventInit) {
super(typeArg, eventInitDict);
if (eventInitDict) {
this.deltaMode = eventInitDict.deltaMode;
this.deltaX = eventInitDict.deltaX;
this.deltaY = eventInitDict.deltaY;
this.deltaZ = eventInitDict.deltaZ;
}
}
static DOM_DELTA_LINE = 1;
static DOM_DELTA_PAGE = 2;
static DOM_DELTA_PIXEL = 0;
}
class Touch {
clientX: number;
clientY: number;
identifier: number;
pageX: number;
pageY: number;
screenX: number;
screenY: number;
target: EventTarget;
constructor(){
}
}
class TouchList extends Array {
item(index: number): Touch {
return this[index];
}
}
interface TouchEvent extends UIEvent {
altKey: boolean;
changedTouches: TouchList;
ctrlKey: boolean;
metaKey: boolean;
shiftKey: boolean;
targetTouches: TouchList;
touches: TouchList;
new(type: number, id: number, name: string, x: number, y: number):TouchEvent;
}
/*
var exp={exp:null};
(function(exp:{exp:any}) {
'use strict';
//这个需要闭包
var APP_TOUCH_DOWN = 0;
var APP_TOUCH_UP = 1;
var APP_TOUCH_MOV = 2;
var APP_TOUCH_PT_DOWN = 5;
var APP_TOUCH_PT_UP = 6;
var m_vTouchs: Touch[] = []
exp.exp = class TouchEvent extends UIEvent {
altKey = false;
changedTouches: Touch[] = [];// TouchList;
ctrlKey = false;
metaKey = false;
shiftKey = false;
targetTouches: Touch[] = [];// TouchList;
touches: Touch[] = [];
constructor(type: number, id: number, name: string, x: number, y: number) {
super('');
var touch = new Touch();
touch.identifier = id;
touch.pageX = touch.screenX = touch.clientX = x;
touch.pageY = touch.screenY = touch.clientY = y;
this.touches.push(touch);
switch(type) {
case APP_TOUCH_DOWN:
case APP_TOUCH_PT_DOWN:
m_vTouchs.push(touch);
break;
case APP_TOUCH_PT_UP: {
//DEL. 已知事件都是一个一个发送的。
var epos = 0;
var tnum = m_vTouchs.length;
while (epos < tnum) {
var ce = m_vTouchs[epos];
if (ce.identifier == id) {
break;
}
epos++;
}
if (epos >= tnum) {
//error not find
} else {
m_vTouchs.splice(epos, 1);
}
}
break;
case APP_TOUCH_MOV: {
//修改. 已知事件都是一个一个发送的。
var tnum = m_vTouchs.length;
var ti = 0;
while (ti < tnum) {
var ce = m_vTouchs[ti];
if (ce.identifier == id) {
m_vTouchs[ti] = touch;
break;
}
ti++;
}
}
break;
case APP_TOUCH_UP:
m_vTouchs = [];
break;
}
this.touches = m_vTouchs;
switch (type) {
case 0:
case 5:
this.type = "touchstart";
break;
case 1:
case 6:
this.type = "touchend";
break;
case 2:
this.type = "touchmove";
break;
}
}
}
})(exp);
var TouchEvent:TouchEvent = <TouchEvent>((<any>exp).exp);
*/
interface DeviceAcceleration {
x: number;
y: number;
z: number;
}
interface DeviceRotationRate {
alpha: number;
beta: number;
gamma: number;
}
interface DeviceAccelerationDict {
x?: number;
y?: number;
z?: number;
}
interface DeviceRotationRateDict {
alpha?: number;
beta?: number;
gamma?: number;
}
class DeviceMotionEvent extends Event {
acceleration: DeviceAcceleration;
accelerationIncludingGravity: DeviceAcceleration;
interval: number;
rotationRate: DeviceRotationRate;
constructor() {
super('devicemotion');
}
initDeviceMotionEvent(type: string, bubbles: boolean, cancelable: boolean, acceleration: DeviceAccelerationDict, accelerationIncludingGravity: DeviceAccelerationDict, rotationRate: DeviceRotationRateDict, interval: number): void {
}
}
window["DeviceMotionEvent"]=DeviceMotionEvent;
class DeviceOrientationEvent extends Event {
absolute: boolean;
alpha: number;
beta: number;
gamma: number;
constructor() {
super('deviceorientation');
}
initDeviceOrientationEvent(type: string, bubbles: boolean, cancelable: boolean, alpha: number, beta: number, gamma: number, absolute: boolean): void {
}
}
window["DeviceOrientationEvent"]=DeviceOrientationEvent;
class DocumentEvent {
constructor() {
}
createEvent(eventInterface: string): Event {
return null;
}
}
class ProgressEvent extends Event {
lengthComputable: boolean;
loaded: number;
total: number;
constructor(type:string) {
super(type);
}
initProgressEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, lengthComputableArg: boolean, loadedArg: number, totalArg: number): void {
//TODO
this.type=typeArg;
this.cancelBubble=canBubbleArg;
this.cancelable=cancelableArg;
this.lengthComputable=lengthComputableArg;
this.loaded=loadedArg;
this.total=totalArg;
}
}
var _lbProgressEvent=window["ProgressEvent"]=ProgressEvent;
+20
View File
@@ -0,0 +1,20 @@
interface GamepadButton {
pressed: boolean;
value: number;
}
class Gamepad{
axes: number[];
buttons: GamepadButton[];
connected: boolean;
id: string;
index: number;
mapping: string;
timestamp: number;
}
class GamepadEvent extends Event {
gamepad: Gamepad;
}
+324
View File
@@ -0,0 +1,324 @@
/**
* 全局变量
*/
enum GL_CAPS
{
NONE = 0,
TEXTURE_COMPRESSION_PVR = 1 << 1,
TEXTURE_COMPRESSION_ETC1 = 1 << 2,
TEXTURE_COMPRESSION_ETC2 = 1 << 3,
TEXTURE_TPG = 1 << 5,
INSTANCEING = 1 << 6,
}
interface ErrorEventHandler {
(message: string, filename?: string, lineno?: number, colno?: number, error?:Error): void;
}
interface LayaBox{
devinfo:{resolution:string,mac:string,imei:string,imsi:string,os:string,osversion:string,phonemodel:string}
getDeviceInfo():any;
}
interface Window extends EventTarget, WindowTimers{
layaHtml5:any;
screen:Screen;
SetupWebglContext();
downloadfile(url:string, force:boolean, onok:(data:string)=>void, onerr:()=>void);
loadLocalStorage(url:string):Storage;
XMLHttpRequest:typeof XMLHttpRequest;
innerHeight: number;
innerWidth: number;
outerWidth: number;
outerHeight:number;
performance:any;
localStorage:Storage;
sessionStorage:WindowSessionStorage;
location:Location;
document:Document;
Audio:typeof HTMLAudioElement;
crypto:Crypto;
console:Console;
pageXOffset: number;
pageYOffset: number;
Image:typeof HTMLImageElement;
layabox:LayaBox;
layaDoc:any;
ConchVirtualBitmap:any; //TODO 临时
alert:(message?: any)=> void
onerror:(message: string, filename?: string, lineno?: number, colno?: number, error?:Error)=>void;
onload: (ev: Event) => any;
open(url?: string, target?: string, features?: string, replace?: boolean): Window;
onresize: (ev: UIEvent) => any;
requestAnimationFrame(callback: FrameRequestCallback): number;
cancelAnimationFrame(handle: number): void;
process:any;
WebSocket:typeof WebSocket;
parent: Window;
frames: Window;
eval(s:any);
evalJS(s:any);
focus():void;
navigator: Navigator;
devicePixelRatio: number;
getComputedStyle(ele:Element,parm:any):any
addEventListener(type: "devicemotion", listener: (ev: DeviceMotionEvent) => any, useCapture?: boolean): void;
addEventListener(type: "deviceorientation", listener: (ev: DeviceOrientationEvent) => any, useCapture?: boolean): void;
addEventListener(type: "message", listener: (ev: MessageEvent) => any, useCapture?: boolean): void;
addEventListener(type: "mousedown", listener: (ev: MouseEvent) => any, useCapture?: boolean): void;
addEventListener(type: "mouseenter", listener: (ev: MouseEvent) => any, useCapture?: boolean): void;
addEventListener(type: "mouseleave", listener: (ev: MouseEvent) => any, useCapture?: boolean): void;
addEventListener(type: "mousemove", listener: (ev: MouseEvent) => any, useCapture?: boolean): void;
addEventListener(type: "mouseout", listener: (ev: MouseEvent) => any, useCapture?: boolean): void;
addEventListener(type: "mouseover", listener: (ev: MouseEvent) => any, useCapture?: boolean): void;
addEventListener(type: "mouseup", listener: (ev: MouseEvent) => any, useCapture?: boolean): void;
addEventListener(type: "mousewheel", listener: (ev: MouseWheelEvent) => any, useCapture?: boolean): void;
addEventListener(type: "offline", listener: (ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: "online", listener: (ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: "orientationchange", listener: (ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: "pause", listener: (ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: "pointercancel", listener: (ev: PointerEvent) => any, useCapture?: boolean): void;
addEventListener(type: "pointerdown", listener: (ev: PointerEvent) => any, useCapture?: boolean): void;
addEventListener(type: "pointerenter", listener: (ev: PointerEvent) => any, useCapture?: boolean): void;
addEventListener(type: "pointerleave", listener: (ev: PointerEvent) => any, useCapture?: boolean): void;
addEventListener(type: "pointermove", listener: (ev: PointerEvent) => any, useCapture?: boolean): void;
addEventListener(type: "pointerout", listener: (ev: PointerEvent) => any, useCapture?: boolean): void;
addEventListener(type: "pointerover", listener: (ev: PointerEvent) => any, useCapture?: boolean): void;
addEventListener(type: "pointerup", listener: (ev: PointerEvent) => any, useCapture?: boolean): void;
addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: "resize", listener: (ev: UIEvent) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
_conchInfo:{version:string};
appcache:AppCache;
loadConchUrl:any;
postMessage:any;
postRuntimeMessage:any;
}
declare var window:Window;
var _window = new _Window();
window.getComputedStyle=function(ele:Element,parm:any):any
{
return null;
}
window.pageXOffset=window.pageYOffset=0;
window.localStorage = new Storage(); //这时候还没有url。
//window.sessionStorage = new Storage(); 有的项目会使用这个,但是如果没有的话,一般都会再用localStorage,为了避免出错,先不要这个。
window.sessionStorage=new WindowSessionStorage();
var location = window.location = new Location;
window.console = new Console();
window.addEventListener = _window.addEventListener.bind(_window);
window.removeEventListener = _window.removeEventListener.bind(_window);
window.dispatchEvent = _window.dispatchEvent.bind(_window);
window.document = new Document(); //是不是应该在sethref之后呢
window.layaDoc = window.document;
window.crypto = new Crypto();
window.devicePixelRatio=1.0;
var Image = window.Image = HTMLImageElement;
var Audio = window.Audio = HTMLAudioElement;
window.requestAnimationFrame = requestAnimationFrame;
window.cancelAnimationFrame = cancelAnimationFrame;
var parent = window.parent = window;
var frames = window.frames = null;
var navigator = window.navigator = new Navigator();
window.open=(url?: string, target?: string, features?: string, replace?: boolean):Window=>{
createProcess('scripts/index.js',url);
return window;
}
var onload = window.onload = null;
function printstack(){
var e = new Error();
alert((<any>e).stack);
}
var div = HTMLDivElement;
window.layabox={
devinfo:(function getDevInfo()
{
var devi = conchConfig.getDeviceInfo();
window.console.log(devi);
return JSON.parse(devi);
})(),
getDeviceInfo:function(){return this.devinfo;}
};
window.layaHtml5={File:File};
var _$innerWidth=getInnerWidth();
var _$innerHeight=getInnerHeight();
var _$devicePixelRatio=getDevicePixelRatio();
Object.defineProperty(window,'innerWidth',{get:function(){return _$innerWidth}});
Object.defineProperty(window,'innerHeight',{get:function(){return _$innerHeight}});
Object.defineProperty(window,'outerWidth',{get:function(){return _$innerWidth}});
Object.defineProperty(window,'outerHeight',{get:function(){return _$innerHeight}});
Object.defineProperty(window,'devicePixelRatio',{get:function(){return _$devicePixelRatio}});
/*conch.setOnBlur && conch.setOnBlur(function(){
var evt = new UIEvent('blur');
evt.view=window;
document._dispatchEvent(evt);
window.dispatchEvent(evt);
});
conch.setOnFocus && conch.setOnFocus(function(){
var evt = new UIEvent('focus');
evt.view=window;
document._dispatchEvent(evt);
window.dispatchEvent(evt);
});*/
conch.setOnResize(function(w,h){
_$innerWidth=w;
_$innerHeight=h;
window.console.log(">>>>>>>>>>>>>>>>innerWidth:"+_$innerWidth+"innerHeight:"+_$innerHeight);
var evt = new UIEvent('resize');
evt.view=window;
//evt.eventPhase=Event.AT_TARGET;
//TODO 还不好使,需要最终能调用到window.onresize
document._dispatchEvent(evt); //需要完整流程
window.dispatchEvent(evt);
//TODO
//window.onresize&&window.onresize(null);
});
conch.config=conchConfig;
class Screen{
get width():number{
return _$innerWidth;
}
get height():number{
return _$innerHeight;
}
}
window.screen=new Screen();
window.onresize=function(e:UIEvent){
//alert('kkkkk')
}
conch.onerror = function (message, filename, lineno, colno, error) {
if (window.onerror)
{
var ln=decodeTemp(lineno);
var cn=decodeTemp(colno);
var er=decodeTemp(error);
var mg=decodeTemp(message);
var fn=decodeTemp(filename);
var e={
message:decodeTemp(message),
stack:er,
name:""
};
window.onerror(mg=="undefined"?undefined:mg,fn=="undefined"?undefined:fn,ln!="undefined"?parseInt(ln):undefined,cn!="undefined"?parseInt(cn):undefined,e);
}
};
/**
* 全局错误处理
*/
Object.defineProperty(window,'onerror',{set:function(fun){
conch.__onerror=fun;
showAlertOnJsException(false);
},get:function(){
return conch.__onerror;
}});
/*window.onerror = function(message: string, filename?: string, lineno?: number, colno?: number, error?:Error): void{
alert('window.onerror');
}*/
//var console = window.console;
var document = window.document;
/**
* 全局函数
*/
interface FrameRequestCallback {
(time: number): void;
}
var addEventListener:(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean)=>void=window.addEventListener.bind(this);
var dispatchEvent:(evt: Event)=>boolean=window.dispatchEvent.bind(this);
var removeEventListener:(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean)=>void=window.removeEventListener.bind(this);
var clearInterval:(handle: number)=>void=window.clearInterval = _window.clearInterval;
var clearTimeout:(handle: number)=>void=window.clearTimeout= _window.clearTimeout;
var setInterval:(handler: any, timeout?: any/*, ...args: any[]*/)=>number=window.setInterval=_window.setInterval;
var setTimeout:(handler: any, timeout?: any/*, ...args: any[]*/)=>number=window.setTimeout=_window.setTimeout;
//onload
Object.defineProperty(window,'runtime',{get:function(){return true}});//给window.runtime赋值
window.postMessage=function(data,d) {
if(typeof(data)=="object")
data=JSON.stringify(data);
conch.callWebviewJS( "window.__getMessemage",encodeURIComponent(data),"" );
}
window.postRuntimeMessage=function(d)
{
if(typeof(d)=="object")
d=JSON.stringify(d);
d=decodeURIComponent(d);
var e=new MessageEvent('message');
e.data=JSON.parse(d);
e.target=window;
var s=new RegExp("(http|file|https)://([^/:]*)(:(\\d+)|)([^?]+)(.*|)");
var rs=s.exec(document.referrer);
if(rs){
e.origin=rs[1]+"://"+rs[2]+rs[3];
}
window.dispatchEvent(e);
}
//为了兼容性而保留的
window.SetupWebglContext = function(){};
//document.createElement("canvas").getContext("conch");
window.downloadfile = function (url, force, onok, onerr) {
//url = encodeURI(url);
if (force) {
url = (function (url) {
var ret = url;
if (url.indexOf('?') < 0) {
ret = url + '?rnd=' + Math.random();
}
else {
ret = url + '&downloadrnd' + Math.random().toString().substr(2) + '=1';
}
return ret;
})(url);
}
var file =new window.layaHtml5.File(url);
var filereader:any = new FileReader();
filereader.onload = function () { onok && onok(filereader.result); };
filereader.onerror = function () { onerr && onerr(); };
filereader.readAsText(file);
};
if(window.navigator.platform!="windows")window["ontouchstart"]=null;
window['GL_CAPS'] = GL_CAPS;
window.focus=function() {}
//根据内存设置大图合集参数
var nMem=conchConfig.getTotalMem();//单位是KB
if( nMem <= 524288 )
{
//设置引擎的大图集的个数
conchConfig.atlasNum=10;
//贴图资源的cache的大小。单位是byte
conchConfig.maxTextureMemSize=64*1024*1024;
}
else if( nMem > 524288 && nMem <= 1048576 )
{
//设置引擎的大图集的个数
conchConfig.atlasNum=16;
//贴图资源的cache的大小。单位是byte
conchConfig.maxTextureMemSize=84*1024*1024;
}
else if( nMem > 1048576 )
{
//设置引擎的大图集的个数
conchConfig.atlasNum=20;
//贴图资源的cache的大小。单位是byte
conchConfig.maxTextureMemSize=128*1024*1024;
}
class Performance{
now(){
return tmGetCurms();
}
}
window["Performance"] = Performance;
window.performance = new Performance();
File diff suppressed because it is too large Load Diff
+305
View File
@@ -0,0 +1,305 @@
class KeyboardEvent extends UIEvent {
altKey: boolean;
char: string;
charCode: number;
ctrlKey: boolean;
key: string;
keyCode: number;
locale: string;
location: number;
metaKey: boolean;
repeat: boolean;
shiftKey: boolean;
which: number;
constructor(typeArg: string, eventInitDict?: KeyboardEventInit) {
super(typeArg);
if (eventInitDict) {
var ini = eventInitDict;
this.altKey = eventInitDict.altKey;
this.initKeyboardEvent(typeArg, ini.bubbles, ini.cancelable, ini.view, ini.key, ini.location, null, ini.repeat, null);
}
}
initKeyboardEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, keyArg: string, locationArg: number, modifiersListArg: string, repeat: boolean, locale: string): void {
this.type = typeArg;
this.cancelable = canBubbleArg;
this.cancelable = cancelableArg;
this.key = keyArg;
this.location = locationArg;
this.locale = locale;
}
static DOM_KEY_LOCATION_JOYSTICK: number;
static DOM_KEY_LOCATION_LEFT = 1;
static DOM_KEY_LOCATION_MOBILE: number;
static DOM_KEY_LOCATION_NUMPAD = 3;
static DOM_KEY_LOCATION_RIGHT = 2;
static DOM_KEY_LOCATION_STANDARD = 0;
}
var _lbKeyboardEvent= window["KeyboardEvent"]=KeyboardEvent;
//var layaDoc = <Document>window.layaDoc;
(function(layaDoc: Document) {
'use strict';
var APP_TOUCH_DOWN = 0;
var APP_TOUCH_UP = 1;
var APP_TOUCH_MOV = 2;
var APP_TOUCH_PT_DOWN = 5;
var APP_TOUCH_PT_UP = 6;
var m_vTouchs: Touch[] = [];
class touchEvt extends UIEvent {
changedTouches: Touch[] = [];
touches: Touch[] = [];
targetTouches:Touch[];
constructor(type: number, id: number, name: string, x: number, y: number) {
super('');
this.targetTouches = this.changedTouches;
var touch = new Touch();// touchObj(p_nID, p_sName, p_nX, p_nY);
//touch.id = p_nID;
touch.identifier = id;
touch.pageX = touch.screenX = touch.clientX = x;
touch.pageY = touch.screenY = touch.clientY = y;
//touch.type = p_sName;
//touch.force = 1;
//touch.radiusX=touch.radiusY=13.8;
this.changedTouches.push(touch);
switch (type) {
case APP_TOUCH_DOWN:
case APP_TOUCH_PT_DOWN:
m_vTouchs.push(touch);
break;
case APP_TOUCH_PT_UP: {
//DEL. 已知事件都是一个一个发送的。
var epos = 0;
var tnum = m_vTouchs.length;
while (epos < tnum) {
var ce = m_vTouchs[epos];
if (ce.identifier == id) {
break;
}
epos++;
}
if (epos >= tnum) {
//error not find
} else {
m_vTouchs.splice(epos, 1);
}
} break;
case APP_TOUCH_MOV: {
//修改. 已知事件都是一个一个发送的。
var tnum = m_vTouchs.length;
var ti = 0;
while (ti < tnum) {
var ce = m_vTouchs[ti];
if (ce.identifier == id) {
m_vTouchs[ti] = touch;
break;
}
ti++;
}
} break;
case APP_TOUCH_UP:
m_vTouchs = [];
break;
}
this.touches = m_vTouchs;
switch (type) {
case 0:
case 5:
this.type = "touchstart";
break;
case 1:
case 6:
this.type = "touchend";
break;
case 2:
this.type = "touchmove";
break;
}
}
//touches
}
var joystickEvt = function(TL_xOffset, TL_yOffset, TR_xOffset, TR_yOffset, LT_Offset, RT_Offset) {
this.THUMBL_xOffset = TL_xOffset;
this.THUMBL_yOffset = TL_yOffset;
this.THUMBR_xOffset = TR_xOffset;
this.THUMBR_yOffset = TR_yOffset;
this.LT_Offset = LT_Offset;
this.RT_Offset = RT_Offset;
}
var keyEvt = function(name, code, keychar, flag) { this.type = name; this.keyCode = code; this.keyChar = keychar; this.altKey = flag & 0x1; this.shiftKey = (flag & 0x2) != 0; this.ctrlKey = (flag & 0x4) != 0; this.preventDefault = function() { }; }
conch.setTouchEvtFunction((touchtype: number, id: number, etype: string, x: number, y: number): void => {
if (conch.disableMultiTouch && id != 0) return;
var doc = window.document;
if (!doc) {
console.log('touch event cant dispatch!');
return;
}
var evt = new touchEvt(touchtype, id, etype, x, y);
evt.target = doc.pickElement(x, y);
doc.dispatchEvent(evt);
});
/*
function smpJson(obj): string {
var ret = '{';
for (var v in obj) {
var val = obj[v];
if (typeof (val) == 'function') val = 'Function'
ret += ' ' + v + '=' + val + '\n';
}
ret += '}';
return ret;
}
*/
function keyEventHandle() {
//TODO 问题 用一个ke的话,如果有人保存就会有问题。
var ke = new _lbKeyboardEvent('');
return function(type: string, keycode: number, keychar: number, AltShiftCtrl: number) {
var doc = window.document;
if (!doc)
return;
var keyinit: KeyboardEventInit = {};
var kc = String.fromCharCode(keycode);
ke.defaultPrevented=false;
ke._propagationStopped=false;
ke.type=type;
//var evt = new KeyboardEvent(type, { key: kc });
ke.key = kc;
ke.keyCode = keycode;
//console.log('altshifctrl=' + AltShiftCtrl + ',keycod=' + keycode + ',keychar=' + keychar);
ke.altKey = (AltShiftCtrl & 0x4) != 0;
ke.shiftKey = (AltShiftCtrl & 0x2) != 0;
ke.ctrlKey = (AltShiftCtrl & 0x1) != 0;
ke.target = doc._topElement;
//TODO 这个是不是不用发事件啊,以提高效率
doc.dispatchEvent(ke);
if (!ke.defaultPrevented) {
//console.log('def evt')
var f = doc['on' + type];
if (f) {
f.call(doc, ke);
}
}
}
}
conch.setKeyEvtFunction(keyEventHandle());
conch.setMouseEvtFunction(function(touchtype: number, type: string, x: number, y: number, wheel: number) {
var doc = window.document;
if (!doc) {
console.log('mouse event cant dispatch!');
return;
}
//console.log('mouseevt:'+type+','+x+','+y+','+wheel)
var target = doc.pickElement(x, y);
if (wheel != 0) {
var evt1 = new MouseWheelEvent();
evt1.clientX = evt1.pageX = evt1.screenX = x;
evt1.clientY = evt1.pageY = evt1.screenY = y;
evt1.target=target;
evt1.wheelDelta = wheel;
doc.dispatchEvent(evt1);
}
else{
var evt;
switch(touchtype)
{
case 10:
evt = new _lbMouseEvent("mousedown");
evt.button = 1;
break;
case 11:
evt = new _lbMouseEvent("mouseup");
evt.button = 1;
break;
default:
evt = new _lbMouseEvent(type);
evt.button = 0;
break;
}
evt.clientX = evt.pageX = evt.screenX = x;
evt.clientY = evt.pageY = evt.screenY = y;
evt.target=target;
doc.dispatchEvent(evt);
}
});
conch.otherBuffer=new ArrayBuffer(40);
conch.otherDataView=new DataView(conch.otherBuffer);
conch.setBuffer(conch.otherBuffer);
conch.setDeviceMotionEvtFunction(function(type:string,ra:number,rb:number,rg:number){
if((typeof ra)!="undefined")
{
var e=new DeviceOrientationEvent();
e.alpha=ra;
e.beta=rb;
e.gamma=rg;
window.dispatchEvent(e);
}
else
{
var d=conch.otherDataView;
var evt=new DeviceMotionEvent();
evt.acceleration={x:d.getFloat32(0,true),y:d.getFloat32(4,true),z:d.getFloat32(8,true)};
evt.accelerationIncludingGravity={x:d.getFloat32(12,true),y:d.getFloat32(16,true),z:d.getFloat32(20,true)};
evt.rotationRate={alpha:d.getFloat32(24,true),beta:d.getFloat32(28,true),gamma:d.getFloat32(32,true)};
evt.interval=d.getFloat32(36,true);
window.dispatchEvent(evt);
}
});
setJoystickEvtFunction(function(type: number, thumbL_xoff: number, thumbL_yoff: number, thumbR_xoff: number, thumbR_yoff: number, LT_offset: number, RT_offset: number) {
//layaDoc.onEvt( type,new joystickEvt( thumbL_xoff,thumbL_yoff,thumbR_xoff,thumbR_yoff,LT_offset,RT_offset ) );
});
//网络监听
conch.setNetworkEvtFunction( function(type:number){
var event = new Event("network");
event["code"] = type;
document.dispatchEvent( event );
});
/*
Object.defineProperty( layaDoc, "keydown", {
get : function () {
return null;
},
set : function ( p_pFunc ) {
this.addEventListener( "keydown",p_pFunc );
}
});
Object.defineProperty( layaDoc, "keyup", {
get : function () {
return null;
},
set : function ( p_pFunc ) {
this.addEventListener( "keyup",p_pFunc );
}
});
//为了兼容错误的监听 onkeydown onkeyup
Object.defineProperty( layaDoc, "onkeydown", {
get : function () {
return null;
},
set : function ( p_pFunc ) {
this.addEventListener( "onkeydown",p_pFunc );
}
});
Object.defineProperty( layaDoc, "onkeyup", {
get : function () {
return null;
},
set : function ( p_pFunc ) {
this.addEventListener( "onkeyup",p_pFunc );
}
});
*/
})(window.document);
File diff suppressed because it is too large Load Diff
+62
View File
@@ -0,0 +1,62 @@
///<reference path="LayaConchRuntime.d.ts" />
/**
* 这个是模拟多重继承的函数
*/
function applyMixins(derivedCtor: any, baseCtors: any[]) {
baseCtors.forEach(baseCtor => {
Object.getOwnPropertyNames(baseCtor.prototype).forEach(name => {
if (name !== 'constructor') {
derivedCtor.prototype[name] = baseCtor.prototype[name];
}
});
});
}
class IDBEnvironment implements IDBEnvironment{}
/**
* 因为有些局部变量不希望直接暴露到全局环境下,所以做一个封装用的全局类
*/
class _Window extends EventTarget {
crypto: Crypto;
onerror: ErrorEventHandler;
Audio:HTMLAudioElement;
private timer = new WindowTimers();
clearInterval:(handle: number)=>void=this.timer.clearInterval;
clearTimeout:(handle: number)=>void = this.timer.clearTimeout;
setInterval:(handler: any, timeout?: any/*, ...args: any[]*/)=>number=this.timer.setInterval;
setTimeout:(handler: any, timeout?: any/*, ...args: any[]*/)=>number=this.timer.setTimeout;
_removeEventListener:(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean)=>void;
constructor(){
super();
this._removeEventListener=this.removeEventListener;
this.removeEventListener=this.removeEventListenernew;
}
document:Document;
//clearImmediate:(handle: number)=>void;
addEventListener (type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void {
if(type=="devicemotion"||type=="deviceorientation"){
conch.setSensorAble(true);
}
super.addEventListener(type,listener,useCapture);
}
removeEventListenernew(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void
{
this._removeEventListener(type, listener, useCapture);
if(type=="devicemotion"||type=="deviceorientation")
{
var de= this._evtMaps.get("devicemotion");
var deo=this._evtMaps.get("deviceorientation");
if((!de||de.length==0)&&(!deo||deo.length==0))
{
conch.setSensorAble(false);
}
}
}
}
//applyMixins(_Window,[EventTarget,WindowTimers,WindowSessionStorage, WindowLocalStorage,GlobalEventHandlers,IDBEnvironment,WindowBase64]);
File diff suppressed because it is too large Load Diff
+244
View File
@@ -0,0 +1,244 @@
class Location {
/* queries:Object;
reload(force:boolean):void;
hash: string;
hostname: string;
href: string;
origin: string;
pathname: string;
port: string;
assign(url: string): void;
reload(forcedReload?: boolean): void;
replace(url: string): void;
toString(): string;*/
// getHref():string;
// setHref(url:string):void;
// fullpath:string;
// protocol:string;
// host:string;
// search:string;
// appUrl:string;
private _nativeObj = conch;
private bk_setHref: Function;
private _host:string;
private _hostname:string;
private _fullpath:string;
private _pathname:string;
private _protocol:string;
private _port:string;
private _search:string;
private _href:string;
private _origin:string;
static __urlCache__:Object={};
hash: string;
get hostname():string
{
return this._hostname;
}
get host():string{
return this._host;
}
get fullpath():string
{
return this._fullpath;
}
get pathname():string
{
return this._pathname;
}
get protocol():string
{
return this._protocol;
}
get search():string
{
return this._search;
}
get port():string
{
return this._port;
}
get origin():string
{
return this._origin;
}
get href(): string {
return this._href;
}
set href(url: string) {
url = this.normalizeUrl(url);
// conch.showLoadingView(true);
var oldhref = this._href;
if (url != oldhref) {
this.setHref(url);
if (this._href != oldhref)
reloadJS(true);
}
}
//未实现
// origin: string;
// port: string;
constructor() {
//重载setHref
this.bk_setHref = this._nativeObj.setHref.bind(this._nativeObj);
// conch.setLocationObj(this._nativeObj);
}
setBaseHref(basehref:string):void
{
//this._nativeObj.setBaseHref(basehref);
}
getBaseHref():string
{
//return this._nativeObj.getBaseHref();
return "";
}
assign(url: string): void {
}
reload(forcedReload?: boolean): void {
reloadJS(forcedReload);
}
replace(url: string): void {
}
toString(): string {
return this._href;
}
/**
* 想在脚本里进行url的解析。所以封装了个setHref函数
*/
setHref = (url:string) => {
if (!url || url.length < 8) {
alert("您的地址不符合要求");
return;
}
var s=new RegExp("(http|file|https)://([^/:]*)(:(\\d+)|)([^?]+)(.*|)","g");
var result;
if((result=s.exec(url))!=null){
this._href=result[0];
this._hostname=result[2];
this._host=result[2]+result[3];
this._pathname=result[5];
this._port=result[4];
this._search=result[6];
this._protocol=result[1]+":";
this._origin=this._protocol+"//"+this._host;
var i=this._pathname?this._pathname.lastIndexOf("/"):-1;
if(i!=-1){
var temp=this._pathname.substring(0,i);
this._fullpath=this._origin+temp;
}
else{
this._fullpath=this._origin+ this._pathname;
}
}
else{
alert("您的地址不符合要求");
}
//this._nativeObj.queries = this.parseQuery(url);
this.bk_setHref(url);
//对应的localStorage
//注意必须在 bk_setHref, 因为需要解析结果。
window.localStorage.create(this._fullpath + '/');
};
normalizeUrl(url): string {
url = url.replace(/\\/g, '/');
if (url[0] === '/')
url = 'file://' + url;
else if (url[1] === ':')
url = 'file:///' + url;
return url.trim();
}
parseQuery(url): Object {
var ret = {};
var p1 = url.indexOf('?');
if (p1 < 0)
return null;
var q = url.substr(p1 + 1);
q && q.split('&').forEach((v, i, a) => {
var kv = v.split('=');
if (kv.length === 2) {
ret[kv[0].trim()] = kv[1].trim();
}
});
return ret;
}
resolve(fileName:string):string{
//从缓存里取出此文件名
var urlcache = Location.__urlCache__[fileName];
//如果已经缓存过,直接返回结果
if (urlcache != null) return urlcache;
if (fileName == null) {
return "";
}
if(fileName.indexOf("//")==0)
{
return this.protocol+fileName;
}
if(fileName.indexOf("file:///")==0||fileName.indexOf("http://")==0||fileName.indexOf("https://")==0)return fileName;
if ((fileName.charAt(1) == ':' && fileName.charAt(2) == '/'))
fileName = "file://" + fileName;
//绝对路径的话,不能从index.html所在路径开始,否则与浏览器不一致
if (fileName.charAt(0) == "/") {
return this._origin + fileName;
}
var basePath = this._fullpath;
var urlfull = basePath + "/" + fileName;
urlcache = Location.__urlCache__[urlfull];
if (urlcache != null) return urlcache;
if (fileName.indexOf("://") < 0)
fileName = basePath + "/" + fileName;
var urls = fileName.split("/");
urls[1] = "";
var str,i = 2,size = urls.length;
while (i < size) {
str = urls[i];
if (str == null) break;
if (str == '' || str == '.') {
urls.splice(i, 1);
continue;
}
if (str == "..") {
if(i<=3&&this._protocol!="file:")
{
urls.splice(i,1);
}
else{
urls.splice(i - 1, 2);
i -= 1;
}
continue;
}
i += 1;
}
fileName = urls.join("/");
Location.__urlCache__[fileName] = fileName;
Location.__urlCache__[urlfull] = fileName;
return fileName;
}
}
+124
View File
@@ -0,0 +1,124 @@
interface NavigatorID {
appName: string;
appVersion: string;
platform: string;
product: string;
productSub: string;
userAgent: string;
vendor: string;
vendorSub: string;
}
interface NavigatorOnLine {
onLine: boolean;
}
interface PositionError {
code: number;
message: string;
toString(): string;
PERMISSION_DENIED: number;
POSITION_UNAVAILABLE: number;
TIMEOUT: number;
}
interface PositionCallback {
(position: Position): void;
}
interface PositionErrorCallback {
(error: PositionError): void;
}
interface Coordinates {
accuracy: number;
altitude: number;
altitudeAccuracy: number;
heading: number;
latitude: number;
longitude: number;
speed: number;
}
interface Position {
coords: Coordinates;
timestamp: number;
}
interface PositionOptions {
enableHighAccuracy?: boolean;
timeout?: number;
maximumAge?: number;
}
interface Geolocation {
clearWatch(watchId: number): void;
getCurrentPosition(successCallback: PositionCallback, errorCallback?: PositionErrorCallback, options?: PositionOptions): void;
watchPosition(successCallback: PositionCallback, errorCallback?: PositionErrorCallback, options?: PositionOptions): number;
}
interface NavigatorGeolocation {
geolocation: Geolocation;
}
class Navigator implements NavigatorID, NavigatorOnLine, NavigatorGeolocation {
//NavigatorID
get appName():string{ return 'Netscape';}
get appVersion(): string{ return this.userAgent};
get platform():string{return window.layabox.devinfo.os};
product: string;
productSub: string;
get userAgent(): string{
var os=window.layabox.devinfo.os;
if(os=="ios")
return "LayaBox(iPhone; CPU iPhone OS Mac OS X)";
else if(os=="android")
return "LayaBox Android";
else
return 'LayaBox/2.1';
};
vendor: string;
vendorSub: string;
get sv():number{
var v:string=window.layabox.devinfo.osversion;
var t:number=parseFloat(v);
if(isNaN(t))
{
t=v.charCodeAt(0)-71;
}
return t;
};
//NavigatorOnLine
onLine: boolean;
//NavigatorGeolocation
geolocation: Geolocation;
get appCodeName(): string{ return 'Mozilla'; }
appMinorVersion: string;
browserLanguage: string;
connectionSpeed: number;
cookieEnabled: boolean;
cpuClass: string;
get language(): string{ return 'zh-CN';};
maxTouchPoints: number;
msManipulationViewsEnabled: boolean;
msMaxTouchPoints: number;
msPointerEnabled: boolean;
pointerEnabled: boolean;
systemLanguage: string;
get userLanguage(): string{return 'zh-CN';}
webdriver: boolean;
constructor(){
}
getGamepads(): Gamepad[]{
return null;
}
javaEnabled(): boolean{return false;}
vibrate(pattern: number | number[]): boolean{
return false;
}
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void{
}
}
+197
View File
@@ -0,0 +1,197 @@
class Node extends EventTarget {
private _childs: Node[] = [];
private _zip = 0;
private _z = 0; //第几层。
private static _nodeid = 0;
ownerDocument: Document;
parentElement: HTMLElement; //父节点如果是Element,这个就有值,并且等于parentNode
parentNode: Node;
nodeType:number;//http://www.w3school.com.cn/jsref/prop_node_nodetype.asp
constructor() {
super();
this.nodeType=1;
this._zip = Node._nodeid++;
}
get firstChild():Node
{
return this._childs?this._childs[0]:null;
}
set firstChild(node:Node)
{
}
get childNodes():Node[]
{
return this._childs;
}
set childNodes(nodes:Node[])
{
}
insertBefore(newChild:Node,oldChild:Node)
{
//暂时直接append
this.appendChild(newChild);
}
appendChild(newChild: Node): Node {
if(newChild==null)return null;
if (newChild == this)
return;
if (this._childs.indexOf(newChild) < 0) {
this._childs.push(newChild);
}
newChild.parentNode = this;
newChild._z = this._z + 1;
var doc = newChild.ownerDocument || this.ownerDocument;
// alert(`append: child is:
// ${newChild.smpJson()},
// i am:
// ${this.smpJson()}`);
//更新最上层对象.
//现在是 > 对于庄园来说,第一个是主画布,append到body上,第二个是一个统计信息,也append到body上
if (doc && newChild._z >=doc._topElement._z && newChild instanceof HTMLCanvasElement&&!(window.document._topElement instanceof HTMLCanvasElement)) {
var ele = <HTMLElement>newChild;
if (ele.__visible) {
window.document._topElement =newChild;
}
}
return newChild;
}
/**
* TODO 现在还没有做深拷贝
*/
cloneNode(deep?: boolean): Node {
if(deep){
//console.error('现在不支持深度clone');
deep=false;
}
function clone(obj) {
if (typeof (obj) != 'object' || obj == null) return obj;
var newObj = Object.create(obj.__proto__); //由于不会遍历父类。先只做浅拷贝,直接给prototype赋值 必须用create
for (var i in obj) {
if (!deep)
newObj[i] = obj[i];
else//注意:如果是c导出的对象,deep clone会出错,因为new的是Object,而不是c对象了。
newObj[i] = clone(obj[i]);
}
return newObj;
}
return clone(this);
}
removeChild(oldChild: Node): Node {
var p = this._childs.indexOf(oldChild);
if (p >= 0) {
this._childs.splice(p, 1);
if(window.document._topElement==oldChild)
window.document._topElement=oldChild.parentElement;
oldChild.parentNode=null;
oldChild.parentElement=null;
return oldChild;
} else
return null;
}
// protected smpJson(): string {
// var ret = '{';
// var me = this;
// for (var v in me) {
// var val = me[v].toString();
// //if (typeof (val) == 'function') val = 'Function'
// ret += ' ' + v + '=' + val + '\n';
// }
// ret += '}';
// return ret;
// }
/**
* 返回父节点。不包括自己。
*/
getAncestorsNode(): Node[] {
var ret = new Array<Node>();
var obj: Node = this;
while (obj.parentNode) {
ret.push(obj.parentNode);
obj = obj.parentNode;
}
return ret;
}
}
class NodeSelector {
querySelector(selectors: string): Element {
return null;
}
querySelectorAll(selectors: string): NodeListOf<Element> {
return <NodeListOf<Element>>[];
}
}
class ChildNode {
constructor() { }
remove(): void {
}
}
class ElementTraversal {
constructor() {
}
}
class Element extends Node implements GlobalEventHandlers, ElementTraversal, NodeSelector, ChildNode {
tagName: string;
_id: string;
className: string;
innerHTML: string;
clientHeight: number;
clientLeft:number;//=0;inputHTMLelement赋值的时候conchinput还么初始化
clientTop:number;//=0;
clientWidth: number;
__visible = true;
set id(s:string){
this._id=s;
document.all.push(this);
}
get id():string{
return this._id;
}
private _attribs: {};
querySelector: (selectors: string) => Element; //接口的空函数
querySelectorAll: (selectors: string) => NodeListOf<Element>;//接口的空函数
createEvent: (eventInterface: string) => Event;//为了 DocumentEvent 接口的空函数tes
remove: () => void;
onpointercancel: (ev: PointerEvent) => any;
onpointerdown: (ev: PointerEvent) => any;
onpointerenter: (ev: PointerEvent) => any;
onpointerleave: (ev: PointerEvent) => any;
onpointermove: (ev: PointerEvent) => any;
onpointerout: (ev: PointerEvent) => any;
onpointerover: (ev: PointerEvent) => any;
onpointerup: (ev: PointerEvent) => any;
onwheel: (ev: WheelEvent) => any;
constructor(){
super();
}
//addEventListener:(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean)=>void;
setAttribute(name: string, value: string): void {
if(!this._attribs)this._attribs=[];
this._attribs[name] = value;
}
getAttribute(name:string):any{
return this._attribs?this._attribs[name]:null;
}
}
applyMixins(Element, [Node, GlobalEventHandlers, ElementTraversal, NodeSelector, ChildNode])
+282
View File
@@ -0,0 +1,282 @@
/**
* name
*/
'use strict'
require("webglPlus.js");
conch["platCallBack"]=function(ret)
{
var objid,m,rs,c,rJSON;
if(ret==null)return;
objid=ret.objId;
m=ret.mName;
c=ret.cName;
rs=ret.v;
var platC:IPlatForm;
if(objid!=-1){
platC=PlatformObj.objMap[objid];
}
else{
platC=PlatformClass.clsMap[c];
}
if(platC){
var callback:Function= platC.callBackList[m];
callback&&callback(rs);
}
}
interface IPlatForm
{
callBackList:Object;
call(methodName,p1?:any,p2?:any,p3?:any,p4?:any,p5?:any,p6?:any,p7?:any,p8?:any,p9?:any);
callWithBack(callback,methodName,p1?:any,p2?:any,p3?:any,p4?:any,p5?:any,p6?:any,p7?:any,p8?:any,p9?:any):void
}
class PlatformBase implements IPlatForm{
callBackList:Object;
className:string;
objid:number;
call(methodName,p1?:any,p2?:any,p3?:any,p4?:any,p5?:any,p6?:any,p7?:any,p8?:any,p9?:any)
{
var a:Array<any>= Array.prototype.slice.call(arguments);
a.shift();
try{
var rs=JSON.parse(conch.callMethod(this.objid,true,this.className,methodName,JSON.stringify(a))||"{}");
return rs.v;
}
catch(e)
{
return null;
}
}
callWithBack(callback,methodName,p1?:any,p2?:any,p3?:any,p4?:any,p5?:any,p6?:any,p7?:any,p8?:any,p9?:any):void
{
this.callBackList[methodName]=callback;
var a:Array<any>= Array.prototype.slice.call(arguments);
a.splice(0,2)
try{
var rs=JSON.parse(conch.callMethod(this.objid,false,this.className,methodName,JSON.stringify(a))||"{}");
return rs.v;
}
catch(e)
{
return null;
}
}
}
class PlatformClass extends PlatformBase {
static clsMap:Object={};
constructor(clsName:string)
{
super();
this.objid=-1;
this.className=clsName;
this.callBackList={};
PlatformClass.clsMap[clsName]=this;
}
static createClass(clsName:string):PlatformClass
{
return PlatformClass.clsMap[clsName]||new PlatformClass(clsName);
}
newObject(p1?:any,p2?:any,p3?:any,p4?:any,p5?:any,p6?:any,p7?:any,p8?:any,p9?:any):PlatformObj
{
var a:Array<any>= Array.prototype.slice.call(arguments);
a.splice(0,0,"<init>");
var rs=new PlatformObj(this);
rs.init.apply(rs,a);
return rs;
}
}
class PlatformObj extends PlatformBase{
static objMap:Object={};
static objNum:number=0;
cls:PlatformClass;
callBackList:Object;
constructor(cls:PlatformClass)
{
super();
this.cls=cls;
this.className=cls.className;
this.callBackList={};
}
init()
{
this.objid=PlatformObj.objNum++;
this.call.apply(this,arguments)||-1;
PlatformObj.objMap[this.objid]=this;
}
}
window["PlatformClass"]=PlatformClass;
window["PlatformObj"]=PlatformObj;
/**
* 直接加载缓存中的某个文件
* @param cache
* @param relUrl 相对路径,从/开始。例如 '/test.html'
*/
function loadRawCache(cache:AppCache, relUrl:string, encode:'raw'|'utf8'):string|ArrayBuffer{
var cpath = cache.getCachePath();
var relFile = relUrl;
var id = new Uint32Array([cache.hashstr(relFile)])[0].toString(16);
var fn = cpath+'/files/'+id.substr(0,2)+'/'+id.substr(2);
var ab = fs_readFileSync(fn);
if(ab){
var content = new Uint8Array(ab,48);
//content就是文件内容
//如果需要字符串
if(encode==='utf8'){
var strCont = String.fromCharCode.apply(null,content);
return strCont
}
else
return content.buffer;
}
return null;
}
class textBitmap
{
_nativeObj:_textBitmap;
_data:ArrayBuffer;
constructor(obj:any)
{
this._nativeObj = obj;
this._data = null;
}
get width():number
{
return this._nativeObj.width;
}
get height():number
{
return this._nativeObj.height;
}
get data():ArrayBuffer
{
return this._data;
}
set data(value:ArrayBuffer)
{
this._data=value;
}
}
window["textBitmap"] = textBitmap;
class measureText
{
width:number = 0;;
height:number = 0;;
constructor()
{
}
}
class conchTextCanvas
{
private charSizeMap = new Map<string, Map<string, any>>();
_nativeObj:_conchTextCanvas;
_currentFont:string = null;
constructor()
{
this._nativeObj = window["_conchTextCanvas"];
}
scale(x:number,y:number):void
{
this._nativeObj.scale(x, y);
}
get font():string
{
this._currentFont = this._nativeObj.font;
return this._currentFont;
}
set font(value:string)
{
this._currentFont = value;
this._nativeObj.font = value;
}
setFontInfo(font:string):void
{
this._nativeObj.setFontInfo(font);
}
measureText(text:string):measureText
{
if (!this._currentFont)
{
return null;
}
var measure:measureText = new measureText();
var widthCount:number = 0;
var maxHeight:number = 0;
var charCode:number = 0;
var char:string = "";
var size:any = null;
var dic:Map<string, any> = null;
if (!text)
{
//兼容老版本undefined报错
return this.measureText('undefined');
}
for (var i:number = 0; i < text.length; i++)
{
char = text.charAt(i);
charCode = text.charCodeAt(i);
dic = this.charSizeMap.get(this._currentFont);
if (!dic)
{
dic = new Map<string, any>();
this.charSizeMap.set(this._currentFont.slice(0), dic);
}
if (charCode >= 0x4E00 && charCode <= 0x9FFF)
{
size = dic.get("国");
if (!size)
{
size = this._nativeObj.measureChar("国".charCodeAt(0));
dic.set("国", size);
}
}
else
{
size = dic.get(char);
if (!size)
{
size = this._nativeObj.measureChar(charCode);
dic.set(char.slice(0), size);
}
}
widthCount += size.width;
maxHeight = size.height > maxHeight ? size.height : maxHeight;
}
measure.width = widthCount;
measure.height = maxHeight;
return measure;
}
initFreeTypeDefaultFontFromFile(defaultTTFs:string):boolean
{
return this._nativeObj.initFreeTypeDefaultFontFromFile(defaultTTFs);
}
initFreeTypeDefaultFontFromBuffer(ab:ArrayBuffer):boolean
{
return this._nativeObj.initFreeTypeDefaultFontFromBuffer(ab);
}
setFontFaceFromUrl(fontFamily:string, TTFFileName:string):boolean
{
return this._nativeObj.setFontFaceFromUrl(fontFamily, TTFFileName);
}
setFontFaceFromBuffer(fontFamily:string, ab:ArrayBuffer):boolean
{
return this._nativeObj.setFontFaceFromBuffer(fontFamily, ab);
}
removeFont(fontFamily:string):boolean
{
return this._nativeObj.removeFont(fontFamily);
}
getTextBitmapData(sText:string,nColor:number, nBorderSize:number,nBorderColor:number)
{
var nativeObj:_textBitmap = this._nativeObj._getTextBitmapData(sText,nColor,nBorderSize,nBorderColor);
var pTextBitmap = new textBitmap(nativeObj);
pTextBitmap.data = nativeObj.data;
return pTextBitmap;
}
}
window["conchTextCanvas"] = new conchTextCanvas;
+19
View File
@@ -0,0 +1,19 @@
class Screen_ extends EventTarget {
availHeight: number;
availWidth: number;
bufferDepth: number;
colorDepth: number;
deviceXDPI: number;
deviceYDPI: number;
fontSmoothingEnabled: boolean;
height: number;
logicalXDPI: number;
logicalYDPI: number;
msOrientation: string;
onmsorientationchange: (ev: Event) => any;
pixelDepth: number;
systemXDPI: number;
systemYDPI: number;
width: number;
}
+210
View File
@@ -0,0 +1,210 @@
///<reference path="./ES6NoDOM.d.ts" />
/**
* 问题:现在不支持 [] 方式的访问
* 不支持length
*/
class Storage {
private storagePath = conchConfig.getStoragePath();
private filename = '';
private db = {};//只保存了值,因为有根据idx索引的需求
private _len:number=0;
fileNamePre:string;
get length():number
{
return this._len;
}
getItem(key: string): any {
return this.db[key]||null;
}
key(index: number): string {
var keys:Array<string>=Object.keys(this.db);
keys.sort();
return keys[index]||null;
}
removeItem(key: string): void {
if(this.db[key])this._len--;
delete this.db[key];
this.savedb();
}
_setItem(key: string, data: string): void
{
if(this.db[key]==null)this._len++;
this.db[key]=data;
Object.defineProperty(this as any,key, {
get: function(){
return this.db[key];
},
enumerable: true,
configurable: true
});
}
setItem(key: string, data: string): void {
this._setItem(key,data);
this.savedb();
}
constructor() {
//Object.observe(this,this.onChange.bind(this));
}
/**
* 根据url来创建一个。在window初始化的时候做。
*/
create(url: string):Storage {
url=location.fullpath;
if (location.protocol=="file:") {
this.filename = url.substring(8).replace(/:/g, '_').replace(/[\\\/]/g, '__')
this.fileNamePre=this.storagePath + '/'+this.filename;
} else{
this.fileNamePre=this.storagePath + '/'+url.split('/')[2].replace(':', '_');
}
this.filename = this.fileNamePre + '.txt';
var strdb = readFileSync(this.filename, 'utf8') || '{}';
var db = JSON.parse(strdb);
for(var v in db){
this._setItem(v,db[v]);
}
return this;
}
onChange(changes) {
if (changes && changes.length) {
//save
}
}
clear() {
this.db = {};
this.savedb();
}
savedb() {
writeStrFileSync(this.filename, JSON.stringify(this.db));
}
}
window["Storage"]=Storage;
class WindowLocalStorage {
localStorage = new Storage();
}
class WindowSessionStorage {
getItem(i:string)
{
return this[i]||null;
}
setItem(i:string,b:Object)
{
this[i]=b;
}
//todo sessionStorage
}
window.loadLocalStorage = function( url ):Storage{
return new Storage().create(url);
};
class _Cookie{
key:string;
value:string;
domain:string;
expires:Date;
static cookies:Array<_Cookie>=[];
static sreg:RegExp=new RegExp("([^=]*)\\s*=\\s*([^;]*)\\s*;\\s*(expires\\s*=\\s*(.{23,26}GMT)|)");
constructor(){
this.domain="";
}
static addCookie(s:string):_Cookie{
var result= _Cookie.sreg.exec(s);
if(result==null){
console.warn("设置cookie无效");
return null;
}
else{
var temp:_Cookie=new _Cookie();
temp.key=result[1];
temp.value=result[2];
if(result[4]){
temp.expires=new Date(result[4]);
}
return temp;
}
}
static pushCookie(c:_Cookie):boolean{
//TO-DO
if(!c.isValid())return false;
for(var i:number=0,len:number=_Cookie.cookies.length;i<len;i++)
{
var temp:_Cookie=_Cookie.cookies[i];
if(temp.key==c.key){
_Cookie.cookies[i]=c;
return true;
}
}
_Cookie.cookies.push(c);
return true;
}
static flush():void
{
writeStrFileSync(document._cookiePath,_Cookie.getString("in","\""));
}
static getString(type:string,joinstr:string):string{
var a:Array<string>=[];
for(var i:number=0,len:number=_Cookie.cookies.length;i<len;i++)
{
var temp:_Cookie=_Cookie.cookies[i];
if(temp.isValid()){
a.push(temp.toLocalString(type));
}
else{
_Cookie.cookies.slice(i,1);
i--;
len--;
}
}
return a.join(joinstr);
}
static toLocalString():string{
return _Cookie.getString("out","; ");
}
isValid():boolean{
if(this.expires&&(this.expires.getTime()<Date.now())){
return false;
}
return true;
}
static init(s:string){
if(s)
{
var temp:Array<string>=s.split("\"");
for(var i:number=0,len:number=temp.length;i<len;i++){
var t:_Cookie= _Cookie.addCookie(temp[i]);
console.warn(">>>>>>>>>>addCookie"+temp[i]);
if(t)
{
t.value=decodeURIComponent(t.value);
t.domain=decodeURIComponent(t.domain);
}
_Cookie.pushCookie(t);
}
}
}
toLocalString(type:string):string{
switch (type) {
case "in":
return this.key+"="+encodeURIComponent(this.value)+"; expires="+this.expires.toGMTString()+"; domain="+encodeURIComponent(this.domain);
case "out":
return this.key+"="+this.value;
default:
return null;
}
}
}
+175
View File
@@ -0,0 +1,175 @@
interface WindowTimers{
clearInterval(handle: number): void;
clearTimeout(handle: number): void;
//为了生成的代码简单,不要后面的可变参数了 ...args: any[]
setInterval(handler: any, timeout?: any): number;
setTimeout(handler: any, timeout?: any): number;
}
namespace ns_Timer {
//TODO怎么避免new
class timerobj{
interval:number;
tm:number;
obj:{};
func:any;
args:any;
num:number;
del=false;
constructor(curtm:number, interval:number, obj:{}, func:Function, args:any, num:number){
this.interval = (interval < 18) ? -1 : interval;//<18则认为全帧
if( Math.abs(conch.maxInterval-interval)<1)
this.interval=-1;
this.tm = curtm + interval;
this.obj = obj;
this.func = func;
this.args = args;
this.num = num;
}
}
//TODO 优化
var timerqueue = function(){
this.AniFrame = [];
this.tmq=new Array<timerobj>();
this.addTimer=function(tm:number,obj:{},func,args:any,num:number ){
//this.curtm = Date.now();
var tmobj = new timerobj(Date.now(),tm,obj,func,args,num);
this.tmq.push(tmobj);
return tmobj;
}
this.delTimer=function(obj){
for(var i=0,sz=this.tmq.length; i<sz; i++){
if(this.tmq[i]===obj){
//this.tmq.splice(i,1);
this.tmq[i].del=true;
break;
}
}
}
this.update=function(){
this.curtm = Date.now();
var i=0;
var btmq=[];
for(var sz=this.tmq.length; i<sz; i++){
var ctm:timerobj = this.tmq[i];
if(ctm.del)continue;
//log('func['+i+']='+ctm.func);
var dt = ctm.tm-this.curtm;
if(dt<0 || ctm.interval<0 || Math.abs(conch.maxInterval-ctm.interval)<1 ){
//run
if(typeof(ctm.func)==='function'){
ctm.func.apply(null,ctm.obj);
}else{
eval(ctm.func);
}
//多次
if(ctm.num<0 || --ctm.num>0 ){
if(dt<0) dt=0;
ctm.tm=dt+this.curtm+ctm.interval;
btmq.push(ctm);
}
}else{
btmq.push(ctm);
}
}
this.tmq.splice(0,sz);//因为在运行的时候也可能添加新的定时器。所以不能直接删掉,只能删掉已经运行的
this.tmq=this.tmq.concat(btmq);
//this.tmq.splice(0,i-1);
}
}
var gTimerQueue = new timerqueue();
export class _WindowTimersExtension {
clearImmediate(handle: number): void {
}
setImmediate(expression: any/*, ...args: any[]*/): number {
return 0;
}
}
export class _WindowTimers extends _WindowTimersExtension implements WindowTimers {
constructor() {
super();
}
clearInterval(handle: number): void {
gTimerQueue.delTimer(handle);
}
clearTimeout(handle: number): void {
gTimerQueue.delTimer(handle);
}
static ET:Array<any>=[];
setInterval(handler: any, timeout?:any,parm?:any): number {
var b=_WindowTimers.ET;
if(arguments.length>2)
{
b= Array.prototype.slice.call(arguments);
b.splice(0,2);
handler.arg=b;
}
return gTimerQueue.addTimer(timeout,b,handler,null,-1);
}
//定时器对象
//现在的问题是不能在回调中删除自己,否则会导致非法:
// tm=null; gc();
setTimeout(handler: any, timeout?: any,parm?:any): number {
if(!timeout) timeout=0;
var b=_WindowTimers.ET;
if(arguments.length>2)
{
b= Array.prototype.slice.call(arguments);
b.splice(0,2);
handler.arg=b;
}
return gTimerQueue.addTimer(timeout,b,handler,null,1);
}
}
var animfrm=0;
export function requestAnimationFrame(callback: FrameRequestCallback): number{
var id = animfrm++;
gTimerQueue.AniFrame.push({id:id,func:callback});
if(!gTimerQueue.AniFrameStTm)
gTimerQueue.AniFrameStTm=Date.now();
return id;
}
export function cancelAnimationFrame(handle: number): void{
}
var framCount=0;
var fpsTimeout=0;
conch.setOnFrame(function(){
if(framCount%30==0)
{
var cur=Date.now();
var space=(cur-fpsTimeout)/30;
fpsTimeout=cur;
window["conchFps"]&&window["conchFps"].render(Math.round(1000/space));
}
framCount++;
gTimerQueue.update();
if(document)
document.onframeend();
});
conch.setOnDraw((vsync)=>{
//console.log('draw');
var curAnimFrms = gTimerQueue.AniFrame;
gTimerQueue.AniFrame=[];
curAnimFrms.forEach(function(af){
if(af.del)return;
af.func(vsync);
});
});
}
var WindowTimers = ns_Timer._WindowTimers;
var requestAnimationFrame = ns_Timer.requestAnimationFrame;
var cancelAnimationFrame = ns_Timer.cancelAnimationFrame;
+155
View File
@@ -0,0 +1,155 @@
class CloseEvent extends Event {
code: number;
reason: string;
wasClean: boolean;
constructor() {
super('close');
}
initCloseEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, wasCleanArg: boolean, codeArg: number, reasonArg: string): void {
}
}
interface ErrorEvent extends Event {
colno: number;
error: any;
filename: string;
lineno: number;
message: string;
initErrorEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, messageArg: string, filenameArg: string, linenoArg: number): void;
}
interface MessagePort extends EventTarget {
onmessage: (ev: MessageEvent) => any;
close(): void;
postMessage(message?: any, ports?: any): void;
start(): void;
addEventListener(type: "message", listener: (ev: MessageEvent) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
}
interface MessageEventInit extends EventInit {
data?: any;
origin?: string;
lastEventId?: string;
channel?: string;
source?: any;
ports?: MessagePort[];
}
class MessageEvent extends Event {
data: any;
origin: string;
ports: any;
source: Window;
constructor(type: string, eventInitDict?: MessageEventInit) {
super(type);
}
initMessageEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, dataArg: any, originArg: string, lastEventIdArg: string, sourceArg: Window): void {
}
}
//ES6 start
interface WebSocket {
/*
addEventListener(type: "close", listener: (ev: CloseEvent) => any, useCapture?: boolean): void;
addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void;
addEventListener(type: "message", listener: (ev: MessageEvent) => any, useCapture?: boolean): void;
addEventListener(type: "open", listener: (ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
*/
}
/**
* 注意必须从 ConchWebSocket 继承,必须要用es6.否则无法new出带两个field的对象。
*/
/*
class WebSocket extends ConchWebSocket implements _EventTarget {
dispatchEvent: (evt: Event) => boolean;//接口
removeEventListener: (type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean) => void;//接口
onmessage: (data: MessageEvent) => void;
_onmessage: (data: ArrayBuffer | string) => void;
constructor(url: string) {
super(url);
this._onmessage = (data: ArrayBuffer | string) => {
var evt = new MessageEvent('message');
evt.data = data;
this.onmessage && this.onmessage(evt);
};
}
static CLOSED = 3;
static CLOSING = 2;
static CONNECTING = 0;
static OPEN = 1;
}
applyMixins(WebSocket, [EventTarget]);
*/
//ES6 end
//ES5 start
class WebSocket extends EventTarget {
private _nativeObj:ConchWebSocket=null;
onmessage: (data: MessageEvent) => void;
constructor(url: string) {
super();
this._nativeObj = new ConchWebSocket(url);
(<any>this._nativeObj)._onmessage = (data: ArrayBuffer | string) => {
var evt = new MessageEvent('message');
evt.data = data;
evt.target=evt.currentTarget=this;
this.onmessage && this.onmessage(evt);
};
}
get binaryType(){
return this._nativeObj.binaryType;
}
set binaryType(b:string){
this._nativeObj.binaryType=b;
}
get timegap(){
return this._nativeObj.timegap;
}
set onopen(f:(e)=>void){
this._nativeObj.onopen=function(){
var e=new Event("open");
e.target=e.currentTarget=this;
f(e);
};
}
set onclose(f:()=>void){
this._nativeObj.onclose=f;
}
set onerror(f:()=>void){
this._nativeObj.onerror=f;
}
close(){
this._nativeObj.close();
}
send(msg:string|ArrayBuffer):void{
this._nativeObj.send(msg);
}
get readyState():number
{
return this._nativeObj.readyState;
}
static CLOSED = 3;
static CLOSING = 2;
static CONNECTING = 0;
static OPEN = 1;
}
//ES5 end
window.WebSocket = WebSocket;
interface Socket {
addEventListener(type: "close", listener: (ev: CloseEvent) => any, useCapture?: boolean): void;
addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void;
addEventListener(type: "message", listener: (ev: MessageEvent) => any, useCapture?: boolean): void;
addEventListener(type: "open", listener: (ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
}
+319
View File
@@ -0,0 +1,319 @@
class XMLHttpRequest extends EventTarget{
public static UNSENT:number = 0;
public static OPENED:number = 1;
public static HEADERS_RECEIVED:number = 2;
public static LOADING:number = 3;
public static DONE:number = 4;
private xhr:_XMLHttpRequest;
private _responseText:string;
private _response:any;
private _responseType:string;
private _readyState:number;
private _status:number;
private _url:string;
private _async:boolean;
private _method:string;
private _onloadcb:(evt:Event)=>any;
private _onrchgcb:(evt:Event)=>any;
private _head:any;
private _hasReqHeader=false;
onerror:(evt:Event)=>any;
withCredentials:boolean=false;
constructor(){
super();
this.xhr=new _XMLHttpRequest();
this._readyState=0;
this._responseText=this._response=this._responseType=this._url="";
this._responseType="text";
this._method="GET";
this.xhr._t=this;
this.xhr.set_onreadystatechange(function(r:number):void{
var _t=this._t;
if (r == 1) {
_t._readyState = 1;
}
if (_t._onrchgcb ) {
//标准的回调是没有参数的。
var e=new _lbEvent("readystatechange");
e.target=_t;
_t._onrchgcb(e);
}
//模拟事件
var ev;
if(_t._status==200){
ev=new _lbEvent("load");
ev.target=_t;
_t.dispatchEvent(ev);
}else if(_t._status==404){
ev=new _lbEvent("error");
ev.target=_t;
_t.dispatchEvent(ev);
}
});
}
setRequestHeader(name:string,value:string):void{
this.xhr.setRequestHeader(name,value);
this._hasReqHeader=true;
}
getAllResponseHeaders(){
return this._head;
}
get responseText()
{
return this._responseText;
}
get response()
{
return this._response;
}
get responseType()
{
return this._responseType;
}
set responseType(type:string)
{
this._responseType=type;
if( type=='blob'){
this.xhr.responseTypeCode=4;
}
else if(type=='arraybuffer'){
this.xhr.responseTypeCode=5;
}else{
this.xhr.responseTypeCode= 1;
}
}
get url()
{
return this._url;
}
get async()
{
return this._async;
}
get readyState():number
{
return this._readyState;
}
get status():number
{
return this._status;
}
private _loadsus():void
{
var e=new _lbEvent("load");
e.target=this;
this._onloadcb(e);
}
set onreadystatechange(listen:(evt:Event)=>any)
{
this._onrchgcb=listen;
if(listen==null)return;
if(this._readyState!=0)
{
var e=new _lbEvent("readystatechange");
e.target=this;
this._onrchgcb(e);
}
}
get onreadystatechange():(evt:Event)=>any
{
return this._onrchgcb;
}
set onload(listen:((evt:Event)=>any))
{
this._onloadcb=listen;
if(listen==null)return;
if(this._readyState==4&&this._status==200)
{
this._loadsus();
}
}
get onload():(evt:Event)=>any
{
return this._onloadcb;
}
getResponseHeader()
{
return this._head;
}
setResponseHeader=function(name,value)
{
this._head=value;
}
open(type:string,url:string,async:boolean)
{
//url = encodeURI(url);
console.log('xhr.'+type+' url='+url);
if(!url)return;
type=type.toUpperCase();
async=true;
url=location.resolve(url);
this._method=(type==='POST'?'POST':'GET');
this._url = url;
this._async = (async == null || async == undefined || async == true) ? true : false;
this.xhr._open(this._method, this._url, this._async);
}
overrideMimeType(mime:string):void
{
if(this._responseType=="text"||this._responseText=="")
this._responseType="arraybuffer";
this.xhr.mimeType="1";
}
send(body:any):void
{
if(body){
if(body instanceof ArrayBuffer|| ArrayBuffer.isView(body) || body instanceof DataView )
this._responseType='arraybuffer';
else if( body instanceof Object){
body = JSON.stringify(body);
}
}
this.xhr._t=this;
var onPostLoad:any=function(buf,strbuf)
{
var _t=this._t;
if (_t.responseType == 'arraybuffer')
{
_t._response = buf;
_t._responseText = strbuf;
}
else
{
_t._response=_t._responseText=buf;
}
//console.log('xhr post ret:'+_this.responseText);
_t._readyState = 4;
_t._status = 200;
_t.xhr._changeState(4);
if(_t._onloadcb)
{
_t._loadsus();
}
onPostLoad.ref=onPostError.ref=null;
}
var onPostError:any=function(e1:number, e2:number){
var _t=this._t;//不用this是因为jsc有泄露
_t._readyState = 4;
_t._status = 404;//e; 目前好像只有200和404
_t.xhr._changeState(4);
if(_t.onerror)
{
var ev=new _lbEvent("error");
ev.target=_t;
ev['ecode1']=e1; //curl返回值
ev['ecode2']=e2; //http返回值。
_t.onerror(ev);
}
onPostLoad.ref=onPostError.ref=null;
}
if(this._method=='POST' && body){
onPostLoad.ref=onPostError.ref=this.xhr;
this.xhr.setPostCB( onPostLoad,onPostError );
this.xhr.postData(this.url,body);
}else if( this._hasReqHeader){
onPostLoad.ref=onPostError.ref=this.xhr;
this.xhr.setPostCB( onPostLoad,onPostError );
this.xhr.getData(this.url)
}
else
{
var file = new conch_File(this.url);
var fileRead = new FileReader();
fileRead.sync = !this.async;
if( this._responseType == "text" || this._responseType == "TEXT" ){
fileRead.responseType = 0;
}else if( this._responseType == "arraybuffer" ){
fileRead.responseType = 1;
}else{
console.log("XMLhttpRequest 暂不支持的类型 responseType=" + this.responseType );
}
fileRead._t=this;
fileRead.onload = function () {
var _t=this._t;
if( _t._responseType == "arraybuffer" ){
_t._response = this.result;
//_t._responseText=?
}else{
_t._response=_t._responseText = this.result;
if(_t._responseType=="json")
{
_t._response=JSON.parse(this.result);
}
}
if(_t.xhr.mimeType)
{
var u8arr = new Uint8Array(_t._response);
var strret="";
u8arr.forEach((v, i, arr) => {
if (v >=0x80) {
strret += String.fromCharCode(0xf700 | v);
}
else if( v==0 ){
strret+='\0';
}
else {
strret += String.fromCharCode(v);
}
});
_t._responseText = strret;
}
_t._readyState = 4;
_t._status = 200;
_t.xhr._changeState(4);
if (_t._onloadcb) {
_t._loadsus();
}
fileRead.onload =null;
fileRead.onerror = null;
//_this.onreadystatechange=null;
}
fileRead.onerror = function () {
var _t=this._t;
_t._readyState = 4;
_t._status = 404;
_t.xhr._changeState(4);
if(_t.onerror)
{
var ev=new _lbEvent("error");
ev.target=_t;
_t.onerror(ev);
}
fileRead.onload =null;
fileRead.onerror = null;
}
if(this.onerror){
fileRead.setIgnoreError(true);
}
if( this.responseType == "arraybuffer" )
fileRead.readAsArrayBuffer(file);
else
fileRead.readAsText(file);
}
}
//扩展的
/* async:boolean;
method:string;
evtmap:Object; //TODO 这个要去掉。*/
}
window.XMLHttpRequest=XMLHttpRequest;
+24
View File
@@ -0,0 +1,24 @@
(function () {
'use strict';
var gl = LayaGLContext;
window["extendWebGLPlusToWebGLContext"](gl);
class AppInfo {
name: string;
version: string;
devUpdateUrl: string;
updateUrl: string;
updateDelay: number;//更新延迟
DomJS: string;
mainjs: string;
};
var appobj:AppInfo = null;
try {
appobj = <AppInfo>JSON.parse(<string>conch.readFileFromAsset('app.json', 'utf8'));
if(appobj){
require(appobj.mainjs);
}
} catch (e) {
require('index');
}
})();
+271
View File
@@ -0,0 +1,271 @@
class JCMemClass{
getChangedFlag():boolean{
return false;
}
setChangedFlag(b:boolean){
}
getDataSize():number{
return 0;
}
getData():ArrayBuffer{
return null;
}
}
/**
* 一个方便操作的buffer
* 1. 直接根据数据构建
* 2. 随时修改:修改,添加,例如动态mesh
* 3. 可以分段提交
*/
class JCGpuBuffer {
//m_bChanged: boolean = false; //任意段发生修改
m_nStreamNum: number = 0; //
vbo: WebGLBuffer = 0;//gpu res
m_nVBLength: number = 0;//对应的显存的大小,如果内存大于显存了,需要重新调整
m_pMemBuffer:JCMemClass[];
m_vStreamStart: number[] = null;
m_nTotalSize=0;
create(size) {
}
/**
* 分段管理
*/
createStreams(s1size, s2size, s3size, ...args) {
this.m_nTotalSize=0;//++++
}
/**
* @param newvb 是否强制更新vb,不再使用老的。
*/
uploadTo(target, newvb: boolean) {
var gl:WebGLRenderingContext;
//计算总大小
this.m_nTotalSize=0;
for(var i=0; i<this.m_pMemBuffer.length; i++){
this.m_nTotalSize+= this.m_pMemBuffer[i].getDataSize();
}
if( this.vbo>0 && (newvb || this.m_nTotalSize>this.m_nVBLength)){
gl.deleteBuffer(this.vbo);//TODO 用重用的方法更好
this.vbo=0;
}
if(this.vbo<=0){
this.vbo = gl.createBuffer();
gl.bindBuffer(target,this.vbo);
gl.bufferData(target,this.m_nTotalSize,gl.DYNAMIC_DRAW); //分配空间
}
gl.bindBuffer(target,this.vbo);
for( var i=0; i<this.m_nStreamNum; i++){
gl.bufferSubData(target,this.m_vStreamStart[i],this.m_pMemBuffer[i].getData());
this.m_pMemBuffer[i].setChangedFlag(false);
}
this.m_nVBLength=this.m_nTotalSize;
}
getStreamMem(idx) {
}
freeGLRes() {
}
}
class JCVB extends JCGpuBuffer {
upload(force) {
}
}
class JCIB extends JCGpuBuffer {
createFromArray(arr) {
}
upload(force) {
}
appendData(p_pIdx, p_nNum, p_nVertOff){
}
}
class JCNamedData {
}
class JCVertexDesc {
m_VertDescs:any[];
getStride(): number {
return 0;
}
getHash() {
}
}
class JCShaderLinkInfo{
//这里包含stride
}
class JCMaterial {
}
/**
* 类似submesh
*/
class JCRenderGroupData {
m_pMesh: JCMesh;
m_nGeoMode: number;
m_nBegin: number = 0; //可能是顶点位置也可能是index位置
m_nEnd: number = 0;
m_bHasObjMat = false;
m_pShaderInfo: any = null;
m_pMaterial: JCMaterial = null;
m_nVertexDesc = 0; //第几个顶点描述
}
class JCMesh {
//m_nVertNum;
/**
* 本mesh用到的所有的顶点格式
*/
m_AllVertexDesc: JCVertexDesc[];
getVB(): JCVB {
return null;
}
getIB(): JCIB {
return null;
}
//缺省大小不用设置
//config(INITSize);
// getStride(id): number {
// return this.m_AllVertexDesc[id].getStride();
// }
regVertexDesc(vd:JCVertexDesc):number{
var h =vd.getHash();
//if( )
return this.m_AllVertexDesc.length;
}
freeGLRes() {
}
//删除内存数据,例如不会变的mesh
freeMemRes() {
}
upload() {
}
getGroupNum():number{
return 0;
}
}
/**
* 单流mesh
* TODO 是否需要一个只保留gpu资源的mesh
*/
class JCMesh1 extends JCMesh{
m_pCurGroup:JCRenderGroupData=null;
m_vRenderGroupDatas:JCRenderGroupData[]=null;
//直接创建vertex
pushVertex(vertType:number, geomode, mtl, {}):JCRenderGroupData {
return null;
}
/**
* 这种情况geomode固定为三角形
* @param relIdx 是否是相对的索引,如果是true,需要全部加上当前的顶点个数
*/
pushElement(vertType:number, mtl, {}, {}, relIdx:boolean) {
}
pushVertexBuf(vertType:number, geomode, mtl, data, len) {
var vetNum = 0;//datalen/stride
}
pushElementsBuf(vertType:number, mtl,vbdata, vblen, ibdata, iblen, relIdx:boolean):JCRenderGroupData {
if(vertType!=this.m_pCurGroup.m_nVertexDesc ||true){
//new group
}
return this.m_pCurGroup;
}
}
function renderMesh(mesh: JCMesh, group: JCRenderGroupData, data, datanum) {
var stride = group.getStride();
}
function fillTris(ib, vb, vertexdesc, shader, texture) {
}
class JCHtml5Context {
m_pDynamicMesh:JCGameMesh=null;
setIBVB(p_nIbId, p_nVbId, p_nShaderId, p_nImgId,
p_nStartIndex, p_nOffset, p_nNumElement, x, y, vertextype) {
var vbbuf;
var ibbuf;
var gpuProg;
var Img;
switch (vertextype) {
case 1://x,y,u,v,r,g,b,a
case 2://x,y,u,v
}
var vdesc: JCVertexDesc = null; //在ctx的成员变量中写死
var mtl:JCMaterial;
if(!vbbuf.vdid){//or <0
vbbuf.viid=this.m_pDynamicMesh.regVertexDesc(vdesc);
}
this.m_pDynamicMesh.pushElementsBuf(vbbuf.viid,mtl,vbbuf,1,ibbuf,1,true);
}
pushTriangleStripsData(pData, len,mtl){
}
}
//动态添加
//材质
//矩阵
//link需要全局的数据的描述
//link结果保存在什么地方
class JCGameMesh extends JCMesh1 {
strokeLink: JCShaderLinkInfo;
fillLink: JCShaderLinkInfo;
mapLink: JCShaderLinkInfo;
fillcolorLink: JCShaderLinkInfo;
drawImgLink: JCShaderLinkInfo;
render() {
}
}
//JCVertexDesc 和stride其实并没有什么关联 mesh属性描述中增加 m_nStride
//JCVertexDesc 与attrib有关
class JCRenderCmd{
}
function testWS(){
var ws = new WebSocket('ws://174.129.224.73/');
ws.onopen=function(ev){
console.log('open');
ws.send('hello');
}
ws.onmessage=function(msg){
console.log(msg);
}
}
+38
View File
@@ -0,0 +1,38 @@
{
"compilerOptions": {
"module": "system",
"noLib": true,
"target": "es6",
"noImplicitAny": false,
"rootDir": ".",
"removeComments": true,
"sourceMap": false,
"outFile": "../../../Redist/scripts/apploader.js"
},
"files": [
"RuntimeExt.ts",
"Base64.ts",
"Debugger.ts",
"Crypto.ts",
"Console.ts",
"Event.ts",
"Bluetooth.ts",
"Gamepad.ts",
"Storage.ts",
"Input.ts",
"Navigator.ts",
"Node.ts",
"Timer.ts",
"Location.ts",
"LayaDomSupport.ts",
"XMLHttpRequest.ts",
"CanvasCtx.ts",
"LayaGL.ts",
"HTMLElements.ts",
"Document.ts",
"WebSocket.ts",
"DOMParser.ts",
"Global.ts",
"apploader.ts"
]
}