How to use requireSimulator method in Appium Xcuitest Driver

Best JavaScript code snippet using appium-xcuitest-driver

runScript2_concat.js

Source:runScript2_concat.js Github

copy

Full Screen

1// Created at Mon Nov 09 2015 14:16:22 GMT+0900 (東京 (標準時))2(function () {3 var R={};4 R.def=function (reqs,func,type) {5 var m=R.getModuleInfo(R.curName);6 m.type=type;7 R.setReqs( m, reqs);8 m.func=function () {9 //console.log("reqjs ",m.name);10 return func.apply(this, R.getObjs(reqs));11 };12 R.loadIfAvailable(m);13 };14 define=function (reqs,func) {15 R.def(reqs,func,"define");16 };17 require=requirejs=function (reqs,func) {18 R.def(reqs,func,"require");19 };20 R.setReqs=function (m, reqs) {21 reqs.forEach(function (req) {22 var reqm=R.getModuleInfo(req);23 if (!reqm.loaded) {24 m.reqs[req]=reqm;25 reqm.revReqs[m.name]=m;26 }27 });28 };29 R.getModuleInfo=function (name) {30 var ms=R.modules;31 if (!ms[name]) ms[name]={name:name,reqs:{},revReqs:{}};32 return ms[name];33 };34 R.doLoad=function (name) {35 var m=R.getModuleInfo(name);36 //console.log("doLoad ",name, m.loaded, m.func);37 if (m.loaded) return m.obj;38 m.loaded=true;39 var res=null;40 if (m.func) res=m.func();41 else {42 var names=name.split(/\./);43 res=(function () {return this;})();44 names.forEach(function (name) {45 if (res) res=res[name];46 });47 if ( res==null) console.log("Warning: No obj for "+name);48 }49 if ( m.type=="define" && res==null) throw("No obj for "+name);50 m.obj=res;51 for (var i in m.revReqs) {52 R.notifyLoaded(m.revReqs[i], m.name);53 }54 return res;55 };56 R.notifyLoaded=function (revReq, loadedModuleName) {57 delete revReq.reqs[loadedModuleName];58 R.loadIfAvailable(revReq);59 };60 R.loadIfAvailable=function (m) {61 for (var i in m.reqs) {62 return;63 }64 R.doLoad(m.name);65 };66 R.getObjs=function (ary) {67 var res=[];68 ary.forEach(function (n) {69 var cur=R.doLoad(n);70 res.push(cur);71 });72 return res;73 };74 R.modules={};75 R.setName=function (n) {76 if (R.curName) {77 if (!R.getModuleInfo(R.curName).func) {78 R.doLoad(R.curName);79 }80 }81 if (n) {82 R.curName=n;83 }84 };85 requireSimulator=R;86 return R;87})();88requireSimulator.setName('extend');89define([],function (){90 return function extend(d,s) {91 for (var i in s) {d[i]=s[i];} 92 };93});94requireSimulator.setName('assert');95define([],function () {96 var Assertion=function(failMesg) {97 this.failMesg=flatten(failMesg || "Assertion failed: ");98 };99 Assertion.prototype={100 fail:function () {101 var a=$a(arguments);102 a=flatten(a);103 a=this.failMesg.concat(a);104 console.log.apply(console,a);105 throw new Error(a.join(" "));106 },107 subAssertion: function () {108 var a=$a(arguments);109 a=flatten(a);110 return new Assertion(this.failMesg.concat(a));111 },112 assert: function (t,failMesg) {113 if (!t) this.fail(failMesg);114 return t;115 },116 eq: function (a,b) {117 if (a!==b) this.fail(a,"!==",b);118 return a;119 },120 is: function (value,type) {121 var t=type,v=value;122 if (t==null) return t;123 if (t._assert_func) {124 t._assert_func.apply(this,[v]);125 return value;126 }127 this.assert(value!=null,[value, "should be ",t]);128 if (t instanceof Array || (typeof global=="object" && typeof global.Array=="function" && t instanceof global.Array) ) {129 if (!value || typeof value.length!="number") {130 this.fail(value, "should be array:");131 }132 var self=this;133 for (var i=0 ;i<t.length; i++) {134 var na=self.subAssertion("failed at ",value,"[",i,"]: ");135 na.is(v[i],t[i]);136 }137 return value;138 }139 if (t===String || t=="string") {140 this.assert(typeof(v)=="string",[v,"should be a string "]);141 return value;142 }143 if (t===Number || t=="number") {144 this.assert(typeof(v)=="number",[v,"should be a number"]);145 return value;146 }147 if (t instanceof RegExp || (typeof global=="object" && typeof global.RegExp=="function" && t instanceof global.RegExp)) {148 this.is(v,String);149 this.assert(t.exec(v),[v,"does not match to",t]);150 return value;151 }152 if (typeof t=="function") {153 this.assert((v instanceof t),[v, "should be ",t]);154 return value;155 }156 if (t && typeof t=="object") {157 for (var k in t) {158 var na=this.subAssertion("failed at ",value,".",k,":");159 na.is(value[k],t[k]);160 }161 return value;162 }163 this.fail("Invaild type: ",t);164 },165 ensureError: function (action, err) {166 try {167 action();168 } catch(e) {169 if(typeof err=="string") {170 assert(e+""===err,action+" thrown an error "+e+" but expected:"+err);171 }172 console.log("Error thrown successfully: ",e.message);173 return;174 }175 this.fail(action,"should throw an error",err);176 }177 };178 /*var assert=function () {179 var a=assert.a(arguments);180 var t=a.shift();181 if (!t) assert.fail(a);182 return true;183 };*/184 $a=function (args) {185 var a=[];186 for (var i=0; i<args.length ;i++) a.push(args[i]);187 return a;188 };189 var top=new Assertion;190 var assert=function () {191 try {192 return top.assert.apply(top,arguments);193 } catch(e) {194 throw new Error(e.message);195 }196 };197 assert.is=function () {198 try {199 return top.is.apply(top,arguments);200 } catch(e) {201 throw new Error(e.message);202 }203 };204 assert.eq=function () {205 try {206 return top.eq.apply(top,arguments);207 } catch(e) {208 throw new Error(e.message);209 }210 };211 assert.ensureError=function () {212 try {213 return top.ensureError.apply(top,arguments);214 } catch(e) {215 throw new Error(e.message);216 }217 };218 assert.fail=top.fail.bind(top);219 /*220 assert.fail=function () {221 var a=assert.a(arguments);222 a=flatten(a);223 a.unshift("Assertion failed: ");224 console.log.apply(console,a);225 throw new Error(a.join(" "));226 };227 assert.is=function (value, type, mesg) {228 var t=type,v=value;229 mesg=mesg||[];230 if (t==null) return true;231 assert(value!=null,mesg.concat([value, "should not be null/undef"]));232 if (t instanceof Array) {233 if (!value || typeof value.length!="number") {234 assert.fail(mesg.concat([value, "should be array:", type]));235 }236 t.forEach(function (te,i) {237 assert.is(value[i],te,mesg.concat(["failed at ",value,"[",i,"]: "]));238 });239 return;240 }241 if (t===String || t=="string") {242 return assert(typeof(v)=="string",243 mesg.concat([v,"should be string "]));244 }245 if (t===Number || t=="number") {246 return assert(typeof(v)=="number",247 mesg.concat([v,"should be number"]));248 }249 if (t instanceof Object) {250 for (var k in t) {251 assert.is(value[k],t[k],mesg.concat(["failed at ",value,".",k,":"]));252 }253 return true;254 }255 if (t._assert_func) {256 return t._assert_func(v,mesg);257 }258 return assert(v instanceof t,259 mesg.concat([v, "should be ",t]));260 };*/261 assert.f=function (f) {262 return {263 _assert_func: f264 };265 };266 assert.and=function () {267 var types=$a(arguments);268 assert(types instanceof Array);269 return assert.f(function (value) {270 var t=this;271 for (var i=0; i<types.length; i++) {272 t.is(value,types[i]);273 }274 });275 };276 function flatten(a) {277 if (a instanceof Array) {278 var res=[];279 a.forEach(function (e) {280 res=res.concat(flatten(e));281 });282 return res;283 }284 return [a];285 }286 function isArg(a) {287 return "length" in a && "caller" in a && "callee" in a;288 };289 return assert;290});291requireSimulator.setName('PathUtil');292define(["assert"],function (assert) {293function endsWith(str,postfix) {294 assert.is(arguments,[String,String]);295 return str.substring(str.length-postfix.length)===postfix;296}297function startsWith(str,prefix) {298 assert.is(arguments,[String,String]);299 return str.substring(0, prefix.length)===prefix;300}301var driveLetter=/^([a-zA-Z]):/;302var PathUtil;303var Path=assert.f(function (s) {304 this.is(s,String);305 this.assert( PathUtil.isPath(s) , [s, " is not a path"]);306});307var Absolute=assert.f(function (s) {308 this.is(s,String);309 this.assert( PathUtil.isAbsolutePath(s) , [s, " is not a absolute path"]);310});311var Relative=assert.f(function (s) {312 this.is(s,String);313 this.assert( !PathUtil.isAbsolutePath(s) , [s, " is not a relative path"]);314});315var AbsDir=assert.and(Dir,Absolute);316var Dir=assert.f(function (s) {317 this.is(s,Path);318 this.assert( PathUtil.isDir(s) , [s, " is not a directory path"]);319});320var File=assert.f(function (s) {321 this.is(s,Path);322 this.assert( !PathUtil.isDir(s) , [s, " is not a file path"]);323});324var SEP="/";325PathUtil={326 Path: Path,Absolute:Absolute, Relative:Relative, Dir:Dir,File:File,327 AbsDir:AbsDir,328 SEP: SEP,329 endsWith: endsWith, startsWith:startsWith,330 hasDriveLetter: function (path) {331 return driveLetter.exec(path);332 },333 isPath: function (path) {334 assert.is(arguments,[String]);335 return !path.match(/\/\//);336 },337 isRelativePath: function (path) {338 assert.is(arguments,[String]);339 return PathUtil.isPath(path) && !PathUtil.isAbsolutePath(path);340 },341 isAbsolutePath: function (path) {342 assert.is(arguments,[String]);343 return PathUtil.isPath(path) &&344 (PathUtil.startsWith(path,SEP) || PathUtil.hasDriveLetter(path));345 },346 isDir: function (path) {347 assert.is(arguments,[Path]);348 return endsWith(path,SEP);349 },350 splitPath: function (path) {351 assert.is(arguments,[Path]);352 var res=path.split(SEP);353 if (res[res.length-1]=="") {354 res[res.length-2]+=SEP;355 res.pop();356 }357 return res;358 },359 name: function(path) {360 assert.is(arguments,[String]);361 return PathUtil.splitPath(path).pop();362 },363 ext: function(path) {364 assert.is(arguments,[String]);365 var n = PathUtil.name(path);366 var r = (/\.[a-zA-Z0-9]+$/).exec(n);367 if (r) return r[0];368 return null;369 },370 truncExt: function(path, ext) {371 assert.is(path,String);372 var name = PathUtil.name(path);373 ext=ext || PathUtil.ext(path);374 assert.is(ext,String);375 return name.substring(0, name.length - ext.length);376 },377 truncSEP: function (path) {378 assert.is(arguments,[Path]);379 if (!PathUtil.isDir(path)) return path;380 return path.substring(0,path.length-1);381 },382 endsWith: function(path, postfix) {383 assert.is(arguments,[String,String]);384 return endsWith(PathUtil.name(path), postfix);385 },386 parent: function(path) {387 assert.is(arguments,[String]);388 return PathUtil.up(path);389 },390 rel: function(path,relPath) {391 assert.is(arguments,[AbsDir, Relative]);392 var paths=PathUtil.splitPath(relPath);393 var resPath=path;394 resPath=resPath.replace(/\/$/,"");395 var t=PathUtil;396 paths.forEach(function (n) {397 if (n==".." || n=="../") resPath=t.up(resPath);398 else {399 resPath=resPath.replace(/\/$/,"");400 resPath+=SEP+(n=="."||n=="./" ? "": n);401 }402 });403 return resPath;404 },405 relPath: function(path,base) {406 assert.is(arguments,[AbsDir,AbsDir]);407 if (path.substring(0,base.length)!=base) {408 return "../"+PathUtil.relPath(path, this.up(base));409 }410 return path.substring(base.length);411 },412 up: function(path) {413 assert.is(arguments,[Path]);414 if (path==SEP) return null;415 var ps=PathUtil.splitPath(path);416 ps.pop();417 return ps.join(SEP)+SEP;418 }419};420return PathUtil;421});422requireSimulator.setName('MIMETypes');423define([], function () {424 return {425 ".png":"image/png",426 ".gif":"image/gif",427 ".jpeg":"image/jpeg",428 ".jpg":"image/jpeg",429 ".ico":"image/icon",430 ".mp3":"audio/mp3",431 ".ogg":"audio/ogg",432 ".txt":"text/plain",433 ".html":"text/html",434 ".htm":"text/html",435 ".css":"text/css",436 ".js":"text/javascript",437 ".json":"text/json",438 ".zip":"application/zip",439 ".swf":"application/x-shockwave-flash",440 ".pdf":"application/pdf",441 ".doc":"application/word",442 ".xls":"application/excel",443 ".ppt":"application/powerpoint",444 '.docx':'application/vnd.openxmlformats-officedocument.wordprocessingml.document',445 '.docm':'application/vnd.ms-word.document.macroEnabled.12',446 '.dotx':'application/vnd.openxmlformats-officedocument.wordprocessingml.template',447 '.dotm':'application/vnd.ms-word.template.macroEnabled.12',448 '.xlsx':'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',449 '.xlsm':'application/vnd.ms-excel.sheet.macroEnabled.12',450 '.xltx':'application/vnd.openxmlformats-officedocument.spreadsheetml.template',451 '.xltm':'application/vnd.ms-excel.template.macroEnabled.12',452 '.xlsb':'application/vnd.ms-excel.sheet.binary.macroEnabled.12',453 '.xlam':'application/vnd.ms-excel.addin.macroEnabled.12',454 '.pptx':'application/vnd.openxmlformats-officedocument.presentationml.presentation',455 '.pptm':'application/vnd.ms-powerpoint.presentation.macroEnabled.12',456 '.potx':'application/vnd.openxmlformats-officedocument.presentationml.template',457 '.potm':'application/vnd.ms-powerpoint.template.macroEnabled.12',458 '.ppsx':'application/vnd.openxmlformats-officedocument.presentationml.slideshow',459 '.ppsm':'application/vnd.ms-powerpoint.slideshow.macroEnabled.12',460 '.ppam':'application/vnd.ms-powerpoint.addin.macroEnabled.12',461 ".tonyu":"text/tonyu"462 };463});464requireSimulator.setName('DataURL');465define(["extend","assert"],function (extend,assert) {466 var A=(typeof Buffer!="undefined") ? Buffer :ArrayBuffer;467 function isBuffer(data) {468 return data instanceof ArrayBuffer ||469 (typeof Buffer!="undefined" && data instanceof Buffer);470 }471 var DataURL=function (data, contentType){472 // data: String/Array/ArrayBuffer473 if (typeof data=="string") {474 this.url=data;475 this.dataURL2bin(data);476 } else if (data && isBuffer(data.buffer)) {477 this.buffer=data.buffer;478 assert.is(contentType,String);479 this.contentType=contentType;480 this.bin2dataURL(this.buffer, this.contentType);481 } else if (isBuffer(data)) {482 this.buffer=data;483 assert.is(contentType,String);484 this.contentType=contentType;485 this.bin2dataURL(this.buffer, this.contentType);486 } else assert.fail("Invalid args: ",arguments);487 };488 extend(DataURL.prototype,{489 bin2dataURL: function (b, contentType) {490 assert(isBuffer(b));491 assert.is(contentType,String);492 var head=this.dataHeader(contentType);493 var base64=Base64_From_ArrayBuffer(b);494 assert.is(base64,String);495 return this.url=head+base64;496 },497 dataURL2bin: function (dataURL) {498 assert.is(arguments,[String]);499 var reg=/data:([^;]+);base64,(.*)$/i;500 var r=reg.exec(dataURL);501 assert(r, ["malformed dataURL:", dataURL] );502 this.contentType=r[1];503 this.buffer=Base64_To_ArrayBuffer(r[2]);504 return assert.is(this.buffer , A);505 },506 dataHeader: function (ctype) {507 assert.is(arguments,[String]);508 return "data:"+ctype+";base64,";509 },510 toString: function () {return assert.is(this.url,String);}511 });512 function Base64_To_ArrayBuffer(base64){513 base64=base64.replace(/[\n=]/g,"");514 var dic = new Object();515 dic[0x41]= 0; dic[0x42]= 1; dic[0x43]= 2; dic[0x44]= 3; dic[0x45]= 4; dic[0x46]= 5; dic[0x47]= 6; dic[0x48]= 7; dic[0x49]= 8; dic[0x4a]= 9; dic[0x4b]=10; dic[0x4c]=11; dic[0x4d]=12; dic[0x4e]=13; dic[0x4f]=14; dic[0x50]=15;516 dic[0x51]=16; dic[0x52]=17; dic[0x53]=18; dic[0x54]=19; dic[0x55]=20; dic[0x56]=21; dic[0x57]=22; dic[0x58]=23; dic[0x59]=24; dic[0x5a]=25; dic[0x61]=26; dic[0x62]=27; dic[0x63]=28; dic[0x64]=29; dic[0x65]=30; dic[0x66]=31;517 dic[0x67]=32; dic[0x68]=33; dic[0x69]=34; dic[0x6a]=35; dic[0x6b]=36; dic[0x6c]=37; dic[0x6d]=38; dic[0x6e]=39; dic[0x6f]=40; dic[0x70]=41; dic[0x71]=42; dic[0x72]=43; dic[0x73]=44; dic[0x74]=45; dic[0x75]=46; dic[0x76]=47;518 dic[0x77]=48; dic[0x78]=49; dic[0x79]=50; dic[0x7a]=51; dic[0x30]=52; dic[0x31]=53; dic[0x32]=54; dic[0x33]=55; dic[0x34]=56; dic[0x35]=57; dic[0x36]=58; dic[0x37]=59; dic[0x38]=60; dic[0x39]=61; dic[0x2b]=62; dic[0x2f]=63;519 var num = base64.length;520 var n = 0;521 var b = 0;522 var e;523 if(!num) return (new A(0));524 //if(num < 4) return null;525 //if(num % 4) return null;526 // AA 12 1527 // AAA 18 2528 // AAAA 24 3529 // AAAAA 30 3530 // AAAAAA 36 4531 // num*6/8532 e = Math.floor(num / 4 * 3);533 if(base64.charAt(num - 1) == '=') e -= 1;534 if(base64.charAt(num - 2) == '=') e -= 1;535 var ary_buffer = new A( e );536 var ary_u8 = (typeof Buffer!="undefined" ? ary_buffer : new Uint8Array( ary_buffer ));537 var i = 0;538 var p = 0;539 while(p < e){540 b = dic[base64.charCodeAt(i)];541 if(b === undefined) fail("Invalid letter: "+base64.charCodeAt(i));//return null;542 n = (b << 2);543 i ++;544 b = dic[base64.charCodeAt(i)];545 if(b === undefined) fail("Invalid letter: "+base64.charCodeAt(i))546 ary_u8[p] = n | ((b >> 4) & 0x3);547 /*if (p==0) {548 console.log("WOW!", n | ((b >> 4) & 0x3), ary_u8[p]);549 }*/550 n = (b & 0x0f) << 4;551 i ++;552 p ++;553 if(p >= e) break;554 b = dic[base64.charCodeAt(i)];555 if(b === undefined) fail("Invalid letter: "+base64.charCodeAt(i))556 ary_u8[p] = n | ((b >> 2) & 0xf);557 n = (b & 0x03) << 6;558 i ++;559 p ++;560 if(p >= e) break;561 b = dic[base64.charCodeAt(i)];562 if(b === undefined) fail("Invalid letter: "+base64.charCodeAt(i))563 ary_u8[p] = n | b;564 i ++;565 p ++;566 }567 function fail(m) {568 console.log(m);569 console.log(base64,i);570 throw new Error(m);571 }572 //console.log("WOW!", ary_buffer[0],ary_u8[0]);573 return ary_buffer;574 }575 function Base64_From_ArrayBuffer(ary_buffer){576 var dic = [577 'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P',578 'Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f',579 'g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v',580 'w','x','y','z','0','1','2','3','4','5','6','7','8','9','+','/'581 ];582 var base64 = "";583 var ary_u8 = new Uint8Array( ary_buffer );584 var num = ary_u8.length;585 var n = 0;586 var b = 0;587 var i = 0;588 while(i < num){589 b = ary_u8[i];590 base64 += dic[(b >> 2)];591 n = (b & 0x03) << 4;592 i ++;593 if(i >= num) break;594 b = ary_u8[i];595 base64 += dic[n | (b >> 4)];596 n = (b & 0x0f) << 2;597 i ++;598 if(i >= num) break;599 b = ary_u8[i];600 base64 += dic[n | (b >> 6)];601 base64 += dic[(b & 0x3f)];602 i ++;603 }604 var m = num % 3;605 if(m){606 base64 += dic[n];607 }608 if(m == 1){609 base64 += "==";610 }else if(m == 2){611 base64 += "=";612 }613 return base64;614 }615 return DataURL;616});617requireSimulator.setName('Contents');618define(["DataURL"],function (DataURL){619 var Contents={620 convert: function (src, destType, options) {621 // options:{encoding: , contentType: }622 // src: String|DataURL|ArrayBuffer|OutputStream|Writer623 // destType: String|DataURL|ArrayBuffer|InputStream|Reader624 var srcType;625 if (typeof src=="string") srcType=String;626 if (src instanceof DataURL) srcType=DataURL;627 if (src instanceof ArrayBuffer) srcType=ArrayBuffer;628 if (srcType==destType) return src;629 throw new Error("Cannot convert from "+srcType+" to "+destType);630 }631 };632 return Contents;633});634requireSimulator.setName('Util');635Util=(function () {636function getQueryString(key, default_)637{638 if (default_==null) default_="";639 key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");640 var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");641 var qs = regex.exec(window.location.href);642 if(qs == null)643 return default_;644 else645 return decodeURLComponentEx(qs[1]);646}647function decodeURLComponentEx(s){648 return decodeURIComponent(s.replace(/\+/g, '%20'));649}650function endsWith(str,postfix) {651 return str.substring(str.length-postfix.length)===postfix;652}653function startsWith(str,prefix) {654 return str.substring(0, prefix.length)===prefix;655}656// From http://hakuhin.jp/js/base64.html#BASE64_DECODE_ARRAY_BUFFER657function Base64_To_ArrayBuffer(base64){658 base64=base64.replace(/[\n=]/g,"");659 var dic = new Object();660 dic[0x41]= 0; dic[0x42]= 1; dic[0x43]= 2; dic[0x44]= 3; dic[0x45]= 4; dic[0x46]= 5; dic[0x47]= 6; dic[0x48]= 7; dic[0x49]= 8; dic[0x4a]= 9; dic[0x4b]=10; dic[0x4c]=11; dic[0x4d]=12; dic[0x4e]=13; dic[0x4f]=14; dic[0x50]=15;661 dic[0x51]=16; dic[0x52]=17; dic[0x53]=18; dic[0x54]=19; dic[0x55]=20; dic[0x56]=21; dic[0x57]=22; dic[0x58]=23; dic[0x59]=24; dic[0x5a]=25; dic[0x61]=26; dic[0x62]=27; dic[0x63]=28; dic[0x64]=29; dic[0x65]=30; dic[0x66]=31;662 dic[0x67]=32; dic[0x68]=33; dic[0x69]=34; dic[0x6a]=35; dic[0x6b]=36; dic[0x6c]=37; dic[0x6d]=38; dic[0x6e]=39; dic[0x6f]=40; dic[0x70]=41; dic[0x71]=42; dic[0x72]=43; dic[0x73]=44; dic[0x74]=45; dic[0x75]=46; dic[0x76]=47;663 dic[0x77]=48; dic[0x78]=49; dic[0x79]=50; dic[0x7a]=51; dic[0x30]=52; dic[0x31]=53; dic[0x32]=54; dic[0x33]=55; dic[0x34]=56; dic[0x35]=57; dic[0x36]=58; dic[0x37]=59; dic[0x38]=60; dic[0x39]=61; dic[0x2b]=62; dic[0x2f]=63;664 var num = base64.length;665 var n = 0;666 var b = 0;667 var e;668 if(!num) return (new ArrayBuffer(0));669 //if(num < 4) return null;670 //if(num % 4) return null;671 // AA 12 1672 // AAA 18 2673 // AAAA 24 3674 // AAAAA 30 3675 // AAAAAA 36 4676 // num*6/8677 e = Math.floor(num / 4 * 3);678 if(base64.charAt(num - 1) == '=') e -= 1;679 if(base64.charAt(num - 2) == '=') e -= 1;680 var ary_buffer = new ArrayBuffer( e );681 var ary_u8 = new Uint8Array( ary_buffer );682 var i = 0;683 var p = 0;684 while(p < e){685 b = dic[base64.charCodeAt(i)];686 if(b === undefined) fail("Invalid letter: "+base64.charCodeAt(i));//return null;687 n = (b << 2);688 i ++;689 b = dic[base64.charCodeAt(i)];690 if(b === undefined) fail("Invalid letter: "+base64.charCodeAt(i))691 ary_u8[p] = n | ((b >> 4) & 0x3);692 n = (b & 0x0f) << 4;693 i ++;694 p ++;695 if(p >= e) break;696 b = dic[base64.charCodeAt(i)];697 if(b === undefined) fail("Invalid letter: "+base64.charCodeAt(i))698 ary_u8[p] = n | ((b >> 2) & 0xf);699 n = (b & 0x03) << 6;700 i ++;701 p ++;702 if(p >= e) break;703 b = dic[base64.charCodeAt(i)];704 if(b === undefined) fail("Invalid letter: "+base64.charCodeAt(i))705 ary_u8[p] = n | b;706 i ++;707 p ++;708 }709 function fail(m) {710 console.log(m);711 console.log(base64,i);712 throw new Error(m);713 }714 return ary_buffer;715}716function Base64_From_ArrayBuffer(ary_buffer){717 var dic = [718 'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P',719 'Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f',720 'g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v',721 'w','x','y','z','0','1','2','3','4','5','6','7','8','9','+','/'722 ];723 var base64 = "";724 var ary_u8 = new Uint8Array( ary_buffer );725 var num = ary_u8.length;726 var n = 0;727 var b = 0;728 var i = 0;729 while(i < num){730 b = ary_u8[i];731 base64 += dic[(b >> 2)];732 n = (b & 0x03) << 4;733 i ++;734 if(i >= num) break;735 b = ary_u8[i];736 base64 += dic[n | (b >> 4)];737 n = (b & 0x0f) << 2;738 i ++;739 if(i >= num) break;740 b = ary_u8[i];741 base64 += dic[n | (b >> 6)];742 base64 += dic[(b & 0x3f)];743 i ++;744 }745 var m = num % 3;746 if(m){747 base64 += dic[n];748 }749 if(m == 1){750 base64 += "==";751 }else if(m == 2){752 base64 += "=";753 }754 return base64;755}756function privatize(o){757 if (o.__privatized) return o;758 var res={__privatized:true};759 for (var n in o) {760 (function (n) {761 var m=o[n];762 if (n.match(/^_/)) return;763 if (typeof m!="function") return;764 res[n]=function () {765 var r=m.apply(o,arguments);766 return r;767 };768 })(n);769 }770 return res;771}772return {773 getQueryString:getQueryString,774 endsWith: endsWith, startsWith: startsWith,775 Base64_To_ArrayBuffer:Base64_To_ArrayBuffer,776 Base64_From_ArrayBuffer:Base64_From_ArrayBuffer,777 privatize: privatize778};779})();780requireSimulator.setName('SFile');781define(["Contents","extend","assert","PathUtil","Util"],782function (C,extend,A,P,Util) {783var SFile=function (fs, path) {784 A.is(path, P.Absolute);785 A(fs && fs.getReturnTypes);786 this._path=path;787 this.fs=fs;788 if (this.isDir() && !P.isDir(path)) {789 this._path+=P.SEP;790 }791};792SFile.is=function (path) {793 return path && typeof (path.isSFile)=="function" && path.isSFile();794};795function getPath(f) {796 if (SFile.is(f)) {797 return f.path();798 } else {799 A.is(f,P.Absolute);800 return f;801 }802}803SFile.prototype={804 isSFile: function (){return true;},805 setPolicy: function (p) {806 if (this.policy) throw new Error("policy already set");807 this.policy=p;808 return this._clone();809 },810 _clone: function (){811 return this._resolve(this.path());812 },813 _resolve: function (path) {814 var res;815 if (SFile.is(path)) {816 res=path;817 } else {818 A.is(path,P.Absolute);819 var topdir;820 if (this.policy && (topdir=this.policy.topDir)) {821 if (topdir.path) topdir=topdir.path();822 if (!P.startsWith(path, topdir)) {823 throw new Error(path+": cannot access. Restricted to "+topdir);824 }825 }826 res=this.fs.getRootFS().get(path);827 res.policy=this.policy;828 }829 if (res.policy) {830 return Util.privatize(res);831 } else {832 return res;833 }834 },835 contains: function (file) {836 A(SFile.is(file),file+" shoud be a SFile object.");837 if (!this.isDir()) return false;838 return P.startsWith( file.path(), this.path());839 },840 // Path from Root841 path: function () {842 return this._path;//this.fs.getPathFromRootFS(this.pathT);843 },844 // Path from This fs845 /*pathInThisFS: function () {846 return this.pathT;847 },*/848 name: function () {849 return P.name(this.path());850 },851 truncExt: function (ext) {852 return P.truncExt(this.path(),ext);853 },854 ext: function () {855 return P.ext(this.path());856 },857 relPath: function (base) {858 // base should be SFile or Path from rootFS859 var bp=(base.path ?860 base.path() :861 base );862 return P.relPath(this.path(), A.is(bp,P.Absolute) );863 },864 up:function () {865 var pathR=this.path();866 var pa=P.up(pathR);867 if (pa==null) return null;868 return this._resolve(pa);869 },870 rel: function (relPath) {871 A.is(relPath, P.Relative);872 this.assertDir();873 var pathR=this.path();874 return this._resolve(P.rel(pathR, relPath));875 },876 startsWith: function (pre) {877 return P.startsWith(this.name(),pre);878 },879 endsWith: function (post) {880 return P.endsWith(this.name(),post);881 },882 equals:function (o) {883 return (o && typeof o.path=="function" && o.path()==this.path());884 },885 toString:function (){886 return this.path();887 },888 //Common889 touch: function () {890 this.fs.touch(this.path());891 },892 isReadOnly: function () {893 this.fs.isReadOnly(this.path());894 },895 isTrashed:function () {896 var m=this.metaInfo();897 if (!m) return false;898 return m.trashed;899 },900 metaInfo: function () {901 if (arguments.length==0) {902 return this.getMetaInfo.apply(this,arguments);903 } else {904 return this.setMetaInfo.apply(this,arguments);905 }906 },907 getMetaInfo: function (options) {908 return this.fs.getMetaInfo(this.path(),options);909 },910 setMetaInfo: function (info, options) {911 return this.fs.setMetaInfo(this.path(),info, options);912 },913 lastUpdate:function () {914 A(this.exists());915 return this.metaInfo().lastUpdate;916 },917 /*rootFS: function () {918 return this.fs.getRootFS();919 },*/920 exists: function (options) {921 options=options||{};922 var p=this.fs.exists(this.path(),options);923 if (p || options.noFollowLink) {924 return p;925 } else {926 return this.resolveLink().exists({noFollowLink:true});927 }928 },929 /*copyTo: function (dst, options) {930 this.fs.cp(this.path(),getPath(dst),options);931 },*/932 rm: function (options) {933 options=options||{};934 if (!this.exists({noFollowLink:true})) {935 var l=this.resolveLink();936 if (!this.equals(l)) return l.rm(options);937 }938 if (this.isDir() && (options.recursive||options.r)) {939 this.each(function (f) {940 f.rm(options);941 });942 }943 var pathT=this.path();944 this.fs.rm(pathT, options);945 },946 removeWithoutTrash: function (options) {947 options=options||{};948 options.noTrash=true;949 this.rm(options);950 },951 isDir: function () {952 return this.fs.isDir(this.path());953 },954 // File955 text:function () {956 var l=this.resolveLink();957 if (!this.equals(l)) return l.text.apply(l,arguments);958 if (arguments.length>0) {959 this.setText(arguments[0]);960 } else {961 return this.getText();962 }963 },964 setText:function (t) {965 A.is(t,String);966 this.fs.setContent(this.path(), t);967 },968 getText:function (t) {969 return this.fs.getContent(this.path(), {type:String});970 },971 setBytes:function (b) {972 A.is(t,ArrayBuffer);973 return this.fs.setContent(b);974 },975 getBytes:function (t) {976 return this.fs.getContent(this.path(), {type:ArrayBuffer});977 },978 getURL: function () {979 return this.fs.getURL(this.path());980 },981 lines:function () {982 return this.text().split("\n");983 },984 obj: function () {985 var file=this;986 if (arguments.length==0) {987 var t=file.text();988 if (!t) return null;989 return JSON.parse(t);990 } else {991 file.text(JSON.stringify(A.is(arguments[0],Object) ));992 }993 },994 copyTo: function (dst, options) {995 return dst.copyFrom(this,options);996 },997 copyFrom: function (src, options) {998 var dst=this;999 var options=options||{};1000 var srcIsDir=src.isDir();1001 var dstIsDir=dst.isDir();1002 if (!srcIsDir && dstIsDir) {1003 dst=dst.rel(src.name());1004 assert(!dst.isDir(), dst+" is a directory.");1005 dstIsDir=false;1006 }1007 if (srcIsDir && !dstIsDir) {1008 this.err("Cannot move dir to file");1009 } else if (!srcIsDir && !dstIsDir) {1010 if (options.echo) options.echo(src+" -> "+dst);1011 return this.fs.cp(A.is(src.path(), P.Absolute), dst.path(),options);1012 /*var srcc=src.getText(); // TODO1013 var res=dst.setText(srcc);1014 if (options.a) {1015 dst.setMetaInfo(src.getMetaInfo());1016 }1017 return res;*/1018 } else {1019 A(srcIsDir && dstIsDir);1020 src.each(function (s) {1021 dst.rel(s.name()).copyFrom(s, options);1022 });1023 }1024 //file.text(src.text());1025 //if (options.a) file.metaInfo(src.metaInfo());1026 },1027 moveFrom: function (src, options) {1028 var res=this.copyFrom(src,options);1029 src.rm({recursive:true});1030 return res;//this.fs.mv(getPath(src),this.path(),options);1031 },1032 // Dir1033 assertDir:function () {1034 A.is(this.path(),P.Dir);1035 return this;1036 },1037 /*files:function (f,options) {1038 var dir=this.assertDir();1039 var res=[];1040 this.each(function (f) {1041 res.add(f);1042 },options);1043 return res;1044 },*/1045 each:function (f,options) {1046 var dir=this.assertDir();1047 dir.listFiles(options).forEach(f);1048 },1049 recursive:function (fun,options) {1050 var dir=this.assertDir();1051 dir.each(function (f) {1052 if (f.isDir()) f.recursive(fun);1053 else fun(f);1054 },options);1055 },1056 listFiles:function (options) {1057 A(options==null || typeof options=="object");1058 var dir=this.assertDir();1059 var l=this.resolveLink();1060 if (!this.equals(l)) return l.listFiles.apply(l,arguments);1061 var path=this.path();1062 var ord;1063 if (typeof options=="function") ord=options;1064 options=dir.convertOptions(options);1065 if (!ord) ord=options.order;1066 var di=this.fs.opendir(path, options);1067 var res=[];1068 for (var i=0;i<di.length; i++) {1069 var name=di[i];1070 //if (!options.includeTrashed && dinfo[i].trashed) continue;1071 if (options.excludes[path+name] ) continue;1072 res.push(dir.rel(name));1073 }1074 if (typeof ord=="function" && res.sort) res.sort(ord);1075 return res;1076 },1077 ls:function (options) {1078 A(options==null || typeof options=="object");1079 var dir=this.assertDir();1080 var res=dir.listFiles(options);1081 return res.map(function (f) {1082 return f.name();1083 });1084 },1085 convertOptions:function(options) {1086 var dir=this.assertDir();1087 var pathR=this.path();1088 if (!options) options={};1089 if (!options.excludes) options.excludes={};1090 if (options.excludes instanceof Array) {1091 var excludes={};1092 options.excludes.forEach(function (e) {1093 if (P.startsWith(e,"/")) {1094 excludes[e]=1;1095 } else {1096 excludes[pathR+e]=1;1097 }1098 });1099 options.excludes=excludes;1100 }1101 return A.is(options,{excludes:{}});1102 },1103 mkdir: function () {1104 this.touch();1105 },1106 link: function (to,options) {// % ln to path1107 to=this._resolve(A(to));1108 this.fs.link(this.path(),to.path(),options);1109 },1110 resolveLink: function () {1111 var l=this.fs.resolveLink(this.path());1112 A.is(l,P.Absolute);1113 return this._resolve(l);1114 },1115 isLink: function () {1116 return this.fs.isLink(this.path());1117 }1118};1119return SFile;1120});1121requireSimulator.setName('FS2');1122define(["extend","PathUtil","MIMETypes","assert","SFile"],function (extend, P, M,assert,SFile){1123 var FS=function () {1124 };1125 function stub(n) {1126 throw new Error (n+" is STUB!");1127 }1128 extend(FS.prototype, {1129 err: function (path, mesg) {1130 throw new Error(path+": "+mesg);1131 },1132 // mounting1133 fstab: function () {1134 return this._fstab=this._fstab||[];//[{fs:this, path:P.SEP}];1135 },1136 resolveFS:function (path, options) {1137 assert.is(path,P.Absolute);1138 var res;1139 this.fstab().forEach(function (tb) {1140 if (res) return;1141 if (P.startsWith(path, tb.path)) {1142 res=tb.fs;1143 }1144 });1145 if (!res) res=this; //this.err(path,"Cannot resolve");1146 return assert.is(res,FS);1147 },1148 isReadOnly: function (path, options) {// mainly for check ENTIRELY read only1149 stub("isReadOnly");1150 },1151 mounted: function (parentFS, mountPoint ) {1152 assert.is(arguments,[FS,P.AbsDir]);1153 this.parentFS=parentFS;1154 this.mountPoint=mountPoint;1155 },1156 relFromMountPoint: function (path) {1157 assert.is(path, P.Absolute);1158 if (this.parentFS) {1159 assert.is(this.mountPoint, P.AbsDir);1160 return P.relPath(path, this.mountPoint);1161 } else {1162 return P.relPath(path, P.SEP);1163 }1164 },1165 dirFromFstab: function (path, options) {1166 assert.is(path, P.AbsDir);1167 var res=(options||{}).res || [];1168 this.fstab().forEach(function (tb) {1169 if (P.up( tb.path )==path) res.push(P.name(tb.path));1170 });1171 return res;1172 },1173 getRootFS: function () {1174 var res;1175 for (var r=this;r;r=r.parentFS){res=r;}1176 return assert.is(res,FS);1177 },1178 //-------- end of mouting1179 //-------- spec1180 getReturnTypes: function (path, options) {1181 //{getContent:String|DataURL|ArrayBuffer|OutputStream|Writer1182 // ,opendir:Array|...}1183 stub("");1184 },1185 //------- for file1186 getContent: function (path, options) {1187 // options:{type:String|DataURL|ArrayBuffer|OutputStream|Writer}1188 // succ : [type],1189 stub("");1190 },1191 setContent: function (path, content, options) {1192 // content: String|ArrayBuffer|InputStream|Reader1193 stub("");1194 },1195 getMetaInfo: function (path, options) {1196 stub("");1197 },1198 setMetaInfo: function (path, info, options) {1199 stub("");1200 },1201 mkdir: function (path, options) {1202 stub("mkdir");1203 },1204 touch: function (path) {1205 stub("touch");1206 },1207 exists: function (path, options) {1208 // exists return false if path is existent by follwing symlink1209 stub("exists");1210 },1211 opendir: function (path, options) {1212 //ret: [String] || Stream<string> // https://nodejs.org/api/stream.html#stream_class_stream_readable1213 stub("opendir");1214 },1215 cp: function(path, dst, options) {1216 assert.is(arguments,[P.Absolute,P.Absolute]);1217 options=options||{};1218 var srcIsDir=this.isDir(path);1219 var dstIsDir=this.resolveFS(dst).isDir(dst);1220 if (!srcIsDir && !dstIsDir) {1221 var cont=this.getContent(path);1222 var res=this.resolveFS(dst).setContent(dst,cont);1223 if (options.a) {1224 //console.log("-a", this.getMetaInfo(path));1225 this.setMetaInfo(dst, this.getMetaInfo(path));1226 }1227 return res;1228 } else {1229 throw "only file to file supports";1230 }1231 },1232 mv: function (path,to,options) {1233 this.cp(path,to,options);1234 return this.rm(path,{r:true});1235 },1236 rm:function (path, options) {1237 stub("");1238 },1239 link: function (path, to, options) {1240 throw new Error("This FS not support link.");1241 },1242 getURL: function (path) {1243 stub("");1244 }1245 });1246 //res=[]; for (var k in a) { res.push(k); } res;1247 FS.delegateMethods=function (prototype, methods) {1248 for (var n in methods) {1249 (function (n){1250 prototype[n]=function () {1251 var path=arguments[0];1252 assert.is(path,P.Absolute);1253 var fs=this.resolveFS(path);1254 //console.log(n, f.fs===this ,f.fs, this);1255 if (fs!==this) {1256 //arguments[0]=f.path;1257 return fs[n].apply(fs, arguments);1258 } else {1259 return methods[n].apply(this, arguments);1260 }1261 };1262 })(n);1263 }1264 };1265 FS.delegateMethods(FS.prototype, {1266 assertWriteable: function (path) {1267 if (this.isReadOnly(path)) this.err(path, "read only.");1268 },1269 mount: function (path, fs, options) {1270 assert.is(arguments,[P.AbsDir, FS] );1271 if (this.exists(path)) {1272 throw new Error(path+": Directory exists");1273 }1274 var parent=P.up(path);1275 if (parent==null) throw new Error("Cannot mount on root");1276 if (!this.exists(parent)) {1277 throw new Error(path+": Parent Directory not exist");1278 }1279 fs.mounted(this, path);1280 this.fstab().unshift({path:path, fs:fs});1281 },1282 getContentType: function (path, options) {1283 var e=P.ext(path);1284 return M[e] || (options||{}).def || "text/plain";1285 },1286 isText:function (path) {1287 var m=this.getContentType(path);1288 return P.startsWith( m, "text");1289 },1290 assertExist: function (path, options) {1291 if (!this.exists(path, options)) {1292 this.err(path, ": No such "+(P.isDir(path)?"directory":"file"));1293 }1294 },1295 isDir: function (path,options) {1296 return P.isDir(path);1297 },1298 find: function (path, options) {1299 assert.is(arguments,[P.Absolute]);1300 var ls=this.opendir(path, options);1301 var t=this;1302 var res=[path];1303 ls.forEach(function (e) {1304 var ep=P.rel(path, e);1305 if (P.isDir(ep)) {1306 var fs=t.resolveFS(ep);1307 res=res.concat(1308 fs.find( ep ,options)1309 );1310 } else {1311 res.push( ep );//getPathFromRootFS1312 }1313 });1314 return res;1315 },1316 resolveLink: function (path) {1317 assert.is(path,P.Absolute);1318 // returns non-link path1319 // ln -s /a/b/ /c/d/1320 // resolveLink /a/b/ -> /a/b/1321 // resolveLink /c/d/e/f -> /a/b/e/f1322 // resolveLink /c/d/non_existent -> /a/b/non_existent1323 // isLink /c/d/ -> /a/b/1324 // isLink /c/d/e/f -> null1325 // ln /testdir/ /ram/files/1326 // resolveLink /ram/files/sub/test2.txt -> /testdir/sub/test2.txt1327 if (this.exists(path)) return path;1328 // path=/ram/files/test.txt1329 for (var p=path ; p ; p=P.up(p)) {1330 assert(!this.mountPoint || P.startsWith(p, this.mountPoint), p+" is out of mountPoint. path="+path);1331 var l=this.isLink(p); // p=/ram/files/ l=/testdir/1332 if (l) {1333 // /testdir/ test.txt1334 var np=P.rel(l,P.relPath(path, p)); // /testdir/test.txt1335 return assert.is(this.resolveFS(np).resolveLink(np),P.Absolute) ;1336 }1337 if (this.exists(p)) return path;1338 }1339 return path;1340 },1341 isLink: function (path) {1342 return null;1343 },1344 get: function (path) {1345 assert.eq(this.resolveFS(path), this);1346 return new SFile(this, path);1347 //var r=this.resolveFS(path);1348 //return new SFile(r.fs, r.path);1349 }1350 });1351 return FS;1352});1353requireSimulator.setName('WebSite');1354define([], function () {1355 var loc=document.location.href;1356 var devMode=!!loc.match(/html\/dev\//) && !!loc.match(/localhost:3/);1357 var WebSite;1358 if (loc.match(/jsrun\.it/)) {1359 WebSite={1360 urlAliases: {1361 "images/Ball.png":"http://jsrun.it/assets/9/X/T/b/9XTbt.png",1362 "images/base.png":"http://jsrun.it/assets/6/F/y/3/6Fy3B.png",1363 "images/Sample.png":"http://jsrun.it/assets/s/V/S/l/sVSlZ.png",1364 "images/neko.png":"http://jsrun.it/assets/f/D/z/z/fDzze.png",//"http://jsrun.it/assets/j/D/9/q/jD9qQ.png",1365 "images/mapchip.png":"http://jsrun.it/assets/f/u/N/v/fuNvz.png",1366 "images/inputPad.png":"http://jsrun.it/assets/r/K/T/Y/rKTY9.png"1367 },top:"",devMode:devMode, pluginTop: "http://tonyuedit.appspot.com/js/plugins",1368 removeJSOutput:true1369 };1370 } else if (1371 loc.match(/tonyuexe\.appspot\.com/) ||1372 loc.match(/localhost:8887/) ||1373 (1374 /*(1375 loc.match(/^file:/) ||1376 loc.match(/localhost/) ||1377 loc.match(/tonyuedit\.appspot\.com/)1378 ) &&*/1379 loc.match(/\/html\/((dev)|(build))\//)1380 )1381 ) {1382 WebSite={1383 urlAliases: {1384 "images/Ball.png":"../../images/Ball.png",1385 "images/base.png":"../../images/base.png",1386 "images/Sample.png":"../../images/Sample.png",1387 "images/neko.png":"../../images/neko.png",1388 "images/inputPad.png":"../../images/inputPad.png",1389 "images/mapchip.png":"../../images/mapchip.png",1390 "images/sound.png":"../../images/sound.png",1391 "images/ecl.png":"../../images/ecl.png"1392 },top:"../..",devMode:devMode1393 };1394 } else {1395 WebSite={1396 urlAliases: {}, top: "",devMode:devMode1397 };1398 }1399 // from https://w3g.jp/blog/js_browser_sniffing20151400 var u=window.navigator.userAgent.toLowerCase();1401 WebSite.tablet=(u.indexOf("windows") != -1 && u.indexOf("touch") != -1)1402 || u.indexOf("ipad") != -11403 || (u.indexOf("android") != -1 && u.indexOf("mobile") == -1)1404 || (u.indexOf("firefox") != -1 && u.indexOf("tablet") != -1)1405 || u.indexOf("kindle") != -11406 || u.indexOf("silk") != -11407 || u.indexOf("playbook") != -1;1408 WebSite.mobile=(u.indexOf("windows") != -1 && u.indexOf("phone") != -1)1409 || u.indexOf("iphone") != -11410 || u.indexOf("ipod") != -11411 || (u.indexOf("android") != -1 && u.indexOf("mobile") != -1)1412 || (u.indexOf("firefox") != -1 && u.indexOf("mobile") != -1)1413 || u.indexOf("blackberry") != -1;1414 if (!WebSite.pluginTop) {1415 WebSite.pluginTop=WebSite.top+"/js/plugins";1416 }1417 WebSite.disableROM={};1418 if (loc.match(/tonyuedit\.appspot\.com/) || loc.match(/localhost:8888/) ) {1419 //WebSite.disableROM={"ROM_d.js":true};1420 }1421 if (loc.match(/\.appspot\.com/) || loc.match(/localhost:888[87]/)) {1422 WebSite.serverType="GAE";1423 }1424 if (loc.match(/localhost:3000/) ) {1425 WebSite.serverType="Node";1426 }1427 if (loc.match(/tonyuexe\.appspot\.com/) ||1428 loc.match(/localhost:8887/)) {1429 WebSite.serverTop=WebSite.top+"/exe"; // Fix NetModule.tonyu!!1430 } else {1431 WebSite.serverTop=WebSite.top+"/edit";// Fix NetModule.tonyu!!1432 }1433 WebSite.sampleImg=WebSite.top+"/images";1434 WebSite.blobPath=WebSite.serverTop+"/serveBlob"; //TODO: urlchange!1435 WebSite.isNW=(typeof process=="object" && process.__node_webkit);1436 WebSite.mp3Disabled=WebSite.isNW;1437 WebSite.tonyuHome="/Tonyu/";1438 WebSite.url={1439 getDirInfo:WebSite.serverTop+"/getDirInfo",1440 getFiles:WebSite.serverTop+"/File2LSSync",1441 putFiles:WebSite.serverTop+"/LS2FileSync"1442 };1443 if (WebSite.isNW) {1444 WebSite.cwd=process.cwd().replace(/\\/g,"/").replace(/\/?$/,"/");1445 if (process.env.TONYU_HOME) {1446 WebSite.tonyuHome=process.env.TONYU_HOME.replace(/\\/g,"/").replace(/\/?$/,"/");1447 } else {1448 WebSite.tonyuHome=WebSite.cwd+"fs/Tonyu/";1449 }1450 WebSite.logdir="/var/log/Tonyu/";1451 WebSite.wwwDir=WebSite.cwd+"www/";1452 WebSite.kernelDir=WebSite.wwwDir+"Kernel/";1453 WebSite.ffmpeg=WebSite.cwd+("ffmpeg/bin/ffmpeg.exe");1454 }1455 if (loc.match(/tonyuedit\.appspot\.com/) ||1456 loc.match(/localhost:888/) ||1457 WebSite.isNW) {1458 WebSite.compiledKernel=WebSite.top+"/Kernel/js/concat.js";1459 } else {1460 WebSite.compiledKernel="http://tonyuexe.appspot.com/Kernel/js/concat.js";1461 }1462 return window.WebSite=WebSite;1463});1464requireSimulator.setName('NativeFS');1465define(["FS2","assert","PathUtil","extend","MIMETypes","DataURL"],1466 function (FS,A,P,extend,MIME,DataURL) {1467 var available=(typeof process=="object" && process.__node_webkit);1468 if (!available) {1469 return function () {1470 throw new Error("This system not suppert native FS");1471 };1472 }1473 var assert=A;1474 var fs=require("fs");1475 var NativeFS=function (rootPoint) {1476 if (rootPoint) {1477 A.is(rootPoint, P.AbsDir);1478 this.rootPoint=rootPoint;1479 }1480 };1481 NativeFS.available=true;1482 var SEP=P.SEP;1483 var json=JSON; // JSON changes when page changes, if this is node module, JSON is original JSON1484 var Pro=NativeFS.prototype=new FS;1485 Pro.toNativePath = function (path) {1486 if (!this.rootPoint) return path;1487 A.is(path, P.Absolute);1488 return P.rel( this.rootPoint, this.relFromMountPoint(path));1489 };1490 /*Pro.isText=function (path) {1491 var e=P.ext(path);1492 var m=MIME[e];1493 return P.startsWith( m, "text");1494 };*/1495 FS.delegateMethods(NativeFS.prototype, {1496 getReturnTypes: function(path, options) {1497 assert.is(arguments,[String]);1498 return {1499 getContent: ArrayBuffer, opendir:[String]1500 };1501 },1502 getContent: function (path, options) {1503 options=options||{};1504 A.is(path,P.Absolute);1505 var np=this.toNativePath(path);1506 var t=options.type;1507 if (this.isText(path)) {1508 if (t===String) {1509 return fs.readFileSync(np, {encoding:"utf8"});1510 } else {1511 return fs.readFileSync(np);1512 //TODOvar bin=fs.readFileSync(np);1513 //throw new Error("TODO: handling bin file "+path);1514 }1515 } else {1516 if (t===String) {1517 var bin=fs.readFileSync(np);1518 var d=new DataURL(bin, this.getContentType(path) );1519 return d.url;1520 } else {1521 return fs.readFileSync(np);1522 }1523 }1524 },1525 setContent: function (path,content) {1526 A.is(path,P.Absolute);1527 var pa=P.up(path);1528 if (pa) this.getRootFS().mkdir(pa);1529 var np=this.toNativePath(path);1530 var cs=typeof content=="string";1531 if (this.isText(path)) {1532 fs.writeFileSync(np, content)1533 /*if (cs) return fs.writeFileSync(np, content);1534 else {1535 return fs.writeFileSync(np, content);1536 //throw new Error("TODO");1537 }*/1538 } else {1539// console.log("NatFS", cs, content);1540 if (!cs) return fs.writeFileSync(np, content);1541 else {1542 var d=new DataURL(content);1543 //console.log(d.buffer);1544 return fs.writeFileSync(np, d.buffer);1545 }1546 }1547 },1548 getMetaInfo: function(path, options) {1549 this.assertExist(path, options);1550 var s=this.stat(path);1551 s.lastUpdate=s.mtime.getTime();1552 return s;1553 },1554 setMetaInfo: function(path, info, options) {1555 //options.lastUpdate1556 //TODO:1557 },1558 isReadOnly: function (path) {1559 // TODO:1560 return false;1561 },1562 stat: function (path) {1563 A.is(path,P.Absolute);1564 var np=this.toNativePath(path);1565 return fs.statSync(np);1566 },1567 mkdir: function(path, options) {1568 assert.is(arguments,[P.Absolute]);1569 if (this.exists(path)){1570 if (this.isDir(path)) {1571 return;1572 } else {1573 throw new Error(this+" is a file. not a dir.");1574 }1575 }1576 this.assertWriteable(path);1577 var pa=P.up(path);1578 if (pa) this.getRootFS().mkdir(pa);1579 var np=this.toNativePath(path);1580 return fs.mkdirSync(np);1581 },1582 opendir: function (path, options) {1583 assert.is(arguments,[String]);1584 var np=this.toNativePath(path);1585 var ts=P.truncSEP(np);1586 var r=fs.readdirSync(np).map(function (e) {1587 var s=fs.statSync(ts+SEP+e);1588 var ss=s.isDirectory()?SEP:"";1589 return e+ss;1590 });1591 var res=this.dirFromFstab(path);1592 return assert.is(res.concat(r),Array);1593 },1594 rm: function(path, options) {1595 assert.is(arguments,[P.Absolute]);1596 options=options||{};1597 this.assertExist(path);1598 var np=this.toNativePath(path);1599 if (this.isDir(path)) {1600 return fs.rmdirSync(np);1601 } else {1602 return fs.unlinkSync(np);1603 }1604 },1605 exists: function (path, options) {1606 var np=this.toNativePath(path);1607 return fs.existsSync(np);1608 },1609 isDir: function (path) {1610 if (!this.exists(path)) {1611 return P.isDir(path);1612 }1613 return this.stat(path).isDirectory();1614 },1615 /*link: function(path, to, options) {1616 }//TODO1617 isLink:1618 */1619 touch: function (path) {1620 if (!this.exists(path) && this.isDir(path)) {1621 this.mkdir(path);1622 } else if (this.exists(path) && !this.isDir(path) ) {1623 // TODO(setlastupdate)1624 }1625 },1626 getURL:function (path) {1627 return "file:///"+path.replace(/\\/g,"/");1628 }1629 });1630 return NativeFS;1631});1632requireSimulator.setName('LSFS');1633define(["FS2","PathUtil","extend","assert"], function(FS,P,extend,assert) {1634 var LSFS = function(storage,options) {1635 this.storage=storage;1636 this.options=options||{};1637 };1638 var isDir = P.isDir.bind(P);1639 var up = P.up.bind(P);1640 var endsWith= P.endsWith.bind(P);1641 //var getName = P.name.bind(P);1642 var Path=P.Path;1643 var Absolute=P.Absolute;1644 var SEP= P.SEP;1645 function now(){1646 return new Date().getTime();1647 }1648 LSFS.ramDisk=function () {1649 var s={};1650 s[P.SEP]="{}";1651 return new LSFS(s);1652 };1653 LSFS.now=now;1654 LSFS.prototype=new FS;1655 //private methods1656 LSFS.prototype.resolveKey=function (path) {1657 assert.is(path,P.Absolute);1658 return P.SEP+this.relFromMountPoint(path);1659 };1660 LSFS.prototype.getItem=function (path) {1661 assert.is(path,P.Absolute);1662 var key=this.resolveKey(path);1663 return this.storage[key];1664 };1665 LSFS.prototype.setItem=function (path, value) {1666 assert.is(path,P.Absolute);1667 var key=this.resolveKey(path);1668 /*if (key.indexOf("..")>=0) {1669 console.log(path,key,value);1670 }*/1671 assert(key.indexOf("..")<0);1672 assert(P.startsWith(key,P.SEP));1673 this.storage[key]=value;1674 };1675 LSFS.prototype.removeItem=function (path) {1676 assert.is(path,P.Absolute);1677 var key=this.resolveKey(path);1678 delete this.storage[key];1679 };1680 LSFS.prototype.itemExists=function (path) {1681 assert.is(path,P.Absolute);1682 var key=this.resolveKey(path);1683 return key in this.storage;1684 };1685 LSFS.prototype.inMyFS=function (path){1686 return !this.mountPoint || P.startsWith(path, this.mountPoint);1687 };1688 LSFS.prototype.getDirInfo=function getDirInfo(path) {1689 assert.is(arguments,[P.AbsDir]);1690 if (path == null) throw new Error("getDir: Null path");1691 if (!endsWith(path, SEP)) path += SEP;1692 assert(this.inMyFS(path));1693 var dinfo = {};1694 try {1695 var dinfos = this.getItem(path);1696 if (dinfos) {1697 dinfo = JSON.parse(dinfos);1698 }1699 } catch (e) {1700 console.log("dinfo err : " , path , dinfos);1701 }1702 return dinfo;1703 };1704 LSFS.prototype.putDirInfo=function putDirInfo(path, dinfo, trashed) {1705 assert.is(arguments,[P.AbsDir, Object]);1706 if (!isDir(path)) throw new Error("Not a directory : " + path);1707 assert(this.inMyFS(path));1708 this.setItem(path, JSON.stringify(dinfo));1709 var ppath = up(path);1710 if (ppath == null) return;1711 if (!this.inMyFS(ppath)) {1712 assert(this.getRootFS()!==this);1713 this.getRootFS().touch(ppath);1714 return;1715 }1716 var pdinfo = this.getDirInfo(ppath);1717 this._touch(pdinfo, ppath, P.name(path), trashed);1718 };1719 LSFS.prototype._touch=function _touch(dinfo, path, name, trashed) {1720 // path:path of dinfo1721 // trashed: this touch is caused by trashing the file/dir.1722 assert.is(arguments,[Object, String, String]);1723 assert(this.inMyFS(path));1724 if (!dinfo[name]) {1725 dinfo[name] = {};1726 if (trashed) dinfo[name].trashed = true;1727 }1728 if (!trashed) delete dinfo[name].trashed;1729 dinfo[name].lastUpdate = now();1730 this.putDirInfo(path, dinfo, trashed);1731 };1732 LSFS.prototype.removeEntry=function removeEntry(dinfo, path, name) { // path:path of dinfo1733 assert.is(arguments,[Object, String, String]);1734 if (dinfo[name]) {1735 dinfo[name] = {1736 lastUpdate: now(),1737 trashed: true1738 };1739 this.putDirInfo(path, dinfo, true);1740 }1741 };1742 LSFS.prototype.removeEntryWithoutTrash=function (dinfo, path, name) { // path:path of dinfo1743 assert.is(arguments,[Object, String, String]);1744 if (dinfo[name]) {1745 delete dinfo[name];1746 this.putDirInfo(path, dinfo, true);1747 }1748 };1749 // public methods (with resolve fs)1750 FS.delegateMethods(LSFS.prototype, {1751 isReadOnly: function () {return this.options.readOnly;},1752 getReturnTypes: function(path, options) {1753 assert.is(arguments,[String]);1754 return {1755 getContent: String, opendir:[String]1756 };1757 },1758 getContent: function(path, options) {1759 assert.is(arguments,[Absolute]);1760 this.assertExist(path);1761 return this.getItem(path);1762 },1763 setContent: function(path, content, options) {1764 assert.is(arguments,[Absolute,String]);1765 this.assertWriteable(path);1766 this.setItem(path, content);1767 this.touch(path);1768 },1769 getMetaInfo: function(path, options) {1770 this.assertExist(path, {includeTrashed:true});1771 assert.is(arguments,[Absolute]);1772 if (path==P.SEP) {1773 return {};1774 }1775 var parent=assert(P.up(path));1776 if (!this.inMyFS(parent)) {1777 return {};1778 }1779 var name=P.name(path);1780 assert.is(parent,P.AbsDir);1781 var pinfo=this.getDirInfo(parent);1782 return assert(pinfo[name]);1783 },1784 setMetaInfo: function(path, info, options) {1785 assert.is(arguments,[String,Object]);1786 this.assertWriteable(path);1787 var parent=assert(P.up(path));1788 if (!this.inMyFS(parent)) {1789 return;1790 }1791 var pinfo=this.getDirInfo(parent);1792 var name=P.name(path);1793 pinfo[name]=info;1794 this.putDirInfo(parent, pinfo, pinfo[name].trashed);1795 },1796 mkdir: function(path, options) {1797 assert.is(arguments,[Absolute]);1798 this.assertWriteable(path);1799 this.touch(path);1800 },1801 opendir: function(path, options) {1802 assert.is(arguments,[String]);1803 //succ: iterator<string> // next()1804 // options: {includeTrashed:Boolean}1805 options=options||{};1806 var inf=this.getDirInfo(path);1807 var res=this.dirFromFstab(path);1808 for (var i in inf) {1809 assert(inf[i]);1810 if (!inf[i].trashed || options.includeTrashed) res.push(i);1811 }1812 return assert.is(res,Array);1813 },1814 rm: function(path, options) {1815 assert.is(arguments,[Absolute]);1816 options=options||{};1817 this.assertWriteable(path);1818 var parent=P.up(path);1819 if (parent==null || !this.inMyFS(parent)) {1820 throw new Error(path+": cannot remove. It is root of this FS.");1821 }1822 this.assertExist(path,{includeTrashed:options.noTrash });1823 if (P.isDir(path)) {1824 var lis=this.opendir(path);1825 if (lis.length>0) {1826 this.err(path,"Directory not empty");1827 }1828 if (options.noTrash) {1829 this.removeItem(path);1830 }1831 } else {1832 this.removeItem(path);1833 }1834 var pinfo=this.getDirInfo(parent);1835 if (options.noTrash) {1836 this.removeEntryWithoutTrash(pinfo, parent, P.name(path) );1837 } else {1838 this.removeEntry(pinfo, parent, P.name(path) );1839 }1840 },1841 exists: function (path,options) {1842 assert.is(arguments,[Absolute]);1843 options=options||{};1844 var name=P.name(path);1845 var parent=P.up(path);1846 if (parent==null || !this.inMyFS(parent)) return true;1847 var pinfo=this.getDirInfo(parent);1848 var res=pinfo[name];1849 if (res && res.trashed && this.itemExists(path)) {1850 if (this.isDir(path)) {1851 } else {1852 assert.fail("Inconsistent "+path+": trashed, but remains in storage");1853 }1854 }1855 if (!res && this.itemExists(path)) {1856 assert.fail("Inconsistent "+path+": not exists in metadata, but remains in storage");1857 }1858 if (res && !res.trashed && !res.link && !this.itemExists(path)) {1859 assert.fail("Inconsistent "+path+": exists in metadata, but not in storage");1860 }1861 if (res && !options.includeTrashed) {1862 res=!res.trashed;1863 }1864 return !!res;1865 },1866 link: function(path, to, options) {1867 assert.is(arguments,[P.AbsDir,P.AbsDir]);1868 this.assertWriteable(path);1869 if (this.exists(path)) this.err(path,"file exists");1870 if (P.isDir(path) && !P.isDir(to)) {1871 this.err(path," can not link to file "+to);1872 }1873 if (!P.isDir(path) && P.isDir(to)) {1874 this.err(path," can not link to directory "+to);1875 }1876 var m={};//assert(this.getMetaInfo(path));1877 m.link=to;1878 m.lastUpdate=now();1879 this.setMetaInfo(path, m);1880 //console.log(this.getMetaInfo(path));1881 console.log(this.storage);1882 //console.log(this.getMetaInfo(P.up(path)));1883 assert(this.exists(path));1884 assert(this.isLink(path));1885 },1886 isLink: function (path) {1887 assert.is(arguments,[P.AbsDir]);1888 if (!this.exists(path)) return null;1889 var m=assert(this.getMetaInfo(path));1890 return m.link;1891 },1892 touch: function (path) {1893 assert.is(arguments,[Absolute]);1894 this.assertWriteable(path);1895 if (!this.itemExists(path)) {1896 if (P.isDir(path)) {1897 this.setItem(path,"{}");1898 } else {1899 this.setItem(path,"");1900 }1901 }1902 var parent=up(path);1903 if (parent!=null) {1904 if (this.inMyFS(parent)) {1905 var pinfo=this.getDirInfo(parent);1906 this._touch(pinfo, parent , P.name(path), false);1907 } else {1908 assert(this.getRootFS()!==this);1909 this.getRootFS().touch(parent);1910 }1911 }1912 },1913 getURL: function (path) {1914 return this.getContent(path,{type:String});1915 }1916 });1917 return LSFS;1918});1919requireSimulator.setName('Env');1920define(["assert","PathUtil"],function (A,P) {1921 var Env=function (value) {1922 this.value=value;1923 };1924 Env.prototype={1925 expand:function (str) {1926 A.is(str,String);1927 var t=this;1928 return str.replace(/\$\{([a-zA-Z0-9_]+)\}/g, function (a,key) {1929 return t.get(key);1930 });1931 },1932 expandPath:function (path) {1933 A.is(path,String);1934 path=this.expand(path);1935 path=path.replace(/\/+/g,"/");1936 return A.is(path,P.Path);1937 },1938 get: function (key) {1939 return this.value[key];1940 },1941 set: function (key, value) {1942 this.value[key]=value;1943 }1944 };1945 return Env;1946});1947requireSimulator.setName('FS');1948define(["FS2","WebSite","NativeFS","LSFS", "PathUtil","Env","assert","SFile"],1949 function (FS,WebSite,NativeFS,LSFS, P,Env,A,SFile) {1950 var FS={};1951 if (typeof window=="object") window.FS=FS;1952 var rootFS;1953 var env=new Env(WebSite);1954 if (WebSite.isNW) {1955 //var nfsp=process.env.TONYU_FS_HOME || P.rel(process.cwd().replace(/\\/g,"/"), "www/fs/");1956 //console.log("nfsp",nfsp);1957 rootFS=new NativeFS();//(nfsp);1958 } else {1959 rootFS=new LSFS(localStorage);1960 }1961 FS.get=function () {1962 return rootFS.get.apply(rootFS,arguments);1963 };1964 FS.expandPath=function () {1965 return env.expandPath.apply(env,arguments);1966 };1967 FS.resolve=function (path, base) {1968 if (SFile.is(path)) return path;1969 path=env.expandPath(path);1970 if (base && !P.isAbsolutePath(path)) {1971 base=env.expandPath(base);1972 return FS.get(base).rel(path);1973 }1974 return FS.get(path);1975 };1976 FS.mount=function () {1977 return rootFS.mount.apply(rootFS,arguments);1978 };1979 return FS;1980});1981requireSimulator.setName('plugins');1982define(["WebSite"],function (WebSite){1983 var plugins={};1984 var installed= {1985 box2d:{src: "Box2dWeb-2.1.a.3.min.js",detection:/BodyActor/,symbol:"Box2D" },1986 timbre: {src:"timbre.js",detection:/\bplay(SE)?\b/,symbol:"T" }1987 };1988 plugins.installed=installed;1989 plugins.detectNeeded=function (src,res) {1990 for (var name in installed) {1991 var r=installed[name].detection.exec(src);1992 if (r) res[name]=1;1993 }1994 return res;1995 };1996 plugins.loaded=function (name) {1997 var i=installed[name];1998 if (!i) throw new Error("plugin not found: "+name);1999 return window[i.symbol];2000 };2001 plugins.loadAll=function (names,options) {2002 options=convOpt(options);2003 var namea=[];2004 for (var name in names) {2005 if (installed[name] && !plugins.loaded(name)) {2006 namea.push(name);2007 }2008 }2009 var i=0;2010 console.log("loading plugins",namea);2011 loadNext();2012 function loadNext() {2013 if (i>=namea.length) options.onload();2014 else plugins.load(namea[i++],loadNext);2015 }2016 };2017 function convOpt(options) {2018 if (typeof options=="function") options={onload:options};2019 if (!options) options={};2020 if (!options.onload) options.onload=function (){};2021 return options;2022 }2023 plugins.load=function (name,options) {2024 var i=installed[name];2025 if (!i) throw new Error("plugin not found: "+name);2026 options=convOpt(options);2027 var src=WebSite.pluginTop+"/"+i.src;2028 if (location.href.match(/^file:/)) {2029 $("<script>").attr("src",src).appendTo("body");2030 setTimeout(options.onload,500);2031 } else {2032 $.getScript(src, options.onload);2033 }2034 };2035 plugins.request=function (name) {2036 if (plugins.loaded(name)) return;2037 var req=new Error("Plugin "+name+" required");2038 req.pluginName=name;2039 };2040 return plugins;2041});2042requireSimulator.setName('DeferredUtil');2043define([], function () {2044 var DU;2045 DU={2046 directPromise:function (v) {2047 var d=new $.Deferred;2048 setTimeout(function () {d.resolve(v);},0);2049 return d.promise();2050 },2051 throwPromise:function (e) {2052 d=new $.Deferred;2053 setTimeout(function () {2054 d.reject(e);2055 }, 0);2056 return d.promise();2057 },2058 throwF: function (f) {2059 return function () {2060 try {2061 return f.apply(this,arguments);2062 } catch(e) {2063 return DU.throwPromise(e);2064 }2065 };2066 }2067 };2068 return DU;2069});2070requireSimulator.setName('compiledProject');2071define(["DeferredUtil"], function (DU) {2072 var CPR=function (ns, url) {2073 return {2074 getNamespace:function () {return ns;},2075 sourceDir: function () {return null;},2076 getDependingProjects: function () {return [];},// virtual2077 loadDependingClasses: function (ctx) {2078 //Same as projectCompiler /TPR/this/ (XXXX)2079 var task=DU.directPromise();2080 var myNsp=this.getNamespace();2081 this.getDependingProjects().forEach(function (p) {2082 if (p.getNamespace()==myNsp) return;2083 task=task.then(function () {2084 return p.loadClasses(ctx);2085 });2086 });2087 return task;2088 },2089 loadClasses: function (ctx) {2090 console.log("Load compiled classes ns=",ns,"url=",url);2091 var d=new $.Deferred;2092 var head = document.getElementsByTagName("head")[0] || document.documentElement;2093 var script = document.createElement("script");2094 script.src = url;2095 var done = false;2096 script.onload = script.onreadystatechange = function() {2097 if ( !done && (!this.readyState ||2098 this.readyState === "loaded" || this.readyState === "complete") ) {2099 done = true;2100 script.onload = script.onreadystatechange = null;2101 if ( head && script.parentNode ) {2102 head.removeChild( script );2103 }2104 console.log("Done Load compiled classes ns=",ns,"url=",url,Tonyu.classes);2105 //same as projectCompiler (XXXX)2106 var cls=Tonyu.classes;2107 ns.split(".").forEach(function (c) {2108 if (cls) cls=cls[c];2109 // comment out : when empty concat.js2110 //if (!cls) throw new Error("namespace Not found :"+ns);2111 });2112 if (cls) {2113 for (var cln in cls) {2114 var cl=cls[cln];2115 var m=Tonyu.klass.getMeta(cl);2116 ctx.classes[m.fullName]=m;2117 }2118 }2119 //------------------XXXX2120 d.resolve();2121 }2122 };2123 this.loadDependingClasses(ctx).then(function () {2124 head.insertBefore( script, head.firstChild );2125 });2126 return d.promise();2127 }2128 }2129 };2130 return CPR;2131});2132requireSimulator.setName('compiledTonyuProject');2133define(["plugins","compiledProject"], function (plugins,CPR) {2134 var CPTR=function (ns, url, dir) {2135 var cpr=CPR(ns,url);2136 var kernelProject=CPR("kernel", WebSite.compiledKernel);2137 var m={2138 getDir: function () {return dir;},2139 getDependingProjects:function () {//override2140 return [kernelProject];2141 },2142 getOptions: function () {2143 var resFile=this.getDir().rel("options.json");2144 return resFile.obj();2145 },2146 getResource: function () {2147 var resFile=this.getDir().rel("res.json");2148 return resFile.obj();2149 },2150 loadPlugins: function (onload) {2151 var opt=this.getOptions();2152 return plugins.loadAll(opt.plugins,onload);2153 },2154 run: function (bootClassName) {2155 var ctx={classes:{}};2156 this.loadClasses(ctx).then(function () {2157 Tonyu.run(bootClassName);2158 });2159 }2160 };2161 for (var k in m) cpr[k]=m[k];2162 return cpr;2163 };2164 return CPTR;2165});2166requireSimulator.setName('Shell');2167define(["FS","Util","WebSite"],function (FS,Util,WebSite) {2168 var Shell={cwd:FS.get("/")};2169 Shell.cd=function (dir) {2170 Shell.cwd=resolve(dir,true);2171 return Shell.pwd();2172 };2173 function resolve(v, mustExist) {2174 var r=resolve2(v);2175 if (mustExist && !r.exists()) throw r+": no such file or directory";2176 return r;2177 }2178 Shell.resolve=resolve;2179 function resolve2(v) {2180 if (typeof v!="string") return v;2181 if (Util.startsWith(v,"/")) return FS.get(v);2182 var c=Shell.cwd;2183 /*while (Util.startsWith(v,"../")) {2184 c=c.up();2185 v=v.substring(3);2186 }*/2187 return c.rel(v);2188 }2189 Shell.pwd=function () {2190 return Shell.cwd+"";2191 };2192 Shell.ls=function (dir){2193 if (!dir) dir=Shell.cwd;2194 else dir=resolve(dir, true);2195 return dir.ls();2196 };2197 Shell.cp=function (from ,to ,options) {2198 if (!options) options={};2199 if (options.v) {2200 Shell.echo("cp", from ,to);2201 options.echo=Shell.echo.bind(Shell);2202 }2203 var f=resolve(from, true);2204 var t=resolve(to);2205 return f.copyTo(t,options);2206 /*if (f.isDir() && t.isDir()) {2207 var sum=0;2208 f.recursive(function (src) {2209 var rel=src.relPath(f);2210 var dst=t.rel(rel);2211 if (options.test || options.v) {2212 Shell.echo((dst.exists()?"[ovr]":"[new]")+dst+"<-"+src);2213 }2214 if (!options.test) {2215 dst.copyFrom(src,options);2216 }2217 sum++;2218 });2219 return sum;2220 } else if (!f.isDir() && !t.isDir()) {2221 t.text(f.text());2222 return 1;2223 } else if (!f.isDir() && t.isDir()) {2224 t.rel(f.name()).text(f.text());2225 return 1;2226 } else {2227 throw "Cannot copy directory "+f+" to file "+t;2228 }*/2229 };2230 Shell.rm=function (file, options) {2231 if (!options) options={};2232 if (options.notrash) {2233 file=resolve(file, false);2234 file.removeWithoutTrash();2235 return 1;2236 }2237 file=resolve(file, true);2238 if (file.isDir() && options.r) {2239 var dir=file;2240 var sum=0;2241 dir.each(function (f) {2242 if (f.exists()) {2243 sum+=Shell.rm(f, options);2244 }2245 });2246 dir.rm();2247 return sum+1;2248 } else {2249 file.rm();2250 return 1;2251 }2252 };2253 Shell.cat=function (file,options) {2254 file=resolve(file, true);2255 Shell.echo(file.text());2256 //else return file.text();2257 };2258 Shell.resolve=function (file) {2259 if (!file) file=".";2260 file=resolve(file);2261 return file;2262 };2263 Shell.grep=function (pattern, file, options) {2264 file=resolve(file, true);2265 if (!options) options={};2266 if (!options.res) options.res=[];2267 if (file.isDir()) {2268 file.each(function (e) {2269 Shell.grep(pattern, e, options);2270 });2271 } else {2272 if (typeof pattern=="string") {2273 file.lines().forEach(function (line, i) {2274 if (line.indexOf(pattern)>=0) {2275 report(file, i+1, line);2276 }2277 });2278 }2279 }2280 return options.res;2281 function report(file, lineNo, line) {2282 if (options.res) {2283 options.res.push({file:file, lineNo:lineNo,line:line});2284 }2285 Shell.echo(file+"("+lineNo+"): "+line);2286 }2287 };2288 Shell.touch=function (f) {2289 f=resolve(f);2290 f.text(f.exists() ? f.text() : "");2291 return 1;2292 };2293 Shell.setout=function (ui) {2294 Shell.outUI=ui;2295 };2296 Shell.echo=function () {2297 console.log.apply(console,arguments);2298 if (Shell.outUI && Shell.outUI.log) Shell.outUI.log.apply(Shell.outUI,arguments);2299 };2300 Shell.err=function () {2301 console.log.apply(console,arguments);2302 if (Shell.outUI && Shell.outUI.err) Shell.outUI.err.apply(Shell.outUI,arguments);2303 };2304 Shell.prompt=function () {};2305 Shell.ASYNC={r:"SH_ASYNC"};2306 Shell.help=function () {2307 for (var k in Shell) {2308 var c=Shell[k];2309 if (typeof c=="function") {2310 Shell.echo(k+(c.description?" - "+c.description:""));2311 }2312 }2313 };2314 sh=Shell;2315 if (WebSite.isNW) {2316 sh.devtool=function () { require('nw.gui').Window.get().showDevTools();}2317 }2318 return Shell;2319});2320requireSimulator.setName('Tonyu');2321if (typeof define!=="function") {2322 define=require("requirejs").define;2323}2324define([],function () {2325return Tonyu=function () {2326 var preemptionTime=60;2327 function thread() {2328 //var stpd=0;2329 var fb={enter:enter, apply:apply,2330 exit:exit, steps:steps, step:step, isAlive:isAlive, isWaiting:isWaiting,2331 suspend:suspend,retVal:0/*retVal*/,tryStack:[],2332 kill:kill, waitFor: waitFor,setGroup:setGroup,2333 enterTry:enterTry,exitTry:exitTry,startCatch:startCatch,2334 waitEvent:waitEvent,runAsync:runAsync,clearFrame:clearFrame};2335 var frame=null;2336 var _isAlive=true;2337 var cnt=0;2338 //var retVal;2339 var _isWaiting=false;2340 var fSuspended=false;2341 function isAlive() {2342 return frame!=null && _isAlive;2343 }2344 function isWaiting() {2345 return _isWaiting;2346 }2347 function suspend() {2348 //throw new Error("Suspend call");2349 fSuspended=true;2350 cnt=0;2351 }2352 function enter(frameFunc) {2353 frame={prev:frame, func:frameFunc};2354 }2355 function apply(obj, methodName, args) {2356 if (!args) args=[];2357 var method;2358 if (typeof methodName=="string") {2359 method=obj["fiber$"+methodName];2360 }2361 if (typeof methodName=="function") {2362 method=methodName.fiber;2363 }2364 args=[fb].concat(args);2365 var pc=0;2366 enter(function () {2367 switch (pc){2368 case 0:2369 method.apply(obj,args);2370 pc=1;break;2371 case 1:2372 exit();2373 pc=2;break;2374 }2375 });2376 }2377 function step() {2378 if (frame) {2379 try {2380 frame.func(fb);2381 } catch(e) {2382 gotoCatch(e);2383 }2384 }2385 }2386 function gotoCatch(e) {2387 if (fb.tryStack.length==0) {2388 kill();2389 handleEx(e);2390 return;2391 }2392 fb.lastEx=e;2393 var s=fb.tryStack.pop();2394 while (frame) {2395 if (s.frame===frame) {2396 fb.catchPC=s.catchPC;2397 break;2398 } else {2399 frame=frame.prev;2400 }2401 }2402 }2403 function startCatch() {2404 var e=fb.lastEx;2405 fb.lastEx=null;2406 return e;2407 }2408 function exit(res) {2409 frame=(frame ? frame.prev:null);2410 //if (frame) frame.res=res;2411 fb.retVal=res;2412 }2413 function enterTry(catchPC) {2414 fb.tryStack.push({frame:frame,catchPC:catchPC});2415 }2416 function exitTry() {2417 fb.tryStack.pop();2418 }2419 function waitEvent(obj,eventSpec) { // eventSpec=[EventType, arg1, arg2....]2420 suspend();2421 if (!obj.on) return;2422 var h;2423 eventSpec=eventSpec.concat(function () {2424 fb.lastEvent=arguments;2425 fb.retVal=arguments[0];2426 h.remove();2427 steps();2428 });2429 h=obj.on.apply(obj, eventSpec);2430 }2431 function runAsync(f) {2432 var succ=function () {2433 fb.retVal=arguments;2434 steps();2435 };2436 var err=function () {2437 var msg="";2438 for (var i=0; i<arguments.length; i++) {2439 msg+=arguments[i]+",";2440 }2441 if (msg.length==0) msg="Async fail";2442 var e=new Error(msg);2443 e.args=arguments;2444 gotoCatch(e);2445 steps();2446 };2447 f(succ,err);2448 suspend();2449 }2450 function waitFor(j) {2451 _isWaiting=true;2452 suspend();2453 if (j && j.addTerminatedListener) j.addTerminatedListener(function () {2454 _isWaiting=false;2455 if (fb.group) fb.group.notifyResume();2456 else if (isAlive()) {2457 try {2458 fb.steps();2459 }catch(e) {2460 handleEx(e);2461 }2462 }2463 //fb.group.add(fb);2464 });2465 }2466 function setGroup(g) {2467 fb.group=g;2468 if (g) g.add(fb);2469 }2470 /*function retVal() {2471 return retVal;2472 }*/2473 function steps() {2474 //stpd++;2475 //if (stpd>5) throw new Error("Depth too much");2476 var sv=Tonyu.currentThread;2477 Tonyu.currentThread=fb;2478 //var lim=new Date().getTime()+preemptionTime;2479 cnt=preemptionTime;2480 fb.preempted=false;2481 fSuspended=false;2482 //while (new Date().getTime()<lim) {2483 while (cnt-->0 && frame) {2484 step();2485 }2486 fb.preempted= (!fSuspended) && isAlive();2487 //stpd--;2488 Tonyu.currentThread=sv;2489 }2490 function kill() {2491 _isAlive=false;2492 frame=null;2493 }2494 function clearFrame() {2495 frame=null;2496 tryStack=[];2497 }2498 return fb;2499 }2500 function timeout(t) {2501 var res={};2502 var ls=[];2503 res.addTerminatedListener=function (l) {2504 ls.push(l);2505 };2506 setTimeout(function () {2507 ls.forEach(function (l) {2508 l();2509 });2510 },t);2511 return res;2512 }2513 function animationFrame() {2514 var res={};2515 var ls=[];2516 res.addTerminatedListener=function (l) {2517 ls.push(l);2518 };2519 requestAnimationFrame(function () {2520 ls.forEach(function (l) {2521 l();2522 });2523 });2524 return res;2525 }2526 function asyncResult() {2527 var res=[];2528 var ls=[];2529 var hasRes=false;2530 res.addTerminatedListener=function (l) {2531 if (hasRes) setTimeout(l,0);2532 else ls.push(l);2533 };2534 res.receiver=function () {2535 hasRes=true;2536 for (var i=0; i<arguments.length; i++) {2537 res[i]=arguments[i];2538 }2539 res.notify();2540 };2541 res.notify=function () {2542 ls.forEach(function (l) {2543 l();2544 });2545 };2546 return res;2547 }2548 function threadGroup() {//@deprecated2549 var threads=[];2550 var waits=[];2551 var _isAlive=true;2552 var thg;2553 var _isWaiting=false;2554 var willAdd=null;2555 function add(thread) {2556 thread.group=thg;2557 if (willAdd) {2558 willAdd.push(thread);2559 } else {2560 threads.push(thread);2561 }2562 }2563 function addObj(obj, methodName,args) {2564 if (!methodName) methodName="main";2565 var th=thread();2566 th.apply(obj,methodName,args);2567 //obj["fiber$"+methodName](th);2568 add(th);2569 return th;2570 }2571 function steps() {2572 try {2573 stepsNoEx();2574 } catch(e) {2575 handleEx(e);2576 }2577 }2578 function stepsNoEx() {2579 for (var i=threads.length-1; i>=0 ;i--) {2580 var thr=threads[i];2581 if (thr.isAlive() && thr.group===thg) continue;2582 threads.splice(i,1);2583 }2584 _isWaiting=true;2585 willAdd=[];2586 threads.forEach(iter);2587 while (willAdd.length>0) {2588 w=willAdd;2589 willAdd=[];2590 w.forEach(function (th) {2591 threads.push(th);2592 iter(th);2593 });2594 }2595 willAdd=null;2596 function iter(th){2597 if (th.isWaiting()) return;2598 _isWaiting=false;2599 th.steps();2600 }2601 }2602 function kill() {2603 _isAlive=false;2604 }2605 var _interval=0, _onStepsEnd;2606 function notifyResume() {2607 if (_isWaiting) {2608 //console.log("resume!");2609 //run();2610 }2611 }2612 return thg={add:add, addObj:addObj, steps:steps, kill:kill, notifyResume: notifyResume, threads:threads};2613 }2614 function handleEx(e) {2615 if (Tonyu.onRuntimeError) {2616 Tonyu.onRuntimeError(e);2617 } else {2618 alert ("エラー! at "+$LASTPOS+" メッセージ : "+e);2619 throw e;2620 }2621 }2622 function defunct(f) {2623 if (f===Function) {2624 return null;2625 }2626 if (typeof f=="function") {2627 f.constructor=null;2628 } else if (typeof f=="object"){2629 for (var i in f) {2630 f[i]=defunct(f[i]);2631 }2632 }2633 return f;2634 }2635 function klass() {2636 var parent, prot, includes=[];2637 if (arguments.length==1) {2638 prot=arguments[0];2639 } else if (arguments.length==2 && typeof arguments[0]=="function") {2640 parent=arguments[0];2641 prot=arguments[1];2642 } else if (arguments.length==2 && arguments[0] instanceof Array) {2643 includes=arguments[0];2644 prot=arguments[1];2645 } else if (arguments.length==3) {2646 parent=arguments[0];2647 if (!parent) {2648 console.log(arguments[2]);2649 throw new Error("No parent class ");2650 }2651 includes=arguments[1];2652 prot=arguments[2];2653 } else {2654 console.log(arguments);2655 throw "Invalid argument spec";2656 }2657 prot=defunct(prot);2658 var res=(prot.initialize? prot.initialize:2659 (parent? function () {2660 parent.apply(this,arguments);2661 }:function (){})2662 );2663 delete prot.initialize;2664 //A includes B B includes C B extends D2665 //A extends E E includes F2666 //A has methods in B,C,E,F. [Mod] A extends D.2667 // Known examples:2668 // Actor extends BaseActor, includes PlayMod.2669 // PlayMod extends BaseActor(because use update() in play())2670 res.methods=prot;2671 //prot=bless(parent, prot);2672 includes.forEach(function (m) {2673 if (!m.methods) throw m+" Does not have methods";2674 for (var n in m.methods) {2675 if (!(n in prot)) {2676 prot[n]=m.methods[n];2677 }2678 }2679 /*for (var n in m.prototype) {2680 if (!(n in prot)) { //-> cannot override color in ColorMod(MetaClicker/FlickEdit)2681 //if ((typeof m.prototype[n])=="function") { //-> BodyActor::onAppear is overriden by Actor::onAppear(nop)2682 prot[n]=m.prototype[n];2683 }2684 }*/2685 });2686 res.prototype=bless(parent, prot);2687 res.prototype.isTonyuObject=true;2688 addMeta(res,{2689 superclass:parent ? parent.meta : null,2690 includes:includes.map(function(c){return c.meta;})2691 });2692 var m=klass.getMeta(res);2693 res.prototype.getClassInfo=function () {2694 return m;2695 };2696 return res;2697 }2698 klass.addMeta=addMeta;2699 function addMeta(k,m) {2700 k.meta=k.meta||{};2701 extend(k.meta, m);2702 }2703 klass.getMeta=function (k) {2704 return k.meta;2705 };2706 klass.ensureNamespace=function (top,nsp) {2707 var keys=nsp.split(".");2708 var o=top;2709 var i;2710 for (i=0; i<keys.length; i++) {2711 var k=keys[i];2712 if (!o[k]) o[k]={};2713 o=o[k];2714 }2715 return o;2716 };2717 klass.define=function (params) {2718 // fullName, shortName,namspace, superclass, includes, methods:{name/fiber$name: func}, decls2719 var parent=params.superclass;2720 var includes=params.includes;2721 var fullName=params.fullName;2722 var shortName=params.shortName;2723 var namespace=params.namespace;2724 var methods=params.methods;2725 var decls=params.decls;2726 var nso=klass.ensureNamespace(Tonyu.classes, namespace);2727 var prot=defunct(methods);2728 var init=prot.initialize;2729 delete prot.initialize;2730 var res;2731 res=(init?2732 (parent? function () {2733 if (!(this instanceof res)) useNew();2734 if (Tonyu.runMode) init.apply(this,arguments);2735 else parent.apply(this,arguments);2736 }:function () {2737 if (!(this instanceof res)) useNew();2738 if (Tonyu.runMode) init.apply(this,arguments);2739 }):2740 (parent? function () {2741 if (!(this instanceof res)) useNew();2742 parent.apply(this,arguments);2743 }:function (){2744 if (!(this instanceof res)) useNew();2745 })2746 );2747 nso[shortName]=res;2748 res.methods=prot;2749 includes.forEach(function (m) {2750 if (!m.methods) throw m+" Does not have methods";2751 for (var n in m.methods) {2752 if (!(n in prot)) {2753 prot[n]=m.methods[n];2754 }2755 }2756 });2757 var props={};2758 var propReg=/^__([gs]et)ter__(.*)$/;2759 for (var k in prot) {2760 if (k.match(/^fiber\$/)) continue;2761 if (prot["fiber$"+k]) {2762 prot[k].fiber=prot["fiber$"+k];2763 prot[k].fiber.methodInfo={name:k,klass:res,fiber:true};2764 }2765 prot[k].methodInfo={name:k,klass:res};2766 var r=propReg.exec(k);2767 if (r) {2768 props[r[2]]=props[r[2]]||{};2769 props[r[2]][r[1]]=prot[k];2770 }2771 }2772 res.prototype=bless(parent, prot);2773 res.prototype.isTonyuObject=true;2774 for (var k in props) {2775 Object.defineProperty(res.prototype, k , props[k]);2776 }2777 addMeta(res,{2778 fullName:fullName,shortName:shortName,namepsace:namespace,decls:decls,2779 superclass:parent ? parent.meta : null,func:res,2780 includes:includes.map(function(c){return c.meta;})2781 });2782 var m=klass.getMeta(res);2783 res.prototype.getClassInfo=function () {2784 return m;2785 };2786 return res;2787 };2788 function bless( klass, val) {2789 if (!klass) return val;2790 return extend( new klass() , val);2791 }2792 function extend (dst, src) {2793 if (src && typeof src=="object") {2794 for (var i in src) {2795 dst[i]=src[i];2796 }2797 }2798 return dst;2799 }2800 //alert("init");2801 var globals={};2802 var classes={};2803 function setGlobal(n,v) {2804 globals[n]=v;2805 }2806 function getGlobal(n) {2807 return globals[n];2808 }2809 function getClass(n) {2810 //CFN: n.split(".")2811 var ns=n.split(".");2812 var res=classes;2813 ns.forEach(function (na) {2814 if (!res) return;2815 res=res[na];2816 });2817 if (!res && ns.length==1) {2818 var found;2819 for (var nn in classes) {2820 var nr=classes[nn][n];2821 if (nr) {2822 if (!res) { res=nr; found=nn+"."+n; }2823 else throw new Error("曖昧なクラス名: "+nn+"."+n+", "+found);2824 }2825 }2826 }2827 return res;//classes[n];2828 }2829 function bindFunc(t,meth) {2830 var res=function () {2831 return meth.apply(t,arguments);2832 };2833 res.methodInfo=Tonyu.extend({thiz:t},meth.methodInfo||{});2834 if (meth.fiber) {2835 res.fiber=function fiber_func() {2836 return meth.fiber.apply(t,arguments);2837 };2838 res.fiber.methodInfo=Tonyu.extend({thiz:t},meth.fiber.methodInfo||{});2839 }2840 return res;2841 }2842 function invokeMethod(t, name, args, objName) {2843 if (!t) throw new Error(objName+"(="+t+")のメソッド "+name+"を呼び出せません");2844 var f=t[name];2845 if (typeof f!="function") throw new Error((objName=="this"? "": objName+".")+name+"(="+f+")はメソッドではありません");2846 return f.apply(t,args);2847 }2848 function callFunc(f,args, fName) {2849 if (typeof f!="function") throw new Error(fName+"は関数ではありません");2850 return f.apply({},args);2851 }2852 function checkNonNull(v, name) {2853 if (v!=v || v==null) throw new Error(name+"(="+v+")は初期化されていません");2854 return v;2855 }2856 function A(args) {2857 var res=[];2858 for (var i=1 ; i<args.length; i++) {2859 res[i-1]=args[i];2860 }2861 return res;2862 }2863 function useNew() {2864 throw new Error("クラス名はnewをつけて呼び出して下さい。");2865 }2866 function not_a_tonyu_object(o) {2867 console.log("Not a tonyu object: ",o);2868 throw new Error(o+" is not a tonyu object");2869 }2870 function hasKey(k, obj) {2871 return k in obj;2872 }2873 function run(bootClassName) {2874 var bootClass=getClass(bootClassName);2875 if (!bootClass) throw new Error( bootClassName+" というクラスはありません");2876 Tonyu.runMode=true;2877 var boot=new bootClass();2878 var th=thread();2879 th.apply(boot,"main");2880 var TPR;2881 if (TPR=Tonyu.currentProject) {2882 TPR.runningThread=th;2883 TPR.runningObj=boot;2884 }2885 $LASTPOS=0;2886 th.steps();2887 }2888 return Tonyu={thread:thread, threadGroup:threadGroup, klass:klass, bless:bless, extend:extend,2889 globals:globals, classes:classes, setGlobal:setGlobal, getGlobal:getGlobal, getClass:getClass,2890 timeout:timeout,animationFrame:animationFrame, asyncResult:asyncResult,bindFunc:bindFunc,not_a_tonyu_object:not_a_tonyu_object,2891 hasKey:hasKey,invokeMethod:invokeMethod, callFunc:callFunc,checkNonNull:checkNonNull,2892 run:run,2893 VERSION:1447046170638,//EMBED_VERSION2894 A:A};2895}();2896});2897requireSimulator.setName('PatternParser');2898define(["Tonyu"], function (Tonyu) {return Tonyu.klass({2899 initialize: function (img, options) {2900 this.options=options || {};2901 this.img=img;2902 this.height = img.height;2903 this.width = img.width;2904 var cv=this.newImage(img.width, img.height);2905 var ctx=cv.getContext("2d");2906 ctx.drawImage(img, 0,0);2907 this.ctx=ctx;2908 this.pixels=this.ctx.getImageData(0, 0, img.width, img.height).data;2909 this.base=this.getPixel(0,0);2910 },2911 newImage: function (w,h) {2912 var cv=document.createElement("canvas");2913 cv.width=w;2914 cv.height=h;2915 return cv;2916 },2917 getPixel: function (x,y) {2918 var imagePixelData = this.pixels;2919 var ofs=(x+y*this.width)*4;2920 var R = imagePixelData[0+ofs];2921 var G = imagePixelData[1+ofs];2922 var B = imagePixelData[2+ofs];2923 var A = imagePixelData[3+ofs];2924 return ((((A*256)+B)*256)+G)*256+R;2925 },2926 setPixel: function (x,y,p) {2927 var ofs=(x+y*this.width)*4;2928 this.pixels[0+ofs]=p & 255;2929 p=(p-(p&255))/256;2930 this.pixels[1+ofs]=p & 255;2931 p=(p-(p&255))/256;2932 this.pixels[2+ofs]=p & 255;2933 p=(p-(p&255))/256;2934 this.pixels[3+ofs]=p & 255;2935 },2936 parse: function () {2937 try {2938 //console.log("parse()");2939 var res=[];// List of charpattern2940 for (var y=0; y<this.height ;y++) {2941 for (var x=0; x<this.width ;x++) {2942 var c=this.getPixel(x, y);2943 if (c!=this.base) {2944 res.push(this.parse1Pattern(x,y));2945 }2946 }2947 }2948 //console.log("parsed:"+res.lenth);2949 return res;2950 } catch (p) {2951 if (p.isParseError) {2952 console.log("parse error! "+p);2953 return {image: this.img, x:0, y:0, width:this.width, height:this.height};2954 }2955 throw p;2956 }2957 },2958 parse1Pattern:function (x,y) {2959 function hex(s){return s;}2960 var trans=this.getPixel(x, y);2961 var dx=x,dy=y;2962 var base=this.base;2963 var width=this.width, height=this.height;2964 while (dx<width) {2965 var pixel = this.getPixel(dx,dy);2966 if (pixel!=trans) break;2967 dx++;2968 }2969 if (dx>=width || this.getPixel(dx,dy)!=base) {2970 throw PatterParseError(dx,dy,hex(this.getPixel(dx,dy))+"!="+hex(base));2971 }2972 dx--;2973 while (dy<height) {2974 if (this.getPixel(dx,dy)!=trans) break;2975 dy++;2976 }2977 if (dy>=height || this.getPixel(dx,dy)!=base) {2978 throw PatterParseError(dx,dy,hex(this.getPixel(dx,dy))+"!="+hex(base));2979 }2980 dy--;2981 var sx=x+1,sy=y+1,w=dx-sx,h=dy-sy;2982 console.log("PP",sx,sy,w,h,dx,dy);2983 if (w*h==0) throw PatterParseError(dx, dy,"w*h==0");2984 var newim=this.newImage(w,h);2985 var nc=newim.getContext("2d");2986 var newImD=nc.getImageData(0,0,w,h);2987 var newD=newImD.data;2988 var di=0;2989 for (var ey=sy ; ey<dy ; ey++) {2990 for (var ex=sx ; ex<dx ; ex++) {2991 var p=this.getPixel(ex, ey);2992 if (p==trans) {2993 newD[di++]=0;2994 newD[di++]=(0);2995 newD[di++]=(0);2996 newD[di++]=(0);2997 } else {2998 newD[di++]=(p&255);2999 p=(p-(p&255))/256;3000 newD[di++]=(p&255);3001 p=(p-(p&255))/256;3002 newD[di++]=(p&255);3003 p=(p-(p&255))/256;3004 newD[di++]=(p&255);3005 }3006 }3007 }3008 nc.putImageData(newImD,0,0);3009 for (var yy=sy-1; yy<=dy; yy++) {3010 for (var xx=sx-1; xx<=dx; xx++) {3011 this.setPixel(xx,yy, base);3012 }3013 }3014 if (this.options.boundsInSrc) {3015 return {x:sx,y:sy,width:w,height:h};3016 }3017 return {image:newim, x:0, y:0, width:w, height:h};3018 function PatterParseError(x,y,msg) {3019 return {toString: function () {3020 return "at ("+x+","+y+") :"+msg;3021 }, isParseError:true};3022 }3023 }3024});});3025requireSimulator.setName('Assets');3026define(["WebSite","Util","Tonyu"],function (WebSite,Util,Tonyu) {3027 var Assets={};3028 Assets.resolve=function (url, baseDir) {3029 if (url==null) url="";3030 url=url.replace(/\$\{([a-zA-Z0-9_]+)\}/g, function (t,name) {3031 return WebSite[name];3032 });3033 if (WebSite.urlAliases[url]) url=WebSite.urlAliases[url];3034 if (Util.startsWith(url,"ls:")) {3035 var rel=url.substring("ls:".length);3036 if (!baseDir) throw new Error("Basedir not specified");3037 var f=baseDir.rel(rel);3038 if (!f.exists()) throw new Error("Resource file not found: "+f);3039 if (WebSite.mp3Disabled && rel.match(/\.mp3$/)) {3040 var oggf=baseDir.rel(rel.replace(/\.mp3$/,".ogg"));3041 if (oggf.exists()) {3042 f=oggf;3043 }3044 }3045 url=f.getURL();3046 }3047 return url;3048 };3049 Tonyu.Assets=Assets;3050 return Assets;3051});3052requireSimulator.setName('ImageList');3053define(["PatternParser","Util","Assets"], function (PP,Util,Assets) {3054 var cache={};3055 function excludeEmpty(resImgs) {3056 var r=[];3057 resImgs.forEach(function (resImg,i) {3058 if (!resImg || resImg.url=="") return;3059 r.push(resImg);3060 });3061 return r;3062 }3063 var IL;3064 IL=function (resImgs, onLoad,options) {3065 // resImgs:[{url: , [pwidth: , pheight:]? }]3066 if (!options) options={};3067 resImgs=excludeEmpty(resImgs);3068 var resa=[];3069 var cnt=resImgs.length;3070 resImgs.forEach(function (resImg,i) {3071 console.log("loading", resImg,i);3072 var url=resImg.url;3073 var urlKey=url;3074 if (cache[urlKey]) {3075 proc.apply(cache[urlKey],[]);3076 return;3077 }3078 url=IL.convURL(url,options.baseDir);3079 //if (!Util.startsWith(url,"data:")) url+="?" + new Date().getTime();3080 var im=$("<img>");3081 im.load(function () {3082 cache[urlKey]=this;3083 proc.apply(this,[]);3084 });3085 im.attr("src",url);3086 function proc() {3087 var pw,ph;3088 if ((pw=resImg.pwidth) && (ph=resImg.pheight)) {3089 var x=0, y=0, w=this.width, h=this.height;3090 var r=[];3091 while (true) {3092 var rw=pw,rh=ph;3093 if (x+pw>w) rw=w-x;3094 if (y+ph>h) rh=h-y;3095 r.push({image:this, x:x,y:y, width:rw, height:rh});3096 x+=pw;3097 if (x+pw>w) {3098 x=0;3099 y+=ph;3100 if (y+ph>h) break;3101 }3102 }3103 resa[i]=r;3104 } else {3105 var p=new PP(this);3106 resa[i]=p.parse();3107 }3108 resa[i].name=resImg.name;3109 cnt--;3110 if (cnt==0) {3111 var res=[];3112 var names={};3113 resa.forEach(function (a) {3114 names[a.name]=res.length;3115 res=res.concat(a);3116 });3117 res.names=names;3118 onLoad(res);3119 }3120 }3121 });3122 };3123 IL.load=IL;3124 IL.parse1=function (resImg, imgDOM, options) {3125 var pw,ph;3126 var res;3127 if ((pw=resImg.pwidth) && (ph=resImg.pheight)) {3128 var x=0, y=0, w=imgDOM.width, h=imgDOM.height;3129 var r=[];3130 while (true) {3131 r.push({image:this, x:x,y:y, width:pw, height:ph});3132 x+=pw;3133 if (x+pw>w) {3134 x=0;3135 y+=ph;3136 if (y+ph>h) break;3137 }3138 }3139 res=r;3140 } else {3141 var p=new PP(imgDOM,options);3142 res=p.parse();3143 }3144 res.name=resImg.name;3145 return res;3146 };3147 IL.convURL=function (url, baseDir) {3148 /*if (url==null) url="";3149 url=url.replace(/\$\{([a-zA-Z0-9_]+)\}/g, function (t,name) {3150 return WebSite[name];3151 });3152 if (WebSite.urlAliases[url]) url=WebSite.urlAliases[url];3153 if (Util.startsWith(url,"ls:")) {3154 var rel=url.substring("ls:".length);3155 if (!baseDir) throw new Error("Basedir not specified");3156 var f=baseDir.rel(rel);3157 if (!f.exists()) throw "ImageList file not found: "+f;3158 url=f.text();3159 }3160 return url;*/3161 return Assets.resolve(url, baseDir);3162 };3163 window.ImageList=IL;3164 return IL;3165});3166requireSimulator.setName('T2MediaLib');3167// forked from makkii_bcr's "T2MediaLib" http://jsdo.it/makkii_bcr/3ioQ3168// T2MediaLib_BGMPlayer //3169var T2MediaLib_BGMPlayer = function(arg_id) {3170 this.id = arg_id;3171 this.playingBGM = null;3172 this.playingBGMName = null;3173 this.bgmPause = 0;3174 this.bgmPauseTime = 0;3175 this.bgmPauseCurrentTime = 0;3176 this.bgmPauseTempo = 0;3177 this.bgmPauseLoop = false;3178 this.bgmPauseLoopStart = 0;3179 this.bgmPauseLoopEnd = 0;3180 this.bgmVolume = 1.0;3181 this.bgmTempo = 1.0;3182};3183// BGM関数郡 //3184T2MediaLib_BGMPlayer.prototype.playBGM = function(idx, loop, offset, loopStart, loopEnd) {3185 if (!T2MediaLib.context) return null;3186 var bgm = this.playingBGM;3187 if (bgm instanceof AudioBufferSourceNode) bgm.stop(0);3188 this.playingBGM = T2MediaLib.playSE(idx, this.bgmVolume, this.bgmTempo, offset, loop, loopStart, loopEnd);3189 this.playingBGMName = idx;3190 this.bgmPause = 0;3191 return this.playingBGM;3192};3193T2MediaLib_BGMPlayer.prototype.stopBGM = function() {3194 var bgm = this.playingBGM;3195 if (!(bgm instanceof AudioBufferSourceNode)) return null;3196 bgm.stop(0);3197 this.playingBGM = null;3198 return bgm;3199};3200T2MediaLib_BGMPlayer.prototype.pauseBGM = function() {3201 var bgm = this.playingBGM;3202 if (!(bgm instanceof AudioBufferSourceNode)) return null;3203 if (this.bgmPause === 0) {3204 this.bgmPauseTime = this.getBGMCurrentTime();3205 this.bgmPauseLoopStart = bgm.loopStart;3206 this.bgmPauseLoopEnd = bgm.loopEnd;3207 this.bgmPauseLoop = bgm.loop;3208 this.bgmPauseCurrentTime = bgm.context.currentTime;3209 this.bgmPauseTempo = T2MediaLib.bgmTempo;3210 bgm.stop(0);3211 this.bgmPause = 1;3212 }3213 return bgm;3214};3215T2MediaLib_BGMPlayer.prototype.resumeBGM = function() {3216 var bgm = this.playingBGM;3217 if (!(bgm instanceof AudioBufferSourceNode)) return null;3218 if (this.bgmPause === 1) {3219 bgm = this.playBGM(this.playingBGMName, this.bgmPauseLoop, this.bgmPauseTime, this.bgmPauseLoopStart, this.bgmPauseLoopEnd);3220 this.bgmPause = 0;3221 }3222 return bgm;3223};3224T2MediaLib_BGMPlayer.prototype.setBGMVolume = function(vol) {3225 var bgm = this.playingBGM;3226 if (!(bgm instanceof AudioBufferSourceNode)) return null;3227 this.bgmVolume = vol;3228 T2MediaLib.setSEVolume(bgm, vol);3229};3230T2MediaLib_BGMPlayer.prototype.setBGMTempo = function(tempo) {3231 var bgm = this.playingBGM;3232 if (!(bgm instanceof AudioBufferSourceNode)) return null;3233 if (this.bgmPause === 0) {3234 bgm.plusTime -= (T2MediaLib.context.currentTime - bgm.playStartTime) * (tempo - this.bgmTempo);3235 }3236 this.bgmTempo = tempo;3237 T2MediaLib.setSERate(bgm, tempo);3238};3239T2MediaLib_BGMPlayer.prototype.getBGMCurrentTime = function() {3240 var bgm = this.playingBGM;3241 if (!(bgm instanceof AudioBufferSourceNode)) return null;3242 var time, time2, currenTime, tempo, plusTime, minusTime, mod;3243 if (this.bgmPause === 0) {3244 currenTime = T2MediaLib.context.currentTime;3245 tempo = this.bgmTempo;3246 } else {3247 currenTime = this.bgmPauseCurrentTime;3248 tempo = this.bgmPauseTempo;3249 }3250 time2 = (currenTime - bgm.playStartTime) * tempo + bgm.plusTime;3251 if (bgm.loop) {3252 if (bgm.loopEnd - bgm.loopStart > 0) { // ループ範囲正常3253 if (time2 < bgm.loopStart) { // ループ範囲前3254 plusTime = 0;3255 minusTime = 0;3256 mod = bgm.buffer.duration;3257 } else { // ループ範囲内3258 plusTime = bgm.loopStart;3259 minusTime = bgm.loopStart;3260 mod = bgm.loopEnd - bgm.loopStart;3261 }3262 } else { // ループ範囲マイナス(ループ無効)3263 mod = bgm.buffer.duration;3264 plusTime = 0;3265 minusTime = 0;3266 }3267 }3268 if (bgm.loop) {3269 time = ((time2 - minusTime) % mod) + plusTime;3270 } else {3271 time = time2;3272 if (time > bgm.buffer.duration) time = bgm.buffer.duration;3273 }3274 return time;3275};3276T2MediaLib_BGMPlayer.prototype.getBGMLength = function() {3277 var bgm = this.playingBGM;3278 if (!(bgm instanceof AudioBufferSourceNode)) return null;3279 return bgm.buffer.duration;3280};3281// ライブラリ本体 //3282// T2MediaLib //3283var T2MediaLib = {3284 context : null,3285 seDataAry : {3286 data : []3287 },3288 bgmPlayerMax : 16,3289 bgmPlayerAry : [],3290 playingBGM : null,3291 playingBGMName : null,3292 bgmPause : 0,3293 bgmPauseTime : 0,3294 bgmPauseCurrentTime : 0,3295 bgmPauseTempo : 0,3296 bgmPauseLoop : false,3297 bgmPauseLoopStart : 0,3298 bgmPauseLoopEnd : 0,3299 bgmVolume : 1.0,3300 bgmTempo : 1.0,3301 playingAudio : null,3302 audioVolume : 1.0,3303 audioTempo : 1.0,3304 audioDataAry : {3305 data : []3306 },3307 // 初期化 //3308 init : function() {3309 if (this.inited) return;3310 this.inited=true;3311 if (this.disabled) return;3312 if (window.AudioContext) {3313 T2MediaLib.context = new AudioContext();3314 } else if (window.webkitAudioContext) {3315 T2MediaLib.context = new webkitAudioContext();3316 } else {3317 T2MediaLib.context = null;3318 console.log('Your browser does not support yet Web Audio API');3319 }3320 // Web Audio API 起動成功3321 if (T2MediaLib.context) {3322 // BGMPlayer初期化 (16個生成)3323 for (var i=0; i<T2MediaLib.bgmPlayerMax; i++) {3324 T2MediaLib.bgmPlayerAry[i] = new T2MediaLib_BGMPlayer(i);3325 }3326 }3327 },3328 // CLEAR系関数 //3329 allClearData : function() {3330 var dataAry = T2MediaLib.seDataAry.data;3331 for (var data in dataAry) {3332 delete dataAry[data];3333 }3334 },3335 clearData : function(idx) {3336 var dataAry = T2MediaLib.seDataAry.data;3337 delete dataAry[idx];3338 },3339 // SEメソッド郡 //3340 loadSEFromArray: function (idx, array) {3341 var ctx=T2MediaLib.context;3342 var myArrayBuffer = ctx.createBuffer(3343 1, array.length, ctx.sampleRate);3344 var nowBuffering = myArrayBuffer.getChannelData(0);3345 for (var i = 0; i < array.length ; i++) {3346 nowBuffering[i] = array[i];3347 }3348 //var source = ctx.createBufferSource();3349 // set the buffer in the AudioBufferSourceNode3350 //source.buffer = myArrayBuffer;3351 T2MediaLib.seDataAry.data[idx]=myArrayBuffer;//source;3352 },3353 loadSE : function(idx, url, callbacks) { //@hoge1e33354 if (!T2MediaLib.context || T2MediaLib.disabled) {3355 T2MediaLib.seDataAry.data[idx] = -1;3356 return null;3357 }3358 if (typeof WebSite=="object" && WebSite.mp3Disabled) {3359 url=url.replace(/\.mp3$/,".ogg");3360 }3361 var xhr = new XMLHttpRequest();3362 xhr.onload = function() {3363 if (xhr.status === 200 || xhr.status=== 0 /*@hoge1e3 for node-webkit base64url */) {3364 var arrayBuffer = xhr.response;3365 if (arrayBuffer instanceof ArrayBuffer) {3366 var successCallback = function(audioBuffer) {3367 /*3368 window.alert('Success : ' +3369 'sampleRate:' + audioBuffer.sampleRate + '\n' +3370 'length:' + audioBuffer.length + '\n' +3371 'duration:' + audioBuffer.duration + '\n' +3372 'numberOfChannels:' + audioBuffer.numberOfChannels + '\n');3373 */3374 T2MediaLib.seDataAry.data[idx] = audioBuffer;3375 if (callbacks && callbacks.succ) callbacks.succ(idx);//@hoge1e33376 };3377 var errorCallback = function(error) {3378 if (error instanceof Error) {3379 console.log('T2MediaLib: '+error.message,url);3380 } else {3381 console.log('T2MediaLib: Error decodeAudioData()',url);3382 }3383 T2MediaLib.seDataAry.data[idx] = -4;3384 if (callbacks && callbacks.err) callbacks.err(idx,T2MediaLib.seDataAry.data[idx]);//@hoge1e33385 };3386 T2MediaLib.context.decodeAudioData(arrayBuffer, successCallback, errorCallback);3387 } else {3388 T2MediaLib.seDataAry.data[idx] = -3;3389 if (callbacks && callbacks.err) callbacks.err(idx,T2MediaLib.seDataAry.data[idx]);//@hoge1e33390 }3391 } else {3392 T2MediaLib.seDataAry.data[idx] = -2;3393 if (callbacks && callbacks.err) callbacks.err(idx,T2MediaLib.seDataAry.data[idx]);//@hoge1e33394 }3395 };3396 xhr.onerror=function (e) {//@hoge1e33397 if (callbacks && callbacks.err) callbacks.err(idx,e+"");3398 };3399 T2MediaLib.seDataAry.data[idx] = null;3400 if (url.match(/^data:/) && Util && Util.Base64_To_ArrayBuffer) {//@hoge1e33401 xhr={onload:xhr.onload};3402 xhr.response=Util.Base64_To_ArrayBuffer( url.replace(/^data:audio\/[a-zA-Z0-9]+;base64,/i,""));3403 xhr.status=200;3404 xhr.onload();3405 } else {3406 xhr.open('GET', url, true);3407 xhr.responseType = 'arraybuffer'; // XMLHttpRequest Level 23408 xhr.send(null);3409 }3410 //setTimeout(T2MediaLib.activate.bind(T2MediaLib),0);3411 },3412 activate: function () {3413 // create empty buffer3414 this.init();3415 if (this.isActivated) return;3416 this.isActivated=true;3417 var myContext=T2MediaLib.context;3418 var buffer = myContext.createBuffer(1, Math.floor(myContext.sampleRate/32), myContext.sampleRate);3419 var ary = buffer.getChannelData(0);3420 var lam = Math.floor(myContext.sampleRate/860);3421 for (var i = 0; i < ary.length; i++) {3422 ary[i] = (i % lam<lam/2?0.1:-0.1)*(i<lam?2:1) ;3423 }3424 //console.log(ary);3425 var source = myContext.createBufferSource();3426 source.buffer = buffer;3427 // connect to output (your speakers)3428 source.connect(myContext.destination);3429 // play the file3430 if (source.noteOn) source.noteOn(0);3431 else if (source.start) source.start(0);3432 },3433 playSE : function(idx, vol, rate, offset, loop, loopStart, loopEnd) {3434 if (!T2MediaLib.context) return null;3435 var audioBuffer = T2MediaLib.seDataAry.data[idx];3436 if (!(audioBuffer instanceof AudioBuffer)) return null;3437 // 引数チェック3438 if (vol === null) {3439 vol = 1;3440 }3441 if (!rate) rate = 1.0;3442 if (!offset) {3443 offset = 0;3444 } else {3445 if (offset > audioBuffer.duration) offset = audioBuffer.duration;3446 else if (offset < 0.0) offset = 0.0;3447 }3448 if (!loop) loop = false;3449 if (!loopStart) {3450 loopStart = 0.0;3451 } else {3452 if (loopStart < 0.0) loopStart = 0.0;3453 else if (loopStart > audioBuffer.duration) loopStart = audioBuffer.duration;3454 }3455 if (!loopEnd) {3456 loopEnd = audioBuffer.duration;3457 } else {3458 if (loopEnd < 0.0) loopEnd = 0.0;3459 else if (loopEnd > audioBuffer.duration) loopEnd = audioBuffer.duration;3460 }3461 var source = T2MediaLib.context.createBufferSource();3462 T2MediaLib.context.createGain = T2MediaLib.context.createGain || T2MediaLib.context.createGainNode;3463 var gainNode = T2MediaLib.context.createGain();3464 source.buffer = audioBuffer;3465 source.loop = loop;3466 source.loopStart = loopStart;3467 source.loopEnd = loopEnd;//audioBuffer.duration;3468 source.playbackRate.value = rate;3469 // 通常ノード接続3470 //source.connect(T2MediaLib.context.destination);3471 // 音量変更できるようノード接続3472 source.connect(gainNode);3473 gainNode.connect(T2MediaLib.context.destination);3474 // ループ開始位置修正3475 var offset_adj;3476 if (loop && loopEnd - loopStart > 0 && offset > loopEnd) {3477 offset_adj = loopEnd;3478 } else {3479 offset_adj = offset;3480 }3481 // 変数追加3482 source.gainNode = gainNode;3483 source.playStartTime = T2MediaLib.context.currentTime;3484 source.playOffset = offset_adj;3485 source.plusTime = offset_adj;3486 // 再生3487 source.start = source.start || source.noteOn;3488 source.stop = source.stop || source.noteOff;3489 gainNode.gain.value = vol * vol;3490 if (offset) {3491 if (loop) source.start(0, offset, 86400);3492 else source.start(0, offset);3493 } else {3494 source.start(0);3495 }3496 source.onended = function(event) {3497 //console.log('"on' + event.type + '" event handler !!');3498 //source.stop(0);3499 delete source.gainNode;3500 //delete source.playStartTime;3501 //delete source.playOffset;3502 //delete source.plusTime;3503 source.onended = null;3504 };3505 //console.log(source);3506 return source;3507 },3508 stopSE : function(sourceObj) {3509 if (!(sourceObj instanceof AudioBufferSourceNode)) return null;3510 sourceObj.stop(0);3511 return sourceObj;3512 },3513 setSEVolume : function(sourceObj, vol) {3514 if (!(sourceObj instanceof AudioBufferSourceNode)) return null;3515 sourceObj.gainNode.gain.value = vol * vol;3516 },3517 setSERate : function(sourceObj, rate) {3518 if (!(sourceObj instanceof AudioBufferSourceNode)) return null;3519 sourceObj.playbackRate.value = rate;3520 },3521 getSEData : function(idx) {3522 return T2MediaLib.seDataAry.data[idx];3523 },3524 // BGMメソッド郡 //3525 loadBGM : function(idx, url, callbacks) {3526 return T2MediaLib.loadSE(idx, url, callbacks);3527 },3528 playBGM : function(id, idx, loop, offset, loopStart, loopEnd) {3529 if (id < 0 || T2MediaLib.bgmPlayerMax <= id) return null;3530 var bgmPlayer = T2MediaLib.bgmPlayerAry[id];3531 if (!(bgmPlayer instanceof T2MediaLib_BGMPlayer)) return null;3532 return bgmPlayer.playBGM(idx, loop, offset, loopStart, loopEnd);3533 },3534 stopBGM : function(id) {3535 if (id < 0 || T2MediaLib.bgmPlayerMax <= id) return null;3536 var bgmPlayer = T2MediaLib.bgmPlayerAry[id];3537 if (!(bgmPlayer instanceof T2MediaLib_BGMPlayer)) return null;3538 return bgmPlayer.stopBGM();3539 },3540 pauseBGM : function(id) {3541 if (id < 0 || T2MediaLib.bgmPlayerMax <= id) return null;3542 var bgmPlayer = T2MediaLib.bgmPlayerAry[id];3543 if (!(bgmPlayer instanceof T2MediaLib_BGMPlayer)) return null;3544 return bgmPlayer.pauseBGM();3545 },3546 resumeBGM : function(id) {3547 if (id < 0 || T2MediaLib.bgmPlayerMax <= id) return null;3548 var bgmPlayer = T2MediaLib.bgmPlayerAry[id];3549 if (!(bgmPlayer instanceof T2MediaLib_BGMPlayer)) return null;3550 return bgmPlayer.resumeBGM();3551 },3552 setBGMVolume : function(id, vol) {3553 if (id < 0 || T2MediaLib.bgmPlayerMax <= id) return null;3554 var bgmPlayer = T2MediaLib.bgmPlayerAry[id];3555 if (!(bgmPlayer instanceof T2MediaLib_BGMPlayer)) return null;3556 return bgmPlayer.setBGMVolume(vol);3557 },3558 setBGMTempo : function(id, tempo) {3559 if (id < 0 || T2MediaLib.bgmPlayerMax <= id) return null;3560 var bgmPlayer = T2MediaLib.bgmPlayerAry[id];3561 if (!(bgmPlayer instanceof T2MediaLib_BGMPlayer)) return null;3562 return bgmPlayer.setBGMTempo(tempo);3563 },3564 getBGMCurrentTime : function(id) {3565 if (id < 0 || T2MediaLib.bgmPlayerMax <= id) return null;3566 var bgmPlayer = T2MediaLib.bgmPlayerAry[id];3567 if (!(bgmPlayer instanceof T2MediaLib_BGMPlayer)) return null;3568 return bgmPlayer.getBGMCurrentTime();3569 },3570 getBGMLength : function(id) {3571 if (id < 0 || T2MediaLib.bgmPlayerMax <= id) return null;3572 var bgmPlayer = T2MediaLib.bgmPlayerAry[id];3573 if (!(bgmPlayer instanceof T2MediaLib_BGMPlayer)) return null;3574 return bgmPlayer.getBGMLength();3575 },3576 getBGMData : function(idx) {3577 return T2MediaLib.getSEData(idx);3578 },3579 getBGMPlayerMax : function() {3580 return T2MediaLib.bgmPlayerMax;3581 },3582 allStopBGM : function() {3583 for (var i=0; i<T2MediaLib.bgmPlayerMax; i++) {3584 T2MediaLib.stopBGM(i);3585 }3586 },3587 // Audioメソッド郡 //3588 loadAudio : function(idx, url) {3589 var audio = new Audio(url);3590 audio.play();3591 T2MediaLib.audioDataAry.data[idx] = null;3592 audio.addEventListener('loadstart', function() {3593 if (!T2MediaLib.context) return null;3594 var source = T2MediaLib.context.createMediaElementSource(audio);3595 source.connect(T2MediaLib.context.destination);3596 }, false);3597 audio.addEventListener('canplay', function() {3598 T2MediaLib.audioDataAry.data[idx] = audio;3599 }, false);3600 audio.load();3601 },3602 playAudio : function(idx, loop, startTime) {3603 var audio = T2MediaLib.audioDataAry.data[idx];3604 if (!audio) return null;3605 if (!startTime) startTime = 0;3606 if (T2MediaLib.playingAudio instanceof Audio) {3607 T2MediaLib.playingAudio.pause();3608 T2MediaLib.playingAudio.currentTime = 0;3609 }3610 T2MediaLib.playingAudio = audio;3611 audio.loop = loop;3612 audio.volume = T2MediaLib.audioVolume;3613 audio.currentTime = startTime;3614 audio.play();3615 return audio;3616 },3617 stopAudio : function() {3618 var audio = T2MediaLib.playingAudio;3619 if (!(audio instanceof Audio)) return null;3620 audio.pause();3621 audio.currentTime = 0;3622 T2MediaLib.playingAudio = null;3623 return audio;3624 },3625 pauseAudio : function() {3626 var audio = T2MediaLib.playingAudio;3627 if (!audio) return null;3628 audio.pause();3629 return audio;3630 },3631 resumeAudio : function() {3632 var audio = T2MediaLib.playingAudio;3633 if (!audio) return null;3634 audio.play();3635 return audio;3636 },3637 setAudioVolume : function(vol) {3638 T2MediaLib.audioVolume = vol;3639 if (T2MediaLib.playingAudio instanceof Audio) {3640 T2MediaLib.playingAudio.volume = vol;3641 }3642 },3643 setAudioTempo : function(tempo) {3644 T2MediaLib.audioTempo = tempo;3645 if (T2MediaLib.playingAudio instanceof Audio) {3646 T2MediaLib.playingAudio.playbackRate = tempo;3647 }3648 },3649 setAudioPosition : function(time) {3650 if (T2MediaLib.playingAudio instanceof Audio) {3651 T2MediaLib.playingAudio.currentTime = time;3652 }3653 },3654 getAudioData : function(idx) {3655 return T2MediaLib.audioDataAry.data[idx];3656 },3657 getAudioCurrentTime : function() {3658 if (!(T2MediaLib.playingAudio instanceof Audio)) return null;3659 return T2MediaLib.playingAudio.currentTime;3660 },3661 getAudioLength : function() {3662 if (!(T2MediaLib.playingAudio instanceof Audio)) return null;3663 return T2MediaLib.playingAudio.duration;3664 }3665};3666// 旧名。そのうち消す3667//T2SoundLib = T2MediaLib;3668// テスト3669//'http://jsrun.it/assets/c/X/4/S/cX4S7.ogg'3670//'http://jsrun.it/assets/5/Z/s/x/5ZsxE.ogg'3671//alert((!window.hasOwnProperty('webkitAudioContext'))+" "+(window.webkitAudioContext.prototype.createGain===undefined));3672//T2MediaLib.init();3673//playSE : function(idx, vol, rate, offset, loop, loopStart, loopEnd) {3674//T2MediaLib.loadSE('test','http://jsrun.it/assets/5/Z/s/x/5ZsxE.ogg');3675//setTimeout(function(){ bgm1 = T2MediaLib.playSE('test', 1.0, 1.0, 0, true, 0, 0); }, 500);3676//setTimeout(function(){ T2MediaLib.stopSE(bgm1); }, 5000);3677/*3678//playSE : function(idx, vol, rate, offset, loop, loopStart, loopEnd) {3679T2MediaLib.loadSE('test','http://jsrun.it/assets/c/X/4/S/cX4S7.ogg');3680setTimeout(function(){ bgm1 = T2MediaLib.playSE('test', 1.0, 1.1, 8, true, 12, 19); }, 500);3681setTimeout(function(){ bgm1.playbackRate.value = 1.2; }, 5000);3682setTimeout(function(){ bgm1.stop(); }, 6000);3683setTimeout(function(){ T2MediaLib.playSE('test'); }, 7000);3684//setTimeout(function(){ T2MediaLib.stopSE(bgm1); }, 5000);3685*/3686/*3687T2MediaLib.loadAudio('test','http://jsrun.it/assets/c/X/4/S/cX4S7.ogg');3688T2MediaLib.loadAudio('test2','http://jsrun.it/assets/q/S/1/C/qS1Ch.ogg');3689setTimeout(function(){ T2MediaLib.playAudio('test'); }, 5000);3690setTimeout(function(){ T2MediaLib.playAudio('test2'); }, 1000);3691setTimeout(function(){ T2MediaLib.playAudio('test', true, 11.5); console.log(T2MediaLib.getAudioCurrentTime()); console.log(T2MediaLib.getAudioLength());}, 1050);3692setTimeout(function(){ T2MediaLib.setAudioTempo(1.5); }, 3000);3693setTimeout(function(){ T2MediaLib.setAudioVolume(0.5); }, 6000);3694setTimeout(function(){ T2MediaLib.setAudioPosition(20); }, 7000);3695setTimeout(function(){ T2MediaLib.stopAudio(); }, 10000);3696*/3697requireSimulator.setName('Tonyu.Iterator');3698define(["Tonyu"], function (T) {3699 function IT(set, arity) {3700 var res={};3701 if (set.tonyuIterator) {3702 return set.tonyuIterator(arity);3703 } else if (set instanceof Array) {3704 res.i=0;3705 if (arity==1) {3706 res.next=function () {3707 if (res.i>=set.length) return false;3708 this[0]=set[res.i];3709 res.i++;3710 return true;3711 };3712 } else {3713 res.next=function () {3714 if (res.i>=set.length) return false;3715 this[0]=res.i;3716 this[1]=set[res.i];3717 res.i++;3718 return true;3719 };3720 }3721 } else if (set instanceof Object){3722 res.i=0;3723 var elems=[];3724 if (arity==1) {3725 for (var k in set) {3726 elems.push(k);3727 }3728 res.next=function () {3729 if (res.i>=elems.length) return false;3730 this[0]=elems[res.i];3731 res.i++;3732 return true;3733 };3734 } else {3735 for (var k in set) {3736 elems.push([k, set[k]]);3737 }3738 res.next=function () {3739 if (res.i>=elems.length) return false;3740 this[0]=elems[res.i][0];3741 this[1]=elems[res.i][1];3742 res.i++;3743 return true;3744 };3745 }3746 } else {3747 console.log(set);3748 throw new Error(set+" is not iterable");3749 }3750 return res;3751 }3752 Tonyu.iterator=IT;3753 return IT;3754});3755requireSimulator.setName('runtime');3756requirejs(["ImageList","T2MediaLib","Tonyu","Tonyu.Iterator"], function () {3757});3758requireSimulator.setName('runScript2');3759requirejs(["FS","compiledTonyuProject","Shell","runtime","WebSite","LSFS","Tonyu"],3760 function (FS, CPTR, sh, rt,WebSite,LSFS,Tonyu) {3761 $(function () {3762 SplashScreen={hide: function () {3763 $("#splash").hide();3764 },show:function(){}};3765 var w=$(window).width();3766 var h=$(window).height();3767 $("body").css({overflow:"hidden", margin:"0px"});3768 var cv=$("<canvas>").attr({width: w-10, height:h-10}).appendTo("body");3769 $(window).resize(onResize);3770 function onResize() {3771 w=$(window).width();3772 h=$(window).height();3773 cv.attr({width: w-10, height: h-10});3774 }3775 var locs=location.href.replace(/\?.*/,"").split(/\//);3776 var prj=locs.pop() || "runscript";3777 var user=locs.pop() || "nobody";3778 var home=FS.get(WebSite.tonyuHome);3779 var ramHome=FS.get("/ram/");3780 FS.mount(ramHome.path(), LSFS.ramDisk() );3781 var curProjectDir=ramHome;3782 var actualFilesDir=home.rel(user+"/"+prj+"/");3783 ramHome.rel("files/").link(actualFilesDir);3784 /*var fo=ScriptTagFS.toObj();3785 for (var fn in fo) {3786 var f=curProjectDir.rel(fn);3787 if (!f.isDir()) {3788 var m=fo[fn];3789 f.text(m.text);3790 delete m.text;3791 if (m.lastUpdate) f.metaInfo(m);3792 }3793 }*/3794 loadFiles(curProjectDir);3795 sh.cd(curProjectDir);3796 WebSite.compiledKernel="js/kernel.js";3797 var curPrj=CPTR("user", "js/concat.js",curProjectDir);3798 start();3799 function start() {3800 Tonyu.currentProject=Tonyu.globals.$currentProject=curPrj;3801 var o=curPrj.getOptions();3802 curPrj.runScriptMode=true;3803 curPrj.run(o.run.bootClass);3804 }3805 });3806});...

