<commit_before>/*
 * 	Copyright (C) 2012-2013 DFKI GmbH
 * 	Deutsches Forschungszentrum fuer Kuenstliche Intelligenz
 * 	German Research Center for Artificial Intelligence
 * 	http://www.dfki.de
 *
 * 	Permission is hereby granted, free of charge, to any person obtaining a
 * 	copy of this software and associated documentation files (the
 * 	"Software"), to deal in the Software without restriction, including
 * 	without limitation the rights to use, copy, modify, merge, publish,
 * 	distribute, sublicense, and/or sell copies of the Software, and to
 * 	permit persons to whom the Software is furnished to do so, subject to
 * 	the following conditions:
 *
 * 	The above copyright notice and this permission notice shall be included
 * 	in all copies or substantial portions of the Software.
 *
 * 	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 * 	OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * 	MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * 	IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 * 	CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 * 	TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
 * 	SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

define(['mmirf/core', 'mmirf/env', 'mmirf/util/deferred', 'mmirf/constants', 'mmirf/commonUtils', 'mmirf/configurationManager', 'mmirf/languageManager'
     , 'mmirf/controllerManager', 'mmirf/modelManager'
     , 'mmirf/presentationManager', 'mmirf/inputManager', 'mmirf/dialogManager', 'module'
     , 'mmirf/semanticInterpreter', 'mmirf/mediaManager', 'mmirf/notificationManager'
  ],
  /**
   * Initializes the MMIR framework:
   * triggers {@link mmir.ready} when initialization has finished.
   *
   * @class
   * @name main
   * @memberof mmir
   * @private
   *
   * @requires require.config
   * @requires util/deferred
   *
   */
  function(mmir, env, deferred, constants, commonUtils, configurationManager, languageManager
	 , controllerManager, modelManager
     , presentationManager, inputManager, dialogManager, module
     , semanticInterpreter, mediaManager, notificationManager
){
	/**
	 * @private
	 * @memberOf mmir */
	var isInit = false;

	//export framework functions/objects:

	/** @memberOf mmir */
	mmir.const = constants;
	/** @memberOf mmir */
	mmir.util = commonUtils;
	/** @memberOf mmir */
	mmir.conf = configurationManager;
	/** @memberOf mmir */
	mmir.notifier = notificationManager.init();

	/**
	 * HELPER create a "namespace" from a package-definition (dot-separated string) from configuration
	 *        or return the global namespace, if there is not config-value
	 * @param {String|Array<String>} configuration name
	 *
	 * @private
	 * @memberOf main
	 */
	var getContextFor = function(ctxConfigName){
		var ctxName = configurationManager.get(ctxConfigName);
		if(ctxName){
			var namespaces = ctxName.split('.');
			var ctx = window, name;
			for(var i=0, size= namespaces.length; i < size; ++i){
				name = namespaces[i];
				if(!ctx[name]){
					ctx[name] = {};
				}
				ctx = ctx[name];
			}
			return ctx;
		}
		return ctx;
	}

	//the context where the controller implementation can be found (default: global context, i.e. window)
	/** @memberOf main */
	var ctrlImplCtx = getContextFor('controllerContext');
	//the context where the model implementations can be found (default: global context, i.e. window)
	/** @memberOf main */
	var modelImplCtx = getContextFor('modelContext');

	/**
	 * Main Initialization:
	 * initializes mmir and exports its functions/modules to (gobal) mmir namespace
	 *
	 * @memberOf main
	 */
	var mainInit = function(){

//		console.log('dom ready');

		//initialize the common-utils:
		commonUtils.init()//<- load directory structure

			//load plugins (if in CORDOVA environment)
			.then(function() {

				return languageManager.init().then(function(langMng){
					mmir.lang = langMng;
				});

			})
			// start the ControllerManager
			.then(function() {

				mmir.ctrl = controllerManager;
				//NOTE: this also gathers information on which
				//      views, layouts etc. are available
				//      -> the presentationManager depends on this information
				return controllerManager.init(ctrlImplCtx);
			})

			//TEST parallelized loading of independent modules:
			.then(function(){

				/** @memberOf main */
				var isMediaManagerLoaded 	= false;
				/** @memberOf main */
				var isModelsLoaded 			= false;
				/** @memberOf main */
				var isVisualsLoaded 		= false;
				/** @memberOf main */
				var isInputManagerLoaded 	= false;
				/** @memberOf main */
				var isDialogManagerLoaded 	= false;
				/** @memberOf main */
				var isSemanticsLoaded       = false;

				/** @memberOf main */
				var checkInitCompleted = function(){

					if(			isMediaManagerLoaded
							&&	isModelsLoaded
							&& 	isVisualsLoaded
							&&	isInputManagerLoaded
							&&	isDialogManagerLoaded
							&&	isSemanticsLoaded
					){

						/**
						 * Additional configuration for requirejs
						 * from configuration.json:
						 *  -> if property "config" is set, apply it as requirejs-config
						 *     before signaling READY
						 *  EXAMPLE:
						 *  the following entry (in config/configuration.json) would add
						 *  the dependency information for www/appjs/test.js as module "testConf"
						 *
						 * 	, "config": {
						 *     	"paths": {
						 *     		"testConf": "../appjs/test"
						 *     	}
						 *     }
						 *
						 * @type PlainObject
						 * @memberOf main
						 */
						var requireConfig = configurationManager.get('config');
						if(requireConfig){
							mmir.require = require.config(requireConfig);
						}

						//"give signal" that the framework is now initialized / ready
						mmir.setInitialized();
					}
				};

				mmir.semantic = semanticInterpreter;
				/** ID for the grammar engine/compiler to be used, if/when JSON grammar are (re-) compiled
				 * @see mmir.SemanticInterpreter#setGrammarEngine
				 * @type String
				 * @memberOf main */
				var grammarEngine = configurationManager.get('grammarCompiler');
				if(grammarEngine){
					semanticInterpreter.setGrammarEngine(grammarEngine);
				}
				/** set synchronous/asynchronous compile-mode for grammar compilation
				 * @see mmir.SemanticInterpreter#setEngineCompileMode
				 * @type Boolean
				 * @memberOf main */
				var grammarCompileMode = configurationManager.get('grammarAsyncCompileMode');
				if(typeof grammarCompileMode !== 'undefined'){
					semanticInterpreter.setEngineCompileMode(grammarCompileMode);
				}

				//TODO impl. automated sync/async loading&execution for compiled grammars
//				var grammarExecMode = configurationManager.get('grammarExecMode');
//				if(typeof grammarExecMode !== 'undefined'){
//					semanticInterpreter.setGrammarExecMode(grammarExecMode);//TODO add async-loaded grammars to ignoreGrammarFiles-list (to prevent loading them in "sync-exec mode")
//				}

				/** list of grammar IDs which should not be loaded, even if there is a compiled grammar available:
				 * @type String
				 * @memberOf main
				 */
				var ignoreGrammarIds = configurationManager.get('ignoreGrammarFiles', void(0));

				commonUtils.loadCompiledGrammars(constants.getGeneratedGrammarsPath(), void(0), ignoreGrammarIds).then(function() {

					isSemanticsLoaded = true;
					checkInitCompleted();
				});

				// start the MediaManager
				mediaManager.init().then(function() {
					isMediaManagerLoaded = true;

					//initialize BEEP notification (after MediaManager was initialized)
					notificationManager.initBeep();

					mmir.media = mediaManager;
					checkInitCompleted();
				});

				//TODO models may access views etc. during their initialization
				//	   --> there should be a way to configure startup, so that models may only be loaded, after everything else was loaded
				modelManager.init(modelImplCtx).then(function(){
					isModelsLoaded = true;
					mmir.model = modelManager;
					checkInitCompleted();
				});

				presentationManager.init().then(function(){

					isVisualsLoaded = true;

					mmir.presentation = presentationManager;
					checkInitCompleted();

				}, function error(err){ console.error('Failed initializing PresentationManager: '+err); });
				//TODO handle reject/fail of the presentationManager's init-Promise!

				dialogManager.init().then(function(res){//_dlgMng, _dialogEngine){
					isDialogManagerLoaded = true;
					mmir.dialog = res.manager;
					mmir.dialogEngine = res.engine;
					checkInitCompleted();
				});

				inputManager.init().then(function(res){//_inputMng, _inputEngine){
					isInputManagerLoaded = true;
					mmir.input = res.manager;
					mmir.inputEngine  = res.engine;
					checkInitCompleted();
				});

			});

	};//END: mainInit(){...

	mainInit();

	return mmir;

});//END: define(...
<commit_msg>BUGFIX mmir.present: use documented reference name (instead of mmir.presentation)<commit_after>/*
 * 	Copyright (C) 2012-2013 DFKI GmbH
 * 	Deutsches Forschungszentrum fuer Kuenstliche Intelligenz
 * 	German Research Center for Artificial Intelligence
 * 	http://www.dfki.de
 *
 * 	Permission is hereby granted, free of charge, to any person obtaining a
 * 	copy of this software and associated documentation files (the
 * 	"Software"), to deal in the Software without restriction, including
 * 	without limitation the rights to use, copy, modify, merge, publish,
 * 	distribute, sublicense, and/or sell copies of the Software, and to
 * 	permit persons to whom the Software is furnished to do so, subject to
 * 	the following conditions:
 *
 * 	The above copyright notice and this permission notice shall be included
 * 	in all copies or substantial portions of the Software.
 *
 * 	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 * 	OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * 	MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * 	IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 * 	CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 * 	TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
 * 	SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

define(['mmirf/core', 'mmirf/env', 'mmirf/util/deferred', 'mmirf/constants', 'mmirf/commonUtils', 'mmirf/configurationManager', 'mmirf/languageManager'
     , 'mmirf/controllerManager', 'mmirf/modelManager'
     , 'mmirf/presentationManager', 'mmirf/inputManager', 'mmirf/dialogManager', 'module'
     , 'mmirf/semanticInterpreter', 'mmirf/mediaManager', 'mmirf/notificationManager'
  ],
  /**
   * Initializes the MMIR framework:
   * triggers {@link mmir.ready} when initialization has finished.
   *
   * @class
   * @name main
   * @memberof mmir
   * @private
   *
   * @requires require.config
   * @requires util/deferred
   *
   */
  function(mmir, env, deferred, constants, commonUtils, configurationManager, languageManager
	 , controllerManager, modelManager
     , presentationManager, inputManager, dialogManager, module
     , semanticInterpreter, mediaManager, notificationManager
){
	/**
	 * @private
	 * @memberOf mmir */
	var isInit = false;

	//export framework functions/objects:

	/** @memberOf mmir */
	mmir.const = constants;
	/** @memberOf mmir */
	mmir.util = commonUtils;
	/** @memberOf mmir */
	mmir.conf = configurationManager;
	/** @memberOf mmir */
	mmir.notifier = notificationManager.init();

	/**
	 * HELPER create a "namespace" from a package-definition (dot-separated string) from configuration
	 *        or return the global namespace, if there is not config-value
	 * @param {String|Array<String>} configuration name
	 *
	 * @private
	 * @memberOf main
	 */
	var getContextFor = function(ctxConfigName){
		var ctxName = configurationManager.get(ctxConfigName);
		if(ctxName){
			var namespaces = ctxName.split('.');
			var ctx = window, name;
			for(var i=0, size= namespaces.length; i < size; ++i){
				name = namespaces[i];
				if(!ctx[name]){
					ctx[name] = {};
				}
				ctx = ctx[name];
			}
			return ctx;
		}
		return ctx;
	}

	//the context where the controller implementation can be found (default: global context, i.e. window)
	/** @memberOf main */
	var ctrlImplCtx = getContextFor('controllerContext');
	//the context where the model implementations can be found (default: global context, i.e. window)
	/** @memberOf main */
	var modelImplCtx = getContextFor('modelContext');

	/**
	 * Main Initialization:
	 * initializes mmir and exports its functions/modules to (gobal) mmir namespace
	 *
	 * @memberOf main
	 */
	var mainInit = function(){

//		console.log('dom ready');

		//initialize the common-utils:
		commonUtils.init()//<- load directory structure

			//load plugins (if in CORDOVA environment)
			.then(function() {

				return languageManager.init().then(function(langMng){
					mmir.lang = langMng;
				});

			})
			// start the ControllerManager
			.then(function() {

				mmir.ctrl = controllerManager;
				//NOTE: this also gathers information on which
				//      views, layouts etc. are available
				//      -> the presentationManager depends on this information
				return controllerManager.init(ctrlImplCtx);
			})

			//TEST parallelized loading of independent modules:
			.then(function(){

				/** @memberOf main */
				var isMediaManagerLoaded 	= false;
				/** @memberOf main */
				var isModelsLoaded 			= false;
				/** @memberOf main */
				var isVisualsLoaded 		= false;
				/** @memberOf main */
				var isInputManagerLoaded 	= false;
				/** @memberOf main */
				var isDialogManagerLoaded 	= false;
				/** @memberOf main */
				var isSemanticsLoaded       = false;

				/** @memberOf main */
				var checkInitCompleted = function(){

					if(			isMediaManagerLoaded
							&&	isModelsLoaded
							&& 	isVisualsLoaded
							&&	isInputManagerLoaded
							&&	isDialogManagerLoaded
							&&	isSemanticsLoaded
					){

						/**
						 * Additional configuration for requirejs
						 * from configuration.json:
						 *  -> if property "config" is set, apply it as requirejs-config
						 *     before signaling READY
						 *  EXAMPLE:
						 *  the following entry (in config/configuration.json) would add
						 *  the dependency information for www/appjs/test.js as module "testConf"
						 *
						 * 	, "config": {
						 *     	"paths": {
						 *     		"testConf": "../appjs/test"
						 *     	}
						 *     }
						 *
						 * @type PlainObject
						 * @memberOf main
						 */
						var requireConfig = configurationManager.get('config');
						if(requireConfig){
							mmir.require = require.config(requireConfig);
						}

						//"give signal" that the framework is now initialized / ready
						mmir.setInitialized();
					}
				};

				mmir.semantic = semanticInterpreter;
				/** ID for the grammar engine/compiler to be used, if/when JSON grammar are (re-) compiled
				 * @see mmir.SemanticInterpreter#setGrammarEngine
				 * @type String
				 * @memberOf main */
				var grammarEngine = configurationManager.get('grammarCompiler');
				if(grammarEngine){
					semanticInterpreter.setGrammarEngine(grammarEngine);
				}
				/** set synchronous/asynchronous compile-mode for grammar compilation
				 * @see mmir.SemanticInterpreter#setEngineCompileMode
				 * @type Boolean
				 * @memberOf main */
				var grammarCompileMode = configurationManager.get('grammarAsyncCompileMode');
				if(typeof grammarCompileMode !== 'undefined'){
					semanticInterpreter.setEngineCompileMode(grammarCompileMode);
				}

				//TODO impl. automated sync/async loading&execution for compiled grammars
//				var grammarExecMode = configurationManager.get('grammarExecMode');
//				if(typeof grammarExecMode !== 'undefined'){
//					semanticInterpreter.setGrammarExecMode(grammarExecMode);//TODO add async-loaded grammars to ignoreGrammarFiles-list (to prevent loading them in "sync-exec mode")
//				}

				/** list of grammar IDs which should not be loaded, even if there is a compiled grammar available:
				 * @type String
				 * @memberOf main
				 */
				var ignoreGrammarIds = configurationManager.get('ignoreGrammarFiles', void(0));

				commonUtils.loadCompiledGrammars(constants.getGeneratedGrammarsPath(), void(0), ignoreGrammarIds).then(function() {

					isSemanticsLoaded = true;
					checkInitCompleted();
				});

				// start the MediaManager
				mediaManager.init().then(function() {
					isMediaManagerLoaded = true;

					//initialize BEEP notification (after MediaManager was initialized)
					notificationManager.initBeep();

					mmir.media = mediaManager;
					checkInitCompleted();
				});

				//TODO models may access views etc. during their initialization
				//	   --> there should be a way to configure startup, so that models may only be loaded, after everything else was loaded
				modelManager.init(modelImplCtx).then(function(){
					isModelsLoaded = true;
					mmir.model = modelManager;
					checkInitCompleted();
				});

				presentationManager.init().then(function(){

					isVisualsLoaded = true;

					mmir.present = presentationManager;
					checkInitCompleted();

				}, function error(err){ console.error('Failed initializing PresentationManager: '+err); });
				//TODO handle reject/fail of the presentationManager's init-Promise!

				dialogManager.init().then(function(res){//_dlgMng, _dialogEngine){
					isDialogManagerLoaded = true;
					mmir.dialog = res.manager;
					mmir.dialogEngine = res.engine;
					checkInitCompleted();
				});

				inputManager.init().then(function(res){//_inputMng, _inputEngine){
					isInputManagerLoaded = true;
					mmir.input = res.manager;
					mmir.inputEngine  = res.engine;
					checkInitCompleted();
				});

			});

	};//END: mainInit(){...

	mainInit();

	return mmir;

});//END: define(...
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2012 Randy Edmunds, Adobe Systems Incorporated. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 */

