Best JavaScript code snippet using root
emulator.spec.js
Source:emulator.spec.js
1/**2 Licensed to the Apache Software Foundation (ASF) under one3 or more contributor license agreements. See the NOTICE file4 distributed with this work for additional information5 regarding copyright ownership. The ASF licenses this file6 to you under the Apache License, Version 2.0 (the7 "License"); you may not use this file except in compliance8 with the License. You may obtain a copy of the License at9 http://www.apache.org/licenses/LICENSE-2.010 Unless required by applicable law or agreed to in writing,11 software distributed under the License is distributed on an12 "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY13 KIND, either express or implied. See the License for the14 specific language governing permissions and limitations15 under the License.16*/17const fs = require('fs');18const path = require('path');19const rewire = require('rewire');20const shelljs = require('shelljs');21const CordovaError = require('cordova-common').CordovaError;22const check_reqs = require('../../bin/templates/cordova/lib/check_reqs');23const superspawn = require('cordova-common').superspawn;24describe('emulator', () => {25 const EMULATOR_LIST = ['emulator-5555', 'emulator-5556', 'emulator-5557'];26 let emu;27 beforeEach(() => {28 emu = rewire('../../bin/templates/cordova/lib/emulator');29 });30 describe('list_images_using_avdmanager', () => {31 it('should properly parse details of SDK Tools 25.3.1 `avdmanager` output', () => {32 const avdList = fs.readFileSync(path.join('spec', 'fixtures', 'sdk25.3-avdmanager_list_avd.txt'), 'utf-8');33 spyOn(superspawn, 'spawn').and.returnValue(Promise.resolve(avdList));34 return emu.list_images_using_avdmanager().then(list => {35 expect(list).toBeDefined();36 expect(list[0].name).toEqual('nexus5-5.1');37 expect(list[0].target).toEqual('Android 5.1 (API level 22)');38 expect(list[1].device).toEqual('pixel (Google)');39 expect(list[2].abi).toEqual('default/x86_64');40 });41 });42 });43 describe('list_images_using_android', () => {44 it('should invoke `android` with the `list avd` command and _not_ the `list avds` command, as the plural form is not supported in some Android SDK Tools versions', () => {45 spyOn(superspawn, 'spawn').and.returnValue(new Promise(() => {}, () => {}));46 emu.list_images_using_android();47 expect(superspawn.spawn).toHaveBeenCalledWith('android', ['list', 'avd']);48 });49 it('should properly parse details of SDK Tools pre-25.3.1 `android list avd` output', () => {50 const avdList = fs.readFileSync(path.join('spec', 'fixtures', 'sdk25.2-android_list_avd.txt'), 'utf-8');51 spyOn(superspawn, 'spawn').and.returnValue(Promise.resolve(avdList));52 return emu.list_images_using_android().then(list => {53 expect(list).toBeDefined();54 expect(list[0].name).toEqual('QWR');55 expect(list[0].device).toEqual('Nexus 5 (Google)');56 expect(list[0].path).toEqual('/Users/shazron/.android/avd/QWR.avd');57 expect(list[0].target).toEqual('Android 7.1.1 (API level 25)');58 expect(list[0].abi).toEqual('google_apis/x86_64');59 expect(list[0].skin).toEqual('1080x1920');60 });61 });62 });63 describe('list_images', () => {64 beforeEach(() => {65 spyOn(fs, 'realpathSync').and.callFake(cmd => cmd);66 });67 it('should try to parse AVD information using `avdmanager` first', () => {68 spyOn(shelljs, 'which').and.callFake(cmd => cmd === 'avdmanager');69 const avdmanager_spy = spyOn(emu, 'list_images_using_avdmanager').and.returnValue(Promise.resolve([]));70 return emu.list_images().then(() => {71 expect(avdmanager_spy).toHaveBeenCalled();72 });73 });74 it('should delegate to `android` if `avdmanager` cant be found and `android` can', () => {75 spyOn(shelljs, 'which').and.callFake(cmd => cmd !== 'avdmanager');76 const android_spy = spyOn(emu, 'list_images_using_android').and.returnValue(Promise.resolve([]));77 return emu.list_images().then(() => {78 expect(android_spy).toHaveBeenCalled();79 });80 });81 it('should correct api level information and fill in the blanks about api level if exists', () => {82 spyOn(shelljs, 'which').and.callFake(cmd => cmd === 'avdmanager');83 spyOn(emu, 'list_images_using_avdmanager').and.returnValue(Promise.resolve([84 {85 name: 'Pixel_7.0',86 device: 'pixel (Google)',87 path: '/Users/maj/.android/avd/Pixel_7.0.avd',88 abi: 'google_apis/x86_64',89 target: 'Android 7.0 (API level 24)'90 }, {91 name: 'Pixel_8.0',92 device: 'pixel (Google)',93 path: '/Users/maj/.android/avd/Pixel_8.0.avd',94 abi: 'google_apis/x86',95 target: 'Android API 26'96 }97 ]));98 return emu.list_images().then(avds => {99 expect(avds[1].target).toContain('Android 8');100 expect(avds[1].target).toContain('API level 26');101 });102 });103 it('should throw an error if neither `avdmanager` nor `android` are able to be found', () => {104 spyOn(shelljs, 'which').and.returnValue(false);105 return emu.list_images().then(106 () => fail('Unexpectedly resolved'),107 err => {108 expect(err).toBeDefined();109 expect(err.message).toContain('Could not find either `android` or `avdmanager`');110 }111 );112 });113 });114 describe('best_image', () => {115 let target_mock;116 beforeEach(() => {117 spyOn(emu, 'list_images');118 target_mock = spyOn(check_reqs, 'get_target').and.returnValue('android-26');119 });120 it('should return undefined if there are no defined AVDs', () => {121 emu.list_images.and.returnValue(Promise.resolve([]));122 return emu.best_image().then(best_avd => {123 expect(best_avd).toBeUndefined();124 });125 });126 it('should return the first available image if there is no available target information for existing AVDs', () => {127 const fake_avd = { name: 'MyFakeAVD' };128 const second_fake_avd = { name: 'AnotherAVD' };129 emu.list_images.and.returnValue(Promise.resolve([fake_avd, second_fake_avd]));130 return emu.best_image().then(best_avd => {131 expect(best_avd).toBe(fake_avd);132 });133 });134 it('should return the first AVD for the API level that matches the project target', () => {135 target_mock.and.returnValue('android-25');136 const fake_avd = { name: 'MyFakeAVD', target: 'Android 7.0 (API level 24)' };137 const second_fake_avd = { name: 'AnotherAVD', target: 'Android 7.1 (API level 25)' };138 const third_fake_avd = { name: 'AVDThree', target: 'Android 8.0 (API level 26)' };139 emu.list_images.and.returnValue(Promise.resolve([fake_avd, second_fake_avd, third_fake_avd]));140 return emu.best_image().then(best_avd => {141 expect(best_avd).toBe(second_fake_avd);142 });143 });144 it('should return the AVD with API level that is closest to the project target API level, without going over', () => {145 target_mock.and.returnValue('android-26');146 const fake_avd = { name: 'MyFakeAVD', target: 'Android 7.0 (API level 24)' };147 const second_fake_avd = { name: 'AnotherAVD', target: 'Android 7.1 (API level 25)' };148 const third_fake_avd = { name: 'AVDThree', target: 'Android 99.0 (API level 134)' };149 emu.list_images.and.returnValue(Promise.resolve([fake_avd, second_fake_avd, third_fake_avd]));150 return emu.best_image().then(best_avd => {151 expect(best_avd).toBe(second_fake_avd);152 });153 });154 it('should not try to compare API levels when an AVD definition is missing API level info', () => {155 emu.list_images.and.returnValue(Promise.resolve([{156 name: 'Samsung_S8_API_26',157 device: 'Samsung S8+ (User)',158 path: '/Users/daviesd/.android/avd/Samsung_S8_API_26.avd',159 abi: 'google_apis/x86',160 target: 'Android 8.0'161 }]));162 return emu.best_image().then(best_avd => {163 expect(best_avd).toBeDefined();164 });165 });166 });167 describe('list_started', () => {168 it('should call adb devices with the emulators flag', () => {169 const AdbSpy = jasmine.createSpyObj('Adb', ['devices']);170 AdbSpy.devices.and.returnValue(Promise.resolve());171 emu.__set__('Adb', AdbSpy);172 return emu.list_started().then(() => {173 expect(AdbSpy.devices).toHaveBeenCalledWith({ emulators: true });174 });175 });176 });177 describe('get_available_port', () => {178 let emus;179 beforeEach(() => {180 emus = [];181 spyOn(emu, 'list_started').and.returnValue(Promise.resolve(emus));182 });183 it('should find the closest available port below 5584 for the emulator', () => {184 const lowestUsedPort = 5565;185 for (let i = 5584; i >= lowestUsedPort; i--) {186 emus.push(`emulator-${i}`);187 }188 return emu.get_available_port().then(port => {189 expect(port).toBe(lowestUsedPort - 1);190 });191 });192 it('should throw an error if no port is available between 5554 and 5584', () => {193 for (let i = 5584; i >= 5554; i--) {194 emus.push(`emulator-${i}`);195 }196 return emu.get_available_port().then(197 () => fail('Unexpectedly resolved'),198 err => {199 expect(err).toEqual(jasmine.any(CordovaError));200 }201 );202 });203 });204 describe('start', () => {205 const port = 5555;206 let emulator;207 let AdbSpy;208 let checkReqsSpy;209 let childProcessSpy;210 let shellJsSpy;211 beforeEach(() => {212 emulator = {213 name: 'Samsung_S8_API_26',214 device: 'Samsung S8+ (User)',215 path: '/Users/daviesd/.android/avd/Samsung_S8_API_26.avd',216 abi: 'google_apis/x86',217 target: 'Android 8.0'218 };219 AdbSpy = jasmine.createSpyObj('Adb', ['shell']);220 AdbSpy.shell.and.returnValue(Promise.resolve());221 emu.__set__('Adb', AdbSpy);222 checkReqsSpy = jasmine.createSpyObj('create_reqs', ['getAbsoluteAndroidCmd']);223 emu.__set__('check_reqs', checkReqsSpy);224 childProcessSpy = jasmine.createSpyObj('child_process', ['spawn']);225 childProcessSpy.spawn.and.returnValue(jasmine.createSpyObj('spawnFns', ['unref']));226 emu.__set__('child_process', childProcessSpy);227 spyOn(emu, 'get_available_port').and.returnValue(Promise.resolve(port));228 spyOn(emu, 'wait_for_emulator').and.returnValue(Promise.resolve('randomname'));229 spyOn(emu, 'wait_for_boot').and.returnValue(Promise.resolve());230 // Prevent pollution of the test logs231 const proc = emu.__get__('process');232 spyOn(proc.stdout, 'write').and.stub();233 shellJsSpy = jasmine.createSpyObj('shelljs', ['which']);234 shellJsSpy.which.and.returnValue('/dev/android-sdk/tools');235 emu.__set__('shelljs', shellJsSpy);236 });237 it('should find an emulator if an id is not specified', () => {238 spyOn(emu, 'best_image').and.returnValue(Promise.resolve(emulator));239 return emu.start().then(() => {240 // This is the earliest part in the code where we can hook in and check241 // the emulator that has been selected.242 const spawnArgs = childProcessSpy.spawn.calls.argsFor(0);243 expect(spawnArgs[1]).toContain(emulator.name);244 });245 });246 it('should use the specified emulator', () => {247 spyOn(emu, 'best_image');248 return emu.start(emulator.name).then(() => {249 expect(emu.best_image).not.toHaveBeenCalled();250 const spawnArgs = childProcessSpy.spawn.calls.argsFor(0);251 expect(spawnArgs[1]).toContain(emulator.name);252 });253 });254 it('should throw an error if no emulator is specified and no default is found', () => {255 spyOn(emu, 'best_image').and.returnValue(Promise.resolve());256 return emu.start().then(257 () => fail('Unexpectedly resolved'),258 err => {259 expect(err).toEqual(jasmine.any(CordovaError));260 }261 );262 });263 it('should unlock the screen after the emulator has booted', () => {264 emu.wait_for_emulator.and.returnValue(Promise.resolve(emulator.name));265 emu.wait_for_boot.and.returnValue(Promise.resolve(true));266 return emu.start(emulator.name).then(() => {267 expect(emu.wait_for_emulator).toHaveBeenCalledBefore(AdbSpy.shell);268 expect(emu.wait_for_boot).toHaveBeenCalledBefore(AdbSpy.shell);269 expect(AdbSpy.shell).toHaveBeenCalledWith(emulator.name, 'input keyevent 82');270 });271 });272 it('should resolve with the emulator id after the emulator has started', () => {273 emu.wait_for_emulator.and.returnValue(Promise.resolve(emulator.name));274 emu.wait_for_boot.and.returnValue(Promise.resolve(true));275 return emu.start(emulator.name).then(emulatorId => {276 expect(emulatorId).toBe(emulator.name);277 });278 });279 it('should resolve with null if starting the emulator times out', () => {280 emu.wait_for_emulator.and.returnValue(Promise.resolve(emulator.name));281 emu.wait_for_boot.and.returnValue(Promise.resolve(false));282 return emu.start(emulator.name).then(emulatorId => {283 expect(emulatorId).toBe(null);284 });285 });286 });287 describe('wait_for_emulator', () => {288 const port = 5656;289 const expectedEmulatorId = `emulator-${port}`;290 let AdbSpy;291 beforeEach(() => {292 AdbSpy = jasmine.createSpyObj('Adb', ['shell']);293 AdbSpy.shell.and.returnValue(Promise.resolve());294 emu.__set__('Adb', AdbSpy);295 spyOn(emu, 'wait_for_emulator').and.callThrough();296 });297 it('should resolve with the emulator id if the emulator has completed boot', () => {298 AdbSpy.shell.and.callFake((emulatorId, shellArgs) => {299 expect(emulatorId).toBe(expectedEmulatorId);300 expect(shellArgs).toContain('getprop dev.bootcomplete');301 return Promise.resolve('1'); // 1 means boot is complete302 });303 return emu.wait_for_emulator(port).then(emulatorId => {304 expect(emulatorId).toBe(expectedEmulatorId);305 });306 });307 it('should call itself again if the emulator is not ready', () => {308 AdbSpy.shell.and.returnValues(309 Promise.resolve('0'),310 Promise.resolve('0'),311 Promise.resolve('1')312 );313 return emu.wait_for_emulator(port).then(() => {314 expect(emu.wait_for_emulator).toHaveBeenCalledTimes(3);315 });316 });317 it('should call itself again if shell fails for a known reason', () => {318 AdbSpy.shell.and.returnValues(319 Promise.reject({ message: 'device not found' }),320 Promise.reject({ message: 'device offline' }),321 Promise.reject({ message: 'device still connecting' }),322 Promise.resolve('1')323 );324 return emu.wait_for_emulator(port).then(() => {325 expect(emu.wait_for_emulator).toHaveBeenCalledTimes(4);326 });327 });328 it('should throw an error if shell fails for an unknown reason', () => {329 const errorMessage = { message: 'Some unknown error' };330 AdbSpy.shell.and.returnValue(Promise.reject(errorMessage));331 return emu.wait_for_emulator(port).then(332 () => fail('Unexpectedly resolved'),333 err => {334 expect(err).toBe(errorMessage);335 }336 );337 });338 });339 describe('wait_for_boot', () => {340 const port = 5656;341 const emulatorId = `emulator-${port}`;342 const psOutput = `343 root 1 0 8504 1512 SyS_epoll_ 00000000 S /init344 u0_a1 2044 1350 1423452 47256 SyS_epoll_ 00000000 S android.process.acore345 u0_a51 2963 1350 1417724 37492 SyS_epoll_ 00000000 S com.google.process.gapps346 `;347 let AdbSpy;348 beforeEach(() => {349 // If we use Jasmine's fake clock, we need to re-require the target module,350 // or else it will not work.351 jasmine.clock().install();352 emu = rewire('../../bin/templates/cordova/lib/emulator');353 AdbSpy = jasmine.createSpyObj('Adb', ['shell']);354 emu.__set__('Adb', AdbSpy);355 spyOn(emu, 'wait_for_boot').and.callThrough();356 // Stop the logs from being polluted357 const proc = emu.__get__('process');358 spyOn(proc.stdout, 'write').and.stub();359 });360 afterEach(() => {361 jasmine.clock().uninstall();362 });363 it('should resolve with true if the system has booted', () => {364 AdbSpy.shell.and.callFake((emuId, shellArgs) => {365 expect(emuId).toBe(emulatorId);366 expect(shellArgs).toContain('ps');367 return Promise.resolve(psOutput);368 });369 return emu.wait_for_boot(emulatorId).then(isReady => {370 expect(isReady).toBe(true);371 });372 });373 it('should should check boot status at regular intervals until ready', () => {374 const retryInterval = emu.__get__('CHECK_BOOTED_INTERVAL');375 const RETRIES = 10;376 let shellPromise = Promise.resolve('');377 AdbSpy.shell.and.returnValue(shellPromise);378 const waitPromise = emu.wait_for_boot(emulatorId);379 let attempts = 0;380 function tickTimer () {381 shellPromise.then(() => {382 if (attempts + 1 === RETRIES) {383 AdbSpy.shell.and.returnValue(Promise.resolve(psOutput));384 jasmine.clock().tick(retryInterval);385 } else {386 attempts++;387 shellPromise = Promise.resolve('');388 AdbSpy.shell.and.returnValue(shellPromise);389 jasmine.clock().tick(retryInterval);390 tickTimer();391 }392 });393 }394 tickTimer();395 // After all the retries and eventual success, this is called396 return waitPromise.then(isReady => {397 expect(isReady).toBe(true);398 expect(emu.wait_for_boot).toHaveBeenCalledTimes(RETRIES + 1);399 });400 });401 it('should should check boot status at regular intervals until timeout', () => {402 const retryInterval = emu.__get__('CHECK_BOOTED_INTERVAL');403 const TIMEOUT = 9000;404 const expectedRetries = Math.floor(TIMEOUT / retryInterval);405 let shellPromise = Promise.resolve('');406 AdbSpy.shell.and.returnValue(shellPromise);407 const waitPromise = emu.wait_for_boot(emulatorId, TIMEOUT);408 let attempts = 0;409 function tickTimer () {410 shellPromise.then(() => {411 attempts++;412 shellPromise = Promise.resolve('');413 AdbSpy.shell.and.returnValue(shellPromise);414 jasmine.clock().tick(retryInterval);415 if (attempts < expectedRetries) {416 tickTimer();417 }418 });419 }420 tickTimer();421 // After all the retries and eventual success, this is called422 return waitPromise.then(isReady => {423 expect(isReady).toBe(false);424 expect(emu.wait_for_boot).toHaveBeenCalledTimes(expectedRetries + 1);425 });426 });427 });428 describe('resolveTarget', () => {429 const arch = 'arm7-test';430 beforeEach(() => {431 const buildSpy = jasmine.createSpyObj('build', ['detectArchitecture']);432 buildSpy.detectArchitecture.and.returnValue(Promise.resolve(arch));433 emu.__set__('build', buildSpy);434 spyOn(emu, 'list_started').and.returnValue(Promise.resolve(EMULATOR_LIST));435 });436 it('should throw an error if there are no running emulators', () => {437 emu.list_started.and.returnValue(Promise.resolve([]));438 return emu.resolveTarget().then(439 () => fail('Unexpectedly resolved'),440 err => {441 expect(err).toEqual(jasmine.any(CordovaError));442 }443 );444 });445 it('should throw an error if the requested emulator is not running', () => {446 const targetEmulator = 'unstarted-emu';447 return emu.resolveTarget(targetEmulator).then(448 () => fail('Unexpectedly resolved'),449 err => {450 expect(err.message).toContain(targetEmulator);451 }452 );453 });454 it('should return info on the first running emulator if none is specified', () => {455 return emu.resolveTarget().then(emulatorInfo => {456 expect(emulatorInfo.target).toBe(EMULATOR_LIST[0]);457 });458 });459 it('should return the emulator info', () => {460 return emu.resolveTarget(EMULATOR_LIST[1]).then(emulatorInfo => {461 expect(emulatorInfo).toEqual({ target: EMULATOR_LIST[1], arch, isEmulator: true });462 });463 });464 });465 describe('install', () => {466 let AndroidManifestSpy;467 let AndroidManifestFns;468 let AndroidManifestGetActivitySpy;469 let AdbSpy;470 let buildSpy;471 let childProcessSpy;472 let target;473 beforeEach(() => {474 target = { target: EMULATOR_LIST[1], arch: 'arm7', isEmulator: true };475 buildSpy = jasmine.createSpyObj('build', ['findBestApkForArchitecture']);476 emu.__set__('build', buildSpy);477 AndroidManifestFns = jasmine.createSpyObj('AndroidManifestFns', ['getPackageId', 'getActivity']);478 AndroidManifestGetActivitySpy = jasmine.createSpyObj('getActivity', ['getName']);479 AndroidManifestFns.getActivity.and.returnValue(AndroidManifestGetActivitySpy);480 AndroidManifestSpy = jasmine.createSpy('AndroidManifest').and.returnValue(AndroidManifestFns);481 emu.__set__('AndroidManifest', AndroidManifestSpy);482 AdbSpy = jasmine.createSpyObj('Adb', ['shell', 'start', 'uninstall']);483 AdbSpy.shell.and.returnValue(Promise.resolve());484 AdbSpy.start.and.returnValue(Promise.resolve());485 AdbSpy.uninstall.and.returnValue(Promise.resolve());486 emu.__set__('Adb', AdbSpy);487 childProcessSpy = jasmine.createSpyObj('child_process', ['exec']);488 childProcessSpy.exec.and.callFake((cmd, opts, callback) => callback());489 emu.__set__('child_process', childProcessSpy);490 });491 it('should get the full target object if only id is specified', () => {492 const targetId = target.target;493 spyOn(emu, 'resolveTarget').and.returnValue(Promise.resolve(target));494 return emu.install(targetId, {}).then(() => {495 expect(emu.resolveTarget).toHaveBeenCalledWith(targetId);496 });497 });498 it('should install to the passed target', () => {499 return emu.install(target, {}).then(() => {500 const execCmd = childProcessSpy.exec.calls.argsFor(0)[0];501 expect(execCmd).toContain(`-s ${target.target} install`);502 });503 });504 it('should install the correct apk based on the architecture and build results', () => {505 const buildResults = {506 apkPaths: 'path/to/apks',507 buildType: 'debug',508 buildMethod: 'foo'509 };510 const apkPath = 'my/apk/path/app.apk';511 buildSpy.findBestApkForArchitecture.and.returnValue(apkPath);512 return emu.install(target, buildResults).then(() => {513 expect(buildSpy.findBestApkForArchitecture).toHaveBeenCalledWith(buildResults, target.arch);514 const execCmd = childProcessSpy.exec.calls.argsFor(0)[0];515 expect(execCmd).toMatch(new RegExp(`install.*${apkPath}`));516 });517 });518 it('should uninstall and reinstall app if failure is due to different certificates', () => {519 let execAlreadyCalled;520 childProcessSpy.exec.and.callFake((cmd, opts, callback) => {521 if (!execAlreadyCalled) {522 execAlreadyCalled = true;523 callback(null, 'Failure: INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES');524 } else {525 callback();526 }527 });528 return emu.install(target, {}).then(() => {529 expect(childProcessSpy.exec).toHaveBeenCalledTimes(2);530 expect(AdbSpy.uninstall).toHaveBeenCalled();531 });532 });533 it('should throw any error not caused by different certificates', () => {534 const errorMsg = 'Failure: Failed to install';535 childProcessSpy.exec.and.callFake((cmd, opts, callback) => {536 callback(null, errorMsg);537 });538 return emu.install(target, {}).then(539 () => fail('Unexpectedly resolved'),540 err => {541 expect(err).toEqual(jasmine.any(CordovaError));542 expect(err.message).toContain(errorMsg);543 }544 );545 });546 it('should unlock the screen on device', () => {547 return emu.install(target, {}).then(() => {548 expect(AdbSpy.shell).toHaveBeenCalledWith(target.target, 'input keyevent 82');549 });550 });551 it('should start the newly installed app on the device', () => {552 const packageId = 'unittestapp';553 const activityName = 'TestActivity';554 AndroidManifestFns.getPackageId.and.returnValue(packageId);555 AndroidManifestGetActivitySpy.getName.and.returnValue(activityName);556 return emu.install(target, {}).then(() => {557 expect(AdbSpy.start).toHaveBeenCalledWith(target.target, `${packageId}/.${activityName}`);558 });559 });560 });...
bse.js
Source:bse.js
1/*2Library homepage: https://github.com/Metafalica/background-size-emu3This library is result of my intellectual work.4I (the author, named Konstantin Izofatov, living in Russia, metafalica@gmx.com) grant you (the user) permissions5to use BgSzEmu.prototype library in any kind of projects (free, paid, etc) and modify it in any way.6However, it's forbidden to sell this library alone (as it is). 7 8This library provided "AS IS". I am not responsible for any damages that you can receive from using it.9Use it on your own risk.10 11This notice should not be removed.12*/13(function ()14{15 function BgSzEmu()16 {17 BgSzEmu.prototype.imageSizeCalculationModeIsBugged = true;18 BgSzEmu.prototype.elemsOnPrevCheck = null;19 //that gif from background-size-polyfill is sure shorter... but meh... it's not mine :P20 BgSzEmu.prototype.transparentSinglePixel = "url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAABGdBTUEAALGPC/xhBQAAAAlwSFlzAAAOwwAADsMBx2+oZAAAABh0RVh0U29mdHdhcmUAcGFpbnQubmV0IDQuMC4zjOaXUAAAAA1JREFUGFdjYGBgYAAAAAUAAYoz4wAAAAAASUVORK5CYII=)";21 }22 BgSzEmu.prototype.scanElems = function ()23 {24 if (!BgSzEmu.prototype.IsIE() || !BgSzEmu.prototype.IsBadIE())25 return;26 if (document.body)27 {28 var curr_elems = new Array();29 BgSzEmu.prototype.getElemsIn(null, curr_elems);30 if (!BgSzEmu.prototype.elemsOnPrevCheck)31 {32 BgSzEmu.prototype.elemsOnPrevCheck = curr_elems.slice(0);33 BgSzEmu.prototype.activateBgSzFixer();34 }35 else36 {37 for (var i = 0; i < curr_elems.length; i++)38 if (BgSzEmu.prototype.isObjectInArray(curr_elems[i], BgSzEmu.prototype.elemsOnPrevCheck))39 {40 if (!curr_elems[i].junkData)41 continue;42 var available_size = BgSzEmu.prototype.getAvailableAreaSizeIn(curr_elems[i], BgSzEmu.prototype.imageSizeCalculationModeIsBugged);43 if (curr_elems[i].junkData.lastSize && (curr_elems[i].junkData.lastSize.width != available_size.width || curr_elems[i].junkData.lastSize.height != available_size.height))44 BgSzEmu.prototype.fixBgFor(curr_elems[i]);45 }46 else47 {48 var curr_bg_img = curr_elems[i].style.backgroundImage || curr_elems[i].style.getAttribute("background-image");49 if (curr_bg_img && !curr_elems[i].junkData)50 BgSzEmu.prototype.fixBgFor(curr_elems[i]);51 }52 BgSzEmu.prototype.elemsOnPrevCheck = curr_elems.slice(0);53 }54 }55 setTimeout(BgSzEmu.prototype.scanElems, 500);56 };57 BgSzEmu.prototype.activateBgSzFixer = function ()58 {59 if (!BgSzEmu.prototype.IsIE() || !BgSzEmu.prototype.IsBadIE())60 return;61 BgSzEmu.prototype.fixBgsRecursiveIn(null);62 window.onresize = BgSzEmu.prototype.handleResize;63 };64 BgSzEmu.prototype.fixBgsRecursiveIn = function (start_elem)65 {66 var curr_elem = start_elem ? start_elem : document.body;67 var bg_sz = curr_elem.style.backgroundSize || curr_elem.style.getAttribute("background-size");68 if (bg_sz)69 BgSzEmu.prototype.fixBgFor(curr_elem);70 for (var i = 0; i < curr_elem.children.length; i++)71 BgSzEmu.prototype.fixBgsRecursiveIn(curr_elem.children[i]);72 };73 BgSzEmu.prototype.handleResize = function ()74 {75 BgSzEmu.prototype.fixBgsRecursiveIn(null);76 };77 BgSzEmu.prototype.handlePropertyChange = function ()78 {79 var evt = window.event;80 var elem = evt.target || evt.srcElement;81 if (evt.propertyName == "onpropertychange" || !elem)82 return;83 if (evt.propertyName == "style.backgroundImage")84 {85 var bg_img = elem.style.backgroundImage || elem.style.getAttribute("background-image");86 if (BgSzEmu.prototype.stringContains(bg_img, BgSzEmu.prototype.transparentSinglePixel))87 return;88 else89 BgSzEmu.prototype.replaceBgImgFor(elem);90 }91 else if (BgSzEmu.prototype.startsWith(evt.propertyName, "style.background"))92 BgSzEmu.prototype.replaceBgImgFor(elem);93 };94 BgSzEmu.prototype.replaceBgImgFor = function (elem)95 {96 if (!BgSzEmu.prototype.elemCanHaveDivAsChildren(elem)) //can't deal with tags that do not support children97 return;98 99 var e_avl_sz = BgSzEmu.prototype.getAvailableAreaSizeIn(elem, BgSzEmu.prototype.imageSizeCalculationModeIsBugged)100 if (e_avl_sz.width == 0 || e_avl_sz.height == 0)101 return; 102 var prop_change_removed = false;103 if (elem.onpropertychange)104 {105 elem.onpropertychange = null;106 prop_change_removed = true;107 }108 var prev_backgroundImage = elem.style.backgroundImage || elem.style.getAttribute("background-image") || elem.background || elem.getAttribute("background");109 //var curr_backgroundSize = elem.style.backgroundSize || elem.style.getAttribute("background-size");110 if (BgSzEmu.prototype.stringContains(prev_backgroundImage, BgSzEmu.prototype.transparentSinglePixel))111 {112 BgSzEmu.prototype.fixBgFor(elem);113 if (prop_change_removed)114 elem.onpropertychange = BgSzEmu.prototype.handlePropertyChange;115 return;116 }117 if (!prev_backgroundImage)118 {119 if (elem.junkData)120 {121 elem.removeChild(elem.junkData.inner_div);122 elem.style.position = elem.junkData.orig_pos;123 elem.style.zIndex = elem.junkData.orig_zInd;124 elem.junkData = null;125 }126 if (prop_change_removed)127 elem.onpropertychange = BgSzEmu.prototype.handlePropertyChange;128 return;129 }130 BgSzEmu.prototype.getImgNaturalSizeAndPassToCallback(elem, prev_backgroundImage, BgSzEmu.prototype.continueBgReplaceFor);131 };132 BgSzEmu.prototype.continueBgReplaceFor = function (elem, prev_backgroundImage, img_natural_size)133 {134 var prev_zIndex = elem.style.zIndex;135 var prev_position = elem.style.position;136 if (img_natural_size.width == 0 && img_natural_size.height == 0) //bad img url?137 {138 if (prop_change_removed)139 elem.onpropertychange = BgSzEmu.prototype.handlePropertyChange;140 return;141 }142 elem.style.backgroundImage = BgSzEmu.prototype.transparentSinglePixel;143 if ("background" in elem)144 elem.background = BgSzEmu.prototype.transparentSinglePixel;145 if (!elem.style.position || elem.style.position == "static")146 elem.style.position = "relative";147 if (!elem.style.zIndex || elem.style.zIndex == "auto")148 elem.style.zIndex = 0;149 var div = document.createElement("div");150 var img = document.createElement("img");151 div.style.margin = 0;152 div.style.top = "0px";153 div.style.left = "0px";154 div.style.width = "100%";155 div.style.height = "100%";156 div.style.overflow = "hidden";157 //div.style.border = "dashed";158 //img.style.border = "double";159 div.style.zIndex = img.style.zIndex = -1;160 div.style.display = img.style.display = "block";161 div.style.position = img.style.position = "absolute";162 div.style.visibility = img.style.visibility = "inherit";163 img.alt = "";164 img.src = BgSzEmu.prototype.getPurePathFrom(prev_backgroundImage);165 if (elem.junkData)166 {167 elem.removeChild(elem.junkData.inner_div);168 elem.junkData = null;169 }170 var junkData = { orig_bgImg: prev_backgroundImage, orig_pos: prev_position, orig_zInd: prev_zIndex, inner_div: div, inner_img: img, inner_img_nat_size: img_natural_size };171 elem.junkData = junkData;172 div.appendChild(img);173 if (elem.firstChild)174 elem.insertBefore(div, elem.firstChild);175 else176 elem.appendChild(div);177 BgSzEmu.prototype.fixBgFor(elem);178 elem.onpropertychange = BgSzEmu.prototype.handlePropertyChange;179 };180 BgSzEmu.prototype.getImgNaturalSizeAndPassToCallback = function (elem, img_path, callback)181 {182 var pure_path = BgSzEmu.prototype.getPurePathFrom(img_path);183 var img = new Image();184 img.onload = function ()185 {186 var sz = { width: this.width, height: this.height };187 callback(elem, img_path, sz);188 };189 img.src = pure_path;190 };191 BgSzEmu.prototype.getAvailableAreaSizeIn = function (elem, get_elem_size_instead_of_inner_div)192 {193 var sz = null;194 if (get_elem_size_instead_of_inner_div || !elem.junkData)195 sz = { width: elem.clientWidth || elem.offsetWidth/* || elem.scrollWidth*/, height: elem.clientHeight || elem.offsetHeight/* || elem.scrollHeight*/ };196 else if (elem.junkData)197 sz = { width: elem.junkData.inner_div.offsetWidth, height: elem.junkData.inner_div.offsetHeight };198 return sz;199 };200 BgSzEmu.prototype.fixBgFor = function (elem)201 {202 var junkData = elem.junkData;203 var bg_sz = elem.style.backgroundSize || elem.style.getAttribute("background-size");204 if (junkData)205 {206 var available_size = BgSzEmu.prototype.getAvailableAreaSizeIn(elem, BgSzEmu.prototype.imageSizeCalculationModeIsBugged);207 var div_width = available_size.width;208 var div_height = available_size.height;209 var divRatio = div_width / div_height;210 elem.junkData.lastSize = available_size;211 if (BgSzEmu.prototype.imageSizeCalculationModeIsBugged)212 {213 junkData.inner_div.style.width = div_width + "px";214 junkData.inner_div.style.height = div_height + "px";215 }216 var img_nat_width = junkData.inner_img_nat_size.width;217 var img_nat_height = junkData.inner_img_nat_size.height;218 var img_curr_width = junkData.inner_img.width || junkData.inner_img.style.width;219 var img_curr_height = junkData.inner_img.height || junkData.inner_img.style.height;220 var imgRatio = (img_curr_width / img_curr_height) || (img_nat_width / img_nat_height);221 var new_img_top = "0px";222 var new_img_left = "0px";223 var new_img_width;224 var new_img_height;225 var elem_bg_pos = BgSzEmu.prototype.getElemBgPos(elem);226 if (bg_sz == "cover" || bg_sz == "contain")227 {228 if ((bg_sz == "cover" && divRatio > imgRatio) || (bg_sz == "contain" && imgRatio > divRatio))229 {230 new_img_width = div_width;231 new_img_height = (new_img_width * img_nat_height) / img_nat_width;232 if (elem_bg_pos.v_pos.is_percents)233 new_img_top = Math.floor((div_height - div_width / imgRatio) * elem_bg_pos.v_pos.value) + "px";234 }235 else236 {237 new_img_height = div_height;238 new_img_width = (img_nat_width * new_img_height) / img_nat_height;239 if (elem_bg_pos.h_pos.is_percents)240 new_img_left = Math.floor((div_width - div_height * imgRatio) * elem_bg_pos.h_pos.value) + "px";241 }242 //var img_width_diff = Math.abs(div_width - new_img_width);243 //var img_height_diff = Math.abs(div_height - new_img_height);244 //var pos_fixer = (bg_sz == "cover" ? -1 : 1);245 elem.junkData.inner_img.width = new_img_width;246 elem.junkData.inner_img.height = new_img_height;247 //elem.junkData.inner_img.style.left = (pos_fixer * (0 + (img_width_diff / 2))) + "px";248 //elem.junkData.inner_img.style.top = (pos_fixer * (0 + (img_height_diff / 2))) + "px";249 elem.junkData.inner_img.style.left = elem_bg_pos.h_pos.is_percents ? new_img_left : elem_bg_pos.h_pos.value;250 elem.junkData.inner_img.style.top = elem_bg_pos.v_pos.is_percents ? new_img_top : elem_bg_pos.v_pos.value;251 }252 else253 {254 var splitted_size = bg_sz.split(" ");255 var t_width = splitted_size[0];256 var t_height = splitted_size[1];257 if (t_width.toLowerCase() == "auto" && t_height.toLowerCase() == "auto")258 {259 t_width = img_nat_width;260 t_height = img_nat_height;261 }262 else if (t_width.toLowerCase() == "auto")263 {264 elem.junkData.inner_img.style.height = t_height;265 var just_set_height = elem.junkData.inner_img.clientHeight || elem.junkData.inner_img.offsetHeight/* || elem.junkData.inner_img.scrollHeight*/;266 var width_to_set = (img_nat_width * just_set_height) / img_nat_height;267 if (!width_to_set || width_to_set < 1)268 width_to_set = 1;269 elem.junkData.inner_img.width = width_to_set;270 }271 else if (t_height.toLowerCase() == "auto")272 {273 elem.junkData.inner_img.style.width = t_width;274 var just_set_width = elem.junkData.inner_img.clientWidth || elem.junkData.inner_img.offsetWidth/* || elem.junkData.inner_img.scrollWidth*/;275 var height_to_set = (just_set_width * img_nat_height) / img_nat_width;276 if (!height_to_set || height_to_set < 1)277 height_to_set = 1;278 elem.junkData.inner_img.height = height_to_set;279 }280 else281 {282 elem.junkData.inner_img.style.width = t_width;283 elem.junkData.inner_img.style.height = t_height;284 }285 elem.junkData.inner_img.style.left = elem_bg_pos.h_pos.is_percents ? Math.floor((div_width - elem.junkData.inner_img.width) * elem_bg_pos.h_pos.value) + "px" : elem_bg_pos.h_pos.value;286 elem.junkData.inner_img.style.top = elem_bg_pos.v_pos.is_percents ? Math.floor((div_height - elem.junkData.inner_img.height) * elem_bg_pos.v_pos.value) + "px" : elem_bg_pos.v_pos.value;287 }288 }289 else if (bg_sz)290 BgSzEmu.prototype.replaceBgImgFor(elem);291 };292 BgSzEmu.prototype.parseBgPosVal = function (word)293 {294 var map = new Array();295 map["left"] = "0.0";296 map["center"] = "0.5";297 map["right"] = "1.0";298 map["top"] = "0.0";299 map["bottom"] = "1.0";300 if (word in map)301 return { value: map[word], is_percents: true };302 else if (BgSzEmu.prototype.endsWith(word, "%"))303 return { value: (word.substr(0, word.length - 1) / 100), is_percents: true };304 return { value: word, is_percents: false };305 };306 //common functions307 BgSzEmu.prototype.IsIE = function ()308 {309 return navigator.userAgent.indexOf('MSIE') !== -1 || navigator.appVersion.indexOf('Trident/') > 0;310 };311 BgSzEmu.prototype.IsBadIE = function ()312 {313 return "attachEvent" in window && !("addEventListener" in window); //detects ie < 9 and ie9 in quirks mode314 };315 BgSzEmu.prototype.getElemsIn = function (start_elem, curr_elems)316 {317 var curr_elem = start_elem ? start_elem : document.body;318 for (var i = 0; i < curr_elem.children.length; i++)319 {320 curr_elems.push(curr_elem.children[i]);321 BgSzEmu.prototype.getElemsIn(curr_elem.children[i], curr_elems);322 }323 };324 BgSzEmu.prototype.getPurePathFrom = function (str_path)325 {326 var final_str = str_path;327 if (final_str.substring(0, ("url(").length) == "url(")328 {329 final_str = final_str.substr(4);330 if (final_str.lastIndexOf(")") == final_str.length - 1)331 final_str = final_str.substr(0, final_str.length - 1);332 }333 return final_str;334 };335 BgSzEmu.prototype.getElemBgPos = function (elem)336 {337 var bg_pos = elem.style.backgroundPosition || elem.style.getAttribute("background-position");338 if (bg_pos)339 {340 var splitted_pos = bg_pos.split(" ");341 var h_pos_ = (splitted_pos[0] ? BgSzEmu.prototype.parseBgPosVal(splitted_pos[0]) : "0%");342 var v_pos_ = (splitted_pos[1] ? BgSzEmu.prototype.parseBgPosVal(splitted_pos[1]) : "0%");343 return { h_pos: h_pos_, v_pos: v_pos_ };344 }345 else346 return { h_pos: { value: "0", is_percents: true }, v_pos: { value: "0", is_percents: true} };347 };348 BgSzEmu.prototype.stringContains = function (str, suffix)349 {350 if (!str)351 return false;352 return str.indexOf(suffix) > -1;353 };354 BgSzEmu.prototype.startsWith = function (str, suffix)355 {356 if (!str)357 return false;358 return str.substring(0, suffix.length) === suffix;359 };360 BgSzEmu.prototype.endsWith = function (str, suffix)361 {362 if (!str)363 return false;364 return str.indexOf(suffix, str.length - suffix.length) >= 0;365 };366 BgSzEmu.prototype.isObjectInArray = function (obj, arr)367 {368 for (var i = 0; i < arr.length; i++)369 if (arr[i] == obj)370 return true;371 return false;372 };373 BgSzEmu.prototype.elemCanHaveDivAsChildren = function (elem)374 {375 if (elem.tagName.toLowerCase() == "tr") //hacky avoid of elemens that will become bugged after adding div376 return false;377 if (!BgSzEmu.prototype.imageSizeCalculationModeIsBugged && elem.tagName.toLowerCase() == "table") //not supported in right mode.378 return false;379 var div = document.createElement("div");380 div.style.display = "none";381 var check_result = true;382 try { elem.appendChild(div); }383 catch (exc) { check_result = false; }384 finally385 {386 if (BgSzEmu.prototype.isObjectInArray(div, elem.children))387 elem.removeChild(div);388 }389 return check_result;390 };391 //common functions end392 var bg_sz_emu = new BgSzEmu();393 bg_sz_emu.scanElems();...
emularity.js
Source:emularity.js
1var emuRunner = null;2var emuConfig = null;3var machineConfig = null;4var machineId = "emularity";5function getUrlVars() {6 var vars = {};7 var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function (m, key, value) {8 vars[key] = value;9 });10 return vars;11}12function processMachineJson(data) {13 var machineList = data.machines;14 machineId = getUrlVars()["machine"];15 for (i = 0; i < machineList.length; i++) {16 var machine = machineList[i];17 if (machine.id == machineId) {18 processMachineConfig(machine);19 }20 }21}22function runDoxbox() {23 console.log("running dosbox");24 var emuArguments = [25 DosBoxLoader.emulatorJS(emuConfig.emulatorJS),26 DosBoxLoader.nativeResolution(emuConfig.nativeResolution.width, emuConfig.nativeResolution.height),27 DosBoxLoader.locateAdditionalEmulatorJS(function (filename) {28 if (emuConfig.fileLocations[filename]) {29 return emuConfig.fileLocations[filename]30 } else {31 return filename;32 }33 }),34 DosBoxLoader.startExe(machineConfig.startExe),35 DosBoxLoader.fileSystemKey(machineId)36 ]37 var fileParams = buildFileLoadParameters(DosBoxLoader);38 emuArguments = emuArguments.concat(fileParams);39 var emulator = new Emulator(document.querySelector("#emularity-canvas"), postRun, DosBoxLoader.apply(this, emuArguments));40 emulator.start({ waitAfterDownloading: true });41}42function runPC98Dosbox() {43 console.log("running pc98dosbox");44 var emuArguments = [45 PC98DosBoxLoader.emulatorJS(emuConfig.emulatorJS),46 PC98DosBoxLoader.emulatorWASM(emuConfig.emulatorWASM),47 PC98DosBoxLoader.nativeResolution(emuConfig.nativeResolution.width, emuConfig.nativeResolution.height),48 PC98DosBoxLoader.startExe(machineConfig.startExe),49 PC98DosBoxLoader.fileSystemKey(machineId)50 ];51 var fileParams = buildFileLoadParameters(PC98DosBoxLoader);52 emuArguments = emuArguments.concat(fileParams);53 var emulator = new Emulator(document.querySelector("#emularity-canvas"), postRun, PC98DosBoxLoader.apply(this, emuArguments));54 emulator.start({ waitAfterDownloading: true });55}56function runSAE() {57 console.log("running sae");58 var emuArguments = [59 SAELoader.model(emuConfig.driverName),60 SAELoader.nativeResolution(emuConfig.nativeResolution.width, emuConfig.nativeResolution.height),61 SAELoader.emulatorJS(emuConfig.emulatorJS),62 SAELoader.fileSystemKey(machineId)63 ];64 var fileParams = buildFileLoadParameters(SAELoader);65 emuArguments = emuArguments.concat(fileParams);66 emuArguments.push(67 SAELoader.rom(emuConfig.rom)68 );69 for (var i = 0; i < machineConfig.floppy.length; i++) {70 emuArguments.push(71 SAELoader.floppy(i, machineConfig.floppy[i])72 );73 }74 var emulator = new Emulator(document.querySelector("#emularity-canvas"), postRun, SAELoader.apply(this, emuArguments));75 emulator.start({ waitAfterDownloading: true });76}77function runMAME() {78 console.log("running mame");79 var emuArguments = [80 JSMAMELoader.driver(emuConfig.driverName),81 JSMAMELoader.nativeResolution(emuConfig.nativeResolution.width, emuConfig.nativeResolution.height),82 JSMAMELoader.emulatorJS(emuConfig.emulatorJS),83 JSMAMELoader.emulatorWASM(emuConfig.emulatorWASM),84 JSMAMELoader.fileSystemKey(machineId)85 ];86 var fileParams = buildFileLoadParameters(JSMAMELoader);87 emuArguments = emuArguments.concat(fileParams);88 for (var i = 0; i < machineConfig.peripherals.length; i++) {89 var peripheral = machineConfig.peripherals[i];90 emuArguments.push(91 JSMAMELoader.peripheral(peripheral.name, peripheral.value)92 );93 }94 var extraArgs = [];95 if (emuConfig.extraArgs) {96 extraArgs = extraArgs.concat(emuConfig.extraArgs);97 }98 if (machineConfig.extraArgs) {99 extraArgs = extraArgs.concat(machineConfig.extraArgs);100 }101 if (extraArgs.length > 0) {102 emuArguments.push(103 JSMAMELoader.extraArgs(extraArgs)104 );105 }106 var canvas = document.querySelector("#emularity-canvas");107 canvas.onclick = function () {108 canvas.focus();109 canvas.requestPointerLock();110 }111 var emulator = new Emulator(document.querySelector("#emularity-canvas"), postRun, JSMESSLoader.apply(this, emuArguments));112 emulator.start({ waitAfterDownloading: true });113}114function runPCE() {115 var emuArguments = [116 PCELoader.emulatorJS(emuConfig.emulatorJS),117 PCELoader.nativeResolution(emuConfig.nativeResolution.width, emuConfig.nativeResolution.height),118 PCELoader.fileSystemKey(machineId),119 PCELoader.locateAdditionalEmulatorJS(function (filename) {120 if (emuConfig.fileLocations[filename]) {121 return emuConfig.fileLocations[filename]122 } else {123 return filename;124 }125 }),126 PCELoader.model(emuConfig.driverName)127 ];128 var fileParams = buildFileLoadParameters(PCELoader);129 emuArguments = emuArguments.concat(fileParams);130 var extraArgs = [];131 if (emuConfig.extraArgs) {132 extraArgs = extraArgs.concat(emuConfig.extraArgs);133 }134 if (machineConfig.extraArgs) {135 extraArgs = extraArgs.concat(machineConfig.extraArgs);136 }137 if (extraArgs.length > 0) {138 emuArguments.push(139 PCELoader.extraArgs(extraArgs)140 );141 }142 var canvas = document.querySelector("#emularity-canvas");143 canvas.onclick = function () {144 canvas.requestPointerLock();145 }146 var emulator = new Emulator(document.querySelector("#emularity-canvas"), postRun, PCELoader.apply(this, emuArguments));147 emulator.start({ waitAfterDownloading: true });148}149function runNP2() {150 var emuArguments = [151 NP2Loader.nativeResolution(emuConfig.nativeResolution.width, emuConfig.nativeResolution.height),152 NP2Loader.emulatorJS(emuConfig.emulatorJS),153 NP2Loader.emulatorWASM(emuConfig.emulatorWASM),154 NP2Loader.fileSystemKey(machineId)155 ];156 var fileParams = buildFileLoadParameters(NP2Loader);157 emuArguments = emuArguments.concat(fileParams);158 var extraArgs = [];159 if (emuConfig.extraArgs) {160 extraArgs = extraArgs.concat(emuConfig.extraArgs);161 }162 if (machineConfig.extraArgs) {163 extraArgs = extraArgs.concat(machineConfig.extraArgs);164 }165 if (extraArgs.length > 0) {166 emuArguments.push(167 NP2Loader.extraArgs(extraArgs)168 );169 }170 var emulator = new Emulator(document.querySelector("#emularity-canvas"), postRun, NP2Loader.apply(this, emuArguments));171 emulator.start({ waitAfterDownloading: true });172}173function buildFileLoadParameters(someLoader) {174 var fileParams = [];175 if (emuConfig.mountFile) {176 for (var i = 0; i < emuConfig.mountFile.length; i++) {177 var file = emuConfig.mountFile[i];178 fileParams.push(179 someLoader.mountFile(180 file.targetPath,181 someLoader.fetchFile(file.title, file.source)182 )183 );184 }185 }186 if (emuConfig.mountZip) {187 for (var i = 0; i < emuConfig.mountZip.length; i++) {188 var file = emuConfig.mountZip[i];189 fileParams.push(190 someLoader.mountZip(191 file.targetPath,192 someLoader.fetchFile(193 file.title,194 file.source195 ))196 );197 }198 }199 if (machineConfig.files) {200 for (var i = 0; i < machineConfig.files.length; i++) {201 var file = machineConfig.files[i];202 fileParams.push(203 someLoader.mountFile(204 file.targetPath,205 someLoader.fetchFile(file.title, file.source)206 )207 );208 }209 }210 if (machineConfig.zips) {211 for (var i = 0; i < machineConfig.zips.length; i++) {212 var zip = machineConfig.zips[i];213 fileParams.push(214 someLoader.mountZip(215 zip.targetPath,216 someLoader.fetchFile(217 zip.title,218 zip.source219 ))220 );221 }222 }223 return fileParams;224}225function processMachineConfig(machine) {226 var emularityConfigURL = "emularity-config/" + machine.emularity + ".json";227 if (machine.emularity.indexOf("dosbox-websocket") === 0) {228 setupJoystick();229 }230 if (machine.emularity.indexOf("dosbox") === 0) {231 emuRunner = runDoxbox;232 }233 if (machine.emularity.indexOf("sae") === 0) {234 emuRunner = runSAE;235 }236 if (machine.emularity.indexOf("np2") === 0) {237 emuRunner = runNP2;238 }239 if (machine.emularity.indexOf("pc98dosbox") === 0) {240 emuRunner = runPC98Dosbox;241 }242 if (machine.emularity.indexOf("mame-") === 0) {243 emuRunner = runMAME;244 }245 if (machine.emularity.indexOf("pce-") === 0) {246 emuRunner = runPCE;247 }248 $.getJSON(emularityConfigURL, function (data) {249 emuConfig = data;250 newDataLoaded();251 });252 $.getJSON(machine.url, function (data) {253 machineConfig = data;254 newDataLoaded();255 });256}257function newDataLoaded() {258 if (emuConfig && machineConfig) {259 showIntroduction();260 emuRunner();261 }262}263$(document).ready(function () {264 $.ajaxSetup({ cache: false });265 var machineParam = getUrlVars()["machine"];266 var emularityParam = getUrlVars()["emularity"];267 var machineUrlParam = getUrlVars()["machineurl"];268 if (machineParam && machineParam.length > 0) {269 $.getJSON("machines.json", processMachineJson);270 } else if (emularityParam && machineUrlParam.length > 0) {271 machineId = emularityParam + "-" + machineUrlParam.replace(/[.:#\/\\]/g, '-');272 var dummyMachineConfig = {273 "machineId": machineId,274 "emularity": emularityParam,275 "url": machineUrlParam276 }277 console.log(dummyMachineConfig);278 processMachineConfig(dummyMachineConfig);279 }280});281function postRun() {282 console.log("Emulator started");283 var bodyWidth = $("body").width();284 if (bodyWidth < 600) {285 $("#mobile-tools").show();286 resizeCanvas();287 }288}289function resizeCanvas() {290 var bodyWidth = $("body").width();291 var canvasWidth = $("#emularity-canvas").width();292 var canvasHeight = $("#emularity-canvas").height();293 if (bodyWidth < canvasWidth) {294 //Resize canvas for mobile device295 var newHeight = Math.round(canvasHeight * bodyWidth / canvasWidth);296 $("#emularity-canvas").width(bodyWidth);297 $("#emularity-canvas").height(newHeight);298 }299}300function toggleMobileKeyboard() {301 var inputElement = document.getElementById("mobile-keyboard-helper");302 inputElement.style.visibility = 'visible'; // unhide the input303 inputElement.focus(); // focus on it so keyboard pops304}305function showIntroduction() {306 var introUrl = "document/pending.md";307 if (machineConfig.introduction) {308 introUrl = machineConfig.introduction;309 }310 var showdownConv = new showdown.Converter();311 showdownConv.setOption('tables',true);312 $.get(introUrl,313 function (data) {314 var htmlContent = showdownConv.makeHtml(data);315 $("#introduction").html(htmlContent);316 }317 );318}319function setupJoystick() {320 navigator.getGamepads_ = navigator.getGamepads;321 navigator.getGamepads = function () {322 var gamepadlist = navigator.getGamepads_();323 var pads = [];324 for (var i = 0; i < gamepadlist.length; i++) {325 pads[i] = (gamepadlist[i] !== null ? gamepadlist[i] : undefined);326 }327 return pads;328 }...
Using AI Code Generation
1var root = require('root');2var emu = root.emu;3var emu2 = root.emu2;4var emu3 = root.emu3;5var emu4 = root.emu4;6var emu5 = root.emu5;7var emu6 = root.emu6;8var emu7 = root.emu7;9var emu8 = root.emu8;10var emu9 = root.emu9;11var emu10 = root.emu10;12var emu11 = root.emu11;13var emu12 = root.emu12;14var emu13 = root.emu13;15var emu14 = root.emu14;16var emu15 = root.emu15;17var emu16 = root.emu16;18var emu17 = root.emu17;19var emu18 = root.emu18;20var emu19 = root.emu19;21var emu20 = root.emu20;22var emu21 = root.emu21;23var emu22 = root.emu22;24var emu23 = root.emu23;25var emu24 = root.emu24;26var emu25 = root.emu25;27var emu26 = root.emu26;28var emu27 = root.emu27;29var emu28 = root.emu28;30var emu29 = root.emu29;31var emu30 = root.emu30;32var emu31 = root.emu31;33var emu32 = root.emu32;34var emu33 = root.emu33;35var emu34 = root.emu34;36var emu35 = root.emu35;37var emu36 = root.emu36;38var emu37 = root.emu37;39var emu38 = root.emu38;40var emu39 = root.emu39;41var emu40 = root.emu40;42var emu41 = root.emu41;43var emu42 = root.emu42;44var emu43 = root.emu43;45var emu44 = root.emu44;46var emu45 = root.emu45;47var emu46 = root.emu46;48var emu47 = root.emu47;49var emu48 = root.emu48;50var emu49 = root.emu49;
Using AI Code Generation
1var emu = require('emu');2emu.root('test');3emu.root('test');4emu.use('module');5emu.use(function(req, res, next) {6});7emu.start(8080);8emu.stop();9emu.get('/', function(req, res) {10 res.send('hello world');11});12emu.post('/form', function(req, res) {13 res.send('hello world');14});15emu.put('/user', function(req, res) {16 res.send('hello world');17});18emu.delete('/user', function(req, res) {19 res.send('hello world');20});21emu.all('/user', function(req, res) {22 res.send('hello world');23});
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!