diff --git a/.bowerrc b/.bowerrc deleted file mode 100644 index a41a3219a..000000000 --- a/.bowerrc +++ /dev/null @@ -1 +0,0 @@ -{ "directory": "static/ext" } diff --git a/.gitignore b/.gitignore index 04bee72b8..c8c269bc7 100644 --- a/.gitignore +++ b/.gitignore @@ -2,7 +2,6 @@ /node_modules newrelic_agent.log /.npm-updated -/.bower-updated *.vscode /out *.heapsnapshot @@ -10,3 +9,7 @@ etc/config/*.local.properties .travis-compilers /nbproject /package-lock.json +*.bundle*.js +*.map +static/dist +static/vs diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index e331bf6f9..6bf3cf17a 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -5,7 +5,8 @@ Before we go too far, an apology: Compiler Explorer grew out of a bit of hacky J well-used project pretty quickly. Not all the code was originally well-written or well-tested. Please be forgiving of that, and be ready to help in improving that. -Note that Compiler Explorer targets the latest Node.js LTS, so it's better if you do so as well when testing your changes locally. (But it will run in everything post-Node.js 8) +Note that Compiler Explorer targets the latest Node.js LTS, so it's better if you do so as well when testing your changes locally. +(But it *should* run in everything post-Node.js 8) ## In brief * Make your changes, trying to stick to the style and code format where possible. We use default IntelliJ settings, @@ -22,8 +23,8 @@ every commit, ensuring that they pass before commiting your changes. _You can di ## Basic code layout -Code is separated into server-side code and client-side code. Server packages are installed via `package.json` and client-side via -`bower.json`. Server code is in `app.js` and in the `lib` directory. Client code is all in the `static` directory. +Code is separated into server-side code and client-side code. All dependencies (server and client side) are installed via `package.json`. +Server code is in `app.js` and in the `lib` directory. Client code is all in the `static` directory. In the server code, the `app.js` sets up a basic `express` middleware-driven web server, delegating to the various compiler backends in `lib/compilers`. Most inherit (loosely) from `lib/base-compiler.js` which does most of the work of running diff --git a/Makefile b/Makefile index 7e72b2629..e04462c17 100644 --- a/Makefile +++ b/Makefile @@ -1,6 +1,8 @@ NODE_DIR?=/opt/compiler-explorer/node -NPM:= $(shell env PATH="$(NODE_DIR)/bin:$$PATH" which npm) -NODE:= $(shell env PATH="$(NODE_DIR)/bin:$$PATH" which node || env PATH="$(NODE_DIR)/bin:$$PATH" which nodejs) +YARN_DIR?=/opt/compiler-explorer/yarn +YARN_EXE:=$(shell env PATH="$(NODE_DIR)/bin:$(YARN_DIR)/bin:$(PATH)" which yarn) +NODE:=$(shell env PATH="$(NODE_DIR)/bin:$(PATH)" which node || env PATH="$(NODE_DIR)/bin:$(PATH)" which nodejs) +YARN:=$(NODE) $(YARN_EXE).js default: run NODE_VERSION_USED:=8 @@ -21,9 +23,8 @@ endif endif .PHONY: clean run test run-amazon c-preload optional-haskell-support optional-d-support optional-rust-support -.PHONY: dist lint prereqs node_modules bower_modules travis-dist -prereqs: optional-haskell-support optional-d-support optional-rust-support node_modules c-preload bower_modules - +.PHONY: dist lint prereqs node_modules travis-dist +prereqs: optional-haskell-support optional-d-support optional-rust-support node_modules webpack c-preload GDC?=gdc DMD?=dmd LDC?=ldc2 @@ -56,24 +57,18 @@ endif NODE_MODULES=.npm-updated $(NODE_MODULES): package.json - $(NPM) install + $(YARN) install @touch $@ -BOWER_MODULES=.bower-updated -$(BOWER_MODULES): bower.json $(NODE_MODULES) - if ! test -f "${BOWER_MODULES}"; then rm -rf static/ext; fi - $(NODE) ./node_modules/bower/bin/bower install - @touch $@ - # Workaround for lack of versioned monaco-editor in bower - rm -rf static/ext/monaco-editor - cp -r node_modules/monaco-editor static/ext/ +webpack: + $(NODE) node_modules/webpack/bin/webpack.js ${WEBPACK_ARGS} lint: $(NODE_MODULES) - $(NODE) ./node_modules/.bin/jshint --config etc/jshintrc.server app.js $(shell find lib test -name '*.js') - $(NODE) ./node_modules/.bin/jshint --config etc/jshintrc.client $(shell find static -name '*.js' -not -path 'static/ext/*' -not -path static/analytics.js) + $(NODE) ./node_modules/.bin/jshint --config etc/jshintrc.server app.js $(shell find lib -name '*.js') + $(NODE) ./node_modules/.bin/jshint --config etc/jshintrc.client $(shell find static -name '*.js' -not -path 'static/dist/*' -not -path static/analytics.js -not -path 'static/vs/*' -not -path 'static/ext/*') node_modules: $(NODE_MODULES) -bower_modules: $(BOWER_MODULES) +webpack: $(WEBPACK) test: $(NODE_MODULES) lint $(MAKE) -C c-preload test @@ -83,37 +78,31 @@ check: $(NODE_MODULES) lint $(NODE) ./node_modules/.bin/mocha --recursive clean: - rm -rf bower_modules node_modules .npm-updated .bower-updated out static/ext + rm -rf node_modules .npm-updated out static/dist static/vs $(MAKE) -C d clean $(MAKE) -C c-preload clean +run: export NODE_ENV=LOCAL WEBPACK_ARGS="-p" run: prereqs $(NODE) ./node_modules/.bin/supervisor -w app.js,lib,etc/config -e 'js|node|properties' --exec $(NODE) $(NODE_ARGS) -- ./app.js $(EXTRA_ARGS) +dev: export NODE_ENV=DEV +dev: prereqs + $(NODE) ./node_modules/.bin/supervisor -w app.js,lib,etc/config -e 'js|node|properties' --exec $(NODE) $(NODE_ARGS) -- ./app.js $(EXTRA_ARGS) + + + HASH := $(shell git rev-parse HEAD) +dist: export WEBPACK_ARGS=-p dist: prereqs - rm -rf out/dist - $(NODE) ./node_modules/requirejs/bin/r.js -o app.build.js - # Move all assets to a versioned directory - echo $(HASH) > out/dist/git_hash - mkdir -p out/dist/v/$(HASH) - mv out/dist/main.js* out/dist/v/$(HASH)/ - mv out/dist/explorer.css out/dist/v/$(HASH)/ - mv out/dist/assets/ out/dist/v/$(HASH)/ - mv out/dist/themes/ out/dist/v/$(HASH)/ - # copy any external references into the directory too - cp -r $(shell pwd)/out/dist/ext out/dist/v/$(HASH)/ext - # uglify requirejs itself - $(NODE) ./node_modules/.bin/uglifyjs out/dist/v/$(HASH)/ext/requirejs/require.js \ - -c \ - --output out/dist/v/$(HASH)/ext/requirejs/require.js \ - --source-map out/dist/v/$(HASH)/ext/requirejs/require.js.map \ - --source-map-url require.js.map \ - --source-map-root //v/$(HASH)/ext/requirejs \ - --prefix 6 + rm -rf out/dist/ + mkdir -p out/dist + mkdir -p out/dist/vs + cp -r static/dist/ out/dist/ + cp -r static/vs/ out/dist/ travis-dist: dist - tar --exclude './.travis-compilers' --exclude './.git' --exclude './static' --exclude './out/dist/ext' -Jcf /tmp/ce-build.tar.xz . + tar --exclude './.travis-compilers' --exclude './.git' --exclude './static' -Jcf /tmp/ce-build.tar.xz . rm -rf out/dist-bin mkdir -p out/dist-bin mv /tmp/ce-build.tar.xz out/dist-bin/${TRAVIS_BUILD_NUMBER}.tar.xz diff --git a/README.md b/README.md index f6590097c..4770b1897 100644 --- a/README.md +++ b/README.md @@ -26,10 +26,10 @@ Compiler Explorer is written in node.js. Assuming you have a compatible version of `node` installed, simply running `make` ought to get you up and running with an Explorer running on port 10240 on your local machine: http://localhost:10240/. Currently Compiler Explorer requires `node` v8 installed, either on the path or at `NODE_PATH` (an environment variable or `make` parameter). -Running with `make EXTRA_ARGS='--language LANG'` will allow you to load `LANG` exclusively, where `LANG` is one for the language ids/aliases defined in `lib/languages.js` -The `Makefile` will automatically install all the third party libraries needed to run; using `npm` to install server-side -components and `bower` to install all the client-facing libraries. +Running with `make EXTRA_ARGS='--language LANG'` will allow you to load `LANG` exclusively, where `LANG` is one for the language ids/aliases defined in `lib/languages.js` +The `Makefile` will automatically install all the third party libraries needed to run; using `yarn` to install server-side and client side components + If you want to point it at your own GCC or similar binaries, either edit the `etc/config/compiler-explorer.defaults.properties` or else make a new one with the name `compiler-explorer.local.properties`. `*.local.properties` files have the highest priority when loading properties. diff --git a/app.js b/app.js index 2fecc6912..c0f17c9e8 100755 --- a/app.js +++ b/app.js @@ -36,8 +36,10 @@ const nopt = require('nopt'), url = require('url'), _ = require('underscore-node'), express = require('express'), + Raven = require('raven'), logger = require('./lib/logger').logger, - Raven = require('raven'); + webpackDevMiddleware = require("webpack-dev-middleware"); + // Parse arguments from command line 'node ./app.js args...' const opts = nopt({ @@ -86,19 +88,30 @@ const port = opts.port || 10240; const staticDir = opts.static || 'static'; const archivedVersions = opts.archivedVersions; let gitReleaseName = ""; -let versionedRootPrefix = ""; const wantedLanguage = opts.language || null; + + + +const webpackConfig = require('./webpack.config.js')[1], + webpackCompiler = require('webpack')(webpackConfig), + manifestName = 'manifest.json', + staticManifestPath = path.join(__dirname, staticDir, webpackConfig.output.publicPath), + assetManifestPath = path.join(staticManifestPath, 'assets'), + staticManifest = require(path.join(staticManifestPath, manifestName)), + assetManifest = require(path.join(assetManifestPath, manifestName)); + // Use the canned git_hash if provided if (opts.static && fs.existsSync(opts.static + "/git_hash")) { gitReleaseName = fs.readFileSync(opts.static + "/git_hash").toString().trim(); } else if (fs.existsSync('.git/')) { // Just if we have been cloned and not downloaded (Thanks David!) gitReleaseName = child_process.execSync('git rev-parse HEAD').toString().trim(); } -if (opts.static && fs.existsSync(opts.static + '/v/' + gitReleaseName)) - versionedRootPrefix = "v/" + gitReleaseName + "/"; + // Don't treat @ in paths as remote adresses const fetchCompilersFromRemote = !opts.noRemoteFetch; +const isDevMode = () => process.env.NODE_ENV === "DEV"; + const propHierarchy = _.flatten([ 'defaults', env, @@ -559,14 +572,25 @@ Promise.all([findCompilers(), aws.initConfig(awsProps)]) logger.info("======================================="); logger.info(`Listening on http://${hostname || 'localhost'}:${port}/`); - logger.info(` serving static files from '${staticDir}'`); if (gitReleaseName) logger.info(` git release ${gitReleaseName}`); function renderConfig(extra) { const options = _.extend(extra, clientOptionsHandler.get()); options.compilerExplorerOptions = JSON.stringify(options); - options.root = versionedRootPrefix; options.extraBodyClass = extraBodyClass; + options.require = function (path) { + if (isDevMode()) { + //this will break assets in dev mode for now + return '/dist/' + path; + } + if(staticManifest.hasOwnProperty(path)) { + return "dist/" + staticManifest[path]; + } + if(assetManifest.hasOwnProperty(path)) { + return "dist/assets/" + assetManifest[path]; + } + logger.warn("Requested an asset I don't know about"); + }; return options; } @@ -575,8 +599,26 @@ Promise.all([findCompilers(), aws.initConfig(awsProps)]) contentPolicyHeader(res); res.render('embed', renderConfig({embedded: true})); }; - const router = express.Router(); - router + const healthCheck = require('./lib/handlers/health-check'); + + if (isDevMode()) { + webServer.use(webpackDevMiddleware(webpackCompiler, { + publicPath: webpackConfig.output.publicPath + })); + webServer.use(express.static(staticDir)); + } else { + //assume that anything not dev is just production this gives sane defaults for anyone who isn't messing with this + logger.info(" serving static files from '" + staticDir + "'"); + webServer.use(express.static(staticDir, {maxAge: staticMaxAgeSecs * 1000})); + } + + webServer + .use(Raven.requestHandler()) + .set('trust proxy', true) + .set('view engine', 'pug') + .use('/healthcheck', new healthCheck.HealthCheckHandler().handle) // before morgan so healthchecks aren't logged + .use(morgan('combined', {stream: logger.stream})) + .use(compression()) .get('/', (req, res) => { staticHeaders(res); contentPolicyHeader(res); @@ -598,39 +640,18 @@ Promise.all([findCompilers(), aws.initConfig(awsProps)]) res.set('Content-Type', 'application/xml'); res.render('sitemap'); }) - .use(sFavicon(`${staticDir}/favicon.ico`)) - .use('/v', express.static(`${staticDir}/v`, {maxAge: Infinity, index: false})) - .use(express.static(staticDir, {maxAge: staticMaxAgeSecs * 1000})); - if (archivedVersions) { - // The archived versions directory is used to serve "old" versioned data during updates. It's expected - // to contain all the SHA-hashed directories from previous versions of Compiler Explorer. - logger.info(" serving archived versions from", archivedVersions); - router.use('/v', express.static(archivedVersions, {maxAge: Infinity, index: false})); - } - router + .use(sFavicon(path.join(staticDir, webpackConfig.output.publicPath, 'favicon.ico'))); + + webServer .use(bodyParser.json({limit: ceProps('bodyParserLimit', maxUploadSize)})) .use(bodyParser.text({limit: ceProps('bodyParserLimit', maxUploadSize), type: () => true})) .use(restreamer()) .use('/source', sourceHandler.handle.bind(sourceHandler)) .use('/api', apiHandler.handle) .use('/g', shortUrlHandler); - - const healthCheck = require('./lib/handlers/health-check'); - webServer - .use(Raven.requestHandler()) - .set('trust proxy', true) - .set('view engine', 'pug') - .use('/healthcheck', new healthCheck.HealthCheckHandler().handle) // before morgan so healthchecks aren't logged - .use(morgan('combined', {stream: logger.stream})) - .use(compression()) - .use(router) - .use(Raven.errorHandler()) - .on('error', err => logger.error('Caught error:', err, "(in web error handler; continuing)")); - - const webAlias = ceProps("web-alias", ""); - if (webAlias) webServer.use(webAlias, router); - _.each(env, e => webServer.use(`/${e}`, router)); logger.info("======================================="); + webServer.use(Raven.errorHandler()); + webServer.on('error', err => logger.error('Caught error:', err, "(in web error handler; continuing)")); webServer.listen(port, hostname); }) .catch(err => { diff --git a/bower.json b/bower.json deleted file mode 100644 index 5a63ac404..000000000 --- a/bower.json +++ /dev/null @@ -1,36 +0,0 @@ -{ - "name": "compiler-explorer", - "description": "Interactively investigate compiler output", - "main": "./app.js", - "authors": [ - "Matt Godbolt" - ], - "license": "BSD-2-Clause", - "homepage": "https://github.com/mattgodbolt/compiler-explorer", - "private": true, - "ignore": [ - "**/.*", - "node_modules", - "bower_components", - "test", - "tests" - ], - "dependencies": { - "requirejs": "^2.3.2", - "underscore": "^1.8.3", - "golden-layout": "^1.5.9", - "jquery": "^3.1.1", - "bootstrap": "^3.3.7", - "selectize": "RabsRincon/selectize.js#master", - "eventEmitter": "^5.1.0", - "lz-string": "^1.4.4", - "clipboard": "^1.5.12", - "raven-js": "^3.10.0", - "es6-promise": "^4.0.5", - "lru-cache": "2.7.3", - "seiyria-bootstrap-slider": "9.7.x", - "big-integer": "https://github.com/peterolson/BigInteger.js.git#^1.6.22", - "file-saver": "filesaver#^1.3.3", - "vis": "4.20.1" - } -} diff --git a/etc/jshintrc.client b/etc/jshintrc.client index ae815b3f0..7d776cc03 100644 --- a/etc/jshintrc.client +++ b/etc/jshintrc.client @@ -2,6 +2,7 @@ "strict": true, "undef": true, "browser": true, - "globals": {"define": false}, + "node": true, + "globals": {"define": false, "monaco": true, "__webpack_public_path__": true}, "esversion": 5 } diff --git a/etc/scripts/pre-commit b/etc/scripts/pre-commit index 96b4f6834..f97124941 100755 --- a/etc/scripts/pre-commit +++ b/etc/scripts/pre-commit @@ -1,5 +1,5 @@ #!/bin/bash -FORBIDDEN='console.log' +FORBIDDEN='console.(log|warn)' FILES_PATTERN='\.(js)(\..+)?$' printf "\033[0;32mRunning tests...\033[0m\n" diff --git a/lib/compilation-env.js b/lib/compilation-env.js index bdb7bb179..d7937c547 100644 --- a/lib/compilation-env.js +++ b/lib/compilation-env.js @@ -101,9 +101,9 @@ CompilationEnvironment.prototype.enqueue = function (job) { try { return job(); } catch (e) { - Raven.captureException(e); - logger.error("Caught promise exception " + e); if (e.stack) logger.info(e.stack); + logger.error("Caught promise exception " + e); + Raven.captureException(e); return Promise.resolve(null); } }; diff --git a/package.json b/package.json index b0e0021e2..3c264719a 100644 --- a/package.json +++ b/package.json @@ -17,41 +17,66 @@ "main": "./app.js", "dependencies": { "aws-sdk": "^2.177.0", + "big-integer": "^1.6.25", "body-parser": "^1.18.2", + "bootstrap": "^3.3.7", + "bootstrap-slider": "^9.9.0", + "clipboard": "^1.7.1", "compiler-opt-info": "0.0.4", "compression": "^1.7.1", "denodeify": "^1.2.1", + "es6-promise": "^4.1.1", "express": "4.16.x", + "file-saver": "^1.3.3", "fs-extra": "0.26.x", + "golden-layout": "^1.5.9", + "html-loader": "^0.5.5", "http-proxy": "^1.16.2", + "jquery": "^3.2.1", "lru-cache": "4.1.1", + "lz-string": "^1.4.4", "monaco-editor": "0.10.1", "morgan": "^1.9.0", "nopt": "3.0.x", "promise-queue": "2.2.3", "pug": "^2.0.0-beta11", "raven": "^2.2.1", + "raven-js": "^3.19.1", + "selectize": "^0.12.4", "serve-favicon": "^2.4.5", "shell-quote": "1.6.x", "temp": "0.8.x", "tree-kill": "^1.2.0", + "uglifyjs-webpack-plugin": "^1.1.8", + "underscore": "^1.8.3", "underscore-node": "*", - "winston": "^2.4.0" + "vis": "4.20.1", + "winston": "^2.4.0", + "wolfy87-eventemitter": "^5.2.3" }, "devDependencies": { "aws-sdk-mock": "^1.7.0", - "bower": "*", "chai": "3.5.x", "chai-as-promised": "^7.1.1", "chai-http": "^3.0.0", "codecov": "^3.0.0", + "copy-webpack-plugin": "^4.1.1", + "css-loader": "^0.28.7", + "extract-text-webpack-plugin": "^3.0.1", + "file-loader": "^1.1.5", "istanbul": "^0.4.5", "jshint": "^2.9.5", "mocha": "^3.3.0", "nock": "^9.1.4", "requirejs": "*", + "style-loader": "^0.19.0", "supervisor": "*", - "uglify-js": "*" + "uglify-js": "*", + "url-loader": "^0.6.2", + "webpack": "^3.6.0", + "webpack-dev-middleware": "^1.12.0", + "webpack-dev-server": "^2.9.4", + "webpack-manifest-plugin": "^1.3.2" }, "scripts": { "test": "mocha --recursive && make test", diff --git a/static/alert.js b/static/alert.js index fbd55c2ca..e67ea78bb 100644 --- a/static/alert.js +++ b/static/alert.js @@ -22,79 +22,77 @@ // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. +"use strict"; -define(function (require) { - "use strict"; - var _ = require('underscore'); - var $ = require('jquery'); +var _ = require('underscore'); +var $ = require('jquery'); - function Alert() { - this.yesHandler = null; - this.noHandler = null; - var yesNo = $('#yes-no'); - yesNo.find('button.yes').click(_.bind(function () { - if (this.yesHandler) this.yesHandler(); - }, this)); - yesNo.find('button.no').click(_.bind(function () { - if (this.noHandler) this.noHandler(); - }, this)); +function Alert() { + this.yesHandler = null; + this.noHandler = null; + var yesNo = $('#yes-no'); + yesNo.find('button.yes').click(_.bind(function () { + if (this.yesHandler) this.yesHandler(); + }, this)); + yesNo.find('button.no').click(_.bind(function () { + if (this.noHandler) this.noHandler(); + }, this)); +} + +Alert.prototype.alert = function (title, body, onClose) { + var modal = $('#alert'); + modal.find('.modal-title').html(title); + modal.find('.modal-body').html(body); + modal.modal(); + if (onClose) { + modal.off('hidden.bs.modal'); + modal.on('hidden.bs.modal', onClose); } +}; - Alert.prototype.alert = function (title, body, onClose) { - var modal = $('#alert'); - modal.find('.modal-title').html(title); - modal.find('.modal-body').html(body); - modal.modal(); - if (onClose) { - modal.off('hidden.bs.modal'); - modal.on('hidden.bs.modal', onClose); - } - }; +Alert.prototype.ask = function (title, question, handlers) { + var modal = $('#yes-no'); + this.yesHandler = handlers.yes; + this.noHandler = handlers.no; + modal.find('.modal-title').html(title); + modal.find('.modal-body').html(question); + modal.modal(); +}; - Alert.prototype.ask = function (title, question, handlers) { - var modal = $('#yes-no'); - this.yesHandler = handlers.yes; - this.noHandler = handlers.no; - modal.find('.modal-title').html(title); - modal.find('.modal-body').html(question); - modal.modal(); - }; +/* Options parameter: + * group: What group this notification is from. Sets data-group's value. Default: none + * collapseSimilar: If set to true, other notifications with the same group will be removed before sending this. (Note that this only has any effect if group is set). Default: true + * alertClass: Space separated classes to give to the notification div element. Default: none + * autoDismiss: If set to true, the notification will fade out and be removed automatically. Default: true + * dismissTime: If allowed by autoDismiss, controls how long the notification will be visible before being automatically removed. Default: 5000ms. Min: 1000ms + */ +Alert.prototype.notify = function (body, options) { + var container = $('#notifications'); + if (!container) return; + var newElement = $(''); + if (!options) options = {}; + // Set defaults + options.collapseSimilar = ("collapseSimilar" in options) ? options.collapseSimilar : true; // Collapse similars by default + options.autoDismiss = ("autoDismiss" in options) ? options.autoDismiss : true; // autoDismiss by default + options.dismissTime = options.dismissTime ? Math.max(1000, options.dismissTime) : 5000; // Dismiss this after 5000ms by default + if (options.group) { + if (options.collapseSimilar) { + // Only collapsing if a group has been specified + container.find('[data-group="' + options.group + '"]').remove(); + } + newElement.attr('data-group', options.group); // Add the group to the data-group + } + if (options.alertClass) { // If we want a custom class, apply it + newElement.addClass(options.alertClass); + } + if (options.autoDismiss) { // Dismiss this after dismissTime + setTimeout(function () { + newElement.fadeOut('slow', function () { + newElement.remove(); + }); + }, options.dismissTime); + } + container.append(newElement); // Add the new notification to the container +}; - /* Options parameter: - * group: What group this notification is from. Sets data-group's value. Default: none - * collapseSimilar: If set to true, other notifications with the same group will be removed before sending this. (Note that this only has any effect if group is set). Default: true - * alertClass: Space separated classes to give to the notification div element. Default: none - * autoDismiss: If set to true, the notification will fade out and be removed automatically. Default: true - * dismissTime: If allowed by autoDismiss, controls how long the notification will be visible before being automatically removed. Default: 5000ms. Min: 1000ms - */ - Alert.prototype.notify = function (body, options) { - var container = $('#notifications'); - if (!container) return; - var newElement = $(''); - if (!options) options = {}; - // Set defaults - options.collapseSimilar = ("collapseSimilar" in options) ? options.collapseSimilar : true; // Collapse similars by default - options.autoDismiss = ("autoDismiss" in options) ? options.autoDismiss : true; // autoDismiss by default - options.dismissTime = options.dismissTime ? Math.max(1000, options.dismissTime) : 5000; // Dismiss this after 5000ms by default - if (options.group) { - if (options.collapseSimilar) { - // Only collapsing if a group has been specified - container.find('[data-group="' + options.group + '"]').remove(); - } - newElement.attr('data-group', options.group); // Add the group to the data-group - } - if (options.alertClass) { // If we want a custom class, apply it - newElement.addClass(options.alertClass); - } - if (options.autoDismiss) { // Dismiss this after dismissTime - setTimeout(function () { - newElement.fadeOut('slow', function () { - newElement.remove(); - }); - }, options.dismissTime); - } - container.append(newElement); // Add the new notification to the container - }; - - return Alert; -}); \ No newline at end of file +module.exports = Alert; diff --git a/static/analytics.js b/static/analytics.js index bafe12f3f..9961db151 100644 --- a/static/analytics.js +++ b/static/analytics.js @@ -23,109 +23,107 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -define(function (require) { - "use strict"; - var options = require('options'); - var Raven = require('raven-js'); - var $ = require('jquery'); +"use strict"; +var options = require('options'); +var Raven = require('raven-js'); +var $ = require('jquery'); - if (options.raven) { - Raven.config(options.raven, { - release: options.release, - environment: options.environment.join("/") - }).install(); - } +if (options.raven) { + Raven.config(options.raven, { + release: options.release, + environment: options.environment.join("/") + }).install(); +} - var gaProxy; - if (options.googleAnalyticsEnabled) { - (function (i, s, o, g, r, a, m) { - i.GoogleAnalyticsObject = r; - i[r] = i[r] || function () { - (i[r].q = i[r].q || []).push(arguments); - }; - i[r].l = 1 * new Date(); - a = s.createElement(o); - m = s.getElementsByTagName(o)[0]; - a.async = 1; - a.src = g; - m.parentNode.insertBefore(a, m); - })(window, document, 'script', '//www.google-analytics.com/analytics.js', 'ga'); - ga('create', options.googleAnalyticsAccount, 'auto'); - ga('send', 'pageview'); - gaProxy = function () { - window.ga.apply(window.ga, arguments); +var gaProxy; +if (options.googleAnalyticsEnabled) { + (function (i, s, o, g, r, a, m) { + i.GoogleAnalyticsObject = r; + i[r] = i[r] || function () { + (i[r].q = i[r].q || []).push(arguments); }; - // fullstory stuff: - window['_fs_debug'] = false; - window['_fs_host'] = 'www.fullstory.com'; - window['_fs_org'] = '2F4NV'; - window['_fs_namespace'] = 'FS'; - (function (m, n, e, t, l, o, g, y) { - if (e in m && m.console && m.console.log) { - m.console.log('FullStory namespace conflict. Please set window["_fs_namespace"].'); - return; - } - g = m[e] = function (a, b) { - g.q ? g.q.push([a, b]) : g._api(a, b); - }; - g.q = []; - o = n.createElement(t); - o.async = 1; - o.src = 'https://' + _fs_host + '/s/fs.js'; - y = n.getElementsByTagName(t)[0]; - y.parentNode.insertBefore(o, y); - g.identify = function (i, v) { - g(l, {uid: i}); - if (v) g(l, v) - }; - g.setUserVars = function (v) { - g(l, v) - }; - g.identifyAccount = function (i, v) { - o = 'account'; - v = v || {}; - v.acctId = i; - g(o, v) - }; - g.clearUserCookie = function (c, d, i) { - if (!c || document.cookie.match('fs_uid=[`;`]*`[`;`]*`[`;`]*`')) { - d = n.domain; - while (1) { - n.cookie = 'fs_uid=;domain=' + d + - ';path=/;expires=' + new Date(0).toUTCString(); - i = d.indexOf('.'); - if (i < 0) break; - d = d.slice(i + 1) - } - } - }; - })(window, document, window['_fs_namespace'], 'script', 'user'); - } else { - gaProxy = function () { - }; - } - - function initialise() { - if (options.embedded) return; - $(function () { - function create_script_element(id, url) { - var el = document.createElement('script'); - el.type = 'text/javascript'; - el.async = true; - el.id = id; - el.src = url; - var s = document.getElementsByTagName('script')[0]; - s.parentNode.insertBefore(el, s); - } - - if (options.sharingEnabled) { - create_script_element('twitter-wjs', 'https://platform.twitter.com/widgets.js'); - } - }); - } - - return { - ga: gaProxy, - initialise: initialise + i[r].l = 1 * new Date(); + a = s.createElement(o); + m = s.getElementsByTagName(o)[0]; + a.async = 1; + a.src = g; + m.parentNode.insertBefore(a, m); + })(window, document, 'script', '//www.google-analytics.com/analytics.js', 'ga'); + ga('create', options.googleAnalyticsAccount, 'auto'); + ga('send', 'pageview'); + gaProxy = function () { + window.ga.apply(window.ga, arguments); }; -}); + // fullstory stuff: + window['_fs_debug'] = false; + window['_fs_host'] = 'www.fullstory.com'; + window['_fs_org'] = '2F4NV'; + window['_fs_namespace'] = 'FS'; + (function (m, n, e, t, l, o, g, y) { + if (e in m && m.console && m.console.log) { + m.console.log('FullStory namespace conflict. Please set window["_fs_namespace"].'); + return; + } + g = m[e] = function (a, b) { + g.q ? g.q.push([a, b]) : g._api(a, b); + }; + g.q = []; + o = n.createElement(t); + o.async = 1; + o.src = 'https://' + _fs_host + '/s/fs.js'; + y = n.getElementsByTagName(t)[0]; + y.parentNode.insertBefore(o, y); + g.identify = function (i, v) { + g(l, {uid: i}); + if (v) g(l, v) + }; + g.setUserVars = function (v) { + g(l, v) + }; + g.identifyAccount = function (i, v) { + o = 'account'; + v = v || {}; + v.acctId = i; + g(o, v) + }; + g.clearUserCookie = function (c, d, i) { + if (!c || document.cookie.match('fs_uid=[`;`]*`[`;`]*`[`;`]*`')) { + d = n.domain; + while (1) { + n.cookie = 'fs_uid=;domain=' + d + + ';path=/;expires=' + new Date(0).toUTCString(); + i = d.indexOf('.'); + if (i < 0) break; + d = d.slice(i + 1) + } + } + }; + })(window, document, window['_fs_namespace'], 'script', 'user'); +} else { + gaProxy = function () { + }; +} + +function initialise() { + if (options.embedded) return; + $(function () { + function create_script_element(id, url) { + var el = document.createElement('script'); + el.type = 'text/javascript'; + el.async = true; + el.id = id; + el.src = url; + var s = document.getElementsByTagName('script')[0]; + s.parentNode.insertBefore(el, s); + } + + if (options.sharingEnabled) { + create_script_element('twitter-wjs', 'https://platform.twitter.com/widgets.js'); + } + }); +} + +module.exports = { + ga: gaProxy, + initialise: initialise +}; diff --git a/static/asm-mode.js b/static/asm-mode.js index 87f45cca1..3a230c651 100644 --- a/static/asm-mode.js +++ b/static/asm-mode.js @@ -22,103 +22,100 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -define(function (require) { - "use strict"; - var monaco = require('monaco'); +"use strict"; - function definition() { - return { - // Set defaultToken to invalid to see what you do not tokenize yet - defaultToken: 'invalid', +function definition() { + return { + // Set defaultToken to invalid to see what you do not tokenize yet + defaultToken: 'invalid', - // C# style strings - escapes: /\\(?:[abfnrtv\\"']|x[0-9A-Fa-f]{1,4}|u[0-9A-Fa-f]{4}|U[0-9A-Fa-f]{8})/, + // C# style strings + escapes: /\\(?:[abfnrtv\\"']|x[0-9A-Fa-f]{1,4}|u[0-9A-Fa-f]{4}|U[0-9A-Fa-f]{8})/, - registers: /%?\b(r[0-9]+[dbw]?|([er]?([abcd][xhl]|cs|fs|ds|ss|sp|bp|ip|sil?|dil?))|[xyz]mm[0-9]+|sp|fp|lr)\b/, + registers: /%?\b(r[0-9]+[dbw]?|([er]?([abcd][xhl]|cs|fs|ds|ss|sp|bp|ip|sil?|dil?))|[xyz]mm[0-9]+|sp|fp|lr)\b/, - intelOperators: /PTR|(D|Q|[XYZ]MM)?WORD/, + intelOperators: /PTR|(D|Q|[XYZ]MM)?WORD/, - tokenizer: { - root: [ - // Error document - [/^<.*>$/, {token: 'annotation'}], - // Label definition - [/^[.a-zA-Z0-9_$?@].*:/, {token: 'type.identifier', next: '@rest'}], - // Label definition (ARM style) - [/^\s*[|][^|]*[|]/, {token: 'type.identifier', next: '@rest'}], - // Label definition (CL style) - [/^\s*[.a-zA-Z0-9_$|]*\s*(PROC|ENDP|DB|DD)/, {token: 'type.identifier', next: '@rest'}], - // Constant definition - [/^[.a-zA-Z0-9_$?@][^=]*=/, {token: 'type.identifier', next: '@rest'}], - // opcode - [/[.a-zA-Z_][.a-zA-Z_0-9]*/, {token: 'keyword', next: '@rest'}], + tokenizer: { + root: [ + // Error document + [/^<.*>$/, {token: 'annotation'}], + // Label definition + [/^[.a-zA-Z0-9_$?@].*:/, {token: 'type.identifier', next: '@rest'}], + // Label definition (ARM style) + [/^\s*[|][^|]*[|]/, {token: 'type.identifier', next: '@rest'}], + // Label definition (CL style) + [/^\s*[.a-zA-Z0-9_$|]*\s*(PROC|ENDP|DB|DD)/, {token: 'type.identifier', next: '@rest'}], + // Constant definition + [/^[.a-zA-Z0-9_$?@][^=]*=/, {token: 'type.identifier', next: '@rest'}], + // opcode + [/[.a-zA-Z_][.a-zA-Z_0-9]*/, {token: 'keyword', next: '@rest'}], - // whitespace - {include: '@whitespace'} - ], + // whitespace + {include: '@whitespace'} + ], - rest: [ - // pop at the beginning of the next line and rematch - [/^.*$/, {token: '@rematch', next: '@pop'}], + rest: [ + // pop at the beginning of the next line and rematch + [/^.*$/, {token: '@rematch', next: '@pop'}], - [/@registers/, 'variable.predefined'], - [/@intelOperators/, 'annotation'], - // brackets - [/[{}<>()\[\]]/, '@brackets'], + [/@registers/, 'variable.predefined'], + [/@intelOperators/, 'annotation'], + // brackets + [/[{}<>()\[\]]/, '@brackets'], - // ARM-style label reference - [/[|][^|]*[|]*/, 'type.identifier'], + // ARM-style label reference + [/[|][^|]*[|]*/, 'type.identifier'], - // numbers - [/\d*\.\d+([eE][\-+]?\d+)?/, 'number.float'], - [/([$]|0[xX])[0-9a-fA-F]+/, 'number.hex'], - [/\d+/, 'number'], - // ARM-style immediate numbers (which otherwise look like comments) - [/#-?\d+/, 'number'], + // numbers + [/\d*\.\d+([eE][\-+]?\d+)?/, 'number.float'], + [/([$]|0[xX])[0-9a-fA-F]+/, 'number.hex'], + [/\d+/, 'number'], + // ARM-style immediate numbers (which otherwise look like comments) + [/#-?\d+/, 'number'], - // operators - [/[-+,*\/!:&]/, 'operator'], + // operators + [/[-+,*\/!:&]/, 'operator'], - // strings - [/"([^"\\]|\\.)*$/, 'string.invalid'], // non-terminated string - [/"/, {token: 'string.quote', bracket: '@open', next: '@string'}], + // strings + [/"([^"\\]|\\.)*$/, 'string.invalid'], // non-terminated string + [/"/, {token: 'string.quote', bracket: '@open', next: '@string'}], - // characters - [/'[^\\']'/, 'string'], - [/(')(@escapes)(')/, ['string', 'string.escape', 'string']], - [/'/, 'string.invalid'], + // characters + [/'[^\\']'/, 'string'], + [/(')(@escapes)(')/, ['string', 'string.escape', 'string']], + [/'/, 'string.invalid'], - // Assume anything else is a label reference - [/%?[.?_$a-zA-Z@][.?_$a-zA-Z0-9@]*/, 'type.identifier'], + // Assume anything else is a label reference + [/%?[.?_$a-zA-Z@][.?_$a-zA-Z0-9@]*/, 'type.identifier'], - // whitespace - {include: '@whitespace'} - ], + // whitespace + {include: '@whitespace'} + ], - comment: [ - [/[^\/*]+/, 'comment'], - [/\/\*/, 'comment', '@push'], // nested comment - ["\\*/", 'comment', '@pop'], - [/[\/*]/, 'comment'] - ], + comment: [ + [/[^\/*]+/, 'comment'], + [/\/\*/, 'comment', '@push'], // nested comment + ["\\*/", 'comment', '@pop'], + [/[\/*]/, 'comment'] + ], - string: [ - [/[^\\"]+/, 'string'], - [/@escapes/, 'string.escape'], - [/\\./, 'string.escape.invalid'], - [/"/, {token: 'string.quote', bracket: '@close', next: '@pop'}] - ], + string: [ + [/[^\\"]+/, 'string'], + [/@escapes/, 'string.escape'], + [/\\./, 'string.escape.invalid'], + [/"/, {token: 'string.quote', bracket: '@close', next: '@pop'}] + ], - whitespace: [ - [/[ \t\r\n]+/, 'white'], - [/\/\*/, 'comment', '@comment'], - [/\/\/.*$/, 'comment'], - [/[#;\\@].*$/, 'comment'] - ] - } - }; - } + whitespace: [ + [/[ \t\r\n]+/, 'white'], + [/\/\*/, 'comment', '@comment'], + [/\/\/.*$/, 'comment'], + [/[#;\\@].*$/, 'comment'] + ] + } + }; +} - monaco.languages.register({id: 'asm'}); - monaco.languages.setMonarchTokensProvider('asm', definition()); -}); +monaco.languages.register({id: 'asm'}); +monaco.languages.setMonarchTokensProvider('asm', definition()); diff --git a/static/ast-view.js b/static/ast-view.js index c3f43962a..fc8ff6481 100644 --- a/static/ast-view.js +++ b/static/ast-view.js @@ -22,131 +22,138 @@ // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. +"use strict"; -define(function (require) { - "use strict"; +var FontScale = require('fontscale'); +var monaco = require('monaco'); +var _ = require('underscore'); +var $ = require('jquery'); - var FontScale = require('fontscale'); - var monaco = require('monaco'); - var _ = require('underscore'); - var $ = require('jquery'); +function Ast(hub, container, state) { + this.container = container; + this.eventHub = hub.createEventHub(); + this.domRoot = container.getElement(); + this.domRoot.html($('#ast').html()); + this._currentDecorations = []; + this.astEditor = monaco.editor.create(this.domRoot.find(".monaco-placeholder")[0], { + value: "", + scrollBeyondLastLine: false, + language: 'cppp', //we only support cpp for now + readOnly: true, + glyphMargin: true, + fontFamily: 'monospace', + quickSuggestions: false, + fixedOverflowWidgets: true, + minimap: { + maxColumn: 80 + }, + lineNumbersMinChars: 3 + }); - function Ast(hub, container, state) { - this.container = container; - this.eventHub = hub.createEventHub(); - this.domRoot = container.getElement(); - this.domRoot.html($('#ast').html()); - this._currentDecorations = []; - this.astEditor = monaco.editor.create(this.domRoot.find(".monaco-placeholder")[0], { - value: "", - scrollBeyondLastLine: false, - language: 'cppp', //we only support cpp for now - readOnly: true, - glyphMargin: true, - fontFamily: 'monospace', - quickSuggestions: false, - fixedOverflowWidgets: true, - minimap: { - maxColumn: 80 - }, - lineNumbersMinChars: 3 - }); + this._compilerid = state.id; + this._compilerName = state.compilerName; + this._editorid = state.editorid; + this.fontScale = new FontScale(this.domRoot, state, this.astEditor); + this.fontScale.on('change', _.bind(this.updateState, this)); - this._compilerid = state.id; - this._compilerName = state.compilerName; - this._editorid = state.editorid; - this.fontScale = new FontScale(this.domRoot, state, this.astEditor); - this.fontScale.on('change', _.bind(this.updateState, this)); + this.container.on('destroy', this.close, this); - this.container.on('destroy', this.close, this); + this.eventHub.on('compileResult', this.onCompileResult, this); + this.eventHub.on('compiler', this.onCompiler, this); + this.eventHub.on('compilerClose', this.onCompilerClose, this); + this.eventHub.on('editorChange', this.onEditorChange, this); + this.eventHub.on('settingsChange', this.onSettingsChange, this); + this.eventHub.emit('astViewOpened', this._compilerid); + this.eventHub.emit('requestSettings'); - this.eventHub.on('compileResult', this.onCompileResult, this); - this.eventHub.on('compiler', this.onCompiler, this); - this.eventHub.on('compilerClose', this.onCompilerClose, this); - this.eventHub.on('editorChange', this.onEditorChange, this); - this.eventHub.on('settingsChange', this.onSettingsChange, this); - this.eventHub.emit('astViewOpened', this._compilerid); - this.eventHub.emit('requestSettings'); + container.on('resize', this.resize, this); + container.on('shown', this.resize, this); + if (state && state.astOutput) { + this.showAstResults(state.astOutput); + } + this.setTitle(); +} - container.on('resize', this.resize, this); - container.on('shown', this.resize, this); - if (state && state.astOutput) { - this.showAstResults(state.astOutput); +// TODO: de-dupe with compiler etc +Ast.prototype.resize = function () { + var topBarHeight = this.domRoot.find(".top-bar").outerHeight(true); + this.astEditor.layout({ + width: this.domRoot.width(), + height: this.domRoot.height() - topBarHeight + }); +}; + +Ast.prototype.onEditorChange = function (id, source) { +}; + +Ast.prototype.onCompileResult = function (id, compiler, result) { + if (this._compilerid == id) { + if (result.hasAstOutput) { + this.showAstResults(result.astOutput); } + else { + this.showAstResults(""); + } + } +}; +Ast.prototype.setTitle = function () { + this.container.setTitle(this._compilerName + " Ast Viewer (Editor #" + this._editorid + ", Compiler #" + this._compilerid + ")"); +}; + +Ast.prototype.getDisplayableAst = function (astResult) { + return "**" + astResult.astType + "** - " + astResult.displayString; +}; + +Ast.prototype.showAstResults = function (results) { + this.astEditor.setValue(results); +}; + +Ast.prototype.onCompiler = function (id, compiler, options, editorid) { + if (id == this._compilerid) { + this._compilerName = compiler ? compiler.name : ''; + this._editorid = editorid; this.setTitle(); } +}; - // TODO: de-dupe with compiler etc - Ast.prototype.resize = function () { - var topBarHeight = this.domRoot.find(".top-bar").outerHeight(true); - this.astEditor.layout({ - width: this.domRoot.width(), - height: this.domRoot.height() - topBarHeight - }); - }; +Ast.prototype.onCompilerClose = function (id) { + if (id === this._compilerid) { + // We can't immediately close as an outer loop somewhere in GoldenLayout is iterating over + // the hierarchy. We can't modify while it's being iterated over. + _.defer(function (self) { + self.container.close(); + }, this); + } +}; - Ast.prototype.onEditorChange = function (id, source) { - }; +Ast.prototype.updateState = function () { +}; - Ast.prototype.onCompileResult = function (id, compiler, result) { - if (this._compilerid == id) { - if (result.hasAstOutput) { - this.showAstResults(result.astOutput); - } - else { - this.showAstResults(""); - } +Ast.prototype.onCompilerClose = function (id) { + if (id === this._compilerid) { + // We can't immediately close as an outer loop somewhere in GoldenLayout is iterating over + // the hierarchy. We can't modify while it's being iterated over. + this.close(); + _.defer(function (self) { + self.container.close(); + }, this); + } +}; + +Ast.prototype.onSettingsChange = function (newSettings) { + this.astEditor.updateOptions({ + minimap: { + enabled: newSettings.showMinimap } - }; - Ast.prototype.setTitle = function () { - this.container.setTitle(this._compilerName + " Ast Viewer (Editor #" + this._editorid + ", Compiler #" + this._compilerid + ")"); - }; + }); +}; - Ast.prototype.getDisplayableAst = function (astResult) { - return "**" + astResult.astType + "** - " + astResult.displayString; - }; +Ast.prototype.close = function () { + this.eventHub.unsubscribe(); + this.eventHub.emit("astViewClosed", this._compilerid); + this.astEditor.dispose(); +}; - Ast.prototype.showAstResults = function (results) { - this.astEditor.setValue(results); - }; - - Ast.prototype.onCompiler = function (id, compiler, options, editorid) { - if (id == this._compilerid) { - this._compilerName = compiler ? compiler.name : ''; - this._editorid = editorid; - this.setTitle(); - } - }; - - Ast.prototype.onCompilerClose = function (id) { - if (id === this._compilerid) { - // We can't immediately close as an outer loop somewhere in GoldenLayout is iterating over - // the hierarchy. We can't modify while it's being iterated over. - this.close(); - _.defer(function (self) { - self.container.close(); - }, this); - } - }; - - Ast.prototype.updateState = function () { - }; - - Ast.prototype.onSettingsChange = function (newSettings) { - this.astEditor.updateOptions({ - minimap: { - enabled: newSettings.showMinimap - } - }); - }; - - Ast.prototype.close = function () { - this.eventHub.unsubscribe(); - this.eventHub.emit("astViewClosed", this._compilerid); - this.astEditor.dispose(); - }; - - return { - Ast: Ast - }; -}); +module.exports = { + Ast: Ast +}; diff --git a/static/cfg-view.js b/static/cfg-view.js index 5b2b4cadb..0b60ea2f7 100644 --- a/static/cfg-view.js +++ b/static/cfg-view.js @@ -23,154 +23,146 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -define(function (require) { - 'use strict'; +'use strict'; - var $ = require('jquery'); - var vis = require('vis'); - var _ = require('underscore'); - require('selectize'); +var $ = require('jquery'); +var vis = require('vis'); +var _ = require('underscore'); - function Cfg(hub, container, state) { - this.container = container; - this.eventHub = hub.createEventHub(); - this.domRoot = container.getElement(); - this.domRoot.html($('#cfg').html()); - this.defaultCfgOutput = {nodes: [{id: 0, shape: 'box', label: 'No Output'}], edges: []}; - this.binaryModeSupport = { - nodes: [{ - id: 0, - shape: 'box', - label: 'Cfg mode cannot be used when the binary filter is set' - }], edges: [] - }; - // Note that this might be outdated if no functions were present when creating the link, but that's handled - // by selectize - this.currentFunc = state.selectedFn || ''; - this.functions = []; - this.networkOpts = { - autoResize: true, - locale: 'en', - edges: { - arrows: {to: {enabled: true}}, - smooth: {enabled: true}, - physics: false - }, - nodes: { - font: {face: 'monospace', align: 'left'} - }, - layout: { - improvedLayout: true, - hierarchical: { - enabled: true, - sortMethod: 'directed', - direction: 'UD', - nodeSpacing: 100, - levelSeparation: 150 - } - }, - physics: { - hierarchicalRepulsion: { - nodeDistance: 125 - } - }, - interaction: { - navigationButtons: false, - keyboard: { - enabled: true, - speed: {x: 10, y: 10, zoom: 0.03}, - bindToWindow: false - } +require('selectize'); +require("vis/dist/vis.css"); + +function Cfg(hub, container, state) { + this.container = container; + this.eventHub = hub.createEventHub(); + this.domRoot = container.getElement(); + this.domRoot.html($('#cfg').html()); + this.defaultCfgOutput = {nodes: [{id: 0, shape: 'box', label: 'No Output'}], edges: []}; + this.binaryModeSupport = { + nodes: [{ + id: 0, + shape: 'box', + label: 'Cfg mode cannot be used when the binary filter is set' + }], edges: [] + }; + // Note that this might be outdated if no functions were present when creating the link, but that's handled + // by selectize + this.currentFunc = state.selectedFn || ''; + this.functions = []; + this.networkOpts = { + autoResize: true, + locale: 'en', + edges: { + arrows: {to: {enabled: true}}, + smooth: {enabled: true}, + physics: false + }, + nodes: { + font: {face: 'monospace', align: 'left'} + }, + layout: { + improvedLayout: true, + hierarchical: { + enabled: true, + sortMethod: 'directed', + direction: 'UD', + nodeSpacing: 100, + levelSeparation: 150 } - }; - - this.cfgVisualiser = new vis.Network(this.domRoot.find('.graph-placeholder')[0], - this.defaultCfgOutput, this.networkOpts); - this.domRoot.find('.show-hide-btn').on('click', _.bind(function () { - this.networkOpts.interaction.navigationButtons = !this.networkOpts.interaction.navigationButtons; - this.cfgVisualiser.setOptions(this.networkOpts); - }, this)); - - this.compilerId = state.id; - this._editorid = state.editorid; - this._binaryFilter = false; - - this.functionPicker = $(this.domRoot).find('.function-picker').selectize({ - sortField: 'name', - valueField: 'name', - labelField: 'name', - searchField: ['name'] - }).on('change', _.bind(function (e) { - var selectedFn = this.functions[e.target.value]; - if (selectedFn) { - this.currentFunc = e.target.value; - this.showCfgResults({ - nodes: selectedFn.nodes, - edges: selectedFn.edges - }); - this.cfgVisualiser.selectNodes([selectedFn.nodes[0].id]); - this.saveState(); + }, + physics: { + hierarchicalRepulsion: { + nodeDistance: 125 } - }, this)); - - this.eventHub.on('compilerClose', this.onCompilerClose, this); - this.eventHub.on('compileResult', this.onCompileResult, this); - this.eventHub.on('compiler', this.onCompiler, this); - this.eventHub.on('filtersChange', this.onFiltersChange, this); - - this.container.on('destroy', this.close, this); - this.container.on('resize', this.resize, this); - this.container.on('shown', this.resize, this); - this.eventHub.emit('cfgViewOpened', this.compilerId); - this.eventHub.emit('requestFilters', this.compilerId); - this.eventHub.emit('requestCompiler', this.compilerId); - - this.adaptStructure = function (names) { - return _.map(names, function (name) {return {name: name};}); - }; - - this.setTitle(); - } - - Cfg.prototype.onCompileResult = function (id, compiler, result) { - if (this.compilerId === id) { - var functionNames = []; - if (this.supportsCfg && !$.isEmptyObject(result.cfg)) { - this.functions = result.cfg; - functionNames = Object.keys(this.functions); - if (functionNames.indexOf(this.currentFunc) === -1) { - this.currentFunc = functionNames[0]; - } - this.showCfgResults({ - nodes: this.functions[this.currentFunc].nodes, - edges: this.functions[this.currentFunc].edges - }); - this.cfgVisualiser.selectNodes([this.functions[this.currentFunc].nodes[0].id]); - } else { - // We don't reset the current function here as we would lose the saved one if this happened at the begining - // (Hint: It *does* happen) - this.showCfgResults(this._binaryFilter ? this.binaryModeSupport : this.defaultCfgOutput); + }, + interaction: { + navigationButtons: false, + keyboard: { + enabled: true, + speed: {x: 10, y: 10, zoom: 0.03}, + bindToWindow: false } - - this.functionPicker[0].selectize.clearOptions(); - this.functionPicker[0].selectize.addOption(functionNames.length ? this.adaptStructure(functionNames) : {name: 'The input does not contain functions'}); - this.functionPicker[0].selectize.refreshOptions(false); - - this.functionPicker[0].selectize.clear(); - this.functionPicker[0].selectize.addItem(functionNames.length ? this.currentFunc : 'The input does not contain functions', true); - this.saveState(); } }; - Cfg.prototype.setTitle = function () { - this.container.setTitle((this._compilerName || '') + ' Graph Viewer (Editor #' + this._editorid + ', Compiler #' + this.compilerId + ')'); + this.cfgVisualiser = new vis.Network(this.domRoot.find('.graph-placeholder')[0], + this.defaultCfgOutput, this.networkOpts); + this.domRoot.find('.show-hide-btn').on('click', _.bind(function () { + this.networkOpts.interaction.navigationButtons = !this.networkOpts.interaction.navigationButtons; + this.cfgVisualiser.setOptions(this.networkOpts); + }, this)); + + this.compilerId = state.id; + this._editorid = state.editorid; + this._binaryFilter = false; + + this.functionPicker = $(this.domRoot).find('.function-picker').selectize({ + sortField: 'name', + valueField: 'name', + labelField: 'name', + searchField: ['name'] + }).on('change', _.bind(function (e) { + var selectedFn = this.functions[e.target.value]; + if (selectedFn) { + this.currentFunc = e.target.value; + this.showCfgResults({ + nodes: selectedFn.nodes, + edges: selectedFn.edges + }); + this.cfgVisualiser.selectNodes([selectedFn.nodes[0].id]); + this.saveState(); + } + }, this)); + + this.eventHub.on('compilerClose', this.onCompilerClose, this); + this.eventHub.on('compileResult', this.onCompileResult, this); + this.eventHub.on('compiler', this.onCompiler, this); + this.eventHub.on('filtersChange', this.onFiltersChange, this); + + this.container.on('destroy', this.close, this); + this.container.on('resize', this.resize, this); + this.container.on('shown', this.resize, this); + this.eventHub.emit('cfgViewOpened', this.compilerId); + this.eventHub.emit('requestFilters', this.compilerId); + this.eventHub.emit('requestCompiler', this.compilerId); + + this.adaptStructure = function (names) { + return _.map(names, function (name) {return {name: name};}); }; - Cfg.prototype.showCfgResults = function (data) { - this.cfgVisualiser.setData(data); - }; + this.setTitle(); +} - Cfg.prototype.onCompiler = function (id, compiler) { +Cfg.prototype.onCompileResult = function (id, compiler, result) { + if (this._compilerid === id) { + var functionNames = []; + if (result.supportsCfg && !$.isEmptyObject(result.cfg)) { + this.functions = result.cfg; + functionNames = Object.keys(this.functions); + if (functionNames.indexOf(this.currentFunc) === -1) { + this.currentFunc = functionNames[0]; + } + this.showCfgResults({ + nodes: this.functions[this.currentFunc].nodes, + edges: this.functions[this.currentFunc].edges + }); + this.cfgVisualiser.selectNodes([this.functions[this.currentFunc].nodes[0].id]); + } else { + // We don't reset the current function here as we would lose the saved one if this happened at the begining + // (Hint: It *does* happen) + this.showCfgResults(this._binaryFilter ? this.binaryModeSupport : this.defaultCfgOutput); + } + + this.functionPicker[0].selectize.clearOptions(); + this.functionPicker[0].selectize.addOption(functionNames.length ? this.adaptStructure(functionNames) : {name: 'The input does not contain functions'}); + this.functionPicker[0].selectize.refreshOptions(false); + + this.functionPicker[0].selectize.clear(); + this.functionPicker[0].selectize.addItem(functionNames.length ? this.currentFunc : 'The input does not contain any function', true); + this.saveState(); + } +}; +Cfg.prototype.onCompiler = function (id, compiler) { if (id === this.compilerId) { this._compilerName = compiler ? compiler.name : ''; this.supportsCfg = compiler.supportsCfg; @@ -178,51 +170,62 @@ define(function (require) { } }; - Cfg.prototype.onFiltersChange = function (id, filters) { - if (this.compilerId === id) { - this._binaryFilter = filters.binary; - } - }; +Cfg.prototype.onFiltersChange = function (id, filters) { + if (this.compilerId === id) { + this._binaryFilter = filters.binary; + } +}; - Cfg.prototype.resize = function () { - if (this.cfgVisualiser.canvas) { - var height = this.domRoot.height() - this.domRoot.find('.top-bar').outerHeight(true); - this.cfgVisualiser.setSize('100%', height.toString()); - this.cfgVisualiser.redraw(); - } - }; +Cfg.prototype.resize = function () { + if (this.cfgVisualiser.canvas) { + var height = this.domRoot.height() - this.domRoot.find('.top-bar').outerHeight(true); + this.cfgVisualiser.setSize('100%', height.toString()); + this.cfgVisualiser.redraw(); + } +}; - Cfg.prototype.saveState = function () { - this.container.setState(this.currentState()); - }; +Cfg.prototype.setTitle = function () { + this.container.setTitle(this._compilerName + ' Graph Viewer (Editor #' + this._editorid + ', Compiler #' + this._compilerid + ')'); +}; - Cfg.prototype.currentState = function () { - return { - id: this.compilerId, - editorid: this._editorid, - selectedFn: this.currentFunc - }; - }; +Cfg.prototype.showCfgResults = function (data) { + this.cfgVisualiser.setData(data); +}; - Cfg.prototype.onCompilerClose = function (compilerId) { - if (this.compilerId === compilerId) { - // We can't immediately close as an outer loop somewhere in GoldenLayout is iterating over - // the hierarchy. We can't modify while it's being iterated over. - this.close(); - _.defer(function (self) { - self.container.close(); - }, this); - } - }; - Cfg.prototype.close = function () { - this.eventHub.unsubscribe(); - this.eventHub.emit('cfgViewClosed', this.compilerId); - this.cfgVisualiser.destroy(); - }; +Cfg.prototype.onCompilerClose = function (compilerId) { + if (this.compilerId === compilerId) { + // We can't immediately close as an outer loop somewhere in GoldenLayout is iterating over + // the hierarchy. We can't modify while it's being iterated over. + this.close(); + _.defer(function (self) { + self.container.close(); + }, this); + } +}; +Cfg.prototype.close = function () { + this.eventHub.unsubscribe(); + this.eventHub.emit('cfgViewClosed', this.compilerId); + this.cfgVisualiser.destroy(); +}; + + + +Cfg.prototype.saveState = function () { + this.container.setState(this.currentState()); +}; + +Cfg.prototype.currentState = function () { return { - Cfg: Cfg + id: this.compilerId, + editorid: this._editorid, + selectedFn: this.currentFunc }; -}); +}; + + +module.exports = { + Cfg: Cfg +}; diff --git a/static/colour.js b/static/colour.js index 174a55a3a..1749d3888 100644 --- a/static/colour.js +++ b/static/colour.js @@ -22,42 +22,38 @@ // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. +"use strict"; -define(function (require) { - "use strict"; +var _ = require('underscore'); - var _ = require('underscore'); - var monaco = require('monaco'); +// themes is an array so one scheme can be used in multiple places. If you want to use it everywhere, ['all'] should suffice +var schemes = [ + {name: 'rainbow', desc: 'Rainbow 1', count: 12, themes: ['default']}, + {name: 'rainbow2', desc: 'Rainbow 2', count: 12, themes: ['default']}, + {name: 'earth', desc: 'Earth tones (colourblind safe)', count: 9, themes: ['default']}, + {name: 'green-blue', desc: 'Greens and blues (colourblind safe)', count: 4, themes: ['default']}, + {name: 'gray-shade', desc: 'Gray shades', count: 4, themes: ['dark']} +]; - // themes is an array so one scheme can be used in multiple places. If you want to use it everywhere, ['all'] should suffice - var schemes = [ - {name: 'rainbow', desc: 'Rainbow 1', count: 12, themes: ['default']}, - {name: 'rainbow2', desc: 'Rainbow 2', count: 12, themes: ['default']}, - {name: 'earth', desc: 'Earth tones (colourblind safe)', count: 9, themes: ['default']}, - {name: 'green-blue', desc: 'Greens and blues (colourblind safe)', count: 4, themes: ['default']}, - {name: 'gray-shade', desc: 'Gray shades', count: 4, themes: ['dark']} - ]; - - function applyColours(editor, colours, schemeName, prevDecorations) { - var scheme = _.findWhere(schemes, {name: schemeName}); - if (!scheme) { - scheme = schemes[0]; - } - var newDecorations = _.map(colours, function (ordinal, line) { - line = parseInt(line) + 1; - return { - range: new monaco.Range(line, 1, line, 1), - options: { - isWholeLine: true, - className: scheme.name + "-" + (ordinal % scheme.count) - } - }; - }); - return editor.deltaDecorations(prevDecorations, newDecorations); +function applyColours(editor, colours, schemeName, prevDecorations) { + var scheme = _.findWhere(schemes, {name: schemeName}); + if (!scheme) { + scheme = schemes[0]; } + var newDecorations = _.map(colours, function (ordinal, line) { + line = parseInt(line) + 1; + return { + range: new monaco.Range(line, 1, line, 1), + options: { + isWholeLine: true, + className: scheme.name + "-" + (ordinal % scheme.count) + } + }; + }); + return editor.deltaDecorations(prevDecorations, newDecorations); +} - return { - applyColours: applyColours, - schemes: schemes - }; -}); +module.exports = { + applyColours: applyColours, + schemes: schemes +}; diff --git a/static/compiler-service.js b/static/compiler-service.js index 538c08214..66b94ba59 100644 --- a/static/compiler-service.js +++ b/static/compiler-service.js @@ -23,122 +23,120 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -define(function (require) { - "use strict"; - var $ = require('jquery'); - var _ = require('underscore'); - var LruCache = require('lru-cache'); - var options = require('options'); - var Promise = require('es6-promise').Promise; +"use strict"; +var $ = require('jquery'); +var _ = require('underscore'); +var LruCache = require('lru-cache'); +var options = require('options'); +var Promise = require('es6-promise').Promise; - function CompilerService() { - this.cache = new LruCache({ - max: 200 * 1024, - length: function (n) { - return JSON.stringify(n).length; - } - }); - this.compilersByLang = {}; - _.each(options.compilers, function (compiler) { - if (!this.compilersByLang[compiler.lang]) this.compilersByLang[compiler.lang] = {}; - this.compilersByLang[compiler.lang][compiler.id] = compiler; - if (compiler.alias) { - this.compilersByLang[compiler.lang][compiler.alias] = compiler; - } - }, this); +function CompilerService() { + this.cache = new LruCache({ + max: 200 * 1024, + length: function (n) { + return JSON.stringify(n).length; + } + }); + this.compilersByLang = {}; + _.each(options.compilers, function (compiler) { + if (!this.compilersByLang[compiler.lang]) this.compilersByLang[compiler.lang] = {}; + this.compilersByLang[compiler.lang][compiler.id] = compiler; + if (compiler.alias) { + this.compilersByLang[compiler.lang][compiler.alias] = compiler; + } + }, this); +} + +CompilerService.prototype.getCompilersForLang = function (langId) { + return this.compilersByLang[langId] || {}; +}; + +CompilerService.prototype.findCompiler = function (langId, compilerId) { + if (!compilerId) return null; + var compilers = this.getCompilersForLang(langId); + if (compilers && compilers[compilerId]) { + return compilers[compilerId]; } + return _.find(compilers, function (compiler) { + return compiler.alias === compilerId; + }); +}; - CompilerService.prototype.getCompilersForLang = function (langId) { - return this.compilersByLang[langId] || {}; - }; - - CompilerService.prototype.findCompiler = function (langId, compilerId) { - if (!compilerId) return null; - var compilers = this.getCompilersForLang(langId); - if (compilers && compilers[compilerId]) { - return compilers[compilerId]; - } - return _.find(compilers, function (compiler) { - return compiler.alias === compilerId; +CompilerService.prototype.submit = function (request) { + var jsonRequest = JSON.stringify(request); + var cachedResult = this.cache.get(jsonRequest); + if (cachedResult) { + return Promise.resolve({ + request: request, + result: cachedResult, + localCacheHit: true }); - }; - - CompilerService.prototype.submit = function (request) { - var jsonRequest = JSON.stringify(request); - var cachedResult = this.cache.get(jsonRequest); - if (cachedResult) { - return Promise.resolve({ - request: request, - result: cachedResult, - localCacheHit: true - }); - } - return new Promise(_.bind(function (resolve, reject) { - $.ajax({ - type: 'POST', - url: 'api/compiler/' + encodeURIComponent(request.compiler) + '/compile', - dataType: 'json', - contentType: 'application/json', - data: jsonRequest, - success: _.bind(function (result) { - if (result && result.okToCache) { - this.cache.set(jsonRequest, result); - } - resolve({ - request: request, - result: result, - localCacheHit: false - }); - }, this), - error: function (xhr, textStatus, errorThrown) { - var error = errorThrown; - if (!error) { - switch (textStatus) { - case "timeout": - error = "Request timed out"; - break; - case "abort": - error = "Request was aborted"; - break; - default: - error = "Error sending request"; - break; - } - } - reject({ - request: request, - error: error - }); + } + return new Promise(_.bind(function (resolve, reject) { + $.ajax({ + type: 'POST', + url: 'api/compiler/' + encodeURIComponent(request.compiler) + '/compile', + dataType: 'json', + contentType: 'application/json', + data: jsonRequest, + success: _.bind(function (result) { + if (result && result.okToCache) { + this.cache.set(jsonRequest, result); } - }); - }, this)); - }; - - CompilerService.prototype.expand = function (source) { - var includeFind = /^\s*#include\s*["<](https?:\/\/[^>"]+)[>"]/; - var lines = source.split("\n"); - var promises = []; - _.each(lines, function (line, lineNumZeroBased) { - var match = line.match(includeFind); - if (match) { - promises.push(new Promise(function (resolve, reject) { - var req = $.get(match[1], function (data) { - data = '#line 1 "' + match[1] + '"\n' + data + '\n\n#line ' + - (lineNumZeroBased + 1) + ' ""\n'; - - lines[lineNumZeroBased] = data; - resolve(); - }); - req.fail(function () { - resolve(); - }); - })); + resolve({ + request: request, + result: result, + localCacheHit: false + }); + }, this), + error: function (xhr, textStatus, errorThrown) { + var error = errorThrown; + if (!error) { + switch (textStatus) { + case "timeout": + error = "Request timed out"; + break; + case "abort": + error = "Request was aborted"; + break; + default: + error = "Error sending request"; + break; + } + } + reject({ + request: request, + error: error + }); } }); - return Promise.all(promises).then(function () { - return lines.join("\n"); - }); - }; + }, this)); +}; - return CompilerService; -}); +CompilerService.prototype.expand = function (source) { + var includeFind = /^\s*#include\s*["<](https?:\/\/[^>"]+)[>"]/; + var lines = source.split("\n"); + var promises = []; + _.each(lines, function (line, lineNumZeroBased) { + var match = line.match(includeFind); + if (match) { + promises.push(new Promise(function (resolve, reject) { + var req = $.get(match[1], function (data) { + data = '#line 1 "' + match[1] + '"\n' + data + '\n\n#line ' + + (lineNumZeroBased + 1) + ' ""\n'; + + lines[lineNumZeroBased] = data; + resolve(); + }); + req.fail(function () { + resolve(); + }); + })); + } + }); + return Promise.all(promises).then(function () { + return lines.join("\n"); + }); +}; + +module.exports = CompilerService; diff --git a/static/compiler.js b/static/compiler.js index 7ccf20b56..23ee5a645 100644 --- a/static/compiler.js +++ b/static/compiler.js @@ -23,1244 +23,1243 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -define(function (require) { - 'use strict'; - var $ = require('jquery'); - var _ = require('underscore'); - var ga = require('analytics').ga; - var colour = require('colour'); - var Toggles = require('toggles'); - var FontScale = require('fontscale'); - var Promise = require('es6-promise').Promise; - var Components = require('components'); - var LruCache = require('lru-cache'); - var options = require('options'); - var monaco = require('monaco'); - var Alert = require('alert'); - var bigInt = require('big-integer'); - var local = require('./local'); - var Raven = require('raven-js'); - require('asm-mode'); +'use strict'; +var $ = require('jquery'); +var _ = require('underscore'); +var ga = require('analytics').ga; +var colour = require('colour'); +var Toggles = require('toggles'); +var FontScale = require('fontscale'); +var Promise = require('es6-promise').Promise; +var Components = require('components'); +var LruCache = require('lru-cache'); +var options = require('options'); +var monaco = require('monaco'); +var Alert = require('alert'); +var bigInt = require('big-integer'); +var local = require('./local'); +var Raven = require('raven-js'); +require('asm-mode'); - require('selectize'); +require('selectize'); - var OpcodeCache = new LruCache({ - max: 64 * 1024, - length: function (n) { - return JSON.stringify(n).length; +var OpcodeCache = new LruCache({ + max: 64 * 1024, + length: function (n) { + return JSON.stringify(n).length; + } +}); + +function patchOldFilters(filters) { + if (filters === undefined) return undefined; + // Filters are of the form {filter: true|false¸ ...}. In older versions, we used + // to suppress the {filter:false} form. This means we can't distinguish between + // "filter not on" and "filter not present". In the latter case we want to default + // the filter. In the former case we want the filter off. Filters now don't suppress + // but there are plenty of permanlinks out there with no filters set at all. Here + // we manually set any missing filters to 'false' to recover the old behaviour of + // "if it's not here, it's off". + _.each(['binary', 'labels', 'directives', 'commentOnly', 'trim', 'intel'], function (oldFilter) { + if (filters[oldFilter] === undefined) filters[oldFilter] = false; + }); + return filters; +} + +var languages = options.languages; + +function Compiler(hub, container, state) { + this.container = container; + this.eventHub = hub.createEventHub(); + this.compilerService = hub.compilerService; + this.domRoot = container.getElement(); + this.domRoot.html($('#compiler').html()); + this.id = state.id || hub.nextCompilerId(); + this.sourceEditorId = state.source || 1; + this.settings = JSON.parse(local.get('settings', '{}')); + // If we don't have a language, but a compiler, find the corresponding language. + this.currentLangId = state.lang; + if (!this.currentLangId && state.compiler) { + this.currentLangId = this.langOfCompiler(state.compiler); + } + if (!this.currentLangId && languages[this.settings.defaultLanguage]) { + this.currentLangId = languages[this.settings.defaultLanguage].id; + } + if (!this.currentLangId) { + this.currentLangId = _.keys(languages)[0]; + } + this.originalCompilerId = state.compiler; + if (state.compiler) + this.compiler = this.findCompiler(this.currentLangId, state.compiler); + else + this.compiler = this.findCompiler(this.currentLangId, options.defaultCompiler[this.currentLangId]); + if (!this.compiler) { + var compilers = this.compilerService.compilersByLang[this.currentLangId]; + if (compilers) this.compiler = _.values(compilers)[0]; + } + this.infoByLang = {}; + this.deferCompiles = hub.deferred; + this.needsCompile = false; + this.options = state.options || options.compileOptions[this.currentLangId]; + this.filters = new Toggles(this.domRoot.find('.filters'), patchOldFilters(state.filters)); + this.source = ''; + this.assembly = []; + this.colours = []; + this.lastResult = {}; + this.pendingRequestSentAt = 0; + this.nextRequest = null; + this.optViewOpen = false; + this.cfgViewOpen = false; + this.wantOptInfo = state.wantOptInfo; + this.decorations = {}; + this.prevDecorations = []; + this.optButton = this.domRoot.find('.btn.view-optimization'); + this.astButton = this.domRoot.find('.btn.view-ast'); + this.gccDumpButton = this.domRoot.find('.btn.view-gccdump'); + this.cfgButton = this.domRoot.find('.btn.view-cfg'); + this.libsButton = this.domRoot.find('.btn.show-libs'); + this.compileTimeLabel = this.domRoot.find('.compile-time'); + this.compileClearCache = this.domRoot.find('.clear-cache'); + + this.availableLibs = {}; + this.updateAvailableLibs = function () { + if (!this.availableLibs[this.currentLangId]) { + this.availableLibs[this.currentLangId] = $.extend(true, {}, options.libs[this.currentLangId]); } + }; + this.updateAvailableLibs(); + _.each(state.libs, _.bind(function (lib) { + if (this.availableLibs[this.currentLangId][lib.name] && + this.availableLibs[this.currentLangId][lib.name].versions && + this.availableLibs[this.currentLangId][lib.name].versions[lib.ver]) { + this.availableLibs[this.currentLangId][lib.name].versions[lib.ver].used = true; + } + }, this)); + + this.linkedFadeTimeoutId = -1; + this.getGroupsInUse = function () { + var currentLangCompilers = _.map(this.getCurrentLangCompilers(), _.identity, this); + return _.map(_.uniq(currentLangCompilers, false, function (compiler) { + return compiler.group; + }), function (compiler) { + return {value: compiler.group, label: compiler.groupName || compiler.group}; + }); + }; + + this.domRoot.find('.compiler-picker').selectize({ + sortField: 'name', + valueField: 'id', + labelField: 'name', + searchField: ['name'], + optgroupField: 'group', + optgroups: this.getGroupsInUse(), + options: _.map(this.getCurrentLangCompilers(), _.identity, this), + items: this.compiler ? [this.compiler.id] : [] + }).on('change', _.bind(function (e) { + var val = $(e.target).val(); + if (val) { + ga('send', { + hitType: 'event', + eventCategory: 'SelectCompiler', + eventAction: val + }); + this.onCompilerChange(val); + } + }, this)); + var optionsChange = _.debounce(_.bind(function (e) { + this.onOptionsChange($(e.target).val()); + }, this), 800); + this.optionsField = this.domRoot.find('.options'); + this.optionsField + .val(this.options) + .on('change', optionsChange) + .on('keyup', optionsChange); + + this.domRoot.find("[data-bind='execute']").toggle(options.supportsExecute); + + this.outputEditor = monaco.editor.create(this.domRoot.find('.monaco-placeholder')[0], { + scrollBeyondLastLine: false, + readOnly: true, + language: 'asm', + fontFamily: '"Fira Mono", monospace', + glyphMargin: !options.embedded, + fixedOverflowWidgets: true, + minimap: { + maxColumn: 80 + }, + lineNumbersMinChars: options.embedded ? 1 : 5 + }); + this.outputEditor.addAction({ + id: 'viewsource', + label: 'Scroll to source', + keybindings: [monaco.KeyMod.CtrlCmd | monaco.KeyCode.F10], + keybindingContext: null, + contextMenuGroupId: 'navigation', + contextMenuOrder: 1.5, + run: _.bind(function (ed) { + var desiredLine = ed.getPosition().lineNumber - 1; + var source = this.assembly[desiredLine].source; + if (source.file === null) { + // a null file means it was the user's source + this.eventHub.emit('editorSetDecoration', this.sourceEditorId, source.line, true); + } else { + // TODO: some indication this asm statement came from elsewhere + this.eventHub.emit('editorSetDecoration', this.sourceEditorId, -1, false); + } + }, this) }); - function patchOldFilters(filters) { - if (filters === undefined) return undefined; - // Filters are of the form {filter: true|false¸ ...}. In older versions, we used - // to suppress the {filter:false} form. This means we can't distinguish between - // "filter not on" and "filter not present". In the latter case we want to default - // the filter. In the former case we want the filter off. Filters now don't suppress - // but there are plenty of permanlinks out there with no filters set at all. Here - // we manually set any missing filters to 'false' to recover the old behaviour of - // "if it's not here, it's off". - _.each(['binary', 'labels', 'directives', 'commentOnly', 'trim', 'intel'], function (oldFilter) { - if (filters[oldFilter] === undefined) filters[oldFilter] = false; - }); - return filters; - } + this.outputEditor.addAction({ + id: 'viewasmdoc', + label: 'View asm doc', + keybindings: [monaco.KeyMod.CtrlCmd | monaco.KeyCode.F8], + keybindingContext: null, + contextMenuGroupId: 'help', + contextMenuOrder: 1.5, + run: _.bind(this.onAsmToolTip, this) + }); - var languages = options.languages; - - function Compiler(hub, container, state) { - this.container = container; - this.eventHub = hub.createEventHub(); - this.compilerService = hub.compilerService; - this.domRoot = container.getElement(); - this.domRoot.html($('#compiler').html()); - this.id = state.id || hub.nextCompilerId(); - this.sourceEditorId = state.source || 1; - this.settings = JSON.parse(local.get('settings', '{}')); - // If we don't have a language, but a compiler, find the corresponding language. - this.currentLangId = state.lang; - if (!this.currentLangId && state.compiler) { - this.currentLangId = this.langOfCompiler(state.compiler); - } - if (!this.currentLangId && languages[this.settings.defaultLanguage]) { - this.currentLangId = languages[this.settings.defaultLanguage].id; - } - if (!this.currentLangId) { - this.currentLangId = _.keys(languages)[0]; - } - this.originalCompilerId = state.compiler; - if (state.compiler) - this.compiler = this.findCompiler(this.currentLangId, state.compiler); - else - this.compiler = this.findCompiler(this.currentLangId, options.defaultCompiler[this.currentLangId]); - if (!this.compiler) { - var compilers = this.compilerService.compilersByLang[this.currentLangId]; - if (compilers) this.compiler = _.values(compilers)[0]; - } - this.infoByLang = {}; - this.deferCompiles = hub.deferred; - this.needsCompile = false; - this.options = state.options || options.compileOptions[this.currentLangId]; - this.filters = new Toggles(this.domRoot.find('.filters'), patchOldFilters(state.filters)); - this.source = ''; - this.assembly = []; - this.colours = []; - this.lastResult = {}; - this.pendingRequestSentAt = 0; - this.nextRequest = null; - this.optViewOpen = false; - this.cfgViewOpen = false; - this.wantOptInfo = state.wantOptInfo; - this.decorations = {}; - this.prevDecorations = []; - this.optButton = this.domRoot.find('.btn.view-optimization'); - this.astButton = this.domRoot.find('.btn.view-ast'); - this.gccDumpButton = this.domRoot.find('.btn.view-gccdump'); - this.cfgButton = this.domRoot.find('.btn.view-cfg'); - this.libsButton = this.domRoot.find('.btn.show-libs'); - this.compileTimeLabel = this.domRoot.find('.compile-time'); - this.compileClearCache = this.domRoot.find('.clear-cache'); - - this.availableLibs = {}; - this.updateAvailableLibs = function () { - if (!this.availableLibs[this.currentLangId]) { - this.availableLibs[this.currentLangId] = $.extend(true, {}, options.libs[this.currentLangId]); - } - }; - this.updateAvailableLibs(); - _.each(state.libs, _.bind(function (lib) { - if (this.availableLibs[this.currentLangId][lib.name] && - this.availableLibs[this.currentLangId][lib.name].versions && - this.availableLibs[this.currentLangId][lib.name].versions[lib.ver]) { - this.availableLibs[this.currentLangId][lib.name].versions[lib.ver].used = true; - } - }, this)); - - this.linkedFadeTimeoutId = -1; - this.getGroupsInUse = function () { - var currentLangCompilers = _.map(this.getCurrentLangCompilers(), _.identity, this); - return _.map(_.uniq(currentLangCompilers, false, function (compiler) { - return compiler.group; - }), function (compiler) { - return {value: compiler.group, label: compiler.groupName || compiler.group}; + this.outputEditor.addAction({ + id: 'toggleColourisation', + label: 'Toggle colourisation', + keybindings: [monaco.KeyMod.CtrlCmd | monaco.KeyMod.Shift | monaco.KeyCode.F1], + keybindingContext: null, + run: _.bind(function () { + this.eventHub.emit('modifySettings', { + colouriseAsm: !this.settings.colouriseAsm }); + }, this) + }); + + var clearEditorsLinkedLines = _.bind(function () { + this.eventHub.emit('editorSetDecoration', this.sourceEditorId, -1, false); + }, this); + + this.outputEditor.onMouseMove(_.bind(function (e) { + this.mouseMoveThrottledFunction(e); + if (this.linkedFadeTimeoutId !== -1) { + clearTimeout(this.linkedFadeTimeoutId); + this.linkedFadeTimeoutId = -1; + } + }, this)); + + this.mouseMoveThrottledFunction = _.throttle(_.bind(this.onMouseMove, this), 250); + + this.outputEditor.onMouseLeave(_.bind(function () { + this.linkedFadeTimeoutId = setTimeout(_.bind(function () { + clearEditorsLinkedLines(); + this.linkedFadeTimeoutId = -1; + }, this), 5000); + }, this)); + + this.fontScale = new FontScale(this.domRoot, state, this.outputEditor); + this.fontScale.on('change', _.bind(function () { + this.saveState(); + this.updateFontScale(); + }, this)); + + this.filters.on('change', _.bind(this.onFilterChange, this)); + + container.on('destroy', this.close, this); + container.on('resize', this.resize, this); + container.on('shown', this.resize, this); + container.on('open', function () { + this.eventHub.emit('compilerOpen', this.id, this.sourceEditorId); + this.updateFontScale(); + }, this); + this.eventHub.on('editorChange', this.onEditorChange, this); + this.eventHub.on('editorClose', this.onEditorClose, this); + this.eventHub.on('colours', this.onColours, this); + this.eventHub.on('resendCompilation', this.onResendCompilation, this); + this.eventHub.on('findCompilers', this.sendCompiler, this); + this.eventHub.on('compilerSetDecorations', this.onCompilerSetDecorations, this); + this.eventHub.on('settingsChange', this.onSettingsChange, this); + + this.eventHub.on('optViewOpened', this.onOptViewOpened, this); + this.eventHub.on('optViewClosed', this.onOptViewClosed, this); + this.eventHub.on('astViewOpened', this.onAstViewOpened, this); + this.eventHub.on('astViewClosed', this.onAstViewClosed, this); + + this.eventHub.on('gccDumpPassSelected', this.onGccDumpPassSelected, this); + this.eventHub.on('gccDumpFiltersChanged', this.onGccDumpFiltersChanged, this); + this.eventHub.on('gccDumpViewOpened', this.onGccDumpViewOpened, this); + this.eventHub.on('gccDumpViewClosed', this.onGccDumpViewClosed, this); + this.eventHub.on('gccDumpUIInit', this.onGccDumpUIInit, this); + + this.eventHub.on('cfgViewOpened', this.onCfgViewOpened, this); + this.eventHub.on('cfgViewClosed', this.onCfgViewClosed, this); + this.eventHub.on('resize', this.resize, this); + this.eventHub.on('requestFilters', function (id) { + if (id === this.id) { + this.eventHub.emit('filtersChange', this.id, this.getEffectiveFilters()); + } + }, this); + this.eventHub.on('requestCompiler', function (id) { + if (id === this.id) { + this.sendCompiler(); + } + }, this); + this.eventHub.on('languageChange', this.onLanguageChange, this); + this.onSettingsChange(this.settings); + this.sendCompiler(); + this.updateCompilerName(); + this.updateButtons(); + + var outputConfig = _.bind(function () { + return Components.getOutput(this.id, this.sourceEditorId); + }, this); + + this.container.layoutManager.createDragSource(this.domRoot.find('.status').parent(), outputConfig); + this.domRoot.find('.status').parent().click(_.bind(function () { + var insertPoint = hub.findParentRowOrColumn(this.container) || + this.container.layoutManager.root.contentItems[0]; + insertPoint.addChild(outputConfig); + }, this)); + + var cloneComponent = _.bind(function () { + return { + type: 'component', + componentName: 'compiler', + componentState: this.currentState() }; + }, this); - this.domRoot.find('.compiler-picker').selectize({ - sortField: 'name', - valueField: 'id', - labelField: 'name', - searchField: ['name'], - optgroupField: 'group', - optgroups: this.getGroupsInUse(), - options: _.map(this.getCurrentLangCompilers(), _.identity, this), - items: this.compiler ? [this.compiler.id] : [] - }).on('change', _.bind(function (e) { - var val = $(e.target).val(); - if (val) { - ga('send', { - hitType: 'event', - eventCategory: 'SelectCompiler', - eventAction: val - }); - this.onCompilerChange(val); - } - }, this)); - var optionsChange = _.debounce(_.bind(function (e) { - this.onOptionsChange($(e.target).val()); - }, this), 800); - this.optionsField = this.domRoot.find('.options'); - this.optionsField - .val(this.options) - .on('change', optionsChange) - .on('keyup', optionsChange); + var createOptView = _.bind(function () { + return Components.getOptViewWith(this.id, this.source, this.lastResult.optOutput, this.getCompilerName(), this.sourceEditorId); + }, this); - this.domRoot.find("[data-bind='execute']").toggle(options.supportsExecute); + var createAstView = _.bind(function () { + return Components.getAstViewWith(this.id, this.source, this.lastResult.astOutput, this.getCompilerName(), this.sourceEditorId); + }, this); - this.outputEditor = monaco.editor.create(this.domRoot.find('.monaco-placeholder')[0], { - scrollBeyondLastLine: false, - readOnly: true, - language: 'asm', - fontFamily: '"Fira Mono", monospace', - glyphMargin: !options.embedded, - fixedOverflowWidgets: true, - minimap: { - maxColumn: 80 + var createGccDumpView = _.bind(function () { + return Components.getGccDumpViewWith(this.id, this.getCompilerName(), this.sourceEditorId, this.lastResult.gccDumpOutput); + }, this); + + var createCfgView = _.bind(function () { + return Components.getCfgViewWith(this.id, this.sourceEditorId); + }, this); + + var panerDropdown = this.domRoot.find('.pane-dropdown'); + var togglePannerAdder = function () { + panerDropdown.dropdown('toggle'); + }; + + this.container.layoutManager + .createDragSource(this.domRoot.find('.btn.add-compiler'), cloneComponent) + ._dragListener.on('dragStart', togglePannerAdder); + + this.domRoot.find('.btn.add-compiler').click(_.bind(function () { + var insertPoint = hub.findParentRowOrColumn(this.container) || + this.container.layoutManager.root.contentItems[0]; + insertPoint.addChild(cloneComponent); + }, this)); + + this.container.layoutManager + .createDragSource(this.optButton, createOptView) + ._dragListener.on('dragStart', togglePannerAdder); + + this.optButton.click(_.bind(function () { + var insertPoint = hub.findParentRowOrColumn(this.container) || + this.container.layoutManager.root.contentItems[0]; + insertPoint.addChild(createOptView); + }, this)); + + this.container.layoutManager + .createDragSource(this.astButton, createAstView) + ._dragListener.on('dragStart', togglePannerAdder); + + this.astButton.click(_.bind(function () { + var insertPoint = hub.findParentRowOrColumn(this.container) || + this.container.layoutManager.root.contentItems[0]; + insertPoint.addChild(createAstView); + }, this)); + + this.container.layoutManager + .createDragSource(this.gccDumpButton, createGccDumpView) + ._dragListener.on('dragStart', togglePannerAdder); + + this.gccDumpButton.click(_.bind(function () { + var insertPoint = hub.findParentRowOrColumn(this.container) || + this.container.layoutManager.root.contentItems[0]; + insertPoint.addChild(createGccDumpView); + }, this)); + + this.container.layoutManager + .createDragSource(this.cfgButton, createCfgView) + ._dragListener.on('dragStart', togglePannerAdder); + + this.cfgButton.click(_.bind(function () { + var insertPoint = hub.findParentRowOrColumn(this.container) || + this.container.layoutManager.root.contentItems[0]; + insertPoint.addChild(createCfgView); + }, this)); + + this.updateLibsDropdown(); + + this.compileClearCache.on('click', _.bind(function () { + this.compilerService.cache.reset(); + this.compile(); + }, this)); + + // Dismiss the popover on escape. + $(document).on('keyup.editable', _.bind(function (e) { + if (e.which === 27) { + this.libsButton.popover('hide'); + } + }, this)); + + // Dismiss on any click that isn't either in the opening element, inside + // the popover or on any alert + $(document).on('click', _.bind(function (e) { + var elem = this.libsButton; + var target = $(e.target); + if (!target.is(elem) && elem.has(target).length === 0 && target.closest('.popover').length === 0) { + elem.popover('hide'); + } + }, this)); + + this.onSettingsChange(this.settings); + this.eventHub.on('initialised', this.undefer, this); + + this.saveState(); +} + +Compiler.prototype.close = function () { + this.eventHub.unsubscribe(); + this.eventHub.emit('compilerClose', this.id); + this.outputEditor.dispose(); +}; + +Compiler.prototype.undefer = function () { + this.deferCompiles = false; + if (this.needsCompile) this.compile(); +}; + +// TODO: need to call resize if either .top-bar or .bottom-bar resizes, which needs some work. +// Issue manifests if you make a window where one compiler is small enough that the buttons spill onto two lines: +// reload the page and the bottom-bar is off the bottom until you scroll a tiny bit. +Compiler.prototype.resize = function () { + var topBarHeight = this.domRoot.find('.top-bar').outerHeight(true); + var bottomBarHeight = this.domRoot.find('.bottom-bar').outerHeight(true); + this.outputEditor.layout({ + width: this.domRoot.width(), + height: this.domRoot.height() - topBarHeight - bottomBarHeight + }); +}; + +// Gets the filters that will actually be used (accounting for issues with binary +// mode etc). +Compiler.prototype.getEffectiveFilters = function () { + if (!this.compiler) return {}; + var filters = this.filters.get(); + if (filters.binary && !this.compiler.supportsBinary) { + delete filters.binary; + } + if (filters.execute && !this.compiler.supportsExecute) { + delete filters.execute; + } + return filters; +}; + +Compiler.prototype.compile = function () { + if (this.deferCompiles) { + this.needsCompile = true; + return; + } + this.needsCompile = false; + var options = { + userArguments: this.options, + compilerOptions: { + produceAst: this.astViewOpen, + produceGccDump: { + opened: this.gccDumpViewOpen, + pass: this.gccDumpPassSelected, + treeDump: this.treeDumpEnabled, + rtlDump: this.rtlDumpEnabled }, - lineNumbersMinChars: options.embedded ? 1 : 5 - }); - this.outputEditor.addAction({ - id: 'viewsource', - label: 'Scroll to source', - keybindings: [monaco.KeyMod.CtrlCmd | monaco.KeyCode.F10], - keybindingContext: null, - contextMenuGroupId: 'navigation', - contextMenuOrder: 1.5, - run: _.bind(function (ed) { - var desiredLine = ed.getPosition().lineNumber - 1; - var source = this.assembly[desiredLine].source; - if (source.file === null) { - // a null file means it was the user's source - this.eventHub.emit('editorSetDecoration', this.sourceEditorId, source.line, true); - } else { - // TODO: some indication this asm statement came from elsewhere - this.eventHub.emit('editorSetDecoration', this.sourceEditorId, -1, false); - } - }, this) - }); - - this.outputEditor.addAction({ - id: 'viewasmdoc', - label: 'View asm doc', - keybindings: [monaco.KeyMod.CtrlCmd | monaco.KeyCode.F8], - keybindingContext: null, - contextMenuGroupId: 'help', - contextMenuOrder: 1.5, - run: _.bind(this.onAsmToolTip, this) - }); - - this.outputEditor.addAction({ - id: 'toggleColourisation', - label: 'Toggle colourisation', - keybindings: [monaco.KeyMod.CtrlCmd | monaco.KeyMod.Shift | monaco.KeyCode.F1], - keybindingContext: null, - run: _.bind(function () { - this.eventHub.emit('modifySettings', { - colouriseAsm: !this.settings.colouriseAsm + produceOptInfo: this.wantOptInfo, + produceCfg: this.cfgViewOpen + }, + filters: this.getEffectiveFilters() + }; + _.each(this.availableLibs[this.currentLangId], function (lib) { + _.each(lib.versions, function (version) { + if (version.used) { + _.each(version.path, function (path) { + options.userArguments += ' -I' + path; }); - }, this) + } }); - - var clearEditorsLinkedLines = _.bind(function () { - this.eventHub.emit('editorSetDecoration', this.sourceEditorId, -1, false); - }, this); - - this.outputEditor.onMouseMove(_.bind(function (e) { - this.mouseMoveThrottledFunction(e); - if (this.linkedFadeTimeoutId !== -1) { - clearTimeout(this.linkedFadeTimeoutId); - this.linkedFadeTimeoutId = -1; - } - }, this)); - - this.mouseMoveThrottledFunction = _.throttle(_.bind(this.onMouseMove, this), 250); - - this.outputEditor.onMouseLeave(_.bind(function () { - this.linkedFadeTimeoutId = setTimeout(_.bind(function () { - clearEditorsLinkedLines(); - this.linkedFadeTimeoutId = -1; - }, this), 5000); - }, this)); - - this.fontScale = new FontScale(this.domRoot, state, this.outputEditor); - this.fontScale.on('change', _.bind(function () { - this.saveState(); - this.updateFontScale(); - }, this)); - - this.filters.on('change', _.bind(this.onFilterChange, this)); - - container.on('destroy', this.close, this); - container.on('resize', this.resize, this); - container.on('shown', this.resize, this); - container.on('open', function () { - this.eventHub.emit('compilerOpen', this.id, this.sourceEditorId); - this.updateFontScale(); - }, this); - this.eventHub.on('editorChange', this.onEditorChange, this); - this.eventHub.on('editorClose', this.onEditorClose, this); - this.eventHub.on('colours', this.onColours, this); - this.eventHub.on('resendCompilation', this.onResendCompilation, this); - this.eventHub.on('findCompilers', this.sendCompiler, this); - this.eventHub.on('compilerSetDecorations', this.onCompilerSetDecorations, this); - this.eventHub.on('settingsChange', this.onSettingsChange, this); - - this.eventHub.on('optViewOpened', this.onOptViewOpened, this); - this.eventHub.on('optViewClosed', this.onOptViewClosed, this); - this.eventHub.on('astViewOpened', this.onAstViewOpened, this); - this.eventHub.on('astViewClosed', this.onAstViewClosed, this); - - this.eventHub.on('gccDumpPassSelected', this.onGccDumpPassSelected, this); - this.eventHub.on('gccDumpFiltersChanged', this.onGccDumpFiltersChanged, this); - this.eventHub.on('gccDumpViewOpened', this.onGccDumpViewOpened, this); - this.eventHub.on('gccDumpViewClosed', this.onGccDumpViewClosed, this); - this.eventHub.on('gccDumpUIInit', this.onGccDumpUIInit, this); - - this.eventHub.on('cfgViewOpened', this.onCfgViewOpened, this); - this.eventHub.on('cfgViewClosed', this.onCfgViewClosed, this); - this.eventHub.on('resize', this.resize, this); - this.eventHub.on('requestFilters', function (id) { - if (id === this.id) { - this.eventHub.emit('filtersChange', this.id, this.getEffectiveFilters()); - } - }, this); - this.eventHub.on('requestCompiler', function (id) { - if (id === this.id) { - this.sendCompiler(); - } - }, this); - this.eventHub.on('languageChange', this.onLanguageChange, this); - this.onSettingsChange(this.settings); - this.sendCompiler(); - this.updateCompilerName(); - this.updateButtons(); - - var outputConfig = _.bind(function () { - return Components.getOutput(this.id, this.sourceEditorId); - }, this); - - this.container.layoutManager.createDragSource(this.domRoot.find('.status').parent(), outputConfig); - this.domRoot.find('.status').parent().click(_.bind(function () { - var insertPoint = hub.findParentRowOrColumn(this.container) || - this.container.layoutManager.root.contentItems[0]; - insertPoint.addChild(outputConfig); - }, this)); - - var cloneComponent = _.bind(function () { - return { - type: 'component', - componentName: 'compiler', - componentState: this.currentState() - }; - }, this); - - var createOptView = _.bind(function () { - return Components.getOptViewWith(this.id, this.source, this.lastResult.optOutput, this.getCompilerName(), this.sourceEditorId); - }, this); - - var createAstView = _.bind(function () { - return Components.getAstViewWith(this.id, this.source, this.lastResult.astOutput, this.getCompilerName(), this.sourceEditorId); - }, this); - - var createGccDumpView = _.bind(function () { - return Components.getGccDumpViewWith(this.id, this.getCompilerName(), this.sourceEditorId, this.lastResult.gccDumpOutput); - }, this); - - var createCfgView = _.bind(function () { - return Components.getCfgViewWith(this.id, this.sourceEditorId); - }, this); - - var panerDropdown = this.domRoot.find('.pane-dropdown'); - var togglePannerAdder = function () { - panerDropdown.dropdown('toggle'); - }; - - this.container.layoutManager - .createDragSource(this.domRoot.find('.btn.add-compiler'), cloneComponent) - ._dragListener.on('dragStart', togglePannerAdder); - - this.domRoot.find('.btn.add-compiler').click(_.bind(function () { - var insertPoint = hub.findParentRowOrColumn(this.container) || - this.container.layoutManager.root.contentItems[0]; - insertPoint.addChild(cloneComponent); - }, this)); - - this.container.layoutManager - .createDragSource(this.optButton, createOptView) - ._dragListener.on('dragStart', togglePannerAdder); - - this.optButton.click(_.bind(function () { - var insertPoint = hub.findParentRowOrColumn(this.container) || - this.container.layoutManager.root.contentItems[0]; - insertPoint.addChild(createOptView); - }, this)); - - this.container.layoutManager - .createDragSource(this.astButton, createAstView) - ._dragListener.on('dragStart', togglePannerAdder); - - this.astButton.click(_.bind(function () { - var insertPoint = hub.findParentRowOrColumn(this.container) || - this.container.layoutManager.root.contentItems[0]; - insertPoint.addChild(createAstView); - }, this)); - - this.container.layoutManager - .createDragSource(this.gccDumpButton, createGccDumpView) - ._dragListener.on('dragStart', togglePannerAdder); - - this.gccDumpButton.click(_.bind(function () { - var insertPoint = hub.findParentRowOrColumn(this.container) || - this.container.layoutManager.root.contentItems[0]; - insertPoint.addChild(createGccDumpView); - }, this)); - - this.container.layoutManager - .createDragSource(this.cfgButton, createCfgView) - ._dragListener.on('dragStart', togglePannerAdder); - - this.cfgButton.click(_.bind(function () { - var insertPoint = hub.findParentRowOrColumn(this.container) || - this.container.layoutManager.root.contentItems[0]; - insertPoint.addChild(createCfgView); - }, this)); - - this.updateLibsDropdown(); - - this.compileClearCache.on('click', _.bind(function () { - this.compilerService.cache.reset(); - this.compile(); - }, this)); - - // Dismiss the popover on escape. - $(document).on('keyup.editable', _.bind(function (e) { - if (e.which === 27) { - this.libsButton.popover('hide'); - } - }, this)); - - // Dismiss on any click that isn't either in the opening element, inside - // the popover or on any alert - $(document).on('click', _.bind(function (e) { - var elem = this.libsButton; - var target = $(e.target); - if (!target.is(elem) && elem.has(target).length === 0 && target.closest('.popover').length === 0) { - elem.popover('hide'); - } - }, this)); - - this.onSettingsChange(this.settings); - this.eventHub.on('initialised', this.undefer, this); - - this.saveState(); - } - - Compiler.prototype.close = function () { - this.eventHub.unsubscribe(); - this.eventHub.emit('compilerClose', this.id); - this.outputEditor.dispose(); - }; - - Compiler.prototype.undefer = function () { - this.deferCompiles = false; - if (this.needsCompile) this.compile(); - }; - - // TODO: need to call resize if either .top-bar or .bottom-bar resizes, which needs some work. - // Issue manifests if you make a window where one compiler is small enough that the buttons spill onto two lines: - // reload the page and the bottom-bar is off the bottom until you scroll a tiny bit. - Compiler.prototype.resize = function () { - var topBarHeight = this.domRoot.find('.top-bar').outerHeight(true); - var bottomBarHeight = this.domRoot.find('.bottom-bar').outerHeight(true); - this.outputEditor.layout({ - width: this.domRoot.width(), - height: this.domRoot.height() - topBarHeight - bottomBarHeight - }); - }; - - // Gets the filters that will actually be used (accounting for issues with binary - // mode etc). - Compiler.prototype.getEffectiveFilters = function () { - if (!this.compiler) return {}; - var filters = this.filters.get(); - if (filters.binary && !this.compiler.supportsBinary) { - delete filters.binary; - } - if (filters.execute && !this.compiler.supportsExecute) { - delete filters.execute; - } - return filters; - }; - - Compiler.prototype.compile = function () { - if (this.deferCompiles) { - this.needsCompile = true; - return; - } - this.needsCompile = false; - var options = { - userArguments: this.options, - compilerOptions: { - produceAst: this.astViewOpen, - produceGccDump: { - opened: this.gccDumpViewOpen, - pass: this.gccDumpPassSelected, - treeDump: this.treeDumpEnabled, - rtlDump: this.rtlDumpEnabled - }, - produceOptInfo: this.wantOptInfo, - produceCfg: this.cfgViewOpen - }, - filters: this.getEffectiveFilters() - }; - _.each(this.availableLibs[this.currentLangId], function (lib) { - _.each(lib.versions, function (version) { - if (version.used) { - _.each(version.path, function (path) { - options.userArguments += ' -I' + path; - }); - } - }); - }); - this.compilerService.expand(this.source).then(_.bind(function (expanded) { - var request = { - source: expanded || '', - compiler: this.compiler ? this.compiler.id : '', - options: options, - lang: this.currentLangId - }; - if (!this.compiler) { - this.onCompileResponse(request, errorResult(''), false); - } else { - this.sendCompile(request); - } - }, this)); - }; - - Compiler.prototype.sendCompile = function (request) { - var onCompilerResponse = _.bind(this.onCompileResponse, this); - - if (this.pendingRequestSentAt) { - // If we have a request pending, then just store this request to do once the - // previous request completes. - this.nextRequest = request; - return; - } - this.eventHub.emit('compiling', this.id, this.compiler); - this.pendingRequestSentAt = Date.now(); - // After a short delay, give the user some indication that we're working on their - // compilation. - var progress = setTimeout(_.bind(function () { - this.setAssembly(fakeAsm('')); - }, this), 500); - this.compilerService.submit(request) - .then(function (x) { - clearTimeout(progress); - onCompilerResponse(request, x.result, x.localCacheHit); - }) - .catch(function (x) { - clearTimeout(progress); - onCompilerResponse(request, errorResult(''), false); - }); - }; - - Compiler.prototype.getBinaryForLine = function (line) { - var obj = this.assembly[line - 1]; - if (!obj) return '
????
????
'; - var address = obj.address ? obj.address.toString(16) : ''; - var opcodes = '
'; - _.each(obj.opcodes, function (op) { - opcodes += ('' + op + ''); - }); - return '
' + address + '
' + opcodes + '
'; - }; - - // TODO: use ContentWidgets? OverlayWidgets? - // Use highlight providers? hover providers? highlight providers? - Compiler.prototype.setAssembly = function (assembly) { - this.assembly = assembly; - if (this.outputEditor.getModel()) { - this.outputEditor.getModel().setValue(_.pluck(assembly, 'text').join('\n')); - var addrToAddrDiv = {}; - var decorations = []; - _.each(this.assembly, _.bind(function (obj, line) { - var address = obj.address ? obj.address.toString(16) : ''; - // var div = $("
" + address + "
"); - addrToAddrDiv[address] = {div: 'moo', line: line}; - }, this)); - - _.each(this.assembly, _.bind(function (obj, line) { - if (obj.links) { - _.each(obj.links, _.bind(function (link) { - var address = link.to.toString(16); - // var thing = $("" + address + ""); - // this.outputEditor.markText( - // from, to, {replacedWith: thing[0], handleMouseEvents: false}); - var dest = addrToAddrDiv[address]; - if (dest) { - decorations.push({ - range: new monaco.Range(line, link.offset, line, link.offset + link.length), - options: {} - }); - // var editor = this.outputEditor; - // thing.hover(function (e) { - // var entered = e.type == "mouseenter"; - // dest.div.toggleClass("highlighted", entered); - // thing.toggleClass("highlighted", entered); - // }); - // thing.on('click', function (e) { - // editor.scrollIntoView({line: dest.line, ch: 0}, 30); - // dest.div.toggleClass("highlighted", false); - // thing.toggleClass("highlighted", false); - // e.preventDefault(); - // }); - } - }, this)); - } - }, this)); - } - }; - - function errorResult(text) { - return {asm: fakeAsm(text), code: -1, stdout: '', stderr: ''}; - } - - function fakeAsm(text) { - return [{text: text, source: null, fake: true}]; - } - - Compiler.prototype.onCompileResponse = function (request, result, cached) { - // Delete trailing empty lines - if ($.isArray(result.asm)) { - var cutCount = 0; - for (var i = result.asm.length - 1; i >= 0; i--) { - if (result.asm[i].text) { - break; - } - cutCount++; - } - result.asm.splice(result.asm.length - cutCount, cutCount); - } - this.lastResult = result; - var timeTaken = Math.max(0, Date.now() - this.pendingRequestSentAt); - var wasRealReply = this.pendingRequestSentAt > 0; - this.pendingRequestSentAt = 0; - ga('send', { - hitType: 'event', - eventCategory: 'Compile', - eventAction: request.compiler, - eventLabel: request.options.userArguments, - eventValue: cached ? 1 : 0 - }); - ga('send', { - hitType: 'timing', - timingCategory: 'Compile', - timingVar: request.compiler, - timingValue: timeTaken - }); - this.setAssembly(result.asm || fakeAsm('')); - if (request.options.filters.binary) { - this.outputEditor.updateOptions({ - lineNumbers: _.bind(this.getBinaryForLine, this), - // Until something comes out of Microsoft/monaco-editor/issues/515, this gets clamped to ten - lineNumbersMinChars: 25, - glyphMargin: false - }); - } else { - this.outputEditor.updateOptions({ - lineNumbers: true, - lineNumbersMinChars: options.embedded ? 1 : 5, - glyphMargin: true - }); - } - var status = this.domRoot.find('.status'); - var allText = _.pluck((result.stdout || []).concat(result.stderr || []), 'text').join('\n'); - var failed = result.code !== 0; - var warns = !failed && !!allText; - status.toggleClass('error', failed); - status.toggleClass('warning', warns); - status.parent().attr('title', allText); - if (cached) { - this.compileTimeLabel.text(' - cached'); - } else if (wasRealReply) { - this.compileTimeLabel.text(' - ' + timeTaken + 'ms'); - } else { - this.compileTimeLabel.text(''); - } - this.eventHub.emit('compileResult', this.id, this.compiler, result); - this.updateButtons(); - - if (this.nextRequest) { - var next = this.nextRequest; - this.nextRequest = null; - this.sendCompile(next); - } - }; - - Compiler.prototype.onEditorChange = function (editor, source, langId, compilerId) { - if (editor === this.sourceEditorId && langId === this.currentLangId && (compilerId === undefined || compilerId === this.id)) { - this.source = source; - this.compile(); - } - }; - - Compiler.prototype.onOptViewClosed = function (id) { - if (this.id == id) { - this.wantOptInfo = false; - this.optViewOpen = false; - this.optButton.prop('disabled', this.optViewOpen); - } - }; - - Compiler.prototype.onAstViewOpened = function (id) { - if (this.id == id) { - this.astButton.prop('disabled', true); - this.astViewOpen = true; - this.compile(); - } - }; - - Compiler.prototype.onAstViewClosed = function (id) { - if (this.id === id) { - this.astButton.prop('disabled', false); - this.astViewOpen = false; - } - }; - - Compiler.prototype.onGccDumpUIInit = function (id) { - if (this.id === id) { - this.compile(); - } - }; - - Compiler.prototype.onGccDumpFiltersChanged = function (id, filters, reqCompile) { - if (this.id === id) { - this.treeDumpEnabled = (filters.treeDump !== false); - this.rtlDumpEnabled = (filters.rtlDump !== false); - - if (reqCompile) { - this.compile(); - } - } - }; - - Compiler.prototype.onGccDumpPassSelected = function (id, passId, reqCompile) { - if (this.id === id) { - this.gccDumpPassSelected = passId; - - if (reqCompile && passId !== '') { - this.compile(); - } - } - }; - - Compiler.prototype.onGccDumpViewOpened = function (id) { - if (this.id === id) { - this.gccDumpButton.prop('disabled', true); - this.gccDumpViewOpen = true; - } - }; - - Compiler.prototype.onGccDumpViewClosed = function (id) { - if (this.id === id) { - this.gccDumpButton.prop('disabled', !this.compiler.supportsGccDump); - this.gccDumpViewOpen = false; - - delete this.gccDumpPassSelected; - delete this.treeDumpEnabled; - delete this.rtlDumpEnabled; - } - }; - - Compiler.prototype.onOptViewOpened = function (id) { - if (this.id === id) { - this.optViewOpen = true; - this.wantOptInfo = true; - this.optButton.prop('disabled', this.optViewOpen); - this.compile(); - } - }; - - Compiler.prototype.onCfgViewOpened = function (id) { - if (this.id == id) { - this.cfgButton.prop('disabled', true); - this.cfgViewOpen = true; - this.compile(); - } - }; - - Compiler.prototype.onCfgViewClosed = function (id) { - if (this.id === id) { - this.cfgViewOpen = false; - this.cfgButton.prop('disabled', this.getEffectiveFilters().binary); - } - }; - - - Compiler.prototype.updateButtons = function () { - if (!this.compiler) return; - var filters = this.getEffectiveFilters(); - // We can support intel output if the compiler supports it, or if we're compiling - // to binary (as we can disassemble it however we like). - var intelAsm = this.compiler.supportsIntel || filters.binary; - this.domRoot.find("[data-bind='intel']").prop('disabled', !intelAsm); - // Disable binary support on compilers that don't work with it. - this.domRoot.find("[data-bind='binary']").prop('disabled', !this.compiler.supportsBinary); - this.domRoot.find("[data-bind='execute']").prop('disabled', !this.compiler.supportsExecute); - // Disable demangle for compilers where we can't access it - this.domRoot.find("[data-bind='demangle']").prop('disabled', !this.compiler.demangler); - // Disable any of the options which don't make sense in binary mode. - var filtersDisabled = !!filters.binary && !this.compiler.supportsFiltersInBinary; - this.domRoot.find('.nonbinary').prop('disabled', filtersDisabled); - // If its already open, we should turn the it off. - // The pane will update with error text - // Other wise we just disable the button. - if (!this.optViewOpen) { - this.optButton.prop('disabled', !this.compiler.supportsOptOutput); - } else { - this.optButton.prop('disabled', true); - } - - if (!this.cfgViewOpen) { - this.cfgButton.prop('disabled', !this.compiler.supportsCfg); - } else { - this.cfgButton.prop('disabled', true); - } - - if (!this.gccDumpViewOpen) { - this.gccDumpButton.prop('disabled', !this.compiler.supportsGccDump); - } else { - this.gccDumpButton.prop('disabled', true); - } - }; - - Compiler.prototype.onOptionsChange = function (options) { - this.options = options; - this.saveState(); - this.compile(); - this.updateButtons(); - this.sendCompiler(); - }; - - Compiler.prototype.onCompilerChange = function (value) { - this.compiler = this.compilerService.findCompiler(this.currentLangId, value); - this.saveState(); - this.compile(); - this.updateButtons(); - this.updateCompilerName(); - this.sendCompiler(); - }; - - Compiler.prototype.sendCompiler = function () { - this.eventHub.emit('compiler', this.id, this.compiler, this.options, this.sourceEditorId); - }; - - Compiler.prototype.onEditorClose = function (editor) { - if (editor === this.sourceEditorId) { - // We can't immediately close as an outer loop somewhere in GoldenLayout is iterating over - // the hierarchy. We can't modify while it's being iterated over. - this.close(); - _.defer(function (self) { - self.container.close(); - }, this); - } - }; - - Compiler.prototype.onFilterChange = function () { - this.eventHub.emit('filtersChange', this.id, this.getEffectiveFilters()); - this.saveState(); - this.compile(); - this.updateButtons(); - }; - - Compiler.prototype.currentState = function () { - var libs = []; - _.each(this.availableLibs[this.currentLangId], function (library, name) { - _.each(library.versions, function (version, ver) { - if (library.versions[ver].used) { - libs.push({name: name, ver: ver}); - } - }); - }); - var state = { + }); + this.compilerService.expand(this.source).then(_.bind(function (expanded) { + var request = { + source: expanded || '', compiler: this.compiler ? this.compiler.id : '', - source: this.sourceEditorId, - options: this.options, - // NB must *not* be effective filters - filters: this.filters.get(), - wantOptInfo: this.wantOptInfo, - libs: libs, + options: options, lang: this.currentLangId }; - this.fontScale.addState(state); - return state; - }; - - Compiler.prototype.saveState = function () { - this.container.setState(this.currentState()); - }; - - Compiler.prototype.updateFontScale = function () { - this.eventHub.emit('compilerFontScale', this.id, this.fontScale.scale); - }; - - Compiler.prototype.onColours = function (editor, colours, scheme) { - if (editor == this.sourceEditorId) { - var asmColours = {}; - _.each(this.assembly, function (x, index) { - if (x.source && x.source.file === null) { - asmColours[index] = colours[x.source.line - 1]; - } - }); - this.colours = colour.applyColours(this.outputEditor, asmColours, scheme, this.colours); + if (!this.compiler) { + this.onCompileResponse(request, errorResult(''), false); + } else { + this.sendCompile(request); } - }; + }, this)); +}; - Compiler.prototype.getCompilerName = function () { - return this.compiler ? this.compiler.name : 'no compiler set'; - }; +Compiler.prototype.sendCompile = function (request) { + var onCompilerResponse = _.bind(this.onCompileResponse, this); - Compiler.prototype.updateCompilerName = function () { - var langName = options.languages[this.currentLangId].name; - var compilerName = this.getCompilerName(); - var compilerVersion = this.compiler ? this.compiler.version : ''; - this.container.setTitle(compilerName + ' (Editor #' + this.sourceEditorId + ', Compiler #' + this.id + ') ' + langName); - this.domRoot.find('.full-compiler-name').text(compilerVersion); - }; - - Compiler.prototype.onResendCompilation = function (id) { - if (id === this.id && !$.isEmptyObject(this.lastResult)) { - this.eventHub.emit('compileResult', this.id, this.compiler, this.lastResult); - } - }; - - Compiler.prototype.updateDecorations = function () { - this.prevDecorations = this.outputEditor.deltaDecorations( - this.prevDecorations, _.flatten(_.values(this.decorations), true)); - }; - - Compiler.prototype.onCompilerSetDecorations = function (id, lineNums, revealLine) { - if (id == this.id) { - if (revealLine && lineNums[0]) - this.outputEditor.revealLineInCenter(lineNums[0]); - this.decorations.linkedCode = _.map(lineNums, function (line) { - return { - range: new monaco.Range(line, 1, line, 1), - options: { - isWholeLine: true, - linesDecorationsClassName: 'linked-code-decoration-margin', - inlineClassName: 'linked-code-decoration-inline' - } - }; - }); - this.updateDecorations(); - } - }; - - Compiler.prototype.onSettingsChange = function (newSettings) { - var before = this.settings; - this.settings = _.clone(newSettings); - if (!before.lastHoverShowSource && this.settings.hoverShowSource) { - this.onCompilerSetDecorations(this.id, []); - } - this.outputEditor.updateOptions({ - contextmenu: this.settings.useCustomContextMenu, - minimap: { - enabled: this.settings.showMinimap && !options.embedded - } - }); - }; - - var hexLike = /^(#?[$]|0x)([0-9a-fA-F]+)$/; - var hexLike2 = /^(#?)([0-9a-fA-F]+)H$/; - var decimalLike = /^(#?)(-?[0-9]+)$/; - - function getNumericToolTip(value) { - var match = hexLike.exec(value) || hexLike2.exec(value); - if (match) { - return value + ' = ' + bigInt(match[2], 16).toString(10); - } - match = decimalLike.exec(value); - if (match) { - var asBig = bigInt(match[2]); - if (asBig.isNegative()) { - asBig = bigInt('ffffffffffffffff', 16).and(asBig); - } - return value + ' = 0x' + asBig.toString(16).toUpperCase(); - } - - return null; + if (this.pendingRequestSentAt) { + // If we have a request pending, then just store this request to do once the + // previous request completes. + this.nextRequest = request; + return; } - - - var getAsmInfo = function (opcode) { - var cacheName = 'asm/' + opcode; - var cached = OpcodeCache.get(cacheName); - if (cached) { - return Promise.resolve(cached.found ? cached.result : null); - } - return new Promise(function (resolve, reject) { - $.ajax({ - type: 'GET', - url: 'api/asm/' + opcode, - dataType: 'json', // Expected, - contentType: 'text/plain', // Sent - success: function (result) { - OpcodeCache.set(cacheName, result); - resolve(result.found ? result.result : null); - }, - error: function (result) { - reject(result); - }, - cache: true - }); + this.eventHub.emit('compiling', this.id, this.compiler); + this.pendingRequestSentAt = Date.now(); + // After a short delay, give the user some indication that we're working on their + // compilation. + var progress = setTimeout(_.bind(function () { + this.setAssembly(fakeAsm('')); + }, this), 500); + this.compilerService.submit(request) + .then(function (x) { + clearTimeout(progress); + onCompilerResponse(request, x.result, x.localCacheHit); + }) + .catch(function (x) { + clearTimeout(progress); + onCompilerResponse(request, errorResult(''), false); }); - }; +}; - Compiler.prototype.onMouseMove = function (e) { - if (e === null || e.target === null || e.target.position === null) return; - if (this.settings.hoverShowSource === true && this.assembly) { - var hoverAsm = this.assembly[e.target.position.lineNumber - 1]; - if (hoverAsm) { - // We check that we actually have something to show at this point! - this.eventHub.emit('editorSetDecoration', this.sourceEditorId, hoverAsm.source && !hoverAsm.source.file ? hoverAsm.source.line : -1, false); - } - } - var currentWord = this.outputEditor.getModel().getWordAtPosition(e.target.position); - if (currentWord && currentWord.word) { - var word = currentWord.word; - currentWord.range = new monaco.Range(e.target.position.lineNumber, currentWord.startColumn, e.target.position.lineNumber, currentWord.endColumn); - // Avoid throwing an exception if somehow (How?) we have a non existent lineNumber. c.f. https://sentry.io/matt-godbolt/compiler-explorer/issues/285270358/ - if (e.target.position.lineNumber < this.outputEditor.getModel().getLineCount()) { - // Hacky workaround to check for negative numbers. c.f. https://github.com/mattgodbolt/compiler-explorer/issues/434 - var lineContent = this.outputEditor.getModel().getLineContent(e.target.position.lineNumber); - if (lineContent[currentWord.startColumn - 2] === '-') { - word = '-' + word; - currentWord.range.startColumn -= 1; - } - } - var numericToolTip = getNumericToolTip(word); - if (numericToolTip) { - this.decorations.numericToolTip = { - range: currentWord.range, - options: {isWholeLine: false, hoverMessage: ['`' + numericToolTip + '`']} - }; - this.updateDecorations(); - } +Compiler.prototype.getBinaryForLine = function (line) { + var obj = this.assembly[line - 1]; + if (!obj) return '
????
????
'; + var address = obj.address ? obj.address.toString(16) : ''; + var opcodes = '
'; + _.each(obj.opcodes, function (op) { + opcodes += ('' + op + ''); + }); + return '
' + address + '
' + opcodes + '
'; +}; - var getTokensForLine = function (model, line) { - //Force line's state to be accurate - if (line > model.getLineCount()) return []; - model.getLineTokens(line, /*inaccurateTokensAcceptable*/false); - // Get the tokenization state at the beginning of this line - var state = model._lines[line - 1].getState(); - if (!state) return []; - var freshState = model._lines[line - 1].getState().clone(); - // Get the human readable tokens on this line - return model._tokenizationSupport.tokenize(model.getLineContent(line), freshState, 0).tokens; - }; +// TODO: use ContentWidgets? OverlayWidgets? +// Use highlight providers? hover providers? highlight providers? +Compiler.prototype.setAssembly = function (assembly) { + this.assembly = assembly; + if (this.outputEditor.getModel()) { + this.outputEditor.getModel().setValue(_.pluck(assembly, 'text').join('\n')); + var addrToAddrDiv = {}; + var decorations = []; + _.each(this.assembly, _.bind(function (obj, line) { + var address = obj.address ? obj.address.toString(16) : ''; + // var div = $("
" + address + "
"); + addrToAddrDiv[address] = {div: 'moo', line: line}; + }, this)); - if (this.settings.hoverShowAsmDoc === true && - _.some(getTokensForLine(this.outputEditor.getModel(), currentWord.range.startLineNumber), function (t) { - return t.offset + 1 === currentWord.startColumn && t.type === 'keyword.asm'; - })) { - getAsmInfo(currentWord.word).then(_.bind(function (response) { - if (response) { - this.decorations.asmToolTip = { - range: currentWord.range, - options: { - isWholeLine: false, - hoverMessage: [response.tooltip + '\n\nMore information available in the context menu.'] - } - }; - this.updateDecorations(); + _.each(this.assembly, _.bind(function (obj, line) { + if (obj.links) { + _.each(obj.links, _.bind(function (link) { + var address = link.to.toString(16); + // var thing = $("" + address + ""); + // this.outputEditor.markText( + // from, to, {replacedWith: thing[0], handleMouseEvents: false}); + var dest = addrToAddrDiv[address]; + if (dest) { + decorations.push({ + range: new monaco.Range(line, link.offset, line, link.offset + link.length), + options: {} + }); + // var editor = this.outputEditor; + // thing.hover(function (e) { + // var entered = e.type == "mouseenter"; + // dest.div.toggleClass("highlighted", entered); + // thing.toggleClass("highlighted", entered); + // }); + // thing.on('click', function (e) { + // editor.scrollIntoView({line: dest.line, ch: 0}, 30); + // dest.div.toggleClass("highlighted", false); + // thing.toggleClass("highlighted", false); + // e.preventDefault(); + // }); } }, this)); } - } - }; + }, this)); + } +}; - Compiler.prototype.onAsmToolTip = function (ed) { - var pos = ed.getPosition(); - var word = ed.getModel().getWordAtPosition(pos); - if (!word || !word.word) return; - var opcode = word.word.toUpperCase(); - getAsmInfo(word.word).then( - _.bind(function (asmHelp) { - if (asmHelp) { - new Alert().alert(opcode + ' help', asmHelp.html + - '

For more information, visit the ' + - opcode + ' documentation .', - function () { - ed.focus(); - ed.setPosition(pos); - } - ); - } else { - new Alert().notify('This token was not found in the documentation.
Only most Intel x86 opcodes supported for now.', { - group: 'notokenindocs', - alertClass: 'notification-error', - dismissTime: 3000 - }); +function errorResult(text) { + return {asm: fakeAsm(text), code: -1, stdout: '', stderr: ''}; +} + +function fakeAsm(text) { + return [{text: text, source: null, fake: true}]; +} + +Compiler.prototype.onCompileResponse = function (request, result, cached) { + // Delete trailing empty lines + if ($.isArray(result.asm)) { + var cutCount = 0; + for (var i = result.asm.length - 1; i >= 0; i--) { + if (result.asm[i].text) { + break; + } + cutCount++; + } + result.asm.splice(result.asm.length - cutCount, cutCount); + } + this.lastResult = result; + var timeTaken = Math.max(0, Date.now() - this.pendingRequestSentAt); + var wasRealReply = this.pendingRequestSentAt > 0; + this.pendingRequestSentAt = 0; + ga('send', { + hitType: 'event', + eventCategory: 'Compile', + eventAction: request.compiler, + eventLabel: request.options.userArguments, + eventValue: cached ? 1 : 0 + }); + ga('send', { + hitType: 'timing', + timingCategory: 'Compile', + timingVar: request.compiler, + timingValue: timeTaken + }); + this.setAssembly(result.asm || fakeAsm('')); + if (request.options.filters.binary) { + this.outputEditor.updateOptions({ + lineNumbers: _.bind(this.getBinaryForLine, this), + // Until something comes out of Microsoft/monaco-editor/issues/515, this gets clamped to ten + lineNumbersMinChars: 25, + glyphMargin: false + }); + } else { + this.outputEditor.updateOptions({ + lineNumbers: true, + lineNumbersMinChars: options.embedded ? 1 : 5, + glyphMargin: true + }); + } + var status = this.domRoot.find('.status'); + var allText = _.pluck((result.stdout || []).concat(result.stderr || []), 'text').join('\n'); + var failed = result.code !== 0; + var warns = !failed && !!allText; + status.toggleClass('error', failed); + status.toggleClass('warning', warns); + status.parent().attr('title', allText); + if (cached) { + this.compileTimeLabel.text(' - cached'); + } else if (wasRealReply) { + this.compileTimeLabel.text(' - ' + timeTaken + 'ms'); + } else { + this.compileTimeLabel.text(''); + } + this.eventHub.emit('compileResult', this.id, this.compiler, result); + this.updateButtons(); + + if (this.nextRequest) { + var next = this.nextRequest; + this.nextRequest = null; + this.sendCompile(next); + } +}; + +Compiler.prototype.onEditorChange = function (editor, source, langId, compilerId) { + if (editor === this.sourceEditorId && langId === this.currentLangId && (compilerId === undefined || compilerId === this.id)) { + this.source = source; + this.compile(); + } +}; + +Compiler.prototype.onOptViewClosed = function (id) { + if (this.id == id) { + this.wantOptInfo = false; + this.optViewOpen = false; + this.optButton.prop('disabled', this.optViewOpen); + } +}; + +Compiler.prototype.onAstViewOpened = function (id) { + if (this.id == id) { + this.astButton.prop('disabled', true); + this.astViewOpen = true; + this.compile(); + } +}; + +Compiler.prototype.onAstViewClosed = function (id) { + if (this.id === id) { + this.astButton.prop('disabled', false); + this.astViewOpen = false; + } +}; + +Compiler.prototype.onGccDumpUIInit = function (id) { + if (this.id === id) { + this.compile(); + } +}; + +Compiler.prototype.onGccDumpFiltersChanged = function (id, filters, reqCompile) { + if (this.id === id) { + this.treeDumpEnabled = (filters.treeDump !== false); + this.rtlDumpEnabled = (filters.rtlDump !== false); + + if (reqCompile) { + this.compile(); + } + } +}; + +Compiler.prototype.onGccDumpPassSelected = function (id, passId, reqCompile) { + if (this.id === id) { + this.gccDumpPassSelected = passId; + + if (reqCompile && passId !== '') { + this.compile(); + } + } +}; + +Compiler.prototype.onGccDumpViewOpened = function (id) { + if (this.id === id) { + this.gccDumpButton.prop('disabled', true); + this.gccDumpViewOpen = true; + } +}; + +Compiler.prototype.onGccDumpViewClosed = function (id) { + if (this.id === id) { + this.gccDumpButton.prop('disabled', !this.compiler.supportsGccDump); + this.gccDumpViewOpen = false; + + delete this.gccDumpPassSelected; + delete this.treeDumpEnabled; + delete this.rtlDumpEnabled; + } +}; + +Compiler.prototype.onOptViewOpened = function (id) { + if (this.id === id) { + this.optViewOpen = true; + this.wantOptInfo = true; + this.optButton.prop('disabled', this.optViewOpen); + this.compile(); + } +}; + +Compiler.prototype.onCfgViewOpened = function (id) { + if (this.id == id) { + this.cfgButton.prop('disabled', true); + this.cfgViewOpen = true; + this.compile(); + } +}; + +Compiler.prototype.onCfgViewClosed = function (id) { + if (this.id === id) { + this.cfgViewOpen = false; + this.cfgButton.prop('disabled', this.getEffectiveFilters().binary); + } +}; + + +Compiler.prototype.updateButtons = function () { + if (!this.compiler) return; + var filters = this.getEffectiveFilters(); + // We can support intel output if the compiler supports it, or if we're compiling + // to binary (as we can disassemble it however we like). + var intelAsm = this.compiler.supportsIntel || filters.binary; + this.domRoot.find("[data-bind='intel']").prop('disabled', !intelAsm); + // Disable binary support on compilers that don't work with it. + this.domRoot.find("[data-bind='binary']").prop('disabled', !this.compiler.supportsBinary); + this.domRoot.find("[data-bind='execute']").prop('disabled', !this.compiler.supportsExecute); + // Disable demangle for compilers where we can't access it + this.domRoot.find("[data-bind='demangle']").prop('disabled', !this.compiler.demangler); + // Disable any of the options which don't make sense in binary mode. + var filtersDisabled = !!filters.binary && !this.compiler.supportsFiltersInBinary; + this.domRoot.find('.nonbinary').prop('disabled', filtersDisabled); + // If its already open, we should turn the it off. + // The pane will update with error text + // Other wise we just disable the button. + if (!this.optViewOpen) { + this.optButton.prop('disabled', !this.compiler.supportsOptOutput); + } else { + this.optButton.prop('disabled', true); + } + + if (!this.cfgViewOpen) { + this.cfgButton.prop('disabled', !this.compiler.supportsCfg); + } else { + this.cfgButton.prop('disabled', true); + } + + if (!this.gccDumpViewOpen) { + this.gccDumpButton.prop('disabled', !this.compiler.supportsGccDump); + } else { + this.gccDumpButton.prop('disabled', true); + } +}; + +Compiler.prototype.onOptionsChange = function (options) { + this.options = options; + this.saveState(); + this.compile(); + this.updateButtons(); + this.sendCompiler(); +}; + +Compiler.prototype.onCompilerChange = function (value) { + this.compiler = this.compilerService.findCompiler(this.currentLangId, value); + this.saveState(); + this.compile(); + this.updateButtons(); + this.updateCompilerName(); + this.sendCompiler(); +}; + +Compiler.prototype.sendCompiler = function () { + this.eventHub.emit('compiler', this.id, this.compiler, this.options, this.sourceEditorId); +}; + +Compiler.prototype.onEditorClose = function (editor) { + if (editor === this.sourceEditorId) { + // We can't immediately close as an outer loop somewhere in GoldenLayout is iterating over + // the hierarchy. We can't modify while it's being iterated over. + this.close(); + _.defer(function (self) { + self.container.close(); + }, this); + } +}; + +Compiler.prototype.onFilterChange = function () { + this.eventHub.emit('filtersChange', this.id, this.getEffectiveFilters()); + this.saveState(); + this.compile(); + this.updateButtons(); +}; + +Compiler.prototype.currentState = function () { + var libs = []; + _.each(this.availableLibs[this.currentLangId], function (library, name) { + _.each(library.versions, function (version, ver) { + if (library.versions[ver].used) { + libs.push({name: name, ver: ver}); + } + }); + }); + var state = { + compiler: this.compiler ? this.compiler.id : '', + source: this.sourceEditorId, + options: this.options, + // NB must *not* be effective filters + filters: this.filters.get(), + wantOptInfo: this.wantOptInfo, + libs: libs, + lang: this.currentLangId + }; + this.fontScale.addState(state); + return state; +}; + +Compiler.prototype.saveState = function () { + this.container.setState(this.currentState()); +}; + +Compiler.prototype.updateFontScale = function () { + this.eventHub.emit('compilerFontScale', this.id, this.fontScale.scale); +}; + +Compiler.prototype.onColours = function (editor, colours, scheme) { + if (editor == this.sourceEditorId) { + var asmColours = {}; + _.each(this.assembly, function (x, index) { + if (x.source && x.source.file === null) { + asmColours[index] = colours[x.source.line - 1]; + } + }); + this.colours = colour.applyColours(this.outputEditor, asmColours, scheme, this.colours); + } +}; + +Compiler.prototype.getCompilerName = function () { + return this.compiler ? this.compiler.name : 'no compiler set'; +}; + +Compiler.prototype.updateCompilerName = function () { + var langName = options.languages[this.currentLangId].name; + var compilerName = this.getCompilerName(); + var compilerVersion = this.compiler ? this.compiler.version : ''; + this.container.setTitle(compilerName + ' (Editor #' + this.sourceEditorId + ', Compiler #' + this.id + ') ' + langName); + this.domRoot.find('.full-compiler-name').text(compilerVersion); +}; + +Compiler.prototype.onResendCompilation = function (id) { + if (id === this.id && !$.isEmptyObject(this.lastResult)) { + this.eventHub.emit('compileResult', this.id, this.compiler, this.lastResult); + } +}; + +Compiler.prototype.updateDecorations = function () { + this.prevDecorations = this.outputEditor.deltaDecorations( + this.prevDecorations, _.flatten(_.values(this.decorations), true)); +}; + +Compiler.prototype.onCompilerSetDecorations = function (id, lineNums, revealLine) { + if (id == this.id) { + if (revealLine && lineNums[0]) + this.outputEditor.revealLineInCenter(lineNums[0]); + this.decorations.linkedCode = _.map(lineNums, function (line) { + return { + range: new monaco.Range(line, 1, line, 1), + options: { + isWholeLine: true, + linesDecorationsClassName: 'linked-code-decoration-margin', + inlineClassName: 'linked-code-decoration-inline' } - }), function (rejection) { - new Alert().notify('There was an error fetching the documentation for this opcode (' + rejection + ').', { + }; + }); + this.updateDecorations(); + } +}; + +Compiler.prototype.onSettingsChange = function (newSettings) { + var before = this.settings; + this.settings = _.clone(newSettings); + if (!before.lastHoverShowSource && this.settings.hoverShowSource) { + this.onCompilerSetDecorations(this.id, []); + } + this.outputEditor.updateOptions({ + contextmenu: this.settings.useCustomContextMenu, + minimap: { + enabled: this.settings.showMinimap && !options.embedded + } + }); +}; + +var hexLike = /^(#?[$]|0x)([0-9a-fA-F]+)$/; +var hexLike2 = /^(#?)([0-9a-fA-F]+)H$/; +var decimalLike = /^(#?)(-?[0-9]+)$/; + +function getNumericToolTip(value) { + var match = hexLike.exec(value) || hexLike2.exec(value); + if (match) { + return value + ' = ' + bigInt(match[2], 16).toString(10); + } + match = decimalLike.exec(value); + if (match) { + var asBig = bigInt(match[2]); + if (asBig.isNegative()) { + asBig = bigInt('ffffffffffffffff', 16).and(asBig); + } + return value + ' = 0x' + asBig.toString(16).toUpperCase(); + } + + return null; +} + + +var getAsmInfo = function (opcode) { + var cacheName = 'asm/' + opcode; + var cached = OpcodeCache.get(cacheName); + if (cached) { + return Promise.resolve(cached.found ? cached.result : null); + } + return new Promise(function (resolve, reject) { + $.ajax({ + type: 'GET', + url: 'api/asm/' + opcode, + dataType: 'json', // Expected, + contentType: 'text/plain', // Sent + success: function (result) { + OpcodeCache.set(cacheName, result); + resolve(result.found ? result.result : null); + }, + error: function (result) { + reject(result); + }, + cache: true + }); + }); +}; + +Compiler.prototype.onMouseMove = function (e) { + if (e === null || e.target === null || e.target.position === null) return; + if (this.settings.hoverShowSource === true && this.assembly) { + var hoverAsm = this.assembly[e.target.position.lineNumber - 1]; + if (hoverAsm) { + // We check that we actually have something to show at this point! + this.eventHub.emit('editorSetDecoration', this.sourceEditorId, hoverAsm.source && !hoverAsm.source.file ? hoverAsm.source.line : -1, false); + } + } + var currentWord = this.outputEditor.getModel().getWordAtPosition(e.target.position); + if (currentWord && currentWord.word) { + var word = currentWord.word; + currentWord.range = new monaco.Range(e.target.position.lineNumber, currentWord.startColumn, e.target.position.lineNumber, currentWord.endColumn); + // Avoid throwing an exception if somehow (How?) we have a non existent lineNumber. c.f. https://sentry.io/matt-godbolt/compiler-explorer/issues/285270358/ + if (e.target.position.lineNumber < this.outputEditor.getModel().getLineCount()) { + // Hacky workaround to check for negative numbers. c.f. https://github.com/mattgodbolt/compiler-explorer/issues/434 + var lineContent = this.outputEditor.getModel().getLineContent(e.target.position.lineNumber); + if (lineContent[currentWord.startColumn - 2] === '-') { + word = '-' + word; + currentWord.range.startColumn -= 1; + } + } + var numericToolTip = getNumericToolTip(word); + if (numericToolTip) { + this.decorations.numericToolTip = { + range: currentWord.range, + options: {isWholeLine: false, hoverMessage: ['`' + numericToolTip + '`']} + }; + this.updateDecorations(); + } + + var getTokensForLine = function (model, line) { + //Force line's state to be accurate + if (line > model.getLineCount()) return []; + model.getLineTokens(line, /*inaccurateTokensAcceptable*/false); + // Get the tokenization state at the beginning of this line + var state = model._lines[line - 1].getState(); + if (!state) return []; + var freshState = model._lines[line - 1].getState().clone(); + // Get the human readable tokens on this line + return model._tokenizationSupport.tokenize(model.getLineContent(line), freshState, 0).tokens; + }; + + if (this.settings.hoverShowAsmDoc === true && + _.some(getTokensForLine(this.outputEditor.getModel(), currentWord.range.startLineNumber), function (t) { + return t.offset + 1 === currentWord.startColumn && t.type === 'keyword.asm'; + })) { + getAsmInfo(currentWord.word).then(_.bind(function (response) { + if (response) { + this.decorations.asmToolTip = { + range: currentWord.range, + options: { + isWholeLine: false, + hoverMessage: [response.tooltip + '\n\nMore information available in the context menu.'] + } + }; + this.updateDecorations(); + } + }, this)); + } + } +}; + +Compiler.prototype.onAsmToolTip = function (ed) { + var pos = ed.getPosition(); + var word = ed.getModel().getWordAtPosition(pos); + if (!word || !word.word) return; + var opcode = word.word.toUpperCase(); + getAsmInfo(word.word).then( + _.bind(function (asmHelp) { + if (asmHelp) { + new Alert().alert(opcode + ' help', asmHelp.html + + '

For more information, visit the ' + + opcode + ' documentation .', + function () { + ed.focus(); + ed.setPosition(pos); + } + ); + } else { + new Alert().notify('This token was not found in the documentation.
Only most Intel x86 opcodes supported for now.', { group: 'notokenindocs', alertClass: 'notification-error', dismissTime: 3000 }); } - ); - }; + }), function (rejection) { + new Alert().notify('There was an error fetching the documentation for this opcode (' + rejection + ').', { + group: 'notokenindocs', + alertClass: 'notification-error', + dismissTime: 3000 + }); + } + ); +}; - Compiler.prototype.updateLibsDropdown = function () { - this.updateAvailableLibs(); - this.libsButton.popover({ - container: 'body', - content: _.bind(function () { - var libsCount = _.keys(this.availableLibs[this.currentLangId]).length; - if (libsCount === 0) { - return $('

') - .text('No libs configured for ' + options.languages[this.currentLangId].name + ' yet. ') - .append($('') - .attr('target', '_blank') - .attr('rel', 'noopener noreferrer') - .attr('href', 'https://github.com/mattgodbolt/compiler-explorer/issues/new') - .text('You can suggest us one at any time ') - .append($('') - .addClass('glyphicon glyphicon-new-window') - .width('16px') - .height('16px') - .attr('title', 'Opens in a new window') - ) - ); - } - var columnCount = Math.ceil(libsCount / 5); - var currentLibIndex = -1; +Compiler.prototype.updateLibsDropdown = function () { + this.updateAvailableLibs(); + this.libsButton.popover({ + container: 'body', + content: _.bind(function () { + var libsCount = _.keys(this.availableLibs[this.currentLangId]).length; + if (libsCount === 0) { + return $('

') + .text('No libs configured for ' + options.languages[this.currentLangId].name + ' yet. ') + .append($('') + .attr('target', '_blank') + .attr('rel', 'noopener noreferrer') + .attr('href', 'https://github.com/mattgodbolt/compiler-explorer/issues/new') + .text('You can suggest us one at any time ') + .append($('') + .addClass('glyphicon glyphicon-new-window') + .width('16px') + .height('16px') + .attr('title', 'Opens in a new window') + ) + ); + } + var columnCount = Math.ceil(libsCount / 5); + var currentLibIndex = -1; - var libLists = []; - for (var i = 0; i < columnCount; i++) { - libLists.push($('
    ').addClass('lib-list')); - } + var libLists = []; + for (var i = 0; i < columnCount; i++) { + libLists.push($('
      ').addClass('lib-list')); + } - // Utility function so we can iterate indefinetly over our lists - var getNextList = function () { - currentLibIndex = (currentLibIndex + 1) % columnCount; - return libLists[currentLibIndex]; - }; - - var onChecked = _.bind(function (e) { - var elem = $(e.target); - // Uncheck every lib checkbox with the same name if we're checking the target - if (elem.prop('checked')) { - var others = $.find('input[name=\'' + elem.prop('name') + '\']'); - _.each(others, function (other) { - $(other).prop('checked', false); - }); - // Recheck the targeted one - elem.prop('checked', true); - } - // And now do the same with the availableLibs object - _.each(this.availableLibs[this.currentLangId][elem.prop('data-lib')].versions, function (version) { - version.used = false; - }); - this.availableLibs[this.currentLangId][elem.prop('data-lib')].versions[elem.prop('data-version')].used = elem.prop('checked'); - this.saveState(); - this.compile(); - }, this); - - _.each(this.availableLibs[this.currentLangId], function (lib, libKey) { - var libsList = getNextList(); - var libHeader = $('') - .text(lib.name + ' ') - .addClass('lib-header'); - if (lib.url && lib.url.length >= 1) { - libHeader.append($('') - .prop('href', lib.url) - .prop('target', '_blank') - .prop('rel', 'noopener noreferrer') - .append($('') - .addClass('glyphicon glyphicon-new-window') - ) - ); - } - var libCat = $('
    • ') - .append(libHeader) - .addClass('lib-item'); - - var libGroup = $('
      '); - - if (libsList.children().length > 0) - libsList.append($('
      ').addClass('lib-separator')); - - _.each(lib.versions, function (version, vKey) { - libGroup.append($('
      ') - .append($('') - .addClass('lib-checkbox') - .prop('data-lib', libKey) - .prop('data-version', vKey) - .prop('checked', version.used) - .prop('name', libKey) - .on('change', onChecked) - ).append($('') - .addClass('lib-label') - .text(lib.name + ' ' + version.version) - .on('click', function () { - $(this).parent().find('.lib-checkbox').trigger('click'); - }) - ) - ); - }); - libGroup.appendTo(libCat); - libCat.appendTo(libsList); - }); - return $('
      ').addClass('libs-container').append(libLists); - }, this), - html: true, - placement: 'bottom', - trigger: 'manual' - }).click(_.bind(function () { - this.libsButton.popover('show'); - }, this)).on('show.bs.popover', function () { - $(this).data('bs.popover').tip().css('max-width', '100%').css('width', 'auto'); - }); - }; - - Compiler.prototype.onLanguageChange = function (editorId, newLangId) { - if (this.sourceEditorId === editorId) { - var oldLangId = this.currentLangId; - this.currentLangId = newLangId; - // Store the current selected stuff to come back to it later in the same session (Not state stored!) - this.infoByLang[oldLangId] = { - compiler: this.compiler && this.compiler.id ? this.compiler.id : options.defaultCompiler[oldLangId], - options: this.options + // Utility function so we can iterate indefinetly over our lists + var getNextList = function () { + currentLibIndex = (currentLibIndex + 1) % columnCount; + return libLists[currentLibIndex]; }; - this.updateLibsDropdown(); - this.updateCompilersSelector(); - this.updateCompilerName(); - this.saveState(); - } - }; - Compiler.prototype.getCurrentLangCompilers = function () { - return this.compilerService.getCompilersForLang(this.currentLangId); - }; + var onChecked = _.bind(function (e) { + var elem = $(e.target); + // Uncheck every lib checkbox with the same name if we're checking the target + if (elem.prop('checked')) { + var others = $.find('input[name=\'' + elem.prop('name') + '\']'); + _.each(others, function (other) { + $(other).prop('checked', false); + }); + // Recheck the targeted one + elem.prop('checked', true); + } + // And now do the same with the availableLibs object + _.each(this.availableLibs[this.currentLangId][elem.prop('data-lib')].versions, function (version) { + version.used = false; + }); + this.availableLibs[this.currentLangId][elem.prop('data-lib')].versions[elem.prop('data-version')].used = elem.prop('checked'); + this.saveState(); + this.compile(); + }, this); - Compiler.prototype.updateCompilersSelector = function () { - var selector = this.domRoot.find('.compiler-picker')[0].selectize; - selector.clearOptions(true); - selector.clearOptionGroups(); - _.each(this.getGroupsInUse(), function (group) { - selector.addOptionGroup(group.value, {label: group.label}); - }, this); - selector.load(_.bind(function (callback) { - callback(_.map(this.getCurrentLangCompilers(), _.identity, this)); + _.each(this.availableLibs[this.currentLangId], function (lib, libKey) { + var libsList = getNextList(); + var libHeader = $('') + .text(lib.name + ' ') + .addClass('lib-header'); + if (lib.url && lib.url.length >= 1) { + libHeader.append($('') + .prop('href', lib.url) + .prop('target', '_blank') + .prop('rel', 'noopener noreferrer') + .append($('') + .addClass('glyphicon glyphicon-new-window') + ) + ); + } + var libCat = $('
    • ') + .append(libHeader) + .addClass('lib-item'); + + var libGroup = $('
      '); + + if (libsList.children().length > 0) + libsList.append($('
      ').addClass('lib-separator')); + + _.each(lib.versions, function (version, vKey) { + libGroup.append($('
      ') + .append($('') + .addClass('lib-checkbox') + .prop('data-lib', libKey) + .prop('data-version', vKey) + .prop('checked', version.used) + .prop('name', libKey) + .on('change', onChecked) + ).append($('') + .addClass('lib-label') + .text(lib.name + ' ' + version.version) + .on('click', function () { + $(this).parent().find('.lib-checkbox').trigger('click'); + }) + ) + ); + }); + libGroup.appendTo(libCat); + libCat.appendTo(libsList); + }); + return $('
      ').addClass('libs-container').append(libLists); + }, this), + html: true, + placement: 'bottom', + trigger: 'manual' + }).click(_.bind(function () { + this.libsButton.popover('show'); + }, this)).on('show.bs.popover', function () { + $(this).data('bs.popover').tip().css('max-width', '100%').css('width', 'auto'); + }); +}; + +Compiler.prototype.onLanguageChange = function (editorId, newLangId) { + if (this.sourceEditorId === editorId) { + var oldLangId = this.currentLangId; + this.currentLangId = newLangId; + // Store the current selected stuff to come back to it later in the same session (Not state stored!) + this.infoByLang[oldLangId] = { + compiler: this.compiler && this.compiler.id ? this.compiler.id : options.defaultCompiler[oldLangId], + options: this.options + }; + this.updateLibsDropdown(); + this.updateCompilersSelector(); + this.updateCompilerName(); + this.saveState(); + } +}; + +Compiler.prototype.getCurrentLangCompilers = function () { + return this.compilerService.getCompilersForLang(this.currentLangId); +}; + +Compiler.prototype.updateCompilersSelector = function () { + var selector = this.domRoot.find('.compiler-picker')[0].selectize; + selector.clearOptions(true); + selector.clearOptionGroups(); + _.each(this.getGroupsInUse(), function (group) { + selector.addOptionGroup(group.value, {label: group.label}); + }, this); + selector.load(_.bind(function (callback) { + callback(_.map(this.getCurrentLangCompilers(), _.identity, this)); + }, this)); + var defaultOrFirst = _.bind(function defaultOrFirst() { + // If the default is a valid compiler, return it + var defaultCompiler = options.defaultCompiler[this.currentLangId]; + if (defaultCompiler) return defaultCompiler; + // Else try to find the first one for this language + var value = _.find(options.compilers, _.bind(function (compiler) { + return compiler.lang === this.currentLangId; }, this)); - var defaultOrFirst = _.bind(function defaultOrFirst() { - // If the default is a valid compiler, return it - var defaultCompiler = options.defaultCompiler[this.currentLangId]; - if (defaultCompiler) return defaultCompiler; - // Else try to find the first one for this language - var value = _.find(options.compilers, _.bind(function (compiler) { - return compiler.lang === this.currentLangId; - }, this)); - // Return the first, or an empty string if none found (Should prob report this one...) - return value && value.id ? value.id : ""; - }, this); - var info = this.infoByLang[this.currentLangId] || {}; - this.compiler = this.findCompiler(this.currentLangId, info.compiler || defaultOrFirst()); - if (this.compiler) selector.setValue([this.compiler.id], true); - this.options = info.options || ""; - this.optionsField.val(this.options); - }; + // Return the first, or an empty string if none found (Should prob report this one...) + return value && value.id ? value.id : ""; + }, this); + var info = this.infoByLang[this.currentLangId] || {}; + this.compiler = this.findCompiler(this.currentLangId, info.compiler || defaultOrFirst()); + if (this.compiler) selector.setValue([this.compiler.id], true); + this.options = info.options || ""; + this.optionsField.val(this.options); +}; - Compiler.prototype.findCompiler = function (langId, compilerId) { - return this.compilerService.findCompiler(langId, compilerId); - }; +Compiler.prototype.findCompiler = function (langId, compilerId) { + return this.compilerService.findCompiler(langId, compilerId); +}; - Compiler.prototype.langOfCompiler = function (compilerId) { - var compiler = _.find(options.compilers, function (compiler) { - return compiler.id === compilerId || compiler.alias === compilerId; - }); - if (!compiler) { - Raven.captureMessage('Unable to find compiler id "' + compilerId + '"'); - compiler = options.compilers[0]; - } - return compiler.lang; - }; +Compiler.prototype.langOfCompiler = function (compilerId) { + var compiler = _.find(options.compilers, function (compiler) { + return compiler.id === compilerId || compiler.alias === compilerId; + }); + if (!compiler) { + Raven.captureMessage('Unable to find compiler id "' + compilerId + '"'); + compiler = options.compilers[0]; + } + return compiler.lang; +}; + +module.exports = { + Compiler: Compiler +}; - return { - Compiler: Compiler - }; -}); diff --git a/static/conformance-view.js b/static/conformance-view.js index 7a1e4b8ab..d97e63f5d 100644 --- a/static/conformance-view.js +++ b/static/conformance-view.js @@ -23,291 +23,300 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -define(function (require) { - "use strict"; +"use strict"; - var options = require('options'); - var _ = require('underscore'); - var $ = require('jquery'); +var options = require('options'); +var _ = require('underscore'); +var $ = require('jquery'); - require('selectize'); +require('selectize'); - function Conformance(hub, container, state) { - this.container = container; - this.eventHub = hub.createEventHub(); - this.compilerService = hub.compilerService; - this.domRoot = container.getElement(); - this.domRoot.html($('#conformance').html()); - this.selectorList = this.domRoot.find('.compiler-list'); - this.addCompilerButton = this.domRoot.find('.add-compiler'); - this.selectorTemplate = $('#compiler-selector .compiler-row'); - this.editorId = state.editorid; - this.nextSelectorId = 0; - this.maxCompilations = options.cvCompilerCountMax || 6; - this.langId = state.langId || _.keys(options.languages)[0]; - this.source = state.source || ""; +function Conformance(hub, container, state) { + this.container = container; + this.eventHub = hub.createEventHub(); + this.compilerService = hub.compilerService; + this.domRoot = container.getElement(); + this.domRoot.html($('#conformance').html()); + this.selectorList = this.domRoot.find('.compiler-list'); + this.addCompilerButton = this.domRoot.find('.add-compiler'); + this.selectorTemplate = $('#compiler-selector .compiler-row'); + this.editorId = state.editorid; + this.nextSelectorId = 0; + this.maxCompilations = options.cvCompilerCountMax || 6; + this.langId = state.langId || _.keys(options.languages)[0]; + this.source = state.source || ""; - this.status = { - allowCompile: false, - allowAdd: true - }; - this.stateByLang = {}; - - this.container.on('destroy', this.close, this); - - this.container.on('open', function () { - this.eventHub.emit("conformanceViewOpen", this.editorId); - }, this); - - this.eventHub.on('resize', this.resize, this); - this.container.on('resize', this.resize, this); - - this.container.on('shown', this.resize, this); - - this.eventHub.on('editorChange', this.onEditorChange, this); - this.eventHub.on('editorClose', this.onEditorClose, this); - this.eventHub.on('languageChange', this.onLanguageChange, this); - - this.addCompilerButton.on('click', _.bind(function () { - this.addCompilerSelector(); - this.saveState(); - }, this)); - - this.initFromState(state); - this.handleToolbarUI(); - } - - Conformance.prototype.setTitle = function (compilerCount) { - this.container.setTitle(options.languages[this.langId].name + " Conformance viewer (Editor #" + this.editorId + ") " + ( - compilerCount !== 0 ? (compilerCount + "/" + this.maxCompilations) : "" - )); + this.status = { + allowCompile: false, + allowAdd: true }; + this.stateByLang = {}; - Conformance.prototype.addCompilerSelector = function (config) { - if (!config) { - config = { - // Code we have - cv: this.nextSelectorId, - // Compiler id which is being used - compilerId: "", - // Options which are in use - options: "", - }; - this.nextSelectorId++; - } - - config.cv = Number(config.cv); - - var newEntry = this.selectorTemplate.clone(); - - newEntry.attr("data-cv", config.cv); - - var onOptionsChange = _.debounce(_.bind(function () { - this.saveState(); - this.compileAll(); - }, this), 800); - - newEntry.find('.options') - .attr("data-cv", config.cv) - .val(config.options) - .on("click", onOptionsChange) - .on("keyup", onOptionsChange); - - newEntry.find('.close') - .attr("data-cv", config.cv) - .on("click", _.bind(function () { - this.removeCompilerSelector(config.cv); - }, this)); - - this.selectorList.append(newEntry); - - var status = newEntry.find('.status').attr("data-cv", config.cv); - var langId = this.langId; - var isVisible = function (compiler) { - return compiler.lang === langId; - }; - - newEntry.find('.compiler-picker') - .attr("data-cv", config.cv) - .selectize({ - sortField: 'name', - valueField: 'id', - labelField: 'name', - searchField: ['name'], - options: _.filter(options.compilers, isVisible), - items: config.compilerId ? [config.compilerId] : [] - }) - .on('change', _.bind(function () { - // Hide the results button when a new compiler is selected - this.handleStatusIcon(status, {code: 0, text: ""}); - // We could narrow the compilation to only this compiler! - this.compileAll(); - // We're not saving state here. It's done after compiling - }, this)); - this.handleStatusIcon(status, {code: 0, text: ""}); - this.handleToolbarUI(); - this.saveState(); - }; - - Conformance.prototype.removeCompilerSelector = function (cv) { - _.each(this.selectorList.children(), function (row) { - var child = $(row); - if (child.attr("data-cv") == cv) { - child.remove(); - } - }, this); - this.handleToolbarUI(); - this.saveState(); - }; - - Conformance.prototype.onEditorChange = function (editorId, newSource, langId) { - if (editorId == this.editorId) { - this.langId = langId; - this.source = newSource; - this.compileAll(); - } - }; - - Conformance.prototype.onEditorClose = function (editorId) { - if (editorId === this.editorId) { - this.close(); - _.defer(function (self) { - self.container.close(); - }, this); - } - }; - - Conformance.prototype.onCompileResponse = function (cv, result) { - var allText = _.pluck((result.stdout || []).concat(result.stderr || []), 'text').join("\n"); - var failed = result.code !== 0; - var warns = !failed && !!allText; - var status = { - text: allText.replace(/\x1b\\[[0-9;]*m/, ''), - code: failed ? 3 : (warns ? 2 : 1) - }; - this.handleStatusIcon(this.selectorList.find('[data-cv="' + cv + '"] .status'), status); - this.saveState(); - }; - - Conformance.prototype.compileAll = function () { - if (!this.source) return; - // Hide previous status icons - this.selectorList.find('.status').css("visibility", "hidden"); - this.compilerService.expand(this.source).then(_.bind(function (expanded) { - var compileCount = 0; - _.each(this.selectorList.children(), _.bind(function (child) { - var picker = $(child).find('.compiler-picker'); - // We make sure we are not over our limit - if (picker && compileCount < this.maxCompilations) { - compileCount++; - if (picker.val()) { - var cv = Number(picker.attr("data-cv")); - var request = { - source: expanded || "", - compiler: picker.val(), - options: { - userArguments: $(child).find(".options[data-cv='" + cv + "']").val(), - filters: {}, - compilerOptions: {produceAst: false, produceOptInfo: false} - } - }; - // This error function ensures that the user will know we had a problem (As we don't save asm) - this.compilerService.submit(request) - .then(_.bind(function (x) { - this.onCompileResponse(cv, x.result); - }, this)) - .catch(_.bind(function (x) { - this.onCompileResponse(cv, { - asm: "", - code: -1, - stdout: "", - stderr: x.error - }); - }, this)); - } - } - }, this)); - }, this)); - }; - - Conformance.prototype.handleToolbarUI = function () { - var compilerCount = this.selectorList.children().length; - - // Only allow new compilers if we allow for more - this.addCompilerButton.attr("disabled", compilerCount >= this.maxCompilations); - - this.setTitle(compilerCount); - }; - - Conformance.prototype.handleStatusIcon = function (element, status) { - if (!element) return; - element.attr("class", "status glyphicon glyphicon-" + (status.code === 3 ? "remove-sign" : (status.code === 2 ? "info-sign" : "ok-sign"))) - .css("visibility", status.code === 0 ? "hidden" : "visible") - .css("color", status.code === 3 ? "red" : (status.code === 2 ? "yellow" : "green")) - .attr("title", status.text) - .attr("aria-label", status.code === 3 ? "Compilation failed!" : (status.code === 2 ? "Compiled with warnings" : "Compiled without warnings")) - .attr("data-status", status.code); - }; - - Conformance.prototype.currentState = function () { - var state = { - editorid: this.editorId, - langId: this.langId, - compilers: [] - }; - _.each(this.selectorList.children(), _.bind(function (child) { - state.compilers.push({ - // Code we have - cv: $(child).attr("data-cv"), - // Compiler which is being used - compilerId: $(child).find('.compiler-picker').val(), - // Options which are in use - options: $(child).find(".options").val(), - }); - }, this)); - return state; - }; - - Conformance.prototype.saveState = function () { - this.container.setState(this.currentState()); - }; - - Conformance.prototype.resize = function () { - this.selectorList.css("height", this.domRoot.height() - this.domRoot.find('.top-bar').outerHeight(true)); - }; - - Conformance.prototype.onLanguageChange = function (editorId, newLangId) { - if (editorId === this.editorId && this.langId !== newLangId) { - var oldLangId = this.langId; - this.stateByLang[oldLangId] = this.currentState(); - - this.langId = newLangId; - this.selectorList.children().remove(); - this.nextSelectorId = 0; - if (this.stateByLang[newLangId]) { - this.initFromState(this.stateByLang[newLangId]); - } - this.handleToolbarUI(); - this.saveState(); - } - }; - - Conformance.prototype.initFromState = function (state) { - if (state.compilers) { - _.each(state.compilers, _.bind(function (config) { - config.cv = this.nextSelectorId; - this.nextSelectorId++; - this.addCompilerSelector(config); - }, this)); - } - }; - - Conformance.prototype.close = function () { + this.container.on('destroy', function () { this.eventHub.unsubscribe(); this.eventHub.emit("conformanceViewClose", this.editorId); + }, this); + + this.container.on('destroy', this.close, this); + this.container.on('open', function () { + this.eventHub.emit("conformanceViewOpen", this.editorId); + }, this); + + this.eventHub.on('resize', this.resize, this); + this.container.on('resize', this.resize, this); + this.eventHub.on('editorChange', this.onEditorChange, this); + this.eventHub.on('editorClose', this.onEditorClose, this); + this.eventHub.on('languageChange', this.onLanguageChange, this); + this.container.on('shown', this.resize, this); + + this.eventHub.on('editorChange', this.onEditorChange, this); + this.eventHub.on('editorClose', this.onEditorClose, this); + + this.addCompilerButton.on('click', _.bind(function () { + this.addCompilerSelector(); + this.saveState(); + }, this)); + + if (state.compilers) { + _.each(state.compilers, _.bind(function (config) { + config.cv = this.nextSelectorId; + this.nextSelectorId++; + this.addCompilerSelector(config); + }, this)); + } + + this.handleToolbarUI(); +} + +Conformance.prototype.setTitle = function (compilerCount) { + this.container.setTitle("Conformance viewer (Editor #" + this.editorId + ") " + ( + compilerCount !== 0 ? (compilerCount + "/" + this.maxCompilations) : "" + )); +}; + + +Conformance.prototype.addCompilerSelector = function (config) { + if (!config) { + config = { + // Code we have + cv: this.nextSelectorId, + // Compiler id which is being used + compilerId: "", + // Options which are in use + options: "", + }; + this.nextSelectorId++; + } + + config.cv = Number(config.cv); + + var newEntry = this.selectorTemplate.clone(); + + newEntry.attr("data-cv", config.cv); + + var onOptionsChange = _.debounce(_.bind(function () { + this.saveState(); + this.compileAll(); + }, this), 800); + + newEntry.find('.options') + .attr("data-cv", config.cv) + .val(config.options) + .on("click", onOptionsChange) + .on("keyup", onOptionsChange); + + newEntry.find('.close') + .attr("data-cv", config.cv) + .on("click", _.bind(function () { + this.removeCompilerSelector(config.cv); + }, this)); + + this.selectorList.append(newEntry); + + var status = newEntry.find('.status').attr("data-cv", config.cv); + var langId = this.langId; + var isVisible = function (compiler) { + return compiler.lang === langId; }; - return { - Conformance: Conformance + newEntry.find('.compiler-picker') + .attr("data-cv", config.cv) + .selectize({ + sortField: 'name', + valueField: 'id', + labelField: 'name', + searchField: ['name'], + options: _.filter(options.compilers, isVisible), + items: config.compilerId ? [config.compilerId] : [] + }) + .on('change', _.bind(function () { + // Hide the results button when a new compiler is selected + this.handleStatusIcon(status, {code: 0, text: ""}); + // We could narrow the compilation to only this compiler! + this.compileAll(); + // We're not saving state here. It's done after compiling + }, this)); + this.handleStatusIcon(status, {code: 0, text: ""}); + this.handleToolbarUI(); + this.saveState(); +}; +Conformance.prototype.removeCompilerSelector = function (cv) { + _.each(this.selectorList.children(), function (row) { + var child = $(row); + if (child.attr("data-cv") == cv) { + child.remove(); + } + }, this); + this.handleToolbarUI(); + this.saveState(); +}; + +Conformance.prototype.onEditorChange = function (editorId, newSource, langId) { + if (editorId == this.editorId) { + this.langId = langId; + this.source = newSource; + this.compileAll(); + } +}; + +Conformance.prototype.onEditorClose = function (editorId) { + if (editorId == this.editorId) { + this.close(); + _.defer(function (self) { + self.container.close(); + }, this); + } +}; + +Conformance.prototype.onCompileResponse = function (cv, result) { + var allText = _.pluck((result.stdout || []).concat(result.stderr || []), 'text').join("\n"); + var failed = result.code !== 0; + var warns = !failed && !!allText; + var status = { + text: allText.replace(/\x1b\\[[0-9;]*m/, ''), + code: failed ? 3 : (warns ? 2 : 1) }; -}); + this.handleStatusIcon(this.selectorList.find('[data-cv="' + cv + '"] .status'), status); + this.saveState(); +}; + +Conformance.prototype.compileAll = function () { + if (!this.source) return; + // Hide previous status icons + this.selectorList.find('.status').css("visibility", "hidden"); + this.compilerService.expand(this.source).then(_.bind(function (expanded) { + var compileCount = 0; + _.each(this.selectorList.children(), _.bind(function (child) { + var picker = $(child).find('.compiler-picker'); + // We make sure we are not over our limit + if (picker && compileCount < this.maxCompilations) { + compileCount++; + if (picker.val()) { + var cv = Number(picker.attr("data-cv")); + var request = { + source: expanded || "", + compiler: picker.val(), + options: { + userArguments: $(child).find(".options[data-cv='" + cv + "']").val(), + filters: {}, + compilerOptions: {produceAst: false, produceOptInfo: false} + } + }; + // This error function ensures that the user will know we had a problem (As we don't save asm) + this.compilerService.submit(request) + .then(_.bind(function (x) { + this.onCompileResponse(cv, x.result); + }, this)) + .catch(_.bind(function (x) { + this.onCompileResponse(cv, { + asm: "", + code: -1, + stdout: "", + stderr: x.error + }); + }, this)); + } + } + }, this)); + }, this)); +}; + +Conformance.prototype.handleToolbarUI = function () { + var compilerCount = this.selectorList.children().length; + + // Only allow new compilers if we allow for more + this.addCompilerButton.attr("disabled", compilerCount >= this.maxCompilations); + + this.setTitle(compilerCount); +}; + +Conformance.prototype.handleStatusIcon = function (element, status) { + if (!element) return; + element.attr("class", "status glyphicon glyphicon-" + (status.code === 3 ? "remove-sign" : (status.code === 2 ? "info-sign" : "ok-sign"))) + .css("visibility", status.code === 0 ? "hidden" : "visible") + .css("color", status.code === 3 ? "red" : (status.code === 2 ? "yellow" : "green")) + .attr("title", status.text) + .attr("aria-label", status.code === 3 ? "Compilation failed!" : (status.code === 2 ? "Compiled with warnings" : "Compiled without warnings")) + .attr("data-status", status.code); +}; + +Conformance.prototype.currentState = function () { + var state = { + editorid: this.editorId, + langId: this.langId, + compilers: [] + }; + _.each(this.selectorList.children(), _.bind(function (child) { + state.compilers.push({ + // Code we have + cv: $(child).attr("data-cv"), + // Compiler which is being used + compilerId: $(child).find('.compiler-picker').val(), + // Options which are in use + options: $(child).find(".options").val(), + }); + }, this)); + return state; +}; + +Conformance.prototype.saveState = function () { + this.container.setState(this.currentState()); +}; + +Conformance.prototype.resize = function () { + this.selectorList.css("height", this.domRoot.height() - this.domRoot.find('.top-bar').outerHeight(true)); +}; + +Conformance.prototype.onLanguageChange = function (editorId, newLangId) { + if (editorId === this.editorId && this.langId !== newLangId) { + var oldLangId = this.langId; + this.stateByLang[oldLangId] = this.currentState(); + + this.langId = newLangId; + this.selectorList.children().remove(); + this.nextSelectorId = 0; + if (this.stateByLang[newLangId]) { + this.initFromState(this.stateByLang[newLangId]); + } + this.handleToolbarUI(); + this.saveState(); + } +}; + +Conformance.prototype.close = function () { + this.eventHub.unsubscribe(); + this.eventHub.emit("conformanceViewClose", this.editorId); +}; + +Conformance.prototype.initFromState = function (state) { + if (state.compilers) { + _.each(state.compilers, _.bind(function (config) { + config.cv = this.nextSelectorId; + this.nextSelectorId++; + this.addCompilerSelector(config); + }, this)); + } +}; +module.exports = { + Conformance: Conformance +}; diff --git a/static/cppp-mode.js b/static/cppp-mode.js index deaeb07f1..8d36db6d2 100644 --- a/static/cppp-mode.js +++ b/static/cppp-mode.js @@ -1,48 +1,45 @@ -define(function (require) { - 'use strict'; - var $ = require('jquery'); - var monaco = require('monaco'); - var cpp = require('vs/basic-languages/src/cpp'); +'use strict'; +var $ = require('jquery'); +var cpp = require('vs/basic-languages/src/cpp'); - // We need to create a new definition for cpp so we can remove invalid keywords +// We need to create a new definition for cpp so we can remove invalid keywords - function definition() { - var cppp = $.extend(true, {}, cpp.language); // deep copy +function definition() { + var cppp = $.extend(true, {}, cpp.language); // deep copy - function removeKeyword(keyword) { - var index = cppp.keywords.indexOf(keyword); - if (index > -1) { - cppp.keywords.splice(index, 1); - } + function removeKeyword(keyword) { + var index = cppp.keywords.indexOf(keyword); + if (index > -1) { + cppp.keywords.splice(index, 1); } - - function removeKeywords(keywords) { - for (var i = 0; i < keywords.length; ++i) { - removeKeyword(keywords[i]); - } - } - - function addKeywords(keywords) { - // (Ruben) Done one by one as if you just push them all, Monaco complains that they're not strings, but as - // far as I can tell, they indeed are all strings. This somehow fixes it. If you know how to fix it, plz go - for (var i = 0; i < keywords.length; ++i) { - cppp.keywords.push(keywords[i]); - } - } - - // We remove everything that's not an identifier, underscore reserved name and not an official C++ keyword... - // Regarding #617, final is a identifier with special meaning, not a fully qualified keyword - removeKeywords(["abstract", "amp", "array", "cpu", "delegate", "each", "event", "finally", "gcnew", - "generic", "in", "initonly", "interface", "interior_ptr", "internal", "literal", "partial", "pascal", - "pin_ptr", "property", "ref", "restrict", "safe_cast", "sealed", "title_static", "where"]); - - addKeywords(["alignas", "alignof", "and", "and_eq", "asm", "bitand", "bitor", "char16_t", "char32_t", "compl", - "not", "not_eq", "or", "or_eq", "xor", "xor_eq"]); - - return cppp; } - monaco.languages.register({id: 'cppp'}); - monaco.languages.setLanguageConfiguration('cppp', cpp.conf); - monaco.languages.setMonarchTokensProvider('cppp', definition()); -}); + function removeKeywords(keywords) { + for (var i = 0; i < keywords.length; ++i) { + removeKeyword(keywords[i]); + } + } + + function addKeywords(keywords) { + // (Ruben) Done one by one as if you just push them all, Monaco complains that they're not strings, but as + // far as I can tell, they indeed are all strings. This somehow fixes it. If you know how to fix it, plz go + for (var i = 0; i < keywords.length; ++i) { + cppp.keywords.push(keywords[i]); + } + } + + // We remove everything that's not an identifier, underscore reserved name and not an official C++ keyword... + // Regarding #617, final is a identifier with special meaning, not a fully qualified keyword + removeKeywords(["abstract", "amp", "array", "cpu", "delegate", "each", "event", "finally", "gcnew", + "generic", "in", "initonly", "interface", "interior_ptr", "internal", "literal", "partial", "pascal", + "pin_ptr", "property", "ref", "restrict", "safe_cast", "sealed", "title_static", "where"]); + + addKeywords(["alignas", "alignof", "and", "and_eq", "asm", "bitand", "bitor", "char16_t", "char32_t", "compl", + "not", "not_eq", "or", "or_eq", "xor", "xor_eq"]); + + return cppp; +} + +monaco.languages.register({id: 'cppp'}); +monaco.languages.setLanguageConfiguration('cppp', cpp.conf); +monaco.languages.setMonarchTokensProvider('cppp', definition()); diff --git a/static/d-mode.js b/static/d-mode.js index 476719f03..a22c6838b 100644 --- a/static/d-mode.js +++ b/static/d-mode.js @@ -21,263 +21,259 @@ // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. +"use strict"; -define(function (require) { - "use strict"; - var monaco = require('monaco'); +function definition() { + return { + defaultToken: 'invalid', - function definition() { - return { - defaultToken: 'invalid', + keywords: [ + 'abstract', + 'alias', + 'align', + 'asm', + 'assert', + 'auto', + 'body', + 'bool', + 'break', + 'byte', + 'case', + 'cast', + 'catch', + 'cdouble', + 'cent', + 'cfloat', + 'char', + 'class', + 'const', + 'continue', + 'creal', + 'dchar', + 'debug', + 'default', + 'delegate', + 'delete ', + 'deprecated', + 'do', + 'double', + 'else', + 'enum', + 'export', + 'extern', + 'false', + 'final', + 'finally', + 'float', + 'for', + 'foreach', + 'foreach_reverse', + 'function', + 'goto', + 'idouble', + 'if', + 'ifloat', + 'immutable', + 'import', + 'in', + 'inout', + 'int', + 'interface', + 'invariant', + 'ireal', + 'is', + 'lazy', + 'long', + 'macro', + 'mixin', + 'module', + 'new', + 'nothrow', + 'null', + 'out', + 'override', + 'package', + 'pragma', + 'private', + 'protected', + 'public', + 'pure', + 'real', + 'ref', + 'return', + 'scope', + 'shared', + 'short', + 'static', + 'struct', + 'super', + 'switch', + 'synchronized', + 'template', + 'this', + 'throw', + 'true', + 'try', + 'typedef', + 'typeid', + 'typeof', + 'ubyte', + 'ucent', + 'uint', + 'ulong', + 'union', + 'unittest', + 'ushort', + 'version', + 'void', + 'volatile', + 'wchar', + 'while', + 'with', + '__FILE__', + '__FILE_FULL_PATH__', + '__MODULE__', + '__LINE__', + '__FUNCTION__', + '__PRETTY_FUNCTION__', + '__gshared', + '__traits', + '__vector', + '__parameters'], - keywords: [ - 'abstract', - 'alias', - 'align', - 'asm', - 'assert', - 'auto', - 'body', - 'bool', - 'break', - 'byte', - 'case', - 'cast', - 'catch', - 'cdouble', - 'cent', - 'cfloat', - 'char', - 'class', - 'const', - 'continue', - 'creal', - 'dchar', - 'debug', - 'default', - 'delegate', - 'delete ', - 'deprecated', - 'do', - 'double', - 'else', - 'enum', - 'export', - 'extern', - 'false', - 'final', - 'finally', - 'float', - 'for', - 'foreach', - 'foreach_reverse', - 'function', - 'goto', - 'idouble', - 'if', - 'ifloat', - 'immutable', - 'import', - 'in', - 'inout', - 'int', - 'interface', - 'invariant', - 'ireal', - 'is', - 'lazy', - 'long', - 'macro', - 'mixin', - 'module', - 'new', - 'nothrow', - 'null', - 'out', - 'override', - 'package', - 'pragma', - 'private', - 'protected', - 'public', - 'pure', - 'real', - 'ref', - 'return', - 'scope', - 'shared', - 'short', - 'static', - 'struct', - 'super', - 'switch', - 'synchronized', - 'template', - 'this', - 'throw', - 'true', - 'try', - 'typedef', - 'typeid', - 'typeof', - 'ubyte', - 'ucent', - 'uint', - 'ulong', - 'union', - 'unittest', - 'ushort', - 'version', - 'void', - 'volatile', - 'wchar', - 'while', - 'with', - '__FILE__', - '__FILE_FULL_PATH__', - '__MODULE__', - '__LINE__', - '__FUNCTION__', - '__PRETTY_FUNCTION__', - '__gshared', - '__traits', - '__vector', - '__parameters'], + typeKeywords: [ + 'bool', 'byte', 'ubyte', 'short', 'ushort', 'int', 'uint', 'long', 'ulong', 'char', 'wchar', 'dchar', + 'float', 'double', 'real', 'ifloat', 'idouble', 'ireal', 'cfloat', 'cdouble', 'creal', 'void' + ], - typeKeywords: [ - 'bool', 'byte', 'ubyte', 'short', 'ushort', 'int', 'uint', 'long', 'ulong', 'char', 'wchar', 'dchar', - 'float', 'double', 'real', 'ifloat', 'idouble', 'ireal', 'cfloat', 'cdouble', 'creal', 'void' + operators: [ + '=', '>', '<', '!', '~', '?', ':', + '==', '<=', '>=', '!=', '&&', '||', '++', '--', + '+', '-', '*', '/', '&', '|', '^', '%', '<<', + '>>', '>>>', '+=', '-=', '*=', '/=', '&=', '|=', + '^=', '%=', '<<=', '>>=', '>>>=' + ], + + // we include these common regular expressions + symbols: /[=>](?!@symbols)/, '@brackets'], + [/@symbols/, { + cases: { + '@operators': 'operator', + '@default': '' + } + }], + + // numbers + [/\d*\.\d+([eE][\-+]?\d+)?[fFdD]?/, 'number.float'], + [/0[xX][0-9a-fA-F_]*[0-9a-fA-F][Ll]?/, 'number.hex'], + [/0[0-7_]*[0-7][Ll]?/, 'number.octal'], + [/0[bB][0-1_]*[0-1][Ll]?/, 'number.binary'], + [/\d+[lL]?/, 'number'], + + // delimiter: after number because of .\d floats + [/[;,.]/, 'delimiter'], + + // strings + [/"([^"\\]|\\.)*$/, 'string.invalid'], // non-teminated string + [/"/, 'string', '@string'], + [/`/, 'string', '@rawstring'], + + // characters + [/'[^\\']'/, 'string'], + [/(')(@escapes)(')/, ['string', 'string.escape', 'string']], + [/'/, 'string.invalid'] ], - operators: [ - '=', '>', '<', '!', '~', '?', ':', - '==', '<=', '>=', '!=', '&&', '||', '++', '--', - '+', '-', '*', '/', '&', '|', '^', '%', '<<', - '>>', '>>>', '+=', '-=', '*=', '/=', '&=', '|=', - '^=', '%=', '<<=', '>>=', '>>>=' + whitespace: [ + [/[ \t\r\n]+/, 'white'], + [/\/\*/, 'comment', '@comment'], + [/\/\+/, 'comment', '@nestingcomment'], + [/\/\/.*$/, 'comment'], ], - // we include these common regular expressions - symbols: /[=>](?!@symbols)/, '@brackets'], - [/@symbols/, { - cases: { - '@operators': 'operator', - '@default': '' - } - }], - - // numbers - [/\d*\.\d+([eE][\-+]?\d+)?[fFdD]?/, 'number.float'], - [/0[xX][0-9a-fA-F_]*[0-9a-fA-F][Ll]?/, 'number.hex'], - [/0[0-7_]*[0-7][Ll]?/, 'number.octal'], - [/0[bB][0-1_]*[0-1][Ll]?/, 'number.binary'], - [/\d+[lL]?/, 'number'], - - // delimiter: after number because of .\d floats - [/[;,.]/, 'delimiter'], - - // strings - [/"([^"\\]|\\.)*$/, 'string.invalid'], // non-teminated string - [/"/, 'string', '@string'], - [/`/, 'string', '@rawstring'], - - // characters - [/'[^\\']'/, 'string'], - [/(')(@escapes)(')/, ['string', 'string.escape', 'string']], - [/'/, 'string.invalid'] - ], - - whitespace: [ - [/[ \t\r\n]+/, 'white'], - [/\/\*/, 'comment', '@comment'], - [/\/\+/, 'comment', '@nestingcomment'], - [/\/\/.*$/, 'comment'], - ], - - comment: [ - [/[^\/*]+/, 'comment'], - [/\*\//, 'comment', '@pop'], - [/[\/*]/, 'comment'] - ], - - nestingcomment: [ - [/[^\/+]+/, 'comment'], - [/\/\+/, 'comment', '@push'], - [/\/\+/, 'comment.invalid'], - [/\+\//, 'comment', '@pop'], - [/[\/+]/, 'comment'] - ], - - string: [ - [/[^\\"]+/, 'string'], - [/@escapes/, 'string.escape'], - [/\\./, 'string.escape.invalid'], - [/"/, 'string', '@pop'] - ], - - rawstring: [ - [/[^\`]/, "string"], - [/`/, "string", "@pop"] - ], - } - }; - } - - function configuration() { - return { - comments: { - lineComment: '//', - blockComment: ['/*', '*/'], - }, - - brackets: [ - ['{', '}'], - ['[', ']'], - ['(', ')'] + comment: [ + [/[^\/*]+/, 'comment'], + [/\*\//, 'comment', '@pop'], + [/[\/*]/, 'comment'] ], - autoClosingPairs: [ - { open: '{', close: '}' }, - { open: '[', close: ']' }, - { open: '(', close: ')' }, - { open: '`', close: '`', notIn: ['string'] }, - { open: '"', close: '"', notIn: ['string'] }, - { open: '\'', close: '\'', notIn: ['string', 'comment'] }, + nestingcomment: [ + [/[^\/+]+/, 'comment'], + [/\/\+/, 'comment', '@push'], + [/\/\+/, 'comment.invalid'], + [/\+\//, 'comment', '@pop'], + [/[\/+]/, 'comment'] ], - surroundingPairs: [ - { open: '{', close: '}' }, - { open: '[', close: ']' }, - { open: '(', close: ')' }, - { open: '`', close: '`' }, - { open: '"', close: '"' }, - { open: '\'', close: '\'' }, - ] - }; - } + string: [ + [/[^\\"]+/, 'string'], + [/@escapes/, 'string.escape'], + [/\\./, 'string.escape.invalid'], + [/"/, 'string', '@pop'] + ], - monaco.languages.register({id: 'd'}); - monaco.languages.setMonarchTokensProvider('d', definition()); - monaco.languages.setLanguageConfiguration('d', configuration()); -}); \ No newline at end of file + rawstring: [ + [/[^\`]/, "string"], + [/`/, "string", "@pop"] + ], + } + }; +} + +function configuration() { + return { + comments: { + lineComment: '//', + blockComment: ['/*', '*/'], + }, + + brackets: [ + ['{', '}'], + ['[', ']'], + ['(', ')'] + ], + + autoClosingPairs: [ + { open: '{', close: '}' }, + { open: '[', close: ']' }, + { open: '(', close: ')' }, + { open: '`', close: '`', notIn: ['string'] }, + { open: '"', close: '"', notIn: ['string'] }, + { open: '\'', close: '\'', notIn: ['string', 'comment'] }, + ], + + surroundingPairs: [ + { open: '{', close: '}' }, + { open: '[', close: ']' }, + { open: '(', close: ')' }, + { open: '`', close: '`' }, + { open: '"', close: '"' }, + { open: '\'', close: '\'' }, + ] + }; +} + +monaco.languages.register({id: 'd'}); +monaco.languages.setMonarchTokensProvider('d', definition()); +monaco.languages.setLanguageConfiguration('d', configuration()); diff --git a/static/diff.js b/static/diff.js index ed86db5c7..ecb20ff46 100644 --- a/static/diff.js +++ b/static/diff.js @@ -23,209 +23,207 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -define(function (require) { - "use strict"; +"use strict"; - var FontScale = require('fontscale'); - var monaco = require('monaco'); - var _ = require('underscore'); - var $ = require('jquery'); +var FontScale = require('fontscale'); +var monaco = require('monaco'); +var _ = require('underscore'); +var $ = require('jquery'); - require('asm-mode'); - require('selectize'); +require('asm-mode'); +require('selectize'); - function State(id, model) { - this.id = id; - this.model = model; - this.compiler = null; - this.result = null; - } +function State(id, model) { + this.id = id; + this.model = model; + this.compiler = null; + this.result = null; +} - State.prototype.update = function (id, compiler, result) { - if (this.id !== id) return false; - this.compiler = compiler; - this.result = result; - var asm = result.asm || []; - this.model.setValue(_.pluck(asm, 'text').join("\n")); - return true; - }; +State.prototype.update = function (id, compiler, result) { + if (this.id !== id) return false; + this.compiler = compiler; + this.result = result; + var asm = result.asm || []; + this.model.setValue(_.pluck(asm, 'text').join("\n")); + return true; +}; - function Diff(hub, container, state) { - this.container = container; - this.eventHub = hub.createEventHub(); - this.domRoot = container.getElement(); - this.domRoot.html($('#diff').html()); - this.compilers = {}; +function Diff(hub, container, state) { + this.container = container; + this.eventHub = hub.createEventHub(); + this.domRoot = container.getElement(); + this.domRoot.html($('#diff').html()); + this.compilers = {}; - this.outputEditor = monaco.editor.createDiffEditor(this.domRoot.find(".monaco-placeholder")[0], { - fontFamily: 'monospace', - scrollBeyondLastLine: false, - readOnly: true, - language: 'asm' - }); + this.outputEditor = monaco.editor.createDiffEditor(this.domRoot.find(".monaco-placeholder")[0], { + fontFamily: 'monospace', + scrollBeyondLastLine: false, + readOnly: true, + language: 'asm' + }); - this.lhs = new State(state.lhs, monaco.editor.createModel('', 'asm')); - this.rhs = new State(state.rhs, monaco.editor.createModel('', 'asm')); - this.outputEditor.setModel({original: this.lhs.model, modified: this.rhs.model}); + this.lhs = new State(state.lhs, monaco.editor.createModel('', 'asm')); + this.rhs = new State(state.rhs, monaco.editor.createModel('', 'asm')); + this.outputEditor.setModel({original: this.lhs.model, modified: this.rhs.model}); - var selectize = this.domRoot.find(".diff-picker").selectize({ - sortField: 'name', - valueField: 'id', - labelField: 'name', - searchField: ['name'], - options: [], - items: [], - render: { - option: function (item, escape) { - return '
      ' + - '' + escape(item.compiler.name) + '' + - '' + escape(item.options) + '' + - '
        ' + - '
      • Editor #' + escape(item.editorId) + '
      • ' + - '
      • Compiler #' + escape(item.id) + '
      • ' + - '
      '; - } + var selectize = this.domRoot.find(".diff-picker").selectize({ + sortField: 'name', + valueField: 'id', + labelField: 'name', + searchField: ['name'], + options: [], + items: [], + render: { + option: function (item, escape) { + return '
      ' + + '' + escape(item.compiler.name) + '' + + '' + escape(item.options) + '' + + '
        ' + + '
      • Editor #' + escape(item.editorId) + '
      • ' + + '
      • Compiler #' + escape(item.id) + '
      • ' + + '
      '; } - }).on('change', _.bind(function (e) { - var target = $(e.target); - var compiler = this.compilers[target.val()]; - if (!compiler) return; - if (target.hasClass('lhs')) { - this.lhs.compiler = compiler; - this.lhs.id = compiler.id; - } else { - this.rhs.compiler = compiler; - this.rhs.id = compiler.id; - } - this.onDiffSelect(compiler.id); - }, this)); - this.selectize = {lhs: selectize[0].selectize, rhs: selectize[1].selectize}; - - this.fontScale = new FontScale(this.domRoot, state, this.outputEditor); - this.fontScale.on('change', _.bind(this.updateState, this)); - - this.eventHub.on('compileResult', this.onCompileResult, this); - this.eventHub.on('compiler', this.onCompiler, this); - this.eventHub.on('compilerClose', this.onCompilerClose, this); - this.eventHub.on('themeChange', this.onThemeChange, this); - this.container.on('destroy', function () { - this.eventHub.unsubscribe(); - this.outputEditor.dispose(); - }, this); - container.on('resize', this.resize, this); - container.on('shown', this.resize, this); - - this.eventHub.emit('resendCompilation', this.lhs.id); - this.eventHub.emit('resendCompilation', this.rhs.id); - this.eventHub.emit('findCompilers'); - this.eventHub.emit('requestTheme'); - - this.updateCompilerNames(); - this.updateCompilers(); - } - - // TODO: de-dupe with compiler etc - Diff.prototype.resize = function () { - var topBarHeight = this.domRoot.find(".top-bar").outerHeight(true); - this.outputEditor.layout({ - width: this.domRoot.width(), - height: this.domRoot.height() - topBarHeight - }); - }; - - Diff.prototype.onDiffSelect = function (id) { - this.eventHub.emit('resendCompilation', id); - this.updateCompilerNames(); - this.updateState(); - }; - - Diff.prototype.onCompileResult = function (id, compiler, result) { - // both sides must be updated, don't be tempted to rewrite this as - // var changes = lhs.update() || rhs.update(); - var lhsChanged = this.lhs.update(id, compiler, result); - var rhsChanged = this.rhs.update(id, compiler, result); - if (lhsChanged || rhsChanged) { - this.updateCompilerNames(); } - }; - - Diff.prototype.onCompiler = function (id, compiler, options, editorId) { + }).on('change', _.bind(function (e) { + var target = $(e.target); + var compiler = this.compilers[target.val()]; if (!compiler) return; - options = options || ""; - var name = compiler.name + " " + options; - // TODO: selectize doesn't play nicely with CSS tricks for truncation; this is the best I can do - // There's a plugin at: http://www.benbybenjacobs.com/blog/2014/04/09/no-wrap-plugin-for-selectize-dot-js - // but it doesn't look easy to integrate. - var maxLength = 30; - if (name.length > maxLength - 3) name = name.substr(0, maxLength - 3) + "..."; - this.compilers[id] = { - id: id, - name: name, - options: options, - editorId: editorId, - compiler: compiler + if (target.hasClass('lhs')) { + this.lhs.compiler = compiler; + this.lhs.id = compiler.id; + } else { + this.rhs.compiler = compiler; + this.rhs.id = compiler.id; + } + this.onDiffSelect(compiler.id); + }, this)); + this.selectize = {lhs: selectize[0].selectize, rhs: selectize[1].selectize}; + + this.fontScale = new FontScale(this.domRoot, state, this.outputEditor); + this.fontScale.on('change', _.bind(this.updateState, this)); + + this.eventHub.on('compileResult', this.onCompileResult, this); + this.eventHub.on('compiler', this.onCompiler, this); + this.eventHub.on('compilerClose', this.onCompilerClose, this); + this.eventHub.on('themeChange', this.onThemeChange, this); + this.container.on('destroy', function () { + this.eventHub.unsubscribe(); + this.outputEditor.dispose(); + }, this); + container.on('resize', this.resize, this); + container.on('shown', this.resize, this); + + this.eventHub.emit('resendCompilation', this.lhs.id); + this.eventHub.emit('resendCompilation', this.rhs.id); + this.eventHub.emit('findCompilers'); + this.eventHub.emit('requestTheme'); + + this.updateCompilerNames(); + this.updateCompilers(); +} + +// TODO: de-dupe with compiler etc +Diff.prototype.resize = function () { + var topBarHeight = this.domRoot.find(".top-bar").outerHeight(true); + this.outputEditor.layout({ + width: this.domRoot.width(), + height: this.domRoot.height() - topBarHeight + }); +}; + +Diff.prototype.onDiffSelect = function (id) { + this.eventHub.emit('resendCompilation', id); + this.updateCompilerNames(); + this.updateState(); +}; + +Diff.prototype.onCompileResult = function (id, compiler, result) { + // both sides must be updated, don't be tempted to rewrite this as + // var changes = lhs.update() || rhs.update(); + var lhsChanged = this.lhs.update(id, compiler, result); + var rhsChanged = this.rhs.update(id, compiler, result); + if (lhsChanged || rhsChanged) { + this.updateCompilerNames(); + } +}; + +Diff.prototype.onCompiler = function (id, compiler, options, editorId) { + if (!compiler) return; + options = options || ""; + var name = compiler.name + " " + options; + // TODO: selectize doesn't play nicely with CSS tricks for truncation; this is the best I can do + // There's a plugin at: http://www.benbybenjacobs.com/blog/2014/04/09/no-wrap-plugin-for-selectize-dot-js + // but it doesn't look easy to integrate. + var maxLength = 30; + if (name.length > maxLength - 3) name = name.substr(0, maxLength - 3) + "..."; + this.compilers[id] = { + id: id, + name: name, + options: options, + editorId: editorId, + compiler: compiler + }; + if (!this.lhs.id) { + this.lhs.compiler = this.compilers[id]; + this.lhs.id = id; + this.onDiffSelect(id); + } else if (!this.rhs.id) { + this.rhs.compiler = this.compilers[id]; + this.rhs.id = id; + this.onDiffSelect(id); + } + this.updateCompilers(); +}; + +Diff.prototype.onCompilerClose = function (id) { + delete this.compilers[id]; + this.updateCompilers(); +}; + +Diff.prototype.updateCompilerNames = function () { + var name = "Diff"; + if (this.lhs.compiler && this.rhs.compiler) + name += " " + this.lhs.compiler.name + " vs " + this.rhs.compiler.name; + this.container.setTitle(name); +}; + +Diff.prototype.updateCompilersFor = function (selectize, id) { + selectize.clearOptions(); + _.each(this.compilers, function (compiler) { + selectize.addOption(compiler); + }, this); + if (this.compilers[id]) { + selectize.setValue(id); + } +}; + +Diff.prototype.updateCompilers = function () { + this.updateCompilersFor(this.selectize.lhs, this.lhs.id); + this.updateCompilersFor(this.selectize.rhs, this.rhs.id); +}; + +Diff.prototype.updateState = function () { + var state = { + lhs: this.lhs.id, + rhs: this.rhs.id + }; + this.fontScale.addState(state); + this.container.setState(state); +}; + +Diff.prototype.onThemeChange = function (newTheme) { + if (this.outputEditor) + this.outputEditor.updateOptions({theme: newTheme.monaco}); +}; + +module.exports = { + Diff: Diff, + getComponent: function (lhs, rhs) { + return { + type: 'component', + componentName: 'diff', + componentState: {lhs: lhs, rhs: rhs}, }; - if (!this.lhs.id) { - this.lhs.compiler = this.compilers[id]; - this.lhs.id = id; - this.onDiffSelect(id); - } else if (!this.rhs.id) { - this.rhs.compiler = this.compilers[id]; - this.rhs.id = id; - this.onDiffSelect(id); - } - this.updateCompilers(); - }; - - Diff.prototype.onCompilerClose = function (id) { - delete this.compilers[id]; - this.updateCompilers(); - }; - - Diff.prototype.updateCompilerNames = function () { - var name = "Diff"; - if (this.lhs.compiler && this.rhs.compiler) - name += " " + this.lhs.compiler.name + " vs " + this.rhs.compiler.name; - this.container.setTitle(name); - }; - - Diff.prototype.updateCompilersFor = function (selectize, id) { - selectize.clearOptions(); - _.each(this.compilers, function (compiler) { - selectize.addOption(compiler); - }, this); - if (this.compilers[id]) { - selectize.setValue(id); - } - }; - - Diff.prototype.updateCompilers = function () { - this.updateCompilersFor(this.selectize.lhs, this.lhs.id); - this.updateCompilersFor(this.selectize.rhs, this.rhs.id); - }; - - Diff.prototype.updateState = function () { - var state = { - lhs: this.lhs.id, - rhs: this.rhs.id - }; - this.fontScale.addState(state); - this.container.setState(state); - }; - - Diff.prototype.onThemeChange = function (newTheme) { - if (this.outputEditor) - this.outputEditor.updateOptions({theme: newTheme.monaco}); - }; - - return { - Diff: Diff, - getComponent: function (lhs, rhs) { - return { - type: 'component', - componentName: 'diff', - componentState: {lhs: lhs, rhs: rhs}, - }; - } - }; -}); + } +}; diff --git a/static/editor.js b/static/editor.js index 8005eaaff..0be71bb97 100644 --- a/static/editor.js +++ b/static/editor.js @@ -22,561 +22,558 @@ // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. +"use strict"; +var _ = require('underscore'); +var $ = require('jquery'); +var colour = require('colour'); +var loadSaveLib = require('loadSave'); +var FontScale = require('fontscale'); +var Components = require('components'); +var monaco = require('monaco'); +var options = require('options'); +var Alert = require('alert'); +var local = require('./local'); +require('./cppp-mode'); +require('./d-mode'); +require('./rust-mode'); +require('./ispc-mode'); +require('./haskell-mode'); +require('./pascal-mode'); +require('selectize'); -define(function (require) { - "use strict"; - var _ = require('underscore'); - var $ = require('jquery'); - var colour = require('colour'); - var loadSaveLib = require('loadSave'); - var FontScale = require('fontscale'); - var Components = require('components'); - var monaco = require('monaco'); - var options = require('options'); - var Alert = require('alert'); - var local = require('./local'); - require('./cppp-mode'); - require('./d-mode'); - require('./rust-mode'); - require('./ispc-mode'); - require('./haskell-mode'); - require('./pascal-mode'); - require('selectize'); +var loadSave = new loadSaveLib.LoadSave(); - var loadSave = new loadSaveLib.LoadSave(); - - var languages = options.languages; - - function Editor(hub, state, container) { - this.id = state.id || hub.nextEditorId(); - this.container = container; - this.domRoot = container.getElement(); - this.domRoot.html($('#codeEditor').html()); - this.eventHub = hub.createEventHub(); - // Should probably be its own function somewhere - this.settings = JSON.parse(local.get('settings', '{}')); - this.ourCompilers = {}; - - this.widgetsByCompiler = {}; - this.asmByCompiler = {}; - this.busyCompilers = {}; - this.colours = []; - - this.decorations = {}; - this.prevDecorations = []; - - this.fadeTimeoutId = -1; - - this.editorSourceByLang = {}; - this.languageBtn = this.domRoot.find('.change-language'); - var langKeys = _.keys(languages); - // Ensure that the btn is disabled if we don't have nothing to select - // Note that is might be disabled for other reasons beforehand - if (langKeys.length <= 1) { - this.languageBtn.prop("disabled", true); - } - this.currentLanguage = languages[langKeys[0]]; - this.waitingForLanguage = state.source && !state.lang; - if (languages[this.settings.defaultLanguage]) { - this.currentLanguage = languages[this.settings.defaultLanguage]; - } - if (languages[state.lang]) { - this.currentLanguage = languages[state.lang]; - } else if (this.settings.newEditorLastLang && languages[hub.lastOpenedLangId]) { - this.currentLanguage = languages[hub.lastOpenedLangId]; - } - var root = this.domRoot.find(".monaco-placeholder"); - var legacyReadOnly = state.options && !!state.options.readOnly; - this.editor = monaco.editor.create(root[0], { - scrollBeyondLastLine: false, - language: this.currentLanguage.monaco, - fontFamily: 'monospace', - readOnly: !!options.readOnly || legacyReadOnly, - glyphMargin: !options.embedded, - quickSuggestions: false, - fixedOverflowWidgets: true, - minimap: { - maxColumn: 80 - }, - folding: true, - lineNumbersMinChars: options.embedded ? 1 : 3, - emptySelectionClipboard: true, - autoIndent: true - }); - - if (state.source !== undefined) { - this.setSource(state.source); - } else { - this.updateEditorCode(); - } - - this.initLoadSaver(); - - var startFolded = /^[/*#;]+\s*setup.*/; - if (state.source && state.source.match(startFolded)) { - var foldAction = this.editor.getAction('editor.fold'); - foldAction.run(); - } - - this.editor.addAction({ - id: 'compile', - label: 'Compile', - keybindings: [monaco.KeyMod.CtrlCmd | monaco.KeyCode.Enter], - keybindingContext: null, - contextMenuGroupId: 'navigation', - contextMenuOrder: 1.5, - run: _.bind(function () { - this.maybeEmitChange(); - }, this) - }); - - this.editor.addAction({ - id: 'toggleCompileOnChange', - label: 'Toggle compile on change', - keybindings: [monaco.KeyMod.CtrlCmd | monaco.KeyMod.Shift | monaco.KeyCode.Enter], - keybindingContext: null, - run: _.bind(function () { - this.eventHub.emit('modifySettings', { - compileOnChange: !this.settings.compileOnChange - }); - new Alert().notify('Compile on code change has been toggled ' + (this.settings.compileOnChange ? 'ON' : 'OFF'), { - group: "togglecompile", - alertClass: this.settings.compileOnChange ? "notification-on" : "notification-off", - dismissTime: 3000 - }); - }, this) - }); - - this.editor.addAction({ - id: 'toggleColourisation', - label: 'Toggle colourisation', - keybindings: [monaco.KeyMod.CtrlCmd | monaco.KeyMod.Shift | monaco.KeyCode.F1], - keybindingContext: null, - run: _.bind(function () { - this.eventHub.emit('modifySettings', { - colouriseAsm: !this.settings.colouriseAsm - }); - }, this) - }); - - this.editor.addAction({ - id: 'viewasm', - label: 'Scroll to assembly', - keybindings: [monaco.KeyMod.CtrlCmd | monaco.KeyCode.F10], - keybindingContext: null, - contextMenuGroupId: 'navigation', - contextMenuOrder: 1.5, - run: function (ed) { - tryCompilerLinkLine(ed.getPosition().lineNumber, true); - } - }); - - var tryCompilerLinkLine = _.bind(function (thisLineNumber, reveal) { - _.each(this.asmByCompiler, _.bind(function (asms, compilerId) { - var targetLines = []; - _.each(asms, function (asmLine, i) { - if (asmLine.source && asmLine.source.file === null && - asmLine.source.line == thisLineNumber) { - targetLines.push(i + 1); - } - }); - this.eventHub.emit('compilerSetDecorations', compilerId, targetLines, reveal); - }, this)); - }, this); - - var clearCompilerLinkedLines = _.bind(function () { - _.each(this.asmByCompiler, _.bind(function (asms, compilerId) { - this.eventHub.emit('compilerSetDecorations', compilerId, -1, false); - }, this)); - }, this); - - this.editor.onMouseLeave(_.bind(function () { - this.fadeTimeoutId = setTimeout(_.bind(function () { - clearCompilerLinkedLines(); - this.fadeTimeoutId = -1; - }, this), 5000); - }, this)); - - this.mouseMoveThrottledFunction = _.throttle(_.bind(function (e) { - if (e !== null && e.target !== null && this.settings.hoverShowSource && e.target.position !== null) { - tryCompilerLinkLine(e.target.position.lineNumber, false); - } - }, this), 250); - - this.editor.onMouseMove(_.bind(function (e) { - this.mouseMoveThrottledFunction(e); - // This can't be throttled or we can clear a timeout where we're already outside - if (this.fadeTimeoutId !== -1) { - clearTimeout(this.fadeTimeoutId); - this.fadeTimeoutId = -1; - } - }, this)); - - this.updateEditorLayout = _.bind(function () { - var topBarHeight = this.domRoot.find(".top-bar").outerHeight(true) || 0; - this.editor.layout({width: this.domRoot.width(), height: this.domRoot.height() - topBarHeight}); - }, this); - - this.fontScale = new FontScale(this.domRoot, state, this.editor); - this.fontScale.on('change', _.bind(this.updateState, this)); - - var usableLanguages = _.filter(languages, function (language) { - return hub.compilerService.compilersByLang[language.id]; - }); - - this.languageBtn.selectize({ - sortField: 'name', - valueField: 'id', - labelField: 'name', - searchField: ['name'], - options: _.map(usableLanguages, _.identity), - items: [this.currentLanguage.id] - }).on('change', _.bind(function (e) { - this.onLanguageChange($(e.target).val()); - }, this)); - this.changeLanguage = function (newLang) { - this.languageBtn[0].selectize.setValue(newLang); - }; - - // We suppress posting changes until the user has stopped typing by: - // * Using _.debounce() to run emitChange on any key event or change - // only after a delay. - // * Only actually triggering a change if the document text has changed from - // the previous emitted. - this.lastChangeEmitted = null; - this.onSettingsChange(this.settings); - this.editor.getModel().onDidChangeContent(_.bind(function () { - this.debouncedEmitChange(); - this.updateState(); - }, this)); - // this.editor.on("keydown", _.bind(function () { - // // Not strictly a change; but this suppresses changes until some time - // // after the last key down (be it an actual change or a just a cursor - // // movement etc). - // this.debouncedEmitChange(); - // }, this)); - - container.on('resize', this.updateEditorLayout); - container.on('shown', this.updateEditorLayout); - container.on('open', _.bind(function () { - this.eventHub.emit('editorOpen', this.id); - }, this)); - container.on('destroy', this.close, this); - this.container.layoutManager.on('initialised', function () { - // Once initialized, let everyone know what text we have. - this.maybeEmitChange(); - }, this); - - this.eventHub.on('compilerOpen', this.onCompilerOpen, this); - this.eventHub.on('compilerClose', this.onCompilerClose, this); - this.eventHub.on('compiling', this.onCompiling, this); - this.eventHub.on('compileResult', this.onCompileResponse, this); - this.eventHub.on('selectLine', this.onSelectLine, this); - this.eventHub.on('editorSetDecoration', this.onEditorSetDecoration, this); - this.eventHub.on('settingsChange', this.onSettingsChange, this); - this.eventHub.on('conformanceViewOpen', this.onConformanceViewOpen, this); - this.eventHub.on('conformanceViewClose', this.onConformanceViewClose, this); - this.eventHub.on('resize', this.updateEditorLayout, this); - - // NB a new compilerConfig needs to be created every time; else the state is shared - // between all compilers created this way. That leads to some nasty-to-find state - // bugs e.g. https://github.com/mattgodbolt/compiler-explorer/issues/225 - var compilerConfig = _.bind(function () { - return Components.getCompiler(this.id, this.currentLanguage.id); - }, this); - - var addCompilerButton = this.domRoot.find('.btn.add-compiler'); - var paneAdderDropdown = this.domRoot.find('.add-pane'); - - var togglePaneAdder = function () { - paneAdderDropdown.dropdown('toggle'); - }; - - this.container.layoutManager - .createDragSource(addCompilerButton, compilerConfig) - ._dragListener.on('dragStart', togglePaneAdder); - - addCompilerButton.click(_.bind(function () { - var insertPoint = hub.findParentRowOrColumn(this.container) || - this.container.layoutManager.root.contentItems[0]; - insertPoint.addChild(compilerConfig); - }, this)); +var languages = options.languages; - var conformanceConfig = _.bind(function () { - return Components.getConformanceView(this.id, this.getSource()); - }, this); +function Editor(hub, state, container) { + this.id = state.id || hub.nextEditorId(); + this.container = container; + this.domRoot = container.getElement(); + this.domRoot.html($('#codeEditor').html()); + this.eventHub = hub.createEventHub(); + // Should probably be its own function somewhere + this.settings = JSON.parse(local.get('settings', '{}')); + this.ourCompilers = {}; - this.conformanceViewerButton = this.domRoot.find('.btn.conformance'); + this.widgetsByCompiler = {}; + this.asmByCompiler = {}; + this.busyCompilers = {}; + this.colours = []; - this.container.layoutManager - .createDragSource(this.conformanceViewerButton, conformanceConfig) - ._dragListener.on('dragStart', togglePaneAdder); - this.conformanceViewerButton.click(_.bind(function () { - var insertPoint = hub.findParentRowOrColumn(this.container) || - this.container.layoutManager.root.contentItems[0]; - insertPoint.addChild(conformanceConfig); - }, this)); - this.updateTitle(); - this.eventHub.on('initialised', this.maybeEmitChange, this); - this.updateState(); + this.decorations = {}; + this.prevDecorations = []; + + this.fadeTimeoutId = -1; + + this.editorSourceByLang = {}; + this.languageBtn = this.domRoot.find('.change-language'); + var langKeys = _.keys(languages); + // Ensure that the btn is disabled if we don't have nothing to select + // Note that is might be disabled for other reasons beforehand + if (langKeys.length <= 1) { + this.languageBtn.prop("disabled", true); + } + this.currentLanguage = languages[langKeys[0]]; + this.waitingForLanguage = state.source && !state.lang; + if (languages[this.settings.defaultLanguage]) { + this.currentLanguage = languages[this.settings.defaultLanguage]; + } + if (languages[state.lang]) { + this.currentLanguage = languages[state.lang]; + } else if (this.settings.newEditorLastLang && languages[hub.lastOpenedLangId]) { + this.currentLanguage = languages[hub.lastOpenedLangId]; + } + var root = this.domRoot.find(".monaco-placeholder"); + var legacyReadOnly = state.options && !!state.options.readOnly; + this.editor = monaco.editor.create(root[0], { + scrollBeyondLastLine: false, + language: this.currentLanguage.monaco, + fontFamily: 'monospace', + readOnly: !!options.readOnly || legacyReadOnly, + glyphMargin: !options.embedded, + quickSuggestions: false, + fixedOverflowWidgets: true, + minimap: { + maxColumn: 80 + }, + folding: true, + lineNumbersMinChars: options.embedded ? 1 : 3, + emptySelectionClipboard: true, + autoIndent: true + }); + + if (state.source !== undefined) { + this.setSource(state.source); + } else { + this.updateEditorCode(); } - // If compilerId is undefined, every compiler will be pinged - Editor.prototype.maybeEmitChange = function (force, compilerId) { - var source = this.getSource(); - if (!force && source === this.lastChangeEmitted) return; - this.lastChangeEmitted = source; - this.eventHub.emit('editorChange', this.id, this.lastChangeEmitted, this.currentLanguage.id, compilerId); - }; + this.initLoadSaver(); - Editor.prototype.updateState = function () { - var state = { - id: this.id, - source: this.getSource(), - lang: this.currentLanguage.id - }; - this.fontScale.addState(state); - this.container.setState(state); - }; + var startFolded = /^[/*#;]+\s*setup.*/; + if (state.source && state.source.match(startFolded)) { + var foldAction = this.editor.getAction('editor.fold'); + foldAction.run(); + } - Editor.prototype.setSource = function (newSource) { - this.editor.getModel().setValue(newSource); - }; + this.editor.addAction({ + id: 'compile', + label: 'Compile', + keybindings: [monaco.KeyMod.CtrlCmd | monaco.KeyCode.Enter], + keybindingContext: null, + contextMenuGroupId: 'navigation', + contextMenuOrder: 1.5, + run: _.bind(function () { + this.maybeEmitChange(); + }, this) + }); - Editor.prototype.getSource = function () { - return this.editor.getModel().getValue(); - }; - - Editor.prototype.onSettingsChange = function (newSettings) { - var before = this.settings; - var after = newSettings; - this.settings = _.clone(newSettings); - - this.editor.updateOptions({ - autoClosingBrackets: this.settings.autoCloseBrackets, - tabSize: this.settings.tabWidth, - quickSuggestions: this.settings.showQuickSuggestions, - contextmenu: this.settings.useCustomContextMenu, - minimap: { - enabled: this.settings.showMinimap && !options.embedded - } - }); - - // TODO: bug when: - // * Turn off auto. - // * edit code - // * change compiler or compiler options (out of date code is used) - var bDac = before.compileOnChange ? before.delayAfterChange : 0; - var aDac = after.compileOnChange ? after.delayAfterChange : 0; - if (bDac !== aDac || !this.debouncedEmitChange) { - if (aDac) { - this.debouncedEmitChange = _.debounce(_.bind(function () { - this.maybeEmitChange(); - }, this), after.delayAfterChange); - this.maybeEmitChange(true); - } else { - this.debouncedEmitChange = _.noop; - } - } - - if (before.hoverShowSource && !after.hoverShowSource) { - this.onEditorSetDecoration(this.id, -1, false); - } - - this.numberUsedLines(); - }; - - Editor.prototype.numberUsedLines = function () { - var result = {}; - // First, note all lines used. - _.each(this.asmByCompiler, function (asm) { - _.each(asm, function (asmLine) { - // If the line has a source indicator, and the source indicator is null (i.e. the - // user's input file), then tag it as used. - if (asmLine.source && asmLine.source.file === null) - result[asmLine.source.line - 1] = true; + this.editor.addAction({ + id: 'toggleCompileOnChange', + label: 'Toggle compile on change', + keybindings: [monaco.KeyMod.CtrlCmd | monaco.KeyMod.Shift | monaco.KeyCode.Enter], + keybindingContext: null, + run: _.bind(function () { + this.eventHub.emit('modifySettings', { + compileOnChange: !this.settings.compileOnChange }); - }); - // Now assign an ordinal to each used line. - var ordinal = 0; - _.each(result, function (v, k) { - result[k] = ordinal++; - }); + new Alert().notify('Compile on code change has been toggled ' + (this.settings.compileOnChange ? 'ON' : 'OFF'), { + group: "togglecompile", + alertClass: this.settings.compileOnChange ? "notification-on" : "notification-off", + dismissTime: 3000 + }); + }, this) + }); - if (_.any(this.busyCompilers)) return; - this.updateColours(this.settings.colouriseAsm ? result : []); - }; + this.editor.addAction({ + id: 'toggleColourisation', + label: 'Toggle colourisation', + keybindings: [monaco.KeyMod.CtrlCmd | monaco.KeyMod.Shift | monaco.KeyCode.F1], + keybindingContext: null, + run: _.bind(function () { + this.eventHub.emit('modifySettings', { + colouriseAsm: !this.settings.colouriseAsm + }); + }, this) + }); - Editor.prototype.updateColours = function (colours) { - this.colours = colour.applyColours(this.editor, colours, this.settings.colourScheme, this.colours); - this.eventHub.emit('colours', this.id, colours, this.settings.colourScheme); - }; + this.editor.addAction({ + id: 'viewasm', + label: 'Scroll to assembly', + keybindings: [monaco.KeyMod.CtrlCmd | monaco.KeyCode.F10], + keybindingContext: null, + contextMenuGroupId: 'navigation', + contextMenuOrder: 1.5, + run: function (ed) { + tryCompilerLinkLine(ed.getPosition().lineNumber, true); + } + }); - Editor.prototype.onCompilerOpen = function (compilerId, editorId) { - if (editorId === this.id) { - // On any compiler open, rebroadcast our state in case they need to know it. - if (this.waitingForLanguage) { - var glCompiler =_.find(this.container.layoutManager.root.getComponentsByName("compiler"), function (compiler) { - return compiler.id === compilerId; - }); - if (glCompiler) { - var selected = _.find(options.compilers, function (compiler) { - return compiler.id === glCompiler.originalCompilerId; - }); - if (selected) { - this.changeLanguage(selected.lang); - } + var tryCompilerLinkLine = _.bind(function (thisLineNumber, reveal) { + _.each(this.asmByCompiler, _.bind(function (asms, compilerId) { + var targetLines = []; + _.each(asms, function (asmLine, i) { + if (asmLine.source && asmLine.source.file === null && + asmLine.source.line == thisLineNumber) { + targetLines.push(i + 1); } - } - this.maybeEmitChange(true, compilerId); - this.ourCompilers[compilerId] = true; - } - }; - - Editor.prototype.onCompilerClose = function (compilerId) { - if (this.ourCompilers[compilerId]) { - monaco.editor.setModelMarkers(this.editor.getModel(), compilerId, []); - delete this.widgetsByCompiler[compilerId]; - delete this.asmByCompiler[compilerId]; - delete this.busyCompilers[compilerId]; - delete this.ourCompilers[compilerId]; - this.numberUsedLines(); - } - }; - - Editor.prototype.onCompiling = function (compilerId) { - if (!this.ourCompilers[compilerId]) return; - this.busyCompilers[compilerId] = true; - }; - - Editor.prototype.onCompileResponse = function (compilerId, compiler, result) { - if (!this.ourCompilers[compilerId]) return; - this.busyCompilers[compilerId] = false; - var output = (result.stdout || []).concat(result.stderr || []); - var widgets = _.compact(_.map(output, function (obj) { - if (!obj.tag) return; - var severity = 3; // error - if (obj.tag.text.match(/^warning/)) severity = 2; - if (obj.tag.text.match(/^note/)) severity = 1; - return { - severity: severity, - message: obj.tag.text, - source: compiler.name + ' #' + compilerId, - startLineNumber: obj.tag.line, - startColumn: obj.tag.column || 0, - endLineNumber: obj.tag.line, - endColumn: -1 - }; + }); + this.eventHub.emit('compilerSetDecorations', compilerId, targetLines, reveal); }, this)); - monaco.editor.setModelMarkers(this.editor.getModel(), compilerId, widgets); - this.decorations.tags = _.map(widgets, function (tag) { - return { - range: new monaco.Range(tag.startLineNumber, tag.startColumn, tag.startLineNumber + 1, 1), - options: { - isWholeLine: false, - inlineClassName: "error-code" - } - }; - }, this); - this.updateDecorations(); - this.asmByCompiler[compilerId] = result.asm; - this.numberUsedLines(); - }; + }, this); - Editor.prototype.onSelectLine = function (id, lineNum) { - if (id === this.id) { - this.editor.setSelection({line: lineNum - 1, ch: 0}, {line: lineNum, ch: 0}); - } - }; + var clearCompilerLinkedLines = _.bind(function () { + _.each(this.asmByCompiler, _.bind(function (asms, compilerId) { + this.eventHub.emit('compilerSetDecorations', compilerId, -1, false); + }, this)); + }, this); - Editor.prototype.onEditorSetDecoration = function (id, lineNum, reveal) { - if (id === this.id) { - if (reveal && lineNum) - this.editor.revealLineInCenter(lineNum); - this.decorations.linkedCode = lineNum === -1 || !lineNum ? - [] - : - [ - { - range: new monaco.Range(lineNum, 1, lineNum, 1), - options: { - isWholeLine: true, - linesDecorationsClassName: 'linked-code-decoration-margin', - inlineClassName: 'linked-code-decoration-inline' - } - } - ]; - this.updateDecorations(); - } - }; + this.editor.onMouseLeave(_.bind(function () { + this.fadeTimeoutId = setTimeout(_.bind(function () { + clearCompilerLinkedLines(); + this.fadeTimeoutId = -1; + }, this), 5000); + }, this)); - Editor.prototype.updateDecorations = function () { - this.prevDecorations = this.editor.deltaDecorations( - this.prevDecorations, _.flatten(_.values(this.decorations), true)); - }; - - Editor.prototype.onConformanceViewOpen = function (editorId) { - if (editorId == this.id) { - this.conformanceViewerButton.attr("disabled", true); - } - }; - - Editor.prototype.onConformanceViewClose = function (editorId) { - if (editorId == this.id) { - this.conformanceViewerButton.attr("disabled", false); - } - }; - - Editor.prototype.initLoadSaver = function () { - this.domRoot.find('.load-save') - .off('click') - .click(_.bind(function () { - loadSave.run(_.bind(function (text) { - this.setSource(text); - this.updateState(); - this.maybeEmitChange(); - }, this), this.getSource(), this.currentLanguage); - }, this)); - }; - - Editor.prototype.onLanguageChange = function (newLangId) { - if (languages[newLangId]) { - if (newLangId !== this.currentLanguage.id) { - var oldLangId = this.currentLanguage.id; - this.currentLanguage = languages[newLangId]; - if (!this.waitingForLanguage) { - this.editorSourceByLang[oldLangId] = this.getSource(); - this.updateEditorCode(); - } - this.initLoadSaver(); - monaco.editor.setModelLanguage(this.editor.getModel(), this.currentLanguage.monaco); - this.updateTitle(); - this.updateState(); - // Broadcast the change to other panels - this.eventHub.emit("languageChange", this.id, newLangId); - this.maybeEmitChange(true); + this.mouseMoveThrottledFunction = _.throttle(_.bind(function (e) { + if (e !== null && e.target !== null && this.settings.hoverShowSource && e.target.position !== null) { + tryCompilerLinkLine(e.target.position.lineNumber, false); } - this.waitingForLanguage = false; + }, this), 250); + + this.editor.onMouseMove(_.bind(function (e) { + this.mouseMoveThrottledFunction(e); + // This can't be throttled or we can clear a timeout where we're already outside + if (this.fadeTimeoutId !== -1) { + clearTimeout(this.fadeTimeoutId); + this.fadeTimeoutId = -1; } + }, this)); + + this.updateEditorLayout = _.bind(function () { + var topBarHeight = this.domRoot.find(".top-bar").outerHeight(true) || 0; + this.editor.layout({width: this.domRoot.width(), height: this.domRoot.height() - topBarHeight}); + }, this); + + this.fontScale = new FontScale(this.domRoot, state, this.editor); + this.fontScale.on('change', _.bind(this.updateState, this)); + + var usableLanguages = _.filter(languages, function (language) { + return hub.compilerService.compilersByLang[language.id]; + }); + + this.languageBtn.selectize({ + sortField: 'name', + valueField: 'id', + labelField: 'name', + searchField: ['name'], + options: _.map(usableLanguages, _.identity), + items: [this.currentLanguage.id] + }).on('change', _.bind(function (e) { + this.onLanguageChange($(e.target).val()); + }, this)); + this.changeLanguage = function (newLang) { + this.languageBtn[0].selectize.setValue(newLang); }; - Editor.prototype.updateTitle = function () { - this.container.setTitle(this.currentLanguage.name + " source #" + this.id); + // We suppress posting changes until the user has stopped typing by: + // * Using _.debounce() to run emitChange on any key event or change + // only after a delay. + // * Only actually triggering a change if the document text has changed from + // the previous emitted. + this.lastChangeEmitted = null; + this.onSettingsChange(this.settings); + this.editor.getModel().onDidChangeContent(_.bind(function () { + this.debouncedEmitChange(); + this.updateState(); + }, this)); + // this.editor.on("keydown", _.bind(function () { + // // Not strictly a change; but this suppresses changes until some time + // // after the last key down (be it an actual change or a just a cursor + // // movement etc). + // this.debouncedEmitChange(); + // }, this)); + + container.on('resize', this.updateEditorLayout); + container.on('shown', this.updateEditorLayout); + container.on('open', _.bind(function () { + this.eventHub.emit('editorOpen', this.id); + }, this)); + container.on('destroy', this.close, this); + this.container.layoutManager.on('initialised', function () { + // Once initialized, let everyone know what text we have. + this.maybeEmitChange(); + }, this); + + this.eventHub.on('compilerOpen', this.onCompilerOpen, this); + this.eventHub.on('compilerClose', this.onCompilerClose, this); + this.eventHub.on('compiling', this.onCompiling, this); + this.eventHub.on('compileResult', this.onCompileResponse, this); + this.eventHub.on('selectLine', this.onSelectLine, this); + this.eventHub.on('editorSetDecoration', this.onEditorSetDecoration, this); + this.eventHub.on('settingsChange', this.onSettingsChange, this); + this.eventHub.on('conformanceViewOpen', this.onConformanceViewOpen, this); + this.eventHub.on('conformanceViewClose', this.onConformanceViewClose, this); + this.eventHub.on('resize', this.updateEditorLayout, this); + + // NB a new compilerConfig needs to be created every time; else the state is shared + // between all compilers created this way. That leads to some nasty-to-find state + // bugs e.g. https://github.com/mattgodbolt/compiler-explorer/issues/225 + var compilerConfig = _.bind(function () { + return Components.getCompiler(this.id, this.currentLanguage.id); + }, this); + + var addCompilerButton = this.domRoot.find('.btn.add-compiler'); + var paneAdderDropdown = this.domRoot.find('.add-pane'); + + var togglePaneAdder = function () { + paneAdderDropdown.dropdown('toggle'); }; - // Called every time we change language, so we get the relevant code - Editor.prototype.updateEditorCode = function () { - this.setSource(this.editorSourceByLang[this.currentLanguage.id] || languages[this.currentLanguage.id].example); - }; + this.container.layoutManager + .createDragSource(addCompilerButton, compilerConfig) + ._dragListener.on('dragStart', togglePaneAdder); - Editor.prototype.close = function () { - this.eventHub.unsubscribe(); - this.eventHub.emit('editorClose', this.id); - this.editor.dispose(); - }; + addCompilerButton.click(_.bind(function () { + var insertPoint = hub.findParentRowOrColumn(this.container) || + this.container.layoutManager.root.contentItems[0]; + insertPoint.addChild(compilerConfig); + }, this)); - return { - Editor: Editor + + var conformanceConfig = _.bind(function () { + return Components.getConformanceView(this.id, this.getSource()); + }, this); + + this.conformanceViewerButton = this.domRoot.find('.btn.conformance'); + + this.container.layoutManager + .createDragSource(this.conformanceViewerButton, conformanceConfig) + ._dragListener.on('dragStart', togglePaneAdder); + this.conformanceViewerButton.click(_.bind(function () { + var insertPoint = hub.findParentRowOrColumn(this.container) || + this.container.layoutManager.root.contentItems[0]; + insertPoint.addChild(conformanceConfig); + }, this)); + this.updateTitle(); + this.eventHub.on('initialised', this.maybeEmitChange, this); + this.updateState(); +} + +// If compilerId is undefined, every compiler will be pinged +Editor.prototype.maybeEmitChange = function (force, compilerId) { + var source = this.getSource(); + if (!force && source === this.lastChangeEmitted) return; + this.lastChangeEmitted = source; + this.eventHub.emit('editorChange', this.id, this.lastChangeEmitted, this.currentLanguage.id, compilerId); +}; + +Editor.prototype.updateState = function () { + var state = { + id: this.id, + source: this.getSource(), + lang: this.currentLanguage.id }; -}); + this.fontScale.addState(state); + this.container.setState(state); +}; + +Editor.prototype.setSource = function (newSource) { + this.editor.getModel().setValue(newSource); +}; + +Editor.prototype.getSource = function () { + return this.editor.getModel().getValue(); +}; + +Editor.prototype.onSettingsChange = function (newSettings) { + var before = this.settings; + var after = newSettings; + this.settings = _.clone(newSettings); + + this.editor.updateOptions({ + autoClosingBrackets: this.settings.autoCloseBrackets, + tabSize: this.settings.tabWidth, + quickSuggestions: this.settings.showQuickSuggestions, + contextmenu: this.settings.useCustomContextMenu, + minimap: { + enabled: this.settings.showMinimap && !options.embedded + } + }); + + // * Turn off auto. + // * edit code + // * change compiler or compiler options (out of date code is used) + var bDac = before.compileOnChange ? before.delayAfterChange : 0; + var aDac = after.compileOnChange ? after.delayAfterChange : 0; + if (bDac !== aDac || !this.debouncedEmitChange) { + if (aDac) { + this.debouncedEmitChange = _.debounce(_.bind(function () { + this.maybeEmitChange(); + }, this), after.delayAfterChange); + this.maybeEmitChange(true); + } else { + this.debouncedEmitChange = _.noop; + } + } + + if (before.hoverShowSource && !after.hoverShowSource) { + this.onEditorSetDecoration(this.id, -1, false); + } + + this.numberUsedLines(); +}; + +Editor.prototype.numberUsedLines = function () { + var result = {}; + // First, note all lines used. + _.each(this.asmByCompiler, function (asm) { + _.each(asm, function (asmLine) { + // If the line has a source indicator, and the source indicator is null (i.e. the + // user's input file), then tag it as used. + if (asmLine.source && asmLine.source.file === null) + result[asmLine.source.line - 1] = true; + }); + }); + // Now assign an ordinal to each used line. + var ordinal = 0; + _.each(result, function (v, k) { + result[k] = ordinal++; + }); + + if (_.any(this.busyCompilers)) return; + this.updateColours(this.settings.colouriseAsm ? result : []); +}; + +Editor.prototype.updateColours = function (colours) { + this.colours = colour.applyColours(this.editor, colours, this.settings.colourScheme, this.colours); + this.eventHub.emit('colours', this.id, colours, this.settings.colourScheme); +}; + +Editor.prototype.onCompilerOpen = function (compilerId, editorId) { + if (editorId === this.id) { + // On any compiler open, rebroadcast our state in case they need to know it. + if (this.waitingForLanguage) { + var glCompiler =_.find(this.container.layoutManager.root.getComponentsByName("compiler"), function (compiler) { + return compiler.id === compilerId; + }); + if (glCompiler) { + var selected = _.find(options.compilers, function (compiler) { + return compiler.id === glCompiler.originalCompilerId; + }); + if (selected) { + this.changeLanguage(selected.lang); + } + } + } + this.maybeEmitChange(true, compilerId); + this.ourCompilers[compilerId] = true; + } +}; + +Editor.prototype.onCompilerClose = function (compilerId) { + if (this.ourCompilers[compilerId]) { + monaco.editor.setModelMarkers(this.editor.getModel(), compilerId, []); + delete this.widgetsByCompiler[compilerId]; + delete this.asmByCompiler[compilerId]; + delete this.busyCompilers[compilerId]; + delete this.ourCompilers[compilerId]; + this.numberUsedLines(); + } +}; + +Editor.prototype.onCompiling = function (compilerId) { + if (!this.ourCompilers[compilerId]) return; + this.busyCompilers[compilerId] = true; +}; + +Editor.prototype.onCompileResponse = function (compilerId, compiler, result) { + if (!this.ourCompilers[compilerId]) return; + this.busyCompilers[compilerId] = false; + var output = (result.stdout || []).concat(result.stderr || []); + var widgets = _.compact(_.map(output, function (obj) { + if (!obj.tag) return; + var severity = 3; // error + if (obj.tag.text.match(/^warning/)) severity = 2; + if (obj.tag.text.match(/^note/)) severity = 1; + return { + severity: severity, + message: obj.tag.text, + source: compiler.name + ' #' + compilerId, + startLineNumber: obj.tag.line, + startColumn: obj.tag.column || 0, + endLineNumber: obj.tag.line, + endColumn: -1 + }; + }, this)); + monaco.editor.setModelMarkers(this.editor.getModel(), compilerId, widgets); + this.decorations.tags = _.map(widgets, function (tag) { + return { + range: new monaco.Range(tag.startLineNumber, tag.startColumn, tag.startLineNumber + 1, 1), + options: { + isWholeLine: false, + inlineClassName: "error-code" + } + }; + }, this); + this.updateDecorations(); + this.asmByCompiler[compilerId] = result.asm; + this.numberUsedLines(); +}; + +Editor.prototype.onSelectLine = function (id, lineNum) { + if (id === this.id) { + this.editor.setSelection({line: lineNum - 1, ch: 0}, {line: lineNum, ch: 0}); + } +}; + +Editor.prototype.onEditorSetDecoration = function (id, lineNum, reveal) { + if (id === this.id) { + if (reveal && lineNum) + this.editor.revealLineInCenter(lineNum); + this.decorations.linkedCode = lineNum === -1 || !lineNum ? + [] + : + [ + { + range: new monaco.Range(lineNum, 1, lineNum, 1), + options: { + isWholeLine: true, + linesDecorationsClassName: 'linked-code-decoration-margin', + inlineClassName: 'linked-code-decoration-inline' + } + } + ]; + this.updateDecorations(); + } +}; + +Editor.prototype.updateDecorations = function () { + this.prevDecorations = this.editor.deltaDecorations( + this.prevDecorations, _.flatten(_.values(this.decorations), true)); +}; + +Editor.prototype.onConformanceViewOpen = function (editorId) { + if (editorId == this.id) { + this.conformanceViewerButton.attr("disabled", true); + } +}; + +Editor.prototype.onConformanceViewClose = function (editorId) { + if (editorId == this.id) { + this.conformanceViewerButton.attr("disabled", false); + } +}; + +Editor.prototype.initLoadSaver = function () { + this.domRoot.find('.load-save') + .off('click') + .click(_.bind(function () { + loadSave.run(_.bind(function (text) { + this.setSource(text); + this.updateState(); + this.maybeEmitChange(); + }, this), this.getSource(), this.currentLanguage); + }, this)); +}; + +Editor.prototype.onLanguageChange = function (newLangId) { + if (languages[newLangId]) { + if (newLangId !== this.currentLanguage.id) { + var oldLangId = this.currentLanguage.id; + this.currentLanguage = languages[newLangId]; + if (!this.waitingForLanguage) { + this.editorSourceByLang[oldLangId] = this.getSource(); + this.updateEditorCode(); + } + this.initLoadSaver(); + monaco.editor.setModelLanguage(this.editor.getModel(), this.currentLanguage.monaco); + this.updateTitle(); + this.updateState(); + // Broadcast the change to other panels + this.eventHub.emit("languageChange", this.id, newLangId); + this.maybeEmitChange(true); + } + this.waitingForLanguage = false; + } +}; + +Editor.prototype.updateTitle = function () { + this.container.setTitle(this.currentLanguage.name + " source #" + this.id); +}; + +// Called every time we change language, so we get the relevant code +Editor.prototype.updateEditorCode = function () { + this.setSource(this.editorSourceByLang[this.currentLanguage.id] || languages[this.currentLanguage.id].example); +}; + +Editor.prototype.close = function () { + this.eventHub.unsubscribe(); + this.eventHub.emit('editorClose', this.id); + this.editor.dispose(); +}; + +module.exports = { + Editor: Editor +}; diff --git a/static/explorer.css b/static/explorer.css index c36cf2271..99affff87 100644 --- a/static/explorer.css +++ b/static/explorer.css @@ -1,10 +1,3 @@ -@import url("ext/bootstrap/dist/css/bootstrap.min.css"); -@import url("ext/golden-layout/src/css/goldenlayout-base.css"); -@import url("ext/selectize/dist/css/selectize.bootstrap2.css"); -@import url("ext/seiyria-bootstrap-slider/dist/css/bootstrap-slider.css"); -@import url("ext/vis/dist/vis.css"); -@import url("colours.css"); - /* TEMP HACK: https://github.com/Microsoft/monaco-editor/issues/349 */ .quick-open-tree .row { margin-left: 0; diff --git a/static/fontscale.js b/static/fontscale.js index 8b663eccf..40fc407b1 100644 --- a/static/fontscale.js +++ b/static/fontscale.js @@ -23,92 +23,90 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -define(function (require) { - "use strict"; - var _ = require('underscore'); - var $ = require('jquery'); - var EventEmitter = require('events'); - var options = require('./options'); +"use strict"; +var _ = require('underscore'); +var $ = require('jquery'); +var EventEmitter = require('events'); +var options = require('./options'); - function makeFontSizeDropdown(elem, interval, obj, buttonDropdown) { - var factor = obj.isFontOfStr ? 10 : 14; - var step = 0.05; - var found = false; +function makeFontSizeDropdown(elem, interval, obj, buttonDropdown) { + var factor = obj.isFontOfStr ? 10 : 14; + var step = 0.05; + var found = false; - var onWheelEvent = function(e) { - e.preventDefault(); - var selectedId = elem.find('.font-option-active').index(); - if (e.originalEvent.deltaY >= 0 && selectedId < elem.children().length - 1) { - selectedId++; - } else if (e.originalEvent.deltaY < 0 && selectedId > 0) { - selectedId--; - } - elem.children().eq(selectedId).trigger('click'); - }; - - var onClickEvent = function() { - // Toggle off the selection of the others - elem.children().removeClass('font-option-active'); - // Toggle us on - $(this).addClass("font-option-active"); - // Send the data - obj.scale = $(this).data("value"); - obj.apply(); - obj.emit('change'); - }; - - for (var i = interval[0]; i <= interval[1]; i += step) { - step *= 1.2; - var newElement = $('
    • '); - newElement.attr('data-value', i); - newElement.addClass('font-option'); - if (!found && (i === obj.scale || Math.floor(i) == obj.scale)) { - found = true; - newElement.addClass('font-option-active'); - } - newElement.text(Math.round(i * factor)); - newElement - .appendTo(elem) - .click(onClickEvent) - .on('wheel', onWheelEvent); + var onWheelEvent = function(e) { + e.preventDefault(); + var selectedId = elem.find('.font-option-active').index(); + if (e.originalEvent.deltaY >= 0 && selectedId < elem.children().length - 1) { + selectedId++; + } else if (e.originalEvent.deltaY < 0 && selectedId > 0) { + selectedId--; } + elem.children().eq(selectedId).trigger('click'); + }; - if (buttonDropdown) { - buttonDropdown.on('wheel', onWheelEvent); + var onClickEvent = function() { + // Toggle off the selection of the others + elem.children().removeClass('font-option-active'); + // Toggle us on + $(this).addClass("font-option-active"); + // Send the data + obj.scale = $(this).data("value"); + obj.apply(); + obj.emit('change'); + }; + + for (var i = interval[0]; i <= interval[1]; i += step) { + step *= 1.2; + var newElement = $('
    • '); + newElement.attr('data-value', i); + newElement.addClass('font-option'); + if (!found && (i === obj.scale || Math.floor(i) == obj.scale)) { + found = true; + newElement.addClass('font-option-active'); } + newElement.text(Math.round(i * factor)); + newElement + .appendTo(elem) + .click(onClickEvent) + .on('wheel', onWheelEvent); } - function FontScale(domRoot, state, fontSelectorOrEditor) { - EventEmitter.call(this); - this.domRoot = domRoot; - this.scale = state.fontScale || options.defaultFontScale; - this.fontSelectorOrEditor = fontSelectorOrEditor; - this.isFontOfStr = typeof(this.fontSelectorOrEditor) === "string"; - this.apply(); - makeFontSizeDropdown(this.domRoot.find('.font-size-list'), [0.3, 3], this, this.domRoot.find('.fs-button')); + if (buttonDropdown) { + buttonDropdown.on('wheel', onWheelEvent); } +} - _.extend(FontScale.prototype, EventEmitter.prototype); +function FontScale(domRoot, state, fontSelectorOrEditor) { + EventEmitter.call(this); + this.domRoot = domRoot; + this.scale = state.fontScale || options.defaultFontScale; + this.fontSelectorOrEditor = fontSelectorOrEditor; + this.isFontOfStr = typeof(this.fontSelectorOrEditor) === "string"; + this.apply(); + makeFontSizeDropdown(this.domRoot.find('.font-size-list'), [0.3, 3], this, this.domRoot.find('.fs-button')); +} - FontScale.prototype.apply = function () { - if (this.isFontOfStr) { - this.domRoot.find(this.fontSelectorOrEditor).css('font-size', (10 * this.scale) + "pt"); - } else { - this.fontSelectorOrEditor.updateOptions({ - fontSize: 14 * this.scale - }); - } - }; +_.extend(FontScale.prototype, EventEmitter.prototype); - FontScale.prototype.addState = function (state) { - if (this.scale != 1.0) - state.fontScale = this.scale; - }; +FontScale.prototype.apply = function () { + if (this.isFontOfStr) { + this.domRoot.find(this.fontSelectorOrEditor).css('font-size', (10 * this.scale) + "pt"); + } else { + this.fontSelectorOrEditor.updateOptions({ + fontSize: 14 * this.scale + }); + } +}; - FontScale.prototype.setScale = function (scale) { - this.scale = scale; - this.apply(); - }; +FontScale.prototype.addState = function (state) { + if (this.scale != 1.0) + state.fontScale = this.scale; +}; - return FontScale; -}); +FontScale.prototype.setScale = function (scale) { + this.scale = scale; + this.apply(); +}; + +module.exports = FontScale; diff --git a/static/haskell-mode.js b/static/haskell-mode.js index e3b49aab7..21e06d102 100644 --- a/static/haskell-mode.js +++ b/static/haskell-mode.js @@ -22,385 +22,383 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -define(function (require) { - "use strict"; - var monaco = require('monaco'); - // From https://github.com/byteally/monaco-haskell - // It does not work right now. Here as a reminder until the author fixes it - function definition() { - return { - module: /^(module)\b/, - import: /^(import)\b/, - module_name: /([A-Z][\w']*)(\.[A-Z][\w']*)*/, - module_exports:/([A-Z][\w']*)(\.[A-Z][\w']*)*/, - target:/([A-Z][\w']*)(\.[A-Z][\w']*)*/, - invalid:/[a-z]+/, - datatype:/[A-Z][\w]+/, - datatypekey:/Int|Float|Text/, - functions:/[a-z]+/, - datacons:/[A-Z][\w]+/, - typcons:/\s*[A-Z][\w]+/, - text:/[A-Z][\w]+/, - classname:/\s*[A-Z][\w]+/, - arguments:/[a-z][\w]*/, - reservedid:/qualified|hiding|case|default|deriving|do|else|if|import|in|infix|infixr|let|of|then|type|where|show|_/, - tokenizer: { - root: [ - [/(@module)/, 'keyword.module.haskell', '@module'], - [/@import/, 'keyword.module.haskell', '@import'], - [/\bdata\b(?=@typcons)/,'keyword','@typcons'], - [/\bnewtype\b(?=\s*@typcons)/,'keyword','@typcons'], - [/\bclass\b(?=\s*@classname)/,'keyword','@classname'], - [/\bclass\b(?=\s*\()/,'keyword','@classname'], - [/@reservedid/,'keyword'], - [/[a-z][\w]+(?=\s*?=)/,'binderas','@binder'], - [/[a-z][\w]+(?=\s*::)/,'binderad','@typconss'], - [/[a-z][\w]+(?=\s*?[a-z]\w*)/,'binder','@typconss'], - [/[a-z][\w]+(?=\s*?::\s*?@datatypekey)/,'bind','@binder'], - [/[a-z][\w]+(?=\s*?=\s*?@datacons)/,'bindings'], - {include:'@whitespace'}, - {include:'@comment'} - ], - import: [ - [/@module_name/,'storage.module,haskell'], - [/(@module_name)(?=\s*as)/, 'storage.module.haskell'], - [/\b(qualified)\b(?=\s*@module_name)/, 'keyword'], - [/(@module_name)(?=\s*?\()/, 'storage.module.haskell'], - [/(@module_name)(?=\s*\bhiding\b)/, 'storage.module.haskell'], - [/\b(hiding)\b(?=\s*?\()/, 'keyword'], - [/\b(as)\b(?=\s*@module_name)/,'keyword'], - [/\(/,'openbracketss','@functions'], - {include:'@comment'} - //{include:'@blockComment'} - ], - module: [ - [/(@module_name)/, 'storage.module.haskell'], - [/\(/, 'openbracket','@module_exports'], - [/@reservedid/,'keyword','@pop'], - [/@invalid/,'invalid'], - [/,/,'commas'], - {include:'@whitespace'}, - {include:'@comment'} - //{include:'@blockComment'} - ], - functions: [ - [/@datatype/,'dcataype','@datatype'], - [/@functions/,'functions'], - [/,/,'commas'], - [/\)(?=\))/,'closebracket'], - [/\)/,'closebracketalla','@popall'], - {include:'@comment'} - //{include:'@blockComment'} - ], - typconss: [ - [/=/,'eqals'], - [/\bundefined\b/,'val','@all'], - [/\bclass\b(?=\s*@classname)/,'keyword','@classname'], - [/\bclass\b(?=\s*\()/,'keyword','@classname'], - [/\binstance\b/,'keyword','@classname'], - [/\bdata\b(?=@typcons)/,'keyword','@typcons'], - [/\bnewtype\b(?=\s*@typcons)/,'keyword','@typcons'], - [/@reservedid/,'keyword','@function'], - [/[a-z]\w*/,'arguments121'], - [/[a-z][\w]+(?=\s*=)/,'binderad','@datacons'], - [/[a-z][\w]+(?=\s*::)/,'binderad','@typconss'], - [/[a-z][\w]+(?=\s*[a-z]\w*)/,'binderad','@typconss'], - [/[a-z]\w*/,'arguments121'], - [/::/,'dcol','@datacons'], - [/->/,'pipes','@binder'], - {include:'@whitespace'}, - {include:'@comment'} - //{include:'@blockComment'} - ], +"use strict"; - function: [ - [/@reservedid/,'keyword'], - [/@datatypekey/,'dtype'], - [/[a-z][\w]+(?=\s*::)/,'binderad','@typconss'], - [/[a-z][\w]+(?=\s*?[a-z]\w*)/,'binder','@typconss'], - [/[a-z]\w*/,'arguments12'], - [/::/,'dcol'], - [/->/,'pipe'], - [/\bclass\b(?=\s*@classname)/,'keyword','@classname'], - [/\bclass\b(?=\s*\()/,'keyword','@classname'], - [/\binstance\b/,'keyword','@classname'], - [/\bdata\b(?=@typcons)/,'keyword','@typcons'], - [/\bnewtype\b(?=\s*@typcons)/,'keyword'], - {include:'@comment'} - //{include:'@blockComment'} - ], - typcons: [ - [/=>/,'pipes'], - [/->/,'pipe','@bind'], - [/\bclass\b(?=\s*@classname)/,'keyword','@classname'], - [/\bclass\b(?=\s*\()/,'keyword','@classname'], - [/\binstance\b/,'keyword','@classname'], - [/\bdata\b(?=@typcons)/,'keyword','@typcons'], - [/\bnewtype\b(?=\s*@typcons)/,'keyword'], - [/@reservedid(?=\s*\()/,'keyword','@typcons'], - [/@reservedid(?=\s*[A-Z][\w]+)/,'keyword','@typcons'], - [/@reservedid/,'keyword','@binder'], - [/@datatypekey/,'dtypes2'], - [/[A-Z][\w]+(?=\s*,)/,'classname','@types'], - [/[A-Z][\w]+(?=\s*[a-z][\w]*\s*,)/,'classname','@types'], - [/@arguments(?=\s*,\s*)/,'argument','@types'], +// From https://github.com/byteally/monaco-haskell +// It does not work right now. Here as a reminder until the author fixes it +function definition() { + return { + module: /^(module)\b/, + import: /^(import)\b/, + module_name: /([A-Z][\w']*)(\.[A-Z][\w']*)*/, + module_exports:/([A-Z][\w']*)(\.[A-Z][\w']*)*/, + target:/([A-Z][\w']*)(\.[A-Z][\w']*)*/, + invalid:/[a-z]+/, + datatype:/[A-Z][\w]+/, + datatypekey:/Int|Float|Text/, + functions:/[a-z]+/, + datacons:/[A-Z][\w]+/, + typcons:/\s*[A-Z][\w]+/, + text:/[A-Z][\w]+/, + classname:/\s*[A-Z][\w]+/, + arguments:/[a-z][\w]*/, + reservedid:/qualified|hiding|case|default|deriving|do|else|if|import|in|infix|infixr|let|of|then|type|where|show|_/, + tokenizer: { + root: [ + [/(@module)/, 'keyword.module.haskell', '@module'], + [/@import/, 'keyword.module.haskell', '@import'], + [/\bdata\b(?=@typcons)/,'keyword','@typcons'], + [/\bnewtype\b(?=\s*@typcons)/,'keyword','@typcons'], + [/\bclass\b(?=\s*@classname)/,'keyword','@classname'], + [/\bclass\b(?=\s*\()/,'keyword','@classname'], + [/@reservedid/,'keyword'], + [/[a-z][\w]+(?=\s*?=)/,'binderas','@binder'], + [/[a-z][\w]+(?=\s*::)/,'binderad','@typconss'], + [/[a-z][\w]+(?=\s*?[a-z]\w*)/,'binder','@typconss'], + [/[a-z][\w]+(?=\s*?::\s*?@datatypekey)/,'bind','@binder'], + [/[a-z][\w]+(?=\s*?=\s*?@datacons)/,'bindings'], + {include:'@whitespace'}, + {include:'@comment'} + ], + import: [ + [/@module_name/,'storage.module,haskell'], + [/(@module_name)(?=\s*as)/, 'storage.module.haskell'], + [/\b(qualified)\b(?=\s*@module_name)/, 'keyword'], + [/(@module_name)(?=\s*?\()/, 'storage.module.haskell'], + [/(@module_name)(?=\s*\bhiding\b)/, 'storage.module.haskell'], + [/\b(hiding)\b(?=\s*?\()/, 'keyword'], + [/\b(as)\b(?=\s*@module_name)/,'keyword'], + [/\(/,'openbracketss','@functions'], + {include:'@comment'} + //{include:'@blockComment'} + ], + module: [ + [/(@module_name)/, 'storage.module.haskell'], + [/\(/, 'openbracket','@module_exports'], + [/@reservedid/,'keyword','@pop'], + [/@invalid/,'invalid'], + [/,/,'commas'], + {include:'@whitespace'}, + {include:'@comment'} + //{include:'@blockComment'} + ], + functions: [ + [/@datatype/,'dcataype','@datatype'], + [/@functions/,'functions'], + [/,/,'commas'], + [/\)(?=\))/,'closebracket'], + [/\)/,'closebracketalla','@popall'], + {include:'@comment'} + //{include:'@blockComment'} + ], + typconss: [ + [/=/,'eqals'], + [/\bundefined\b/,'val','@all'], + [/\bclass\b(?=\s*@classname)/,'keyword','@classname'], + [/\bclass\b(?=\s*\()/,'keyword','@classname'], + [/\binstance\b/,'keyword','@classname'], + [/\bdata\b(?=@typcons)/,'keyword','@typcons'], + [/\bnewtype\b(?=\s*@typcons)/,'keyword','@typcons'], + [/@reservedid/,'keyword','@function'], + [/[a-z]\w*/,'arguments121'], + [/[a-z][\w]+(?=\s*=)/,'binderad','@datacons'], + [/[a-z][\w]+(?=\s*::)/,'binderad','@typconss'], + [/[a-z][\w]+(?=\s*[a-z]\w*)/,'binderad','@typconss'], + [/[a-z]\w*/,'arguments121'], + [/::/,'dcol','@datacons'], + [/->/,'pipes','@binder'], + {include:'@whitespace'}, + {include:'@comment'} + //{include:'@blockComment'} + ], - [/[A-Z][\w]+/,'typecons'], - [/[a-z][\w]+(?=\s*?=)/,'binderas','@binder'], - [/[a-z][\w]+(?=\s*::)/,'binderad','@typconss'], - [/[a-z][\w]+(?=\s*?[a-z]\w*)/,'bind','@typconss'], - [/[a-z][\w]+(?=\s*?::\s*?@datatypekey)/,'bind','@binder'], - [/[a-z][\w]+(?=\s*?=\s*?@datacons)/,'bindings'], - [/{/,'oopen','@initialise'], - [/[a-z]\w*/,'arguments13'], + function: [ + [/@reservedid/,'keyword'], + [/@datatypekey/,'dtype'], + [/[a-z][\w]+(?=\s*::)/,'binderad','@typconss'], + [/[a-z][\w]+(?=\s*?[a-z]\w*)/,'binder','@typconss'], + [/[a-z]\w*/,'arguments12'], + [/::/,'dcol'], + [/->/,'pipe'], + [/\bclass\b(?=\s*@classname)/,'keyword','@classname'], + [/\bclass\b(?=\s*\()/,'keyword','@classname'], + [/\binstance\b/,'keyword','@classname'], + [/\bdata\b(?=@typcons)/,'keyword','@typcons'], + [/\bnewtype\b(?=\s*@typcons)/,'keyword'], + {include:'@comment'} + //{include:'@blockComment'} + ], + typcons: [ + [/=>/,'pipes'], + [/->/,'pipe','@bind'], + [/\bclass\b(?=\s*@classname)/,'keyword','@classname'], + [/\bclass\b(?=\s*\()/,'keyword','@classname'], + [/\binstance\b/,'keyword','@classname'], + [/\bdata\b(?=@typcons)/,'keyword','@typcons'], + [/\bnewtype\b(?=\s*@typcons)/,'keyword'], + [/@reservedid(?=\s*\()/,'keyword','@typcons'], + [/@reservedid(?=\s*[A-Z][\w]+)/,'keyword','@typcons'], + [/@reservedid/,'keyword','@binder'], + [/@datatypekey/,'dtypes2'], + [/[A-Z][\w]+(?=\s*,)/,'classname','@types'], + [/[A-Z][\w]+(?=\s*[a-z][\w]*\s*,)/,'classname','@types'], + [/@arguments(?=\s*,\s*)/,'argument','@types'], - [/\(/,'open_bracket'], - [/=/,'Equalss','@datacons'], - [/,/,'commaa'], - [/::/,'colondouble','@datacons'], - [/\)/,'closebrak','@initialise'], - [/\)(?=\s* \t\r\n\bdata\b)/,'closed','@popall'], - {include:'@whitespace'}, - {include:'@comment'} + [/[A-Z][\w]+/,'typecons'], + [/[a-z][\w]+(?=\s*?=)/,'binderas','@binder'], + [/[a-z][\w]+(?=\s*::)/,'binderad','@typconss'], + [/[a-z][\w]+(?=\s*?[a-z]\w*)/,'bind','@typconss'], + [/[a-z][\w]+(?=\s*?::\s*?@datatypekey)/,'bind','@binder'], + [/[a-z][\w]+(?=\s*?=\s*?@datacons)/,'bindings'], + [/{/,'oopen','@initialise'], + [/[a-z]\w*/,'arguments13'], + + [/\(/,'open_bracket'], + [/=/,'Equalss','@datacons'], + [/,/,'commaa'], + [/::/,'colondouble','@datacons'], + [/\)/,'closebrak','@initialise'], + [/\)(?=\s* \t\r\n\bdata\b)/,'closed','@popall'], + {include:'@whitespace'}, + {include:'@comment'} // {include:'@blockComment'} - ], - bind: [ - [/@datatypekey/,'dtyp','@typconss'], - [/[a-z][\w]*/,'typvar','@typconss'], - [/\(/,'opens','@typcons'], - {include:'@whitespace'}, - ], - types: [ - [/[a-z][\w]*/,'argument123'], - [/,/,'commaa'], - [/[A-Z][\w]*/,'classname'], - [/\)/,'closex'], - [/=>/,'pipe','@type'], - {include:'@whitespace'}, - {include:'@comment'} + ], + bind: [ + [/@datatypekey/,'dtyp','@typconss'], + [/[a-z][\w]*/,'typvar','@typconss'], + [/\(/,'opens','@typcons'], + {include:'@whitespace'}, + ], + types: [ + [/[a-z][\w]*/,'argument123'], + [/,/,'commaa'], + [/[A-Z][\w]*/,'classname'], + [/\)/,'closex'], + [/=>/,'pipe','@type'], + {include:'@whitespace'}, + {include:'@comment'} // {include:'@blockComment'} - ], - datacons: [ - [/=/,'Equalst'], - [/\bclass\b(?=\s*@classname)/,'keyword','@classname'], - [/\bclass\b(?=\s*\()/,'keyword','@classname'], + ], + datacons: [ + [/=/,'Equalst'], + [/\bclass\b(?=\s*@classname)/,'keyword','@classname'], + [/\bclass\b(?=\s*\()/,'keyword','@classname'], - [/\bundefined\b/,'val','@all'], - [/\bnewtype\b(?=\s*@typcons)/,'keyword','@typcons'], - [/\binstance\b/,'keyword','@classname'], - [/[a-z][\w]*(?=\s*?->)/,'typvar','@typcons'], + [/\bundefined\b/,'val','@all'], + [/\bnewtype\b(?=\s*@typcons)/,'keyword','@typcons'], + [/\binstance\b/,'keyword','@classname'], + [/[a-z][\w]*(?=\s*?->)/,'typvar','@typcons'], - [/@reservedid(?=\s*\()/,'keyword','@typcons'], - [/@datatypekey(?=\s*[a-z]\w*)/,'dtypess1','@typcons'], - [/@datatypekey/,'dtypes1'], - [/@reservedid(?=\s*[A-Z][\w]+)/,'keyword','@typcons'], - [/@reservedid/,'keyword'], - [/[A-Z][\w]+(?=\s*=>)/,'classname','@type'], - [/[A-Z][\w]+(?=\s*[a-z][\w]*\s*=>)/,'classnames','@type'], - [/[a-z][\w]+(?=\s*?::)/,'bindera','@typconss'], - [/[a-z][\w]+(?=\s*?[a-z]\w*)/,'binde','@typconss'], + [/@reservedid(?=\s*\()/,'keyword','@typcons'], + [/@datatypekey(?=\s*[a-z]\w*)/,'dtypess1','@typcons'], + [/@datatypekey/,'dtypes1'], + [/@reservedid(?=\s*[A-Z][\w]+)/,'keyword','@typcons'], + [/@reservedid/,'keyword'], + [/[A-Z][\w]+(?=\s*=>)/,'classname','@type'], + [/[A-Z][\w]+(?=\s*[a-z][\w]*\s*=>)/,'classnames','@type'], + [/[a-z][\w]+(?=\s*?::)/,'bindera','@typconss'], + [/[a-z][\w]+(?=\s*?[a-z]\w*)/,'binde','@typconss'], - [/[a-z][\w]+/,'binder','@typconss'], + [/[a-z][\w]+/,'binder','@typconss'], - [/\bdata\b(?=@typcons)/,'keyword','@typcons'], + [/\bdata\b(?=@typcons)/,'keyword','@typcons'], - [/@datacons/,'datacon'], - [/@reservedid/,'keyword','@binder'], - [/@datacons(?=\s*@datatypekey)/,'datacons'], + [/@datacons/,'datacon'], + [/@reservedid/,'keyword','@binder'], + [/@datacons(?=\s*@datatypekey)/,'datacons'], - [/[a-z][\w]+(?=\s*?::\s*@datatype,)/,'bindera','@binder'], - [/[a-z][\w]+(?=\s*?::\s*@datatype,)/,'bindera','@binder'], - [/[a-z][\w]+(?=\s*?=\s*(\d)+,)/,'binderb','@binder'], - [/[a-z][\w]+(?=\s*?=\s*(\d)+)/,'binderc','@binder'], - [/[a-z][\w]+(?=\s*?=\s*"(\w)+.+?")/,'binderd','@binder'], - [/[a-z][\w]+(?=\s*?=\s*"(\w)+.+?",)/,'bindere','@binder'], - [/{/,'openbracketd','@initialise'], - [/"\w+.+"/,'type'], - [/\d+/,'type'], - [/->/,'pip','@binder'], - [/,/,'commas33','@initialise'], - [/\|/,'alternate'], - [/\(/,'open','@typcons'], - [/}/,'clos','@initialise'], - {include:'@whitespace'}, - {include:'@comment'} + [/[a-z][\w]+(?=\s*?::\s*@datatype,)/,'bindera','@binder'], + [/[a-z][\w]+(?=\s*?::\s*@datatype,)/,'bindera','@binder'], + [/[a-z][\w]+(?=\s*?=\s*(\d)+,)/,'binderb','@binder'], + [/[a-z][\w]+(?=\s*?=\s*(\d)+)/,'binderc','@binder'], + [/[a-z][\w]+(?=\s*?=\s*"(\w)+.+?")/,'binderd','@binder'], + [/[a-z][\w]+(?=\s*?=\s*"(\w)+.+?",)/,'bindere','@binder'], + [/{/,'openbracketd','@initialise'], + [/"\w+.+"/,'type'], + [/\d+/,'type'], + [/->/,'pip','@binder'], + [/,/,'commas33','@initialise'], + [/\|/,'alternate'], + [/\(/,'open','@typcons'], + [/}/,'clos','@initialise'], + {include:'@whitespace'}, + {include:'@comment'} // {include:'@blockComment'} - ], - type: [ - [/[a-z][\w]*/,'argument'], - [/,/,'commas'], - [/=>/,'pipe'], - [/[A-Z][\w]*/,'typcons'], - [/->/,'pipe','@binder'], - {include:'@whitespace'}, - {include:'@comment'} + ], + type: [ + [/[a-z][\w]*/,'argument'], + [/,/,'commas'], + [/=>/,'pipe'], + [/[A-Z][\w]*/,'typcons'], + [/->/,'pipe','@binder'], + {include:'@whitespace'}, + {include:'@comment'} // {include:'@blockComment'} - ], - all: [ - [/=/,'equals'], + ], + all: [ + [/=/,'equals'], - [/\binstance\b/,'keyword','@classname'], - [/\bclass\b(?=\s*@classname)/,'keyword','@classname'], - [/\bclass\b(?=\s*\()/,'keyword','@classname'], - [/\bdata\b(?=@typcons)/,'keyword','@typcons'], + [/\binstance\b/,'keyword','@classname'], + [/\bclass\b(?=\s*@classname)/,'keyword','@classname'], + [/\bclass\b(?=\s*\()/,'keyword','@classname'], + [/\bdata\b(?=@typcons)/,'keyword','@typcons'], - [/\bnewtype\b(?=\s*@typcons)/,'keyword'], - [/@reservedid/,'keyword','@typconss'], - [/[A-Z][\w]+/,'typecons','@typcons'], - [/[a-z][\w]+(?=\s*=)/,'binderad','@typconss'], - [/[a-z][\w]+(?=\s*::)/,'binderad','@typconss'], - [/[a-z][\w]+(?=\s*?[a-z]\w*)/,'binder','@typconss'], - {include:'@comment'} + [/\bnewtype\b(?=\s*@typcons)/,'keyword'], + [/@reservedid/,'keyword','@typconss'], + [/[A-Z][\w]+/,'typecons','@typcons'], + [/[a-z][\w]+(?=\s*=)/,'binderad','@typconss'], + [/[a-z][\w]+(?=\s*::)/,'binderad','@typconss'], + [/[a-z][\w]+(?=\s*?[a-z]\w*)/,'binder','@typconss'], + {include:'@comment'} // {include:'@blockComment'} - ], - selectors: [ - [/[a-z][\w]+/,'selectors'], - [/=/,'Equalsto','@datacons'], - [/"(\w)+.+"/,'type'], - [/\d+/,'type'], - [/}/,'closeS'], - {include:'@comment'} + ], + selectors: [ + [/[a-z][\w]+/,'selectors'], + [/=/,'Equalsto','@datacons'], + [/"(\w)+.+"/,'type'], + [/\d+/,'type'], + [/}/,'closeS'], + {include:'@comment'} // {include:'@blockComment'} - ], - initialise: [ - [/\binstance\b/,'keyword','@classname'], - [/\bdata\b(?=\s*@typcons)/,'keyword','@typcons'], - [/\bnewtype\b(?=\s*@typcons)/,'keyword','@typcons'], - [/\bclass\b(?=\s*@classname)/,'keyword','@classname'], - [/\bclass\b(?=\s*\()/,'keyword','@classname'], - [/@datatypekey(?=\s*)/,'datatype'], - [/{/,'open'], - [/@reservedid/,'keyword'], - [/\(/,'opn','@typcons'], - [/\|/,'alternates','@datacons'], - [/,/,'comma3'], + ], + initialise: [ + [/\binstance\b/,'keyword','@classname'], + [/\bdata\b(?=\s*@typcons)/,'keyword','@typcons'], + [/\bnewtype\b(?=\s*@typcons)/,'keyword','@typcons'], + [/\bclass\b(?=\s*@classname)/,'keyword','@classname'], + [/\bclass\b(?=\s*\()/,'keyword','@classname'], + [/@datatypekey(?=\s*)/,'datatype'], + [/{/,'open'], + [/@reservedid/,'keyword'], + [/\(/,'opn','@typcons'], + [/\|/,'alternates','@datacons'], + [/,/,'comma3'], - [/[a-z][\w]+(?=\s*?=\s*?\b@reservedid\b)/,'binder','@all'], - [/[a-z][\w]+(?=\s*?=\s*?\bundefined\b)/,'binder','@binder'], - [/[a-z][\w]+(?=\s*?=\s*?@datacons)/,'bindings'], - [/[a-z][\w]+(?=\s*?::\s*@datatypekey)/,'bindera','@binder'], - [/[a-z][\w]+(?=\s*::)/,'binder','@binder'], + [/[a-z][\w]+(?=\s*?=\s*?\b@reservedid\b)/,'binder','@all'], + [/[a-z][\w]+(?=\s*?=\s*?\bundefined\b)/,'binder','@binder'], + [/[a-z][\w]+(?=\s*?=\s*?@datacons)/,'bindings'], + [/[a-z][\w]+(?=\s*?::\s*@datatypekey)/,'bindera','@binder'], + [/[a-z][\w]+(?=\s*::)/,'binder','@binder'], - [/[a-z][\w]+(?=\s*?::\s*@datatypekey,)/,'binderb','@binder'], - [/[a-z][\w]+(?=\s*?=\s*(\d)+,)/,'binderc','@binder'], - [/[a-z][\w]+(?=\s*?=\s*(\d)+)/,'binderd','@binder'], - [/[a-z][\w]+(?=\s*?=\s*"(\w)+.+?",)/,'binders','@binder'], - [/[a-z][\w]+(?=\s*?=\s*"(\w)+.+?")/,'bindere','@binder'], + [/[a-z][\w]+(?=\s*?::\s*@datatypekey,)/,'binderb','@binder'], + [/[a-z][\w]+(?=\s*?=\s*(\d)+,)/,'binderc','@binder'], + [/[a-z][\w]+(?=\s*?=\s*(\d)+)/,'binderd','@binder'], + [/[a-z][\w]+(?=\s*?=\s*"(\w)+.+?",)/,'binders','@binder'], + [/[a-z][\w]+(?=\s*?=\s*"(\w)+.+?")/,'bindere','@binder'], - [/[a-z][\w]+(?=\s*[a-z]\w*)/,'binder','@typconss'], - [/::/,'doublecolons','@datacons'], - [/=/,'Equalsto','@datacons'], - {include:'@whitespace'}, - {include:'@comment'} + [/[a-z][\w]+(?=\s*[a-z]\w*)/,'binder','@typconss'], + [/::/,'doublecolons','@datacons'], + [/=/,'Equalsto','@datacons'], + {include:'@whitespace'}, + {include:'@comment'} // {include:'@blockComment'} - ], - classname: [ - [/\binstance\b/,'keyword','@classname'], - [/\bclass\b(?=\s*@classname)/,'keyword','@classname'], - [/\bclass\b(?=\s*\()/,'keyword','@classname'], - [/\bdata\b(?=\s*?@typcons)/,'keyword','@typcons'], - [/\bnewtype\b(?=\s*@typcons)/,'keyword','@typcons'], - [/[a-z][\w]+(?=\s*?=)/,'binderas','@binder'], - [/[a-z][\w]+(?=\s*?::\s*?@datatypekey)/,'binderas','@binder'], - [/@datatypekey/,'dtype'], - [/[A-Z][\w]*/,'classname'], - [/@reservedid/,'keyword','@typcons'], - [/[a-z]\w*/,'arguments'], - [/,/,'commas'], - [/\(/, 'openbracket'], - [/\)/,'closebracket'], - [/=>/,'pipe','@superclass'], - {include:'@whitespace'}, - {include:'@comment'} + ], + classname: [ + [/\binstance\b/,'keyword','@classname'], + [/\bclass\b(?=\s*@classname)/,'keyword','@classname'], + [/\bclass\b(?=\s*\()/,'keyword','@classname'], + [/\bdata\b(?=\s*?@typcons)/,'keyword','@typcons'], + [/\bnewtype\b(?=\s*@typcons)/,'keyword','@typcons'], + [/[a-z][\w]+(?=\s*?=)/,'binderas','@binder'], + [/[a-z][\w]+(?=\s*?::\s*?@datatypekey)/,'binderas','@binder'], + [/@datatypekey/,'dtype'], + [/[A-Z][\w]*/,'classname'], + [/@reservedid/,'keyword','@typcons'], + [/[a-z]\w*/,'arguments'], + [/,/,'commas'], + [/\(/, 'openbracket'], + [/\)/,'closebracket'], + [/=>/,'pipe','@superclass'], + {include:'@whitespace'}, + {include:'@comment'} // {include:'@blockComment'} - ], - binder: [ - [/\binstance\b/,'keyword','@classname'], - [/\bclass\b(?=\s*@classname)/,'keyword','@classname'], - [/\bclass\b(?=\s*\()/,'keyword','@classname'], - [/\bdata\b(?=\s*?@typcons)/,'keyword','@typcons'], - [/@reservedid/,'keyword'], - [/[a-z][\w]+(?=\s*::)/,'binder'], - [/[a-z][\w]+(?=\s*=)/,'binder'], - [/::/,'doublecolons','@datacons'], - [/@datatypekey(?=\s*[a-z]\w*)/,'dtypes','@typcons'], - [/@datatypekey/,'dtypess'], - [/\bnewtype\b(?=\s*@typcons)/,'keyword','@typcons'], - [/->/,'pipe'], - [/\d+/,'digit'], - [/{/,'open'], - [/=/,'Equalsto','@datacons'], + ], + binder: [ + [/\binstance\b/,'keyword','@classname'], + [/\bclass\b(?=\s*@classname)/,'keyword','@classname'], + [/\bclass\b(?=\s*\()/,'keyword','@classname'], + [/\bdata\b(?=\s*?@typcons)/,'keyword','@typcons'], + [/@reservedid/,'keyword'], + [/[a-z][\w]+(?=\s*::)/,'binder'], + [/[a-z][\w]+(?=\s*=)/,'binder'], + [/::/,'doublecolons','@datacons'], + [/@datatypekey(?=\s*[a-z]\w*)/,'dtypes','@typcons'], + [/@datatypekey/,'dtypess'], + [/\bnewtype\b(?=\s*@typcons)/,'keyword','@typcons'], + [/->/,'pipe'], + [/\d+/,'digit'], + [/{/,'open'], + [/=/,'Equalsto','@datacons'], - [/\(/,'opn','@typcons'], - [/\|/,'alternates','@datacons'], - [/,/,'comma3'], + [/\(/,'opn','@typcons'], + [/\|/,'alternates','@datacons'], + [/,/,'comma3'], - [/[a-z][\w]*/,'typvar','@typconss'], - [/\bclass\b(?=\s*@classname)/,'keyword','@classname'], - [/\bclass\b(?=\s*\()/,'keyword','@classname'], - [/\binstance\b/,'keyword','@classname'], - [/\bundefined\b/,'value'], - {include:'@whitespace'}, - {include:'@comment'} + [/[a-z][\w]*/,'typvar','@typconss'], + [/\bclass\b(?=\s*@classname)/,'keyword','@classname'], + [/\bclass\b(?=\s*\()/,'keyword','@classname'], + [/\binstance\b/,'keyword','@classname'], + [/\bundefined\b/,'value'], + {include:'@whitespace'}, + {include:'@comment'} // {include:'@blockComment'} - ], - superclass: [ - [/[A-Z][\w]+/,'typeclass'], - [/@reservedid/,'keyword','@typcons'], - [/[a-z][\w]*/,'typearguments'], - {include:'@whitespace'}, - {include:'@comment'} - //{include:'@blockComment'} - ], - argument: [ - [/[a-z][\w]*(?=\s*->)/,'argument'], - [/->/,'pipea','@binder'], - {include:'@whitespace'}, - {include:'@comment'} + ], + superclass: [ + [/[A-Z][\w]+/,'typeclass'], + [/@reservedid/,'keyword','@typcons'], + [/[a-z][\w]*/,'typearguments'], + {include:'@whitespace'}, + {include:'@comment'} + //{include:'@blockComment'} + ], + argument: [ + [/[a-z][\w]*(?=\s*->)/,'argument'], + [/->/,'pipea','@binder'], + {include:'@whitespace'}, + {include:'@comment'} // {include:'@blockComment'} - ], - datatype: [ - [/\(/,'openbracketd','@pop'], - {include:'@comment'} - //{include:'@blockComment'} - ], - module_exports: [ - [/(@module_exports)/,'storage.module.haskell'], - [/\(/,'openbracket','@target'], - [/\)/,'closebracket','@popall'], - [/,/,'comma1'], - [/@invalid/,'invalid'], - {include:'@whitespace'}, - {include:'@comment'} + ], + datatype: [ + [/\(/,'openbracketd','@pop'], + {include:'@comment'} + //{include:'@blockComment'} + ], + module_exports: [ + [/(@module_exports)/,'storage.module.haskell'], + [/\(/,'openbracket','@target'], + [/\)/,'closebracket','@popall'], + [/,/,'comma1'], + [/@invalid/,'invalid'], + {include:'@whitespace'}, + {include:'@comment'} // {include:'@blockcomment'} - ], - target: [ - [/(@target)/,'target'], - [/,/,'comma2'], - [/\)/,'closebracket','@pop'], - {include:'@comment'} + ], + target: [ + [/(@target)/,'target'], + [/,/,'comma2'], + [/\)/,'closebracket','@pop'], + {include:'@comment'} // {include:'@blockComment'} - ], - whitespace: [ - [/\t\r\n/,'whitespace'], - [/\s*/,'whitespace'] + ], + whitespace: [ + [/\t\r\n/,'whitespace'], + [/\s*/,'whitespace'] - ], - comment: [ - [/--/,'punctuation.comment.haskell'], - {include:'@whitespace'}, - ], - Block_comment: [ - [/{-/,'punctuation.comment.haskell'], - [/-}/,'comment.block.haskell'], - {include:'@whitespace'} - ], - } - }; - } + ], + comment: [ + [/--/,'punctuation.comment.haskell'], + {include:'@whitespace'}, + ], + Block_comment: [ + [/{-/,'punctuation.comment.haskell'], + [/-}/,'comment.block.haskell'], + {include:'@whitespace'} + ], + } + }; +} - monaco.languages.register({id: 'haskell'}); - // TODO: Currently not working. Here as a reminder - /*monaco.languages.setMonarchTokensProvider('haskell', definition());*/ -}); \ No newline at end of file +monaco.languages.register({id: 'haskell'}); +// TODO: Currently not working. Here as a reminder +/*monaco.languages.setMonarchTokensProvider('haskell', definition());*/ \ No newline at end of file diff --git a/static/hub.js b/static/hub.js index 0e8b0416a..3c720a1a2 100644 --- a/static/hub.js +++ b/static/hub.js @@ -23,224 +23,223 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -define(function (require) { - 'use strict'; - var _ = require('underscore'); - var Raven = require('raven-js'); - var editor = require('editor'); - var compiler = require('compiler'); - var output = require('output'); - var Components = require('components'); - var diff = require('diff'); - var optView = require('opt-view'); - var astView = require('ast-view'); - var gccDumpView = require('gccdump-view'); - var cfgView = require('cfg-view'); - var conformanceView = require('conformance-view'); - var CompilerService = require('compiler-service'); +'use strict'; - function Ids() { - this.used = {}; - } +var _ = require('underscore'); +var Raven = require('raven-js'); +var editor = require('editor'); +var compiler = require('compiler'); +var output = require('output'); +var Components = require('components'); +var diff = require('diff'); +var optView = require('opt-view'); +var astView = require('ast-view'); +var gccDumpView = require('gccdump-view'); +var cfgView = require('cfg-view'); +var conformanceView = require('conformance-view'); +var CompilerService = require('compiler-service'); - Ids.prototype.add = function (id) { - this.used[id] = true; - }; - Ids.prototype.remove = function (id) { - delete this.used[id]; - }; - Ids.prototype.next = function () { - for (var i = 1; i < 100000; ++i) { - if (!this.used[i]) { - this.used[i] = true; - return i; - } +function Ids() { + this.used = {}; +} + +Ids.prototype.add = function (id) { + this.used[id] = true; +}; +Ids.prototype.remove = function (id) { + delete this.used[id]; +}; +Ids.prototype.next = function () { + for (var i = 1; i < 100000; ++i) { + if (!this.used[i]) { + this.used[i] = true; + return i; } - throw 'Ran out of ids!?'; - }; - - function Hub(layout, subLangId) { - this.layout = layout; - this.editorIds = new Ids(); - this.compilerIds = new Ids(); - this.compilerService = new CompilerService(); - this.deferred = true; - this.deferredEmissions = []; - this.lastOpenedLangId = null; - this.subdomainLangId = subLangId || null; - - // FIXME - // We can't avoid this self as _ is undefined at this point - var self = this; - - layout.registerComponent(Components.getEditor().componentName, - function (container, state) { - return self.codeEditorFactory(container, state); - }); - layout.registerComponent(Components.getCompiler().componentName, - function (container, state) { - return self.compilerFactory(container, state); - }); - layout.registerComponent(Components.getOutput().componentName, - function (container, state) { - return self.outputFactory(container, state); - }); - layout.registerComponent(diff.getComponent().componentName, - function (container, state) { - return self.diffFactory(container, state); - }); - layout.registerComponent(Components.getOptView().componentName, - function (container, state) { - return self.optViewFactory(container, state); - }); - layout.registerComponent(Components.getAstView().componentName, - function (container, state) { - return self.astViewFactory(container, state); - }); - layout.registerComponent(Components.getGccDumpView().componentName, - function (container, state) { - return self.gccDumpViewFactory(container, state); - }); - layout.registerComponent(Components.getCfgView().componentName, - function (container, state) { - return self.cfgViewFactory(container, state); - }); - layout.registerComponent(Components.getConformanceView().componentName, - function (container, state) { - return self.confomanceFactory(container, state); - }); - - layout.eventHub.on('editorOpen', function (id) { - this.editorIds.add(id); - }, this); - layout.eventHub.on('editorClose', function (id) { - this.editorIds.remove(id); - }, this); - layout.eventHub.on('compilerOpen', function (id) { - this.compilerIds.add(id); - }, this); - layout.eventHub.on('compilerClose', function (id) { - this.compilerIds.remove(id); - }, this); - layout.eventHub.on('languageChange', function (editorId, langId) { - this.lastOpenedLangId = langId; - }, this); - layout.init(); - this.undefer(); - layout.eventHub.emit('initialised'); } + throw 'Ran out of ids!?'; +}; - Hub.prototype.undefer = function () { - this.deferred = false; - var eventHub = this.layout.eventHub; - _.each(this.deferredEmissions, function (args) { - eventHub.emit.apply(eventHub, args); +function Hub(layout, subLangId) { + this.layout = layout; + this.editorIds = new Ids(); + this.compilerIds = new Ids(); + this.compilerService = new CompilerService(); + this.deferred = true; + this.deferredEmissions = []; + this.lastOpenedLangId = null; + this.subdomainLangId = subLangId || null; + + // FIXME + // We can't avoid this self as _ is undefined at this point + var self = this; + + layout.registerComponent(Components.getEditor().componentName, + function (container, state) { + return self.codeEditorFactory(container, state); + }); + layout.registerComponent(Components.getCompiler().componentName, + function (container, state) { + return self.compilerFactory(container, state); + }); + layout.registerComponent(Components.getOutput().componentName, + function (container, state) { + return self.outputFactory(container, state); + }); + layout.registerComponent(diff.getComponent().componentName, + function (container, state) { + return self.diffFactory(container, state); + }); + layout.registerComponent(Components.getOptView().componentName, + function (container, state) { + return self.optViewFactory(container, state); + }); + layout.registerComponent(Components.getAstView().componentName, + function (container, state) { + return self.astViewFactory(container, state); + }); + layout.registerComponent(Components.getGccDumpView().componentName, + function (container, state) { + return self.gccDumpViewFactory(container, state); + }); + layout.registerComponent(Components.getCfgView().componentName, + function (container, state) { + return self.cfgViewFactory(container, state); + }); + layout.registerComponent(Components.getConformanceView().componentName, + function (container, state) { + return self.confomanceFactory(container, state); }); - this.deferredEmissions = []; - }; - Hub.prototype.nextEditorId = function () { - return this.editorIds.next(); - }; - Hub.prototype.nextCompilerId = function () { - return this.compilerIds.next(); - }; + layout.eventHub.on('editorOpen', function (id) { + this.editorIds.add(id); + }, this); + layout.eventHub.on('editorClose', function (id) { + this.editorIds.remove(id); + }, this); + layout.eventHub.on('compilerOpen', function (id) { + this.compilerIds.add(id); + }, this); + layout.eventHub.on('compilerClose', function (id) { + this.compilerIds.remove(id); + }, this); + layout.eventHub.on('languageChange', function (editorId, langId) { + this.lastOpenedLangId = langId; + }, this); + layout.init(); + this.undefer(); + layout.eventHub.emit('initialised'); +} - Hub.prototype.codeEditorFactory = function (container, state) { - // Ensure editors are closable: some older versions had 'isClosable' false. - // NB there doesn't seem to be a better way to do this than reach into the config and rely on the fact nothing - // has used it yet. - container.parent.config.isClosable = true; - return new editor.Editor(this, state, container); - }; +Hub.prototype.undefer = function () { + this.deferred = false; + var eventHub = this.layout.eventHub; + _.each(this.deferredEmissions, function (args) { + eventHub.emit.apply(eventHub, args); + }); + this.deferredEmissions = []; +}; - Hub.prototype.compilerFactory = function (container, state) { - return new compiler.Compiler(this, container, state); - }; +Hub.prototype.nextEditorId = function () { + return this.editorIds.next(); +}; +Hub.prototype.nextCompilerId = function () { + return this.compilerIds.next(); +}; - Hub.prototype.outputFactory = function (container, state) { - return new output.Output(this, container, state); - }; - Hub.prototype.diffFactory = function (container, state) { - return new diff.Diff(this, container, state); - }; - Hub.prototype.optViewFactory = function (container, state) { - return new optView.Opt(this, container, state); - }; - Hub.prototype.astViewFactory = function (container, state) { - return new astView.Ast(this, container, state); - }; - Hub.prototype.gccDumpViewFactory = function (container, state) { - return new gccDumpView.GccDump(this, container, state); - }; - Hub.prototype.cfgViewFactory = function (container, state) { - return new cfgView.Cfg(this, container, state); - }; - Hub.prototype.confomanceFactory = function (container, state) { - return new conformanceView.Conformance(this, container, state); - }; +Hub.prototype.codeEditorFactory = function (container, state) { + // Ensure editors are closable: some older versions had 'isClosable' false. + // NB there doesn't seem to be a better way to do this than reach into the config and rely on the fact nothing + // has used it yet. + container.parent.config.isClosable = true; + return new editor.Editor(this, state, container); +}; - function WrappedEventHub(hub, eventHub) { - this.hub = hub; - this.eventHub = eventHub; - this.subscriptions = []; +Hub.prototype.compilerFactory = function (container, state) { + return new compiler.Compiler(this, container, state); +}; + +Hub.prototype.outputFactory = function (container, state) { + return new output.Output(this, container, state); +}; +Hub.prototype.diffFactory = function (container, state) { + return new diff.Diff(this, container, state); +}; +Hub.prototype.optViewFactory = function (container, state) { + return new optView.Opt(this, container, state); +}; +Hub.prototype.astViewFactory = function (container, state) { + return new astView.Ast(this, container, state); +}; +Hub.prototype.gccDumpViewFactory = function (container, state) { + return new gccDumpView.GccDump(this, container, state); +}; +Hub.prototype.cfgViewFactory = function (container, state) { + return new cfgView.Cfg(this, container, state); +}; +Hub.prototype.confomanceFactory = function (container, state) { + return new conformanceView.Conformance(this, container, state); +}; + +function WrappedEventHub(hub, eventHub) { + this.hub = hub; + this.eventHub = eventHub; + this.subscriptions = []; +} + +WrappedEventHub.prototype.emit = function () { + // Events are deferred during initialisation to allow all the components to install their listeners before + // all the emits are done. This fixes some ordering issues. + if (this.hub.deferred) { + this.hub.deferredEmissions.push(arguments); + } else { + this.eventHub.emit.apply(this.eventHub, arguments); } +}; +WrappedEventHub.prototype.on = function (event, callback, context) { + this.eventHub.on(event, callback, context); + this.subscriptions.push({evt: event, fn: callback, ctx: context}); +}; +WrappedEventHub.prototype.unsubscribe = function () { + _.each(this.subscriptions, _.bind(function (obj) { + try { + this.eventHub.off(obj.evt, obj.fn, obj.ctx); + } catch (e) { + Raven.captureMessage('Can not unsubscribe from ' + obj.evt.toString() + ' :"' + e.msg + '"'); + } + }, this)); + this.subscriptions = []; +}; - WrappedEventHub.prototype.emit = function () { - // Events are deferred during initialisation to allow all the components to install their listeners before - // all the emits are done. This fixes some ordering issues. - if (this.hub.deferred) { - this.hub.deferredEmissions.push(arguments); +Hub.prototype.createEventHub = function () { + return new WrappedEventHub(this, this.layout.eventHub); +}; + +Hub.prototype.findParentRowOrColumn = function (elem) { + while (elem) { + if (elem.isRow || elem.isColumn) return elem; + elem = elem.parent; + } + return elem; +}; + +Hub.prototype.addAtRoot = function (newElem) { + var rootFirstItem = this.layout.root.contentItems[0]; + if (rootFirstItem) { + if (rootFirstItem.isRow || rootFirstItem.isColumn) { + rootFirstItem.addChild(newElem); } else { - this.eventHub.emit.apply(this.eventHub, arguments); + var newRow = this.layout.createContentItem({type: 'row'}, this.layout.root); + this.layout.root.replaceChild(rootFirstItem, newRow); + newRow.addChild(rootFirstItem); + newRow.addChild(newElem); } - }; - WrappedEventHub.prototype.on = function (event, callback, context) { - this.eventHub.on(event, callback, context); - this.subscriptions.push({evt: event, fn: callback, ctx: context}); - }; - WrappedEventHub.prototype.unsubscribe = function () { - _.each(this.subscriptions, _.bind(function (obj) { - try { - this.eventHub.off(obj.evt, obj.fn, obj.ctx); - } catch (e) { - Raven.captureMessage('Can not unsubscribe from ' + obj.evt.toString() + ' :"' + e.msg + '"'); - } - }, this)); - this.subscriptions = []; - }; + } else { + this.layout.root.addChild({ + type: 'row', + content: [newElem] + }); + } +}; - Hub.prototype.createEventHub = function () { - return new WrappedEventHub(this, this.layout.eventHub); - }; - - Hub.prototype.findParentRowOrColumn = function (elem) { - while (elem) { - if (elem.isRow || elem.isColumn) return elem; - elem = elem.parent; - } - return elem; - }; - - Hub.prototype.addAtRoot = function (newElem) { - var rootFirstItem = this.layout.root.contentItems[0]; - if (rootFirstItem) { - if (rootFirstItem.isRow || rootFirstItem.isColumn) { - rootFirstItem.addChild(newElem); - } else { - var newRow = this.layout.createContentItem({type: 'row'}, this.layout.root); - this.layout.root.replaceChild(rootFirstItem, newRow); - newRow.addChild(rootFirstItem); - newRow.addChild(newElem); - } - } else { - this.layout.root.addChild({ - type: 'row', - content: [newElem] - }); - } - }; - - return Hub; -}); +module.exports = Hub; diff --git a/static/ispc-mode.js b/static/ispc-mode.js index 937f1a8ca..13a49aaf6 100644 --- a/static/ispc-mode.js +++ b/static/ispc-mode.js @@ -1,60 +1,58 @@ -define(function (require) { - 'use strict'; - var jquery = require('jquery'); - var monaco = require('monaco'); - var cpp = require('vs/basic-languages/src/cpp'); +'use strict'; - function definition() { - var ispc = jquery.extend(true, {}, cpp.language); // deep copy +var jquery = require('jquery'); +var cpp = require('vs/basic-languages/src/cpp'); - ispc.tokenPostfix = '.ispc'; +function definition() { + var ispc = jquery.extend(true, {}, cpp.language); // deep copy - ispc.keywords.push( - 'cbreak', - 'ccontinue', - 'cdo', - 'cfor', - 'cif', - 'creturn', - 'cwhile', - 'delete', - 'export', - 'foreach', - 'foreach_active', - 'foreach_tiled', - 'foreach_unique', - 'int16', - 'int32', - 'int64', - 'int8', - 'launch', - 'new', - 'operator', - 'programCount', - 'programIndex', - 'reference', - 'soa', - 'sync', - 'task', - 'taskCount', - 'taskCount0', - 'taskCount1', - 'taskCount2', - 'taskIndex', - 'taskIndex0', - 'taskIndex1', - 'taskIndex2', - 'threadCount', - 'threadIndex', - 'uniform', - 'unmasked', - 'varying' - ); + ispc.tokenPostfix = '.ispc'; - return ispc; - } + ispc.keywords.push( + 'cbreak', + 'ccontinue', + 'cdo', + 'cfor', + 'cif', + 'creturn', + 'cwhile', + 'delete', + 'export', + 'foreach', + 'foreach_active', + 'foreach_tiled', + 'foreach_unique', + 'int16', + 'int32', + 'int64', + 'int8', + 'launch', + 'new', + 'operator', + 'programCount', + 'programIndex', + 'reference', + 'soa', + 'sync', + 'task', + 'taskCount', + 'taskCount0', + 'taskCount1', + 'taskCount2', + 'taskIndex', + 'taskIndex0', + 'taskIndex1', + 'taskIndex2', + 'threadCount', + 'threadIndex', + 'uniform', + 'unmasked', + 'varying' + ); + return ispc; +} + +monaco.languages.register({id: 'ispc'}); +monaco.languages.setLanguageConfiguration('ispc', cpp.conf); +monaco.languages.setMonarchTokensProvider('ispc', definition()); - monaco.languages.register({id: 'ispc'}); - monaco.languages.setLanguageConfiguration('ispc', cpp.conf); - monaco.languages.setMonarchTokensProvider('ispc', definition()); -}); diff --git a/static/loadSave.js b/static/loadSave.js index 419b735b7..4ede3b89b 100644 --- a/static/loadSave.js +++ b/static/loadSave.js @@ -23,165 +23,164 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -define(function (require) { - "use strict"; - var $ = require('jquery'); - var _ = require('underscore'); - var saveAs = require('filesaver'); - var Alert = require('./alert'); - var local = require('./local'); - var Promise = require('es6-promise').Promise; +"use strict"; +var $ = require('jquery'); +var _ = require('underscore'); +var saveAs = require('filesaver'); +var Alert = require('./alert'); +var local = require('./local'); +var Promise = require('es6-promise').Promise; - function getLocalFiles() { - return JSON.parse(local.get('files', "{}")); - } +function getLocalFiles() { + return JSON.parse(local.get('files', "{}")); +} - function setLocalFile(name, file) { - var files = getLocalFiles(); - files[name] = file; - local.set('files', JSON.stringify(files)); - } +function setLocalFile(name, file) { + var files = getLocalFiles(); + files[name] = file; + local.set('files', JSON.stringify(files)); +} - function LoadSave() { - this.modal = $('#load-save'); - this.alert = new Alert(); - this.onLoad = _.identity; - this.editorText = ''; - this.extension = '.txt'; - this.modal.find('.local-file').change(_.bind(this.onLocalFile, this)); +function LoadSave() { + this.modal = $('#load-save'); + this.alert = new Alert(); + this.onLoad = _.identity; + this.editorText = ''; + this.extension = '.txt'; + this.modal.find('.local-file').change(_.bind(this.onLocalFile, this)); - this.modal.find('.save-button').click(_.bind(this.onSaveToBrowserStorage, this)); - this.modal.find('.save-file').click(_.bind(this.onSaveToFile, this)); + this.modal.find('.save-button').click(_.bind(this.onSaveToBrowserStorage, this)); + this.modal.find('.save-file').click(_.bind(this.onSaveToFile, this)); - this.fetchBuiltins(); - } + this.fetchBuiltins(); +} - LoadSave.prototype.fetchBuiltins = function () { - return new Promise(_.bind(function (resolve, reject) { - $.getJSON('source/builtin/list', function (list) { - resolve(list); - }); +LoadSave.prototype.fetchBuiltins = function () { + return new Promise(_.bind(function (resolve, reject) { + $.getJSON('source/builtin/list', function (list) { + resolve(list); + }); + }, this)); +}; + +LoadSave.prototype.populateBuiltins = function () { + var isVisible = _.bind(function (entry) { + return this.currentLanguage && this.currentLanguage.id === entry.lang; + }, this); + return this.fetchBuiltins() + .then(_.bind(function (builtins) { + this.populate(this.modal.find('.examples'), + _.map(_.filter(builtins, isVisible), _.bind(function (elem) { + return { + name: elem.name, + load: _.bind(function () { + this.doLoad(elem); + }, this) + }; + }, this)) + ); }, this)); - }; +}; - LoadSave.prototype.populateBuiltins = function () { - var isVisible = _.bind(function (entry) { - return this.currentLanguage && this.currentLanguage.id === entry.lang; - }, this); - return this.fetchBuiltins() - .then(_.bind(function (builtins) { - this.populate(this.modal.find('.examples'), - _.map(_.filter(builtins, isVisible), _.bind(function (elem) { - return { - name: elem.name, - load: _.bind(function () { - this.doLoad(elem); - }, this) - }; - }, this)) - ); - }, this)); - }; +LoadSave.prototype.populateLocalStorage = function () { + this.populate( + this.modal.find('.local-storage'), + _.map(getLocalFiles(), _.bind(function (data, name) { + return { + name: name, + load: _.bind(function () { + this.onLoad(data); + this.modal.modal('hide'); + }, this) + }; + }, this))); +}; - LoadSave.prototype.populateLocalStorage = function () { - this.populate( - this.modal.find('.local-storage'), - _.map(getLocalFiles(), _.bind(function (data, name) { - return { - name: name, - load: _.bind(function () { - this.onLoad(data); - this.modal.modal('hide'); - }, this) - }; - }, this))); - }; +LoadSave.prototype.populate = function (root, list) { + root.find('li:not(.template)').remove(); + var template = root.find('.template'); + _.each(list, _.bind(function (elem) { + template + .clone() + .removeClass('template') + .appendTo(root) + .find('a') + .text(elem.name) + .click(elem.load); + }, this)); +}; - LoadSave.prototype.populate = function (root, list) { - root.find('li:not(.template)').remove(); - var template = root.find('.template'); - _.each(list, _.bind(function (elem) { - template - .clone() - .removeClass('template') - .appendTo(root) - .find('a') - .text(elem.name) - .click(elem.load); - }, this)); - }; +LoadSave.prototype.onLocalFile = function (event) { + var files = event.target.files; + var file = files[0]; + var reader = new FileReader(); + reader.onload = _.bind(function () { + this.onLoad(reader.result); + }, this); + reader.readAsText(file); + this.modal.modal('hide'); +}; - LoadSave.prototype.onLocalFile = function (event) { - var files = event.target.files; - var file = files[0]; - var reader = new FileReader(); - reader.onload = _.bind(function () { - this.onLoad(reader.result); - }, this); - reader.readAsText(file); +LoadSave.prototype.run = function (onLoad, editorText, currentLanguage) { + this.populateLocalStorage(); + this.onLoad = onLoad; + this.editorText = editorText; + // In case we don't send anything... + this.currentLanguage = currentLanguage; + this.extension = currentLanguage.extensions[0] || '.txt'; + this.modal.find('.local-file').attr('accept', _.map(currentLanguage.extensions, function (extension) { + return extension + ', '; + }, this)); + this.populateBuiltins().then(_.bind(function () { + this.modal.modal(); + }, this)); +}; + +LoadSave.prototype.onSaveToBrowserStorage = function () { + var name = this.modal.find('.save-name').val(); + if (!name) { + this.alert.alert("Save name", "Invalid save name"); + return; + } + name += " (" + this.currentLanguage.name + ")"; + var done = _.bind(function () { + setLocalFile(name, this.editorText); + }, this); + if (getLocalFiles()[name] !== undefined) { this.modal.modal('hide'); - }; - - LoadSave.prototype.run = function (onLoad, editorText, currentLanguage) { - this.populateLocalStorage(); - this.onLoad = onLoad; - this.editorText = editorText; - // In case we don't send anything... - this.currentLanguage = currentLanguage; - this.extension = currentLanguage.extensions[0] || '.txt'; - this.modal.find('.local-file').attr('accept', _.map(currentLanguage.extensions, function (extension) { - return extension + ', '; - }, this)); - this.populateBuiltins().then(_.bind(function () { - this.modal.modal(); - }, this)); - }; - - LoadSave.prototype.onSaveToBrowserStorage = function () { - var name = this.modal.find('.save-name').val(); - if (!name) { - this.alert.alert("Save name", "Invalid save name"); - return; - } - name += " (" + this.currentLanguage.name + ")"; - var done = _.bind(function () { - setLocalFile(name, this.editorText); - }, this); - if (getLocalFiles()[name] !== undefined) { - this.modal.modal('hide'); - this.alert.ask( - "Replace current?", - "Do you want to replace the existing saved file '" + name + "'?", - {yes: done}); - } else { - done(); - this.modal.modal('hide'); - } - }; - - LoadSave.prototype.onSaveToFile = function () { - try { - saveAs(new Blob( - [this.editorText], - {type: "text/plain;charset=utf-8"}), - "Compiler Explorer Code" + this.extension); - } catch (e) { - new Alert().notify('Error while saving your code. Use the clipboard instead.', { - group: "savelocalerror", - alertClass: "notification-error", - dismissTime: 5000 - }); - } - }; - - LoadSave.prototype.doLoad = function (element) { - // TODO: handle errors. consider promises... - $.getJSON('source/builtin/load/' + element.lang + '/' + element.file, - _.bind(function (response) { - this.onLoad(response.file); - }, this)); + this.alert.ask( + "Replace current?", + "Do you want to replace the existing saved file '" + name + "'?", + {yes: done}); + } else { + done(); this.modal.modal('hide'); - }; + } +}; - return {LoadSave: LoadSave}; -}); +LoadSave.prototype.onSaveToFile = function () { + try { + saveAs(new Blob( + [this.editorText], + {type: "text/plain;charset=utf-8"}), + "Compiler Explorer Code" + this.extension); + } catch (e) { + new Alert().notify('Error while saving your code. Use the clipboard instead.', { + group: "savelocalerror", + alertClass: "notification-error", + dismissTime: 5000 + }); + } +}; + +LoadSave.prototype.doLoad = function (element) { + // TODO: handle errors. consider promises... + $.getJSON('source/builtin/load/' + element.lang + '/' + element.file, + _.bind(function (response) { + this.onLoad(response.file); + }, this)); + this.modal.modal('hide'); +}; + + +module.exports = {LoadSave: LoadSave}; diff --git a/static/local.js b/static/local.js index 7d6cf86ca..29961bf46 100644 --- a/static/local.js +++ b/static/local.js @@ -23,44 +23,42 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -define(function (require) { - "use strict"; - var options = require('./options'); - var prefix = options.localStoragePrefix || ''; +"use strict"; +var options = require('./options'); +var prefix = options.localStoragePrefix || ''; - function get(key, ifNotPresent) { - var result; - try { - result = window.localStorage.getItem(prefix + key); - } catch (e) { - // Swallow up any security exceptions... - return ifNotPresent; - } - if (result === null) return ifNotPresent; - return result; +function get(key, ifNotPresent) { + var result; + try { + result = window.localStorage.getItem(prefix + key); + } catch (e) { + // Swallow up any security exceptions... + return ifNotPresent; } + if (result === null) return ifNotPresent; + return result; +} - function set(key, value) { - try { - window.localStorage.setItem(prefix + key, value); - return true; - } catch (e) { - // Swallow up any security exceptions... - } - return false; +function set(key, value) { + try { + window.localStorage.setItem(prefix + key, value); + return true; + } catch (e) { + // Swallow up any security exceptions... } + return false; +} - function remove(key) { - try { - window.localStorage.removeItem(prefix + key); - } catch (e) { - // Swallow up any security exceptions... - } +function remove(key) { + try { + window.localStorage.removeItem(prefix + key); + } catch (e) { + // Swallow up any security exceptions... } +} - return { - set: set, - get: get, - remove: remove - }; -}); +module.exports = { + set: set, + get: get, + remove: remove +}; diff --git a/static/main.js b/static/main.js index a6be5de1a..f9eab55d4 100644 --- a/static/main.js +++ b/static/main.js @@ -21,203 +21,179 @@ // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. +// POSSIBILITY OF SUCH DAMAGE +"use strict"; -require.config({ // jshint ignore:line - paths: { - bootstrap: 'ext/bootstrap/dist/js/bootstrap', - jquery: 'ext/jquery/dist/jquery', - underscore: 'ext/underscore/underscore', - goldenlayout: 'ext/golden-layout/dist/goldenlayout', - selectize: 'ext/selectize/dist/js/selectize', - sifter: 'ext/sifter/sifter', - microplugin: 'ext/microplugin/src/microplugin', - events: 'ext/eventEmitter/EventEmitter', - lzstring: 'ext/lz-string/libs/lz-string', - clipboard: 'ext/clipboard/dist/clipboard', - 'big-integer': 'ext/big-integer/BigInteger.min', - 'raven-js': 'ext/raven-js/dist/raven', - 'es6-promise': 'ext/es6-promise/es6-promise', - 'lru-cache': 'ext/lru-cache/lib/lru-cache', - vs: "ext/monaco-editor/min/vs", - 'bootstrap-slider': 'ext/seiyria-bootstrap-slider/dist/bootstrap-slider', - filesaver: 'ext/file-saver/FileSaver', - vis: 'ext/vis/dist/vis.min' - }, - shim: { - underscore: {exports: '_'}, - filesaver: {exports: 'saveAs'}, - 'lru-cache': {exports: 'LRUCache'}, - bootstrap: ['jquery'], - 'bootstrap-slider': ['bootstrap'] - }, - waitSeconds: 60 -}); +require("monaco-loader")().then(function() { + +require('bootstrap'); +require('bootstrap-slider'); -define(function (require) { - "use strict"; - require('bootstrap'); - require('bootstrap-slider'); - var analytics = require('analytics'); - var sharing = require('sharing'); - var _ = require('underscore'); - var $ = require('jquery'); - var GoldenLayout = require('goldenlayout'); - var Components = require('components'); - var url = require('url'); - var clipboard = require('clipboard'); - var Hub = require('hub'); - var Raven = require('raven-js'); - var settings = require('./settings'); - var local = require('./local'); - var Alert = require('./alert'); - var themer = require('./themes'); +var analytics = require('analytics'); +var sharing = require('sharing'); +var _ = require('underscore'); +var $ = require('jquery'); +var GoldenLayout = require('goldenlayout'); +var Components = require('components'); +var url = require('./url'); +var clipboard = require('clipboard'); +var Hub = require('hub'); +var Raven = require('raven-js'); +var settings = require('./settings'); +var local = require('./local'); +var Alert = require('./alert'); +var themer = require('./themes'); - function setupSettings(hub) { - var eventHub = hub.layout.eventHub; - var defaultSettings = { - defaultLanguage: hub.subdomainLangId - }; - var currentSettings = JSON.parse(local.get('settings', null)) || defaultSettings; +//css +require("bootstrap/dist/css/bootstrap.min.css"); +require("goldenlayout/src/css/goldenlayout-base.css"); +require("selectize/dist/css/selectize.bootstrap2.css"); +require("bootstrap-slider/dist/css/bootstrap-slider.css"); +require("./colours.css"); +require("./explorer.css"); - function onChange(settings) { - currentSettings = settings; - local.set('settings', JSON.stringify(settings)); - eventHub.emit('settingsChange', settings); - } +function setupSettings(hub) { + var eventHub = hub.layout.eventHub; + var defaultSettings = { + defaultLanguage: hub.subdomainLangId + }; + var currentSettings = JSON.parse(local.get('settings', null)) || defaultSettings; - new themer.Themer(eventHub, currentSettings); - - eventHub.on('requestSettings', function () { - eventHub.emit('settingsChange', currentSettings); - }); - - var setSettings = settings($('#settings'), currentSettings, onChange, hub.subdomainLangId); - eventHub.on('modifySettings', function (newSettings) { - setSettings(_.extend(currentSettings, newSettings)); - }); + function onChange(settings) { + currentSettings = settings; + local.set('settings', JSON.stringify(settings)); + eventHub.emit('settingsChange', settings); } - function start() { - analytics.initialise(); + new themer.Themer(eventHub, currentSettings); - var options = require('options'); + eventHub.on('requestSettings', function () { + eventHub.emit('settingsChange', currentSettings); + }); - var subdomainPart = window.location.hostname.split('.')[0]; - var langBySubdomain = _.find(options.languages, function (lang) { - return lang.id === subdomainPart || lang.alias.indexOf(subdomainPart) >= 0; - }); - var subLangId = langBySubdomain ? langBySubdomain.id : null; + var setSettings = settings($('#settings'), currentSettings, onChange, hub.subdomainLangId); + eventHub.on('modifySettings', function (newSettings) { + setSettings(_.extend(currentSettings, newSettings)); + }); +} - var defaultConfig = { - settings: {showPopoutIcon: false}, - content: [{ - type: 'row', - content: [ - Components.getEditor(1, subLangId), - Components.getCompiler(1, subLangId) - ] - }] - }; - - $(window).bind('hashchange', function () { - // punt on hash events and just reload the page if there's a hash - if (window.location.hash.substr(1)) - window.location.reload(); - }); +function start() { + analytics.initialise(); - var config; - if (!options.embedded) { - config = url.deserialiseState(window.location.hash.substr(1)); - if (config) { - // replace anything in the default config with that from the hash - config = _.extend(defaultConfig, config); - } + var options = require('options'); - if (!config) { - var savedState = local.get('gl', null); - config = savedState !== null ? JSON.parse(savedState) : defaultConfig; - } - } else { - config = _.extend(defaultConfig, - { - settings: { - showMaximiseIcon: false, - showCloseIcon: false, - hasHeaders: false - } - }, - sharing.configFromEmbedded(window.location.hash.substr(1))); - } + var subdomainPart = window.location.hostname.split('.')[0]; + var langBySubdomain = _.find(options.languages, function (lang) { + return lang.id === subdomainPart || lang.alias.indexOf(subdomainPart) >= 0; + }); + var subLangId = langBySubdomain ? langBySubdomain.id : null; - var root = $("#root"); - - var layout; - var hub; - try { - layout = new GoldenLayout(config, root); - hub = new Hub(layout, subLangId); - } catch (e) { - Raven.captureException(e); - layout = new GoldenLayout(defaultConfig, root); - hub = new Hub(layout, subLangId); - } - layout.on('stateChanged', function () { - var config = layout.toConfig(); - // Only preserve state in localStorage in non-embedded mode. - if (!options.embedded) { - local.set('gl', JSON.stringify(config)); - } else { - var strippedToLast = window.location.pathname; - strippedToLast = strippedToLast.substr(0, - strippedToLast.lastIndexOf('/') + 1); - $('a.link').attr('href', strippedToLast + '#' + url.serialiseState(config)); - } - }); - - function sizeRoot() { - var height = $(window).height() - root.position().top; - root.height(height); - layout.updateSize(); - } - - $(window).resize(sizeRoot); - sizeRoot(); - - new clipboard('.btn.clippy'); - - setupSettings(hub); - - sharing.initShareButton($('#share'), layout); - - function setupAdd(thing, func) { - layout.createDragSource(thing, func); - thing.click(function () { - hub.addAtRoot(func()); - }); - } - - setupAdd($('#add-diff'), function () { - return Components.getDiff(); - }); - setupAdd($('#add-editor'), function () { - return Components.getEditor(); - }); - $('#ui-reset').click(function () { - local.remove('gl'); + var defaultConfig = { + settings: {showPopoutIcon: false}, + content: [{ + type: 'row', + content: [ + Components.getEditor(1, subLangId), + Components.getCompiler(1, subLangId) + ] + }] + }; + + $(window).bind('hashchange', function () { + // punt on hash events and just reload the page if there's a hash + if (window.location.hash.substr(1)) window.location.reload(); - }); - $('#thanks-to').click(function () { - $.get('thanks.html', function (result) { - new Alert().alert("Special thanks to", $(result)); - }); - }); - $('#changes').click(function () { - $.get('changelog.html', function (result) { - new Alert().alert("Changelog", $(result)); - }); + }); + + var config; + if (!options.embedded) { + config = url.deserialiseState(window.location.hash.substr(1)); + if (config) { + // replace anything in the default config with that from the hash + config = _.extend(defaultConfig, config); + } + + if (!config) { + var savedState = local.get('gl', null); + config = savedState !== null ? JSON.parse(savedState) : defaultConfig; + } + } else { + config = _.extend(defaultConfig, + { + settings: { + showMaximiseIcon: false, + showCloseIcon: false, + hasHeaders: false + } + }, + sharing.configFromEmbedded(window.location.hash.substr(1))); + } + + var root = $("#root"); + + var layout; + var hub; + try { + layout = new GoldenLayout(config, root); + hub = new Hub(layout, subLangId); + } catch (e) { + Raven.captureException(e); + layout = new GoldenLayout(defaultConfig, root); + hub = new Hub(layout, subLangId); + } + layout.on('stateChanged', function () { + var config = layout.toConfig(); + // Only preserve state in localStorage in non-embedded mode. + if (!options.embedded) { + local.set('gl', JSON.stringify(config)); + } else { + var strippedToLast = window.location.pathname; + strippedToLast = strippedToLast.substr(0, + strippedToLast.lastIndexOf('/') + 1); + $('a.link').attr('href', strippedToLast + '#' + url.serialiseState(config)); + } + }); + + function sizeRoot() { + var height = $(window).height() - root.position().top; + root.height(height); + layout.updateSize(); + } + + $(window).resize(sizeRoot); + sizeRoot(); + + new clipboard('.btn.clippy'); + + setupSettings(hub); + + sharing.initShareButton($('#share'), layout); + + function setupAdd(thing, func) { + layout.createDragSource(thing, func); + thing.click(function () { + hub.addAtRoot(func()); }); } + setupAdd($('#add-diff'), function () { + return Components.getDiff(); + }); + setupAdd($('#add-editor'), function () { + return Components.getEditor(); + }); + $('#ui-reset').click(function () { + local.remove('gl'); + window.location.reload(); + }); + $('#thanks-to').click(function () { + new Alert().alert("Special thanks to", $(require('./thanks.html'))); + }); + $('#changes').click(function () { + new Alert().alert("Changelog", $(require('./changelog.html'))); + }); +} + $(start); }); + diff --git a/static/monaco-loader.js b/static/monaco-loader.js new file mode 100644 index 000000000..f3fef9e00 --- /dev/null +++ b/static/monaco-loader.js @@ -0,0 +1,27 @@ +"use strict"; + +var Promise = require('es6-promise').Promise, + _loaded = false, + _loadPromise = null; + +// Returns promise that will be fulfilled when monaco is available +var waitForMonaco = function() { + if (_loadPromise) { + return _loadPromise; + } + + _loadPromise = new Promise(function(resolve, reject) { + if (typeof(window.monaco) === 'object') { + resolve(window.monaco); + return window.monaco; + } + + window.require(['vs/editor/editor.main'], function() { + _loaded = true; + resolve(window.monaco); + }); + }); + return _loadPromise; +}; + +module.exports = waitForMonaco; diff --git a/static/monaco.js b/static/monaco.js index 90ffb4d68..f15995118 100644 --- a/static/monaco.js +++ b/static/monaco.js @@ -23,9 +23,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -define(function (require) { - "use strict"; - require('vs/editor/editor.main'); - return monaco; // jshint ignore:line -}); + +//until webpack can support monaco properly it exists on the window +module.exports = monaco; \ No newline at end of file diff --git a/static/opt-view.js b/static/opt-view.js index 06b54af48..eb064dc73 100644 --- a/static/opt-view.js +++ b/static/opt-view.js @@ -22,169 +22,202 @@ // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. +"use strict"; -define(function (require) { - "use strict"; +var FontScale = require('fontscale'); +var monaco = require('monaco'); +var options = require('options'); +var _ = require('underscore'); +var $ = require('jquery'); - var FontScale = require('fontscale'); - var monaco = require('monaco'); - var _ = require('underscore'); - var $ = require('jquery'); +require('asm-mode'); +require('selectize'); - function Opt(hub, container, state) { - state = state || {}; - this.container = container; - this.eventHub = hub.createEventHub(); - this.domRoot = container.getElement(); - this.domRoot.html($('#opt').html()); - this.compilers = {}; - this.code = state.source || ""; - this._currentDecorations = []; - this.optEditor = monaco.editor.create(this.domRoot.find(".monaco-placeholder")[0], { - value: this.code, - scrollBeyondLastLine: false, - language: 'cppp', //we only support cpp(p) for now - readOnly: true, - glyphMargin: true, - quickSuggestions: false, - fontFamily: 'monospace', - fixedOverflowWidgets: true, - minimap: { - maxColumn: 80 - }, - lineNumbersMinChars: 3 - }); +function Opt(hub, container, state) { + state = state || {}; + this.container = container; + this.eventHub = hub.createEventHub(); + this.domRoot = container.getElement(); + this.domRoot.html($('#opt').html()); + this.compilers = {}; + this.code = state.source || ""; + this._currentDecorations = []; + this.optEditor = monaco.editor.create(this.domRoot.find(".monaco-placeholder")[0], { + value: this.code, + scrollBeyondLastLine: false, + language: 'cppp', //we only support cpp(p) for now + readOnly: true, + glyphMargin: true, + quickSuggestions: false, + fixedOverflowWidgets: true, + fontFamily: 'monospace', + minimap: { + maxColumn: 80 + }, + lineNumbersMinChars: 3 + }); - this._compilerid = state.id; - this._compilerName = state.compilerName; - this._editorid = state.editorid; - this.fontScale = new FontScale(this.domRoot, state, this.optEditor); - this.fontScale.on('change', _.bind(this.updateState, this)); + this._compilerid = state.id; + this._compilerName = state.compilerName; + this._editorid = state.editorid; + this.fontScale = new FontScale(this.domRoot, state, this.optEditor); + this.fontScale.on('change', _.bind(this.updateState, this)); - this.eventHub.on('compileResult', this.onCompileResult, this); - this.eventHub.on('compiler', this.onCompiler, this); - this.eventHub.on('compilerClose', this.onCompilerClose, this); - this.eventHub.on('editorChange', this.onEditorChange, this); - this.eventHub.on('settingsChange', this.onSettingsChange, this); - this.eventHub.on('resize', this.resize, this); - this.container.on('destroy', this.close, this); - this.eventHub.emit('requestSettings'); + this.eventHub.on('compileResult', this.onCompileResult, this); + this.eventHub.on('compiler', this.onCompiler, this); + this.eventHub.on('compilerClose', this.onCompilerClose, this); + this.eventHub.on('editorChange', this.onEditorChange, this); + this.eventHub.on('settingsChange', this.onSettingsChange, this); + this.eventHub.on('resize', this.resize, this); + this.container.on('destroy', this.close, this); + this.eventHub.emit('requestSettings'); - container.on('resize', this.resize, this); - container.on('shown', this.resize, this); - if (state && state.optOutput) { - this.showOptResults(state.optOutput); - } - this.setTitle(); - this.eventHub.emit("optViewOpened", this._compilerid); + container.on('resize', this.resize, this); + container.on('shown', this.resize, this); + if (state && state.optOutput) { + this.showOptResults(state.optOutput); } + this.setTitle(); + this.eventHub.emit("optViewOpened", this._compilerid); +} - // TODO: de-dupe with compiler etc - Opt.prototype.resize = function () { - var topBarHeight = this.domRoot.find(".top-bar").outerHeight(true); - this.optEditor.layout({ - width: this.domRoot.width(), - height: this.domRoot.height() - topBarHeight +// TODO: de-dupe with compiler etc +Opt.prototype.resize = function () { + var topBarHeight = this.domRoot.find(".top-bar").outerHeight(true); + this.optEditor.layout({ + width: this.domRoot.width(), + height: this.domRoot.height() - topBarHeight + }); +}; + +Opt.prototype.onEditorChange = function (id, source) { + if (this._editorid == id) { + this.code = source; + this.optEditor.setValue(source); + } +}; + +Opt.prototype.onCompileResult = function (id, compiler, result) { + if (result.hasOptOutput && this._compilerid == id) { + this.showOptResults(result.optOutput); + } +}; +Opt.prototype.setTitle = function () { + this.container.setTitle(this._compilerName + " Opt Viewer (Editor #" + this._editorid + ", Compiler #" + this._compilerid + ")"); +}; + +Opt.prototype.getDisplayableOpt = function (optResult) { + return "**" + optResult.optType + "** - " + optResult.displayString; +}; + +Opt.prototype.showOptResults = function (results) { + var opt = []; + + results = _.filter(results, function (x) { + return x.DebugLoc !== undefined; + }); + + results = _.groupBy(results, function (x) { + return x.DebugLoc.Line; + }); + + _.mapObject(results, function (value, key) { + var linenumber = Number(key); + var className = value.reduce(function (acc, x) { + if (x.optType == "Missed" || acc == "Missed") { + return "Missed"; + } else if (x.optType == "Passed" || acc == "Passed") { + return "Passed"; + } + return x.optType; + }, ""); + var contents = _.map(value, this.getDisplayableOpt, this); + opt.push({ + range: new monaco.Range(linenumber, 1, linenumber, Infinity), + options: { + isWholeLine: true, + glyphMarginClassName: "opt-decoration." + className.toLowerCase(), + hoverMessage: contents, + glyphMarginHoverMessage: contents + } }); - }; + }, this); - Opt.prototype.onEditorChange = function (id, source) { - if (this._editorid === id) { - this.code = source; - this.optEditor.setValue(source); + this._currentDecorations = this.optEditor.deltaDecorations(this._currentDecorations, opt); +}; + +Opt.prototype.onCompiler = function (id, compiler, options, editorid) { + if (id === this._compilerid) { + this._compilerName = compiler ? compiler.name : ''; + this.setTitle(); + if (compiler && !compiler.supportsOptOutput) { + this.code = this.optEditor.getValue(); + this.optEditor.setValue("<" + compiler.version + " does not support the optimisation view>"); + return; } - }; - Opt.prototype.onCompileResult = function (id, compiler, result) { - if (result.hasOptOutput && this._compilerid === id) { - this.showOptResults(result.optOutput); - } - }; - Opt.prototype.setTitle = function () { - this.container.setTitle(this._compilerName + " Opt Viewer (Editor #" + this._editorid + ", Compiler #" + this._compilerid + ")"); - }; + this._editorid = editorid; + this.optEditor.setValue(this.code); + } +}; - Opt.prototype.getDisplayableOpt = function (optResult) { - return "**" + optResult.optType + "** - " + optResult.displayString; - }; +// TODO: de-dupe with compiler etc +Opt.prototype.resize = function () { + var topBarHeight = this.domRoot.find(".top-bar").outerHeight(true); + this.optEditor.layout({ + width: this.domRoot.width(), + height: this.domRoot.height() - topBarHeight + }); +}; - Opt.prototype.showOptResults = function (results) { - var opt = []; +Opt.prototype.onEditorChange = function (id, source) { + if (this._editorid === id) { + this.code = source; + this.optEditor.setValue(source); + } +}; - results = _.filter(results, function (x) { - return x.DebugLoc !== undefined; - }); +Opt.prototype.onCompileResult = function (id, compiler, result) { + if (result.hasOptOutput && this._compilerid === id) { + this.showOptResults(result.optOutput); + } +}; - results = _.groupBy(results, function (x) { - return x.DebugLoc.Line; - }); +Opt.prototype.setTitle = function () { + this.container.setTitle(this._compilerName + " Opt Viewer (Editor #" + this._editorid + ", Compiler #" + this._compilerid + ")"); +}; - _.mapObject(results, function (value, key) { - var linenumber = Number(key); - var className = value.reduce(function (acc, x) { - if (x.optType === "Missed" || acc === "Missed") { - return "Missed"; - } else if (x.optType === "Passed" || acc === "Passed") { - return "Passed"; - } - return x.optType; - }, ""); - var contents = _.map(value, this.getDisplayableOpt, this); - opt.push({ - range: new monaco.Range(linenumber, 1, linenumber, Infinity), - options: { - isWholeLine: true, - glyphMarginClassName: "opt-decoration." + className.toLowerCase(), - hoverMessage: contents, - glyphMarginHoverMessage: contents - } - }); +Opt.prototype.getDisplayableOpt = function (optResult) { + return "**" + optResult.optType + "** - " + optResult.displayString; +}; + +Opt.prototype.updateState = function () { +}; + +Opt.prototype.close = function () { + this.eventHub.unsubscribe(); + this.eventHub.emit("optViewClosed", this._compilerid); + this.optEditor.dispose(); +}; + +Opt.prototype.onCompilerClose = function (id) { + if (id === this._compilerid) { + // We can't immediately close as an outer loop somewhere in GoldenLayout is iterating over + // the hierarchy. We can't modify while it's being iterated over. + this.close(); + _.defer(function (self) { + self.container.close(); }, this); + } +}; - this._currentDecorations = this.optEditor.deltaDecorations(this._currentDecorations, opt); - }; - - Opt.prototype.onCompiler = function (id, compiler, options, editorid) { - if (id === this._compilerid) { - this._compilerName = compiler ? compiler.name : ''; - this.setTitle(); - if (compiler && !compiler.supportsOptOutput) { - this.code = this.optEditor.getValue(); - this.optEditor.setValue("<" + compiler.version + " does not support the optimisation view>"); - return; - } - this._editorid = editorid; - this.optEditor.setValue(this.code); +Opt.prototype.onSettingsChange = function (newSettings) { + this.optEditor.updateOptions({ + minimap: { + enabled: newSettings.showMinimap } - }; - Opt.prototype.onCompilerClose = function (id) { - if (id === this._compilerid) { - // We can't immediately close as an outer loop somewhere in GoldenLayout is iterating over - // the hierarchy. We can't modify while it's being iterated over. - this.close(); - _.defer(function (self) { - self.container.close(); - }, this); - } - }; + }); +}; - Opt.prototype.updateState = function () { - }; - - Opt.prototype.onSettingsChange = function (newSettings) { - this.optEditor.updateOptions({ - minimap: { - enabled: newSettings.showMinimap - } - }); - }; - - Opt.prototype.close = function () { - this.eventHub.unsubscribe(); - this.eventHub.emit("optViewClosed", this._compilerid); - this.optEditor.dispose(); - }; - - return { - Opt: Opt - }; -}); +module.exports = { + Opt: Opt +}; diff --git a/static/options.js b/static/options.js index 74154d5c2..b26716b81 100644 --- a/static/options.js +++ b/static/options.js @@ -23,8 +23,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -define(function (require) { "use strict"; - return window.compilerExplorerOptions; -}); + module.exports = window.compilerExplorerOptions; + diff --git a/static/output.js b/static/output.js index d00ce8972..10c291caf 100644 --- a/static/output.js +++ b/static/output.js @@ -23,129 +23,126 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -define(function (require) { - "use strict"; +"use strict"; - var _ = require('underscore'); - var $ = require('jquery'); - var FontScale = require('fontscale'); - var AnsiToHtml = require('ansi-to-html'); +var _ = require('underscore'); +var $ = require('jquery'); +var FontScale = require('fontscale'); +var AnsiToHtml = require('ansi-to-html'); - function makeAnsiToHtml(color) { - return new AnsiToHtml({ - fg: color ? color : '#333', - bg: '#f5f5f5', - stream: true, - escapeXML: true - }); - } +function makeAnsiToHtml(color) { + return new AnsiToHtml({ + fg: color ? color : '#333', + bg: '#f5f5f5', + stream: true, + escapeXML: true + }); +} - function Output(hub, container, state) { - this.container = container; - this.compilerId = state.compiler; - this.editorId = state.editor; - this.eventHub = hub.createEventHub(); - this.domRoot = container.getElement(); - this.domRoot.html($('#compiler-output').html()); - this.contentRoot = this.domRoot.find(".content"); - this.compilerName = ""; - this.fontScale = new FontScale(this.domRoot, state, "pre"); +function Output(hub, container, state) { + this.container = container; + this.compilerId = state.compiler; + this.editorId = state.editor; + this.eventHub = hub.createEventHub(); + this.domRoot = container.getElement(); + this.domRoot.html($('#compiler-output').html()); + this.contentRoot = this.domRoot.find(".content"); + this.compilerName = ""; + this.fontScale = new FontScale(this.domRoot, state, "pre"); - this.container.on('destroy', this.close, this); + this.container.on('destroy', this.close, this); + + this.eventHub.on('compileResult', this.onCompileResult, this); + this.eventHub.on('compilerFontScale', this.onFontScale, this); + this.eventHub.on('compilerClose', this.onCompilerClose, this); + this.eventHub.emit('resendCompilation', this.compilerId); + + this.updateCompilerName(); +} - this.eventHub.on('compileResult', this.onCompileResult, this); - this.eventHub.on('compilerFontScale', this.onFontScale, this); - this.eventHub.on('compilerClose', this.onCompilerClose, this); - this.eventHub.emit('resendCompilation', this.compilerId); +Output.prototype.onCompileResult = function (id, compiler, result) { + if (id !== this.compilerId) return; + if (compiler) this.compilerName = compiler.name; - this.updateCompilerName(); - } + this.contentRoot.empty(); - Output.prototype.onCompileResult = function (id, compiler, result) { - if (id !== this.compilerId) return; - if (compiler) this.compilerName = compiler.name; + var ansiToHtml = makeAnsiToHtml(); - this.contentRoot.empty(); + _.each((result.stdout || []).concat(result.stderr || []), function (obj) { + this.add(ansiToHtml.toHtml(obj.text), obj.tag ? obj.tag.line : obj.line); + }, this); - var ansiToHtml = makeAnsiToHtml(); + if (!result.execResult) { + this.add("Compiler returned: " + result.code); + } else { + this.add("Program returned: " + result.execResult.code); + if (result.execResult.stderr.length || result.execResult.stdout.length) { + ansiToHtml = makeAnsiToHtml("red"); + _.each(result.execResult.stderr, function (obj) { + this.programOutput(ansiToHtml.toHtml(obj.text), "red"); + }, this); - _.each((result.stdout || []).concat(result.stderr || []), function (obj) { - this.add(ansiToHtml.toHtml(obj.text), obj.tag ? obj.tag.line : obj.line); - }, this); - - if (!result.execResult) { - this.add("Compiler returned: " + result.code); - } else { - this.add("Program returned: " + result.execResult.code); - if (result.execResult.stderr.length || result.execResult.stdout.length) { - ansiToHtml = makeAnsiToHtml("red"); - _.each(result.execResult.stderr, function (obj) { - this.programOutput(ansiToHtml.toHtml(obj.text), "red"); - }, this); - - ansiToHtml = makeAnsiToHtml(); - _.each(result.execResult.stdout, function (obj) { - this.programOutput(ansiToHtml.toHtml(obj.text)); - }, this); - } - } - - this.updateCompilerName(); - }; - - Output.prototype.onFontScale = function (id, scale) { - if (id === this.compilerId) this.fontScale.setScale(scale); - }; - - Output.prototype.programOutput = function (msg, color) { - var elem = $('
      ').appendTo(this.contentRoot) - .html(msg) - .css('font-family', '"Courier New", Courier, monospace'); - if (color) - elem.css("color", color); - }; - - Output.prototype.add = function (msg, lineNum) { - var elem = $('
      ').appendTo(this.contentRoot); - if (lineNum) { - elem.html($('').prop('href', '#').html(msg)) - .click(_.bind(function (e) { - this.eventHub.emit('editorSetDecoration', this.editorId, lineNum, true); - // do not bring user to the top of index.html - // http://stackoverflow.com/questions/3252730 - e.preventDefault(); - return false; - }, this)) - .on('mouseover', _.bind(function () { - this.eventHub.emit('editorSetDecoration', this.editorId, lineNum, false); - }, this)); - } else { - elem.html(msg); - } - }; - - Output.prototype.updateCompilerName = function () { - var name = "#" + this.compilerId; - if (this.compilerName) name += " with " + this.compilerName; - this.container.setTitle(name); - }; - - Output.prototype.onCompilerClose = function (id) { - if (id === this.compilerId) { - // We can't immediately close as an outer loop somewhere in GoldenLayout is iterating over - // the hierarchy. We can't modify while it's being iterated over. - this.close(); - _.defer(function (self) { - self.container.close(); + ansiToHtml = makeAnsiToHtml(); + _.each(result.execResult.stdout, function (obj) { + this.programOutput(ansiToHtml.toHtml(obj.text)); }, this); } - }; + } - Output.prototype.close = function () { - this.eventHub.unsubscribe(); - }; + this.updateCompilerName(); +}; - return { - Output: Output - }; -}); +Output.prototype.onFontScale = function (id, scale) { + if (id === this.compilerId) this.fontScale.setScale(scale); +}; + +Output.prototype.programOutput = function (msg, color) { + var elem = $('
      ').appendTo(this.contentRoot) + .html(msg) + .css('font-family', '"Courier New", Courier, monospace'); + if (color) + elem.css("color", color); +}; + +Output.prototype.add = function (msg, lineNum) { + var elem = $('
      ').appendTo(this.contentRoot); + if (lineNum) { + elem.html($('').prop('href', '#').html(msg)) + .click(_.bind(function (e) { + this.eventHub.emit('editorSetDecoration', this.editorId, lineNum, true); + // do not bring user to the top of index.html + // http://stackoverflow.com/questions/3252730 + e.preventDefault(); + return false; + }, this)) + .on('mouseover', _.bind(function () { + this.eventHub.emit('editorSetDecoration', this.editorId, lineNum, false); + }, this)); + } else { + elem.html(msg); + } +}; + +Output.prototype.updateCompilerName = function () { + var name = "#" + this.compilerId; + if (this.compilerName) name += " with " + this.compilerName; + this.container.setTitle(name); +}; + +Output.prototype.onCompilerClose = function (id) { + if (id === this.compilerId) { + // We can't immediately close as an outer loop somewhere in GoldenLayout is iterating over + // the hierarchy. We can't modify while it's being iterated over. + _.defer(function (self) { + self.container.close(); + }, this); + } +}; + +Output.prototype.close = function () { + this.eventHub.unsubscribe(); +}; + +module.exports = { + Output: Output +}; diff --git a/static/rust-mode.js b/static/rust-mode.js index 0631b5ee2..5122ba3ae 100644 --- a/static/rust-mode.js +++ b/static/rust-mode.js @@ -22,118 +22,116 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -define(function (require) { - "use strict"; - var monaco = require('monaco'); - function definition() { - return { - defaultToken: 'invalid', +"use strict"; - keywords: [ - 'abstract', 'alignof', 'as', 'become', 'box', - 'break', 'const', 'continue', 'crate', 'do', - 'else', 'enum', 'extern', 'false', 'final', - 'fn', 'for', 'if', 'impl', 'in', - 'let', 'loop', 'macro', 'match', 'mod', - 'move', 'mut', 'offsetof', 'override', 'priv', - 'proc', 'pub', 'pure', 'ref', 'return', - 'Self', 'self', 'sizeof', 'static', 'struct', - 'super', 'trait', 'true', 'type', 'typeof', - 'unsafe', 'unsized', 'use', 'virtual', 'where', - 'while', 'yield' +function definition() { + return { + defaultToken: 'invalid', + + keywords: [ + 'abstract', 'alignof', 'as', 'become', 'box', + 'break', 'const', 'continue', 'crate', 'do', + 'else', 'enum', 'extern', 'false', 'final', + 'fn', 'for', 'if', 'impl', 'in', + 'let', 'loop', 'macro', 'match', 'mod', + 'move', 'mut', 'offsetof', 'override', 'priv', + 'proc', 'pub', 'pure', 'ref', 'return', + 'Self', 'self', 'sizeof', 'static', 'struct', + 'super', 'trait', 'true', 'type', 'typeof', + 'unsafe', 'unsized', 'use', 'virtual', 'where', + 'while', 'yield' + ], + + typeKeywords: [ + 'array', 'bool', 'char', 'f32', 'f64', 'i16', 'i32', 'i64', 'i8', + 'isize', 'pointer', 'slice', 'str', 'tuple', 'u16', 'u32', 'u64', 'u8', + 'usize' + ], + + operators: [ + '=', '>', '<', '!', '~', '?', ':', + '==', '<=', '>=', '!=', '&&', '||', '++', '--', + '+', '-', '*', '/', '&', '|', '^', '%', '<<', + '>>', '>>>', '+=', '-=', '*=', '/=', '&=', '|=', + '^=', '%=', '<<=', '>>=', '>>>=' + ], + + symbols: /[=>](?!@symbols)/, '@brackets'], + [/@symbols/, { + cases: { + '@operators': 'operator', + '@default': '' + } + }], + + [/#!\[[^]*\]/, 'annotation'], + [/#!.*$/, 'annotation.invalid'], + + // numbers + [/\d*\.\d+([eE][\-+]?\d+)?[fFdD]?/, 'number.float'], + [/0[xX][0-9a-fA-F_]*[0-9a-fA-F][Ll]?/, 'number.hex'], + [/0[0-7_]*[0-7][Ll]?/, 'number.octal'], + [/0[bB][0-1_]*[0-1][Ll]?/, 'number.binary'], + [/\d+[lL]?/, 'number'], + + // delimiter: after number because of .\d floats + [/[;,.]/, 'delimiter'], + + // strings + [/"([^"\\]|\\.)*$/, 'string.invalid'], // non-teminated string + [/"/, 'string', '@string'], + + // characters + [/'[^\\']'/, 'string'], + [/(')(@escapes)(')/, ['string', 'string.escape', 'string']], + [/'/, 'string.invalid'] ], - typeKeywords: [ - 'array', 'bool', 'char', 'f32', 'f64', 'i16', 'i32', 'i64', 'i8', - 'isize', 'pointer', 'slice', 'str', 'tuple', 'u16', 'u32', 'u64', 'u8', - 'usize' + whitespace: [ + [/[ \t\r\n]+/, 'white'], + [/\/\*/, 'comment', '@comment'], + [/\/\/.*$/, 'comment'], ], - operators: [ - '=', '>', '<', '!', '~', '?', ':', - '==', '<=', '>=', '!=', '&&', '||', '++', '--', - '+', '-', '*', '/', '&', '|', '^', '%', '<<', - '>>', '>>>', '+=', '-=', '*=', '/=', '&=', '|=', - '^=', '%=', '<<=', '>>=', '>>>=' + comment: [ + [/[^\/*]+/, 'comment'], + [/\/\*/, 'comment', '@push'], + [/\/\*/, 'comment.invalid'], + ["\\*/", 'comment', '@pop'], + [/[\/*]/, 'comment'] ], - symbols: /[=>](?!@symbols)/, '@brackets'], - [/@symbols/, { - cases: { - '@operators': 'operator', - '@default': '' - } - }], - - [/#!\[[^]*\]/, 'annotation'], - [/#!.*$/, 'annotation.invalid'], - - // numbers - [/\d*\.\d+([eE][\-+]?\d+)?[fFdD]?/, 'number.float'], - [/0[xX][0-9a-fA-F_]*[0-9a-fA-F][Ll]?/, 'number.hex'], - [/0[0-7_]*[0-7][Ll]?/, 'number.octal'], - [/0[bB][0-1_]*[0-1][Ll]?/, 'number.binary'], - [/\d+[lL]?/, 'number'], - - // delimiter: after number because of .\d floats - [/[;,.]/, 'delimiter'], - - // strings - [/"([^"\\]|\\.)*$/, 'string.invalid'], // non-teminated string - [/"/, 'string', '@string'], - - // characters - [/'[^\\']'/, 'string'], - [/(')(@escapes)(')/, ['string', 'string.escape', 'string']], - [/'/, 'string.invalid'] - ], - - whitespace: [ - [/[ \t\r\n]+/, 'white'], - [/\/\*/, 'comment', '@comment'], - [/\/\/.*$/, 'comment'], - ], - - comment: [ - [/[^\/*]+/, 'comment'], - [/\/\*/, 'comment', '@push'], - [/\/\*/, 'comment.invalid'], - ["\\*/", 'comment', '@pop'], - [/[\/*]/, 'comment'] - ], - - string: [ - [/[^\\"]+/, 'string'], - [/@escapes/, 'string.escape'], - [/\\./, 'string.escape.invalid'], - [/"/, 'string', '@pop'] - ], - }, - }; - } - - monaco.languages.register({id: 'rust'}); - monaco.languages.setMonarchTokensProvider('rust', definition()); -}); \ No newline at end of file +monaco.languages.register({id: 'rust'}); +monaco.languages.setMonarchTokensProvider('rust', definition()); diff --git a/static/settings.js b/static/settings.js index bf5080c31..8763e7bd8 100644 --- a/static/settings.js +++ b/static/settings.js @@ -23,190 +23,188 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -define(function (require) { - "use strict"; - var $ = require('jquery'); - var _ = require('underscore'); - var colour = require('./colour'); - var themes = require('./themes').themes; - var options = require('./options'); +"use strict"; +var $ = require('jquery'); +var _ = require('underscore'); +var colour = require('./colour'); +var themes = require('./themes').themes; +var options = require('./options'); - function Setting(elem, name, Control, param) { - this.elem = elem; - this.name = name; - this.control = new Control(elem, param); +function Setting(elem, name, Control, param) { + this.elem = elem; + this.name = name; + this.control = new Control(elem, param); +} + +Setting.prototype.getUi = function () { + return this.control.getUi(this.elem); +}; +Setting.prototype.putUi = function (value) { + this.control.putUi(this.elem, value); +}; + +function Checkbox() { +} + +Checkbox.prototype.getUi = function (elem) { + return !!elem.prop('checked'); +}; +Checkbox.prototype.putUi = function (elem, value) { + elem.prop('checked', !!value); +}; + +function Select(elem, populate) { + elem.empty(); + _.each(populate, function (e) { + elem.append($('")); + }); +} + +Select.prototype.getUi = function (elem) { + return elem.val(); +}; +Select.prototype.putUi = function (elem, value) { + elem.val(value); +}; + +function Slider(elem, sliderSettings) { + elem.slider(sliderSettings); +} + +Slider.prototype.getUi = function (elem) { + return elem.slider('getValue'); +}; + +Slider.prototype.putUi = function (elem, value) { + elem.slider('setValue', value); +}; + +function setupSettings(root, settings, onChange, langId) { + settings = settings || {}; + + var settingsObjs = []; + + function onUiChange() { + var settings = {}; + _.each(settingsObjs, function (s) { + settings[s.name] = s.getUi(); + }); + onChange(settings); } - Setting.prototype.getUi = function () { - return this.control.getUi(this.elem); - }; - Setting.prototype.putUi = function (value) { - this.control.putUi(this.elem, value); - }; - - function Checkbox() { - } - - Checkbox.prototype.getUi = function (elem) { - return !!elem.prop('checked'); - }; - Checkbox.prototype.putUi = function (elem, value) { - elem.prop('checked', !!value); - }; - - function Select(elem, populate) { - elem.empty(); - _.each(populate, function (e) { - elem.append($('")); + function onSettingsChange(settings) { + _.each(settingsObjs, function (s) { + s.putUi(settings[s.name]); }); } - Select.prototype.getUi = function (elem) { - return elem.val(); - }; - Select.prototype.putUi = function (elem, value) { - elem.val(value); - }; - - function Slider(elem, sliderSettings) { - elem.slider(sliderSettings); + function add(elem, key, defaultValue, Type, param) { + if (settings[key] === undefined) + settings[key] = defaultValue; + settingsObjs.push(new Setting(elem, key, Type, param)); + elem.change(onUiChange); } - Slider.prototype.getUi = function (elem) { - return elem.slider('getValue'); - }; - - Slider.prototype.putUi = function (elem, value) { - elem.slider('setValue', value); - }; - - function setupSettings(root, settings, onChange, langId) { - settings = settings || {}; - - var settingsObjs = []; - - function onUiChange() { - var settings = {}; - _.each(settingsObjs, function (s) { - settings[s.name] = s.getUi(); - }); - onChange(settings); + add(root.find('.colourise'), 'colouriseAsm', true, Checkbox); + add(root.find('.autoCloseBrackets'), 'autoCloseBrackets', true, Checkbox); + var colourSchemeSelect = root.find('.colourScheme'); + add(colourSchemeSelect, 'colourScheme', colour.schemes[0].name, Select, + _.map(colour.schemes, function (scheme) { + return {label: scheme.name, desc: scheme.desc}; + }) + ); + // Handle older settings + if (settings.delayAfterChange === 0) { + settings.delayAfterChange = 750; + settings.compileOnChange = false; + } + add(root.find('.compileOnChange'), 'compileOnChange', true, Checkbox); + add(root.find('.delay'), 'delayAfterChange', 750, Slider, { + max: 3000, + step: 250, + min: 250, + formatter: function (x) { + return (x / 1000.0).toFixed(2) + "s"; } + }); + add(root.find('.hoverShowSource'), 'hoverShowSource', true, Checkbox); + add(root.find('.hoverShowAsmDoc'), 'hoverShowAsmDoc', true, Checkbox); + var themeSelect = root.find('.theme'); + add(themeSelect, 'theme', themes.default.id, Select, + _.map(themes, function (theme) { + return {label: theme.id, desc: theme.name}; + }) + ); + add(root.find('.showQuickSuggestions'), 'showQuickSuggestions', false, Checkbox); + add(root.find('.useCustomContextMenu'), 'useCustomContextMenu', true, Checkbox); + add(root.find('.showMinimap'), 'showMinimap', true, Checkbox); - function onSettingsChange(settings) { - _.each(settingsObjs, function (s) { - s.putUi(settings[s.name]); - }); - } - - function add(elem, key, defaultValue, Type, param) { - if (settings[key] === undefined) - settings[key] = defaultValue; - settingsObjs.push(new Setting(elem, key, Type, param)); - elem.change(onUiChange); - } - - add(root.find('.colourise'), 'colouriseAsm', true, Checkbox); - add(root.find('.autoCloseBrackets'), 'autoCloseBrackets', true, Checkbox); - var colourSchemeSelect = root.find('.colourScheme'); - add(colourSchemeSelect, 'colourScheme', colour.schemes[0].name, Select, - _.map(colour.schemes, function (scheme) { - return {label: scheme.name, desc: scheme.desc}; - }) - ); - // Handle older settings - if (settings.delayAfterChange === 0) { - settings.delayAfterChange = 750; - settings.compileOnChange = false; - } - add(root.find('.compileOnChange'), 'compileOnChange', true, Checkbox); - add(root.find('.delay'), 'delayAfterChange', 750, Slider, { - max: 3000, - step: 250, - min: 250, - formatter: function (x) { - return (x / 1000.0).toFixed(2) + "s"; - } - }); - add(root.find('.hoverShowSource'), 'hoverShowSource', true, Checkbox); - add(root.find('.hoverShowAsmDoc'), 'hoverShowAsmDoc', true, Checkbox); - var themeSelect = root.find('.theme'); - add(themeSelect, 'theme', themes.default.id, Select, - _.map(themes, function (theme) { - return {label: theme.id, desc: theme.name}; - }) - ); - add(root.find('.showQuickSuggestions'), 'showQuickSuggestions', false, Checkbox); - add(root.find('.useCustomContextMenu'), 'useCustomContextMenu', true, Checkbox); - add(root.find('.showMinimap'), 'showMinimap', true, Checkbox); - - function handleThemes() { - var newTheme = themeSelect.val(); - // Store the scheme of the old theme - $.data(themeSelect, 'theme-' + $.data(themeSelect, 'last-theme'), colourSchemeSelect.val()); - // Get the scheme of the new theme - var newThemeStoredScheme = $.data(themeSelect, 'theme-' + newTheme); - var isStoredUsable = false; - colourSchemeSelect.empty(); - _.each(colour.schemes, function (scheme) { - if (!scheme.themes || scheme.themes.length === 0 || scheme.themes.indexOf(newTheme) !== -1 || scheme.themes.indexOf('all') !== -1) { - colourSchemeSelect.append($('")); - if (newThemeStoredScheme === scheme.name) { - isStoredUsable = true; - } + function handleThemes() { + var newTheme = themeSelect.val(); + // Store the scheme of the old theme + $.data(themeSelect, 'theme-' + $.data(themeSelect, 'last-theme'), colourSchemeSelect.val()); + // Get the scheme of the new theme + var newThemeStoredScheme = $.data(themeSelect, 'theme-' + newTheme); + var isStoredUsable = false; + colourSchemeSelect.empty(); + _.each(colour.schemes, function (scheme) { + if (!scheme.themes || scheme.themes.length === 0 || scheme.themes.indexOf(newTheme) !== -1 || scheme.themes.indexOf('all') !== -1) { + colourSchemeSelect.append($('")); + if (newThemeStoredScheme === scheme.name) { + isStoredUsable = true; } - }); - if (colourSchemeSelect.children().length >= 1) { - colourSchemeSelect.val(isStoredUsable ? newThemeStoredScheme : colourSchemeSelect.first().val()); - } else { - // This should never happen. In case it does, lets use the default one - colourSchemeSelect.append($('")); - colourSchemeSelect.val(colourSchemeSelect.first().val()); } - colourSchemeSelect.trigger('change'); - } - - var langs = options.languages; - - var defaultLanguageSelector = root.find('.defaultLanguage'); - var defLang = settings.defaultLanguage || _.keys(langs)[0] || 'c++'; - add(defaultLanguageSelector, 'defaultLanguage', defLang, Select, - _.map(langs, function (lang) { - return {label: lang.id, desc: lang.name}; - }) - ); - - defaultLanguageSelector.val(defLang); - if (langId) { - defaultLanguageSelector - .prop('disabled', true) - .prop('title', 'Default language inherited from subdomain') - .css('cursor', 'not-allowed'); - } - - add(root.find('.newEditorLastLang'), 'newEditorLastLang', true, Checkbox); - - function setSettings(settings) { - onSettingsChange(settings); - onChange(settings); - } - - add(root.find('.tabWidth'), 'tabWidth', 4, Select, - _.map([2, 4, 8], function (size) { - return {label: size, desc: size}; - }) - ); - - - setSettings(settings); - handleThemes(); - themeSelect.change(function () { - handleThemes(); - $.data(themeSelect, 'last-theme', themeSelect.val()); }); - $.data(themeSelect, 'last-theme', themeSelect.val()); - return setSettings; + if (colourSchemeSelect.children().length >= 1) { + colourSchemeSelect.val(isStoredUsable ? newThemeStoredScheme : colourSchemeSelect.first().val()); + } else { + // This should never happen. In case it does, lets use the default one + colourSchemeSelect.append($('")); + colourSchemeSelect.val(colourSchemeSelect.first().val()); + } + colourSchemeSelect.trigger('change'); } - return setupSettings; -}); + var langs = options.languages; + + var defaultLanguageSelector = root.find('.defaultLanguage'); + var defLang = settings.defaultLanguage || _.keys(langs)[0] || 'c++'; + add(defaultLanguageSelector, 'defaultLanguage', defLang, Select, + _.map(langs, function (lang) { + return {label: lang.id, desc: lang.name}; + }) + ); + + defaultLanguageSelector.val(defLang); + if (langId) { + defaultLanguageSelector + .prop('disabled', true) + .prop('title', 'Default language inherited from subdomain') + .css('cursor', 'not-allowed'); + } + + add(root.find('.newEditorLastLang'), 'newEditorLastLang', true, Checkbox); + + function setSettings(settings) { + onSettingsChange(settings); + onChange(settings); + } + + add(root.find('.tabWidth'), 'tabWidth', 4, Select, + _.map([2, 4, 8], function (size) { + return {label: size, desc: size}; + }) + ); + + + setSettings(settings); + handleThemes(); + themeSelect.change(function () { + handleThemes(); + $.data(themeSelect, 'last-theme', themeSelect.val()); + }); + $.data(themeSelect, 'last-theme', themeSelect.val()); + return setSettings; +} + +module.exports = setupSettings; diff --git a/static/sharing.js b/static/sharing.js index 598ee2d41..e745d060f 100644 --- a/static/sharing.js +++ b/static/sharing.js @@ -23,14 +23,13 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -define(function (require) { "use strict"; var $ = require('jquery'); var _ = require('underscore'); var options = require('options'); var shortenURL = require('urlshorten-google'); var Components = require('components'); - var url = require('url'); + var url = require('./url'); function configFromEmbedded(embeddedUrl) { // Old-style link? @@ -141,8 +140,7 @@ define(function (require) { } } - return { + module.exports = { initShareButton: initShareButton, configFromEmbedded: configFromEmbedded }; -}); diff --git a/static/themes.js b/static/themes.js index 4d340c266..56ed8c66c 100644 --- a/static/themes.js +++ b/static/themes.js @@ -23,57 +23,54 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -define(function (require) { - "use strict"; - var $ = require('jquery'); - var _ = require('underscore'); - var monaco = require('monaco'); - var themes = { - default: { - path: "./themes/explorer-default.css", - id: "default", - name: "Default", - monaco: "vs" // Optional field - }, - dark: { - path: "./themes/dark/theme-dark.css", - id: "dark", - name: "Dark", - monaco: "vs-dark" - } - }; +"use strict"; +var $ = require('jquery'); +var _ = require('underscore'); - function Themer(eventHub, initialSettings) { - this.currentTheme = null; - this.eventHub = eventHub; - - this.setTheme = function (theme) { - if (this.currentTheme === theme) return; - $.get(require.toUrl(theme.path), _.bind(function (cssData) { - $('#theme').html(cssData); - monaco.editor.setTheme(theme.monaco); - this.eventHub.emit('resize'); - }, this)); - this.currentTheme = theme; - }; - - this.onSettingsChange = function (newSettings) { - var newTheme = themes[newSettings.theme] || themes.default; - if (!newTheme.monaco) - newTheme.monaco = "vs"; - this.setTheme(newTheme); - }; - this.onSettingsChange(initialSettings); - - this.eventHub.on('settingsChange', this.onSettingsChange, this); - - this.eventHub.on('requestTheme', function () { - this.eventHub.emit('themeChange', this.currentTheme); - }, this); +var themes = { + default: { + path: "default", + id: "default", + name: "Default", + monaco: "vs" // Optional field + }, + dark: { + path: "dark", + id: "dark", + name: "Dark", + monaco: "vs-dark" } +}; - return { - themes: themes, - Themer: Themer +function Themer(eventHub, initialSettings) { + this.currentTheme = null; + this.eventHub = eventHub; + + this.setTheme = function (theme) { + if (this.currentTheme === theme) return; + var cssData = require('./themes/' + theme.path + "-theme.css"); + $('#theme').html(cssData.toString()); + monaco.editor.setTheme(theme.monaco); + this.eventHub.emit('resize'); + this.currentTheme = theme; }; -}); + + this.onSettingsChange = function (newSettings) { + var newTheme = themes[newSettings.theme] || themes.default; + if (!newTheme.monaco) + newTheme.monaco = "vs"; + this.setTheme(newTheme); + }; + this.onSettingsChange(initialSettings); + + this.eventHub.on('settingsChange', this.onSettingsChange, this); + + this.eventHub.on('requestTheme', function () { + this.eventHub.emit('themeChange', this.currentTheme); + }, this); +} + +module.exports = { + themes: themes, + Themer: Themer +}; diff --git a/static/themes/contrast/theme-contrast.css b/static/themes/contrast-theme.css similarity index 96% rename from static/themes/contrast/theme-contrast.css rename to static/themes/contrast-theme.css index 9cc9c14a2..1294cf97b 100644 --- a/static/themes/contrast/theme-contrast.css +++ b/static/themes/contrast-theme.css @@ -1,4 +1,4 @@ -@import url("../../ext/golden-layout/src/css/goldenlayout-dark-theme.css"); +@import url("~golden-layout/src/css/goldenlayout-dark-theme.css"); .navbar-inverse { background-color: #000; diff --git a/static/themes/dark/theme-dark.css b/static/themes/dark-theme.css similarity index 98% rename from static/themes/dark/theme-dark.css rename to static/themes/dark-theme.css index 47eeca5fc..d1ccee8ab 100644 --- a/static/themes/dark/theme-dark.css +++ b/static/themes/dark-theme.css @@ -1,4 +1,4 @@ -@import url("../../ext/golden-layout/src/css/goldenlayout-dark-theme.css"); +@import url("~golden-layout/src/css/goldenlayout-dark-theme.css"); body { background-color: #333 !important; diff --git a/static/themes/explorer-default.css b/static/themes/default-theme.css similarity index 94% rename from static/themes/explorer-default.css rename to static/themes/default-theme.css index 37e13a84b..482ea8617 100644 --- a/static/themes/explorer-default.css +++ b/static/themes/default-theme.css @@ -1,4 +1,4 @@ -@import url("../ext/golden-layout/src/css/goldenlayout-light-theme.css"); +@import url("~golden-layout/src/css/goldenlayout-light-theme.css"); .navbar-inverse { background-color: #226; diff --git a/static/toggles.js b/static/toggles.js index b288ea1a2..59b491ed2 100644 --- a/static/toggles.js +++ b/static/toggles.js @@ -23,7 +23,6 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -define(function (require) { "use strict"; var _ = require('underscore'); var $ = require('jquery'); @@ -77,5 +76,4 @@ define(function (require) { }.bind(this)); }; - return Toggles; -}); + module.exports = Toggles; diff --git a/static/url.js b/static/url.js index 271dd01ca..e514b2cbf 100644 --- a/static/url.js +++ b/static/url.js @@ -22,105 +22,102 @@ // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. +"use strict"; +var GoldenLayout = require('goldenlayout'); +var rison = require('rison'); +var $ = require('jquery'); +var Components = require('components'); +var lzstring = require('lzstring'); +var _ = require('underscore'); -define(function (require) { - "use strict"; - var GoldenLayout = require('goldenlayout'); - var rison = require('rison'); - var $ = require('jquery'); - var Components = require('components'); - var lzstring = require('lzstring'); - var _ = require('underscore'); +function convertOldState(state) { + var sc = state.compilers[0]; + if (!sc) throw new Error("Unable to determine compiler from old state"); + var content = []; + var source; + if (sc.sourcez) { + source = lzstring.decompressFromBase64(sc.sourcez); + } else { + source = sc.source; + } + var options = {compileOnChange: true, colouriseAsm: state.filterAsm.colouriseAsm}; + var filters = _.clone(state.filterAsm); + delete filters.colouriseAsm; + content.push(Components.getEditorWith(1, source, options)); + content.push(Components.getCompilerWith(1, filters, sc.options, sc.compiler)); + return {version: 4, content: [{type: 'row', content: content}]}; +} - function convertOldState(state) { - var sc = state.compilers[0]; - if (!sc) throw new Error("Unable to determine compiler from old state"); - var content = []; - var source; - if (sc.sourcez) { - source = lzstring.decompressFromBase64(sc.sourcez); - } else { - source = sc.source; +function loadState(state) { + if (!state || state.version === undefined) return false; + switch (state.version) { + case 1: + state.filterAsm = {}; + state.version = 2; + /* falls through */ + case 2: + state.compilers = [state]; + state.version = 3; + /* falls through */ + case 3: + state = convertOldState(state); + break; // no fall through + case 4: + state = GoldenLayout.unminifyConfig(state); + break; + default: + throw new Error("Invalid version '" + state.version + "'"); + } + return state; +} + +function risonify(obj) { + return rison.quote(rison.encode_object(obj)); +} + +function unrisonify(text) { + return rison.decode_object(decodeURIComponent(text.replace(/\+/g, '%20'))); +} + +function deserialiseState(stateText) { + var state; + var exception; + try { + state = unrisonify(stateText); + if (state && state.z) { + state = unrisonify(lzstring.decompressFromBase64(state.z)); } - var options = {compileOnChange: true, colouriseAsm: state.filterAsm.colouriseAsm}; - var filters = _.clone(state.filterAsm); - delete filters.colouriseAsm; - content.push(Components.getEditorWith(1, source, options)); - content.push(Components.getCompilerWith(1, filters, sc.options, sc.compiler)); - return {version: 4, content: [{type: 'row', content: content}]}; + } catch (ex) { + exception = ex; } - function loadState(state) { - if (!state || state.version === undefined) return false; - switch (state.version) { - case 1: - state.filterAsm = {}; - state.version = 2; - /* falls through */ - case 2: - state.compilers = [state]; - state.version = 3; - /* falls through */ - case 3: - state = convertOldState(state); - break; // no fall through - case 4: - state = GoldenLayout.unminifyConfig(state); - break; - default: - throw new Error("Invalid version '" + state.version + "'"); - } - return state; - } - - function risonify(obj) { - return rison.quote(rison.encode_object(obj)); - } - - function unrisonify(text) { - return rison.decode_object(decodeURIComponent(text.replace(/\+/g, '%20'))); - } - - function deserialiseState(stateText) { - var state; - var exception; + if (!state) { try { - state = unrisonify(stateText); - if (state && state.z) { - state = unrisonify(lzstring.decompressFromBase64(state.z)); - } + state = $.parseJSON(decodeURIComponent(stateText)); } catch (ex) { - exception = ex; - } - - if (!state) { - try { - state = $.parseJSON(decodeURIComponent(stateText)); - } catch (ex) { - if (!exception) exception = ex; - } - } - if (!state && exception) throw exception; - return loadState(state); - } - - function serialiseState(stateText) { - var ctx = GoldenLayout.minifyConfig({content: stateText.content}); - ctx.version = 4; - var uncompressed = risonify(ctx); - var compressed = risonify({z: lzstring.compressToBase64(uncompressed)}); - var MinimalSavings = 0.20; // at least this ratio smaller - if (compressed.length < uncompressed.length * (1.0 - MinimalSavings)) { - return compressed; - } else { - return uncompressed; + if (!exception) exception = ex; } } + if (!state && exception) throw exception; + return loadState(state); +} - return { - deserialiseState: deserialiseState, - serialiseState: serialiseState, - unrisonify: unrisonify, - risonify: risonify - }; -}); +function serialiseState(stateText) { + var ctx = GoldenLayout.minifyConfig({content: stateText.content}); + ctx.version = 4; + var uncompressed = risonify(ctx); + var compressed = risonify({z: lzstring.compressToBase64(uncompressed)}); + var MinimalSavings = 0.20; // at least this ratio smaller + if (compressed.length < uncompressed.length * (1.0 - MinimalSavings)) { + return compressed; + } else { + return uncompressed; + } +} + +module.exports = { + deserialiseState: deserialiseState, + serialiseState: serialiseState, + unrisonify: unrisonify, + risonify: risonify +}; diff --git a/static/urlshorten-google.js b/static/urlshorten-google.js index 7f5cfbbb7..b72023615 100644 --- a/static/urlshorten-google.js +++ b/static/urlshorten-google.js @@ -23,45 +23,43 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -define(function (require) { - "use strict"; - var options = require('options'); - var Alert = require('alert'); - var $ = require('jquery'); +"use strict"; +var options = require('options'); +var Alert = require('alert'); +var $ = require('jquery'); - function googleJSClientLoaded() { - var gapi = window.gapi; - gapi.client.setApiKey(options.gapiKey); - gapi.client.load('urlshortener', 'v1', googleJSClientLoaded.done); +function googleJSClientLoaded() { + var gapi = window.gapi; + gapi.client.setApiKey(options.gapiKey); + gapi.client.load('urlshortener', 'v1', googleJSClientLoaded.done); +} + +function shortenURL(url, done) { + var gapi = window.gapi; + if (!gapi || !gapi.client || !gapi.client.urlshortener) { + // Load the Google APIs client library asynchronously, then the + // urlshortener API, and finally come back here. + window.googleJSClientLoaded = googleJSClientLoaded; + googleJSClientLoaded.done = function () { + shortenURL(url, done); + }; + $(document.body).append('