/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */
/*global define, brackets, $, Mustache, CodeMirror, _showShortcuts */

define(function (require, exports, module) {
    "use strict";

    // Brackets modules
    var CommandManager      = brackets.getModule("command/CommandManager"),
        DocumentManager     = brackets.getModule("document/DocumentManager"),
        EditorManager       = brackets.getModule("editor/EditorManager"),
        ExtensionUtils      = brackets.getModule("utils/ExtensionUtils"),
        KeyBindingManager   = brackets.getModule("command/KeyBindingManager"),
        Menus               = brackets.getModule("command/Menus"),
        PanelManager        = brackets.getModule("view/PanelManager"),
        PreferencesManager  = brackets.getModule("preferences/PreferencesManager");

    var panelHtml           = require("text!templates/bottom-panel.html"),
        shortcutsHtml       = require("text!templates/shortcut-table.html"),
        TOGGLE_SHORTCUTS_ID = "redmunds.show-shortcuts.view.shortcuts",
        keyList = [],
        loaded = false,
        panel,
        togglePanelShortcut = "Ctrl-Shift-/",
        $filterField,
        currentFilter;

    var sortByBase = 1,
        sortByBinding = 2,
        sortByCmdId = 3,
        sortByCmdName = 4,
        sortByOrig = 5,
        sortColumn = sortByBase,
        sortAscending = true;

    var origBrackets = "Brackets",
        origCodeMirror = "CodeMirror",
        origExtension = "Extension";

    // Determine base key by stripping modifier keys
    function _getBaseKey(keyBinding) {
        var keyBase = keyBinding
            .replace(/Ctrl-/, "")
            .replace(/Shift-/, "")
            .replace(/Alt-/, "");
        if (brackets.platform === "mac") {
            keyBase = keyBase.replace(/Cmd-/, "");
        }
        return keyBase;
    }

    function _findKeyBinding(kl, keyBinding) {
        var j;
        for (j = 0; j < kl.length; j++) {
            if (keyBinding === kl[j].keyBinding) {
                return j;
            }
        }
        return -1;
    }

    function _ucFirst(string) {
        return string.charAt(0).toUpperCase() + string.slice(1);
    }

    // "ReloadInBrowser" => "Reload In Browser"
    // "extension_manager" => "Extension Manager"
    function _humanizeString(string) {
        // Replace "foo_bar" with "foo bar" and "FooBar" with " Foo Bar"
        string = string.replace(/_/g, " ").replace(/([A-Z])/g, " $1");
        // Trim whitespace
        string = string.replace(/(^\s+)/, "").replace(/(\s+$)/, "");
        // Split words by whitespace, uppercase the first letter, join with a space
        string = string.split(/\s+/).map(_ucFirst).join(" ");

        return string;
    }

    function _getOriginFromCommandId(cmdID) {
        // According to CommandManager.register() documentation:
        //  Core commands in Brackets use a simple command title as an id, for example "open.file".
        //  Extensions should use the following format: "author.myextension.mycommandname".
        //  For example, "lschmitt.csswizard.format.css".
        var idArray = cmdID.split(".");
        if (idArray.length > 2) {
            // more than two qualifiers
            return origExtension + " (" + _humanizeString(idArray[1]) + ")";
        } else if (idArray.length < 2) {
            // less than two qualifiers
            return origExtension;
        }

        // check for a brackets menu
        var q1 = idArray[0].toLowerCase();
        if (q1 === "file" || q1 === "edit" || q1 === "view" || q1 === "navigate" || q1 === "debug" || q1 === "help") {
            return origBrackets;
        }

        // must be an extension
        return origExtension;
    }

    // CodeMirror and Brackets key maps have different formats, so collect
    // keys into a normalized array
    function _getkeyList() {
        var i,
            base,
            command,
            key,
            id;

        // Brackets keymap
        var bracketsKeymap = KeyBindingManager.getKeymap();
        if (bracketsKeymap) {
            for (i in bracketsKeymap) {
                if (bracketsKeymap.hasOwnProperty(i)) {
                    key = bracketsKeymap[i];
                    if (key) {
                        id = "shortcuts-" + key.commandID.replace(/\./g, "");
                        base = _getBaseKey(i);
                        command = CommandManager.get(key.commandID);
                        keyList.push({
                            id: id,
                            keyBase: base,
                            keyBinding: i,
                            commandID: key.commandID,
                            commandName: command.getName(),
                            origin: _getOriginFromCommandId(key.commandID),
                            filter: command.getName().toLowerCase()
                        });
                    }
                }
            }
        }

        // CodeMirror keymap
        if (CodeMirror.keyMap) {
            var cmKeymap = (brackets.platform === "mac")
                ? CodeMirror.keyMap.macDefault : CodeMirror.keyMap.pcDefault;
            if (cmKeymap) {
                for (i in cmKeymap) {
                    // Note that we only ignore CodeMirror duplicates, but
                    // we want to see Brackets & Extensions duplicates
                    if (cmKeymap.hasOwnProperty(i) &&
                            (i !== "fallthrough") &&
                            (_findKeyBinding(keyList, i) === -1)) {
                        base = _getBaseKey(i);
                        id = "shortcuts-" + cmKeymap[i].replace(/\./g, "");
                        keyList.push({
                            id: id,
                            keyBase: base,
                            keyBinding: i,
                            commandID: cmKeymap[i],
                            commandName: cmKeymap[i],
                            origin: origCodeMirror,
                            filter: cmKeymap[i].toLowerCase()
                        });
                    }
                }
            }
        }

        return keyList;
    }

    function _strcmp(a, b) {
        if (a < b) {
            return (sortAscending ? -1 : 1);
        } else if (a > b) {
            return (sortAscending ? 1 : -1);
        }
        return 0;
    }

    function _stricmp(a, b) {
        return _strcmp(a.toLowerCase(), b.toLowerCase());
    }

    function _keyBaseSort(a, b) {
        // First sort by whether it's a single char or not, so letters are separated from key
        // names (e.g. Backspace). Then sort by base key, finally key binding string
        var a2 = ((a.keyBase.length === 1) ? "0" : "1") + a.keyBase,
            b2 = ((b.keyBase.length === 1) ? "0" : "1") + b.keyBase,
            c = _strcmp(a2, b2);

        if (c !== 0) {
            return c;
        } else {
            return _strcmp(a.keyBinding, b.keyBinding);
        }
    }

    function _keyBindingSort(a, b) {
        return _strcmp(a.keyBinding, b.keyBinding);
    }

    function _keyCmdIdSort(a, b) {
        return _stricmp(a.commandID, b.commandID);
    }

    function _keyCmdNameSort(a, b) {
        return _strcmp(a.commandName, b.commandName);
    }

    function _keyOrigSort(a, b) {
        return _strcmp(a.origin, b.origin);
    }

    function _getSortFunc() {
        if (sortColumn === sortByBinding) {
            return _keyBindingSort;
        } else if (sortColumn === sortByCmdId) {
            return _keyCmdIdSort;
        } else if (sortColumn === sortByCmdName) {
            return _keyCmdNameSort;
        } else if (sortColumn === sortByOrig) {
            return _keyOrigSort;
        }
        return _keyBaseSort;
    }

    function _getShortcutsHtml() {
        var msData = {};
        msData.keyList = keyList.sort(_getSortFunc());
        return Mustache.render(shortcutsHtml, msData);
    }

    function _changeSorting(newSortColumn) {
        if (newSortColumn === sortColumn) {
            // Same column, so change sort direction
            sortAscending = !sortAscending;
        } else {
            // New sort column
            sortColumn = newSortColumn;
        }

        // Update page
        _showShortcuts();
    }

    function _filterShortcuts(forceFiltering) {
        var terms = $filterField.val().trim().toLocaleLowerCase();
        if (forceFiltering || terms !== currentFilter) {
            currentFilter = terms;
            terms = terms.split(/\s+?/);
            $.each(keyList, function (i, key) {
                var match;
                if (terms === "") {
                    match = true;
                } else {
                    $.each(terms, function (i, term) {
                        if (match !== false) {
                            match = key.filter.indexOf(term) > -1;
                        }
                    });
                }
                key.filterMatch = match;
            });
        }
    }

    function _showShortcuts() {
        var $shortcuts = $("#shortcuts");

        // Apply any active filter
        _filterShortcuts(true);

        // Add new markup
        $shortcuts.find(".resizable-content").html(_getShortcutsHtml());
        $shortcuts.find("thead th").eq(sortColumn - 1).addClass('sort-' + (sortAscending ? 'ascending' : 'descending'));

        // Setup header sort buttons
        $("thead .shortcut-base a", $shortcuts).on("click", function () {
            _changeSorting(sortByBase);
        });
        $("thead .shortcut-binding a", $shortcuts).on("click", function () {
            _changeSorting(sortByBinding);
        });
        $("thead .shortcut-cmd-id a", $shortcuts).on("click", function () {
            _changeSorting(sortByCmdId);
        });
        $("thead .shortcut-cmd-name a", $shortcuts).on("click", function () {
            _changeSorting(sortByCmdName);
        });
        $("thead .shortcut-orig a", $shortcuts).on("click", function () {
            _changeSorting(sortByOrig);
        });
    }

    function _handleShowHideShortcuts() {
        if (panel.isVisible()) {
            // This panel probably won't get opened very often, so only maintain data
            // while panel is open (for faster sorting) and discard when closed.
            keyList = [];
            panel.hide();
            CommandManager.get(TOGGLE_SHORTCUTS_ID).setChecked(false);
            EditorManager.focusEditor();
        } else {
            panel.show();
            CommandManager.get(TOGGLE_SHORTCUTS_ID).setChecked(true);
            $filterField.val("").focus();

            // Only get data once while panel is open
            if (keyList.length === 0) {
                keyList = _getkeyList();
            }
            _showShortcuts();
        }
        EditorManager.resizeEditor();
    }

    function _copyTableToCurrentDoc() {

        var editor = EditorManager.getCurrentFullEditor();
        if (!editor) {
            return;
        }

        var instance = editor._codeMirror;
        if (!instance) {
            return;
        }

        var start = instance.getCursor(true),
            end   = instance.getCursor(false);

        instance.replaceRange(_getShortcutsHtml(), start, end);
    }

    function init() {
        var $shortcutsPanel,
            $shortcutsContent,
            s,
            view_menu;

        ExtensionUtils.loadStyleSheet(module, "shortcuts.css");

        // Register function as command
        CommandManager.register("Show Shortcuts", TOGGLE_SHORTCUTS_ID, _handleShowHideShortcuts);

        // Add command to View menu, if it exists
        view_menu = Menus.getMenu(Menus.AppMenuBar.VIEW_MENU);
        if (view_menu) {
            view_menu.addMenuItem(TOGGLE_SHORTCUTS_ID, togglePanelShortcut);
        }

        // Add the HTML UI
        s = Mustache.render(panelHtml);

        // AppInit.htmlReady() has already executed before extensions are loaded
        // so, for now, we need to call this ourself
        panel = PanelManager.createBottomPanel(TOGGLE_SHORTCUTS_ID, $(s), 100);
        panel.hide();

        $shortcutsPanel = $("#shortcuts");
        $shortcutsContent = $shortcutsPanel.find(".resizable-content");

        $shortcutsPanel.find(".copy-table").click(function () {
            _copyTableToCurrentDoc();
        });

        $shortcutsPanel.find(".shortcuts-close").click(function () {
            CommandManager.execute(TOGGLE_SHORTCUTS_ID);
        });

        $filterField = $shortcutsPanel.find(".toolbar .filter");
        $filterField.on("keyup", _showShortcuts);
    }

    init();
});
<commit_msg>Remove keyList key ID that's redundant after filtering refactoring<commit_after>/*
 * Copyright (c) 2012 Randy Edmunds, Adobe Systems Incorporated. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 */

