-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlibretro.js
406 lines (373 loc) · 11.6 KB
/
libretro.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
/**
* RetroArch Web Player
*
* This provides the basic JavaScript for the RetroArch web player.
*/
var BrowserFS = BrowserFS;
var afs;
var initializationCount = 0;
var setImmediate;
var Module = {
noInitialRun: true,
arguments: ["-v", "--menu"],
encoder: new TextEncoder(),
message_queue:[],
message_out:[],
message_accum:"",
retroArchSend: function(msg) {
let bytes = this.encoder.encode(msg+"\n");
this.message_queue.push([bytes,0]);
},
retroArchRecv: function() {
let out = this.message_out.shift();
if(out == null && this.message_accum != "") {
out = this.message_accum;
this.message_accum = "";
}
return out;
},
preRun: [
function(module) {
function stdin() {
// Return ASCII code of character, or null if no input
while(module.message_queue.length > 0){
var msg = module.message_queue[0][0];
var index = module.message_queue[0][1];
if(index >= msg.length) {
module.message_queue.shift();
} else {
module.message_queue[0][1] = index+1;
// assumption: msg is a uint8array
return msg[index];
}
}
return null;
}
function stdout(c) {
if(c == null) {
// flush
if(module.message_accum != "") {
module.message_out.push(module.message_accum);
module.message_accum = "";
}
} else {
let s = String.fromCharCode(c);
if(s == "\n") {
if(module.message_accum != "") {
module.message_out.push(module.message_accum);
module.message_accum = "";
}
} else {
module.message_accum = module.message_accum+s;
}
}
}
module.FS.init(stdin, stdout);
}
],
postRun: [],
onRuntimeInitialized: function()
{
appInitialized();
},
print: function(text)
{
console.log(text);
},
printErr: function(text)
{
console.error(text);
},
canvas: document.getElementById("canvas"),
totalDependencies: 0,
monitorRunDependencies: function(left)
{
this.totalDependencies = Math.max(this.totalDependencies, left);
}
};
function cleanupStorage()
{
localStorage.clear();
if (BrowserFS.FileSystem.IndexedDB.isAvailable())
{
var req = indexedDB.deleteDatabase("RetroArch");
req.onsuccess = function () {
console.log("Deleted database successfully");
};
req.onerror = function () {
console.log("Couldn't delete database");
};
req.onblocked = function () {
console.log("Couldn't delete database due to the operation being blocked");
};
}
document.getElementById("btnClean").disabled = true;
}
function idbfsInit()
{
$('#icnLocal').removeClass('fa-globe');
$('#icnLocal').addClass('fa-spinner fa-spin');
var imfs = new BrowserFS.FileSystem.InMemory();
if (BrowserFS.FileSystem.IndexedDB.isAvailable())
{
afs = new BrowserFS.FileSystem.AsyncMirror(imfs,
new BrowserFS.FileSystem.IndexedDB(function(e, fs)
{
if (e)
{
//fallback to imfs
afs = new BrowserFS.FileSystem.InMemory();
console.log("WEBPLAYER: error: " + e + " falling back to in-memory filesystem");
appInitialized();
}
else
{
// initialize afs by copying files from async storage to sync storage.
afs.initialize(function (e)
{
if (e)
{
afs = new BrowserFS.FileSystem.InMemory();
console.log("WEBPLAYER: error: " + e + " falling back to in-memory filesystem");
appInitialized();
}
else
{
idbfsSyncComplete();
}
});
}
},
"RetroArch"));
}
}
function idbfsSyncComplete()
{
$('#icnLocal').removeClass('fa-spinner').removeClass('fa-spin');
$('#icnLocal').addClass('fa-check');
console.log("WEBPLAYER: idbfs setup successful");
appInitialized();
}
function appInitialized()
{
/* Need to wait for the file system, the wasm runtime, and the zip download
to complete before enabling the Run button. */
initializationCount++;
if (initializationCount == 3)
{
setupFileSystem("browser");
preLoadingComplete();
}
}
function preLoadingComplete()
{
/* Make the Preview image clickable to start RetroArch. */
$('.webplayer-preview').addClass('loaded').click(function () {
startRetroArch();
return false;
});
document.getElementById("btnRun").disabled = false;
$('#btnRun').removeClass('disabled');
}
var zipTOC;
function zipfsInit() {
// 256 MB max bundle size
let buffer = new ArrayBuffer(256*1024*1024);
let bufferView = new Uint8Array(buffer);
let idx = 0;
// bundle should be in four parts (this can be changed later)
Promise.all([fetch("assets/frontend/bundle.zip.aa"),
fetch("assets/frontend/bundle.zip.ab"),
fetch("assets/frontend/bundle.zip.ac"),
fetch("assets/frontend/bundle.zip.ad")
]).then(function(resps) {
Promise.all(resps.map((r) => r.arrayBuffer())).then(function(buffers) {
for (let buf of buffers) {
if (idx+buf.byteLength > buffer.maxByteLength) {
console.log("WEBPLAYER: error: bundle.zip is too large");
}
bufferView.set(new Uint8Array(buf), idx, buf.byteLength);
idx += buf.byteLength;
}
BrowserFS.FileSystem.ZipFS.computeIndex(BrowserFS.BFSRequire('buffer').Buffer(new Uint8Array(buffer, 0, idx)), function(toc) {
zipTOC = toc;
appInitialized();
});
})
});
}
function setupFileSystem(backend)
{
/* create a mountable filesystem that will server as a root
mountpoint for browserfs */
var mfs = new BrowserFS.FileSystem.MountableFileSystem();
/* create an XmlHttpRequest filesystem for the bundled data */
var xfs1 = new BrowserFS.FileSystem.ZipFS(zipTOC);
/* create an XmlHttpRequest filesystem for core assets */
var xfs2 = new BrowserFS.FileSystem.XmlHttpRequest
(".index-xhr", "assets/cores/");
console.log("WEBPLAYER: initializing filesystem: " + backend);
mfs.mount('/home/web_user/retroarch/userdata', afs);
mfs.mount('/home/web_user/retroarch/', xfs1);
mfs.mount('/home/web_user/retroarch/userdata/content/downloads', xfs2);
BrowserFS.initialize(mfs);
var BFS = new BrowserFS.EmscriptenFS(Module.FS, Module.PATH, Module.ERRNO_CODES);
Module.FS.mount(BFS, {root: '/home'}, '/home');
console.log("WEBPLAYER: " + backend + " filesystem initialization successful");
}
/**
* Retrieve the value of the given GET parameter.
*/
function getParam(name) {
var results = new RegExp('[?&]' + name + '=([^&#]*)').exec(window.location.href);
if (results) {
return results[1] || null;
}
}
function startRetroArch()
{
$('.webplayer').show();
$('.webplayer-preview').hide();
document.getElementById("btnRun").disabled = true;
$('#btnFullscreen').removeClass('disabled');
$('#btnMenu').removeClass('disabled');
$('#btnAdd').removeClass('disabled');
$('#btnRom').removeClass('disabled');
document.getElementById("btnAdd").disabled = false;
document.getElementById("btnRom").disabled = false;
document.getElementById("btnMenu").disabled = false;
document.getElementById("btnFullscreen").disabled = false;
Module["canvas"] = document.getElementById("canvas");
Module["canvas"].addEventListener("click", () => Module["canvas"].focus());
Module['callMain'](Module['arguments']);
Module['resumeMainLoop']();
Module['canvas'].focus();
}
function selectFiles(files)
{
$('#btnAdd').addClass('disabled');
$('#icnAdd').removeClass('fa-plus');
$('#icnAdd').addClass('fa-spinner spinning');
var count = files.length;
for (var i = 0; i < count; i++)
{
filereader = new FileReader();
filereader.file_name = files[i].name;
filereader.readAsArrayBuffer(files[i]);
filereader.onload = function(){uploadData(this.result, this.file_name)};
filereader.onloadend = function(evt)
{
console.log("WEBPLAYER: file: " + this.file_name + " upload complete");
if (evt.target.readyState == FileReader.DONE)
{
$('#btnAdd').removeClass('disabled');
$('#icnAdd').removeClass('fa-spinner spinning');
$('#icnAdd').addClass('fa-plus');
}
}
}
}
function uploadData(data,name)
{
var dataView = new Uint8Array(data);
Module.FS.createDataFile('/', name, dataView, true, false);
var data = Module.FS.readFile(name,{ encoding: 'binary' });
Module.FS.writeFile('/home/web_user/retroarch/userdata/content/' + name, data ,{ encoding: 'binary' });
Module.FS.unlink(name);
}
function switchCore(corename) {
localStorage.setItem("core", corename);
}
function switchStorage(backend) {
if (backend != localStorage.getItem("backend"))
{
localStorage.setItem("backend", backend);
location.reload();
}
}
// When the browser has loaded everything.
$(function() {
// Enable all available ToolTips.
$('.tooltip-enable').tooltip({
placement: 'right'
});
// Allow hiding the top menu.
$('.showMenu').hide();
$('#btnHideMenu, .showMenu').click(function () {
$('nav').slideToggle('slow');
$('.showMenu').toggle('slow');
});
/**
* Attempt to disable some default browser keys.
*/
var keys = {
9: "tab",
13: "enter",
16: "shift",
18: "alt",
27: "esc",
33: "rePag",
34: "avPag",
35: "end",
36: "home",
37: "left",
38: "up",
39: "right",
40: "down",
112: "F1",
113: "F2",
114: "F3",
115: "F4",
116: "F5",
117: "F6",
118: "F7",
119: "F8",
120: "F9",
121: "F10",
122: "F11",
123: "F12"
};
window.addEventListener('keydown', function (e) {
if (keys[e.which]) {
e.preventDefault();
}
});
// Switch the core when selecting one.
$('#core-selector a').click(function () {
var coreChoice = $(this).data('core');
switchCore(coreChoice);
});
// Find which core to load.
var core = localStorage.getItem("core", core);
if (!core) {
core = 'gambatte';
}
loadCore(core);
});
function loadCore(core) {
// Make the core the selected core in the UI.
var coreTitle = $('#core-selector a[data-core="' + core + '"]').addClass('active').text();
$('#dropdownMenu1').text(coreTitle);
// Load the Core's related JavaScript.
import("./"+core+"_libretro.js").then(script => {
script.default(Module).then(mod => {
Module = mod;
$('#icnRun').removeClass('fa-spinner').removeClass('fa-spin');
$('#icnRun').addClass('fa-play');
$('#lblDrop').removeClass('active');
$('#lblLocal').addClass('active');
idbfsInit();
zipfsInit();
}).catch(err => { console.error("Couldn't instantiate module",err); throw err; });
}).catch(err => { console.error("Couldn't load script",err); throw err; });
}
function keyPress(k)
{
function kp(k, event) {
var oEvent = new KeyboardEvent(event, { code: k });
document.dispatchEvent(oEvent);
document.getElementById('canvas').focus();
}
kp(k, "keydown");
setTimeout(function(){kp(k, "keyup")}, 50);
}