<commit_before>// Copyright (C) 2015 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * @fileoverview
 * Registers a language handler for Swift
 *
 *
 * To use, include prettify.js and this file in your HTML page.
 * Then put your code in an HTML tag like
 *
(my swift code)

 * This file supports the following language extensions:
 *     lang-swift - Swift
 *
 * I used https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/AboutTheLanguageReference.html
 * as the basis for this. In particular, I targeted the revision from
 * 2015-04-08. Swift is still evolving, and this was the latest version
 * available at the time.
 *
 * @author cerech@google.com
 */

PR['registerLangHandler'](
    PR['createSimpleLexer'](
        [
          //whitespace
          [PR['PR_PLAIN'],                /^[\s\n\r\t\u000B\u000C\u0000]+/, null, '\s\n\r\t\u000B\u000C\u0000']
        ],
        [
          //single-line comment
          [PR['PR_COMMENT'],              /^\/\/.*?[\n\r]/, null]
          //multiline comment
          [PR['PR_COMMENT'],              /^\/\*.*?\/\*\//, null]
        ]),
    ['swift']);

//PR['registerLangHandler'](
//    PR['createSimpleLexer'](
//        [
//         ['opn',             /^\(+/, null, '('],
//        ['clo',             /^\)+/, null, ')'],
//       // A line comment that starts with ;
//         [PR['PR_COMMENT'],     /^;[^\r\n]*/, null, ';'],
//         // Whitespace
//         [PR['PR_PLAIN'],       /^[\t\n\r \xA0]+/, null, '\t\n\r \xA0'],
//         // A double quoted, possibly multi-line, string.
//         [PR['PR_STRING'],      /^\"(?:[^\"\\]|\\[\s\S])*(?:\"|$)/, null, '"']
//        ],
//        [
//         [PR['PR_KEYWORD'],     /^(?:block|c[ad]+r|catch|con[ds]|def(?:ine|un)|do|eq|eql|equal|equalp|eval-when|flet|format|go|if|labels|lambda|let|load-time-value|locally|macrolet|multiple-value-call|nil|progn|progv|quote|require|return-from|setq|symbol-macrolet|t|tagbody|the|throw|unwind)\b/, null],
//         [PR['PR_LITERAL'],
//          /^[+\-]?(?:[0#]x[0-9a-f]+|\d+\/\d+|(?:\.\d+|\d+(?:\.\d*)?)(?:[ed][+\-]?\d+)?)/i],
//         // A single quote possibly followed by a word that optionally ends with
//         // = ! or ?.
//         [PR['PR_LITERAL'],
//          /^\'(?:-*(?:\w|\\[\x21-\x7e])(?:[\w-]*|\\[\x21-\x7e])[=!?]?)?/],
//         // A word that optionally ends with = ! or ?.
//         [PR['PR_PLAIN'],
//          /^-*(?:[a-z_]|\\[\x21-\x7e])(?:[\w-]*|\\[\x21-\x7e])[=!?]?/i],
//         // A printable non-space non-special character
//         [PR['PR_PUNCTUATION'], /^[^\w\t\n\r \xA0()\"\\\';]+/]
//        ]),
//    ['cl', 'el', 'lisp', 'lsp', 'scm', 'ss', 'rkt']);*/
<commit_msg>Add highlighting for Swift keywords<commit_after>// Copyright (C) 2015 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * @fileoverview
 * Registers a language handler for Swift
 *
 *
 * To use, include prettify.js and this file in your HTML page.
 * Then put your code in an HTML tag like
 *
(my swift code)

 * This file supports the following language extensions:
 *     lang-swift - Swift
 *
 * I used https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/AboutTheLanguageReference.html
 * as the basis for this. In particular, I targeted the revision from
 * 2015-04-08. Swift is still evolving, and this was the latest version
 * available at the time. I will keep the code unoptimized to ease changes that come with new Swift standards.
 *
 * @author cerech@google.com
 */

PR['registerLangHandler'](
    PR['createSimpleLexer'](
        [
          //whitespace
          //unicodes are vertical tab, form feed, and null, respectively
          [PR['PR_PLAIN'],                /^[\s\n\r\t\u000B\u000C\u0000]+/, null, '\s\n\r\t\u000B\u000C\u0000']
        ],
        [
          //keywords
          [PR['PR_KEYWORD'],              /^\b(?:__COLUMN__|__FILE__|__FUNCTION__|__LINE__|associativity|as|break|case|class|continue|convenience|default|deinit|didSet|do|dynamic|dynamicType|enum|fallthrough|false|final|for|func|get|import|infix|init|inout|internal|in|is|lazy|left|let|mutating|nil|none|nonmutating|operator|optional|override|postfix|precedence|prefix|private|protocol|Protocol|public|required|return|right|safe|self|set|static|struct|subscript|super|switch|true|Type|typealias|unowned|unsafe|var|weak|while|willSet)\b/, null],
          //double slash comments
          [PR['PR_COMMENT'],              /^\/\/.*?[\n\r]/, null],
          //slash star comments
          [PR['PR_COMMENT'],              /^\/\*[\s\S]*?(?:\*\/|$)/, null]
        ]),
    ['swift']);

//PR['registerLangHandler'](
//    PR['createSimpleLexer'](
//        [
//         ['opn',             /^\(+/, null, '('],
//        ['clo',             /^\)+/, null, ')'],
//       // A line comment that starts with ;
//         [PR['PR_COMMENT'],     /^;[^\r\n]*/, null, ';'],
//         // Whitespace
//         [PR['PR_PLAIN'],       /^[\t\n\r \xA0]+/, null, '\t\n\r \xA0'],
//         // A double quoted, possibly multi-line, string.
//         [PR['PR_STRING'],      /^\"(?:[^\"\\]|\\[\s\S])*(?:\"|$)/, null, '"']
//        ],
//        [
//         [PR['PR_KEYWORD'],     /^(?:block|c[ad]+r|catch|con[ds]|def(?:ine|un)|do|eq|eql|equal|equalp|eval-when|flet|format|go|if|labels|lambda|let|load-time-value|locally|macrolet|multiple-value-call|nil|progn|progv|quote|require|return-from|setq|symbol-macrolet|t|tagbody|the|throw|unwind)\b/, null],
//         [PR['PR_LITERAL'],
//          /^[+\-]?(?:[0#]x[0-9a-f]+|\d+\/\d+|(?:\.\d+|\d+(?:\.\d*)?)(?:[ed][+\-]?\d+)?)/i],
//         // A single quote possibly followed by a word that optionally ends with
//         // = ! or ?.
//         [PR['PR_LITERAL'],
//          /^\'(?:-*(?:\w|\\[\x21-\x7e])(?:[\w-]*|\\[\x21-\x7e])[=!?]?)?/],
//         // A word that optionally ends with = ! or ?.
//         [PR['PR_PLAIN'],
//          /^-*(?:[a-z_]|\\[\x21-\x7e])(?:[\w-]*|\\[\x21-\x7e])[=!?]?/i],
//         // A printable non-space non-special character
//         [PR['PR_PUNCTUATION'], /^[^\w\t\n\r \xA0()\"\\\';]+/]
//        ]),
//    ['cl', 'el', 'lisp', 'lsp', 'scm', 'ss', 'rkt']);*/
<|endoftext|>


<commit_before>var express = require('express'),
	mongo = require('mongoskin'),
	MongoStore = require('connect-mongo')(express),
	optionalSession = require('./lib/optionalSession');

exports.configure = function(app) {
	//Load configuration
	require('./config').load(app);

	//Initialise database
	app.db = mongo.db(app.set('db-uri'), { safe: true });

	app.use(function(req, res, next) {
		req.db = app.db;
		next();
	});

	app.configure('development', function() {
		app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
	});

	app.configure('production', function() {
		app.use(express.errorHandler({ dumpExceptions: false, showStack: false }));

		//Emergency error handling
		process.on('uncaughtException', function(error) {
			app.error(error);
		});
	});

	app.configure(function() {
		//Set up Jade as view engine
		app.set('views', __dirname + '/views');
		app.set('view engine', 'jade');
		app.set('view options', { layout: false });

		//Redirect to host specified in config
		app.use(function(req, res, next) {
			if (req.host != app.set('host')) {
				res.redirect(301, req.protocol + '://' + app.set('host') + req.url);
			} else {
				next();
			}
		});

		//Set up cookie parser
		app.use(express.cookieParser(app.set('secret')));

		//Set up sessions with MongoDB as session store
		app.use(express.session({
			key: 'session',
			store: new MongoStore({ url: app.set('db-uri') }),
			cookie: {
				path: '/',
				httpOnly: true,
				maxAge: 20 * 365 * 24 * 60 * 60 * 1000 //20 years
			}
		}));

		//Disable automatic session creation
		app.use(optionalSession());

		//Set up body parser to process the payload of POST requests
		app.use(express.bodyParser());

		//Allow setting of method using _method GET or POST parameter
		//so that PUT and DELETE can be used
		app.use(express.methodOverride());

		//Set up gzip/deflate compression
		app.use(express.compress());

		//Serve static files from "public" directory
		app.use(express.static(__dirname + '/public', { maxAage: 365 * 24 * 60 * 60 * 1000 }));

  		//Set up express.js routing
		app.use(app.router);
	});
};<commit_msg>Prevented stray process after unhandled exception<commit_after>var express = require('express'),
	mongo = require('mongoskin'),
	MongoStore = require('connect-mongo')(express),
	optionalSession = require('./lib/optionalSession');

exports.configure = function(app) {
	//Load configuration
	require('./config').load(app);

	//Initialise database
	app.db = mongo.db(app.set('db-uri'), { safe: true });

	app.use(function(req, res, next) {
		req.db = app.db;
		next();
	});

	app.configure('development', function() {
		app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
	});

	app.configure('production', function() {
		app.use(express.errorHandler({ dumpExceptions: false, showStack: false }));

		//Emergency error handling
		process.on('uncaughtException', function(error) {
			console.error(new Date().toISOString() + ' *** UPDATIFIED CRASH ***');
			console.error(error);
			console.error(error.stack);
			process.exit(1);
		});
	});

	app.configure(function() {
		//Set up Jade as view engine
		app.set('views', __dirname + '/views');
		app.set('view engine', 'jade');
		app.set('view options', { layout: false });

		//Redirect to host specified in config
		app.use(function(req, res, next) {
			if (req.host != app.set('host')) {
				res.redirect(301, req.protocol + '://' + app.set('host') + req.url);
			} else {
				next();
			}
		});

		//Set up cookie parser
		app.use(express.cookieParser(app.set('secret')));

		//Set up sessions with MongoDB as session store
		app.use(express.session({
			key: 'session',
			store: new MongoStore({ url: app.set('db-uri') }),
			cookie: {
				path: '/',
				httpOnly: true,
				maxAge: 20 * 365 * 24 * 60 * 60 * 1000 //20 years
			}
		}));

		//Disable automatic session creation
		app.use(optionalSession());

		//Set up body parser to process the payload of POST requests
		app.use(express.bodyParser());

		//Allow setting of method using _method GET or POST parameter
		//so that PUT and DELETE can be used
		app.use(express.methodOverride());

		//Set up gzip/deflate compression
		app.use(express.compress());

		//Serve static files from "public" directory
		app.use(express.static(__dirname + '/public', { maxAage: 365 * 24 * 60 * 60 * 1000 }));

  		//Set up express.js routing
		app.use(app.router);
	});
};<|endoftext|>


<commit_before>/* eslint-disable global-require */
export const langs = [
  {
    value: 'en-US',
    native: 'English (US)',
    data: require('./en-US.json'),
  }, /* {
    value: 'bg-BG',
    native: 'български bǎlgarski',
    data: require('./bg-BG.json'),
  }, {
    value: 'cs-CZ',
    native: 'Čeština',
    data: require('./cs-CZ.json'),
  }, */ {
    value: 'de-DE',
    native: 'Deutsch',
    data: require('./de-DE.json'),
  }, {
    value: 'es-ES',
    native: 'Español',
    data: require('./es-ES.json'),
  }, /* {
    value: 'es-PE',
    native: 'Español (América Latina)',
    data: require('./es-PE.json'),
  }, {
    value: 'fi-FI',
    native: 'Suomi',
    data: require('./fi-FI.json'),
  },  {
    value: 'fr-FR',
    native: 'Français',
    data: require('./fr-FR.json'),
  }, */ {
    value: 'it-IT',
    native: 'Italiano',
    data: require('./it-IT.json'),
  }, {
    value: 'ja-JP',
    native: '日本語',
    data: require('./ja-JP.json'),
  }, /* {
    value: 'ko-KR',
    native: '한국어',
    data: require('./ko-KR.json'),
  }, */ {
    value: 'ms-MY',
    native: 'Bahasa Melayu',
    data: require('./ms-MY.json'),
  }, /* {
    value: 'nl-NL',
    native: 'Nederlands',
    data: require('./nl-NL.json'),
  }, */ {
    value: 'pl-PL',
    native: 'Polski',
    data: require('./pl-PL.json'),
  }, {
    value: 'pt-BR',
    native: 'Português Brasileiro',
    data: require('./pt-BR.json'),
  }, {
    value: 'ru-RU',
    native: 'Русский',
    data: require('./ru-RU.json'),
  }, /* {
    value: 'sv-SE',
    native: 'Svenska',
    data: require('./sv-SE.json'),
  }, {
    value: 'tr-TR',
    native: 'Türkçe',
    data: require('./tr-TR.json'),
  },  {
    value: 'uk-UA',
    native: 'Українська',
    data: require('./uk-UA.json'),
  }, {
    value: 'vi-VN',
    native: 'Tiếng Việt',
    data: require('./vi-VN.json'),
  }, */ {
    value: 'zh-CN',
    native: '中文',
    data: require('./zh-CN.json'),
  }, /* {
    value: 'zh-TW',
    native: '中文 (繁體字)',
    data: require('./zh-TW.json'),
  }, */
];
const savedLang = window.localStorage && window.localStorage.getItem('localization');
const langToUse = (langs.find(lang => lang.value === savedLang) || langs[0]).data;
export default langToUse;
<commit_msg>Fix lang bug<commit_after>/* eslint-disable global-require */
export const langs = [
  {
    value: 'en-US',
    native: 'English (US)',
    data: require('./en-US.json'),
  }, /* {
    value: 'bg-BG',
    native: 'български bǎlgarski',
    data: require('./bg-BG.json'),
  }, {
    value: 'cs-CZ',
    native: 'Čeština',
    data: require('./cs-CZ.json'),
  }, */ {
    value: 'de-DE',
    native: 'Deutsch',
    data: require('./de-DE.json'),
  }, {
    value: 'es-ES',
    native: 'Español',
    data: require('./es-ES.json'),
  }, /* {
    value: 'es-PE',
    native: 'Español (América Latina)',
    data: require('./es-PE.json'),
  }, {
    value: 'fi-FI',
    native: 'Suomi',
    data: require('./fi-FI.json'),
  },  {
    value: 'fr-FR',
    native: 'Français',
    data: require('./fr-FR.json'),
  }, */ {
    value: 'it-IT',
    native: 'Italiano',
    data: require('./it-IT.json'),
  }, {
    value: 'ja-JP',
    native: '日本語',
    data: require('./ja-JP.json'),
  }, /* {
    value: 'ko-KR',
    native: '한국어',
    data: require('./ko-KR.json'),
  }, */ {
    value: 'ms-MY',
    native: 'Bahasa Melayu',
    data: require('./ms-MY.json'),
  }, /* {
    value: 'nl-NL',
    native: 'Nederlands',
    data: require('./nl-NL.json'),
  }, */ {
    value: 'pl-PL',
    native: 'Polski',
    data: require('./pl-PL.json'),
  }, {
    value: 'pt-BR',
    native: 'Português Brasileiro',
    data: require('./pt-BR.json'),
  }, {
    value: 'ru-RU',
    native: 'Русский',
    data: require('./ru-RU.json'),
  }, /* {
    value: 'sv-SE',
    native: 'Svenska',
    data: require('./sv-SE.json'),
  }, {
    value: 'tr-TR',
    native: 'Türkçe',
    data: require('./tr-TR.json'),
  },  {
    value: 'uk-UA',
    native: 'Українська',
    data: require('./uk-UA.json'),
  }, {
    value: 'vi-VN',
    native: 'Tiếng Việt',
    data: require('./vi-VN.json'),
  }, */ {
    value: 'zh-CN',
    native: '中文',
    data: require('./zh-CN.json'),
  }, /* {
    value: 'zh-TW',
    native: '中文 (繁體字)',
    data: require('./zh-TW.json'),
  }, */
];
const savedLang = window.localStorage && window.localStorage.getItem('localization');
const selectedLang = langs.find(lang => lang.value === savedLang) || { };
export default { ...langs[0].data, ...selectedLang.data };
<|endoftext|>


<commit_before>require([
    'jquery',
    'backbone',
    'arches',
    'models/concept',
    'views/rdm/concept-tree',
    'views/rdm/concept-report',
    'views/concept-search',
    'views/rdm/modals/add-scheme-form',
    'views/rdm/modals/export-scheme-form',
    'views/rdm/modals/delete-scheme-form',
    'views/rdm/modals/import-scheme-form',
    'views/rdm/modals/add-collection-form',
    'views/rdm/modals/delete-collection-form',
    'views/base-manager',
    'viewmodels/alert-json',
    'jquery-validate',
], function($, Backbone, arches, ConceptModel, ConceptTree, ConceptReport, ConceptSearch,
    AddSchemeForm, ExportSchemeForm, DeleteSchemeForm, ImportSchemeForm, AddCollectionForm,
    DeleteCollectionForm, BaseManagerView, JsonErrorAlertViewModel) {

    var RDMView = BaseManagerView.extend({
        initialize: function(options){
            var self = this;
            var mode = 'semantic';

            // Models and views
            var concept = new ConceptModel({
                id: $('#selected-conceptid').val()
            });
            var conceptTree = new ConceptTree({
                el: $('#jqtree')[0],
                model: concept,
                url: arches.urls.concept_tree + 'semantic'
            });
            var dropdownTree = new ConceptTree({
                el: $('#ddtree')[0],
                model: concept,
                url: arches.urls.concept_tree + 'collections'
            });
            var conceptReport = new ConceptReport({
                el: $('#concept_report')[0],
                model: concept,
                mode: 'semantic',
                viewModel: this.viewModel
            });
            var conceptsearch = new ConceptSearch({
                el: $('#rdm-concept-search-container')[0],
                model: concept
            });

            concept.on({
                'change': function(){
                    window.history.pushState({}, "conceptid", concept.get('id'));
                },
                'save': function(){
                    conceptTree.render();
                    dropdownTree.render();
                    conceptReport.render();
                    concept.reset();
                },
                'delete': function(){
                    conceptTree.render();
                    dropdownTree.render();
                    conceptReport.render();
                    concept.reset();
                },
                'collection_created': function() {
                    //window.location.reload();
                    dropdownTree.render();
                },
            });

            conceptTree.on({
                'conceptMoved': function() {
                    conceptReport.render();
                },
                'conceptSelected': function(conceptid){
                    concept.clear();
                    concept.set('id', conceptid);
                    conceptReport.mode = 'semantic';
                    conceptReport.render();
                }
            });

            dropdownTree.on({
                'conceptMoved': function() {
                    conceptReport.render();
                },
                'conceptSelected': function(conceptid){
                    concept.clear();
                    concept.set('id', conceptid);
                    conceptReport.mode = 'collections';
                    conceptReport.render();
                }
            });

            conceptReport.on({
                'conceptSelected': function(conceptid) {
                    concept.clear();
                    concept.set('id', conceptid);

                    conceptReport.mode = 'semantic';
                    conceptReport.render();
                },
                'dropdownConceptSelected': function(conceptid) {
                    concept.clear();
                    concept.set('id', conceptid);

                    conceptReport.mode = 'collections';
                    conceptReport.render();
                },
                'parentsChanged': function() {
                    conceptTree.render();
                    conceptReport.render();
                },
                'conceptsImported': function() {
                    conceptReport.render();
                }
            });

            conceptsearch.on("select2-selecting", function(e, el) {
                concept.clear();
                concept.set('id', e.val);
                conceptTree.render();
                conceptReport.render();
            }, conceptsearch);

            $('a[href="#rdm-panel"]').on( "click", function(){
                var selectedNode = conceptTree.tree.tree('getSelectedNode');
                concept.clear();
                concept.set('id', selectedNode.id || '');

                conceptReport.mode = 'semantic';
                conceptReport.render();
            });

            $('a[href="#dropdown-panel"]').on( "click", function(){
                var selectedNode = dropdownTree.tree.tree('getSelectedNode');
                concept.clear();
                concept.set('id', selectedNode.id || '');

                conceptReport.mode = 'collections';
                conceptReport.render();
            });

            $('a[data-toggle="#add-scheme-form"]').on( "click", function(){
                var self = this;
                var form = new AddSchemeForm({
                    el: $('#add-scheme-form')
                });
                form.modal.modal('show');
                form.on({
                    'conceptSchemeAdded': function(newScheme){
                        conceptTree.render();
                        concept.set('id', newScheme.id);
                        conceptReport.render();
                    }
                });
            });

            $('a[data-toggle="#export-scheme-form"]').on( "click", function(){
                var self = this;
                var form = new ExportSchemeForm({
                    el: $('#export-scheme-form')
                });
                form.modal.modal('show');
            });

            $('a[data-toggle="#delete-scheme-form"]').on( "click", function(){
                var self = this;
                var form = new DeleteSchemeForm({
                    el: $('#delete-scheme-form'),
                    model: null,
                    viewModel: this.viewModel
                });
                form.modal.modal('show');
                form.on({
                    'conceptSchemeDeleted': function(){
                        window.location = arches.urls.rdm;
                    }
                });
            }.bind(this));

            $('a[data-toggle="#import-scheme-form"]').on( "click", function(){
                var self = this;
                var form = new ImportSchemeForm({
                    el: $('#import-scheme-form'),
                    model: concept,
                    viewModel: this.viewModel
                });
                form.modal.modal('show');
                form.on({
                    'conceptSchemeAdded': function(response, status){
                        if (status === 'success'){
                            conceptTree.render();
                            concept.set('id', response.responseJSON.id);
                            conceptReport.render();

                        } else {
                            self.viewModel.alert(new JsonErrorAlertViewModel('ep-alert-red', response.responseJSON));
                        }
                    }
                });
            }.bind(this));

            $('a[data-toggle="#add-collection-form"]').on( "click", function(){
                var self = this;
                var form = new AddCollectionForm({
                    el: $('#add-collection-form')
                });
                form.modal.modal('show');
                form.on({
                    'collectionAdded': function(newCollection){
                        dropdownTree.render();
                        concept.set('id', newCollection.id);
                        conceptReport.render();
                    }
                })
            });

            $('a[data-toggle="#delete-collection-form"]').on( "click", function(){
                var self = this;
                var form = new DeleteCollectionForm({
                    el: $('#delete-collection-form'),
                    model: null
                });
                form.modal.modal('show');
                form.on({
                    'collectionDeleted': function(){
                        dropdownTree.render();
                    }
                });
            });

            $('a[data-toggle="#export-all-collections"]').on( "click", function(){
                window.open(arches.urls.export_concept_collections,'_blank');
            });

            BaseManagerView.prototype.initialize.call(this, options);
        }
    });

    return new RDMView();
});
<commit_msg>lints<commit_after>require([
    'jquery',
    'backbone',
    'arches',
    'models/concept',
    'views/rdm/concept-tree',
    'views/rdm/concept-report',
    'views/concept-search',
    'views/rdm/modals/add-scheme-form',
    'views/rdm/modals/export-scheme-form',
    'views/rdm/modals/delete-scheme-form',
    'views/rdm/modals/import-scheme-form',
    'views/rdm/modals/add-collection-form',
    'views/rdm/modals/delete-collection-form',
    'views/base-manager',
    'viewmodels/alert-json',
    'jquery-validate',
], function($, Backbone, arches, ConceptModel, ConceptTree, ConceptReport, ConceptSearch,
    AddSchemeForm, ExportSchemeForm, DeleteSchemeForm, ImportSchemeForm, AddCollectionForm,
    DeleteCollectionForm, BaseManagerView, JsonErrorAlertViewModel) {

    var RDMView = BaseManagerView.extend({
        initialize: function(options){
            var mode = 'semantic';

            // Models and views
            var concept = new ConceptModel({
                id: $('#selected-conceptid').val()
            });
            var conceptTree = new ConceptTree({
                el: $('#jqtree')[0],
                model: concept,
                url: arches.urls.concept_tree + 'semantic'
            });
            var dropdownTree = new ConceptTree({
                el: $('#ddtree')[0],
                model: concept,
                url: arches.urls.concept_tree + 'collections'
            });
            var conceptReport = new ConceptReport({
                el: $('#concept_report')[0],
                model: concept,
                mode: 'semantic',
                viewModel: this.viewModel
            });
            var conceptsearch = new ConceptSearch({
                el: $('#rdm-concept-search-container')[0],
                model: concept
            });

            concept.on({
                'change': function(){
                    window.history.pushState({}, "conceptid", concept.get('id'));
                },
                'save': function(){
                    conceptTree.render();
                    dropdownTree.render();
                    conceptReport.render();
                    concept.reset();
                },
                'delete': function(){
                    conceptTree.render();
                    dropdownTree.render();
                    conceptReport.render();
                    concept.reset();
                },
                'collection_created': function() {
                    //window.location.reload();
                    dropdownTree.render();
                },
            });

            conceptTree.on({
                'conceptMoved': function() {
                    conceptReport.render();
                },
                'conceptSelected': function(conceptid){
                    concept.clear();
                    concept.set('id', conceptid);
                    conceptReport.mode = 'semantic';
                    conceptReport.render();
                }
            });

            dropdownTree.on({
                'conceptMoved': function() {
                    conceptReport.render();
                },
                'conceptSelected': function(conceptid){
                    concept.clear();
                    concept.set('id', conceptid);
                    conceptReport.mode = 'collections';
                    conceptReport.render();
                }
            });

            conceptReport.on({
                'conceptSelected': function(conceptid) {
                    concept.clear();
                    concept.set('id', conceptid);

                    conceptReport.mode = 'semantic';
                    conceptReport.render();
                },
                'dropdownConceptSelected': function(conceptid) {
                    concept.clear();
                    concept.set('id', conceptid);

                    conceptReport.mode = 'collections';
                    conceptReport.render();
                },
                'parentsChanged': function() {
                    conceptTree.render();
                    conceptReport.render();
                },
                'conceptsImported': function() {
                    conceptReport.render();
                }
            });

            conceptsearch.on("select2-selecting", function(e, el) {
                concept.clear();
                concept.set('id', e.val);
                conceptTree.render();
                conceptReport.render();
            }, conceptsearch);

            $('a[href="#rdm-panel"]').on( "click", function(){
                var selectedNode = conceptTree.tree.tree('getSelectedNode');
                concept.clear();
                concept.set('id', selectedNode.id || '');

                conceptReport.mode = 'semantic';
                conceptReport.render();
            });

            $('a[href="#dropdown-panel"]').on( "click", function(){
                var selectedNode = dropdownTree.tree.tree('getSelectedNode');
                concept.clear();
                concept.set('id', selectedNode.id || '');

                conceptReport.mode = 'collections';
                conceptReport.render();
            });

            $('a[data-toggle="#add-scheme-form"]').on( "click", function(){
                var form = new AddSchemeForm({
                    el: $('#add-scheme-form')
                });
                form.modal.modal('show');
                form.on({
                    'conceptSchemeAdded': function(newScheme){
                        conceptTree.render();
                        concept.set('id', newScheme.id);
                        conceptReport.render();
                    }
                });
            });

            $('a[data-toggle="#export-scheme-form"]').on( "click", function(){
                var form = new ExportSchemeForm({
                    el: $('#export-scheme-form')
                });
                form.modal.modal('show');
            });

            $('a[data-toggle="#delete-scheme-form"]').on( "click", function(){
                var form = new DeleteSchemeForm({
                    el: $('#delete-scheme-form'),
                    model: null,
                    viewModel: this.viewModel
                });
                form.modal.modal('show');
                form.on({
                    'conceptSchemeDeleted': function(){
                        window.location = arches.urls.rdm;
                    }
                });
            }.bind(this));

            $('a[data-toggle="#import-scheme-form"]').on( "click", function(){
                var self = this;
                var form = new ImportSchemeForm({
                    el: $('#import-scheme-form'),
                    model: concept,
                    viewModel: this.viewModel
                });
                form.modal.modal('show');
                form.on({
                    'conceptSchemeAdded': function(response, status){
                        if (status === 'success'){
                            conceptTree.render();
                            concept.set('id', response.responseJSON.id);
                            conceptReport.render();

                        } else {
                            self.viewModel.alert(new JsonErrorAlertViewModel('ep-alert-red', response.responseJSON));
                        }
                    }
                });
            }.bind(this));

            $('a[data-toggle="#add-collection-form"]').on( "click", function(){
                var form = new AddCollectionForm({
                    el: $('#add-collection-form')
                });
                form.modal.modal('show');
                form.on({
                    'collectionAdded': function(newCollection){
                        dropdownTree.render();
                        concept.set('id', newCollection.id);
                        conceptReport.render();
                    }
                });
            });

            $('a[data-toggle="#delete-collection-form"]').on( "click", function(){
                var form = new DeleteCollectionForm({
                    el: $('#delete-collection-form'),
                    model: null
                });
                form.modal.modal('show');
                form.on({
                    'collectionDeleted': function(){
                        dropdownTree.render();
                    }
                });
            });

            $('a[data-toggle="#export-all-collections"]').on( "click", function(){
                window.open(arches.urls.export_concept_collections,'_blank');
            });

            BaseManagerView.prototype.initialize.call(this, options);
        }
    });

    return new RDMView();
});
<|endoftext|>


<commit_before>define(function(require, exports, module) {
    main.consumes = [
        "Plugin", "dialog.error", "ui", "settings", "tabManager", "save",
        "menus", "preferences.keybindings", "preferences.general",
        "preferences.project", "c9", "commands", "watcher", "fs",
        "tree.favorites", "preferences", "util"
    ];
    main.provides = ["configure"];
    return main;

    function main(options, imports, register) {
        var Plugin = imports.Plugin;
        var settings = imports.settings;
        var commands = imports.commands;
        var save = imports.save;
        var menus = imports.menus;
        var watcher = imports.watcher;
        var tabManager = imports.tabManager;
        var preferences = imports.preferences;
        var ui = imports.ui;
        var c9 = imports.c9;
        var fs = imports.fs;
        var kbprefs = imports["preferences.keybindings"];
        var genprefs = imports["preferences.general"];
        var prjprefs = imports["preferences.project"];
        var showError = imports["dialog.error"].show;
        var favs = imports["tree.favorites"];
        var util = imports.util;

        var join = require("path").join;

        /***** Initialization *****/

        var plugin = new Plugin("Ajax.org", main.consumes);
        // var emit = plugin.getEmitter();

        var cssSession = new Plugin("Ajax.org", main.consumes);
        var services, initPlugin;

        var pathFromFavorite = options.pathFromFavorite;

        var loaded = false;
        function load() {
            if (loaded) return false;
            loaded = true;

            // Init Script
            var script = settings.get("user/config/init.js");
            if (script) {
                runInitJs(script);
            }

            // Init CSS
            var css = settings.get("user/config/styles.css");
            if (css)
                insertCss(css, false, cssSession);

            settings.on("user/config/styles.css", function(css) {
                cssSession.cleanUp();
                insertCss(css, false, cssSession);
            });

            commands.addCommand({
                name: "restartc9",
                group: "General",
                bindKey: { mac: "Command-R", win: "Ctrl-R" },
                exec: function() {
                    location.reload();
                }
            }, plugin);
            commands.addCommand({
                name: "rerunInitScript",
                group: "General",
                bindKey: { mac: "Command-Enter", win: "Ctrl-Enter" },
                isAvailable: function() {
                    return tabManager.focussedTab && tabManager.focussedTab.path == "~/.c9/init.js";
                },
                exec: function() {
                    var script = settings.get("user/config/init.js");
                    runInitJs(script);
                }
            }, plugin);

            menus.addItemByPath("Cloud9/~", new ui.divider(), 300, plugin);
            menus.addItemByPath("Cloud9/Go To Your Dashboard", new ui.item({
                onclick: function() { window.open(options.dashboardUrl); }
            }), 310, plugin);

            menus.addItemByPath("Cloud9/~", new ui.divider(), 350, plugin);
            menus.addItemByPath("Cloud9/Open Your Project Settings", new ui.item({
                onclick: editProjectSettings
            }), 400, plugin);
            menus.addItemByPath("Cloud9/Open Your User Settings", new ui.item({
                onclick: editUserSettings
            }), 400, plugin);
            menus.addItemByPath("Cloud9/Open Your Keymap", new ui.item({
                onclick: function() {
                    kbprefs.editUserKeys();
                }
            }), 600, plugin);
            menus.addItemByPath("Cloud9/Open Your Init Script", new ui.item({
                onclick: editInitJs
            }), 700, plugin);
            menus.addItemByPath("Cloud9/Open Your Stylesheet", new ui.item({
                onclick: editStylesCss
            }), 800, plugin);

            if (!c9.hosted) {
                menus.addItemByPath("Cloud9/Restart Cloud9", new apf.item({
                    command: "restartc9"
                }), 2000080, plugin);
            } else {
                menus.addItemByPath("Cloud9/Restart Workspace", new apf.item({
                    command: "restartc9vm"
                }), 2000080, plugin);
            }

            genprefs.on("edit", function() {
                editUserSettings();
            });
            prjprefs.on("edit", function() {
                editProjectSettings();
            });

            save.on("beforeSave", function(e) {
                if (!e.document.meta.config) return;

                var path = e.document.meta.config;

                // Doing save as, it is now a normal document
                if (e.path != path && e.path != util.normalizePath(path)) {
                    delete e.document.meta.config;
                    delete e.document.meta.nofs;
                    return;
                }

                if (path == "~/.c9/init.js") {
                    settings.setJson("user/config/init.js", e.document.value);
                    showError("Please reload or press '" + commands.getHotkey("rerunInitScript") + "' for these changes to take effect.");
                }
                else if (path == "~/.c9/styles.css") {
                    var css = e.document.value;
                    settings.setJson("user/config/styles.css", css);
                }
                else if (path == settings.paths.project) {
                    try { var project = JSON.parse(e.document.value); }
                    catch (e) {
                        showError("Syntax Error in Project Settings: " + e.message);
                        return false;
                    }

                    // @todo doesn't update UI
                    // settings.model.project = project;
                    settings.read({ project: project });
                    settings.save(true);
                }
                else if (path == settings.paths.user) {
                    try { var user = JSON.parse(e.document.value); }
                    catch (e) {
                        showError("Syntax Error in User Settings: " + e.message);
                        return false;
                    }

                    // @todo doesn't update UI
                    // settings.model.user = user;
                    settings.read({ user: user });
                    settings.save(true);
                }

                delete e.document.meta.newfile;
                e.document.undoManager.bookmark();

                return false;
            }, plugin);

            // Load initial project settings from disk and match against latest from database
            var initWatcher, projectPath;
            settings.on("read", function() {
                if (initWatcher) return;
                initWatcher = true;

                // Keep project file consistent with changes on disk
                watcher.on("change", function(e) {
                    if (e.path == projectPath)
                        fs.readFile(e.path, readHandler);
                });
                watcher.on("delete", function(e) {
                    if (e.path == projectPath)
                        watcher.watch(projectPath);
                });
                watcher.on("failed", function(e) {
                    if (e.path == projectPath) {
                        setTimeout(function() {
                            watcher.watch(projectPath); // Retries once after 1s
                        });
                    }
                });

                function readHandler(err, data) {
                    if (err) return;

                    settings.paths.project = projectPath;

                    try { var json = JSON.parse(data); }
                    catch (e) { return; }

                    settings.update("project", json);
                }

                function updateFavPath() {
                    var mainPath = favs.getFavoritePaths()[0];
                    if (mainPath)
                        mainPath = join(mainPath, ".c9/project.settings");
                    else
                        mainPath = originalPath;

                    // Unwatch old project path
                    if (projectPath)
                        watcher.unwatch(projectPath);

                    // Set new project path
                    projectPath = mainPath;

                    // Watch project path
                    watcher.watch(projectPath);

                    // Read from disk
                    fs.readFile(mainPath, readHandler);
                }

                // At startup read the project settings from disk
                if (pathFromFavorite) {
                    var originalPath = settings.paths.project;

                    favs.on("favoriteAdd", updateFavPath);
                    favs.on("favoriteRemove", updateFavPath);
                    favs.on("favoriteReorder", updateFavPath);

                    updateFavPath();
                }
                else {
                    projectPath = settings.paths.project;

                    // Watch project path
                    watcher.watch(projectPath);

                    // Read from disk
                    fs.readFile(projectPath, readHandler);
                }
            });
        }

        /***** Methods *****/

        function insertCss(css, staticPrefix, plugin) {
            // we do not use ui.insertCss to make sure user stylesheet is
            // appended to the body tag and have highest priority
            // without this priority of css rules will be different after
            // saving stylesheet and after reloading cloud9

            css += "\n/*# sourceURL=~/.c9/styles.css */";
            var style = document.createElement("style");
            style.appendChild(document.createTextNode(css));
            document.body.appendChild(style);

            // Cleanup
            plugin.addOther(function() {
                style.parentNode.removeChild(style);
            });
        }

        function openTab(path, value, syntax, defaultValue) {
            tabManager.open({
                path: path,
                value: value || defaultValue,
                active: true,
                editorType: "ace",
                document: {
                    ace: { customSyntax: syntax },
                    meta: { config: path, newfile: !value.length, nofs: true }
                }
            }, function(err, tab) {

            });
        }

        function editInitJs() {
            var script = settings.get("user/config/init.js") || "";
            openTab("~/.c9/init.js", script, "javascript",
                "// You can access plugins via the 'services' global variable\n" +
                "/*global services, plugin*/\n");
        }

        function editStylesCss() {
            // preferences.hide();
            var css = settings.get("user/config/styles.css") || "";
            openTab("~/.c9/styles.css", css, "css");
        }

        function editProjectSettings() {
            // preferences.hide();
            var value = JSON.stringify(settings.model.project, 0, "    ")
                .replace(/"true"/g, "true")
                .replace(/"false"/g, "false");
            openTab(settings.paths.project, value, "javascript");
        }
        function editUserSettings() {
            // preferences.hide();
            var value = JSON.stringify(settings.model.user, 0, "    ")
                .replace(/"true"/g, "true")
                .replace(/"false"/g, "false");
            openTab(settings.paths.user, value, "javascript");
        }

        function runInitJs(script) {
            c9.once("ready", function() {
                try {
                    var fn = new Function("services, plugin", script
                        + "\n//@ sourceURL=config/init.js");
                    if (initPlugin) initPlugin.unload();
                    var initPlugin = new Plugin("initScript", []);
                    initPlugin.name = "initScript";
                    fn(services, initPlugin);
                }
                catch (e) {
                    console.error(e);
                    setTimeout(function() {
                        showError("Error Executing init.js: ", e.message);
                    }, 500);
                }
             });
        }

        /***** Lifecycle *****/

        plugin.on("load", function() {
            load();
        });
        plugin.on("enable", function() {

        });
        plugin.on("disable", function() {

        });
        plugin.on("unload", function() {
            loaded = false;
            if (initPlugin) initPlugin.unload();
        });

        /***** Register and define API *****/

        /**
         *
         **/
        plugin.freezePublicAPI({
            get services() { return services; },
            set services(value) { services = value; },

            /**
             *
             */
            editInitJs: editInitJs,

            /**
             *
             */
            editStylesCss: editStylesCss,

            /**
             *
             */
            editProjectSettings: editProjectSettings,

            /**
             *
             */
            editUserSettings: editUserSettings
        });

        register(null, {
            configure: plugin
        });
    }
});
<commit_msg>remove plugin manager code from ide.html<commit_after>define(function(require, exports, module) {
    main.consumes = [
        "Plugin", "dialog.error", "ui", "settings", "tabManager", "save",
        "menus", "preferences.keybindings", "preferences.general",
        "preferences.project", "c9", "commands", "watcher", "fs",
        "tree.favorites", "util", "hub"
    ];
    main.provides = ["configure"];
    return main;

    function main(options, imports, register) {
        var Plugin = imports.Plugin;
        var settings = imports.settings;
        var commands = imports.commands;
        var save = imports.save;
        var menus = imports.menus;
        var watcher = imports.watcher;
        var tabManager = imports.tabManager;
        var ui = imports.ui;
        var c9 = imports.c9;
        var fs = imports.fs;
        var kbprefs = imports["preferences.keybindings"];
        var genprefs = imports["preferences.general"];
        var prjprefs = imports["preferences.project"];
        var services = imports.hub.app.services;
        var showError = imports["dialog.error"].show;
        var favs = imports["tree.favorites"];
        var util = imports.util;

        var join = require("path").join;

        /***** Initialization *****/

        var plugin = new Plugin("Ajax.org", main.consumes);
        // var emit = plugin.getEmitter();

        var cssSession = new Plugin("Ajax.org", main.consumes);
        var initPlugin;

        var pathFromFavorite = options.pathFromFavorite;

        var loaded = false;
        function load() {
            if (loaded) return false;
            loaded = true;

            // Init Script
            var script = settings.get("user/config/init.js");
            if (script) {
                runInitJs(script);
            }

            // Init CSS
            var css = settings.get("user/config/styles.css");
            if (css)
                insertCss(css, false, cssSession);

            settings.on("user/config/styles.css", function(css) {
                cssSession.cleanUp();
                insertCss(css, false, cssSession);
            });

            commands.addCommand({
                name: "restartc9",
                group: "General",
                bindKey: { mac: "Command-R", win: "Ctrl-R" },
                exec: function() {
                    location.reload();
                }
            }, plugin);
            commands.addCommand({
                name: "rerunInitScript",
                group: "General",
                bindKey: { mac: "Command-Enter", win: "Ctrl-Enter" },
                isAvailable: function() {
                    return tabManager.focussedTab && tabManager.focussedTab.path == "~/.c9/init.js";
                },
                exec: function() {
                    var script = settings.get("user/config/init.js");
                    runInitJs(script);
                }
            }, plugin);

            menus.addItemByPath("Cloud9/~", new ui.divider(), 300, plugin);
            menus.addItemByPath("Cloud9/Go To Your Dashboard", new ui.item({
                onclick: function() { window.open(options.dashboardUrl); }
            }), 310, plugin);

            menus.addItemByPath("Cloud9/~", new ui.divider(), 350, plugin);
            menus.addItemByPath("Cloud9/Open Your Project Settings", new ui.item({
                onclick: editProjectSettings
            }), 400, plugin);
            menus.addItemByPath("Cloud9/Open Your User Settings", new ui.item({
                onclick: editUserSettings
            }), 400, plugin);
            menus.addItemByPath("Cloud9/Open Your Keymap", new ui.item({
                onclick: function() {
                    kbprefs.editUserKeys();
                }
            }), 600, plugin);
            menus.addItemByPath("Cloud9/Open Your Init Script", new ui.item({
                onclick: editInitJs
            }), 700, plugin);
            menus.addItemByPath("Cloud9/Open Your Stylesheet", new ui.item({
                onclick: editStylesCss
            }), 800, plugin);

            if (!c9.hosted) {
                menus.addItemByPath("Cloud9/Restart Cloud9", new apf.item({
                    command: "restartc9"
                }), 2000080, plugin);
            } else {
                menus.addItemByPath("Cloud9/Restart Workspace", new apf.item({
                    command: "restartc9vm"
                }), 2000080, plugin);
            }

            genprefs.on("edit", function() {
                editUserSettings();
            });
            prjprefs.on("edit", function() {
                editProjectSettings();
            });

            save.on("beforeSave", function(e) {
                if (!e.document.meta.config) return;

                var path = e.document.meta.config;

                // Doing save as, it is now a normal document
                if (e.path != path && e.path != util.normalizePath(path)) {
                    delete e.document.meta.config;
                    delete e.document.meta.nofs;
                    return;
                }

                if (path == "~/.c9/init.js") {
                    settings.setJson("user/config/init.js", e.document.value);
                    showError("Please reload or press '" + commands.getHotkey("rerunInitScript") + "' for these changes to take effect.");
                }
                else if (path == "~/.c9/styles.css") {
                    var css = e.document.value;
                    settings.setJson("user/config/styles.css", css);
                }
                else if (path == settings.paths.project) {
                    try { var project = JSON.parse(e.document.value); }
                    catch (e) {
                        showError("Syntax Error in Project Settings: " + e.message);
                        return false;
                    }

                    // @todo doesn't update UI
                    // settings.model.project = project;
                    settings.read({ project: project });
                    settings.save(true);
                }
                else if (path == settings.paths.user) {
                    try { var user = JSON.parse(e.document.value); }
                    catch (e) {
                        showError("Syntax Error in User Settings: " + e.message);
                        return false;
                    }

                    // @todo doesn't update UI
                    // settings.model.user = user;
                    settings.read({ user: user });
                    settings.save(true);
                }

                delete e.document.meta.newfile;
                e.document.undoManager.bookmark();

                return false;
            }, plugin);

            // Load initial project settings from disk and match against latest from database
            var initWatcher, projectPath;
            settings.on("read", function() {
                if (initWatcher) return;
                initWatcher = true;

                // Keep project file consistent with changes on disk
                watcher.on("change", function(e) {
                    if (e.path == projectPath)
                        fs.readFile(e.path, readHandler);
                });
                watcher.on("delete", function(e) {
                    if (e.path == projectPath)
                        watcher.watch(projectPath);
                });
                watcher.on("failed", function(e) {
                    if (e.path == projectPath) {
                        setTimeout(function() {
                            watcher.watch(projectPath); // Retries once after 1s
                        });
                    }
                });

                function readHandler(err, data) {
                    if (err) return;

                    settings.paths.project = projectPath;

                    try { var json = JSON.parse(data); }
                    catch (e) { return; }

                    settings.update("project", json);
                }

                function updateFavPath() {
                    var mainPath = favs.getFavoritePaths()[0];
                    if (mainPath)
                        mainPath = join(mainPath, ".c9/project.settings");
                    else
                        mainPath = originalPath;

                    // Unwatch old project path
                    if (projectPath)
                        watcher.unwatch(projectPath);

                    // Set new project path
                    projectPath = mainPath;

                    // Watch project path
                    watcher.watch(projectPath);

                    // Read from disk
                    fs.readFile(mainPath, readHandler);
                }

                // At startup read the project settings from disk
                if (pathFromFavorite) {
                    var originalPath = settings.paths.project;

                    favs.on("favoriteAdd", updateFavPath);
                    favs.on("favoriteRemove", updateFavPath);
                    favs.on("favoriteReorder", updateFavPath);

                    updateFavPath();
                }
                else {
                    projectPath = settings.paths.project;

                    // Watch project path
                    watcher.watch(projectPath);

                    // Read from disk
                    fs.readFile(projectPath, readHandler);
                }
            });
        }

        /***** Methods *****/

        function insertCss(css, staticPrefix, plugin) {
            // we do not use ui.insertCss to make sure user stylesheet is
            // appended to the body tag and have highest priority
            // without this priority of css rules will be different after
            // saving stylesheet and after reloading cloud9

            css += "\n/*# sourceURL=~/.c9/styles.css */";
            var style = document.createElement("style");
            style.appendChild(document.createTextNode(css));
            document.body.appendChild(style);

            // Cleanup
            plugin.addOther(function() {
                style.parentNode.removeChild(style);
            });
        }

        function openTab(path, value, syntax, defaultValue) {
            tabManager.open({
                path: path,
                value: value || defaultValue,
                active: true,
                editorType: "ace",
                document: {
                    ace: { customSyntax: syntax },
                    meta: { config: path, newfile: !value.length, nofs: true }
                }
            }, function(err, tab) {

            });
        }

        function editInitJs() {
            var script = settings.get("user/config/init.js") || "";
            openTab("~/.c9/init.js", script, "javascript",
                "// You can access plugins via the 'services' global variable\n" +
                "/*global services, plugin*/\n");
        }

        function editStylesCss() {
            var css = settings.get("user/config/styles.css") || "";
            openTab("~/.c9/styles.css", css, "css");
        }

        function editProjectSettings() {
            var value = JSON.stringify(settings.model.project, 0, "    ")
                .replace(/"true"/g, "true")
                .replace(/"false"/g, "false");
            openTab(settings.paths.project, value, "javascript");
        }
        function editUserSettings() {
            var value = JSON.stringify(settings.model.user, 0, "    ")
                .replace(/"true"/g, "true")
                .replace(/"false"/g, "false");
            openTab(settings.paths.user, value, "javascript");
        }

        function runInitJs(script) {
            c9.once("ready", function() {
                try {
                    var fn = new Function("services, plugin", script
                        + "\n//@ sourceURL=config/init.js");
                    if (initPlugin) initPlugin.unload();
                    var initPlugin = new Plugin("initScript", []);
                    initPlugin.name = "initScript";
                    fn(services, initPlugin);
                }
                catch (e) {
                    console.error(e);
                    setTimeout(function() {
                        showError("Error Executing init.js: ", e.message);
                    }, 500);
                }
             });
        }

        /***** Lifecycle *****/

        plugin.on("load", function() {
            load();
        });
        plugin.on("enable", function() {

        });
        plugin.on("disable", function() {

        });
        plugin.on("unload", function() {
            loaded = false;
            if (initPlugin) initPlugin.unload();
        });

        /***** Register and define API *****/

        /**
         *
         **/
        plugin.freezePublicAPI({
            /**
             *
             */
            editInitJs: editInitJs,

            /**
             *
             */
            editStylesCss: editStylesCss,

            /**
             *
             */
            editProjectSettings: editProjectSettings,

            /**
             *
             */
            editUserSettings: editUserSettings
        });

        register(null, {
            configure: plugin
        });
    }
});
<|endoftext|>


<commit_before>(function (exports) {
  var util, T, escodegen, Types, uglify;
  if (typeof process !== "undefined") {
    util = require("./util.js");
    T = require("./estransform.js");
    escodegen = require("./escodegen.js");
    Types = require("./types.js");
    uglify = require("uglify-js");

    snarf = require('fs').readFileSync;
  } else {
    util = this.util;
    T = estransform;
    escodegen = this.escodegen;
    Types = this.Types;
    uglify = load("./uglify-js.js");
  }

  /**
   * Import AST nodes
   */
  const Node = T.Node;
  const Program = T.Program;
  const Literal = T.Literal;
  const Identifier = T.Identifier;
  const FunctionDeclaration = T.FunctionDeclaration;
  const FunctionExpression = T.FunctionExpression;
  const AssignmentExpression = T.AssignmentExpression;
  const ExpressionStatement = T.ExpressionStatement;
  const CallExpression = T.CallExpression;
  const VariableDeclaration = T.VariableDeclaration;
  const VariableDeclarator = T.VariableDeclarator;
  const BlockStatement = T.BlockStatement;
  const ReturnStatement = T.ReturnStatement;
  const MemberExpression = T.MemberExpression;
  const IfStatement = T.IfStatement;
  const BinaryExpression = T.BinaryExpression;
  const UnaryExpression = T.UnaryExpression;
  const SequenceExpression = T.SequenceExpression;
  const ArrayExpression = T.ArrayExpression;
  const ForInStatement = T.ForInStatement;

  /**
   * Import utilities.
   */
  const extend = util.extend;
  const assert = util.assert;

  var logger;
  var minReplaceLength;
  var callGraphAvailable;
  var callProfiling;

  exports.initialize = function (o, cmdLineOpts) {
    logger = o.logger;
    if (cmdLineOpts["lazy-minimum"] === true) {
      minReplaceLength = 0;
    } else {
      minReplaceLength = cmdLineOpts["lazy-minimum"];
    }

    callGraphAvailable = cmdLineOpts["call-graph"];

    if (cmdLineOpts["read-profile"] !== "") {
      var profileStr = snarf(cmdLineOpts["read-profile"]);
      callProfiling = new Uint8Array(JSON.parse(profileStr));
    }
  };

  function stringifyNode(node) {
    var s = escodegen.generate(node, {format: {indent: { style: '', base: 0}}});
    if (node instanceof BlockStatement) {
      return uglify('(function()' + s + ')')
        .replace(/^.*?\{/, '').replace(/\}\)$/, '');
    } else {
      return uglify('(' + s + ')')
        .replace(/^\(/, '').replace(/\)$/, '');
    }
  }

  /**
   * Begin rewrite pass
   */

  function shouldLazify(functionNode, length) {
    return (length > minReplaceLength &&
            (!callGraphAvailable || !functionNode.called) &&
            (typeof callProfiling === "undefined" || !callProfiling[functionNode.idNumber]));
  }

  function Laziness() {
    this.functionStrings = Object.create(null);
    this.functionMap = Object.create(null);
    this.isClosure = false;
    this.needsStub = false;
    this.needsStubF = false;
  }

  function stubConstructor(strId, funcId) {
    var tempId = new Identifier("t");
    return new FunctionDeclaration(
      new Identifier("stub"),
      [strId, funcId],
      new BlockStatement([
        new IfStatement(
          new BinaryExpression(
            "===",
            new UnaryExpression(
              "typeof",
              strId
            ),
            new Literal("string")
          ),
          new BlockStatement([
            new VariableDeclaration(
              "var", [
                new VariableDeclarator(
                  tempId,
                  new CallExpression(
                    new Identifier("eval"),
                    [strId]
                  )
                )
              ]
            ),
            new ExpressionStatement(
              new AssignmentExpression(
                new MemberExpression(
                  tempId,
                  new Identifier("prototype"),
                  false,
                  "."
                ),
                "=",
                new MemberExpression(
                  funcId,
                  new Identifier("prototype"),
                  false,
                  "."
                )
              )
            ),
            new ForInStatement(
              new VariableDeclaration(
                "var", [
                  new VariableDeclarator(
                    new Identifier("x")
                  )
                ]
              ),
              funcId,
              new BlockStatement([
                new ExpressionStatement(
                  new AssignmentExpression(
                    new MemberExpression(
                      tempId,
                      new Identifier("x"),
                      true
                    ), "=",
                    new MemberExpression(
                      funcId,
                      new Identifier("x"),
                      true
                    )
                  )
                )
              ])
            ),
            new ReturnStatement(
              tempId
            )
          ])
        ),
        new ReturnStatement(
          funcId
        )
      ])
    );
  }

  function stubFConstructor(strId, funcId, paramsId) {
    var tempId = new Identifier("t");
    return new FunctionDeclaration(
      new Identifier("stubF"),
      [strId, funcId, paramsId],
      new BlockStatement([
        new IfStatement(
          new BinaryExpression(
            "===",
            new UnaryExpression(
              "typeof",
              strId
            ),
            new Literal("string")
          ),
          new BlockStatement([
            new ExpressionStatement(
              new CallExpression(
                new MemberExpression(
                  paramsId,
                  new Identifier("push"),
                  false, "."
                ),
                [strId]
              )
            ),
            new VariableDeclaration(
              "var", [
                new VariableDeclarator(
                  tempId,
                  new CallExpression(
                    new MemberExpression(
                      new Identifier("Function"),
                      new Identifier("apply"),
                      false, "."
                    ),
                    [
                      new Identifier("this"),
                      paramsId
                    ]
                  )
                )
              ]
            ),
            new ExpressionStatement(
              new AssignmentExpression(
                new MemberExpression(
                  tempId,
                  new Identifier("prototype"),
                  false,
                  "."
                ),
                "=",
                new MemberExpression(
                  funcId,
                  new Identifier("prototype"),
                  false,
                  "."
                )
              )
            ),
            new ForInStatement(
              new VariableDeclaration(
                "var", [
                  new VariableDeclarator(
                    new Identifier("x")
                  )
                ]
              ),
              funcId,
              new BlockStatement([
                new ExpressionStatement(
                  new AssignmentExpression(
                    new MemberExpression(
                      tempId,
                      new Identifier("x"),
                      true
                    ), "=",
                    new MemberExpression(
                      funcId,
                      new Identifier("x"),
                      true
                    )
                  )
                )
              ])
            ),
            new ReturnStatement(
              tempId
            )
          ])
        ),
        new ReturnStatement(
          funcId
        )
      ])
    );
  }

  function stub(id, strName, stubName, thisId, params) {
    var tempId = new Identifier("t");
    var strId = new Identifier(strName);

    var stubParams = [strId, id];

    if (stubName === "stubF") {
      var paramArray = [];
      for (var i = 0, l = params.length; i < l; i++) {
        paramArray.push(new Literal(params[i].name));
      }
      stubParams.push(new ArrayExpression(paramArray));
    }

    if (!thisId) {
      thisId = new Identifier("this");
    }

    return new BlockStatement([
      new ExpressionStatement(
        new AssignmentExpression(
          id, "=",
          new CallExpression(
            new Identifier(stubName),
            stubParams
          )
        )
      ),
      new ExpressionStatement(
        new AssignmentExpression(
          strId, "=", new Identifier("null")
        )
      ),
      new ReturnStatement(
        new CallExpression(
          new MemberExpression(
            id,
            new Identifier("apply"),
            false,
            "."
          ),
          [thisId, new Identifier("arguments")]
        )
      )
    ]);
  }

  function passOverList(list, passFunction, o) {
    return list.map(function (node) {
      return node[passFunction](o);
    }).filter(function (node) {
      return node !== null;
    });
  }

  Node.prototype.lazyParsePass = T.makePass("lazyParsePass", "lazyParseNode");

  Program.prototype.lazyParsePass = function (o) {
    o.scope = this.frame;
    o = extend(o);
    o.laziness = new Laziness();

    this.body = passOverList(this.body, 'lazyParsePass', o);

    var strId, strDeclaration;
    for (var name in o.laziness.functionStrings) {
      strId = new Identifier(name, "variable");
      strDeclaration = new VariableDeclaration(
        "var",
        [new VariableDeclarator(strId, new Literal(o.laziness.functionStrings[name]), undefined)]
      );
      this.body.unshift(strDeclaration);
    }

    if (o.laziness.needsStub) {
      this.body.unshift(stubConstructor(o.scope.freshTemp(), o.scope.freshTemp()));
    }
    if (o.laziness.needsStubF) {
      this.body.unshift(stubFConstructor(o.scope.freshTemp(), o.scope.freshTemp(), o.scope.freshTemp()));
    }

    return this;
  };

  var curId = 0;
  FunctionExpression.prototype.lazyParsePass =
  FunctionDeclaration.prototype.lazyParsePass = function (o) {
    var childOpts = extend(o);
    childOpts.scope = this.frame;
    childOpts.laziness = new Laziness();
    this.body = this.body.lazyParsePass(childOpts);
    this.idNumber = curId++; // NOTE: this is AFTER parsing children
                             // (as is the post-order traversal in
                             // callGraph)

    var strId, strDeclaration;
    for (var name in childOpts.laziness.functionStrings) {
      strId = new Identifier(name, "variable");
      strDeclaration = new VariableDeclaration(
        "var",
        [new VariableDeclarator(strId, new Literal(childOpts.laziness.functionStrings[name]), undefined)]
      );
      if (this.body instanceof BlockStatement) {
        this.body.body.unshift(strDeclaration);
      } else {
        this.body = new BlockStatement([strDeclaration, this.body]);
      }
    }

    var stubNode;
    if (childOpts.laziness.needsStub) {
      stubNode = stubConstructor(o.scope.freshTemp(), o.scope.freshTemp());
      if (this.body instanceof BlockStatement) {
        this.body.body.unshift(stubNode);
      } else {
        this.body = new BlockStatement([stubNode, this.body]);
      }
    }
    if (childOpts.laziness.needsStubF) {
      stubNode = stubFConstructor(o.scope.freshTemp(), o.scope.freshTemp(), o.scope.freshTemp());
      if (this.body instanceof BlockStatement) {
        this.body.body.unshift(stubNode);
      } else {
        this.body = new BlockStatement([stubNode, this.body]);
      }
    }

    if (childOpts.laziness.isClosure) {
      o.laziness.isClosure = true;
    }

    if (this instanceof FunctionDeclaration) {
      var functionString = stringifyNode(this);
      if (shouldLazify(this, functionString.length)) {
        if (this.id instanceof Identifier && this.params) {
          for (var i = 0, l = this.params.length; i < l; i++) {
            var param = this.params[i];
            if (param instanceof Identifier && this.id.name === param.name) {
              return this;
            }
          }
        }

        var id = o.scope.freshTemp();
        if (childOpts.laziness.isClosure) {
          o.laziness.functionStrings[id.name] = '(' + functionString + ')';
          this.body = stub(this.id, id.name, "stub");
          o.laziness.needsStub = true;
        } else {
          functionString = stringifyNode(this.body);
          o.laziness.functionStrings[id.name] = functionString;
          this.body = stub(this.id, id.name, "stubF", null, this.params);
          o.laziness.needsStubF = true;
        }

        o.laziness.functionMap[this.id.name] = {mangled: id.name, isClosure: childOpts.laziness.isClosure, params: this.params};
      }
      return this;
    } else {
      this.isClosure = childOpts.laziness.isClosure;
      return this;
    }
  }

  Identifier.prototype.lazyParseNode = function (o) {
    if (this.name === "eval") {
      o.laziness.isClosure = true;
      return this;
    }
    if (!o.laziness.isClosure &&
        this.kind === "variable") {
      var scope = o.scope;
      var variable = scope.variables[this.name];
      var parentVar = scope.getVariable(this.name);

      if (!parentVar) {
        // Should be the identifier for a catch clause
        return this;
      }

      if (!variable && !parentVar.external) {
        o.laziness.isClosure = true;
      }
    }
    return this;
  }

  AssignmentExpression.prototype.lazyParseNode = function (o) {
    if (this.right instanceof FunctionExpression) {
      var oldId = this.right.id;
      this.right.id = null;
      var functionString = stringifyNode(this.right);
      if (shouldLazify(this.right, functionString.length)) {
        var id = o.scope.freshTemp();

        var thisId = new Identifier("this");
        if (this.left instanceof MemberExpression &&
            (!thisId instanceof MemberExpression && thisId.property instanceof Identifier && thisId.property.name == "prototype")) {
          // We just use this if assigning to a prototype
          thisId = this.left.object;
        }

        if (this.right.isClosure) {
          o.laziness.functionStrings[id.name] = '(' + functionString + ')';
          this.right.body = stub(this.left, id.name, "stub", thisId);
          o.laziness.needsStub = true;
        } else {
          o.laziness.functionStrings[id.name] = stringifyNode(this.right.body);
          this.right.body = stub(this.left, id.name, "stubF", thisId, this.right.params);
          o.laziness.needsStubF = true;
        }

        var funcName;
        if (this.left instanceof Identifier) {
          funcName = this.left.name;
        } else {
          funcName = id.name;
        }
        o.laziness.functionMap[funcName] = {mangled: id.name, isClosure: this.right.isClosure, params: this.right.params};
      } else {
        this.right.id = oldId;
      }
    }
    // else if (this.right instanceof Identifier) {
    //   this.right = resolve(this.right, o);
    // }

    return this;
  }

  CallExpression.prototype.lazyParseNode = function (o) {
    for (var i = 0, l = this.arguments.length; i < l; i++) {
      this.arguments[i] = resolve(this.arguments[i], o);
    }
  }

  function resolve(identifier, o) {
    if (identifier.variable && identifier.variable.type instanceof Types.ArrowType
       && o.laziness.functionMap[identifier.name]) {
      var functionEntry = o.laziness.functionMap[identifier.name];
      var strId = new Identifier(o.laziness.functionMap[identifier.name].mangled);

      var stubCall;
      if (functionEntry.isClosure) {
        stubCall = new CallExpression(
          new Identifier("stub"),
          [strId, identifier]
        );
      } else {
        var paramArray = [];
        for (var i = 0, l = functionEntry.params.length; i < l; i++) {
          paramArray.push(new Literal(functionEntry.params[i].name));
        }
        stubCall = new CallExpression(
          new Identifier("stubF"),
          [strId, identifier, new ArrayExpression(paramArray)]
        );
      }

      return new SequenceExpression([
        new AssignmentExpression(
          identifier, "=",
          stubCall
        ),
        new AssignmentExpression(
          strId, "=",
          new Identifier("null")
        ),
        identifier
      ]);
    } else {
      return identifier;
    }
  }

}).call(this, typeof exports === "undefined" ? (lazyParse = {}) : exports);
<commit_msg>Fixed namespace collisions in stubs<commit_after>(function (exports) {
  var util, T, escodegen, Types, uglify;
  if (typeof process !== "undefined") {
    util = require("./util.js");
    T = require("./estransform.js");
    escodegen = require("./escodegen.js");
    Types = require("./types.js");
    uglify = require("uglify-js");

    snarf = require('fs').readFileSync;
  } else {
    util = this.util;
    T = estransform;
    escodegen = this.escodegen;
    Types = this.Types;
    uglify = load("./uglify-js.js");
  }

  /**
   * Import AST nodes
   */
  const Node = T.Node;
  const Program = T.Program;
  const Literal = T.Literal;
  const Identifier = T.Identifier;
  const FunctionDeclaration = T.FunctionDeclaration;
  const FunctionExpression = T.FunctionExpression;
  const AssignmentExpression = T.AssignmentExpression;
  const ExpressionStatement = T.ExpressionStatement;
  const CallExpression = T.CallExpression;
  const VariableDeclaration = T.VariableDeclaration;
  const VariableDeclarator = T.VariableDeclarator;
  const BlockStatement = T.BlockStatement;
  const ReturnStatement = T.ReturnStatement;
  const MemberExpression = T.MemberExpression;
  const IfStatement = T.IfStatement;
  const BinaryExpression = T.BinaryExpression;
  const UnaryExpression = T.UnaryExpression;
  const SequenceExpression = T.SequenceExpression;
  const ArrayExpression = T.ArrayExpression;
  const ForInStatement = T.ForInStatement;

  /**
   * Import utilities.
   */
  const extend = util.extend;
  const assert = util.assert;

  var logger;
  var minReplaceLength;
  var callGraphAvailable;
  var callProfiling;

  exports.initialize = function (o, cmdLineOpts) {
    logger = o.logger;
    if (cmdLineOpts["lazy-minimum"] === true) {
      minReplaceLength = 0;
    } else {
      minReplaceLength = cmdLineOpts["lazy-minimum"];
    }

    callGraphAvailable = cmdLineOpts["call-graph"];

    if (cmdLineOpts["read-profile"] !== "") {
      var profileStr = snarf(cmdLineOpts["read-profile"]);
      callProfiling = new Uint8Array(JSON.parse(profileStr));
    }
  };

  function stringifyNode(node) {
    var s = escodegen.generate(node, {format: {indent: { style: '', base: 0}}});
    if (node instanceof BlockStatement) {
      return uglify('(function()' + s + ')')
        .replace(/^.*?\{/, '').replace(/\}\)$/, '');
    } else {
      return uglify('(' + s + ')')
        .replace(/^\(/, '').replace(/\)$/, '');
    }
  }

  /**
   * Begin rewrite pass
   */

  function shouldLazify(functionNode, length) {
    return (length > minReplaceLength &&
            (!callGraphAvailable || !functionNode.called) &&
            (typeof callProfiling === "undefined" || !callProfiling[functionNode.idNumber]));
  }

  function Laziness() {
    this.functionStrings = Object.create(null);
    this.functionMap = Object.create(null);
    this.isClosure = false;
    this.needsStub = false;
    this.needsStubF = false;
  }

  function stubConstructor(scope) {
    var strId = scope.freshTemp();
    var funcId = scope.freshTemp();
    var tempId = scope.freshTemp();
    var iterId = scope.freshTemp();
    return new FunctionDeclaration(
      new Identifier("stub"),
      [strId, funcId],
      new BlockStatement([
        new IfStatement(
          new BinaryExpression(
            "===",
            new UnaryExpression(
              "typeof",
              strId
            ),
            new Literal("string")
          ),
          new BlockStatement([
            new VariableDeclaration(
              "var", [
                new VariableDeclarator(
                  tempId,
                  new CallExpression(
                    new Identifier("eval"),
                    [strId]
                  )
                )
              ]
            ),
            new ExpressionStatement(
              new AssignmentExpression(
                new MemberExpression(
                  tempId,
                  new Identifier("prototype"),
                  false,
                  "."
                ),
                "=",
                new MemberExpression(
                  funcId,
                  new Identifier("prototype"),
                  false,
                  "."
                )
              )
            ),
            new ForInStatement(
              new VariableDeclaration(
                "var", [
                  new VariableDeclarator(
                    iterId
                  )
                ]
              ),
              funcId,
              new BlockStatement([
                new ExpressionStatement(
                  new AssignmentExpression(
                    new MemberExpression(
                      tempId,
                      iterId,
                      true
                    ), "=",
                    new MemberExpression(
                      funcId,
                      iterId,
                      true
                    )
                  )
                )
              ])
            ),
            new ReturnStatement(
              tempId
            )
          ])
        ),
        new ReturnStatement(
          funcId
        )
      ])
    );
  }

  function stubFConstructor(scope) {
    var strId = scope.freshTemp();
    var funcId = scope.freshTemp();
    var paramsId = scope.freshTemp();
    var tempId = scope.freshTemp();
    var iterId = scope.freshTemp();
    return new FunctionDeclaration(
      new Identifier("stubF"),
      [strId, funcId, paramsId],
      new BlockStatement([
        new IfStatement(
          new BinaryExpression(
            "===",
            new UnaryExpression(
              "typeof",
              strId
            ),
            new Literal("string")
          ),
          new BlockStatement([
            new ExpressionStatement(
              new CallExpression(
                new MemberExpression(
                  paramsId,
                  new Identifier("push"),
                  false, "."
                ),
                [strId]
              )
            ),
            new VariableDeclaration(
              "var", [
                new VariableDeclarator(
                  tempId,
                  new CallExpression(
                    new MemberExpression(
                      new Identifier("Function"),
                      new Identifier("apply"),
                      false, "."
                    ),
                    [
                      new Identifier("this"),
                      paramsId
                    ]
                  )
                )
              ]
            ),
            new ExpressionStatement(
              new AssignmentExpression(
                new MemberExpression(
                  tempId,
                  new Identifier("prototype"),
                  false,
                  "."
                ),
                "=",
                new MemberExpression(
                  funcId,
                  new Identifier("prototype"),
                  false,
                  "."
                )
              )
            ),
            new ForInStatement(
              new VariableDeclaration(
                "var", [
                  new VariableDeclarator(
                    iterId
                  )
                ]
              ),
              funcId,
              new BlockStatement([
                new ExpressionStatement(
                  new AssignmentExpression(
                    new MemberExpression(
                      tempId,
                      iterId,
                      true
                    ), "=",
                    new MemberExpression(
                      funcId,
                      iterId,
                      true
                    )
                  )
                )
              ])
            ),
            new ReturnStatement(
              tempId
            )
          ])
        ),
        new ReturnStatement(
          funcId
        )
      ])
    );
  }

  function stub(id, strName, stubName, thisId, params) {
    var tempId = new Identifier("t");
    var strId = new Identifier(strName);

    var stubParams = [strId, id];

    if (stubName === "stubF") {
      var paramArray = [];
      for (var i = 0, l = params.length; i < l; i++) {
        paramArray.push(new Literal(params[i].name));
      }
      stubParams.push(new ArrayExpression(paramArray));
    }

    if (!thisId) {
      thisId = new Identifier("this");
    }

    return new BlockStatement([
      new ExpressionStatement(
        new AssignmentExpression(
          id, "=",
          new CallExpression(
            new Identifier(stubName),
            stubParams
          )
        )
      ),
      new ExpressionStatement(
        new AssignmentExpression(
          strId, "=", new Identifier("null")
        )
      ),
      new ReturnStatement(
        new CallExpression(
          new MemberExpression(
            id,
            new Identifier("apply"),
            false,
            "."
          ),
          [thisId, new Identifier("arguments")]
        )
      )
    ]);
  }

  function passOverList(list, passFunction, o) {
    return list.map(function (node) {
      return node[passFunction](o);
    }).filter(function (node) {
      return node !== null;
    });
  }

  Node.prototype.lazyParsePass = T.makePass("lazyParsePass", "lazyParseNode");

  Program.prototype.lazyParsePass = function (o) {
    o.scope = this.frame;
    o = extend(o);
    o.laziness = new Laziness();

    this.body = passOverList(this.body, 'lazyParsePass', o);

    var strId, strDeclaration;
    for (var name in o.laziness.functionStrings) {
      strId = new Identifier(name, "variable");
      strDeclaration = new VariableDeclaration(
        "var",
        [new VariableDeclarator(strId, new Literal(o.laziness.functionStrings[name]), undefined)]
      );
      this.body.unshift(strDeclaration);
    }

    if (o.laziness.needsStub) {
      this.body.unshift(stubConstructor(o.scope));
    }
    if (o.laziness.needsStubF) {
      this.body.unshift(stubFConstructor(o.scope));
    }

    return this;
  };

  var curId = 0;
  FunctionExpression.prototype.lazyParsePass =
  FunctionDeclaration.prototype.lazyParsePass = function (o) {
    var childOpts = extend(o);
    childOpts.scope = this.frame;
    childOpts.laziness = new Laziness();
    this.body = this.body.lazyParsePass(childOpts);
    this.idNumber = curId++; // NOTE: this is AFTER parsing children
                             // (as is the post-order traversal in
                             // callGraph)

    var strId, strDeclaration;
    for (var name in childOpts.laziness.functionStrings) {
      strId = new Identifier(name, "variable");
      strDeclaration = new VariableDeclaration(
        "var",
        [new VariableDeclarator(strId, new Literal(childOpts.laziness.functionStrings[name]), undefined)]
      );
      if (this.body instanceof BlockStatement) {
        this.body.body.unshift(strDeclaration);
      } else {
        this.body = new BlockStatement([strDeclaration, this.body]);
      }
    }

    var stubNode;
    if (childOpts.laziness.needsStub) {
      stubNode = stubConstructor(o.scope);
      if (this.body instanceof BlockStatement) {
        this.body.body.unshift(stubNode);
      } else {
        this.body = new BlockStatement([stubNode, this.body]);
      }
    }
    if (childOpts.laziness.needsStubF) {
      stubNode = stubFConstructor(o.scope);
      if (this.body instanceof BlockStatement) {
        this.body.body.unshift(stubNode);
      } else {
        this.body = new BlockStatement([stubNode, this.body]);
      }
    }

    if (childOpts.laziness.isClosure) {
      o.laziness.isClosure = true;
    }

    if (this instanceof FunctionDeclaration) {
      var functionString = stringifyNode(this);
      if (shouldLazify(this, functionString.length)) {
        if (this.id instanceof Identifier && this.params) {
          for (var i = 0, l = this.params.length; i < l; i++) {
            var param = this.params[i];
            if (param instanceof Identifier && this.id.name === param.name) {
              return this;
            }
          }
        }

        var id = o.scope.freshTemp();
        if (childOpts.laziness.isClosure) {
          o.laziness.functionStrings[id.name] = '(' + functionString + ')';
          this.body = stub(this.id, id.name, "stub");
          o.laziness.needsStub = true;
        } else {
          functionString = stringifyNode(this.body);
          o.laziness.functionStrings[id.name] = functionString;
          this.body = stub(this.id, id.name, "stubF", null, this.params);
          o.laziness.needsStubF = true;
        }

        o.laziness.functionMap[this.id.name] = {mangled: id.name, isClosure: childOpts.laziness.isClosure, params: this.params};
      }
      return this;
    } else {
      this.isClosure = childOpts.laziness.isClosure;
      return this;
    }
  }

  Identifier.prototype.lazyParseNode = function (o) {
    if (this.name === "eval") {
      o.laziness.isClosure = true;
      return this;
    }
    if (!o.laziness.isClosure &&
        this.kind === "variable") {
      var scope = o.scope;
      var variable = scope.variables[this.name];
      var parentVar = scope.getVariable(this.name);

      if (!parentVar) {
        // Should be the identifier for a catch clause
        return this;
      }

      if (!variable && !parentVar.external) {
        o.laziness.isClosure = true;
      }
    }
    return this;
  }

  AssignmentExpression.prototype.lazyParseNode = function (o) {
    if (this.right instanceof FunctionExpression) {
      var oldId = this.right.id;
      this.right.id = null;
      var functionString = stringifyNode(this.right);
      if (shouldLazify(this.right, functionString.length)) {
        var id = o.scope.freshTemp();

        var thisId = new Identifier("this");
        if (this.left instanceof MemberExpression &&
            (!thisId instanceof MemberExpression && thisId.property instanceof Identifier && thisId.property.name == "prototype")) {
          // We just use this if assigning to a prototype
          thisId = this.left.object;
        }

        if (this.right.isClosure) {
          o.laziness.functionStrings[id.name] = '(' + functionString + ')';
          this.right.body = stub(this.left, id.name, "stub", thisId);
          o.laziness.needsStub = true;
        } else {
          o.laziness.functionStrings[id.name] = stringifyNode(this.right.body);
          this.right.body = stub(this.left, id.name, "stubF", thisId, this.right.params);
          o.laziness.needsStubF = true;
        }

        var funcName;
        if (this.left instanceof Identifier) {
          funcName = this.left.name;
        } else {
          funcName = id.name;
        }
        o.laziness.functionMap[funcName] = {mangled: id.name, isClosure: this.right.isClosure, params: this.right.params};
      } else {
        this.right.id = oldId;
      }
    }
    // else if (this.right instanceof Identifier) {
    //   this.right = resolve(this.right, o);
    // }

    return this;
  }

  CallExpression.prototype.lazyParseNode = function (o) {
    for (var i = 0, l = this.arguments.length; i < l; i++) {
      this.arguments[i] = resolve(this.arguments[i], o);
    }
  }

  function resolve(identifier, o) {
    if (identifier.variable && identifier.variable.type instanceof Types.ArrowType
       && o.laziness.functionMap[identifier.name]) {
      var functionEntry = o.laziness.functionMap[identifier.name];
      var strId = new Identifier(o.laziness.functionMap[identifier.name].mangled);

      var stubCall;
      if (functionEntry.isClosure) {
        stubCall = new CallExpression(
          new Identifier("stub"),
          [strId, identifier]
        );
      } else {
        var paramArray = [];
        for (var i = 0, l = functionEntry.params.length; i < l; i++) {
          paramArray.push(new Literal(functionEntry.params[i].name));
        }
        stubCall = new CallExpression(
          new Identifier("stubF"),
          [strId, identifier, new ArrayExpression(paramArray)]
        );
      }

      return new SequenceExpression([
        new AssignmentExpression(
          identifier, "=",
          stubCall
        ),
        new AssignmentExpression(
          strId, "=",
          new Identifier("null")
        ),
        identifier
      ]);
    } else {
      return identifier;
    }
  }

}).call(this, typeof exports === "undefined" ? (lazyParse = {}) : exports);
<|endoftext|>