/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */
/*global define, brackets, $, Mustache, CodeMirror, _showShortcuts */

define(function (require, exports, module) {
    "use strict";

    // Brackets modules
    var CommandManager      = brackets.getModule("command/CommandManager"),
        DocumentManager     = brackets.getModule("document/DocumentManager"),
        EditorManager       = brackets.getModule("editor/EditorManager"),
        ExtensionUtils      = brackets.getModule("utils/ExtensionUtils"),
        KeyBindingManager   = brackets.getModule("command/KeyBindingManager"),
        Menus               = brackets.getModule("command/Menus"),
        PanelManager        = brackets.getModule("view/PanelManager"),
        PreferencesManager  = brackets.getModule("preferences/PreferencesManager");

    var panelHtml           = require("text!templates/bottom-panel.html"),
        shortcutsHtml       = require("text!templates/shortcut-table.html"),
        TOGGLE_SHORTCUTS_ID = "redmunds.show-shortcuts.view.shortcuts",
        keyList = [],
        loaded = false,
        panel,
        togglePanelShortcut = "Ctrl-Shift-/",
        $filterField,
        currentFilter;

    var sortByBase = 1,
        sortByBinding = 2,
        sortByCmdId = 3,
        sortByCmdName = 4,
        sortByOrig = 5,
        sortColumn = sortByBase,
        sortAscending = true;

    var origBrackets = "Brackets",
        origCodeMirror = "CodeMirror",
        origExtension = "Extension";

    // Determine base key by stripping modifier keys
    function _getBaseKey(keyBinding) {
        var keyBase = keyBinding
            .replace(/Ctrl-/, "")
            .replace(/Shift-/, "")
            .replace(/Alt-/, "");
        if (brackets.platform === "mac") {
            keyBase = keyBase.replace(/Cmd-/, "");
        }
        return keyBase;
    }

    function _findKeyBinding(kl, keyBinding) {
        var j;
        for (j = 0; j < kl.length; j++) {
            if (keyBinding === kl[j].keyBinding) {
                return j;
            }
        }
        return -1;
    }

    function _ucFirst(string) {
        return string.charAt(0).toUpperCase() + string.slice(1);
    }

    // "ReloadInBrowser" => "Reload In Browser"
    // "extension_manager" => "Extension Manager"
    function _humanizeString(string) {
        // Replace "foo_bar" with "foo bar" and "FooBar" with " Foo Bar"
        string = string.replace(/_/g, " ").replace(/([A-Z])/g, " $1");
        // Trim whitespace
        string = string.replace(/(^\s+)/, "").replace(/(\s+$)/, "");
        // Split words by whitespace, uppercase the first letter, join with a space
        string = string.split(/\s+/).map(_ucFirst).join(" ");

        return string;
    }

    function _getOriginFromCommandId(cmdID) {
        // According to CommandManager.register() documentation:
        //  Core commands in Brackets use a simple command title as an id, for example "open.file".
        //  Extensions should use the following format: "author.myextension.mycommandname".
        //  For example, "lschmitt.csswizard.format.css".
        var idArray = cmdID.split(".");
        if (idArray.length > 2) {
            // more than two qualifiers
            return origExtension + " (" + _humanizeString(idArray[1]) + ")";
        } else if (idArray.length < 2) {
            // less than two qualifiers
            return origExtension;
        }

        // check for a brackets menu
        var q1 = idArray[0].toLowerCase();
        if (q1 === "file" || q1 === "edit" || q1 === "view" || q1 === "navigate" || q1 === "debug" || q1 === "help") {
            return origBrackets;
        }

        // must be an extension
        return origExtension;
    }

    // CodeMirror and Brackets key maps have different formats, so collect
    // keys into a normalized array
    function _getkeyList() {
        var i,
            base,
            command,
            key;

        // Brackets keymap
        var bracketsKeymap = KeyBindingManager.getKeymap();
        if (bracketsKeymap) {
            for (i in bracketsKeymap) {
                if (bracketsKeymap.hasOwnProperty(i)) {
                    key = bracketsKeymap[i];
                    if (key) {
                        base = _getBaseKey(i);
                        command = CommandManager.get(key.commandID);
                        keyList.push({
                            keyBase: base,
                            keyBinding: i,
                            commandID: key.commandID,
                            commandName: command.getName(),
                            origin: _getOriginFromCommandId(key.commandID),
                            filter: command.getName().toLowerCase()
                        });
                    }
                }
            }
        }

        // CodeMirror keymap
        if (CodeMirror.keyMap) {
            var cmKeymap = (brackets.platform === "mac")
                ? CodeMirror.keyMap.macDefault : CodeMirror.keyMap.pcDefault;
            if (cmKeymap) {
                for (i in cmKeymap) {
                    // Note that we only ignore CodeMirror duplicates, but
                    // we want to see Brackets & Extensions duplicates
                    if (cmKeymap.hasOwnProperty(i) &&
                            (i !== "fallthrough") &&
                            (_findKeyBinding(keyList, i) === -1)) {
                        base = _getBaseKey(i);
                        keyList.push({
                            keyBase: base,
                            keyBinding: i,
                            commandID: cmKeymap[i],
                            commandName: cmKeymap[i],
                            origin: origCodeMirror,
                            filter: cmKeymap[i].toLowerCase()
                        });
                    }
                }
            }
        }

        return keyList;
    }

    function _strcmp(a, b) {
        if (a < b) {
            return (sortAscending ? -1 : 1);
        } else if (a > b) {
            return (sortAscending ? 1 : -1);
        }
        return 0;
    }

    function _stricmp(a, b) {
        return _strcmp(a.toLowerCase(), b.toLowerCase());
    }

    function _keyBaseSort(a, b) {
        // First sort by whether it's a single char or not, so letters are separated from key
        // names (e.g. Backspace). Then sort by base key, finally key binding string
        var a2 = ((a.keyBase.length === 1) ? "0" : "1") + a.keyBase,
            b2 = ((b.keyBase.length === 1) ? "0" : "1") + b.keyBase,
            c = _strcmp(a2, b2);

        if (c !== 0) {
            return c;
        } else {
            return _strcmp(a.keyBinding, b.keyBinding);
        }
    }

    function _keyBindingSort(a, b) {
        return _strcmp(a.keyBinding, b.keyBinding);
    }

    function _keyCmdIdSort(a, b) {
        return _stricmp(a.commandID, b.commandID);
    }

    function _keyCmdNameSort(a, b) {
        return _strcmp(a.commandName, b.commandName);
    }

    function _keyOrigSort(a, b) {
        return _strcmp(a.origin, b.origin);
    }

    function _getSortFunc() {
        if (sortColumn === sortByBinding) {
            return _keyBindingSort;
        } else if (sortColumn === sortByCmdId) {
            return _keyCmdIdSort;
        } else if (sortColumn === sortByCmdName) {
            return _keyCmdNameSort;
        } else if (sortColumn === sortByOrig) {
            return _keyOrigSort;
        }
        return _keyBaseSort;
    }

    function _getShortcutsHtml() {
        var msData = {};
        msData.keyList = keyList.sort(_getSortFunc());
        return Mustache.render(shortcutsHtml, msData);
    }

    function _changeSorting(newSortColumn) {
        if (newSortColumn === sortColumn) {
            // Same column, so change sort direction
            sortAscending = !sortAscending;
        } else {
            // New sort column
            sortColumn = newSortColumn;
        }

        // Update page
        _showShortcuts();
    }

    function _filterShortcuts(forceFiltering) {
        var terms = $filterField.val().trim().toLocaleLowerCase();
        if (forceFiltering || terms !== currentFilter) {
            currentFilter = terms;
            terms = terms.split(/\s+?/);
            $.each(keyList, function (i, key) {
                var match;
                if (terms === "") {
                    match = true;
                } else {
                    $.each(terms, function (i, term) {
                        if (match !== false) {
                            match = key.filter.indexOf(term) > -1;
                        }
                    });
                }
                key.filterMatch = match;
            });
        }
    }

    function _showShortcuts() {
        var $shortcuts = $("#shortcuts");

        // Apply any active filter
        _filterShortcuts(true);

        // Add new markup
        $shortcuts.find(".resizable-content").html(_getShortcutsHtml());
        $shortcuts.find("thead th").eq(sortColumn - 1).addClass('sort-' + (sortAscending ? 'ascending' : 'descending'));

        // Setup header sort buttons
        $("thead .shortcut-base a", $shortcuts).on("click", function () {
            _changeSorting(sortByBase);
        });
        $("thead .shortcut-binding a", $shortcuts).on("click", function () {
            _changeSorting(sortByBinding);
        });
        $("thead .shortcut-cmd-id a", $shortcuts).on("click", function () {
            _changeSorting(sortByCmdId);
        });
        $("thead .shortcut-cmd-name a", $shortcuts).on("click", function () {
            _changeSorting(sortByCmdName);
        });
        $("thead .shortcut-orig a", $shortcuts).on("click", function () {
            _changeSorting(sortByOrig);
        });
    }

    function _handleShowHideShortcuts() {
        if (panel.isVisible()) {
            // This panel probably won't get opened very often, so only maintain data
            // while panel is open (for faster sorting) and discard when closed.
            keyList = [];
            panel.hide();
            CommandManager.get(TOGGLE_SHORTCUTS_ID).setChecked(false);
            EditorManager.focusEditor();
        } else {
            panel.show();
            CommandManager.get(TOGGLE_SHORTCUTS_ID).setChecked(true);
            $filterField.val("").focus();

            // Only get data once while panel is open
            if (keyList.length === 0) {
                keyList = _getkeyList();
            }
            _showShortcuts();
        }
        EditorManager.resizeEditor();
    }

    function _copyTableToCurrentDoc() {

        var editor = EditorManager.getCurrentFullEditor();
        if (!editor) {
            return;
        }

        var instance = editor._codeMirror;
        if (!instance) {
            return;
        }

        var start = instance.getCursor(true),
            end   = instance.getCursor(false);

        instance.replaceRange(_getShortcutsHtml(), start, end);
    }

    function init() {
        var $shortcutsPanel,
            $shortcutsContent,
            s,
            view_menu;

        ExtensionUtils.loadStyleSheet(module, "shortcuts.css");

        // Register function as command
        CommandManager.register("Show Shortcuts", TOGGLE_SHORTCUTS_ID, _handleShowHideShortcuts);

        // Add command to View menu, if it exists
        view_menu = Menus.getMenu(Menus.AppMenuBar.VIEW_MENU);
        if (view_menu) {
            view_menu.addMenuItem(TOGGLE_SHORTCUTS_ID, togglePanelShortcut);
        }

        // Add the HTML UI
        s = Mustache.render(panelHtml);

        // AppInit.htmlReady() has already executed before extensions are loaded
        // so, for now, we need to call this ourself
        panel = PanelManager.createBottomPanel(TOGGLE_SHORTCUTS_ID, $(s), 100);
        panel.hide();

        $shortcutsPanel = $("#shortcuts");
        $shortcutsContent = $shortcutsPanel.find(".resizable-content");

        $shortcutsPanel.find(".copy-table").click(function () {
            _copyTableToCurrentDoc();
        });

        $shortcutsPanel.find(".shortcuts-close").click(function () {
            CommandManager.execute(TOGGLE_SHORTCUTS_ID);
        });

        $filterField = $shortcutsPanel.find(".toolbar .filter");
        $filterField.on("keyup", _showShortcuts);
    }

    init();
});
<|endoftext|>