Full Screen

Full Screen

dumpScript.js

Source:dumpScript.js Github

copy

Full Screen

1var FS=require ("./SFile");2var js=FS.get("js");3exports.genShim=function (req,res) {4 var reqConf=require ("../reqConf").conf;5 /*js.recursive(function (s) {6 if (s.endsWith(".js")) {7 }8 });*/9 var revPath={};10 var shim={};11 for (var i in reqConf.shim) shim[i]=reqConf.shim[i];12 var com=/^((\/\*([^\/]|[^*]\/|\r|\n)*\*\/)*(\/\/.*\r?\n)*)*/g;13 for (var name in reqConf.paths) {14 //console.log(name);15 var fn=reqConf.paths[name]+".js";16 revPath[fn]=name;17 //console.log(fn);18 var f=js.rel(fn);19 if (!f.exists()) {20 console.log(f+" not exists");21 continue;22 }23 var src=f.text();24 /*var appendConcat=null;25 if (src.match(/\/\/CONCAT:(\[[^\]]*\])/)) {26 appendConcat=eval(RegExp.$1);27 }*/28 src=src.replace(com,"");29 var isModule=src.match(/(\brequirejs\b)|(\brequire\b)|(\bdefine\b)/);30 if (name in shim) {31 if (isModule) {32 console.log(f+"("+name+") has both shim and require/define");33 }34 continue;35 }36 if (isModule) {37 if (src.match(/\[([^\]]*)\]/)) {38 var reqs=RegExp.lastMatch;39 try {40 var reqa=eval(reqs);41 /*if (appendConcat) {42 reqa=reqa.concat(appendConcat);43 console.log("AppendConcat", name, reqa);44 }*/45 shim[name]={deps:reqa, exports:name ,srcHead: src.substring(0,50) };46 } catch(e) {47 console.log("dumpScript:Error eval "+name+" src:\n"+reqs);48 throw e;49 }50 } else {51 console.log(name+" does not have dependencty section / "+f);52 }53 }54 }55 var excludes=/(ace-noconflict)|(^server)/;56 js.recursive(function (s) {57 if (s.relPath(js).match(excludes)) return;58 if (s.endsWith(".js")) {59 var r=s.relPath(js);60 if (!revPath[r] ) console.log(r+" is not scanned");61 }62 });63 var nrq={shim:shim,paths:reqConf.paths};64 if (res) res.send(nrq);65 return nrq;66};67var excludes={timbre:1, ace:1};68exports.concat=function (req,res) {69 var name=req.query.name;70 var names=req.query.names;71 if (name) names=[name];72 var outfile=req.query.outfile;73 var reqConf=exports.genShim();74 var progs=[];75 var visited={};76 for (var i in excludes) visited[i]=true;77 names.forEach(loop);78 function loop(name) {79 if (visited[name]) return;80 var s=reqConf.shim[name];81 visited[name]=true;82 if (s && s.deps) {83 s.deps.forEach(loop);84 }85 progs.push(name);86 }87 var buf="";88 buf+="// Created at "+new Date()+"\n";89 var reqSim=FS.get("js/lib/requireSimulator.js").text().replace(/\r/g,"");90 buf+=reqSim+"\n";91 progs.forEach(function (name) {92 buf+="requireSimulator.setName('"+name+"');\n";93 var fn=reqConf.paths[name];94 if (!fn) console.log("dumpScript.js: file not found for module "+name);95 buf+=js.rel(fn+".js").text().replace(/\r/g,"")+"\n";96 });97 buf+="requireSimulator.setName();\n";98 console.log("Done generate ",names);99 if (outfile) {100 var ouf=FS.get("js/gen/"+outfile+"_concat.js");101 ouf.text(buf);102 var ugf=FS.get("js/gen/"+outfile+"_concat.min.js");103 uglify(ouf, ugf);104 res.send({mesg: "Wrote to "+ouf+" and "+ugf});105 } else {106 res.setHeader("Content-type","text/javascript;charset=utf-8");107 res.send(buf);108 }109};110function uglify(srcF, dstF) {111 try {112 var UglifyJS = require("uglify-js");113 var r=UglifyJS.minify(srcF.path());114 dstF.text(r.code);115 }catch(e) {116 console.log("Uglify fail "+e);117 dstF.text(srcF.text());118 }...

Full Screen

Full Screen

plugins.js

Source:plugins.js Github

copy

Full Screen

1define(["WebSite","root"],function (WebSite,root){2 var plugins={};3 var installed= {4 box2d:{src: "Box2dWeb-2.1.a.3.min.js",detection:/BodyActor/,symbol:"Box2D" },5 timbre: {src:"timbre.js",symbol:"T" },6 gif: {src:"gif-concat.js",detection:/GIFWriter/,symbol:"GIF"},7 Mezonet: {src:"Mezonet.js", symbol: "Mezonet"},8 PicoAudio: {src:"PicoAudio.min.js", symbol:"PicoAudio"},9 JSZip: {src:"jszip.min.js", symbol:"JSZip"},10 // single js is required for runScript1.js11 jquery_ui: {src:"jquery-ui.js", detection:/\$InputBox/,symbol:"$.ui"}12 };13 plugins.installed=installed;14 plugins.detectNeeded=function (src,res) {15 for (var name in installed) {16 var d=installed[name].detection;17 if (d) {18 var r=d.exec(src);19 if (r) res[name]=1;20 }21 }22 return res;23 };24 plugins.loaded=function (name) {25 var i=installed[name];26 if (!i) throw new Error("plugin not found: "+name);27 return hasInGlobal(i.symbol);28 };29 function hasInGlobal(name) {30 // name: dot ok31 var g=window;32 name.split(".").forEach(function (e) {33 if (!g) return;34 g=g[e];35 });36 return g;37 }38 plugins.loadAll=function (names,options) {39 options=convOpt(options);40 var namea=[];41 for (var name in names) {42 if (installed[name] && !plugins.loaded(name)) {43 namea.push(name);44 }45 }46 var i=0;47 console.log("loading plugins",namea);48 setTimeout(loadNext,0);49 function loadNext() {50 if (i>=namea.length) options.onload();51 else plugins.load(namea[i++],loadNext);52 }53 };54 function convOpt(options) {55 if (typeof options=="function") options={onload:options};56 if (!options) options={};57 if (!options.onload) options.onload=function (){};58 return options;59 }60 plugins.load=function (name,options) {61 var i=installed[name];62 if (!i) throw new Error("plugin not found: "+name);63 options=convOpt(options);64 var src=WebSite.pluginTop+"/"+i.src;65 var reqj=root.requirejs;66 /*if (typeof requireSimulator==="undefined") {67 if (typeof requirejs==="function") reqj=requirejs;68 } else {69 if (requireSimulator.real) reqj=requireSimulator.real.requirejs;70 }*/71 if (reqj) {72 if (!src.match(/^https?:/)) src=src.replace(/\.js$/,"");73 console.log("Loading plugin via requirejs",src);74 reqj([src], function (res) {75 if (!window[i.symbol] && res) window[i.symbol]=res;76 options.onload(res);77 });78 } else {79 console.log("Loading plugin via <script>",src);80 var s=document.createElement("script");81 s.src=src;82 s.onload=options.onload;83 document.body.appendChild(s);84 //$("<script>").on("load",options.onload).attr("src",src).appendTo("body");85 }86 //setTimeout(options.onload,500);87 };88 plugins.request=function (name) {89 if (plugins.loaded(name)) return;90 var req=new Error("Plugin "+name+" required");91 req.pluginName=name;92 };93 return plugins;...

Full Screen

Full Screen

permissions.js

Source:permissions.js Github

copy

Full Screen

...44 } = requireOptions(opts);45 if (!service) {46 throw new Error(`The 'service' option is expected to be present`);47 }48 requireSimulator(this);49 return await this.opts.device.getPermission(bundleId, service);50};51/**52 * @typedef {Object} SetPermissionsOptions53 *54 * @property {Object} access - One or more access rules to set.55 * The following keys are supported:56 * - all: Apply the action to all services.57 * - calendar: Allow access to calendar.58 * - contacts-limited: Allow access to basic contact info.59 * - contacts: Allow access to full contact details.60 * - location: Allow access to location services when app is in use.61 * - location-always: Allow access to location services at all times.62 * - photos-add: Allow adding photos to the photo library.63 * - photos: Allow full access to the photo library.64 * - media-library: Allow access to the media library.65 * - microphone: Allow access to audio input.66 * - motion: Allow access to motion and fitness data.67 * - reminders: Allow access to reminders.68 * - siri: Allow use of the app with Siri.69 * The following values are supported:70 * - yes: To grant the permission71 * - no: To revoke the permission72 * - unset: To reset the permission73 * @property {string} bundleId - The bundle identifier of the destination app.74 */75/**76 * Set application permission state on Simulator.77 *78 * @since Xcode SDK 11.479 * @param {SetPermissionsOptions} opts - Permissions options.80 * @throws {Error} If permission setting fails or the device is not a Simulator.81 */82commands.mobileSetPermissions = async function mobileSetPermissions (opts = {}) {83 const {84 access,85 bundleId,86 } = requireOptions(opts);87 if (!_.isPlainObject(access)) {88 throw new Error(`The 'access' option is expected to be a map`);89 }90 requireSimulator(this);91 await this.opts.device.setPermissions(bundleId, access);92};93Object.assign(extensions, commands, helpers);94export { commands, helpers };...

Full Screen

Full Screen

requireSimulator2_head.js

Source:requireSimulator2_head.js Github

copy

Full Screen

1// This is kowareta! because r.js does not generate module name:2// define("FSLib",[], function () { ...3/*4(function (d,f) {5module.exports=f();6})7*/8define([],function () {9 var define,requirejs;10 var R={};11 var REQJS="REQJS_";12 var reqjsSeq=0;13 R.def=function (name, reqs,func) {14 var m=R.getModuleInfo(name);15 if (typeof reqs=="function") {16 func=reqs;17 reqs=R.reqsFromFunc(func);18 R.setReqs( m, reqs);19 m.func=function () {20 var module={exports:{}};21 var res=func(R.doLoad,module,module.exports);22 return res || module.exports;23 };24 } else {25 R.setReqs( m, reqs);26 m.func=function () {27 return func.apply(this, R.getObjs(reqs));28 };29 }30 R.loadIfAvailable(m);31 };32 define=function (name,reqs,func) {33 R.def(name, reqs,func);34 };35 define.amd={};36 requirejs=function (reqs,func) {37 R.def(REQJS+(reqjsSeq++),reqs,func);38 };39 R.setReqs=function (m, reqs) {40 reqs.forEach(function (req) {41 var reqm=R.getModuleInfo(req);42 if (!reqm.loaded) {43 m.reqs[req]=reqm;44 reqm.revReqs[m.name]=m;45 }46 });47 };48 R.getModuleInfo=function (name) {49 var ms=R.modules;50 return ms[name]=ms[name]||{name:name,reqs:{},revReqs:{}};51 };52 R.doLoad=function (name) {53 var m=R.getModuleInfo(name);54 if (m.loaded) return m.obj;55 m.loaded=true;56 var res=m.func();57 if ( res==null && !name.match(/^REQJS_/)) console.log("Warning: No obj for "+name);58 m.obj=res;59 for (var i in m.revReqs) {60 R.notifyLoaded(m.revReqs[i], m.name);61 }62 return res;63 };64 R.notifyLoaded=function (dependingMod, loadedModuleName) {65 // depengindMod depends on loadedModule66 delete dependingMod.reqs[loadedModuleName];67 R.loadIfAvailable(dependingMod);68 };69 R.loadIfAvailable=function (m) {70 for (var i in m.reqs) {71 return;72 }73 R.doLoad(m.name);74 };75 R.getObjs=function (ary) {76 var res=[];77 ary.forEach(function (n) {78 var cur=R.doLoad(n);79 res.push(cur);80 });81 return res;82 };83 R.reqsFromFunc=function (f) {84 var str=f+"";85 var res=[];86 str.replace(/require\s*\(\s*["']([^"']+)["']\s*\)/g,function (m,a) {87 res.push(a);88 });89 return res;90 };91 R.modules={};92 //requireSimulator=R;...

Full Screen

Full Screen

requireSimulator.js

Source:requireSimulator.js Github

copy

Full Screen

1(function () {2 var R={};3 R.def=function (reqs,func,type) {4 var m=R.getModuleInfo(R.curName);5 m.type=type;6 R.setReqs( m, reqs);7 m.func=function () {8 //console.log("reqjs ",m.name);9 return func.apply(this, R.getObjs(reqs));10 };11 R.loadIfAvailable(m);12 };13 define=function () {14 var a=Array.prototype.slice.call(arguments);15 if (typeof a[0]==="string") R.curName=a.shift();16 var reqs=a.shift();17 var func=a.shift();18 R.def(reqs,func,"define");19 };20 define.amd={jQuery:true};21 /*require=*/requirejs=function (reqs,func) {22 R.def(reqs,func,"require");23 };24 R.setReqs=function (m, reqs) {25 reqs.forEach(function (req) {26 var reqm=R.getModuleInfo(req);27 if (!reqm.loaded) {28 m.reqs[req]=reqm;29 reqm.revReqs[m.name]=m;30 }31 });32 };33 R.getModuleInfo=function (name) {34 var ms=R.modules;35 if (!ms[name]) ms[name]={name:name,reqs:{},revReqs:{}};36 return ms[name];37 };38 R.doLoad=function (name) {39 var m=R.getModuleInfo(name);40 //console.log("doLoad ",name, m.loaded, m.func);41 if (m.loaded) return m.obj;42 m.loaded=true;43 var res=null;44 if (m.func) res=m.func();45 else {46 var names=name.split(/\./);47 res=(function () {return this;})();48 names.forEach(function (name) {49 if (res) res=res[name];50 });51 if ( res==null) console.log("Warning: No obj for "+name);52 }53 if ( m.type=="define" && res==null) throw("No obj for "+name);54 m.obj=res;55 for (var i in m.revReqs) {56 R.notifyLoaded(m.revReqs[i], m.name);57 }58 return res;59 };60 R.notifyLoaded=function (revReq, loadedModuleName) {61 delete revReq.reqs[loadedModuleName];62 R.loadIfAvailable(revReq);63 };64 R.loadIfAvailable=function (m) {65 for (var i in m.reqs) {66 return;67 }68 R.doLoad(m.name);69 };70 R.getObjs=function (ary) {71 var res=[];72 ary.forEach(function (n) {73 var cur=R.doLoad(n);74 res.push(cur);75 });76 return res;77 };78 R.modules={};79 R.setName=function (n) {80 if (R.curName) {81 if (!R.getModuleInfo(R.curName).func) {82 R.doLoad(R.curName);83 }84 }85 if (n) {86 R.curName=n;87 }88 };89 requireSimulator=R;90 return R;...

Full Screen

Full Screen

requireSimulator2.js

Source:requireSimulator2.js Github

copy

Full Screen

1(function () {2 var R={};3 var REQJS="REQJS_";4 var reqjsSeq=0;5 R.def=function (name, reqs,func) {6 var m=R.getModuleInfo(name);7 if (typeof reqs=="function") {8 func=reqs;9 reqs=R.reqsFromFunc(func);10 R.setReqs( m, reqs);11 m.func=function () {12 var module={exports:{}};13 var res=func(R.doLoad,module,module.exports);14 return res || module.exports;15 };16 } else { 17 R.setReqs( m, reqs);18 m.func=function () {19 return func.apply(this, R.getObjs(reqs));20 };21 }22 R.loadIfAvailable(m);23 };24 define=function (name,reqs,func) {25 R.def(name, reqs,func);26 };27 requirejs=function (reqs,func) {28 R.def(REQJS+(reqjsSeq++),reqs,func);29 };30 R.setReqs=function (m, reqs) {31 reqs.forEach(function (req) {32 var reqm=R.getModuleInfo(req);33 if (!reqm.loaded) {34 m.reqs[req]=reqm;35 reqm.revReqs[m.name]=m;36 }37 });38 };39 R.getModuleInfo=function (name) {40 var ms=R.modules;41 return ms[name]=ms[name]||{name:name,reqs:{},revReqs:{}};42 };43 R.doLoad=function (name) {44 var m=R.getModuleInfo(name);45 if (m.loaded) return m.obj;46 m.loaded=true;47 var res=m.func();48 if ( res==null && !name.match(/^REQJS_/)) console.log("Warning: No obj for "+name);49 m.obj=res;50 for (var i in m.revReqs) {51 R.notifyLoaded(m.revReqs[i], m.name);52 }53 return res;54 };55 R.notifyLoaded=function (dependingMod, loadedModuleName) {56 // depengindMod depends on loadedModule57 delete dependingMod.reqs[loadedModuleName];58 R.loadIfAvailable(dependingMod);59 };60 R.loadIfAvailable=function (m) {61 for (var i in m.reqs) {62 return;63 }64 R.doLoad(m.name);65 };66 R.getObjs=function (ary) {67 var res=[];68 ary.forEach(function (n) {69 var cur=R.doLoad(n);70 res.push(cur);71 });72 return res;73 };74 R.reqsFromFunc=function (f) {75 var str=f+"";76 var res=[];77 str.replace(/require\s*\(\s*["']([^"']+)["']\s*\)/g,function (m,a) {78 res.push(a); 79 });80 return res;81 };82 R.modules={};83 requireSimulator=R;84 return R;...

Full Screen

Full Screen

moduleSimulator.js

Source:moduleSimulator.js Github

copy

Full Screen

...6 })(module, module.exports, require);`;7 // eslint-disable-next-line no-eval8 eval(wrappedSrc);9}10function requireSimulator(moduleName) {11 console.log(`Require invoked for module: ${moduleName}`);12 const id = requireSimulator.resolve(moduleName);13 if (requireSimulator.cache[id]) {14 return requireSimulator.cache[id].exports;15 }16 const module = {17 exports: {},18 id19 };20 requireSimulator.cache[id] = module;21 loadModule(id, module, requireSimulator);22 return module.exports;23}24requireSimulator.resolve = moduleName => moduleName || '';25requireSimulator.cache = {};26const result = requireSimulator('./test.js');...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var wd = require('wd');2var assert = require('assert');3var path = require('path');4var fs = require('fs');5var xcode = require('appium-xcode');6var simctl = require('node-simctl');7var _ = require('lodash');8var chai = require('chai');9var chaiAsPromised = require('chai-as-promised');10chai.use(chaiAsPromised);11var should = chai.should();12var expect = chai.expect;13var driver = wd.promiseChainRemote('localhost', 4723);14var desired = {15};16describe('Appium XCUITest Driver', function () {17 this.timeout(300000);18 before(function () {19 return driver.init(desired);20 });21 after(function () {22 return driver.quit();23 });24 it('should be able to start a session', function () {25 .sleep(5000)26 .elementByAccessibilityId('ComputeSumButton')27 .click()28 .elementByAccessibilityId('Answer')29 .text()30 .should.become('42');31 });32 it('should be able to start a session and use requireSimulator', function () {33 .requireSimulator()34 .then(function (sim) {35 return simctl.boot(sim.udid)36 .then(function () {37 return simctl.install(sim.udid, app);38 })39 .then(function () {40 return simctl.launch(sim.udid, 'com.example.apple-samplecode.UICatalog');41 })42 .then(function () {43 return simctl.terminate(sim.udid, 'com.example.apple-samplecode.UICatalog');44 })45 .then(function () {46 return simctl.uninstall(sim.udid, 'com.example.apple-samplecode.UICatalog');47 })48 .then(function () {49 return simctl.shutdown(sim.udid);50 });51 });52 });53});

Full Screen

Using AI Code Generation

copy

Full Screen

1const {requireSimulator} = require('appium/node_modules/appium-xcuitest-driver/lib/simulator-management/simulator-xcode-11');2const {SimulatorXcode11} = requireSimulator;3const sim = new SimulatorXcode11();4sim.startSimulator();5sim.getRunningSim();6sim.stopSimulator();7sim.deleteSim();8sim.createSim();9sim.getSim();10sim.getSimLocale();11sim.setSimLocale();12sim.getSimLocation();13sim.setSimLocation();14sim.getSimLogs();15sim.getSimScreenshot();16sim.getSimState();17sim.getSimUdid();18sim.getSimVersion();19sim.installSim();20sim.isSimRunning();21sim.launchSim();22sim.openUrl();23sim.removeSim();24sim.runSimReset();25sim.runSimSecurityDeleteAllContacts();26sim.runSimSecurityDeleteAllPhotos();27sim.runSimSecurityDeleteAllWebCredentials();28sim.runSimSecurityDeleteKeychain();29sim.runSimSecurityDeleteKeychainItem();30sim.runSimSecuritySetKeychain();31sim.runSimSecuritySetKeychainItem();32sim.runSimShutdown();33sim.runSimTerminate();34sim.runSimWdaLaunch();35sim.runSimWdaQuit();36sim.runSimWdaStart();37sim.runSimWdaStop();38sim.simExists();39sim.terminateSim();40sim.uninstallSim();41sim.wdaAgentUrl();42sim.wdaBaseUrl();

Full Screen

Using AI Code Generation

copy

Full Screen

1var wd = require('wd');2var assert = require('assert');3var _ = require('lodash');4var path = require('path');5var fs = require('fs');6var os = require('os');7var rimraf = require('rimraf');8var unzip = require('unzip');9var request = require('request');10var Q = require('q');11var uuid = require('uuid-js');12var xcode = require('appium-xcode');13var simctl = require('node-simctl');14var simulator = require('node-simulator');15var desired = {

Full Screen

Using AI Code Generation

copy

Full Screen

1const requireSimulator = require('appium-xcuitest-driver').requireSimulator;2const sim = requireSimulator();3const simctl = new sim.Simctl();4simctl.getDevices()5 .then((devices) => {6 console.log(devices);7 });8const requireDevice = require('appium-xcuitest-driver').requireDevice;9const sim = requireDevice();10const simctl = new sim.Simctl();11simctl.getDevices()12 .then((devices) => {13 console.log(devices);14 });15const requireUdid = require('appium-xcuitest-driver').requireUdid;16const sim = requireUdid();17const simctl = new sim.Simctl();18simctl.getDevices()19 .then((devices) => {20 console.log(devices);21 });22const requireXcode = require('appium-xcuitest-driver').requireXcode;23const sim = requireXcode();24const simctl = new sim.Simctl();25simctl.getDevices()26 .then((devices) => {27 console.log(devices);28 });29const requireXcodeBuild = require('appium-xcuitest-driver').requireXcodeBuild;30const sim = requireXcodeBuild();31const simctl = new sim.Simctl();32simctl.getDevices()33 .then((devices) => {34 console.log(devices);35 });36const requireIos = require('appium-xcuitest-driver').requireIos;37const sim = requireIos();38const simctl = new sim.Simctl();39simctl.getDevices()40 .then((devices) => {41 console.log(devices);42 });43const requireIosSdk = require('appium-xcuitest-driver').require

Full Screen

Using AI Code Generation

copy

Full Screen

1var wd = require('wd');2var assert = require('assert');3var _ = require('lodash');4var simulator = require('appium-xcuitest-driver').simulator;5var desired = {6};7var driver = wd.promiseChainRemote('localhost', 4723);8 .init(desired)9 .then(function () {10 return simulator.requireSimulator();11 })12 .then(function () {13 return driver.quit();14 })15 .catch(function (err) {16 console.log(err);17 });18appium --allow-insecure chromedriver_autodownload -p 4723 --default-capabilities '{"browserName":"","platformName":"iOS","platformVersion":"10.3","deviceName":"iPhone 7","app":"/Users/username/Desktop/MyApp.app"}' --command-timeout 7200 --session-override

Full Screen

Using AI Code Generation

copy

Full Screen

1const { remote } = require('webdriverio');2const { simctl } = require('node-simctl');3const { XCUITestDriver } = require('appium-xcuitest-driver');4const { IOSPerformanceLog } = require('appium-ios-log');5(async () => {6 const sim = await simctl.createDevice('iPhone 11', 'iPhone 11', 'iOS 13.3');7 const driver = new XCUITestDriver();8 await driver.createSession({

Full Screen

Using AI Code Generation

copy

Full Screen

1const wd = require('wd');2const chai = require('chai');3const chaiAsPromised = require('chai-as-promised');4chai.use(chaiAsPromised);5const expect = chai.expect;6const XCUITestDriver = require('appium-xcuitest-driver');7const XCUITestSimulator = require('appium-xcuitest-simulator');8const XCUITestSimulatorManagement = require('appium-xcuitest-simulator/lib/simulator-management');9const XCUITestSimulatorManagementXcode7 = require('appium-xcuitest-simulator/lib/simulator-management-xcode-7');10const XCUITestSimulatorManagementXcode8 = require('appium-xcuitest-simulator/lib/simulator-management-xcode-8');11const driver = wd.promiseChainRemote('localhost', 4723);12const caps = {13};14const driver = new XCUITestDriver();15const simulator = driver.requireSimulator('iPhone 6', '10.2');16simulator.launch(function(err) {17 if(err) {18 console.log(err);19 }20 simulator.installApp('/Users/username/Desktop/test.app').then(function() {21 console.log('App installed');22 }).catch(function(err) {23 console.log(err);24 });25});

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Appium Xcuitest Driver automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Sign up Free
_

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful