"use strict"; // 8bitworkshop IDE user interface import $ = require("jquery"); import * as bootstrap from "bootstrap"; import { CodeProject } from "./project"; import { WorkerResult, WorkerOutput, VerilogOutput, SourceFile, WorkerError, FileData } from "./workertypes"; import { ProjectWindows } from "./windows"; import { Platform, Preset, DebugSymbols, DebugEvalCondition } from "./baseplatform"; import { PLATFORMS, EmuHalt, Toolbar } from "./emu"; import * as Views from "./views"; import { createNewPersistentStore } from "./store"; import { getFilenameForPath, getFilenamePrefix, highlightDifferences, invertMap, byteArrayToString, compressLZG, byteArrayToUTF8, isProbablyBinary, getWithBinary, getBasePlatform } from "./util"; import { StateRecorderImpl } from "./recorder"; import { GHSession, GithubService, getRepos, parseGithubURL } from "./services"; // external libs (TODO) declare var Tour, GIF, saveAs, JSZip, Mousetrap, Split, firebase; // in index.html declare var exports; // make sure VCS doesn't start if (window['Javatari']) window['Javatari'].AUTO_START = false; var PRESETS : Preset[]; // presets array export var platform_id : string; // platform ID string (platform) export var store_id : string; // store ID string (repo || platform) export var repo_id : string; // repository ID (repo) export var platform : Platform; // emulator object var toolbar = $("#controls_top"); var uitoolbar : Toolbar; export var current_project : CodeProject; // current CodeProject object export var projectWindows : ProjectWindows; // window manager var stateRecorder : StateRecorderImpl; var userPaused : boolean; // did user explicitly pause? var current_output : WorkerOutput; // current ROM var current_preset_entry : Preset; // current preset object (if selected) var store; // persistent store export var compparams; // received build params from worker export var lastDebugState; // last debug state (object) var lastDebugInfo; // last debug info (CPU text) var debugCategory; // current debug category var debugTickPaused = false; var recorderActive = false; var lastBreakExpr = "c.PC == 0x6000"; // TODO: codemirror multiplex support? var TOOL_TO_SOURCE_STYLE = { 'dasm': '6502', 'acme': '6502', 'cc65': 'text/x-csrc', 'ca65': '6502', 'z80asm': 'z80', 'sdasz80': 'z80', 'sdcc': 'text/x-csrc', 'verilator': 'verilog', 'jsasm': 'z80', 'zmac': 'z80', 'bataribasic': 'bataribasic', 'markdown': 'markdown', 'xasm6809': 'z80' } function alertError(s:string) { bootbox.alert(s); } function alertInfo(s:string) { bootbox.alert(s); } function newWorker() : Worker { return new Worker("./src/worker/loader.js"); } var hasLocalStorage : boolean = function() { try { const key = "__some_random_key_you_are_not_going_to_use__"; localStorage.setItem(key, key); localStorage.removeItem(key); return true; } catch (e) { return false; } }(); function getCurrentPresetTitle() : string { if (!current_preset_entry) return current_project.mainPath || "ROM"; else return current_preset_entry.title || current_preset_entry.name || current_project.mainPath || "ROM"; } function setLastPreset(id:string) { if (hasLocalStorage) { if (repo_id) localStorage.setItem("__lastrepo", repo_id); else localStorage.removeItem("__lastrepo"); localStorage.setItem("__lastplatform", platform_id); localStorage.setItem("__lastid_"+store_id, id); } } function unsetLastPreset() { if (hasLocalStorage) { delete qs['file']; localStorage.removeItem("__lastid_"+store_id); } } function initProject() { current_project = new CodeProject(newWorker(), platform_id, platform, store); projectWindows = new ProjectWindows($("#workspace")[0] as HTMLElement, current_project); current_project.callbackGetRemote = getWithBinary; current_project.callbackBuildResult = (result:WorkerResult) => { setCompileOutput(result); refreshWindowList(); }; current_project.callbackBuildStatus = (busy:boolean) => { if (busy) { toolbar.addClass("is-busy"); } else { toolbar.removeClass("is-busy"); toolbar.removeClass("has-errors"); // may be added in next callback projectWindows.setErrors(null); $("#error_alert").hide(); } $('#compile_spinner').css('visibility', busy ? 'visible' : 'hidden'); }; } function refreshWindowList() { var ul = $("#windowMenuList").empty(); var separate = false; function addWindowItem(id, name, createfn) { if (separate) { ul.append(document.createElement("hr")); separate = false; } var li = document.createElement("li"); var a = document.createElement("a"); a.setAttribute("class", "dropdown-item"); a.setAttribute("href", "#"); if (id == projectWindows.getActiveID()) $(a).addClass("dropdown-item-checked"); a.appendChild(document.createTextNode(name)); li.appendChild(a); ul.append(li); if (createfn) { projectWindows.setCreateFunc(id, createfn); $(a).click( (e) => { projectWindows.createOrShow(id); ul.find('a').removeClass("dropdown-item-checked"); ul.find(e.target).addClass("dropdown-item-checked"); }); } } function loadEditor(path:string) { var tool = platform.getToolForFilename(path); var mode = tool && TOOL_TO_SOURCE_STYLE[tool]; return new Views.SourceEditor(path, mode); } function addEditorItem(id:string) { var data = current_project.getFile(id); if (typeof data === 'string') addWindowItem(id, getFilenameForPath(id), loadEditor); else if (data instanceof Uint8Array) addWindowItem(id, getFilenameForPath(id), () => { return new Views.BinaryFileView(id, data as Uint8Array); }); } // add main file editor addEditorItem(current_project.mainPath); // add other source files current_project.iterateFiles( (id, text) => { if (text && id != current_project.mainPath) addEditorItem(id); }); // add listings // TODO: update listing when recompiling separate = true; var listings = current_project.getListings(); if (listings) { for (var lstfn in listings) { var lst = listings[lstfn]; // add listing if source/assembly file exists and has text if ((lst.assemblyfile && lst.assemblyfile.text) || (lst.sourcefile && lst.sourcefile.text)) { addWindowItem(lstfn, getFilenameForPath(lstfn), (path) => { return new Views.ListingView(path); }); } } } // add other tools separate = true; if (platform.disassemble) { addWindowItem("#disasm", "Disassembly", () => { return new Views.DisassemblerView(); }); } if (platform.readAddress) { addWindowItem("#memory", "Memory Browser", () => { return new Views.MemoryView(); }); } if (platform.readVRAMAddress) { addWindowItem("#memvram", "VRAM Browser", () => { return new Views.VRAMMemoryView(); }); } if (current_project.segments) { addWindowItem("#memmap", "Memory Map", () => { return new Views.MemoryMapView(); }); } if (platform.startProfiling && platform.runEval && platform.getRasterScanline) { addWindowItem("#profiler", "Profiler", () => { return new Views.ProfileView(); }); } addWindowItem('#asseteditor', 'Asset Editor', () => { return new Views.AssetEditorView(); }); } function loadProject(preset_id:string) { // set current file ID current_project.mainPath = preset_id; setLastPreset(preset_id); // load files from storage or web URLs current_project.loadFiles([preset_id], function(err, result) { if (err) { alertError(err); } else if (result && result.length) { // we need this to build create functions for the editor refreshWindowList(); // show main file projectWindows.createOrShow(preset_id); // build project current_project.setMainFile(preset_id); } }); } function reloadProject(id:string) { // leave repository == '/' if (id == '/') { qs = {repo:'/'}; } else if (id.indexOf('://') >= 0) { var urlparse = parseGithubURL(id); if (urlparse) { qs = {repo:urlparse.repopath}; } } else { qs['platform'] = platform_id; qs['file'] = id; } gotoNewLocation(); } function getSkeletonFile(fileid:string) : Promise { var ext = platform.getToolForFilename(fileid); // TODO: .mame return $.get( "presets/"+getBasePlatform(platform_id)+"/skeleton."+ext, 'text').catch((e) => { alertError("Could not load skeleton for " + platform_id + "/" + ext + "; using blank file"); }); } function checkEnteredFilename(fn : string) : boolean { if (fn.indexOf(" ") >= 0) { alertError("No spaces in filenames, please."); return false; } return true; } function _createNewFile(e) { // TODO: support spaces bootbox.prompt({ title:"Enter the name of your new main source file.", placeholder:"newfile" + platform.getDefaultExtension(), callback:(filename) => { if (filename && filename.trim().length > 0) { if (!checkEnteredFilename(filename)) return; if (filename.indexOf(".") < 0) { filename += platform.getDefaultExtension(); } var path = "local/" + filename; getSkeletonFile(path).then( (result) => { return store.setItem(path, result || "\n"); }).then(() => { reloadProject("local/" + filename); }); } } } as any); return true; } function _uploadNewFile(e) { $("#uploadFileElem").click(); } function handleFileUpload(files: File[]) { console.log(files); var index = 0; var gotoMainFile = (files.length == 1); function uploadNextFile() { var f = files[index++]; if (!f) { console.log("Done uploading"); if (gotoMainFile) { gotoNewLocation(); } else { updateSelector(); alertInfo("Files uploaded."); } } else { var path = "local/" + f.name; var reader = new FileReader(); reader.onload = function(e) { var arrbuf = (e.target).result as ArrayBuffer; var data : FileData = new Uint8Array(arrbuf); // convert to UTF8, unless it's a binary file if (isProbablyBinary(path, data)) { gotoMainFile = false; } else { data = byteArrayToUTF8(data).replace('\r\n','\n'); // convert CRLF to LF } // store in local forage // TODO: use projectWindows uploadFile() store.setItem(path, data, function(err, result) { if (err) alertError("Error uploading " + path + ": " + err); else { console.log("Uploaded " + path + " " + data.length + " bytes"); if (index == 1) { qs['file'] = path; // TODO? } uploadNextFile(); } }); } reader.readAsArrayBuffer(f); // read as binary } } if (files) uploadNextFile(); } function getCurrentMainFilename() : string { return getFilenameForPath(current_project.mainPath); } function getCurrentEditorFilename() : string { return getFilenameForPath(projectWindows.getActiveID()); } // GITHUB stuff (TODO: move) var githubService : GithubService; function getCookie(name) { var nameEQ = name + "="; var ca = document.cookie.split(';'); for(var i=0;i < ca.length;i++) { var c = ca[i]; while (c.charAt(0)==' ') c = c.substring(1,c.length); if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length); } return null; } function getGithubService() { if (!githubService) { // get github API key from cookie // TODO: move to service? var ghkey = getCookie('__github_key'); githubService = new GithubService(exports['Octokat'], ghkey, store, current_project); console.log("loaded github service"); } return githubService; } function getBoundGithubURL() : string { var toks = (repo_id||'').split('/'); if (toks.length != 2) { alertError("You are not in a GitHub repository. Choose Import or Publish first."); return null; } return 'https://github.com/' + toks[0] + '/' + toks[1]; } function importProjectFromGithub(githuburl:string) { var sess : GHSession; var urlparse = parseGithubURL(githuburl); if (!urlparse) { alertError('Could not parse Github URL.'); return; } // redirect to repo if exists var existing = getRepos()[urlparse.repopath]; if (existing && !confirm("You've already imported " + urlparse.repopath + " -- do you want to replace all files?")) { return; } // create new store for imported repository setWaitDialog(true); var newstore = createNewPersistentStore(urlparse.repopath, () => { }); // import into new store setWaitProgress(0.25); return getGithubService().import(githuburl).then( (sess1:GHSession) => { sess = sess1; setWaitProgress(0.75); return getGithubService().pull(githuburl, newstore); }).then( (sess2:GHSession) => { // TODO: only first session has mainPath? // reload repo qs = {repo:sess.repopath}; // file:sess.mainPath, platform:sess.platform_id}; setWaitDialog(false); gotoNewLocation(); }).catch( (e) => { setWaitDialog(false); console.log(e); alertError("Could not import " + githuburl + ": " + e); }); } function _importProjectFromGithub(e) { var modal = $("#importGithubModal"); var btn = $("#importGithubButton"); modal.modal('show'); btn.off('click').on('click', () => { var githuburl = $("#importGithubURL").val()+""; modal.modal('hide'); importProjectFromGithub(githuburl); }); } function _publishProjectToGithub(e) { if (repo_id) { alertError("This project (" + current_project.mainPath + ") is already bound to a Github repository. Choose 'Push Changes' to update."); return; } var modal = $("#publishGithubModal"); var btn = $("#publishGithubButton"); modal.modal('show'); btn.off('click').on('click', () => { var name = $("#githubRepoName").val()+""; var desc = $("#githubRepoDesc").val()+""; var priv = $("#githubRepoPrivate").val() == 'private'; var license = $("#githubRepoLicense").val()+""; var sess; modal.modal('hide'); setWaitDialog(true); getGithubService().login().then( () => { setWaitProgress(0.25); return getGithubService().publish(name, desc, license, priv); }).then( (sess) => { setWaitProgress(0.5); repo_id = qs['repo'] = sess.repopath; return pushChangesToGithub('initial import from 8bitworkshop.com'); }).then( () => { setWaitProgress(1.0); reloadProject(current_project.stripLocalPath(current_project.mainPath)); }).catch( (e) => { setWaitDialog(false); console.log(e); alertError("Could not publish GitHub repository: " + e); }); }); } function _pushProjectToGithub(e) { var ghurl = getBoundGithubURL(); if (!ghurl) return; var modal = $("#pushGithubModal"); var btn = $("#pushGithubButton"); modal.modal('show'); btn.off('click').on('click', () => { var commitMsg = $("#githubCommitMsg").val()+""; modal.modal('hide'); pushChangesToGithub(commitMsg); }); } function _pullProjectFromGithub(e) { var ghurl = getBoundGithubURL(); if (!ghurl) return; setWaitDialog(true); getGithubService().pull(ghurl).then( (sess:GHSession) => { setWaitDialog(false); }); } function pushChangesToGithub(message:string) { var ghurl = getBoundGithubURL(); if (!ghurl) return; // build file list for push var files = []; for (var path in current_project.filedata) { var newpath = current_project.stripLocalPath(path); var data = current_project.filedata[path]; if (newpath && data) { files.push({path:newpath, data:data}); } } // push files setWaitDialog(true); return getGithubService().login().then( () => { setWaitProgress(0.5); return getGithubService().commitPush(ghurl, message, files); }).then( (sess) => { setWaitDialog(false); alertInfo("Pushed files to " + ghurl); return sess; }).catch( (e) => { setWaitDialog(false); console.log(e); alertError("Could not push GitHub repository: " + e); }); } function _shareEmbedLink(e) { if (current_output == null) { // TODO alertError("Please fix errors before sharing."); return true; } if (!(current_output instanceof Uint8Array)) { alertError("Can't share a Verilog executable yet. (It's not actually a ROM...)"); return true; } loadClipboardLibrary(); loadScript('lib/liblzg.js', () => { // TODO: Module is bad var name (conflicts with MAME) var lzgrom = compressLZG( window['Module'], Array.from(current_output) ); window['Module'] = null; // so we load it again next time var lzgb64 = btoa(byteArrayToString(lzgrom)); var embed = { p: platform_id, //n: current_project.mainPath, r: lzgb64 }; var linkqs = $.param(embed); var fulllink = get8bitworkshopLink(linkqs, 'embed.html'); var iframelink = '