<commit_before>const electron = require("electron");
const path = require("path");
const url = require("url");

let window = null;

// Wait until the app is ready
electron.app.once('ready', function () {
    // Create a new window
    window = new electron.BrowserWindow({
        // Set the initial width to 400px
        width: 400,
        // Set the initial height to 500px
        height: 500,
        // Don't show the window until it ready, this prevents any white flickering
        show: false,
    });

    // Load a URL in the window to the local index.html path
    window.loadURL(url.format({
        pathname: path.join(__dirname, 'index.html'),
        protocol: 'file:',
        slashes: true
    }))

    // Show window when page is ready
    window.once('ready-to-show', function () {
        window.show()
    })
})<commit_msg>update<commit_after>const electron = require("electron");
const path = require("path");
const url = require("url");

let window = null;

// Wait until the app is ready
electron.app.once('ready', function () {
    // Create a new window
    window = new electron.BrowserWindow({
        // Set the initial width to 400px
        width: 1500,
        // Set the initial height to 500px
        height: 800,
        // Don't show the window until it ready, this prevents any white flickering
        show: false,
    });

    // Load a URL in the window to the local index.html path
    window.loadURL(url.format({
        pathname: path.join(__dirname, 'index.html'),
        protocol: 'file:',
        slashes: true
    }))

    // Show window when page is ready
    window.once('ready-to-show', function () {
        window.show()
    })
})<|endoftext|>


<commit_before>// Version
var VERSION = '0.1-dev';

var system = require('system');
var args = system.args;
var server = require('webserver').create();
var page = require('webpage').create();
var fs = require('fs');

var usage =
  'Usage: phantomjs main.js [options]\n' +
'Options:\n' +
    '  -h,--help            Print this usage message and exit\n' +
    '  -v,--version         Print the version number and exit\n' +
    '  -p,--port <port>     IP port on which to start the server\n' +
    '  -r,--requests <num>  Process this many requests and then exit.  -1 means \n' +
    '                       never stop.\n' +
    '  -b,--bench <page>    Use alternate bench page (default is index.html)\n' +
'  -d,--debug           Enable verbose debug messages\n';

var port = 16000;
var requests_to_serve = -1;
var bench_page = 'index.html';
var debug = false;

// Parse command-line options.  This keeps track of which one we are on
var arg_num = 1;

// Helper function for option parsing.  Allow option/arg in any of
// these forms:
//    1: -p 1234
//    2: --po 1234
//    3: --po=1234
// Returns:
//    1 or 2: true
//    3:      '1234'
//    else:   false
function option_match(name, takes_optarg, arg) {
  var ieq = arg.indexOf('=');

  var arg_key;
  if (arg.substr(0, 2) == '--' && (takes_optarg && ieq != -1)) {  // form #3
    arg_key = arg.substring(2, ieq);
    if (name.substr(0, arg_key.length) == arg_key) {
      return arg.substr(ieq + 1);
    }
    return false;
  }

  if (arg.substr(0, 2) == '--') {
    arg_key = arg.substr(2);
  }
  else if (arg.substr(0, 1) == '-') {
    arg_key = arg.substr(1);
  }
  else {
    return false;
  }
  return name.substr(0, arg_key.length) == arg_key;
}

// This helper handles one option that takes an option-argument
function option_arg_parse(name) {
  var arg = args[arg_num];
  match = option_match(name, true, arg);
  if (!match) return false;

  if (typeof match != 'string') {
    if (arg_num + 1 < args.length) {
      arg_num++;
      match = args[arg_num];
    }
    else {
      phantom.exit(1);
    }
  }

  if (name == 'port') {
      port = match - 0;
  }
  else if (name == 'requests') { requests_to_serve = match - 0; }
  else if (name == 'bench') { bench_page = match; }

  arg_num++;
  return true;
}

var to_exit = false;
while (arg_num < args.length) {
  var arg = args[arg_num];

  if (option_match('help', false, arg)) {
    console.log(usage);
    phantom.exit(0);
    break;
  }

  if (option_match('version', false, arg)) {
    console.log('svgtex version ' + VERSION);
    phantom.exit(0);
    break;
  }

  if (option_match('debug', false, arg)) {
    debug = true;
    arg_num++;
    continue;
  }

  if (option_arg_parse('port')) {
    continue;
  }
  if (option_arg_parse('requests')) {
    continue;
  }
  if (option_arg_parse('bench')) {
    continue;
  }

  console.error("Unrecognized argument: '" + arg + "'. Use '--help' for usage info.");
  phantom.exit(1);
  break;
}

/*
  console.log(
    'port = ' + port + ", " +
    'requests_to_serve = ' + requests_to_serve + ", " +
    'bench_page = ' + bench_page + ", " +
    'debug = ' + debug + "\n"
  );
*/

// activeRequests holds information about any active MathJax requests.  It is
// a hash, with a sequential number as the key.  request_num gets incremented
// for *every* HTTP request, but only requests that get passed to MathJax have an
// entry in activeRequests.  Each element of activeRequests
// is an array of [<response object>, <start time>].
var request_num = 0;
var activeRequests = {};

// This will hold the test HTML form, which is read once, the first time it is
// requested, from test.html.
var test_form_filename = 'test.html';
var test_form = null;

var service = null;

// thanks to:
// stackoverflow.com/questions/5515869/string-length-in-bytes-in-javascript
function utf8_strlen(str) {
  var m = encodeURIComponent(str).match(/%[89ABab]/g);
  return str.length + (m ? m.length : 0);
}

// This is the callback that gets invoked after the math has been converted.
// The argument, data, is an array that holds the three arguments from the
// process() function in engine.js:  the request number, the original
// text, and either the converted svg, or an array of one element
// that holds an error message.
page.onCallback = function(data) {
  var query = data[0],
      num = query.num,
      src = query.q,
      svg_or_error = data[1],
      mml = data[2],
      record = activeRequests[num],
      resp = record[0],
      start_time = record[1],
      duration = (new Date()).getTime() - start_time,
      duration_msg = ', took ' + duration + 'ms.',
      log ,
      validRequest = false,
      success = data[3];
    if( (typeof svg_or_error) === 'string'){
        validRequest = true;
        log = num + ': ' + src.substr(0, 30) + '.. ' +
            src.length + 'B query, OK ' + svg_or_error.length + 'B result' +
            duration_msg;
    } else {
        log = src.substr(0, 30) + '.. ' +
            src.length + 'B query, error: ' + svg_or_error[0] + duration_msg;
    }
  if(query.format == 'json'){
      if ( validRequest ) {
          resp.statusCode = 200;
          out = JSON.stringify({input:src,
              svg:svg_or_error,
              mml:mml,
              log:log,
              success:success});
          resp.setHeader('Content-Type', 'application/json');
          resp.setHeader('Content-Length', utf8_strlen(out).toString() );
          resp.write(out);
      } else {
          resp.statusCode = 400;
          out = JSON.stringify({input:src,
              err:svg_or_error[0],
              mml:mml,
              log:log,
              success:success});
          //out = JSON.stringify({err:data[1][0],svg:data[1],mml:data[2],'log':log,'sucess':false});
          resp.write(out);
          console.log(log);
          phantom.exit(1);
      }
  } else {
  if ((typeof svg_or_error) === 'string') {
    resp.statusCode = 200;
    resp.setHeader("Content-Type", "image/svg+xml; charset=utf-8");
    resp.setHeader("Content-Length", utf8_strlen(svg_or_error));
    resp.write(svg_or_error);
    console.log(log);
  }
  else {
    resp.statusCode = 400;    // bad request
    resp.write(svg_or_error[0]);
    console.log(num, log);
  }
  resp.close();
  }
  delete(activeRequests[num]);

  if (!(--requests_to_serve)) {
    phantom.exit();
  }
}

// Parse the request and return an object with the parsed values.
// It will either have an error indication, e.g.
//   { num: 5, status_code: 400, error: "message" }
// Or indicate that the test form should be returned, e.g.
//   { num: 5, test_form: 1 }
// or a valid request, e.g.
//   { num: 5, type: 'tex', q: 'n^2', width: '500' }

function parse_request(req) {
  // Set any defaults here:
  var query = {
    num: request_num++,
    type: 'tex',
    width: null,
    format: 'svg' //possible svg or json
  };

  if (debug) {
    if (req.method == 'POST') {
      console.log("  req.postRaw = '" + req.postRaw + "'");
    }
    else {
      console.log("  req.url = '" + req.url + "'");
    }
  }

  var qs;   // will store the content of the (tex or mml) math
  if (req.method == 'GET') {
    var url = req.url;

    if (url == '' || url == '/') {
      // User has requested the test form
      if (test_form == null && fs.isReadable(test_form_filename)) {
        test_form = fs.read(test_form_filename);  // set the global variable
      }
      if (test_form != null) {
        query.test_form = 1;
      }
      else {
        query.status_code = 500;  // Internal server error
        query.error = "Can't find test form";
      }
      return query;
    }

    var iq = url.indexOf("?");
    if (iq == -1) {  // no query string
      query.status_code = 400;  // bad request
      query.error = "Missing query string";
      return query;
    }

    qs = url.substr(iq+1);
  }

  else if (req.method == 'POST') {
    if (typeof req.postRaw !== 'string') {   // which can happen
      query.status_code = 400;  // bad request
      query.error = "Missing post content";
      return query;
    }
    qs = req.postRaw;
  }

  else {  // method is not GET or POST
    query.status_code = 400;  // bad request
    query.error = "Method " + req.method + " not supported";
    return query;
  }

  var param_strings = qs.split(/&/);
  var num_param_strings = param_strings.length;

  for (var i = 0; i < num_param_strings; ++i) {
    var ps = param_strings[i];
    var ie = ps.indexOf('=');
    if (ie == -1) {
      query.status_code = 400;  // bad request
      query.error = "Can't decipher request parameter";
      return query;
    }
    var key = ps.substr(0, ie);
    var val = decodeURIComponent(ps.substr(ie+1).replace(/\+/g, ' '));
    if (key == 'type') {
      query.type = val;
    }
    else if (key == 'q') {
      query.q = val;
    }
    else if (key == 'width') {
      query.width = parseInt(val) || null;
    }
    else if (key == 'format') {
        query.format = val;
    }
    else {
      query.status_code = 400;  // bad request
      query.error = "Unrecognized parameter name: " + key;
      return query;
    }
  }
  if (!query.q) {   // no source math
    query.status_code = 400;  // bad request
    query.error = "No source math detected in input";
    return query;
  }

  return query;
}

function listenLoop() {
  // Set up the listener that will respond to every new request
  service = server.listen('0.0.0.0:' + port, function(req, resp) {
    var query = parse_request(req);
    var request_num = query.num;
    console.log(request_num + ': ' + "received: " + req.method + " " +
        req.url.substr(0, 30) + " ..");

    if (query.test_form) {
      console.log(request_num + ": returning test form");
      resp.write(test_form);
      resp.close();
    }
    else {
      if (query.error) {
        console.log(request_num + ": error: " + query.error);
        resp.statusCode = query.status_code;
        resp.write(query.error);
        resp.close();
      }

      else {
        // The following evaluates the function argument in the page's context,
        // with query -> _query. That, in turn, calls the process() function in
        // engine.js, which causes MathJax to render the math.  The callback is
        // PhantomJS's callPhantom() function, which in turn calls page.onCallback(),
        // above.  This just queues up the call, and will return at once.
        activeRequests[request_num] = [resp, (new Date()).getTime()];
        page.evaluate(function(_query) {
          window.engine.process(_query, window.callPhantom);
        }, query);
      }
    }
  });

  if (!service) {
    console.log("server failed to start on port " + port);
    phantom.exit(1);
  }
  else {
    console.log("Server started on port " + port);
    console.log("Point your brownser at http://localhost:" + port + " for a test form.");
  }
}

console.log("Loading bench page " + bench_page);
page.open(bench_page, listenLoop);

/* These includeJs calls would allow us to specify the MathJax location as a
   command-line parameter, but then you'd have to take the <script> tags out of
   index.html, and we'd lose the ability to debug by loading that in a browser
   directly.
page.open('index.html', function (status) {
  page.includeJs('mathjax/MathJax.js?config=TeX-AMS-MML_SVG', function() {
    page.includeJs('engine.js', listenLoop);
  });
});
*/

<commit_msg>Fix: Remove MathML out if used as input<commit_after>// Version
var VERSION = '0.1-dev';

var system = require('system');
var args = system.args;
var server = require('webserver').create();
var page = require('webpage').create();
var fs = require('fs');

var usage =
  'Usage: phantomjs main.js [options]\n' +
'Options:\n' +
    '  -h,--help            Print this usage message and exit\n' +
    '  -v,--version         Print the version number and exit\n' +
    '  -p,--port <port>     IP port on which to start the server\n' +
    '  -r,--requests <num>  Process this many requests and then exit.  -1 means \n' +
    '                       never stop.\n' +
    '  -b,--bench <page>    Use alternate bench page (default is index.html)\n' +
'  -d,--debug           Enable verbose debug messages\n';

var port = 16000;
var requests_to_serve = -1;
var bench_page = 'index.html';
var debug = false;

// Parse command-line options.  This keeps track of which one we are on
var arg_num = 1;

// Helper function for option parsing.  Allow option/arg in any of
// these forms:
//    1: -p 1234
//    2: --po 1234
//    3: --po=1234
// Returns:
//    1 or 2: true
//    3:      '1234'
//    else:   false
function option_match(name, takes_optarg, arg) {
  var ieq = arg.indexOf('=');

  var arg_key;
  if (arg.substr(0, 2) == '--' && (takes_optarg && ieq != -1)) {  // form #3
    arg_key = arg.substring(2, ieq);
    if (name.substr(0, arg_key.length) == arg_key) {
      return arg.substr(ieq + 1);
    }
    return false;
  }

  if (arg.substr(0, 2) == '--') {
    arg_key = arg.substr(2);
  }
  else if (arg.substr(0, 1) == '-') {
    arg_key = arg.substr(1);
  }
  else {
    return false;
  }
  return name.substr(0, arg_key.length) == arg_key;
}

// This helper handles one option that takes an option-argument
function option_arg_parse(name) {
  var arg = args[arg_num];
  match = option_match(name, true, arg);
  if (!match) return false;

  if (typeof match != 'string') {
    if (arg_num + 1 < args.length) {
      arg_num++;
      match = args[arg_num];
    }
    else {
      phantom.exit(1);
    }
  }

  if (name == 'port') {
      port = match - 0;
  }
  else if (name == 'requests') { requests_to_serve = match - 0; }
  else if (name == 'bench') { bench_page = match; }

  arg_num++;
  return true;
}

var to_exit = false;
while (arg_num < args.length) {
  var arg = args[arg_num];

  if (option_match('help', false, arg)) {
    console.log(usage);
    phantom.exit(0);
    break;
  }

  if (option_match('version', false, arg)) {
    console.log('svgtex version ' + VERSION);
    phantom.exit(0);
    break;
  }

  if (option_match('debug', false, arg)) {
    debug = true;
    arg_num++;
    continue;
  }

  if (option_arg_parse('port')) {
    continue;
  }
  if (option_arg_parse('requests')) {
    continue;
  }
  if (option_arg_parse('bench')) {
    continue;
  }

  console.error("Unrecognized argument: '" + arg + "'. Use '--help' for usage info.");
  phantom.exit(1);
  break;
}

/*
  console.log(
    'port = ' + port + ", " +
    'requests_to_serve = ' + requests_to_serve + ", " +
    'bench_page = ' + bench_page + ", " +
    'debug = ' + debug + "\n"
  );
*/

// activeRequests holds information about any active MathJax requests.  It is
// a hash, with a sequential number as the key.  request_num gets incremented
// for *every* HTTP request, but only requests that get passed to MathJax have an
// entry in activeRequests.  Each element of activeRequests
// is an array of [<response object>, <start time>].
var request_num = 0;
var activeRequests = {};

// This will hold the test HTML form, which is read once, the first time it is
// requested, from test.html.
var test_form_filename = 'test.html';
var test_form = null;

var service = null;

// thanks to:
// stackoverflow.com/questions/5515869/string-length-in-bytes-in-javascript
function utf8_strlen(str) {
  var m = encodeURIComponent(str).match(/%[89ABab]/g);
  return str.length + (m ? m.length : 0);
}

// This is the callback that gets invoked after the math has been converted.
// The argument, data, is an array that holds the three arguments from the
// process() function in engine.js:  the request number, the original
// text, and either the converted svg, or an array of one element
// that holds an error message.
page.onCallback = function(data) {
  var query = data[0],
      num = query.num,
      src = query.q,
      svg_or_error = data[1],
      mml = data[2],
      record = activeRequests[num],
      resp = record[0],
      start_time = record[1],
      duration = (new Date()).getTime() - start_time,
      duration_msg = ', took ' + duration + 'ms.',
      log ,
      validRequest = false,
      success = data[3];
    if( (typeof svg_or_error) === 'string'){
        validRequest = true;
        log = num + ': ' + src.substr(0, 30) + '.. ' +
            src.length + 'B query, OK ' + svg_or_error.length + 'B result' +
            duration_msg;
    } else {
        log = src.substr(0, 30) + '.. ' +
            src.length + 'B query, error: ' + svg_or_error[0] + duration_msg;
    }
  if(query.format == 'json'){
      if ( validRequest ) {
          resp.statusCode = 200;
          //Temporary fix for BUG 62921
          if (query.type == 'mml'){
              mml = '';
              src = 'mathml';
          }
          //End of fix
          out = JSON.stringify({input:src,
              svg:svg_or_error,
              mml:mml,
              log:log,
              success:success});
          resp.setHeader('Content-Type', 'application/json');
          resp.setHeader('Content-Length', utf8_strlen(out).toString() );
          resp.write(out);
      } else {
          resp.statusCode = 400;
          out = JSON.stringify({input:src,
              err:svg_or_error[0],
              mml:mml,
              log:log,
              success:success});
          //out = JSON.stringify({err:data[1][0],svg:data[1],mml:data[2],'log':log,'sucess':false});
          resp.write(out);
          console.log(log);
          phantom.exit(1);
      }
  } else {
  if ((typeof svg_or_error) === 'string') {
    resp.statusCode = 200;
    resp.setHeader("Content-Type", "image/svg+xml; charset=utf-8");
    resp.setHeader("Content-Length", utf8_strlen(svg_or_error));
    resp.write(svg_or_error);
    console.log(log);
  }
  else {
    resp.statusCode = 400;    // bad request
    resp.write(svg_or_error[0]);
    console.log(num, log);
  }
  resp.close();
  }
  delete(activeRequests[num]);

  if (!(--requests_to_serve)) {
    phantom.exit();
  }
}

// Parse the request and return an object with the parsed values.
// It will either have an error indication, e.g.
//   { num: 5, status_code: 400, error: "message" }
// Or indicate that the test form should be returned, e.g.
//   { num: 5, test_form: 1 }
// or a valid request, e.g.
//   { num: 5, type: 'tex', q: 'n^2', width: '500' }

function parse_request(req) {
  // Set any defaults here:
  var query = {
    num: request_num++,
    type: 'tex',
    width: null,
    format: 'svg' //possible svg or json
  };

  if (debug) {
    if (req.method == 'POST') {
      console.log("  req.postRaw = '" + req.postRaw + "'");
    }
    else {
      console.log("  req.url = '" + req.url + "'");
    }
  }

  var qs;   // will store the content of the (tex or mml) math
  if (req.method == 'GET') {
    var url = req.url;

    if (url == '' || url == '/') {
      // User has requested the test form
      if (test_form == null && fs.isReadable(test_form_filename)) {
        test_form = fs.read(test_form_filename);  // set the global variable
      }
      if (test_form != null) {
        query.test_form = 1;
      }
      else {
        query.status_code = 500;  // Internal server error
        query.error = "Can't find test form";
      }
      return query;
    }

    var iq = url.indexOf("?");
    if (iq == -1) {  // no query string
      query.status_code = 400;  // bad request
      query.error = "Missing query string";
      return query;
    }

    qs = url.substr(iq+1);
  }

  else if (req.method == 'POST') {
    if (typeof req.postRaw !== 'string') {   // which can happen
      query.status_code = 400;  // bad request
      query.error = "Missing post content";
      return query;
    }
    qs = req.postRaw;
  }

  else {  // method is not GET or POST
    query.status_code = 400;  // bad request
    query.error = "Method " + req.method + " not supported";
    return query;
  }

  var param_strings = qs.split(/&/);
  var num_param_strings = param_strings.length;

  for (var i = 0; i < num_param_strings; ++i) {
    var ps = param_strings[i];
    var ie = ps.indexOf('=');
    if (ie == -1) {
      query.status_code = 400;  // bad request
      query.error = "Can't decipher request parameter";
      return query;
    }
    var key = ps.substr(0, ie);
    var val = decodeURIComponent(ps.substr(ie+1).replace(/\+/g, ' '));
    if (key == 'type') {
      query.type = val;
    }
    else if (key == 'q') {
      query.q = val;
    }
    else if (key == 'width') {
      query.width = parseInt(val) || null;
    }
    else if (key == 'format') {
        query.format = val;
    }
    else {
      query.status_code = 400;  // bad request
      query.error = "Unrecognized parameter name: " + key;
      return query;
    }
  }
  if (!query.q) {   // no source math
    query.status_code = 400;  // bad request
    query.error = "No source math detected in input";
    return query;
  }

  return query;
}

function listenLoop() {
  // Set up the listener that will respond to every new request
  service = server.listen('0.0.0.0:' + port, function(req, resp) {
    var query = parse_request(req);
    var request_num = query.num;
    console.log(request_num + ': ' + "received: " + req.method + " " +
        req.url.substr(0, 30) + " ..");

    if (query.test_form) {
      console.log(request_num + ": returning test form");
      resp.write(test_form);
      resp.close();
    }
    else {
      if (query.error) {
        console.log(request_num + ": error: " + query.error);
        resp.statusCode = query.status_code;
        resp.write(query.error);
        resp.close();
      }

      else {
        // The following evaluates the function argument in the page's context,
        // with query -> _query. That, in turn, calls the process() function in
        // engine.js, which causes MathJax to render the math.  The callback is
        // PhantomJS's callPhantom() function, which in turn calls page.onCallback(),
        // above.  This just queues up the call, and will return at once.
        activeRequests[request_num] = [resp, (new Date()).getTime()];
        page.evaluate(function(_query) {
          window.engine.process(_query, window.callPhantom);
        }, query);
      }
    }
  });

  if (!service) {
    console.log("server failed to start on port " + port);
    phantom.exit(1);
  }
  else {
    console.log("Server started on port " + port);
    console.log("Point your brownser at http://localhost:" + port + " for a test form.");
  }
}

console.log("Loading bench page " + bench_page);
page.open(bench_page, listenLoop);

/* These includeJs calls would allow us to specify the MathJax location as a
   command-line parameter, but then you'd have to take the <script> tags out of
   index.html, and we'd lose the ability to debug by loading that in a browser
   directly.
page.open('index.html', function (status) {
  page.includeJs('mathjax/MathJax.js?config=TeX-AMS-MML_SVG', function() {
    page.includeJs('engine.js', listenLoop);
  });
});
*/

<|endoftext|>


<commit_before>// !! Node must be called from aran directory !!
// Don't use the same name for in.html and out.html !!
// usage: node aran.js linvail.js 1< in.html 1> out.html
// The linvail file should populate the aran object:
//   a) Literals:      window.aran.literals.{number|string|regex|array|object|function}
//   b) Operations:    window.aran.operations.{plus|minus|...}
//   c) Global object: window.aran.shadows.{document|XMLHttpRequest|...}
// N.B. It is the user responsability to compile with window.aran.eval any js code
// that fly in the system (e.g. window.eval, window.document.createElement("script"))

var fs = require("fs")
var htmlparser = require("htmlparser2")

if (process.argv.length !== 3) {
  throw new Error("Usage: node main.js options.js 1< in.html 1> out.html")
}

var esprima = fs.readFileSync("esprima.js").toString()
var escodegen = fs.readFileSync("escodegen.browser.js").toString()
var miley = fs.readFileSync("miley.js").toString()
var options = fs.readFileSync(process.argv[2]).toString()
var aran = fs.readFileSync("aran.js").toString()

var out = process.stdout
var is_js = false

process.stdin.pipe(new htmlparser.Parser({
  onopentag: function(tag, attrs) {
    open_tag(tag, attrs)
    if (tag === "script") {
      if (attrs.src) {
        out.write("aran.load(\"")
        out.write(attrs.src)
        out.write("\", ")
        out.write(attrs.async)
        out.write(")")
      } else {
        is_js = true
        out.write("aran.compile(\"")
      }
    } else if (tag === "html") {
      out.write("<script>")
      out.write(js_escape(esprima))
      out.write(js_escape(escodegen))
      out.write(js_escape(miley))
      out.write("window.aran={};\n")
      out.write(js_escape(options))
      out.write(js_escape(aran))
      out.write("</script>")
    }
  },
  // text nodes are not decoded (< does not become <)
  ontext: function(text) {
    if (is_js) { text = string_escape(js_escape(text)) }
    out.write(text)
  },
  onclosetag: function(tag) {
    if (tag === "script") {
      is_js = false
      out.write("\")")
    }
    close_tag(tag)
  }
}))

function open_tag (tag, attrs) {
  out.write("<"+tag)
  for (var attr in attrs) {
    out.write(" ")
    out.write(attr)
    out.write("=\"")
    // attributes are not decoded (< does not become <)
    out.write(attrs[attr])
    out.write("\"")
  }
  out.write(">")
}

function close_tag (tag) {
  out.write("</")
  out.write(tag)
  out.write(">")
}

function js_escape (str) {
  // </script> can only occurs within string litteral and comments
  // as "</script>" and "<\/script>" evaluate to the same string
  // the semantic is preserved
  return str.replace(/<\/script>/g, "<\\/script>")
}

function string_escape (str) {
  return str.replace(/\\/g, "\\\\").replace(/"/g, "\\\"").replace(/\n/g, "\\n")
}
<commit_msg>source was not evaluated, correcected<commit_after>// !! Node must be called from aran directory !!
// Don't use the same name for in.html and out.html !!
// usage: node aran.js linvail.js 1< in.html 1> out.html
// The linvail file should populate the aran object:
//   a) Literals:      window.aran.literals.{number|string|regex|array|object|function}
//   b) Operations:    window.aran.operations.{plus|minus|...}
//   c) Global object: window.aran.shadows.{document|XMLHttpRequest|...}
// N.B. It is the user responsability to compile with window.aran.eval any js code
// that fly in the system (e.g. window.eval, window.document.createElement("script"))

var fs = require("fs")
var htmlparser = require("htmlparser2")

if (process.argv.length !== 3) {
  throw new Error("Usage: node main.js options.js 1< in.html 1> out.html")
}

var esprima = fs.readFileSync("esprima.js").toString()
var escodegen = fs.readFileSync("escodegen.browser.js").toString()
var miley = fs.readFileSync("miley.js").toString()
var options = fs.readFileSync(process.argv[2]).toString()
var aran = fs.readFileSync("aran.js").toString()

var out = process.stdout
var is_js = false

process.stdin.pipe(new htmlparser.Parser({
  onopentag: function(tag, attrs) {
    open_tag(tag, attrs)
    if (tag === "script") {
      if (attrs.src) {
        out.write("aran.load(\"")
        out.write(attrs.src)
        out.write("\", ")
        out.write(attrs.async)
        out.write(")")
      } else {
        is_js = true
        out.write("eval(aran.compile(\"")
      }
    } else if (tag === "html") {
      out.write("<script>")
      out.write(js_escape(esprima))
      out.write(js_escape(escodegen))
      out.write(js_escape(miley))
      out.write("window.aran={};\n")
      out.write(js_escape(options))
      out.write(js_escape(aran))
      out.write("</script>")
    }
  },
  // text nodes are not decoded (< does not become <)
  ontext: function(text) {
    if (is_js) { text = string_escape(js_escape(text)) }
    out.write(text)
  },
  onclosetag: function(tag) {
    if (tag === "script") {
      is_js = false
      out.write("\"))")
    }
    close_tag(tag)
  }
}))

function open_tag (tag, attrs) {
  out.write("<"+tag)
  for (var attr in attrs) {
    out.write(" ")
    out.write(attr)
    out.write("=\"")
    // attributes are not decoded (< does not become <)
    out.write(attrs[attr])
    out.write("\"")
  }
  out.write(">")
}

function close_tag (tag) {
  out.write("</")
  out.write(tag)
  out.write(">")
}

function js_escape (str) {
  // </script> can only occurs within string litteral and comments
  // as "</script>" and "<\/script>" evaluate to the same string
  // the semantic is preserved
  return str.replace(/<\/script>/g, "<\\/script>")
}

function string_escape (str) {
  return str.replace(/\\/g, "\\\\").replace(/"/g, "\\\"").replace(/\n/g, "\\n")
}
<|endoftext|>


<commit_before>var app = {};

// $(function() { //when DOM is ready...
	app.users = new UserCollection([

		{username:'Jennifer'},
		{username:'Jason'},
		{username:'Ty'}
	]);

var LoginModel = Backbone.Model.extend({
	// // defaults : {"username" : ""},
	// replace : function(usr){
	// this.set("username", usr);
	// }
});

//LOGIN VIEW---------------------------------------------------------

var LoginView = Backbone.View.extend({
	render : function (){
		console.log("render login");
		var login = '<button id="login" type="submit">Login</button>';
		var usrBtn = '<button id="newName">Add Name</button>';
		var input = '
<input type="text" id="userField" value="Add New User Name">';
		var headline = '
To Do List
';
		var headline2 = '
Please log in.
';
		var nametag = "
name:
";
		var selector = this.userSelector();
		this.$el.html("

" + headline + headline2 + nametag + selector + login + input + usrBtn + "
");
		// this.el.append(this.$el);
	},
    userSelector: function(){
		var users = [];
		content = "";

		for (var i = 0;i < app.users.length; i++){
			users.push(app.users.models[i].attributes.username);
			content+=("<option>"+users[i]+"</option>");

      	}
		content = "<select id='selectDropdown'>"+content+"</select>";
		return content;
	},

	addNewUser: function(){
		var newUser = $("#userField").val();
		app.users.add({username: newUser});
		this.render();
	},

	events: {
		"click #login" 		: "userLogin",
		"click #newName"	: "addNewUser"
	},

	userLogin : function(){
		$("#login-area").hide();
		userView.render();
 	}

 });

	var UserModel = Backbone.Model.extend({
	    defaults : {"value" : ""},
	    replace : function (str) {
	      this.set("value", str);
	    }
	});

// ----------------------------------------------------------------
//USERVIEW---------------------------------------------------------
// ----------------------------------------------------------------

var UserView = Backbone.View.extend({
	render: function (){
		console.log("RENDERING SOMETHING!!!!!");
		var userVal = this.model.get("creator");
		var greeting= "
 Hello, "+ userVal+" !!
";
		var btn = '<button id="createTasks">List of Tasks</button>';
		var input = '<input type="text" value= "Enter another task"/>';
		this.$el.html("
"+greeting+"
");
		$('#app').append(this.el);
		console.log('user works!',this.el);

	},

	initialize: function(){
		this.model.on("change", this.render, this);
	},

	events: {
		"click #login" : "render"
	}
	// taskList : function(){
	// 	this.taskView.add({});
	// }

});

var TaskModel = Backbone.Model.extend({
    defaults : {"value" : ""},
    replace : function (str) {
      this.set("value", str);
    }
});

// var TaskView = Backbone.View.extend({
// 	render: function (){
// 		console.log('rendering task view');
// 		var taskVal = this.model.get("title");
// 		var btn = '<button id="showTasks">Add New Task</button>';
// 		var input = '<input type="text" value= "Create A New Task"/>';
// 		this.$el.html("

"+taskVal+"
");
// 		console.log('it works!');

// 	},

// 	initialize: function(){
// 		this.model.on("change", this.render, this);
// 	},

// 	events: {
// 		"click #login" : "render"
// 	},
// 	taskList : function(){
// 		this.taskView.add({});
// 	}

// });

// var TaskCollection = Backbone.Collection.extend({
//     model : TaskModel
// });

// var TaskCollectionView = Backbone.View.extend({
//     render : function () {
//     	console.log('Rendering!');
//         var btn = '<button id="addTask">Add Task</button>';
//         var div = '

';
//         this.$el.html(div + btn);
// },

//    initialize: function () {
//    	console.log('BLAH!');
//    	this.listenTo(this.collection, "add", this.addView);
//    },
//    events : {
//    	"click #addTask" : "addModel",
//    },
//    addModel : function(){
//    	this.collection.add({});
//    },
//     addView : function (newModel) {
//     	console.log('New Model');
//         // newModel.set("value","Enter New Task");
//         var view = new TaskView({model : newModel});
//         view.render();
//         this.$("#taskList").append(view.$el);
//     }

//   });
// });
var content;
var loginView;
var userView;
var userModel;
var taskView;
var taskCollection;
var testModel;
var taskCollectionView;
$(document).ready( function () {
	console.log("ready");

userModel = new UserModel({title:'Make this page work!',
                           description: 'Fix all the code!',
                           creator: 'Jennifer'});

loginView = new LoginView({el:"#app"});
loginView.render();

userModel = new UserModel({title:'Make this page work!',
                           description: 'Fix all the code!',
                           creator: app.users});

userView = new UserView({ model: userModel});
// userView.render();

// userModel = new UserModel({creator: 'Jennifer'});
// userView = new UserView({el: "#app"})

// taskCollection = new TaskCollection();
// taskView = new TaskView({model: testModel});
// taskCollectionView = new TaskCollectionView({ collection : taskCollection});
// taskCollectionView.render();
// taskCollection.add(testModel)

// taskView.render();

$("#app").append(userView.$el);

});

// 	 app.tasks = new TaskCollection([
// 		// test data here
// 	]);

// 	app.gui = new GUI(app.users,
// 						app.tasks,
// 						'#app');// selector of main div
// });
<commit_msg>Selected user name rendering on userView<commit_after>var app = {};

// $(function() { //when DOM is ready...
	app.users = new UserCollection([

		{username:'Jennifer'},
		{username:'Jason'},
		{username:'Ty'}
]);

var LoginModel = Backbone.Model.extend({
	// // defaults : {"username" : ""},
	// replace : function(usr){
	// this.set("username", usr);
	// }
});

//LOGIN VIEW---------------------------------------------------------

var LoginView = Backbone.View.extend({
	render : function (){
		console.log("render login");
		var login = '<button id="login" type="submit">Login</button>';
		var usrBtn = '<button id="newName">Add Name</button>';
		var input = '
<input type="text" id="userField" value="Add New User Name">';
		var headline = '
To Do List
';
		var headline2 = '
Please log in.
';
		var nametag = "
name:
";
		var selector = this.userSelector();
		this.$el.html("

" + headline + headline2 + nametag + selector + login + input + usrBtn + "
");
		// this.el.append(this.$el);
	},
    userSelector: function(){
		var users = [];
		content = "";

		for (var i = 0;i < app.users.length; i++){
			users.push(app.users.models[i].attributes.username);
			content+=("<option>"+users[i]+"</option>");

      	}
		content = "<select id='selectDropdown'>"+content+"</select>";
		return content;
	},

	addNewUser: function(){
		var newUser = $("#userField").val();
		app.users.add({username: newUser});
		this.render();
	},

	events: {
		"click #login" 		: "userLogin",
		"click #newName"	: "addNewUser"
	},

	userLogin : function(){
		$("#login-area").hide();
		var selectedUser = $("#selectDropdown").val();
		var userModel = app.users.where({username: selectedUser})[0];
		 console.log(userModel);
		userView = new UserView({model: userModel});
		userView.render();
		//this.model.get(username)
 	}

 });

	var UserModel = Backbone.Model.extend({
	    defaults : {"value" : ""},
	    replace : function (str) {
	      this.set("value", str);
	    }
	});

// ----------------------------------------------------------------
//USERVIEW---------------------------------------------------------
// ----------------------------------------------------------------

var UserView = Backbone.View.extend({

	render: function (){
	console.log(this.model);

	var greeting= "
 Hello, "+ this.model.get('username') +" !!
";
	var btn = '<button id="createTasks">List of Tasks</button>';
	var input = '<input type="text" value= "Enter another task"/>';
	this.$el.html("
"+greeting+"
");
	$('#app').append(this.el);
	console.log('user works!',this.el);

	},

	// initialize: function(){
	// 	this.model.on("change", this.render, this);
	// },

	events: {
		"click #login" : "render"
	}
	// taskList : function(){
	// 	this.taskView.add({});
	// }

});

var TaskModel = Backbone.Model.extend({
    defaults : {"value" : ""},
    replace : function (str) {
      this.set("value", str);
    }
});

var content;
var loginView;
var userView;
var taskView;
var taskCollection;
var testModel;
var taskCollectionView;

$(document).ready( function () {
	console.log("ready");

// userModel = new UserModel({title:'Make this page work!',
//                            description: 'Fix all the code!',
//                            creator: 'Jennifer'});

loginView = new LoginView({el:"#app"});
loginView.render();

userModel = new UserModel({title:'Make this page work!',
                           description: 'Fix all the code!',
                           creator: app.users});

// userView.render();

// userModel = new UserModel({creator: 'Jennifer'});
// userView = new UserView({el: "#app"})

// taskCollection = new TaskCollection();
// taskView = new TaskView({model: testModel});
// taskCollectionView = new TaskCollectionView({ collection : taskCollection});
// taskCollectionView.render();
// taskCollection.add(testModel)

// taskView.render();

// $("#app").append(userView.$el);

});

// 	 app.tasks = new TaskCollection([
// 		// test data here
// 	]);

// 	app.gui = new GUI(app.users,
// 						app.tasks,
// 						'#app');// selector of main div
// });
<|endoftext|>