diff --git a/.gitignore b/.gitignore index 09061c2a..1171d6d8 100644 --- a/.gitignore +++ b/.gitignore @@ -1,27 +1,41 @@ -lib-cov -*.seed -*.csv -*.dat -*.out -*.pid -*.gz +# Logs +logs +*.log +# Runtime data pids -logs -results +*.pid +*.seed + +# Directory for instrumented libs generated by jscoverage/JSCover +lib-cov + +# Coverage directory used by tools like istanbul +coverage + +# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) +.grunt + +# Compiled binary addons (http://nodejs.org/api/addons.html) +build/Release + +# Dependency directory +# Deployed apps should consider commenting this line out: +# see https://npmjs.org/doc/faq.html#Should-I-check-my-node_modules-folder-into-git +node_modules -npm-debug.log -settings.json -/node_modules/ -/appBuilds/ -/client/build/ -.addons +# Bower Vendors +editor/vendors -/.env +# All installed packages +packages/* +!packages/.gitkeep -/.tmp/ +# Build output +build -/addons/cb.files.editor/ace/ -**/addon-built.js -/extras/ +# Tmp directory +.tmp +# Packages for testing +test/packages \ No newline at end of file diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 00000000..6e5919de --- /dev/null +++ b/.travis.yml @@ -0,0 +1,3 @@ +language: node_js +node_js: + - "0.10" diff --git a/AUTHORS b/AUTHORS index 8b41dd85..6b18f31c 100644 --- a/AUTHORS +++ b/AUTHORS @@ -3,4 +3,5 @@ Authors ordered by first contribution. Samy Pessé Aaron O'Mullan Cyril MORISSE -Julien LEICHER \ No newline at end of file +Julien LEICHER +Mark Achée \ No newline at end of file diff --git a/CHANGES b/CHANGES.md similarity index 77% rename from CHANGES rename to CHANGES.md index a151379b..27e14324 100644 --- a/CHANGES +++ b/CHANGES.md @@ -1,3 +1,63 @@ +2014-04-01 Samy Pessé + Aaron O'Mullan + Mark Achée + + * Bump version to 0.7.4 + * New outline panel + * Improve the terminal (resize, themes) + * Improve command palette (navigation and display) + * Add recent files to command palette + * Fix reload of browser when ctrl+r or cmd+r and non in file + * Open tags from command palette select the correct pattern + * Images open by default width image viewer + * Add command for searching code in a specific folder + * Fix export as archive (tar.gz instead of zip) + +2014-03-23 Samy Pessé + Aaron O'Mullan + + * Bump version to 0.7.3 + * Fix addons build when node used from desktop extras + * Add Find/Replace in files + * Add Maven project support + * Add base runner for Java + * Improve command palette: selection, scrolling + * Add action "npm install" for node projects + * Fix run of long process command in terminal + * Fix heroku deployment (push key and git push) + * Add welcome message + +2014-03-19 Samy Pessé + Aaron O'Mullan + + * Bump version to 0.7.2 + * Fix addons installation on linux desktop + * Fix runner and project detection on linux desktop + +2014-03-19 Samy Pessé + Aaron O'Mullan + + * Bump version to 0.7.1 + * Graphical debugger with supports of python (pdb) and native (gdb), coming soon: Java, PHP, Ruby and HHVM + * Add copy/cut/paste for files + * Fix tabs restoration + * Improve stability of grid UI + * Fix addons installation + +2014-03-09 Samy Pessé + Aaron O'Mullan + + * Bump version to 0.7.0 + * New tabs system: grid system, resize, reorder + * New statusbar + * New command palette (test it using Command+Shift+P or Ctrl+Shift+P) + * Stop state for run button + * Apache runner is now working (with MySQL) + * Addons need an engine field + * Django support (auto-run) + * Performance improved (faster boot, ...) + * Editor uses .jshintrc file for JSHing worker configuration + 2014-02-25 Samy Pessé Aaron O'Mullan diff --git a/Gruntfile.js b/Gruntfile.js deleted file mode 100644 index e031b961..00000000 --- a/Gruntfile.js +++ /dev/null @@ -1,404 +0,0 @@ -module.exports = function (grunt) { - var fs = require('fs'); - var path = require("path"); - var pkg = require("./package.json"); - var _ = require('lodash'); - - // Path to the client src - var clientPath = path.resolve(__dirname, "client"); - - // Constants - var NW_VERSION = "0.8.4"; - - // Load grunt modules - grunt.loadNpmTasks('hr.js'); - grunt.loadNpmTasks('grunt-exec'); - grunt.loadNpmTasks('grunt-node-webkit-builder'); - grunt.loadNpmTasks('grunt-contrib-compress'); - grunt.loadNpmTasks('grunt-contrib-clean'); - grunt.loadNpmTasks('grunt-contrib-copy'); - - // Init GRUNT configuraton - grunt.initConfig({ - 'pkg': grunt.file.readJSON('package.json'), - 'hr': { - build: { - // Base directory for the application - "base": clientPath, - - // Application name - "name": "Codebox", - - // Mode debug - "debug": process.env.CLIENT_DEBUG != null, - - // Main entry point for application - "main": "main", - "index": grunt.file.read(path.resolve(clientPath, "index.html")), - - // Build output directory - "build": path.resolve(clientPath, "build"), - - // Static files mappage - "static": { - "templates": path.resolve(clientPath, "resources", "templates"), - "images": path.resolve(clientPath, "resources", "images"), - "fonts": path.resolve(clientPath, "resources", "fonts"), - "require-tools": path.resolve(clientPath, "resources", "require-tools") - }, - - // Stylesheet entry point - "style": path.resolve(clientPath, "resources/stylesheets/main.less"), - - // Modules paths - 'paths': { - 'moment': 'vendors/moment' - }, - "shim": { - 'resources/resources': { - deps: [ - 'vendors/bootstrap/carousel', - 'vendors/bootstrap/dropdown', - 'vendors/bootstrap/button', - 'vendors/bootstrap/modal', - 'vendors/bootstrap/affix', - 'vendors/bootstrap/alert', - 'vendors/bootstrap/collapse', - 'vendors/bootstrap/tooltip', - 'vendors/bootstrap/popover', - 'vendors/bootstrap/scrollspy', - 'vendors/bootstrap/tab', - 'vendors/bootstrap/transition', - 'vendors/taphold' - ] - }, - 'vendors/socket.io': { - exports: 'io' - }, - 'vendors/crypto': { - exports: 'CryptoJS' - }, - 'vendors/diff_match_patch': { - exports: 'diff_match_patch' - }, - 'vendors/mousetrap': { - exports: 'Mousetrap' - }, - 'vendors/filer': { - exports: 'Filer', - deps: [ - 'vendors/idb.filesystem' - ] - } - }, - 'args': { - 'version': pkg.version, - 'debug': process.env.CLIENT_DEBUG != null - }, - 'options': { - - } - } - }, - nodewebkit: { - mac: { - options: { - build_dir: './appBuilds', - mac: true, - win: false, - linux32: false, - linux64: false, - mac_icns: "./desktop/icons/mac.icns", - credits: "./desktop/credits.html", - version: NW_VERSION, - zip: false - }, - src: [ - ".tmp/**", - - // grunt.file.copy duplicates symbolic and hard links - // so we need to copy it with the shell - "!.tmp/extras/**", - ] - }, - linux: { - options: { - build_dir: './appBuilds', - mac: false, - win: false, - linux32: true, - linux64: false, - version: NW_VERSION, - zip: false - }, - src: [ - ".tmp/**" - ] - } - }, - exec: { - nwbuild: { - command: "./scripts/nwbuild.sh "+NW_VERSION, - cwd: '.tmp/', - stdout: true, - stderr: true - }, - build_extras: { - command: "./scripts/build_extras.sh", - cwd: '.tmp/', - stdout: true, - stderr: true - }, - publish: { - command: "npm publish", - cwd: '.tmp/', - stdout: true, - stderr: true - }, - build_files_editor: { - command: "npm install", - cwd: './addons/cb.files.editor/', - stdout: true, - stderr: true - }, - copy_extras: { - // Copy and preserve symbolic links - command: "mv .tmp/extras ./appBuilds/releases/Codebox/mac/Codebox.app/Contents/Resources/app.nw/extras", - cwd: '.', - stdout: true, - stderr: true - }, - build_mac_release: { - command: "./scripts/build_mac_dmg.sh", - cwd: './', - stdout: true, - stderr: true - }, - build_linux_release: { - command: "./scripts/build_linux_tar.sh", - cwd: './', - stdout: true, - stderr: true - }, - clean_addons: { - command: "rm -rf */**/addon-built.js", - cwd: '.', - stdout: true, - stderr: true - }, - clean_addons_tmp: { - command: "rm -rf */**/addon-built.js", - cwd: '.tmp/', - stdout: true, - stderr: true - } - }, - copy: { - // Copy most files over - tmp: { - expand: true, - dot: false, - cwd: './', - dest: '.tmp/', - src: [ - // Most files except the ones below - "./**", - - // Ignore gitignore - "!.gitignore", - - // Ignore dev related things - "!./tmp/**", - "!./.git/**", - "!./.addons/**", - "!./appBuilds/**", - - // grunt.file.copy duplicates symbolic and hard links - // so we need to copy it with the shell - "!./extras/**", - - // Only take "./client/build" - "!./client/**", - "./client/build/**", - - // Ignore some build time only modules - "./node_modules/.bin/**", - "!./node_modules/grunt/**", - "!./node_modules/grunt-*/**", - "!./node_modules/hr.js/**", - - // Exclude test directories from node modules - "!./node_modules/**/test/**", - ], - - // Preserve permissions - options: { - mode: true - } - }, - - // Change the package.json to use node-webkit's - desktopPKG: { - cwd: './', - src: '.tmp/desktop/package.json', - dest: '.tmp/package.json', - options: { - // Change main entry point - process: function (content, srcpath) { - grunt.log.write('processing '+ srcpath + '...\n'); - return content.replace( - '"main": "index.html",', - '"main": "desktop/index.html",' - ); - } - } - }, - - // Installer for linux - linuxInstaller: { - cwd: './', - src: 'scripts/install_linux.sh', - dest: './appBuilds/releases/Codebox/linux32/Codebox/install.sh' - }, - - // Installer for linux - linuxIcon: { - cwd: './', - src: './desktop/icons/128.png', - dest: './appBuilds/releases/Codebox/linux32/Codebox/icon.png' - }, - }, - compress: { - tmp: { - options: { - mode: 'gzip', - pretty: true - }, - expand: true, - src: [ - // Codebox Built addons - '.tmp/addons/*/addon-built.js', - - // Ace source - '.tmp/addons/cb.files.editor/ace/**', - - // HR.js application - '.tmp/client/build/static/application.{js,css}' - ], - filter: function(src) { - // Compressable file formats - if(!_.contains([ - 'js', - 'css', - 'svg', - 'less', - 'html', - 'snippets' - ], - path.extname(src).slice(1) - )) return false; - try { - // We don't want to gzip tiny files - // Skip files < 10kb - return fs.statSync(src).size > 10*1024; - } catch(err) {} - return false; - } - } - }, - clean: { - tmp: ['.tmp/'] - }, - buildAddons: { - tmp: { - addonsFolder: ".tmp/addons/" - }, - dev: { - addonsFolder: "./addons/", - force: false - } - } - }); - - // Load in any and all tasks in the `tasks` folder - grunt.loadTasks('tasks'); - - // Rebuild all addons - grunt.registerTask('rebuildAddons', [ - 'exec:clean_addons', - 'buildAddons:dev' - ]); - - // Build - grunt.registerTask('build', [ - 'hr', - 'exec:build_files_editor', - 'buildAddons:dev' - ]); - - // Build tmp directory - grunt.registerTask('tmp', [ - 'build', - 'clean:tmp', - 'copy:tmp', - 'exec:clean_addons_tmp', - 'buildAddons:tmp', - 'compress:tmp' - ]); - - // Desktop app generation - grunt.registerTask('build-app-mac', [ - 'tmp', - 'copy:desktopPKG', - 'exec:nwbuild', - 'exec:build_extras', - 'nodewebkit:mac', - 'exec:copy_extras', - 'clean:tmp', - 'exec:build_mac_release' - ]); - grunt.registerTask('build-app-linux', [ - 'tmp', - 'copy:desktopPKG', - 'exec:nwbuild', - 'nodewebkit:linux', - 'copy:linuxInstaller', - 'copy:linuxIcon', - 'clean:tmp', - 'exec:build_linux_release' - ]); - - // Desktop app test - grunt.registerTask('testApps', [ - 'tmp', - 'copy:desktopPKG', - 'exec:nwbuild' - ]); - - // Publish to NPM - grunt.registerTask('publish', [ - 'tmp', - 'exec:publish', - 'clean:tmp' - ]); - - // Run - grunt.registerTask('run', function() { - var done = this.async(); - var options = this.options({}); - - grunt.util.spawn({ - cmd: "node", - opts: { - cwd: path.resolve(__dirname), - stdio: 'inherit' - }, - args: ["./bin/codebox.js", "run"] - }, done); - }); - - grunt.registerTask('default', [ - 'build', - 'run' - ]); -}; \ No newline at end of file diff --git a/README.md b/README.md index 8a83071b..52f8fab9 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,9 @@ # Codebox > "Open source cloud & desktop IDE." +[![Build Status](https://travis-ci.org/CodeboxIDE/codebox.png?branch=master)](https://travis-ci.org/CodeboxIDE/codebox) +[![NPM version](https://badge.fury.io/js/codebox.svg)](http://badge.fury.io/js/codebox) + Codebox is a complete and modular Cloud IDE. It can run on any unix-like machine (Linux, Mac OS X). It is an open source component of [codebox.io](https://www.codebox.io) (Cloud IDE as a Service). The IDE can run on your desktop (Linux or Mac), on your server or the cloud. You can use the [codebox.io](https://www.codebox.io) service to host and manage IDE instances. @@ -10,7 +13,7 @@ Codebox is built with web technologies: `node.js`, `javascript`, `html` and `les The project is open source under the [Apache 2.0](https://github.com/FriendCode/codebox/blob/master/LICENSE) license. A screencast of the IDE is available on [Youtube](https://www.youtube.com/watch?v=xvPEngyXA2A). -![Image](https://raw.github.com/FriendCode/codebox/master/docs/assets/base.png) +![Image](https://raw.github.com/FriendCode/codebox/master/screenshot.png) ## How to install and run Codebox @@ -36,11 +39,21 @@ $ codebox run ./myworkspace --open Use this command to run and open Codebox IDE. By default, Codebox uses GIT to identify you, you can use the option ```--email=john.doe@gmail.com``` to define the email you want to use during GIT operations. -Others comand line options are available and can be list with: ```codebox --help```. For deeper configuration, take a look at the documentation about [environment variables](https://github.com/FriendCode/codebox/blob/master/docs/server/env.md). +Others comand line options are available and can be list with: ```codebox --help```. For deeper configuration, take a look at the documentation about [environment variables](http://help.codebox.io/ide/env.html). + +#### Command line options + +``` +-h, --help output usage information +-V, --version output the version number +-r, --root [path] Root folder for the workspace, default is current directory +-t, --templates [list] Configuration templates, separated by commas +-p, --port [port] HTTP port +``` #### Need help? -The IDE's documentation can be found in the [docs](../master/docs) folder. Feel free to ask any questions or signal problems by adding issues. +The IDE's documentation can be found at [help.codebox.io](http://help.codebox.io). Feel free to ask any questions or signal problems by adding issues. ## Helping Codebox @@ -56,3 +69,5 @@ The IDE's documentation can be found in the [docs](../master/docs) folder. Feel * **Twitter:** [@CodeboxIO](https://twitter.com/CodeboxIO) * **Blog:** [blog.codebox.io](http://blog.codebox.io) * **Youtube:** [Codebox Channel](http://www.youtube.com/channel/UCWocQwS2VmDS3Ej0LQYWVIw) + + diff --git a/addons/cb.collaborators/client.js b/addons/cb.collaborators/client.js deleted file mode 100644 index 3daf1e79..00000000 --- a/addons/cb.collaborators/client.js +++ /dev/null @@ -1,10 +0,0 @@ -define([], function() { - var $ = codebox.require("hr/dom"); - var collaborators = codebox.require("core/collaborators"); - var search = codebox.require("core/search"); - var box = codebox.require("core/box"); - var user = codebox.require("core/user"); - var menu = codebox.require("core/commands/menu"); - - -}); \ No newline at end of file diff --git a/addons/cb.collaborators/package.json b/addons/cb.collaborators/package.json deleted file mode 100644 index 6c65b466..00000000 --- a/addons/cb.collaborators/package.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "name": "cb.collaborators", - "version": "0.1.1", - "title": "Collaborators Menu", - "description": "Collaborators list in a menu.", - "homepage": "https://github.com/FriendCode/codebox", - "license": "Apache", - "author": { - "name": "Codebox", - "email": "contact@friendco.de", - "url": "https://www.codebox.io" - }, - "client": { - "main": "client" - } -} \ No newline at end of file diff --git a/addons/cb.deploy/client.js b/addons/cb.deploy/client.js deleted file mode 100644 index d65069c7..00000000 --- a/addons/cb.deploy/client.js +++ /dev/null @@ -1,230 +0,0 @@ -define([], function() { - var Q = codebox.require("hr/promise"); - var _ = codebox.require("hr/utils"); - var dialogs = codebox.require("utils/dialogs"); - var box = codebox.require("core/box"); - var rpc = codebox.require("core/backends/rpc"); - var Command = codebox.require("models/command"); - var menu = codebox.require("core/commands/menu"); - var user = codebox.require("core/user"); - - var CryptoJS = codebox.require("vendors/crypto"); - - // Settings for deployment - var settings = user.settings("deploymentSolutions"); - - // Return list of solutions - var getSolutionTypes = function() { - return rpc.execute("deploy/solutions"); - }; - - // Return infos for a specific solution type - var getSolutionType = function(id) { - return getSolutionTypes().then(function(_types) { - var s = _.find(_types, function(_type) { - return _type.id == id; - }); - if (!s) throw "Invalid solution type"; - return s; - }); - }; - - // Id for a solution name - var solutionId = function(name) { - return CryptoJS.MD5(name).toString(); - }; - - // Add a solution - var addSolution = function(name, solution) { - var solutions = settings.get("solutions", {}); - var id = solutionId(name); - if (solutions[id]) return Q.reject("Solution already exists"); - solutions[id] = { - 'name': name, - 'type': solution, - 'settings': {} - }; - settings.set("solutions", solutions); - return settings.save().then(function() { - return solutions[id]; - }); - }; - - // Remove a solution - var removeSolution = function(id) { - var solutions = settings.get("solutions", {}); - if (!solutions[id]) return Q.reject("Invalid solution"); - delete solutions[id]; - settings.set("solutions", solutions); - return settings.save(); - }; - - // Run a solution - var runSolution = function(solution, actionId) { - if (_.isString(solution)) solution = getSolution(solution); - - return rpc.execute("deploy/run", { - 'solution': solution.type, - 'action': actionId, - 'config': solution.settings - }) - .then(function(data) { - // Handle shells - if (data.shellId) { - box.openTerminal(data.shellId, { - id: "deploy."+solutionId(solution.name)+"."+actionId, - title: data.title || "Deployment to "+solution.name+" ("+actionId+")", - icon: "fa-cloud-upload" - }); - } - }, function(err) { - dialogs.alert("Error with "+_.escape(solution.name), err.message || err); - }); - }; - - // Return solution informations by its id - var getSolution = function(id) { - var solutions = settings.get("solutions", {}); - return solutions[id]; - }; - - var setSolutionSettings = function(id, _settings) { - var solutions = settings.get("solutions", {}); - solutions[id].settings = _settings; - settings.set("solutions", solutions); - }; - - // Open settings for a solution - var openSettings = function(id) { - var solution = getSolution(id); - return getSolutionType(solution.type).then(function(_type) { - return dialogs.fields("Configuration for "+_.escape(solution.name), _type.settings, solution.settings); - }) - .then(function(newSettings) { - setSolutionSettings(id, newSettings); - return settings.save(); - }); - }; - - // Command to add a new deployment solution - var addCommand = Command.register("deploy.solutions.add", { - title: "Add Solution", - offline: false, - action: function(page) { - getSolutionTypes().then(function(solutionTypes) { - return dialogs.fields("Add Deployment Solution", { - name: { - type: "text", - label: "Label" - }, - solution: { - type: "select", - label: "Type", - options: _.object(_.map(solutionTypes, function(solution) { - return [ - solution.id, - solution.name - ]; - })) - } - }); - }) - .then(function(data) { - if (!data.name || !data.solution) throw "Need 'name' and 'solution'"; - return addSolution(data.name, data.solution); - }) - .then(function(solution) { - return openSettings(solutionId(solution.name)); - }); - } - }); - - // Command to remove a solution - var removeCommand = Command.register("deploy.solutions.remove", { - title: "Remove Solution", - offline: false, - action: function() { - dialogs.select("Remove Deployment Dolution", - "Select a solution, this solution and its configuration will be removed from your settings.", - _.chain(settings.get("solutions", {})) - .map(function(solution, id) { - return [id, solution.name] - }) - .object() - .value()).then(removeSolution); - } - }); - - // Deploy Menu - var deployMenu = menu.register("deploy", { - title: "Deploy", - position: 90, - offline: false - }); - - // Update list of solutions - var updateSolutions = function() { - return getSolutionTypes().then(function(_types) { - var solutions = settings.get("solutions", {}); - - deployMenu.clearMenu(); - - // Add command to create new solutions - deployMenu.menuSection(_.compact([ - addCommand, - _.size(solutions) > 0 ? removeCommand : null - ])); - - // Add all solutions - if (_.size(solutions) == 0) return; - deployMenu.menuSection( - _.chain(solutions) - .map(function(solution, solutionId) { - var solutionType = _.find(_types, function(_type) { - return _type.id == solution.type; - }); - if (!solutionType) return null; - - var command = Command.register({ - title: solution.name, - type: "menu", - offline: false, - action: function() { - openSettings(solutionId(solution.name)); - } - }); - - command.menuSection( - _.map(solutionType.actions, function(action) { - return { - title: action.name, - offline: false, - action: function() { - return runSolution(solution, action.id); - } - }; - }) - ); - - command.menuSection([ - { - title: "Configure", - offline: false, - action: function() { - openSettings(solutionId); - } - } - ]); - - return command; - }) - .compact() - .value() - ); - }); - - }; - - updateSolutions(); - settings.change(updateSolutions); -}); \ No newline at end of file diff --git a/addons/cb.deploy/package.json b/addons/cb.deploy/package.json deleted file mode 100644 index 1faac33d..00000000 --- a/addons/cb.deploy/package.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "name": "cb.deploy", - "version": "0.1.0", - "title": "Project", - "description": "Deployment menu for all solutions", - "homepage": "https://github.com/FriendCode/codebox", - "license": "Apache", - "author": { - "name": "Codebox", - "email": "contact@friendco.de", - "url": "https://www.codebox.io" - }, - "client": { - "main": "client" - } -} \ No newline at end of file diff --git a/addons/cb.files.editor/ace.js b/addons/cb.files.editor/ace.js deleted file mode 100644 index 7090ee09..00000000 --- a/addons/cb.files.editor/ace.js +++ /dev/null @@ -1,10 +0,0 @@ -define([ - "ace/ace", - - // All the ace extensions we used - "ace/ext-modelist", - "ace/ext-language_tools", - "ace/ext-whitespace" -], function() { - return window.ace; -}); \ No newline at end of file diff --git a/addons/cb.files.editor/build.sh b/addons/cb.files.editor/build.sh deleted file mode 100755 index e6b2524b..00000000 --- a/addons/cb.files.editor/build.sh +++ /dev/null @@ -1,55 +0,0 @@ -#!/bin/bash - -# This script will prepare ace for running properly - -RM_EXTENSIONS=(elastic_tabstops_lite chromevox statusbar emmet error_marker keybinding_menu old_ie textarea themelist static_highlight split spellcheck settings_menu) -RM_LANG=(abap cobol forth mushcode vbscript tcl velocity pascal powershell asciidoc apache_conf ada soy_template verilog vhdl autohotkey batchfile c9search) - -# Sed like command using perl -# We need this because on OS X, sed does not support ignoring case -function PSED { - perl -C -e 'use utf8;' -i -pe $1 $2 -} - -# Remove useless extensions -for ext in ${RM_EXTENSIONS[*]} -do - echo "Remove extension $ext" - rm -f ace/ext-$ext.js -done - -# Remove languages -for lang in ${RM_LANG[*]} -do - echo "Remove language $lang" - - # Remove the files - rm -f "ace/mode-$lang.js" "ace/snippets/$lang.js" "ace/worker-$lang.js" - - # Remove any references in ext-modelist - - # Remove extension mapping - PSED "s/,?${lang}\:\[\"[^\"]+?\"\]//gi" ace/ext-modelist.js - - # Remove readable name mapping - PSED "s/,?${lang}\:\"\w+\"//gi" ace/ext-modelist.js -done - -# Cleanup our previous replaces -# Remove any bad comas left over from modelist -PSED "s/\{,/{/gi" ace/ext-modelist.js -PSED "s/,\}/{/gi" ace/ext-modelist.js - -# Detect empty snippets -# using the value of their 'snippetText' variable -SREGEX="snippetText=(\"\"|\'\')" - -# Remove empty snippet files -find ./ace/snippets -name "*.js" -print | \ -xargs grep -E ${SREGEX} -l | \ -xargs rm -f - - -# Remove useless themes -echo "Removes themes" -rm -rf ace/theme-*.js \ No newline at end of file diff --git a/addons/cb.files.editor/client.js b/addons/cb.files.editor/client.js deleted file mode 100644 index 0e5d8ded..00000000 --- a/addons/cb.files.editor/client.js +++ /dev/null @@ -1,124 +0,0 @@ -define([ - "ace", - "views/file", - "codecomplete" -], function(ace, FileEditorView, codecomplete) { - var $ = codebox.require("hr/dom"); - var commands = codebox.require("core/commands/toolbar"); - var settings = codebox.require("core/settings"); - var files = codebox.require("core/files"); - var languages = codebox.require("utils/languages"); - - var aceconfig = ace.require("ace/config"); - aceconfig.set("basePath", "static/addons/cb.files.editor/ace"); - - // Add settings - settings.add({ - 'namespace': "editor", - 'title': "Code Editor", - 'defaults': { - 'theme': "github", - 'fontsize': "12", - 'printmargincolumn': 80, - 'showprintmargin': false, - 'highlightactiveline': false, - 'wraplimitrange': 80, - 'enablesoftwrap': false, - 'enablesofttabs': true, - 'autocollaboration': true, - 'tabsize': 4, - 'keyboard': "textinput" - }, - 'fields': { - 'keyboard': { - 'label': "Keyboard mode", - 'type': "select", - 'options': { - "vim": "Vim", - "emacs": "Emacs", - "textinput": "Default" - } - }, - 'fontsize': { - 'label': "Font Size", - 'type': "number", - 'min': 10, - 'max': 30, - 'step': 1 - }, - 'printmargincolumn': { - 'label': "Print Margin Column", - 'type': "number", - 'min': 0, - 'max': 1000, - 'step': 1 - }, - 'wraplimitrange': { - 'label': "Wrap Limit Range", - 'type': "number", - 'min': 0, - 'max': 1000, - 'step': 1 - }, - 'autocollaboration': { - 'label': "Auto enable realtime collaboration", - 'type': "checkbox" - }, - 'showprintmargin': { - 'label': "Show Print Margin", - 'type': "checkbox" - }, - 'highlightactiveline': { - 'label': "Highlight Active Line", - 'type': "checkbox" - }, - 'enablesoftwrap': { - 'label': "Enable Soft Wrap", - 'type': "checkbox" - }, - 'enablesofttabs': { - 'label': "Use Soft Tabs", - 'type': "checkbox" - }, - 'tabsize': { - 'label': "Tab Size", - 'type': "number", - 'min': 0, - 'max': 1000, - 'step': 1 - } - } - }); - - // Build code files extensions list - var textExts = _.reduce(languages.LIST, function(list, language) { - list = list.concat(language.extensions || []); - if (language.primary_extension) list.push(language.primary_extension); - return list; - }, [ - // Defaults extensions - '.txt' - ]); - - // List of mime type - var mimeTypes = [ - "text/plain" - ]; - - // Add files handler - files.addHandler("ace", { - name: "Code Editor", - View: FileEditorView, - fallback: true, - setActive: true, - valid: function(file) { - return (!file.isDirectory() - && (_.contains(textExts, file.extension()) || _.contains(mimeTypes, file.get("mime")))); - } - }); - - // Return globals - return { - 'ace': ace - }; -}); \ No newline at end of file diff --git a/addons/cb.files.editor/codecomplete.js b/addons/cb.files.editor/codecomplete.js deleted file mode 100644 index 8f2fe97a..00000000 --- a/addons/cb.files.editor/codecomplete.js +++ /dev/null @@ -1,31 +0,0 @@ -define([ - "ace" -], function(ace) { - var rpc = codebox.require("core/backends/rpc"); - var langTools = ace.require("ace/ext/language_tools"); - - var normalizeTag = function(tag) { - return { - 'name': tag.name, - 'value': tag.name, - 'score': 0, - 'meta': tag.meta || "" - }; - }; - - langTools.addCompleter({ - getCompletions: function(editor, session, pos, prefix, callback) { - if (prefix.length === 0) { callback(null, []); return } - - rpc.execute("codecomplete/get", { - 'query': prefix - }).then(function(data) { - callback(null, _.map(data.results, normalizeTag)); - }, function(err) { - callback(err); - }); - } - }); - - return {}; -}); \ No newline at end of file diff --git a/addons/cb.files.editor/download_ace.sh b/addons/cb.files.editor/download_ace.sh deleted file mode 100755 index 02e24e97..00000000 --- a/addons/cb.files.editor/download_ace.sh +++ /dev/null @@ -1,28 +0,0 @@ -#!/bin/bash - -# Ace version to pull -ACE_VERSION="ec3677e978de275bbe1ff8f21f4a157bdb9b8f9e" -ACE_URL="https://github.com/FriendCode/ace-builds/archive/${ACE_VERSION}.tar.gz" - -# Ace build we want to keep -ACE_SUB="src-min-noconflict" - -# Current folder -DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" - -# Destination folder -DEST="${DIR}/ace" - -# Make sure $DEST exists -mkdir -p ${DEST} - -# Check if it's already downloaded -if [ -f "${DEST}/ace.js" ]; then - echo "Ace is already downloaded" - echo "'rm -rf ace' if you want to redownload" - exit 0 -fi - -# Download tar.gz and pipe to tar -# decompressing it to $DEST -wget -O - ${ACE_URL} | tar -xzv -C ${DEST} --strip-components=2 ace-builds-${ACE_VERSION}/${ACE_SUB} diff --git a/addons/cb.files.editor/package.json b/addons/cb.files.editor/package.json deleted file mode 100644 index c7f9bdf2..00000000 --- a/addons/cb.files.editor/package.json +++ /dev/null @@ -1,25 +0,0 @@ -{ - "name": "cb.files.editor", - "version": "0.1.1", - "title": "Code Editor", - "description": "Code Editor with ACE.", - "homepage": "https://github.com/FriendCode/codebox", - "license": "Apache", - "author": { - "name": "Codebox", - "email": "contact@friendco.de", - "url": "https://www.codebox.io" - }, - "client": { - "main": "client", - "provides": [ - "ace" - ], - "resources": [ - "ace/**" - ] - }, - "scripts": { - "postinstall": "./download_ace.sh && ./build.sh" - } -} diff --git a/addons/cb.files.editor/stylesheets/file.less b/addons/cb.files.editor/stylesheets/file.less deleted file mode 100644 index cdae1423..00000000 --- a/addons/cb.files.editor/stylesheets/file.less +++ /dev/null @@ -1,91 +0,0 @@ -.mixin-cursor-color(@color) { - @pseudo-selector: ~".marker-@{color}"; - @{pseudo-selector} { - &.marker-selection { - background: ~"#@{color}"; - } - } -} - -.addon-files-aceeditor { - .file-participants { - a { - position: relative; - overflow: hidden; - padding: 6px 10px; - border-left: 6px solid #eee; - } - } - - .editor-inner { - .editor-ace { - -webkit-font-smoothing: subpixel-antialiased; - font-smoothing: subpixel-antialiased; - - position: absolute !important; - top: 0px; - bottom: 0px; - left: 0px; - right: 0px; - border-radius: 0px; - padding: 0px; - - .marker-cursor { - position: absolute; - border-left: 2px solid red; - opacity: 1; - } - - .marker-selection { - position: absolute; - background: red; - opacity: 0.2; - } - .mixin-cursor-color("1abc9c"); - .mixin-cursor-color("9b59b6"); - .mixin-cursor-color("e67e22"); - .mixin-cursor-color("16a085"); - .mixin-cursor-color("c0392b"); - .mixin-cursor-color("2980b9"); - .mixin-cursor-color("f39c12"); - .mixin-cursor-color("8e44ad"); - - .marker-cursor { - position: absolute; - z-index: 5; - border-left: 2px solid #0ff; - margin-left: -1px; - right: 5px; - text-align: right; - color: #ff0; - border-bottom: 1px dotted rgba(0,255,255,0.30); - } - .marker-cursor-nametag { - position: absolute; - bottom: -1px; - right: 0px; - text-align: right; - color: #fff; - background: #0ff; - padding: 0px; - padding-left: 3px; - padding-right: 3px; - opacity: 1; - font-family: Arial, sans-serif; - font-weight: 600; - pointer-events: auto; - cursor: help; - } - .marker-cursor-nametag-flag { - position: absolute; - bottom: 0px; - left: -6px; - width: 0px; - height: 0px; - border: 3px solid rgba(0,255,255,0.00); - border-right: 3px solid #0ff; - border-bottom: 3px solid #0ff; - } - } - } -} diff --git a/addons/cb.files.editor/templates/file.html b/addons/cb.files.editor/templates/file.html deleted file mode 100644 index cbb2e425..00000000 --- a/addons/cb.files.editor/templates/file.html +++ /dev/null @@ -1,3 +0,0 @@ -
-
-
\ No newline at end of file diff --git a/addons/cb.files.editor/theme/textmate.js b/addons/cb.files.editor/theme/textmate.js deleted file mode 100644 index 1f0fa775..00000000 --- a/addons/cb.files.editor/theme/textmate.js +++ /dev/null @@ -1,10 +0,0 @@ -define([ - "less!theme/textmate.less" -], function(cssContent) { - - return { - 'isDark': false, - 'cssClass': "ace-tm", - 'cssText': cssContent - } -}); \ No newline at end of file diff --git a/addons/cb.files.editor/theme/textmate.less b/addons/cb.files.editor/theme/textmate.less deleted file mode 100644 index 269f85cf..00000000 --- a/addons/cb.files.editor/theme/textmate.less +++ /dev/null @@ -1,182 +0,0 @@ - - -.ace_editor { - /* Search dialog */ - .ace_search, .ace_search.right { - right: 0px; - left: 0px; - max-width: none; - bottom: 0px; - top: auto; - border: 1px solid; - border-radius: 0px; - padding: 0px; - box-shadow: 2px 3px 5px rgba(0,0,0,.2); - - font-smoothing: subpixel-antialiased; - -webkit-font-smoothing: subpixel-antialiased; - - .ace_searchbtn_close { - margin: 9px 5px 0px 5px; - } - - .ace_search_field { - } - - .ace_search_form, .ace_replace_form { - border-radius: 0px; - margin: 4px; - } - - .ace_search_options { - text-align: left; - display: inline-block; - float: right; - margin: 0px; - padding: 4px; - height: 24px; - } - - .ace_button { - border-radius: 0px; - padding: 2px 4px; - margin: 0 3px 0 0; - display: inline-block; - } - - .ace_searchbtn, .ace_replacebtn{ - padding: 0px 5px; - border-radius: 0px; - } - } - - &.ace-tm { - background-color: #FFFFFF; - color: #4D4D4C; - - .ace_gutter { - background: transparent; - color: #4D4D4C - } - - .ace_print-margin { - width: 1px; - background: #f6f6f6 - } - - .ace_cursor { - color: #AEAFAD - } - - .ace_marker-layer .ace_selection { - background: #eaeaea; - } - - &.ace_multiselect .ace_selection.ace_start { - box-shadow: 0 0 3px 0px #FFFFFF; - border-radius: 2px - } - - .ace_marker-layer .ace_step { - background: rgb(255, 255, 0) - } - - .ace_marker-layer .ace_bracket { - margin: -1px 0 0 -1px; - border: 1px solid #D1D1D1 - } - - .ace_marker-layer .ace_active-line { - background: #EFEFEF - } - - .ace_gutter-active-line { - background-color : transparent; - } - - .ace_marker-layer .ace_selected-word { - border: 1px solid #D6D6D6 - } - - .ace_invisible { - color: #D1D1D1 - } - - .ace_keyword, - .ace_meta, - .ace_storage, - .ace_storage.ace_type, - .ace_support.ace_type { - color: #8959A8 - } - - .ace_keyword.ace_operator { - color: #3E999F - } - - .ace_constant.ace_character, - .ace_constant.ace_language, - .ace_constant.ace_numeric, - .ace_keyword.ace_other.ace_unit, - .ace_support.ace_constant, - .ace_variable.ace_parameter { - color: #F5871F - } - - .ace_constant.ace_other { - color: #666969 - } - - .ace_invalid { - color: #FFFFFF; - background-color: #C82829 - } - - .ace_invalid.ace_deprecated { - color: #FFFFFF; - background-color: #8959A8 - } - - .ace_fold { - background-color: #4271AE; - border-color: #4D4D4C - } - - .ace_entity.ace_name.ace_function, - .ace_support.ace_function, - .ace_variable { - color: #4271AE - } - - .ace_support.ace_class, - .ace_support.ace_type { - color: #C99E00 - } - - .ace_heading, - .ace_string { - color: #718C00 - } - - .ace_entity.ace_name.ace_tag, - .ace_entity.ace_other.ace_attribute-name, - .ace_meta.ace_tag, - .ace_string.ace_regexp, - .ace_variable { - color: #C82829 - } - - .ace_comment { - color: #8E908C - } - - .ace_indent-guide { - background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAACCAYAAACZgbYnAAAAE0lEQVQImWP4////f4bdu3f/BwAlfgctduB85QAAAABJRU5ErkJggg==) right repeat-y - } - - .ace_search { - border-color: #cbcbcb; - background: #e5e5e5; - } - } -} \ No newline at end of file diff --git a/addons/cb.files.editor/views/file.js b/addons/cb.files.editor/views/file.js deleted file mode 100644 index d3b68a20..00000000 --- a/addons/cb.files.editor/views/file.js +++ /dev/null @@ -1,509 +0,0 @@ -define([ - "ace", - "theme/textmate", - "text!templates/file.html", - "less!stylesheets/file.less", -], function(ace, aceDefaultTheme, templateFile) { - var _ = codebox.require("hr/utils"); - var $ = codebox.require("hr/dom"); - var hr = codebox.require("hr/hr"); - var alerts = codebox.require("utils/alerts"); - var FilesTabView = codebox.require("views/files/tab"); - var FileSync = codebox.require("utils/filesync"); - var user = codebox.require("core/user"); - var menu = codebox.require("core/commands/menu"); - var settings = codebox.require("core/settings"); - var Command = codebox.require("models/command"); - var themes = codebox.require("core/themes"); - var box = codebox.require("core/box"); - var collaborators = codebox.require("core/collaborators"); - var keyboard = codebox.require("utils/keyboard"); - - var logging = hr.Logger.addNamespace("editor"); - var userSettings = user.settings("editor"); - - // Import ace - var aceRange = ace.require("ace/range"); - var aceModes = ace.require("ace/ext/modelist"); - var aceLangs = ace.require("ace/ext/language_tools"); - var aceWhitespace = ace.require("ace/ext/whitespace"); - - - var FileEditorView = FilesTabView.extend({ - className: "addon-files-aceeditor", - templateLoader: "text", - template: templateFile, - defaults: {}, - events: {}, - shortcuts: { - "mod+s": "saveFile", - "mod+r": "runFile", - "mod+f": "searchInFile" - }, - - // Constructor - initialize: function() { - var that = this; - FileEditorView.__super__.initialize.apply(this, arguments); - - // Syntax menu command - var syntaxMenu = new Command({}, { - 'title': "Syntax", - 'type': "menu" - }); - syntaxMenu.menu.add(_.map(aceModes.modesByName, function(mode, name) { - return { - 'title': mode.caption, - 'action': function() { - that.setMode(name); - } - } - })); - - // Toggle collaboration - this.collaborationToggle = new Command({}, { - 'type': "checkbox", - 'title': "Toggle Collaboration Mode", - 'flags': this.model.isNewfile() ? "hidden": "", - 'offline': false, - 'action': function(state) { - that.editor - that.sync.updateEnv({ - 'sync': state - }); - } - }); - - // Collaborators - this.collaboratorsMenu = new Command({}, { - 'title': "Collaborators", - 'type': "menu", - 'flags': "disabled" - }); - - // Tab menu - this.tab.menu.menuSection([ - { - 'type': "action", - 'title': "Save", - 'shortcuts': [ - "mod+s" - ], - 'bindKeyboard': false, - 'action': function() { - that.sync.save(); - } - }, - { - 'type': "action", - 'title': "Run File", - 'shortcuts': [ - "mod+r" - ], - 'flags': this.model.isNewfile() ? "disabled": "", - 'bindKeyboard': false, - 'action': function() { - that.model.run(); - } - } - ]).menuSection([ - this.collaborationToggle, - syntaxMenu - ]).menuSection([ - { - 'title': "Convert Indentation to Spaces", - 'action': function() { - that.convertIndentation(" ", userSettings.get("tabsize", 4)); - } - }, - { - 'title': "Convert Indentation to Tabs", - 'action': function() { - that.convertIndentation("\t", 1); - } - } - ]).menuSection([ - this.collaboratorsMenu - ]).menuSection([{ - 'type': "action", - 'title': "Settings", - 'offline': false, - 'action': function() { - settings.open("editor"); - } - }]); - - // Create sync - this.sync = new FileSync(); - this.sync.on("update:env", function(options) { - if (options.reset) { - this._op_set = true; - this.editor.setValue(""); - this._op_set = false; - } - this.collaborationToggle.toggleFlag("active", options.sync); - this.collaboratorsMenu.toggleFlag("disabled", !options.sync); - }, this); - - // Create base ace editor instance - this.$editor = $("
", { - 'class': "editor-ace" - }); - this.editor = ace.edit(this.$editor.get(0)); - this.editor.session.setUseWorker(true); - this.setOptions(); - this.markersS = {}; - this.markersC = {}; - this._op_set = false; - - // Configure editor - this.editor.setOptions({ - enableBasicAutocompletion: true, - enableSnippets: true - }); - - // Bind settings changement - var update = function() { - var ops = _.extend({}, { - "mode": this.options.mode, - "readonly": this.options.readonly - }); - this.setOptions(ops); - }; - userSettings.change(update, this); - user.settings("themes").change(update, this); - - // Bind editor changement -> sync - this.editor.getSession().selection.on('changeSelection', function(){ - var selection = that.editor.getSelectionRange(); - that.sync.updateUserSelection(selection.start.column, selection.start.row, selection.end.column, selection.end.row); - }); - this.editor.getSession().selection.on('changeCursor', function(){ - var cursor = that.editor.getSession().getSelection().getCursor(); - that.sync.updateUserCursor(cursor.column, cursor.row); - }); - - var $doc = this.editor.session.doc; - - // Force unix newline mode (for cursor position calcul) - $doc.setNewLineMode("unix"); - - // Send change - $doc.on('change', function(d) { - if (that._op_set) return; - that.sync.updateContent(that.editor.session.getValue()); - }); - - // Bind sync -> editor - this.sync.on("file:mode", function(mode) { - this.setMode(mode) - }, this); - this.sync.on("content", function(content, oldcontent, patches) { - var selection, cursor_lead, cursor_anchor, scroll_y, operations; - - // if resync patches is null - patches = patches || []; - - // Calcul operaitons from patch - operations = this.sync.patchesToOps(patches); - - // Do some operations on selection to preserve selection - selection = this.editor.getSession().getSelection(); - - scroll_y = this.editor.getSession().getScrollTop(); - - cursor_lead = selection.getSelectionLead(); - cursor_lead = this.sync.cursorApplyOps({ - x: cursor_lead.column, - y: cursor_lead.row - }, operations, oldcontent); - - cursor_anchor = selection.getSelectionAnchor(); - cursor_anchor = this.sync.cursorApplyOps({ - x: cursor_anchor.column, - y: cursor_anchor.row - }, operations, oldcontent); - - // Set editor content - this._op_set = true; - - // Apply ace delta all in once - $doc.applyDeltas( - _.map(operations, function(op) { - return { - action: op.type+"Text", - range: { - start: that.posFromIndex(op.index), - end: that.posFromIndex(op.index + op.content.length) - }, - text: op.content - } - }) - ); - - // Check document content is as expected - if ($doc.getValue() != content) { - logging.error("Invalid operation ", content, $doc.getValue()); - $doc.setValue(content); - this.sync.sendSync(); - } - this._op_set = false; - - // Move cursors - this.editor.getSession().setScrollTop(scroll_y); - - cursor_anchor = this.sync.cursorPosByindex(cursor_anchor, content); - this.editor.getSession().getSelection().setSelectionAnchor(cursor_anchor.y, cursor_anchor.x); - - cursor_lead = this.sync.cursorPosByindex(cursor_lead, content); - this.editor.getSession().getSelection().selectTo(cursor_lead.y, cursor_lead.x); - }, this); - - // Participant cursor moves - this.sync.on("cursor:move", function(cId, c) { - var name, range = new aceRange.Range(c.y, c.x, c.y, c.x+1); - - // Remove old cursor - if (this.markersC[cId]) this.editor.getSession().removeMarker(this.markersC[cId]); - - // Calcul name - name = cId - var participant = collaborators.getById(cId); - if (participant) name = participant.get("name"); - - // Add new cursor - this.markersC[cId] = this.editor.getSession().addMarker(range, "marker-cursor marker-"+c.color.replace("#", ""), function(html, range, left, top, config){ - html.push("
" - + "
 "+name+" 
" - + "
 
"); - }, true); - }, this); - - // Participant selection - this.sync.on("selection:move", function(cId, c) { - var range = new aceRange.Range(c.start.y, c.start.x, c.end.y, c.end.x); - if (this.markersS[cId]) this.editor.getSession().removeMarker(this.markersS[cId]); - this.markersS[cId] = this.editor.getSession().addMarker(range, "marker-selection marker-"+c.color.replace("#", ""), "line", false); - }, this); - - // Remove a cursor/selection - this.sync.on("cursor:remove selection:remove", function(cId) { - if (this.markersC[cId]) this.editor.getSession().removeMarker(this.markersC[cId]); - if (this.markersS[cId]) this.editor.getSession().removeMarker(this.markersS[cId]); - delete this.markersC[cId]; - delete this.markersS[cId] - }, this); - - // Participants list change - this.sync.on("participants", function() { - this.collaboratorsMenu.set("label", _.size(this.sync.participants)); - this.collaboratorsMenu.menu.reset(_.map(this.sync.participants, function(participant) { - return { - 'type': "action", - 'title': participant.user.get("name"), - 'action': function() { - that.editor.getSession().getSelection().setSelectionAnchor(participant.cursor.y, participant.cursor.x); - that.editor.getSession().getSelection().selectTo(participant.cursor.y, participant.cursor.x); - that.editor.focus(); - } - } - })); - }, this); - - // Parent tab - this.tab.on("tab:layout", function() { - this.editor.resize(); - }, this); - this.tab.on("tab:state", function(state) { - if (state) this.focus(); - }, this); - this.tab.on("tab:close", function() { - this.sync.close(); - this.off(); - }, this); - - // Bind editor sync state changements - this.sync.on("sync:state", function(state) { - this.editor.setReadOnly(!state); - if (!state) { - this.tab.setTabState("warning", true); - } else { - this.tab.setTabState("warning", false); - } - }, this); - this.sync.on("mode", function(mode) { - this.tab.setTabState("sync", mode == this.sync.modes.SYNC); - }, this); - this.sync.on("close", function(mode) { - this.tab.closeTab(); - }, this); - this.sync.on("error", function(err) { - alerts.show("Error: "+(err.message || err), 3000); - }, this); - - this.sync.on("sync:modified", function(state) { - this.tab.setTabState("modified", state); - }, this); - - this.sync.on("sync:loading", function(state) { - this.tab.setTabState("loading", state); - }, this); - - // Define file for code editor - this.sync.setFile(this.model, { - 'sync': userSettings.get("autocollaboration") ? collaborators.size() > 1 : false - }); - this.focus(); - - var $input = this.editor.textInput.getElement(); - var handleKeyEvent = function(e) { - if (!e.altKey && !e.ctrlKey && !e.metaKey) return; - keyboard.enableKeyEvent(e); - }; - $input.addEventListener('keypress', handleKeyEvent, false); - $input.addEventListener('keydown', handleKeyEvent, false); - $input.addEventListener('keyup', handleKeyEvent, false); - }, - - // Finish rendering - finish: function() { - // Add editor to content - this.$editor.appendTo(this.$(".editor-inner")); - this.editor.resize(); - this.editor.renderer.updateFull(); - - return FileEditorView.__super__.finish.apply(this, arguments); - }, - - focus: function() { - this.editor.focus(); - return this; - }, - - /* - * Set editor options: theme, fontsize, ... - */ - setOptions: function(opts) { - this.options = _.defaults(opts || {}, userSettings.all({}), { - mode: "text", - fontsize: "12", - printmargincolumn: 80, - showprintmargin: false, - highlightactiveline: false, - wraplimitrange: 80, - enablesoftwrap: false, - keyboard: "textinput", - enablesofttabs: true, - tabsize: 4 - }); - - this.setMode(this.options.mode); - this.setKeyboardmode(this.options.keyboard); - this.setTheme(themes.current().editor.theme || aceDefaultTheme); - this.$editor.css("font-size", this.options.fontsize+"px"); - this.editor.setPrintMarginColumn(this.options.printmargincolumn); - this.editor.setShowPrintMargin(this.options.showprintmargin); - this.editor.setHighlightActiveLine(this.options.highlightactiveline); - this.editor.getSession().setUseWrapMode(this.options.enablesoftwrap); - this.editor.getSession().setWrapLimitRange(this.options.wraplimitrange, this.options.wraplimitrange); - this.editor.getSession().setUseSoftTabs(this.options.enablesofttabs); - this.editor.getSession().setTabSize(this.options.tabsize); - return this; - }, - - posFromIndex: function(index) { - var row, lines; - lines = this.editor.session.doc.getAllLines(); - for (row = 0; row < lines.length; row++) { - var line = lines[row]; - if (index <= (line.length)) break; - index = index - (line.length + 1); - } - - return { - 'row': row, - 'column': index - }; - }, - - /* - * Get editor mode - */ - getMode: function() { - return this.options.mode; - }, - - /* - * Set editor mode - * @lang : editor lang mode - */ - setMode: function(lang) { - this.options.mode = lang; - this.editor.getSession().setMode("ace/mode/"+lang); - this.trigger("change:mode"); - return this; - }, - - /* - * Set editor keyboard mode - * @mode: keyboard mode (vim, emacs) - */ - setKeyboardmode: function(mode) { - var self = this; - this.options.keyboard = mode; - ace.config.loadModule(["keybinding", "ace/keyboard/"+self.options.keyboard], function(binding) { - if (binding && binding.handler) { - self.editor.setKeyboardHandler(binding.handler); - self.trigger("change:keyboardmode"); - } - }); - return this; - }, - - /* - * Set theme - * @theme_name : name of the theme - */ - setTheme: function(theme) { - if (_.isString(theme)) { - theme = "ace/theme/" + theme; - } - this.editor.setTheme(theme); - this.trigger("change:theme"); - return this; - }, - - /* - * Convert indentations to - */ - convertIndentation: function(ch, len) { - aceWhitespace.convertIndentation(this.editor.session, ch, len); - }, - - /* - * Save file - */ - saveFile: function(e) { - if (e) e.preventDefault(); - this.sync.save(); - }, - - /* - * Run this file - */ - runFile: function(e) { - if (e) e.preventDefault(); - this.model.run(); - }, - - /* - * Open search box in code editor - */ - searchInFile: function(e) { - if (e) e.preventDefault(); - this.editor.execCommand("find"); - } - }); - - return FileEditorView; -}); \ No newline at end of file diff --git a/addons/cb.files.image/client.js b/addons/cb.files.image/client.js deleted file mode 100644 index 4e584efd..00000000 --- a/addons/cb.files.image/client.js +++ /dev/null @@ -1,18 +0,0 @@ -define([ - "views/image" -], function(FileImageView) { - var _ = codebox.require("hr/utils"); - var files = codebox.require("core/files"); - - var imageExts = [ - ".png", ".jpg", ".gif", ".tiff", ".jpeg", ".bmp", ".webp", ".svg" - ]; - - files.addHandler("imageviewer", { - name: "Image Viewer", - View: FileImageView, - valid: function(file) { - return (!file.isDirectory() && _.contains(imageExts, file.extension())); - } - }); -}); \ No newline at end of file diff --git a/addons/cb.files.image/package.json b/addons/cb.files.image/package.json deleted file mode 100644 index e81b3140..00000000 --- a/addons/cb.files.image/package.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "name": "cb.files.image", - "version": "0.0.1", - "title": "Image Viewer", - "description": "Images files viewer (png, jpeg, gif).", - "homepage": "https://github.com/FriendCode/codebox", - "license": "Apache", - "author": { - "name": "Codebox", - "email": "contact@friendco.de", - "url": "https://www.codebox.io" - }, - "client": { - "main": "client" - } -} diff --git a/addons/cb.files.image/stylesheets/image.less b/addons/cb.files.image/stylesheets/image.less deleted file mode 100644 index 8e5abe6b..00000000 --- a/addons/cb.files.image/stylesheets/image.less +++ /dev/null @@ -1,5 +0,0 @@ -.addon-files-aceeditor { - .image { - - } -} \ No newline at end of file diff --git a/addons/cb.files.image/templates/image.html b/addons/cb.files.image/templates/image.html deleted file mode 100644 index 40e7dc5f..00000000 --- a/addons/cb.files.image/templates/image.html +++ /dev/null @@ -1 +0,0 @@ -
\ No newline at end of file diff --git a/addons/cb.files.image/views/image.js b/addons/cb.files.image/views/image.js deleted file mode 100644 index 9b0182ce..00000000 --- a/addons/cb.files.image/views/image.js +++ /dev/null @@ -1,19 +0,0 @@ -define([ - "text!templates/image.html", - "less!stylesheets/image.less" -], function(templateFile) { - var _ = codebox.require("hr/utils"); - var $ = codebox.require("hr/dom"); - var hr = codebox.require("hr/hr"); - var Dialogs = codebox.require("utils/dialogs"); - var FilesBaseView = codebox.require("views/files/base"); - - var FileImageView = FilesBaseView.extend({ - className: "addon-files-imageviewer", - templateLoader: "text", - template: templateFile, - events: {} - }); - - return FileImageView; -}); \ No newline at end of file diff --git a/addons/cb.git/client.js b/addons/cb.git/client.js deleted file mode 100644 index 0efc3d6f..00000000 --- a/addons/cb.git/client.js +++ /dev/null @@ -1,241 +0,0 @@ -define(["views/dialog"], function(GitDialog) { - var commands = codebox.require("core/commands/toolbar"); - var app = codebox.require("core/app"); - var box = codebox.require("core/box"); - var dialogs = codebox.require("utils/dialogs"); - var menu = codebox.require("core/commands/menu"); - var box = codebox.require("core/box"); - var Command = codebox.require("models/command"); - var rpc = codebox.require("core/backends/rpc"); - var operations = codebox.require("core/operations"); - - // Check git status - var updateStatus = function() { - return rpc.execute("git/status") - .then(function() { - updateMenu(true); - return updateBranchesMenu(); - }, function(err) { - updateMenu(false); - }) - }; - - // Branches menu - var branchesMenu = Command.register({ - 'title': "Switch To Branch", - 'type': "menu", - 'offline': false - }); - var updateBranchesMenu = function() { - return rpc.execute("git/branches") - .then(function(branches) { - branchesMenu.menu.reset(_.map(branches, function(branch) { - return { - 'title': branch.name, - 'flags': branch.active ? "active" : "", - 'action': function() { - var ref = branch.name; - return operations.start("git.checkout", function(op) { - return rpc.execute("git/checkout", { - 'ref': ref - }) - }, { - title: "Checkout '"+ref+"'" - }).then(updateBranchesMenu); - } - } - })); - }); - }; - - // Handle http auth - var handleHttpAuth = function(method) { - return Q(method()) - .fail(function(err) { - if (err.code == 401) { - // Fields for https auth - var fields = { - username: { - type: "text", - label: "Username" - }, - password: { - type: "password", - label: "Password" - } - }; - - // Passphrase for ssh - if (err.message.toLowerCase().indexOf("authentication") < 0) { - fields = { - passphrase: { - type: "text", - label: "Passphrase" - } - }; - } - - return dialogs.fields("Need authentication:", fields) - .then(method); - } - }) - }; - - // Add menu - var gitMenu = menu.register("git", { - title: "Repository", - offline: false - }); - - var updateMenu = function(state) { - // Clear menu - gitMenu.clearMenu(); - - // Invalid repository - if (!state) { - gitMenu.menuSection([ - { - 'title': "No GIT Repository detected", - 'type': "label", - 'iconMenu': "warning" - }, - { - 'title': "Initialize Local Repository", - 'offline': false, - 'action': function() { - return operations.start("git.init", function(op) { - return rpc.execute("git/init") - }, { - title: "Initializing GIT repository" - }); - } - }, - { - 'title': "Clone Remote Repository", - 'offline': false, - 'action': function() { - return operations.start("git.clone", function(op) { - return dialogs.prompt("Clone Remote Repository", "Remote repository URI:").then(function(url) { - if (!url) return; - return handleHttpAuth(function(creds) { - return rpc.execute("git/clone", { - 'url': url, - 'auth': creds || {} - }); - }); - }); - }, { - title: "Cloning GIT repository" - }); - } - } - ]); - } else { - gitMenu.menuSection([ - { - 'title': "Commit", - 'shortcuts': ["mod+shift+C"], - 'offline': false, - 'action': function() { - dialogs.open(GitDialog); - } - } - ]).menuSection([ - { - 'title': "Synchronize", - 'shortcuts': ["mod+S"], - 'offline': false, - 'action': function() { - return operations.start("git.sync", function(op) { - return handleHttpAuth(function(creds) { - return rpc.execute("git/sync", { - 'auth': creds || {} - }); - }); - }, { - title: "Pushing & Pulling" - }); - } - }, - { - 'title': "Push", - 'shortcuts': ["mod+P"], - 'offline': false, - 'action': function() { - return operations.start("git.push", function(op) { - return handleHttpAuth(function(creds) { - return rpc.execute("git/push", { - 'auth': creds || {} - }); - }); - }, { - title: "Pushing" - }); - } - }, - { - 'title': "Pull", - 'shortcuts': ["shift+mod+P"], - 'offline': false, - 'action': function() { - return operations.start("git.pull", function(op) { - return handleHttpAuth(function(creds) { - return rpc.execute("git/pull", { - 'auth': creds || {} - }); - }); - }, { - title: "Pulling" - }); - } - } - ]).menuSection([ - branchesMenu, - { - 'title': "Refresh branches", - 'offline': false, - 'action': updateBranchesMenu, - } - ]).menuSection([ - { - 'title': "Create a branch", - 'offline': false, - 'action': function() { - dialogs.prompt("Create a branch", "Enter the name for the new branch:").then(function(name) { - if (!name) return; - operations.start("git.branch.create", function(op) { - return rpc.execute("git/branch/create", { - 'name': name - }) - }, { - title: "Creating branch '"+name+"'" - }); - }); - } - }, - { - 'title': "Delete a branch", - 'offline': false, - 'action': function() { - dialogs.prompt("Delete a branch", "Enter the name of the branch you want to delete:").then(function(name) { - if (!name) return; - operations.start("git.branch.delete", function(op) { - return rpc.execute("git/branch/delete", { - 'name': name - }) - }, { - title: "Deleting branch '"+name+"'" - }).then(updateBranchesMenu); - }); - } - } - ]); - } - }; - - box.on("box:git", function() { - updateStatus(); - }); - updateStatus(); -}); - diff --git a/addons/cb.git/node/main.js b/addons/cb.git/node/main.js deleted file mode 100644 index f23406be..00000000 --- a/addons/cb.git/node/main.js +++ /dev/null @@ -1,29 +0,0 @@ -// Requires -var _ = require('lodash'); -var Gittle = require('gittle'); -var GitRPCService = require('./service').GitRPCService; - - -function setup(options, imports, register) { - // Import - var rpc = imports.rpc; - var events = imports.events; - var workspace = imports.workspace; - - // Service - var service = new GitRPCService(workspace, events); - - // Register RPC - rpc.register('git', service); - - // Register - register(null, { - "git": { - repo: service.repo, - }, - "git_rpc": service - }); -} - -// Exports -module.exports = setup; diff --git a/addons/cb.git/node/service.js b/addons/cb.git/node/service.js deleted file mode 100644 index 0404ae7d..00000000 --- a/addons/cb.git/node/service.js +++ /dev/null @@ -1,150 +0,0 @@ -// Requires -var Q = require('q'); -var _ = require('lodash'); -var Gittle = require('gittle'); - -function GitRPCService(workspace, events) { - this.workspace = workspace; - this.events = events; - - this.repo = new Gittle(workspace.root); - - _.bindAll(this); -} - -GitRPCService.prototype.init = function(args, meta) { - var that = this; - return Gittle.init(this.workspace.root).then(function(repo) { - that.events.emit('git.init', { - userId: meta.user.userId - }); - - that.repo = repo; - return that.repo.status(); - }); -}; - -GitRPCService.prototype.clone = function(args, meta) { - var that = this; - if (!args.url) throw "Need an url for cloning a repository"; - return Gittle.clone(args.url, this.workspace.root, args.auth || {}).then(function(repo) { - that.events.emit('git.clone', { - userId: meta.user.userId, - url: args.url - }); - - that.repo = repo; - return that.repo.status(); - }); -}; - -GitRPCService.prototype.status = function() { - return this.repo.status(); -}; - -GitRPCService.prototype.sync = function(args, meta) { - var that = this; - return this.repo.sync(null, null, args.auth || {}) - .then(function() { - that.events.emit('git.sync', { - userId: meta.user.userId - }); - }); -}; - -GitRPCService.prototype.push = function(args, meta) { - var that = this; - return this.repo.push(null, null, args.auth || {}) - .then(function() { - that.events.emit('git.push', { - userId: meta.user.userId - }); - }); -}; - -GitRPCService.prototype.pull = function(args, meta) { - var that = this; - return this.repo.pull(null, null, args.auth || {}) - .then(function() { - that.events.emit('git.pull', { - userId: meta.user.userId - }); - }); -}; - -GitRPCService.prototype.commit = function(args, meta) { - var msg = args.message; - var files = args.files || []; - var name = meta.user.name; - var email = meta.user.email; - - if(!_.all([msg, files, name, email])) { - return Q.reject(new Error("Could not commit because arguments are missing and/or invalid")); - } - - var that = this; - return this.repo.commitWith(name, email, msg, files) - .then(function() { - that.events.emit('git.commit', { - userId: meta.user.userId, - - message: msg, - name: name, - email: email, - files: files - }); - }); -}; - -GitRPCService.prototype.commits = function(args) { - return this.repo.commits(args.ref, args.limit, args.skip); -}; - -GitRPCService.prototype.branches = function(args) { - var activeBranch, that = this; - - // Get current active branch - return this.repo.branch().then(function(branch) { - activeBranch = branch; - - // Get all local branches - return that.repo.branches(); - }).then(function(branches) { - return _.map(branches, function(branch) { - return { - 'name': branch.name, - 'active': branch.name == activeBranch.name - } - }); - }) -}; - -GitRPCService.prototype.branch_create = function(args) { - if (!args.name) return Q.reject(new Error("Need a name to create a branch")); - return this.repo.create_branch(args.name); -}; - -GitRPCService.prototype.checkout = function(args) { - if (!args.ref) return Q.reject(new Error("Need a referance (ref) to checkout")); - return this.repo.checkout(args.ref); -}; - -GitRPCService.prototype.branch_delete = function(args) { - if (!args.name) return Q.reject(new Error("Need a name to delete a branch")); - return this.repo.delete_branch(args.name); -}; - -GitRPCService.prototype.commits_pending = function() { - return this.repo.commits_pending(); -}; - -GitRPCService.prototype.diff = function(args) { - return this.repo.diff(args.new, args.old).then(function(diffs) { - return _.map(diffs, function(diff) { - return diff.normalize(); - }) - }); -}; - -// Exports -exports.GitRPCService = GitRPCService; diff --git a/addons/cb.git/package.json b/addons/cb.git/package.json deleted file mode 100644 index 84ec2a0e..00000000 --- a/addons/cb.git/package.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "name": "cb.git", - "version": "0.0.3", - "title": "GIT", - "description": "Integration of Git into your workspace.", - "homepage": "https://github.com/FriendCode/codebox", - "license": "Apache", - "author": { - "name": "Codebox", - "email": "contact@friendco.de", - "url": "https://www.codebox.io" - }, - "client": { - "main": "client" - }, - "main": "./node/main", - "plugin": { - "provides": [ - "git", - "git_rpc" - ], - "consumes": [ - "rpc", - "events", - "workspace" - ] - } -} \ No newline at end of file diff --git a/addons/cb.git/stylesheets/git.less b/addons/cb.git/stylesheets/git.less deleted file mode 100644 index 6ee1e81e..00000000 --- a/addons/cb.git/stylesheets/git.less +++ /dev/null @@ -1,64 +0,0 @@ -.addon-git-dialog { - .modal-body { - padding: 0px; - } - .modal-footer { - margin: 0px; - } - - .navbar { - margin: 0px; - } - - .git-changes { - .git-commit { - padding: 15px 10px; - margin: 0px; - background: #f8f8f8; - - textarea { - resize: none; - } - } - - .git-changes-files { - list-style: none; - margin: 0px; - padding: 0px; - - .file { - background: #fdfdfd; - box-shadow: 0px 1px 0px #fff inset; - border-top: 1px solid #ddd; - padding: 6px; - padding-left: 55px; - position: relative; - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; - - .file-type { - position: absolute; - display: block; - top: 0px; - left: 0px; - width: 45px; - bottom: 0px; - padding: 6px; - text-align: center; - color: #fff; - - &.type-M { - background: #3498db; - } - &.type-A { - background: #2ecc71; - } - &.type-D { - background: #e74c3c; - } - } - } - } - } -} \ No newline at end of file diff --git a/addons/cb.git/templates/dialog.html b/addons/cb.git/templates/dialog.html deleted file mode 100644 index 299a6aef..00000000 --- a/addons/cb.git/templates/dialog.html +++ /dev/null @@ -1,28 +0,0 @@ - \ No newline at end of file diff --git a/addons/cb.git/views/dialog.js b/addons/cb.git/views/dialog.js deleted file mode 100644 index 139a7fa4..00000000 --- a/addons/cb.git/views/dialog.js +++ /dev/null @@ -1,75 +0,0 @@ -define([ - "text!templates/dialog.html", - "less!stylesheets/git.less" -], function(templateFile) { - var DialogView = codebox.require("views/dialogs/base"); - var box = codebox.require("core/box"); - var rpc = codebox.require("core/backends/rpc"); - var operations = codebox.require("core/operations"); - - var GitDialog = DialogView.extend({ - className: "addon-git-dialog modal fade", - templateLoader: "text", - template: templateFile, - events: _.extend({}, DialogView.prototype.events,{ - "submit form": "submit" - }), - - // Constructor - initialize: function(options) { - var that = this; - GitDialog.__super__.initialize.apply(this, arguments); - - that.git = null; - - rpc.execute("git/status").then(function(status) { - that.git = status; - that.render(); - }); - return this; - }, - - // Template Context - templateContext: function() { - return { - git: this.git - }; - }, - - // Render - render: function() { - if (!this.git) return this; - return GitDialog.__super__.render.apply(this, arguments); - }, - - // Finish rendering - finish: function() { - return GitDialog.__super__.finish.apply(this, arguments); - }, - - // Commit (and sync) - submit: function(e) { - if (e) e.preventDefault(); - - var that = this; - var sync = this.$(".git-commit .btn-git-sync").hasClass("active"); - var message = this.$(".git-commit textarea").val(); - - if (message.length == 0) { - return; - } - - operations.start("git.commit", function(op) { - return rpc.execute("git/commit", { - 'message': message - }); - }, { - title: "Commiting" - }).then(function() { - that.close(); - }) - } - }); - - return GitDialog; -}); \ No newline at end of file diff --git a/addons/cb.help/client.js b/addons/cb.help/client.js deleted file mode 100644 index 71a724b7..00000000 --- a/addons/cb.help/client.js +++ /dev/null @@ -1,57 +0,0 @@ -define(["views/dialog"], function(HelpDialog) { - var hr = codebox.require("hr/hr"); - var app = codebox.require("core/app"); - var menu = codebox.require("core/commands/menu"); - var files = codebox.require("core/files"); - var rpc = codebox.require("core/backends/rpc"); - var dialogs = codebox.require("utils/dialogs"); - var Command = codebox.require("models/command"); - - // Command open changelog - var commandChanges = Command.register({ - 'id': "help.changes", - 'title': "Open Release Notes", - 'action': function(title) { - return rpc.execute("box/changes").then(function(changes) { - return files.openNew(title || "Release Notes", changes.content); - }); - } - }); - - // Add menu - menu.register("help", { - title: "Help", - position: 100 - }).menuSection([ - commandChanges, - { - 'id': "help.documentation", - 'title': "Documentation", - 'shortcuts': ['?'], - 'action': function() { - dialogs.open(HelpDialog); - } - } - ]).menuSection([ - { - 'id': "help.feedback", - 'title': "Submit feedback", - 'offline': false, - 'action': function() { - window.open("https://github.com/FriendCode/codebox/issues"); - } - } - ]); - - // Open changes if version changes - app.once("ready", function() { - var currentVersion = hr.configs.args.version; - var lastVersion = hr.Storage.get("codeboxVersion"); - - if (currentVersion != lastVersion) { - commandChanges.run(); - } - hr.Storage.set("codeboxVersion", currentVersion); - }); -}); - diff --git a/addons/cb.help/extensions/github.js b/addons/cb.help/extensions/github.js deleted file mode 100644 index 642b9def..00000000 --- a/addons/cb.help/extensions/github.js +++ /dev/null @@ -1,25 +0,0 @@ -// -// Github Extension (WIP) -// ~~strike-through~~ -> strike-through -// - -(function(){ - var github = function(converter) { - return [ - { - // strike-through - // NOTE: showdown already replaced "~" with "~T", so we need to adjust accordingly. - type : 'lang', - regex : '(~T){2}([^~]+)(~T){2}', - replace : function(match, prefix, content, suffix) { - return '' + content + ''; - } - } - ]; - }; - - // Client-side export - if (typeof window !== 'undefined' && window.Showdown && window.Showdown.extensions) { window.Showdown.extensions.github = github; } - // Server-side export - if (typeof module !== 'undefined') module.exports = github; -}()); \ No newline at end of file diff --git a/addons/cb.help/extensions/table.js b/addons/cb.help/extensions/table.js deleted file mode 100644 index d77a035b..00000000 --- a/addons/cb.help/extensions/table.js +++ /dev/null @@ -1,106 +0,0 @@ -/*global module:true*/ -/* - * Basic table support with re-entrant parsing, where cell content - * can also specify markdown. - * - * Tables - * ====== - * - * | Col 1 | Col 2 | - * |======== |====================================================| - * |**bold** | ![Valid XHTML] (http://w3.org/Icons/valid-xhtml10) | - * | Plain | Value | - * - */ - -(function(){ - var table = function(converter) { - var tables = {}, style = 'text-align:left;', filter; - tables.th = function(header){ - if (header.trim() === "") { return "";} - var id = header.trim().replace(/ /g, '_').toLowerCase(); - return '' + header + ''; - }; - tables.td = function(cell) { - return '' + converter.makeHtml(cell) + ''; - }; - tables.ths = function(){ - var out = "", i = 0, hs = [].slice.apply(arguments); - for (i;i'); - hs = line.substring(1, line.length -1).split('|'); - tbl.push(tables.thead.apply(this, hs)); - line = lines[++i]; - if (!line.trim().match(/^[|]{1}[-=| ]+[|]{1}$/)) { - // not a table rolling back - line = lines[--i]; - } - else { - line = lines[++i]; - tbl.push(''); - while (line.trim().match(/^[|]{1}.*[|]{1}$/)) { - line = line.trim(); - tbl.push(tables.tr.apply(this, line.substring(1, line.length -1).split('|'))); - line = lines[++i]; - } - tbl.push(''); - tbl.push(''); - // we are done with this table and we move along - out.push(tbl.join('\n')); - tbl = []; - continue; - } - } - out.push(line); - } - return out.join('\n'); - }; - return [ - { - type: 'lang', - filter: filter - } - ]; - }; - - // Client-side export - if (typeof window !== 'undefined' && window.Showdown && window.Showdown.extensions) { window.Showdown.extensions.table = table; } - // Server-side export - if (typeof module !== 'undefined') { - module.exports = table; - } -}()); \ No newline at end of file diff --git a/addons/cb.help/package.json b/addons/cb.help/package.json deleted file mode 100644 index 0dc32cef..00000000 --- a/addons/cb.help/package.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "name": "cb.help", - "version": "0.0.1", - "title": "Help", - "description": "Documentation for Codebox", - "homepage": "https://github.com/FriendCode/codebox", - "license": "Apache", - "author": { - "name": "Codebox", - "email": "contact@friendco.de", - "url": "https://www.codebox.io" - }, - "client": { - "main": "client" - } -} \ No newline at end of file diff --git a/addons/cb.help/showdown.js b/addons/cb.help/showdown.js deleted file mode 100644 index b488bad2..00000000 --- a/addons/cb.help/showdown.js +++ /dev/null @@ -1,1454 +0,0 @@ -// -// showdown.js -- A javascript port of Markdown. -// -// Copyright (c) 2007 John Fraser. -// -// Original Markdown Copyright (c) 2004-2005 John Gruber -// -// -// Redistributable under a BSD-style open source license. -// See license.txt for more information. -// -// The full source distribution is at: -// -// A A L -// T C A -// T K B -// -// -// - -// -// Wherever possible, Showdown is a straight, line-by-line port -// of the Perl version of Markdown. -// -// This is not a normal parser design; it's basically just a -// series of string substitutions. It's hard to read and -// maintain this way, but keeping Showdown close to the original -// design makes it easier to port new features. -// -// More importantly, Showdown behaves like markdown.pl in most -// edge cases. So web applications can do client-side preview -// in Javascript, and then build identical HTML on the server. -// -// This port needs the new RegExp functionality of ECMA 262, -// 3rd Edition (i.e. Javascript 1.5). Most modern web browsers -// should do fine. Even with the new regular expression features, -// We do a lot of work to emulate Perl's regex functionality. -// The tricky changes in this file mostly have the "attacklab:" -// label. Major or self-explanatory changes don't. -// -// Smart diff tools like Araxis Merge will be able to match up -// this file with markdown.pl in a useful way. A little tweaking -// helps: in a copy of markdown.pl, replace "#" with "//" and -// replace "$text" with "text". Be sure to ignore whitespace -// and line endings. -// - - -// -// Showdown usage: -// -// var text = "Markdown *rocks*."; -// -// var converter = new Showdown.converter(); -// var html = converter.makeHtml(text); -// -// alert(html); -// -// Note: move the sample code to the bottom of this -// file before uncommenting it. -// - - -// -// Showdown namespace -// -var Showdown = { extensions: {} }; - -// -// forEach -// -var forEach = Showdown.forEach = function(obj, callback) { - if (typeof obj.forEach === 'function') { - obj.forEach(callback); - } else { - var i, len = obj.length; - for (i = 0; i < len; i++) { - callback(obj[i], i, obj); - } - } -}; - -// -// Standard extension naming -// -var stdExtName = function(s) { - return s.replace(/[_-]||\s/g, '').toLowerCase(); -}; - -// -// converter -// -// Wraps all "globals" so that the only thing -// exposed is makeHtml(). -// -Showdown.converter = function(converter_options) { - -// -// Globals: -// - -// Global hashes, used by various utility routines -var g_urls; -var g_titles; -var g_html_blocks; - -// Used to track when we're inside an ordered or unordered list -// (see _ProcessListItems() for details): -var g_list_level = 0; - -// Global extensions -var g_lang_extensions = []; -var g_output_modifiers = []; - - -// -// Automatic Extension Loading (node only): -// - -if (typeof module !== 'undefind' && typeof exports !== 'undefined' && typeof require !== 'undefind') { - var fs = require('fs'); - - if (fs) { - // Search extensions folder - var extensions = fs.readdirSync((__dirname || '.')+'/extensions').filter(function(file){ - return ~file.indexOf('.js'); - }).map(function(file){ - return file.replace(/\.js$/, ''); - }); - // Load extensions into Showdown namespace - Showdown.forEach(extensions, function(ext){ - var name = stdExtName(ext); - Showdown.extensions[name] = require('./extensions/' + ext); - }); - } -} - -this.makeHtml = function(text) { -// -// Main function. The order in which other subs are called here is -// essential. Link and image substitutions need to happen before -// _EscapeSpecialCharsWithinTagAttributes(), so that any *'s or _'s in the -// and tags get encoded. -// - - // Clear the global hashes. If we don't clear these, you get conflicts - // from other articles when generating a page which contains more than - // one article (e.g. an index page that shows the N most recent - // articles): - g_urls = {}; - g_titles = {}; - g_html_blocks = []; - - // attacklab: Replace ~ with ~T - // This lets us use tilde as an escape char to avoid md5 hashes - // The choice of character is arbitray; anything that isn't - // magic in Markdown will work. - text = text.replace(/~/g,"~T"); - - // attacklab: Replace $ with ~D - // RegExp interprets $ as a special character - // when it's in a replacement string - text = text.replace(/\$/g,"~D"); - - // Standardize line endings - text = text.replace(/\r\n/g,"\n"); // DOS to Unix - text = text.replace(/\r/g,"\n"); // Mac to Unix - - // Make sure text begins and ends with a couple of newlines: - text = "\n\n" + text + "\n\n"; - - // Convert all tabs to spaces. - text = _Detab(text); - - // Strip any lines consisting only of spaces and tabs. - // This makes subsequent regexen easier to write, because we can - // match consecutive blank lines with /\n+/ instead of something - // contorted like /[ \t]*\n+/ . - text = text.replace(/^[ \t]+$/mg,""); - - // Run language extensions - Showdown.forEach(g_lang_extensions, function(x){ - text = _ExecuteExtension(x, text); - }); - - // Handle github codeblocks prior to running HashHTML so that - // HTML contained within the codeblock gets escaped propertly - text = _DoGithubCodeBlocks(text); - - // Turn block-level HTML blocks into hash entries - text = _HashHTMLBlocks(text); - - // Strip link definitions, store in hashes. - text = _StripLinkDefinitions(text); - - text = _RunBlockGamut(text); - - text = _UnescapeSpecialChars(text); - - // attacklab: Restore dollar signs - text = text.replace(/~D/g,"$$"); - - // attacklab: Restore tildes - text = text.replace(/~T/g,"~"); - - // Run output modifiers - Showdown.forEach(g_output_modifiers, function(x){ - text = _ExecuteExtension(x, text); - }); - - return text; -}; -// -// Options: -// - -// Parse extensions options into separate arrays -if (converter_options && converter_options.extensions) { - - var self = this; - - // Iterate over each plugin - Showdown.forEach(converter_options.extensions, function(plugin){ - - // Assume it's a bundled plugin if a string is given - if (typeof plugin === 'string') { - plugin = Showdown.extensions[stdExtName(plugin)]; - } - - if (typeof plugin === 'function') { - // Iterate over each extension within that plugin - Showdown.forEach(plugin(self), function(ext){ - // Sort extensions by type - if (ext.type) { - if (ext.type === 'language' || ext.type === 'lang') { - g_lang_extensions.push(ext); - } else if (ext.type === 'output' || ext.type === 'html') { - g_output_modifiers.push(ext); - } - } else { - // Assume language extension - g_output_modifiers.push(ext); - } - }); - } else { - throw "Extension '" + plugin + "' could not be loaded. It was either not found or is not a valid extension."; - } - }); -} - - -var _ExecuteExtension = function(ext, text) { - if (ext.regex) { - var re = new RegExp(ext.regex, 'g'); - return text.replace(re, ext.replace); - } else if (ext.filter) { - return ext.filter(text); - } -}; - -var _StripLinkDefinitions = function(text) { -// -// Strips link definitions from text, stores the URLs and titles in -// hash references. -// - - // Link defs are in the form: ^[id]: url "optional title" - - /* - var text = text.replace(/ - ^[ ]{0,3}\[(.+)\]: // id = $1 attacklab: g_tab_width - 1 - [ \t]* - \n? // maybe *one* newline - [ \t]* - ? // url = $2 - [ \t]* - \n? // maybe one newline - [ \t]* - (?: - (\n*) // any lines skipped = $3 attacklab: lookbehind removed - ["(] - (.+?) // title = $4 - [")] - [ \t]* - )? // title is optional - (?:\n+|$) - /gm, - function(){...}); - */ - - // attacklab: sentinel workarounds for lack of \A and \Z, safari\khtml bug - text += "~0"; - - text = text.replace(/^[ ]{0,3}\[(.+)\]:[ \t]*\n?[ \t]*?[ \t]*\n?[ \t]*(?:(\n*)["(](.+?)[")][ \t]*)?(?:\n+|(?=~0))/gm, - function (wholeMatch,m1,m2,m3,m4) { - m1 = m1.toLowerCase(); - g_urls[m1] = _EncodeAmpsAndAngles(m2); // Link IDs are case-insensitive - if (m3) { - // Oops, found blank lines, so it's not a title. - // Put back the parenthetical statement we stole. - return m3+m4; - } else if (m4) { - g_titles[m1] = m4.replace(/"/g,"""); - } - - // Completely remove the definition from the text - return ""; - } - ); - - // attacklab: strip sentinel - text = text.replace(/~0/,""); - - return text; -} - - -var _HashHTMLBlocks = function(text) { - // attacklab: Double up blank lines to reduce lookaround - text = text.replace(/\n/g,"\n\n"); - - // Hashify HTML blocks: - // We only want to do this for block-level HTML tags, such as headers, - // lists, and tables. That's because we still want to wrap

s around - // "paragraphs" that are wrapped in non-block-level tags, such as anchors, - // phrase emphasis, and spans. The list of tags we're looking for is - // hard-coded: - var block_tags_a = "p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math|ins|del|style|section|header|footer|nav|article|aside"; - var block_tags_b = "p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math|style|section|header|footer|nav|article|aside"; - - // First, look for nested blocks, e.g.: - //

- //
- // tags for inner block must be indented. - //
- //
- // - // The outermost tags must start at the left margin for this to match, and - // the inner nested divs must be indented. - // We need to do this before the next, more liberal match, because the next - // match will start at the first `
` and stop at the first `
`. - - // attacklab: This regex can be expensive when it fails. - /* - var text = text.replace(/ - ( // save in $1 - ^ // start of line (with /m) - <($block_tags_a) // start tag = $2 - \b // word break - // attacklab: hack around khtml/pcre bug... - [^\r]*?\n // any number of lines, minimally matching - // the matching end tag - [ \t]* // trailing spaces/tabs - (?=\n+) // followed by a newline - ) // attacklab: there are sentinel newlines at end of document - /gm,function(){...}}; - */ - text = text.replace(/^(<(p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math|ins|del)\b[^\r]*?\n<\/\2>[ \t]*(?=\n+))/gm,hashElement); - - // - // Now match more liberally, simply from `\n` to `\n` - // - - /* - var text = text.replace(/ - ( // save in $1 - ^ // start of line (with /m) - <($block_tags_b) // start tag = $2 - \b // word break - // attacklab: hack around khtml/pcre bug... - [^\r]*? // any number of lines, minimally matching - // the matching end tag - [ \t]* // trailing spaces/tabs - (?=\n+) // followed by a newline - ) // attacklab: there are sentinel newlines at end of document - /gm,function(){...}}; - */ - text = text.replace(/^(<(p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math|style|section|header|footer|nav|article|aside)\b[^\r]*?<\/\2>[ \t]*(?=\n+)\n)/gm,hashElement); - - // Special case just for
. It was easier to make a special case than - // to make the other regex more complicated. - - /* - text = text.replace(/ - ( // save in $1 - \n\n // Starting after a blank line - [ ]{0,3} - (<(hr) // start tag = $2 - \b // word break - ([^<>])*? // - \/?>) // the matching end tag - [ \t]* - (?=\n{2,}) // followed by a blank line - ) - /g,hashElement); - */ - text = text.replace(/(\n[ ]{0,3}(<(hr)\b([^<>])*?\/?>)[ \t]*(?=\n{2,}))/g,hashElement); - - // Special case for standalone HTML comments: - - /* - text = text.replace(/ - ( // save in $1 - \n\n // Starting after a blank line - [ ]{0,3} // attacklab: g_tab_width - 1 - - [ \t]* - (?=\n{2,}) // followed by a blank line - ) - /g,hashElement); - */ - text = text.replace(/(\n\n[ ]{0,3}[ \t]*(?=\n{2,}))/g,hashElement); - - // PHP and ASP-style processor instructions ( and <%...%>) - - /* - text = text.replace(/ - (?: - \n\n // Starting after a blank line - ) - ( // save in $1 - [ ]{0,3} // attacklab: g_tab_width - 1 - (?: - <([?%]) // $2 - [^\r]*? - \2> - ) - [ \t]* - (?=\n{2,}) // followed by a blank line - ) - /g,hashElement); - */ - text = text.replace(/(?:\n\n)([ ]{0,3}(?:<([?%])[^\r]*?\2>)[ \t]*(?=\n{2,}))/g,hashElement); - - // attacklab: Undo double lines (see comment at top of this function) - text = text.replace(/\n\n/g,"\n"); - return text; -} - -var hashElement = function(wholeMatch,m1) { - var blockText = m1; - - // Undo double lines - blockText = blockText.replace(/\n\n/g,"\n"); - blockText = blockText.replace(/^\n/,""); - - // strip trailing blank lines - blockText = blockText.replace(/\n+$/g,""); - - // Replace the element text with a marker ("~KxK" where x is its key) - blockText = "\n\n~K" + (g_html_blocks.push(blockText)-1) + "K\n\n"; - - return blockText; -}; - -var _RunBlockGamut = function(text) { -// -// These are all the transformations that form block-level -// tags like paragraphs, headers, and list items. -// - text = _DoHeaders(text); - - // Do Horizontal Rules: - var key = hashBlock("
"); - text = text.replace(/^[ ]{0,2}([ ]?\*[ ]?){3,}[ \t]*$/gm,key); - text = text.replace(/^[ ]{0,2}([ ]?\-[ ]?){3,}[ \t]*$/gm,key); - text = text.replace(/^[ ]{0,2}([ ]?\_[ ]?){3,}[ \t]*$/gm,key); - - text = _DoLists(text); - text = _DoCodeBlocks(text); - text = _DoBlockQuotes(text); - - // We already ran _HashHTMLBlocks() before, in Markdown(), but that - // was to escape raw HTML in the original Markdown source. This time, - // we're escaping the markup we've just created, so that we don't wrap - //

tags around block-level tags. - text = _HashHTMLBlocks(text); - text = _FormParagraphs(text); - - return text; -}; - - -var _RunSpanGamut = function(text) { -// -// These are all the transformations that occur *within* block-level -// tags like paragraphs, headers, and list items. -// - - text = _DoCodeSpans(text); - text = _EscapeSpecialCharsWithinTagAttributes(text); - text = _EncodeBackslashEscapes(text); - - // Process anchor and image tags. Images must come first, - // because ![foo][f] looks like an anchor. - text = _DoImages(text); - text = _DoAnchors(text); - - // Make links out of things like `` - // Must come after _DoAnchors(), because you can use < and > - // delimiters in inline links like [this](). - text = _DoAutoLinks(text); - text = _EncodeAmpsAndAngles(text); - text = _DoItalicsAndBold(text); - - // Do hard breaks: - text = text.replace(/ +\n/g,"
\n"); - - return text; -} - -var _EscapeSpecialCharsWithinTagAttributes = function(text) { -// -// Within tags -- meaning between < and > -- encode [\ ` * _] so they -// don't conflict with their use in Markdown for code, italics and strong. -// - - // Build a regex to find HTML tags and comments. See Friedl's - // "Mastering Regular Expressions", 2nd Ed., pp. 200-201. - var regex = /(<[a-z\/!$]("[^"]*"|'[^']*'|[^'">])*>|)/gi; - - text = text.replace(regex, function(wholeMatch) { - var tag = wholeMatch.replace(/(.)<\/?code>(?=.)/g,"$1`"); - tag = escapeCharacters(tag,"\\`*_"); - return tag; - }); - - return text; -} - -var _DoAnchors = function(text) { -// -// Turn Markdown link shortcuts into XHTML
tags. -// - // - // First, handle reference-style links: [link text] [id] - // - - /* - text = text.replace(/ - ( // wrap whole match in $1 - \[ - ( - (?: - \[[^\]]*\] // allow brackets nested one level - | - [^\[] // or anything else - )* - ) - \] - - [ ]? // one optional space - (?:\n[ ]*)? // one optional newline followed by spaces - - \[ - (.*?) // id = $3 - \] - )()()()() // pad remaining backreferences - /g,_DoAnchors_callback); - */ - text = text.replace(/(\[((?:\[[^\]]*\]|[^\[\]])*)\][ ]?(?:\n[ ]*)?\[(.*?)\])()()()()/g,writeAnchorTag); - - // - // Next, inline-style links: [link text](url "optional title") - // - - /* - text = text.replace(/ - ( // wrap whole match in $1 - \[ - ( - (?: - \[[^\]]*\] // allow brackets nested one level - | - [^\[\]] // or anything else - ) - ) - \] - \( // literal paren - [ \t]* - () // no id, so leave $3 empty - ? // href = $4 - [ \t]* - ( // $5 - (['"]) // quote char = $6 - (.*?) // Title = $7 - \6 // matching quote - [ \t]* // ignore any spaces/tabs between closing quote and ) - )? // title is optional - \) - ) - /g,writeAnchorTag); - */ - text = text.replace(/(\[((?:\[[^\]]*\]|[^\[\]])*)\]\([ \t]*()?[ \t]*((['"])(.*?)\6[ \t]*)?\))/g,writeAnchorTag); - - // - // Last, handle reference-style shortcuts: [link text] - // These must come last in case you've also got [link test][1] - // or [link test](/foo) - // - - /* - text = text.replace(/ - ( // wrap whole match in $1 - \[ - ([^\[\]]+) // link text = $2; can't contain '[' or ']' - \] - )()()()()() // pad rest of backreferences - /g, writeAnchorTag); - */ - text = text.replace(/(\[([^\[\]]+)\])()()()()()/g, writeAnchorTag); - - return text; -} - -var writeAnchorTag = function(wholeMatch,m1,m2,m3,m4,m5,m6,m7) { - if (m7 == undefined) m7 = ""; - var whole_match = m1; - var link_text = m2; - var link_id = m3.toLowerCase(); - var url = m4; - var title = m7; - - if (url == "") { - if (link_id == "") { - // lower-case and turn embedded newlines into spaces - link_id = link_text.toLowerCase().replace(/ ?\n/g," "); - } - url = "#"+link_id; - - if (g_urls[link_id] != undefined) { - url = g_urls[link_id]; - if (g_titles[link_id] != undefined) { - title = g_titles[link_id]; - } - } - else { - if (whole_match.search(/\(\s*\)$/m)>-1) { - // Special case for explicit empty url - url = ""; - } else { - return whole_match; - } - } - } - - url = escapeCharacters(url,"*_"); - var result = ""; - - return result; -} - - -var _DoImages = function(text) { -// -// Turn Markdown image shortcuts into tags. -// - - // - // First, handle reference-style labeled images: ![alt text][id] - // - - /* - text = text.replace(/ - ( // wrap whole match in $1 - !\[ - (.*?) // alt text = $2 - \] - - [ ]? // one optional space - (?:\n[ ]*)? // one optional newline followed by spaces - - \[ - (.*?) // id = $3 - \] - )()()()() // pad rest of backreferences - /g,writeImageTag); - */ - text = text.replace(/(!\[(.*?)\][ ]?(?:\n[ ]*)?\[(.*?)\])()()()()/g,writeImageTag); - - // - // Next, handle inline images: ![alt text](url "optional title") - // Don't forget: encode * and _ - - /* - text = text.replace(/ - ( // wrap whole match in $1 - !\[ - (.*?) // alt text = $2 - \] - \s? // One optional whitespace character - \( // literal paren - [ \t]* - () // no id, so leave $3 empty - ? // src url = $4 - [ \t]* - ( // $5 - (['"]) // quote char = $6 - (.*?) // title = $7 - \6 // matching quote - [ \t]* - )? // title is optional - \) - ) - /g,writeImageTag); - */ - text = text.replace(/(!\[(.*?)\]\s?\([ \t]*()?[ \t]*((['"])(.*?)\6[ \t]*)?\))/g,writeImageTag); - - return text; -} - -var writeImageTag = function(wholeMatch,m1,m2,m3,m4,m5,m6,m7) { - var whole_match = m1; - var alt_text = m2; - var link_id = m3.toLowerCase(); - var url = m4; - var title = m7; - - if (!title) title = ""; - - if (url == "") { - if (link_id == "") { - // lower-case and turn embedded newlines into spaces - link_id = alt_text.toLowerCase().replace(/ ?\n/g," "); - } - url = "#"+link_id; - - if (g_urls[link_id] != undefined) { - url = g_urls[link_id]; - if (g_titles[link_id] != undefined) { - title = g_titles[link_id]; - } - } - else { - return whole_match; - } - } - - alt_text = alt_text.replace(/"/g,"""); - url = escapeCharacters(url,"*_"); - var result = "\""' + _RunSpanGamut(m1) + "");}); - - text = text.replace(/^(.+)[ \t]*\n-+[ \t]*\n+/gm, - function(matchFound,m1){return hashBlock('

' + _RunSpanGamut(m1) + "

");}); - - // atx-style headers: - // # Header 1 - // ## Header 2 - // ## Header 2 with closing hashes ## - // ... - // ###### Header 6 - // - - /* - text = text.replace(/ - ^(\#{1,6}) // $1 = string of #'s - [ \t]* - (.+?) // $2 = Header text - [ \t]* - \#* // optional closing #'s (not counted) - \n+ - /gm, function() {...}); - */ - - text = text.replace(/^(\#{1,6})[ \t]*(.+?)[ \t]*\#*\n+/gm, - function(wholeMatch,m1,m2) { - var h_level = m1.length; - return hashBlock("' + _RunSpanGamut(m2) + ""); - }); - - function headerId(m) { - return m.replace(/[^\w]/g, '').toLowerCase(); - } - return text; -} - -// This declaration keeps Dojo compressor from outputting garbage: -var _ProcessListItems; - -var _DoLists = function(text) { -// -// Form HTML ordered (numbered) and unordered (bulleted) lists. -// - - // attacklab: add sentinel to hack around khtml/safari bug: - // http://bugs.webkit.org/show_bug.cgi?id=11231 - text += "~0"; - - // Re-usable pattern to match any entirel ul or ol list: - - /* - var whole_list = / - ( // $1 = whole list - ( // $2 - [ ]{0,3} // attacklab: g_tab_width - 1 - ([*+-]|\d+[.]) // $3 = first list item marker - [ \t]+ - ) - [^\r]+? - ( // $4 - ~0 // sentinel for workaround; should be $ - | - \n{2,} - (?=\S) - (?! // Negative lookahead for another list item marker - [ \t]* - (?:[*+-]|\d+[.])[ \t]+ - ) - ) - )/g - */ - var whole_list = /^(([ ]{0,3}([*+-]|\d+[.])[ \t]+)[^\r]+?(~0|\n{2,}(?=\S)(?![ \t]*(?:[*+-]|\d+[.])[ \t]+)))/gm; - - if (g_list_level) { - text = text.replace(whole_list,function(wholeMatch,m1,m2) { - var list = m1; - var list_type = (m2.search(/[*+-]/g)>-1) ? "ul" : "ol"; - - // Turn double returns into triple returns, so that we can make a - // paragraph for the last item in a list, if necessary: - list = list.replace(/\n{2,}/g,"\n\n\n");; - var result = _ProcessListItems(list); - - // Trim any trailing whitespace, to put the closing `` - // up on the preceding line, to get it past the current stupid - // HTML block parser. This is a hack to work around the terrible - // hack that is the HTML block parser. - result = result.replace(/\s+$/,""); - result = "<"+list_type+">" + result + "\n"; - return result; - }); - } else { - whole_list = /(\n\n|^\n?)(([ ]{0,3}([*+-]|\d+[.])[ \t]+)[^\r]+?(~0|\n{2,}(?=\S)(?![ \t]*(?:[*+-]|\d+[.])[ \t]+)))/g; - text = text.replace(whole_list,function(wholeMatch,m1,m2,m3) { - var runup = m1; - var list = m2; - - var list_type = (m3.search(/[*+-]/g)>-1) ? "ul" : "ol"; - // Turn double returns into triple returns, so that we can make a - // paragraph for the last item in a list, if necessary: - var list = list.replace(/\n{2,}/g,"\n\n\n");; - var result = _ProcessListItems(list); - result = runup + "<"+list_type+">\n" + result + "\n"; - return result; - }); - } - - // attacklab: strip sentinel - text = text.replace(/~0/,""); - - return text; -} - -_ProcessListItems = function(list_str) { -// -// Process the contents of a single ordered or unordered list, splitting it -// into individual list items. -// - // The $g_list_level global keeps track of when we're inside a list. - // Each time we enter a list, we increment it; when we leave a list, - // we decrement. If it's zero, we're not in a list anymore. - // - // We do this because when we're not inside a list, we want to treat - // something like this: - // - // I recommend upgrading to version - // 8. Oops, now this line is treated - // as a sub-list. - // - // As a single paragraph, despite the fact that the second line starts - // with a digit-period-space sequence. - // - // Whereas when we're inside a list (or sub-list), that line will be - // treated as the start of a sub-list. What a kludge, huh? This is - // an aspect of Markdown's syntax that's hard to parse perfectly - // without resorting to mind-reading. Perhaps the solution is to - // change the syntax rules such that sub-lists must start with a - // starting cardinal number; e.g. "1." or "a.". - - g_list_level++; - - // trim trailing blank lines: - list_str = list_str.replace(/\n{2,}$/,"\n"); - - // attacklab: add sentinel to emulate \z - list_str += "~0"; - - /* - list_str = list_str.replace(/ - (\n)? // leading line = $1 - (^[ \t]*) // leading whitespace = $2 - ([*+-]|\d+[.]) [ \t]+ // list marker = $3 - ([^\r]+? // list item text = $4 - (\n{1,2})) - (?= \n* (~0 | \2 ([*+-]|\d+[.]) [ \t]+)) - /gm, function(){...}); - */ - list_str = list_str.replace(/(\n)?(^[ \t]*)([*+-]|\d+[.])[ \t]+([^\r]+?(\n{1,2}))(?=\n*(~0|\2([*+-]|\d+[.])[ \t]+))/gm, - function(wholeMatch,m1,m2,m3,m4){ - var item = m4; - var leading_line = m1; - var leading_space = m2; - - if (leading_line || (item.search(/\n{2,}/)>-1)) { - item = _RunBlockGamut(_Outdent(item)); - } - else { - // Recursion for sub-lists: - item = _DoLists(_Outdent(item)); - item = item.replace(/\n$/,""); // chomp(item) - item = _RunSpanGamut(item); - } - - return "
  • " + item + "
  • \n"; - } - ); - - // attacklab: strip sentinel - list_str = list_str.replace(/~0/g,""); - - g_list_level--; - return list_str; -} - - -var _DoCodeBlocks = function(text) { -// -// Process Markdown `
    ` blocks.
    -//
    -
    -	/*
    -		text = text.replace(text,
    -			/(?:\n\n|^)
    -			(								// $1 = the code block -- one or more lines, starting with a space/tab
    -				(?:
    -					(?:[ ]{4}|\t)			// Lines must start with a tab or a tab-width of spaces - attacklab: g_tab_width
    -					.*\n+
    -				)+
    -			)
    -			(\n*[ ]{0,3}[^ \t\n]|(?=~0))	// attacklab: g_tab_width
    -		/g,function(){...});
    -	*/
    -
    -	// attacklab: sentinel workarounds for lack of \A and \Z, safari\khtml bug
    -	text += "~0";
    -
    -	text = text.replace(/(?:\n\n|^)((?:(?:[ ]{4}|\t).*\n+)+)(\n*[ ]{0,3}[^ \t\n]|(?=~0))/g,
    -		function(wholeMatch,m1,m2) {
    -			var codeblock = m1;
    -			var nextChar = m2;
    -
    -			codeblock = _EncodeCode( _Outdent(codeblock));
    -			codeblock = _Detab(codeblock);
    -			codeblock = codeblock.replace(/^\n+/g,""); // trim leading newlines
    -			codeblock = codeblock.replace(/\n+$/g,""); // trim trailing whitespace
    -
    -			codeblock = "
    " + codeblock + "\n
    "; - - return hashBlock(codeblock) + nextChar; - } - ); - - // attacklab: strip sentinel - text = text.replace(/~0/,""); - - return text; -}; - -var _DoGithubCodeBlocks = function(text) { -// -// Process Github-style code blocks -// Example: -// ```ruby -// def hello_world(x) -// puts "Hello, #{x}" -// end -// ``` -// - - - // attacklab: sentinel workarounds for lack of \A and \Z, safari\khtml bug - text += "~0"; - - text = text.replace(/(?:^|\n)```(.*)\n([\s\S]*?)\n```/g, - function(wholeMatch,m1,m2) { - var language = m1; - var codeblock = m2; - - codeblock = _EncodeCode(codeblock); - codeblock = _Detab(codeblock); - codeblock = codeblock.replace(/^\n+/g,""); // trim leading newlines - codeblock = codeblock.replace(/\n+$/g,""); // trim trailing whitespace - - codeblock = "
    " + codeblock + "\n
    "; - - return hashBlock(codeblock); - } - ); - - // attacklab: strip sentinel - text = text.replace(/~0/,""); - - return text; -} - -var hashBlock = function(text) { - text = text.replace(/(^\n+|\n+$)/g,""); - return "\n\n~K" + (g_html_blocks.push(text)-1) + "K\n\n"; -} - -var _DoCodeSpans = function(text) { -// -// * Backtick quotes are used for spans. -// -// * You can use multiple backticks as the delimiters if you want to -// include literal backticks in the code span. So, this input: -// -// Just type ``foo `bar` baz`` at the prompt. -// -// Will translate to: -// -//

    Just type foo `bar` baz at the prompt.

    -// -// There's no arbitrary limit to the number of backticks you -// can use as delimters. If you need three consecutive backticks -// in your code, use four for delimiters, etc. -// -// * You can use spaces to get literal backticks at the edges: -// -// ... type `` `bar` `` ... -// -// Turns to: -// -// ... type `bar` ... -// - - /* - text = text.replace(/ - (^|[^\\]) // Character before opening ` can't be a backslash - (`+) // $2 = Opening run of ` - ( // $3 = The code block - [^\r]*? - [^`] // attacklab: work around lack of lookbehind - ) - \2 // Matching closer - (?!`) - /gm, function(){...}); - */ - - text = text.replace(/(^|[^\\])(`+)([^\r]*?[^`])\2(?!`)/gm, - function(wholeMatch,m1,m2,m3,m4) { - var c = m3; - c = c.replace(/^([ \t]*)/g,""); // leading whitespace - c = c.replace(/[ \t]*$/g,""); // trailing whitespace - c = _EncodeCode(c); - return m1+""+c+""; - }); - - return text; -} - -var _EncodeCode = function(text) { -// -// Encode/escape certain characters inside Markdown code runs. -// The point is that in code, these characters are literals, -// and lose their special Markdown meanings. -// - // Encode all ampersands; HTML entities are not - // entities within a Markdown code span. - text = text.replace(/&/g,"&"); - - // Do the angle bracket song and dance: - text = text.replace(//g,">"); - - // Now, escape characters that are magic in Markdown: - text = escapeCharacters(text,"\*_{}[]\\",false); - -// jj the line above breaks this: -//--- - -//* Item - -// 1. Subitem - -// special char: * -//--- - - return text; -} - - -var _DoItalicsAndBold = function(text) { - - // must go first: - text = text.replace(/(\*\*|__)(?=\S)([^\r]*?\S[*_]*)\1/g, - "$2"); - - text = text.replace(/(\*|_)(?=\S)([^\r]*?\S)\1/g, - "$2"); - - return text; -} - - -var _DoBlockQuotes = function(text) { - - /* - text = text.replace(/ - ( // Wrap whole match in $1 - ( - ^[ \t]*>[ \t]? // '>' at the start of a line - .+\n // rest of the first line - (.+\n)* // subsequent consecutive lines - \n* // blanks - )+ - ) - /gm, function(){...}); - */ - - text = text.replace(/((^[ \t]*>[ \t]?.+\n(.+\n)*\n*)+)/gm, - function(wholeMatch,m1) { - var bq = m1; - - // attacklab: hack around Konqueror 3.5.4 bug: - // "----------bug".replace(/^-/g,"") == "bug" - - bq = bq.replace(/^[ \t]*>[ \t]?/gm,"~0"); // trim one level of quoting - - // attacklab: clean up hack - bq = bq.replace(/~0/g,""); - - bq = bq.replace(/^[ \t]+$/gm,""); // trim whitespace-only lines - bq = _RunBlockGamut(bq); // recurse - - bq = bq.replace(/(^|\n)/g,"$1 "); - // These leading spaces screw with
     content, so we need to fix that:
    -			bq = bq.replace(
    -					/(\s*
    [^\r]+?<\/pre>)/gm,
    -				function(wholeMatch,m1) {
    -					var pre = m1;
    -					// attacklab: hack around Konqueror 3.5.4 bug:
    -					pre = pre.replace(/^  /mg,"~0");
    -					pre = pre.replace(/~0/g,"");
    -					return pre;
    -				});
    -
    -			return hashBlock("
    \n" + bq + "\n
    "); - }); - return text; -} - - -var _FormParagraphs = function(text) { -// -// Params: -// $text - string to process with html

    tags -// - - // Strip leading and trailing lines: - text = text.replace(/^\n+/g,""); - text = text.replace(/\n+$/g,""); - - var grafs = text.split(/\n{2,}/g); - var grafsOut = []; - - // - // Wrap

    tags. - // - var end = grafs.length; - for (var i=0; i= 0) { - grafsOut.push(str); - } - else if (str.search(/\S/) >= 0) { - str = _RunSpanGamut(str); - str = str.replace(/^([ \t]*)/g,"

    "); - str += "

    " - grafsOut.push(str); - } - - } - - // - // Unhashify HTML blocks - // - end = grafsOut.length; - for (var i=0; i= 0) { - var blockText = g_html_blocks[RegExp.$1]; - blockText = blockText.replace(/\$/g,"$$$$"); // Escape any dollar signs - grafsOut[i] = grafsOut[i].replace(/~K\d+K/,blockText); - } - } - - return grafsOut.join("\n\n"); -} - - -var _EncodeAmpsAndAngles = function(text) { -// Smart processing for ampersands and angle brackets that need to be encoded. - - // Ampersand-encoding based entirely on Nat Irons's Amputator MT plugin: - // http://bumppo.net/projects/amputator/ - text = text.replace(/&(?!#?[xX]?(?:[0-9a-fA-F]+|\w+);)/g,"&"); - - // Encode naked <'s - text = text.replace(/<(?![a-z\/?\$!])/gi,"<"); - - return text; -} - - -var _EncodeBackslashEscapes = function(text) { -// -// Parameter: String. -// Returns: The string, with after processing the following backslash -// escape sequences. -// - - // attacklab: The polite way to do this is with the new - // escapeCharacters() function: - // - // text = escapeCharacters(text,"\\",true); - // text = escapeCharacters(text,"`*_{}[]()>#+-.!",true); - // - // ...but we're sidestepping its use of the (slow) RegExp constructor - // as an optimization for Firefox. This function gets called a LOT. - - text = text.replace(/\\(\\)/g,escapeCharacters_callback); - text = text.replace(/\\([`*_{}\[\]()>#+-.!])/g,escapeCharacters_callback); - return text; -} - - -var _DoAutoLinks = function(text) { - - text = text.replace(/<((https?|ftp|dict):[^'">\s]+)>/gi,"
    $1"); - - // Email addresses: - - /* - text = text.replace(/ - < - (?:mailto:)? - ( - [-.\w]+ - \@ - [-a-z0-9]+(\.[-a-z0-9]+)*\.[a-z]+ - ) - > - /gi, _DoAutoLinks_callback()); - */ - text = text.replace(/<(?:mailto:)?([-.\w]+\@[-a-z0-9]+(\.[-a-z0-9]+)*\.[a-z]+)>/gi, - function(wholeMatch,m1) { - return _EncodeEmailAddress( _UnescapeSpecialChars(m1) ); - } - ); - - return text; -} - - -var _EncodeEmailAddress = function(addr) { -// -// Input: an email address, e.g. "foo@example.com" -// -// Output: the email address as a mailto link, with each character -// of the address encoded as either a decimal or hex entity, in -// the hopes of foiling most address harvesting spam bots. E.g.: -// -// foo -// @example.com -// -// Based on a filter by Matthew Wickline, posted to the BBEdit-Talk -// mailing list: -// - - var encode = [ - function(ch){return "&#"+ch.charCodeAt(0)+";";}, - function(ch){return "&#x"+ch.charCodeAt(0).toString(16)+";";}, - function(ch){return ch;} - ]; - - addr = "mailto:" + addr; - - addr = addr.replace(/./g, function(ch) { - if (ch == "@") { - // this *must* be encoded. I insist. - ch = encode[Math.floor(Math.random()*2)](ch); - } else if (ch !=":") { - // leave ':' alone (to spot mailto: later) - var r = Math.random(); - // roughly 10% raw, 45% hex, 45% dec - ch = ( - r > .9 ? encode[2](ch) : - r > .45 ? encode[1](ch) : - encode[0](ch) - ); - } - return ch; - }); - - addr = "" + addr + ""; - addr = addr.replace(/">.+:/g,"\">"); // strip the mailto: from the visible part - - return addr; -} - - -var _UnescapeSpecialChars = function(text) { -// -// Swap back in all the special characters we've hidden. -// - text = text.replace(/~E(\d+)E/g, - function(wholeMatch,m1) { - var charCodeToReplace = parseInt(m1); - return String.fromCharCode(charCodeToReplace); - } - ); - return text; -} - - -var _Outdent = function(text) { -// -// Remove one level of line-leading tabs or spaces -// - - // attacklab: hack around Konqueror 3.5.4 bug: - // "----------bug".replace(/^-/g,"") == "bug" - - text = text.replace(/^(\t|[ ]{1,4})/gm,"~0"); // attacklab: g_tab_width - - // attacklab: clean up hack - text = text.replace(/~0/g,"") - - return text; -} - -var _Detab = function(text) { -// attacklab: Detab's completely rewritten for speed. -// In perl we could fix it by anchoring the regexp with \G. -// In javascript we're less fortunate. - - // expand first n-1 tabs - text = text.replace(/\t(?=\t)/g," "); // attacklab: g_tab_width - - // replace the nth with two sentinels - text = text.replace(/\t/g,"~A~B"); - - // use the sentinel to anchor our regex so it doesn't explode - text = text.replace(/~B(.+?)~A/g, - function(wholeMatch,m1,m2) { - var leadingText = m1; - var numSpaces = 4 - leadingText.length % 4; // attacklab: g_tab_width - - // there *must* be a better way to do this: - for (var i=0; i *:first-child { - margin-top: 0 !important; - } - - & > *:last-child { - margin-bottom: 0 !important; - } - - a { - color: #4183C4; - text-decoration: none; - } - - a.absent { - color: #cc0000; - } - - a.anchor { - display: block; - padding-left: 30px; - margin-left: -30px; - cursor: pointer; - position: absolute; - top: 0; - left: 0; - bottom: 0; - } - - h1, h2, h3, h4, h5, h6 { - margin: 20px 0 10px; - padding: 0; - font-weight: bold; - -webkit-font-smoothing: antialiased; - cursor: text; - position: relative; - } - - h2:first-child, h1:first-child, h1:first-child + h2, h3:first-child, h4:first-child, h5:first-child, h6:first-child { - margin-top: 0; - padding-top: 0; - } - - h1:hover a.anchor, h2:hover a.anchor, h3:hover a.anchor, h4:hover a.anchor, h5:hover a.anchor, h6:hover a.anchor { - text-decoration: none; - } - - h1 tt, h1 code { - font-size: inherit; - } - - h2 tt, h2 code { - font-size: inherit; - } - - h3 tt, h3 code { - font-size: inherit; - } - - h4 tt, h4 code { - font-size: inherit; - } - - h5 tt, h5 code { - font-size: inherit; - } - - h6 tt, h6 code { - font-size: inherit; - } - - h1 { - font-size: 28px; - color: black; - } - - h2 { - font-size: 24px; - border-bottom: 1px solid #cccccc; - color: black; - } - - h3 { - font-size: 18px; - } - - h4 { - font-size: 16px; - } - - h5 { - font-size: 14px; - } - - h6 { - color: #777777; - font-size: 14px; - } - - p, blockquote, ul, ol, dl, li, table, pre { - margin: 8px 0; - } - - body > h2:first-child { - margin-top: 0; - padding-top: 0; - } - - body > h1:first-child { - margin-top: 0; - padding-top: 0; - } - - body > h1:first-child + h2 { - margin-top: 0; - padding-top: 0; - } - - body > h3:first-child, body > h4:first-child, body > h5:first-child, body > h6:first-child { - margin-top: 0; - padding-top: 0; - } - - a:first-child h1, a:first-child h2, a:first-child h3, a:first-child h4, a:first-child h5, a:first-child h6 { - margin-top: 0; - padding-top: 0; - } - - h1 p, h2 p, h3 p, h4 p, h5 p, h6 p { - margin-top: 0; - } - - li p.first { - display: inline-block; - } - - ul, ol { - padding-left: 30px; - } - - ul :first-child, ol :first-child { - margin-top: 0; - } - - ul :last-child, ol :last-child { - margin-bottom: 0; - } - - dl { - padding: 0; - } - - dl dt { - font-size: 14px; - font-weight: bold; - font-style: italic; - padding: 0; - margin: 15px 0 5px; - } - - dl dt:first-child { - padding: 0; - } - - dl dt > :first-child { - margin-top: 0; - } - - dl dt > :last-child { - margin-bottom: 0; - } - - dl dd { - margin: 0 0 15px; - padding: 0 15px; - } - - dl dd > :first-child { - margin-top: 0; - } - - dl dd > :last-child { - margin-bottom: 0; - } - - blockquote { - border-left: 4px solid #dddddd; - padding: 0 15px; - color: #777777; - } - - blockquote > :first-child { - margin-top: 0; - } - - blockquote > :last-child { - margin-bottom: 0; - } - - table { - padding: 0; - width: 100%; - } - table tr { - border-top: 1px solid #cccccc; - background-color: white; - margin: 0; - padding: 0; - } - - table tr:nth-child(2n) { - background-color: #f8f8f8; - } - - table tr th { - font-weight: bold; - border: 1px solid #cccccc; - text-align: left; - margin: 0; - padding: 6px 13px; - } - - table tr td { - border: 1px solid #cccccc; - text-align: left; - margin: 0; - padding: 6px 13px; - } - - table tr th :first-child, table tr td :first-child { - margin-top: 0; - } - - table tr th :last-child, table tr td :last-child { - margin-bottom: 0; - } - - img { - max-width: 100%; - } - - span.frame { - display: block; - overflow: hidden; - } - - span.frame > span { - border: 1px solid #dddddd; - display: block; - float: left; - overflow: hidden; - margin: 13px 0 0; - padding: 7px; - width: auto; - } - - span.frame span img { - display: block; - float: left; - } - - span.frame span span { - clear: both; - color: #333333; - display: block; - padding: 5px 0 0; - } - - span.align-center { - display: block; - overflow: hidden; - clear: both; - } - - span.align-center > span { - display: block; - overflow: hidden; - margin: 13px auto 0; - text-align: center; - } - - span.align-center span img { - margin: 0 auto; - text-align: center; - } - - span.align-right { - display: block; - overflow: hidden; - clear: both; - } - - span.align-right > span { - display: block; - overflow: hidden; - margin: 13px 0 0; - text-align: right; - } - - span.align-right span img { - margin: 0; - text-align: right; - } - - span.float-left { - display: block; - margin-right: 13px; - overflow: hidden; - float: left; - } - - span.float-left span { - margin: 13px 0 0; - } - - span.float-right { - display: block; - margin-left: 13px; - overflow: hidden; - float: right; - } - - span.float-right > span { - display: block; - overflow: hidden; - margin: 13px auto 0; - text-align: right; - } - - code, tt { - margin: 0 2px; - padding: 0 5px; - white-space: nowrap; - border: 1px solid #eaeaea; - background-color: #f8f8f8; - border-radius: 3px; - } - - pre code { - margin: 0; - padding: 0; - white-space: pre; - border: none; - background: transparent; - } - - .highlight pre { - background-color: #f8f8f8; - border: 1px solid #cccccc; - font-size: 13px; - line-height: 19px; - overflow: auto; - padding: 6px 10px; - border-radius: 3px; - } - - pre { - background-color: #f8f8f8; - border: 1px solid #cccccc; - font-size: 13px; - line-height: 19px; - overflow: auto; - padding: 6px 10px; - border-radius: 3px; - } - - pre code, pre tt { - background-color: transparent; - border: none; - } -} \ No newline at end of file diff --git a/addons/cb.help/templates/dialog.html b/addons/cb.help/templates/dialog.html deleted file mode 100644 index 30a0ce7d..00000000 --- a/addons/cb.help/templates/dialog.html +++ /dev/null @@ -1,30 +0,0 @@ - \ No newline at end of file diff --git a/addons/cb.help/views/dialog.js b/addons/cb.help/views/dialog.js deleted file mode 100644 index d4951618..00000000 --- a/addons/cb.help/views/dialog.js +++ /dev/null @@ -1,39 +0,0 @@ -define([ - "views/page", - "text!templates/dialog.html", - "less!stylesheets/dialog.less" -], function(PageView, templateFile) { - var DialogView = codebox.require("views/dialogs/base"); - var box = codebox.require("core/box"); - - var HelpDialog = DialogView.extend({ - className: "addon-help-dialog modal fade", - templateLoader: "text", - template: templateFile, - events: _.extend({}, DialogView.prototype.events,{ - "click .action-gohome": "openHome" - }), - - // Constructor - initialize: function() { - HelpDialog.__super__.initialize.apply(this, arguments); - this.page = new PageView({}, this); - return this; - }, - - // Finish rendering - finish: function() { - this.page.render(); - this.page.$el.appendTo(this.$(".help-page-body")); - return HelpDialog.__super__.finish.apply(this, arguments); - }, - - // Open home page - openHome: function(e) { - if (e) e.preventDefault(); - this.page.loadPage() - } - }); - - return HelpDialog; -}); \ No newline at end of file diff --git a/addons/cb.help/views/page.js b/addons/cb.help/views/page.js deleted file mode 100644 index c997b11d..00000000 --- a/addons/cb.help/views/page.js +++ /dev/null @@ -1,65 +0,0 @@ -define([ - "showdown", - "extensions/github", - "extensions/table", - "less!stylesheets/page.less" -], function(Showdown) { - var hr = codebox.require("hr/hr"); - var _ = codebox.require("hr/utils"); - var $ = codebox.require("hr/dom"); - var URL = codebox.require("utils/url"); - - var PageView = hr.View.extend({ - className: "addon-help-page", - events: { - "click a": "clickLink" - }, - - // Constructor - initialize: function() { - PageView.__super__.initialize.apply(this, arguments); - this.converter = new Showdown.converter({ extensions: ['github', 'table'] }); - - this.content = ""; - this.loadPage(this.options.page); - return this; - }, - - // Load page - loadPage: function(page) { - var that = this; - - this.currentPage = page || "README.md"; - return hr.Requests.get("/docs/"+this.currentPage).then(function(content) { - that.content = content; - }, function() { - that.content = "# Error with page: "+_.escape(that.currentPage); - }).fin(function() { - that.render(); - }); - }, - - // Render - render: function() { - this.$el.html(this.converter.makeHtml(this.content)); - return this.ready(); - }, - - // Click link - clickLink: function(e) { - e.preventDefault(); - - var $a = $(e.currentTarget); - var url = $a.attr("href") - var r = new RegExp('^(?:[a-z]+:)?//', 'i'); - if (!r.test(url)) { - url = URL.absolutize(this.currentPage, url); - this.loadPage(url); - } else { - window.open(url); - } - } - }); - - return PageView; -}); \ No newline at end of file diff --git a/addons/cb.manager/client.js b/addons/cb.manager/client.js deleted file mode 100644 index 5bdefd0b..00000000 --- a/addons/cb.manager/client.js +++ /dev/null @@ -1,23 +0,0 @@ -define([ - "settings", - "views/dialog" -], function(managerSettings, InstallerDialog) { - var commands = codebox.require("core/commands/toolbar"); - var app = codebox.require("core/app"); - var dialogs = codebox.require("utils/dialogs"); - var menu = codebox.require("core/commands/menu"); - - // Add opening command - var command = commands.register("addons.manager.open", { - title: "Add-ons", - icon: "puzzle-piece", - visible: false, - offline: false, - }, function() { - dialogs.open(InstallerDialog); - }); - - // Add the command to file/tools menu - menu.getById("file").menu.add(command); -}); - diff --git a/addons/cb.manager/collections/addons.js b/addons/cb.manager/collections/addons.js deleted file mode 100644 index a843f5c9..00000000 --- a/addons/cb.manager/collections/addons.js +++ /dev/null @@ -1,112 +0,0 @@ -define([ - "settings" -], function(managerSettings) { - var Q = codebox.require("hr/promise"); - var hr = codebox.require("hr/hr"); - var _ = codebox.require("hr/utils"); - var Addon = codebox.require("models/addon"); - var addons = codebox.require("core/addons"); - var Addons = codebox.require("collections/addons"); - var box = codebox.require("core/box"); - - var Addons = Addons.extend({ - model: Addon, - defaults: _.defaults({ - loader: "allIndex", - loaderArgs: [], - startIndex: 0, - limit: 10 - }, hr.Collection.prototype.defaults), - - // Get index - getIndex: function() { - var that = this; - var indexKey = managerSettings.user.get("registry"); - - this._index = this._index || hr.Cache.get("addons", indexKey); - if (this._index) { - return Q(this._index); - } - - return hr.Requests.getJSON(box.proxyUrl(managerSettings.user.get("registry")+"/api/addons?limit=1000")).then(function(index) { - that._index = index; - that._index.addons = _.map(that._index.addons, function(addon) { - return _.extend(addon['package'], { - 'git': addon.git - }); - }); - hr.Cache.set("addons", indexKey, that._index, 60*60); - - return Q(that._index); - }); - }, - - // Addon from indexes - getFromIndex: function(options, filter) { - var that = this; - options = _.defaults({}, options || {}, this.options); - - return this.getIndex().then(function(index) { - var results = filter(index.addons); - - that.add({ - 'list': results.slice(options.startIndex, options.startIndex+options.limit), - 'n': _.size(results) - }); - - return Q(results); - }); - }, - - // Get index - allIndex: function(options) { - return this.getFromIndex(options, _.identity); - }, - - // Search in index - searchIndex: function(query, options) { - query = query.toLowerCase(); - return this.getFromIndex(options, function(index) { - - return _.filter(index, function(addon) { - var text = [ - addon.name, - addon.description, - addon.author, - addon.title - ].join(" ").toLowerCase(); - return text.search(query) >= 0; - }); - }); - }, - - // Return installed addons - allInstalled: function(options) { - this.reset(addons.filter(function(model) { - return !addons.isDefault(model.get("name")); - }), { - totalCount: true - }); - }, - - // Return defaults addons - allDefaults: function(options) { - this.reset(addons.filter(function(model) { - return addons.isDefault(model.get("name")); - }), { - totalCount: true - }); - }, - - // Return non installed addons - allAvailable: function(options) { - return this.getFromIndex(options, function(index) { - return _.filter(index, function(addon) { - return !addons.isInstalled(addon.name); - }); - }); - } - }); - - return Addons; -}); \ No newline at end of file diff --git a/addons/cb.manager/package.json b/addons/cb.manager/package.json deleted file mode 100644 index 89fcb6da..00000000 --- a/addons/cb.manager/package.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "name": "cb.manager", - "version": "0.1.3", - "title": "Add-ons", - "description": "Add-ons manager: install or uninstall addons from the main repository", - "homepage": "https://github.com/FriendCode/codebox", - "license": "Apache", - "author": { - "name": "Codebox", - "email": "contact@friendco.de", - "url": "https://www.codebox.io" - }, - "client": { - "main": "client" - } -} \ No newline at end of file diff --git a/addons/cb.manager/settings.js b/addons/cb.manager/settings.js deleted file mode 100644 index 038ba7e9..00000000 --- a/addons/cb.manager/settings.js +++ /dev/null @@ -1,19 +0,0 @@ -define([], function() { - var settings = codebox.require("core/settings"); - - // Add settings - return settings.add({ - 'namespace': "manager", - 'title': "Addons", - 'defaults': { - 'registry': "https://api.codebox.io" - }, - 'fields': { - 'registry': { - 'label': "Registry", - 'type': "text" - } - } - }); -}); - diff --git a/addons/cb.manager/stylesheets/addons.less b/addons/cb.manager/stylesheets/addons.less deleted file mode 100644 index 26a2bd8f..00000000 --- a/addons/cb.manager/stylesheets/addons.less +++ /dev/null @@ -1,67 +0,0 @@ -.addon-manager-dialog { - .modal-dialog { - @media screen and (min-width: 768px) { - width: 760px; - } - } - - .modal-body { - padding: 0px; - } - - .search-input { - float: right; - width: 200px; - border: 1px solid #ddd; - padding: 5px; - margin-top: -5px; - - &:hover, &:focus { - outline: 0; - } - } - - .addons-list { - list-style: none; - margin: 0px; - padding: 0px 20px; - - .hr-list-message-more { - text-align: center; - background: #eee; - margin: 0px; - } - - .addon-item { - min-height: 60px; - margin: 10px 0px; - - p { - margin: 0px; - - &.name { - text-overflow: ellipsis; - overflow: hidden; - white-space: nowrap; - } - } - - .base { - float: left; - width: 100px; - margin-right: 10px; - - .version { - color: #666; - } - } - .more { - margin-left: 110px; - } - .actions { - float: right; - margin-left: 20px; - } - } - } -} diff --git a/addons/cb.manager/templates/addon.html b/addons/cb.manager/templates/addon.html deleted file mode 100644 index a8f5299f..00000000 --- a/addons/cb.manager/templates/addon.html +++ /dev/null @@ -1,27 +0,0 @@ -
    - <% if (!isDefault) { %> - <% if (addonStatus == "error") { %> - - <% } %> - <% if (isInstalled && !isUpdated) { %> - - <% } else { %> - <% if (!isInstalled) { %> - Install - <% } else { %> - Uninstall - <% } %> - <% } %> - <% } else { %> - - <% } %> -
    - -
    -

    <%- model.get("title") %>

    -

    <%- model.get("version") %>

    -
    - \ No newline at end of file diff --git a/addons/cb.manager/templates/dialog.html b/addons/cb.manager/templates/dialog.html deleted file mode 100644 index a4637249..00000000 --- a/addons/cb.manager/templates/dialog.html +++ /dev/null @@ -1,30 +0,0 @@ - \ No newline at end of file diff --git a/addons/cb.manager/views/addons.js b/addons/cb.manager/views/addons.js deleted file mode 100644 index e1f3c1dc..00000000 --- a/addons/cb.manager/views/addons.js +++ /dev/null @@ -1,65 +0,0 @@ -define([ - 'collections/addons', - 'text!templates/addon.html', - 'less!stylesheets/addons' -], function(Addons, templateFile) { - var hr = codebox.require("hr/hr"); - var _ = codebox.require("hr/utils"); - var addons = codebox.require("core/addons"); - - // Collections of addons - var managerAddons = new Addons(); - managerAddons.getIndex(); - - var AddonItem = hr.List.Item.extend({ - className: "addon-item", - templateLoader: "text", - template: templateFile, - events: { - 'click .action-install': 'install', - 'click .action-uninstall': 'uninstall' - }, - - templateContext: function() { - return { - 'model': this.model, - 'addonStatus': addons.getState(this.model.get("name")), - 'isInstalled': addons.isInstalled(this.model.get("name")), - 'isDefault': addons.isDefault(this.model.get("name")), - 'isUpdated': addons.isUpdated(this.model) - } - }, - - install: function(e) { - if (e) e.preventDefault(); - var that = this; - var btn = this.$(".action-install"); - btn.button('loading'); - addons.install(this.model.get("git")).then(_.bind(this.render, this)).fin(function() { - btn.button('reset'); - that.update(); - }); - }, - uninstall: function(e) { - if (e) e.preventDefault(); - var that = this; - var btn = this.$(".action-install"); - btn.button('loading'); - addons.uninstall(this.model.get("name")).then(_.bind(this.render, this)).fin(function() { - btn.button('reset'); - that.update(); - }); - } - }); - - var AddonsList = hr.List.extend({ - className: "addons-list", - Collection: Addons, - Item: AddonItem, - defaults: _.defaults({ - 'collection': managerAddons - }, hr.List.prototype.defaults) - }); - - return AddonsList; -}); \ No newline at end of file diff --git a/addons/cb.manager/views/dialog.js b/addons/cb.manager/views/dialog.js deleted file mode 100644 index aa011ce8..00000000 --- a/addons/cb.manager/views/dialog.js +++ /dev/null @@ -1,61 +0,0 @@ -define([ - "views/addons", - "text!templates/dialog.html" -], function(AddonsList, templateFile) { - var $ = codebox.require("hr/dom"); - var DialogView = codebox.require("views/dialogs/base"); - var dialogs = codebox.require("utils/dialogs"); - var addons = codebox.require("core/addons"); - - var InstallerDialog = DialogView.extend({ - className: "addon-manager-dialog modal fade", - templateLoader: "text", - template: templateFile, - events: _.extend({}, DialogView.prototype.events,{ - "click .action-fromurl": "installFromUrl", - "click a[data-addons]": "filterAddons" - }), - - // Constructor - initialize: function(options) { - InstallerDialog.__super__.initialize.apply(this, arguments); - - this.list = new AddonsList(); - return this; - }, - - // Finish rendering - finish: function() { - this.list.$el.appendTo(this.$(".list")) - return InstallerDialog.__super__.finish.apply(this, arguments); - }, - - // Install from url - installFromUrl: function(e) { - if (e) e.preventDefault(); - dialogs.prompt("Install a new addon", "GIT url for the addon:", "").then(function(url) { - addons.install(url).then(function() { - dialogs.alert("Installation", "Add-on installed with success!"); - }, function() { - dialogs.alert("Installation", "Sorry, installation failed, please check that the url you entered is correct and the GIT repository a correct CodeBox add-on."); - }); - }); - }, - - // Filter addons - filterAddons: function(e) { - e.preventDefault(); - var filter = $(e.currentTarget).data("addons"); - var filters = { - 'all': "allIndex", - 'installed': "allInstalled", - 'defaults': "allDefaults", - 'available': "allAvailable" - }; - this.list.collection.reset([]); - this.list.collection[filters[filter]](); - } - }); - - return InstallerDialog; -}); \ No newline at end of file diff --git a/addons/cb.offline/client.js b/addons/cb.offline/client.js deleted file mode 100644 index 9c293635..00000000 --- a/addons/cb.offline/client.js +++ /dev/null @@ -1,78 +0,0 @@ -define([ - "settings", - "menus" -], function(settings, menus) { - var $ = codebox.require("hr/dom"); - var Q = codebox.require("hr/promise"); - var app = codebox.require("core/app"); - var box = codebox.require("core/box"); - var menu = codebox.require("core/commands/menu"); - var commands = codebox.require("core/commands/toolbar"); - var operations = codebox.require("core/operations"); - var hr = codebox.require("hr/hr"); - var Command = codebox.require("models/command"); - var localfs = codebox.require("core/localfs"); - - var _syncInterval = null; - - - // Run offline cache update operation - var op = operations.start("offline.update", null, { - 'title': "Downloading new version", - 'icon': "fa-download", - 'state': window.applicationCache.status == window.applicationCache.IDLE ? "idle" : "running", - 'progress': 0 - }); - - // Application manifest - $(window.applicationCache).bind('downloading progress', function(e) { - var progress = 0; - if (e && e.originalEvent && e.originalEvent.lengthComputable) { - progress = Math.round(100*e.originalEvent.loaded/e.originalEvent.total); - } - op.state("running"); - op.progress(progress); - }); - $(window.applicationCache).bind('checking', function(e) { - op.state("running"); - op.progress(0); - }); - $(window.applicationCache).bind('noupdate cached obsolete error', function(e) { - op.state("idle"); - }); - - - // Update settings - var updateSettings = function() { - var enabled = settings.user.get("enabled", true); - if (_syncInterval) clearInterval(_syncInterval); - - // Enable sync - localfs.enableSync(settings.user.get("enabled", true)); - - // Set ignored files - localfs.setIgnoredFiles(settings.user.get("syncIgnore", "").split("\n")); - - // Toggle menu - menus.sync.toggleFlag("hidden", !enabled); - - // Run sync every 10min - _syncInterval = setInterval(function() { - localfs.autoSync(); - }, settings.user.get("syncInterval", 10)*60*1000); - }; - - setTimeout(function() { - localfs.sync(); - }, 5*1000); - - // Run sync everytime there is a modification - box.on("box:watch", function() { - localfs.autoSync(); - }); - - // Change settings - settings.user.change(updateSettings); - updateSettings(); -}); - diff --git a/addons/cb.offline/menus.js b/addons/cb.offline/menus.js deleted file mode 100644 index 6228db97..00000000 --- a/addons/cb.offline/menus.js +++ /dev/null @@ -1,78 +0,0 @@ -define([], function() { - var box = codebox.require("core/box"); - var menu = codebox.require("core/commands/menu"); - var commands = codebox.require("core/commands/toolbar"); - var operations = codebox.require("core/operations"); - var hr = codebox.require("hr/hr"); - var Command = codebox.require("models/command"); - var localfs = codebox.require("core/localfs"); - var dialogs = codebox.require("utils/dialogs"); - - // Command to check connection - var checkConnection = commands.register("offline.check", { - 'title': "Check Connection", - 'offline': true, - 'icon': "bolt" - }, function() { - hr.Offline.check(); - }); - - // Changes list - var menuListChanges = new Command({}, { - 'title': "Changes", - 'type': "menu", - 'flags': "disabled" - }); - - // Menu Synchronize - var menuSync = menu.register("offline.synchronize", { - title: "Synchronize", - position: 95, - offline: false - }).menuSection([ - checkConnection - ]).menuSection([ - { - 'title': "Calcul Changes", - 'offline': false, - 'action': function() { - return localfs.sync(); - } - } - ]).menuSection([ - { - 'title': "Reset All Changes", - 'offline': false, - 'action': function() { - return localfs.reset(); - } - }, - { - 'title': "Apply All Changes", - 'offline': false, - 'action': function() { - var n = localfs.changes.size(); - if (n == 0) return; - - dialogs.confirm("Do you really want to apply "+n+" changes?").then(function(yes) { - if (!yes) return; - return localfs.changes.applyAll(); - }); - } - } - ]).menuSection([ - menuListChanges - ]); - - // Changes update - localfs.changes.on("add remove reset", function() { - menuListChanges.toggleFlag("disabled", localfs.changes.size() == 0); - menuListChanges.menu.reset(localfs.changes.map(function(change) { - return change.command(); - })); - }); - - return { - 'sync': menuSync - } -}); \ No newline at end of file diff --git a/addons/cb.offline/package.json b/addons/cb.offline/package.json deleted file mode 100644 index 47699b6d..00000000 --- a/addons/cb.offline/package.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "name": "cb.offline", - "version": "0.0.1", - "title": "Help", - "description": "Menu for managing offline sync", - "homepage": "https://github.com/FriendCode/codebox", - "license": "Apache", - "author": { - "name": "Codebox", - "email": "contact@friendco.de", - "url": "https://www.codebox.io" - }, - "client": { - "main": "client" - } -} \ No newline at end of file diff --git a/addons/cb.offline/settings.js b/addons/cb.offline/settings.js deleted file mode 100644 index b77d222c..00000000 --- a/addons/cb.offline/settings.js +++ /dev/null @@ -1,30 +0,0 @@ -define([], function() { - var settings = codebox.require("core/settings"); - - // Add settings - return settings.add({ - 'namespace': "offline", - 'title': "Offline", - 'defaults': { - 'enabled': false, - 'syncInterval': 10 - }, - 'fields': { - 'enabled': { - 'label': 'Enable Files Synchronization', - 'type': "checkbox" - }, - 'syncInterval': { - 'label': "Synchronization (minutes)", - 'type': "number", - 'min': 1, - 'max': 1000, - 'step': 1 - }, - 'syncIgnore': { - 'label': "Ignored files (one by line)", - 'type': "textarea" - } - } - }); -}); \ No newline at end of file diff --git a/addons/cb.panel.files/client.js b/addons/cb.panel.files/client.js deleted file mode 100644 index 5f2de0c7..00000000 --- a/addons/cb.panel.files/client.js +++ /dev/null @@ -1,76 +0,0 @@ -define([ - "views/panel" -], function(PanelFilesView) { - var Command = codebox.require("models/command"); - var commands = codebox.require("core/commands/toolbar"); - var app = codebox.require("core/app"); - var panels = codebox.require("core/panels"); - var files = codebox.require("core/files"); - var menu = codebox.require("core/commands/menu"); - var box = codebox.require("core/box"); - - // Add files panels - var panel = panels.register("files", PanelFilesView); - - // Open files panel - panel.connectCommand(commands.register("files.tree.open", { - title: "Files", - icon: "folder-o", - position: 2, - shortcuts: [ - "alt+f" - ] - })); - - // Recents files - var recentFiles = Command.register("file.recents", { - 'type': "menu", - 'title': "Open Recent" - }); - files.recent.on("add remove reset", function() { - recentFiles.menu.reset(files.recent.map(function(file) { - var path = file.path(); - return { - 'title': file.get("name"), - 'action': function() { - files.open(path); - } - }; - }).reverse()); - }); - - - // Command new file - menu.getById("file").menuSection([ - { - 'id': "file.new", - 'type': "action", - 'title': "New File", - 'shortcuts': ["alt+shift+n"], - 'action': function() { - files.openNew() - } - }, { - 'id': "folder.create", - 'type': "action", - 'title': "New Folder", - 'shortcuts': ["alt+shift+f"], - 'action': function() { - box.root.actionMkdir(); - } - }, - recentFiles - ], { - position: 0 - }).menuSection([ - { - 'id': "workspace.save.zip", - 'type': "action", - 'title': "Save Project As ZIP", - 'offline': false, - 'action': function() { - window.open("/export/zip"); - } - } - ]); -}); \ No newline at end of file diff --git a/addons/cb.panel.files/package.json b/addons/cb.panel.files/package.json deleted file mode 100644 index de280540..00000000 --- a/addons/cb.panel.files/package.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "name": "cb.panel.files", - "version": "0.1.0", - "title": "Files Panel", - "description": "Files Tree Panel for exploring and managing the filesystem", - "homepage": "https://github.com/FriendCode/codebox", - "license": "Apache", - "author": { - "name": "Codebox", - "email": "contact@friendco.de", - "url": "https://www.codebox.io" - }, - "client": { - "main": "client" - } -} \ No newline at end of file diff --git a/addons/cb.panel.files/settings.js b/addons/cb.panel.files/settings.js deleted file mode 100644 index f56f3c9d..00000000 --- a/addons/cb.panel.files/settings.js +++ /dev/null @@ -1,29 +0,0 @@ -define([], function() { - var $ = codebox.require("hr/dom"); - var settings = codebox.require("core/settings"); - - // Add settings - return settings.add({ - 'namespace': "files-panel", - 'title': "Files Explorer Panel", - 'defaults': { - 'openfiles': true, - 'hiddenfiles': true, - 'gitfolder': false - }, - 'fields': { - 'openfiles': { - 'label': "Show Open Files", - 'type': "checkbox" - }, - 'hiddenfiles': { - 'label': "Show Hidden Files", - 'type': "checkbox" - }, - 'gitfolder': { - 'label': "Show GIT Folder", - 'type': "checkbox" - } - } - }); -}); \ No newline at end of file diff --git a/addons/cb.panel.files/stylesheets/files.less b/addons/cb.panel.files/stylesheets/files.less deleted file mode 100644 index d9fa0ddd..00000000 --- a/addons/cb.panel.files/stylesheets/files.less +++ /dev/null @@ -1,93 +0,0 @@ -.cb-files-tree { - margin: 0px; - padding: 0px; - list-style: none; - - &.root { - - } - - .file-item { - cursor: default; - line-height: 24px; - font-size: 14px; - - &.hr-list-fiter-on { - display: none; - } - - >.files { - display: none; - } - - &.active, &.active:hover { - >.name { - background: rgba(0,0,0, 0.08); - color: inherit; - } - } - - &.disabled { - >.name { - color: #999; - } - } - - &.ui-context-menu { - >.name { - background: rgba(0, 0, 0, 0.15); - } - } - - >.name { - color: inherit; - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; - display: block; - z-index: 1; - position: relative; - - &:hover { - background: #5E9EF3; - color: #fff; - } - - >i { - width: 11px; - text-align: center; - - &.fa-file { - color: transparent; - text-shadow: none; - } - } - >.fa-caret-right { - display: inline-block; - } - >.fa-caret-down { - display: none; - } - } - - &.type-directory { - >.name { - /*color: inherit;*/ - } - } - - &.open { - >.files { - display: block; - } - >.name { - >.fa-caret-right { - display: none; - } - >.fa-caret-down { - display: inline-block; - } - } - } - } -} \ No newline at end of file diff --git a/addons/cb.panel.files/stylesheets/panel.less b/addons/cb.panel.files/stylesheets/panel.less deleted file mode 100644 index 65b56333..00000000 --- a/addons/cb.panel.files/stylesheets/panel.less +++ /dev/null @@ -1,21 +0,0 @@ -.cb-panel-files { - position: absolute; - top: 0px; - bottom: 0px; - left: 0px; - width: 100%; - z-index: 10; - - .files-panel-section { - margin-bottom: 10px; - - .section-header { - text-transform: uppercase; - font-weight: 800; - padding: 0px 10px; - font-size: 13px; - opacity: 0.65; - line-height: 28px; - } - } -} \ No newline at end of file diff --git a/addons/cb.panel.files/templates/item.html b/addons/cb.panel.files/templates/item.html deleted file mode 100644 index ccbc5a13..00000000 --- a/addons/cb.panel.files/templates/item.html +++ /dev/null @@ -1,12 +0,0 @@ - - <% if (file.isDirectory()) { %> - - - <% } else { %> - - <% } %> - <%- file.get("name") %> - -<% if (file.isDirectory()) { %> -
    -<% } %> \ No newline at end of file diff --git a/addons/cb.panel.files/templates/panel.html b/addons/cb.panel.files/templates/panel.html deleted file mode 100644 index 7a9f2853..00000000 --- a/addons/cb.panel.files/templates/panel.html +++ /dev/null @@ -1,9 +0,0 @@ -
    -
    Open Files
    -
    -
    - -
    -
    Folders
    -
    -
    \ No newline at end of file diff --git a/addons/cb.panel.files/views/list.js b/addons/cb.panel.files/views/list.js deleted file mode 100644 index 3503341d..00000000 --- a/addons/cb.panel.files/views/list.js +++ /dev/null @@ -1,23 +0,0 @@ -define([ - "views/tree" -], function(FilesTreeView) { - var _ = codebox.require("hr/utils"); - var $ = codebox.require("hr/dom"); - var hr = codebox.require("hr/hr"); - - // Commands list - var FilesListView = hr.List.extend({ - tagName: "ul", - className: "cb-files-tree", - - Item: FilesTreeView.Item, - defaults: _.extend({}, hr.List.prototype.defaults, { - baseFilter: function(model) { - return !model.isNewfile(); - } - }) - }); - - - return FilesListView; -}); \ No newline at end of file diff --git a/addons/cb.panel.files/views/panel.js b/addons/cb.panel.files/views/panel.js deleted file mode 100644 index e183e78f..00000000 --- a/addons/cb.panel.files/views/panel.js +++ /dev/null @@ -1,80 +0,0 @@ -define([ - "settings", - "views/tree", - "views/list", - "text!templates/panel.html", - "less!stylesheets/panel.less" -], function(panelSettings, FilesTreeView, FilesListView, templateFile) { - var _ = codebox.require("hr/utils"); - var $ = codebox.require("hr/dom"); - var hr = codebox.require("hr/hr"); - var box = codebox.require("core/box"); - var files = codebox.require("core/files"); - var search = codebox.require("core/search"); - var ContextMenu = codebox.require("utils/contextmenu"); - var PanelBaseView = codebox.require("views/panels/base"); - - var PanelFilesView = PanelBaseView.extend({ - className: "cb-panel-files", - templateLoader: "text", - template: templateFile, - - initialize: function() { - PanelFilesView.__super__.initialize.apply(this, arguments); - - this.listActive = new FilesListView({ - collection: files.active - }); - - this.tree = new FilesTreeView({ - model: box.root - }); - this.tree.update(); - - this.tree.on("count", function(count) { - this.toggle(count > 0); - }, this); - - this.listActive.on("add remove filter", function(item, state) { - this.$(".files-section-open").toggle(panelSettings.user.get("openfiles") && this.listActive.count() > 0); - }, this); - - // Offline - hr.Offline.on("state", function() { - this.update(); - }, this); - - // Settings update - panelSettings.user.change(function() { - this.update(); - }, this); - - // Context menu - ContextMenu.add(this.$el, box.root.contextMenu()); - }, - - render: function() { - this.tree.$el.detach(); - this.listActive.$el.detach(); - - return PanelFilesView.__super__.render.apply(this, arguments); - }, - - finish: function() { - this.toggle(this.tree.countFiles > 0); - - if (panelSettings.user.get("openfiles")) { - this.listActive.$el.appendTo(this.$(".files-section-open .section-content")); - this.$(".files-section-open").toggle(this.listActive.count() > 0); - } else { - this.$(".files-section-open").hide(); - } - - this.tree.$el.appendTo(this.$(".files-section-tree .section-content")); - - return PanelFilesView.__super__.finish.apply(this, arguments); - }, - }); - - return PanelFilesView; -}); \ No newline at end of file diff --git a/addons/cb.panel.files/views/tree.js b/addons/cb.panel.files/views/tree.js deleted file mode 100644 index 9ffcd7a9..00000000 --- a/addons/cb.panel.files/views/tree.js +++ /dev/null @@ -1,161 +0,0 @@ -define([ - "settings", - "text!templates/item.html", - "less!stylesheets/files.less" -], function(panelSettings, templateFile) { - var _ = codebox.require("hr/utils"); - var $ = codebox.require("hr/dom"); - var hr = codebox.require("hr/hr"); - var box = codebox.require("core/box"); - var ContextMenu = codebox.require("utils/contextmenu"); - var FilesBaseView = codebox.require("views/files/base"); - - // File item in the tree - var FilesTreeViewItem = FilesBaseView.extend({ - tagName: "li", - className: "file-item", - templateLoader: "text", - template: templateFile, - events: { - "click .name": "select", - "dblclick .name": "open" - }, - - // Constructor - initialize: function(options) { - FilesTreeViewItem.__super__.initialize.apply(this, arguments); - var that = this; - - // View for subfiles - this.subFiles = null; - this.paddingLeft = this.options.paddingLeft || 0; - - // Context menu - ContextMenu.add(this.$el, this.model.contextMenu()); - - box.on("file.active", function(path) { - this.$el.toggleClass("active", this.model.path() == path); - }, this); - - return this; - }, - - // Finish rendering - finish: function() { - this.$el.toggleClass("disabled", !this.model.canOpen()); - this.$(">.name").css("padding-left", this.paddingLeft); - this.$el.toggleClass("type-directory", this.model.isDirectory()); - - if (this.subFiles) { - this.subFiles.$el.appendTo(this.$(".files")); - } - return FilesTreeViewItem.__super__.finish.apply(this, arguments); - }, - - // (event) select the file : extend tree - select: function(e) { - if (e != null) { - e.preventDefault(); - e.stopPropagation(); - } - - if (!this.model.canOpen()) { - return; - } - - if (this.model.isDirectory()) { - if (this.subFiles == null) { - this.subFiles = new FilesTreeView({ - "codebox": this.codebox, - "model": this.model, - "paddingLeft": this.paddingLeft+15 - }); - this.subFiles.$el.appendTo(this.$(".files")); - this.subFiles.update(); - } - this.$el.toggleClass("open"); - } else { - this.open(); - } - }, - - // (event) open the file or directory - open: function(e) { - if (e != null) { - e.preventDefault(); - e.stopPropagation(); - } - - if (!this.model.canOpen()) { - return; - } - - if (!this.model.isDirectory()) { - this.model.open({ - 'userChoice': false - }); - } else { - this.select(); - } - } - }); - - // Complete files tree - var FilesTreeView = FilesBaseView.extend({ - tagName: "ul", - className: "cb-files-tree", - - // Constructor - initialize: function(options) { - FilesTreeView.__super__.initialize.apply(this, arguments); - var that = this; - - this.countFiles = 0; - this.paddingLeft = this.options.paddingLeft || 10; - - panelSettings.user.change(function() { - this.update(); - }, this); - - return this; - }, - - // Render the files tree - render: function() { - var that = this; - this.$el.toggleClass("root", this.model.isRoot()); - - // Context menu - ContextMenu.add(this.$el, this.model.contextMenu()); - - this.model.listdir().then(function(files) { - that.empty(); - that.countFiles = 0; - - _.each(files, function(file) { - if ((file.isGit() && !panelSettings.user.get("gitfolder")) - || (file.isHidden() && !panelSettings.user.get("hiddenfiles"))) { - return; - } - - var v = new FilesTreeViewItem({ - "codebox": that.codebox, - "model": file, - "paddingLeft": that.paddingLeft - }); - v.update(); - v.$el.appendTo(that.$el); - - that.countFiles = that.countFiles + 1; - }); - that.trigger("count", that.countFiles); - }); - - return that.ready(); - }, - }, { - 'Item': FilesTreeViewItem - }); - - return FilesTreeView; -}); \ No newline at end of file diff --git a/addons/cb.panel.search/client.js b/addons/cb.panel.search/client.js deleted file mode 100644 index 6245a892..00000000 --- a/addons/cb.panel.search/client.js +++ /dev/null @@ -1,21 +0,0 @@ -define([ - "views/panel" -], function(PanelSearchView) { - var commands = codebox.require("core/commands/toolbar"); - var app = codebox.require("core/app"); - var panels = codebox.require("core/panels"); - - // Add search panel - var panel = panels.register("search", PanelSearchView); - - // Add opening command - var command = commands.register("search.open", { - title: "Search", - icon: "search", - position: 0, - shortcuts: [ - "alt+s" - ] - }); - panel.connectCommand(command); -}); \ No newline at end of file diff --git a/addons/cb.panel.search/package.json b/addons/cb.panel.search/package.json deleted file mode 100644 index 28709d83..00000000 --- a/addons/cb.panel.search/package.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "name": "cb.panel.search", - "version": "0.1.0", - "title": "Search Panel", - "description": "Search panel for searching files or resources", - "homepage": "https://github.com/FriendCode/codebox", - "license": "Apache", - "author": { - "name": "Codebox", - "email": "contact@friendco.de", - "url": "https://www.codebox.io" - }, - "client": { - "main": "client" - } -} \ No newline at end of file diff --git a/addons/cb.panel.search/stylesheets/panel.less b/addons/cb.panel.search/stylesheets/panel.less deleted file mode 100644 index 7c51a800..00000000 --- a/addons/cb.panel.search/stylesheets/panel.less +++ /dev/null @@ -1,43 +0,0 @@ -.cb-panel-search { - position: absolute; - top: 0px; - bottom: 0px; - left: 0px; - width: 100%; - z-index: 10; - padding: 4px 6px; - - input.search-query { - border-radius: 1px; - background: #fff; - color: #222; - border: none; - width: 100%; - margin: 0px 0; - padding: 3px 5px; - font-size: 12px; - line-height: 20px; - border: 1px solid #ddd; - - &:hover, &:focus { - outline: 0; - } - } - - .results { - position: absolute; - right: 0px; - left: 0px; - width: auto; - margin: 0px; - padding: 0px; - top: 36px; - bottom: 0px; - padding-top: 0px; - overflow-y: auto; - - .category { - display: none; - } - } -} \ No newline at end of file diff --git a/addons/cb.panel.search/templates/panel.html b/addons/cb.panel.search/templates/panel.html deleted file mode 100644 index fff98183..00000000 --- a/addons/cb.panel.search/templates/panel.html +++ /dev/null @@ -1,2 +0,0 @@ - -
    \ No newline at end of file diff --git a/addons/cb.panel.search/views/panel.js b/addons/cb.panel.search/views/panel.js deleted file mode 100644 index a7ea95a3..00000000 --- a/addons/cb.panel.search/views/panel.js +++ /dev/null @@ -1,200 +0,0 @@ -define([ - "text!templates/panel.html", - "less!stylesheets/panel.less" -], function(templateFile) { - var _ = codebox.require("hr/utils"); - var $ = codebox.require("hr/dom"); - var hr = codebox.require("hr/hr"); - var search = codebox.require("core/search"); - var PanelBaseView = codebox.require("views/panels/base"); - - var PanelSearchView = PanelBaseView.extend({ - className: "cb-panel-search", - template: templateFile, - templateLoader: "text", - events: { - "click input": "focus", - "blur input": "inputBlur", - "focus input": "inputFocus", - "keydown input": "keydown", - "keyup input": "keyup", - "click .result": "openResult" - }, - - initialize: function(options) { - PanelSearchView.__super__.initialize.apply(this, arguments); - - this.openCallback = {}; - this.nResults = 0; - this.selected = 0; - this.query = ""; - - // Bind events - this.on("panel:open", function() { - this.focus(); - }, this); - this.on("panel:close", function() { - this.blur(); - }, this); - - return this; - }, - - /* (event) Key input in search */ - keydown: function(e) { - var key = e.which || e.keyCode; - var q = $(e.currentTarget).val(); - - if (key == 38 || key == 40 || key == 13) { - e.preventDefault(); - } - - if (q.length == 0 && key == 8) { - e.preventDefault(); - this.blur(); - this.clearResults(); - this.close(); - } - }, - - /* (event) Key input in search */ - keyup: function(e) { - var key = e.which || e.keyCode; - var q = $(e.currentTarget).val(); - - if (key == 27) { - /* ESC */ - e.preventDefault(); - this.blur(); - this.clearResults(); - this.close(); - return; - } else if (key == 38) { - /* UP */ - this.selected = this.selected - 1; - } else if (key == 40) { - /* DOWN */ - this.selected = this.selected + 1; - } else if (key == 13) { - /* ENTER */ - e.preventDefault(); - this.openResult(this.selected); - } - this.doSearch(q); - - this.selectResult(this.selected); - }, - - /* (event) Focus on search */ - focus: function(e) { - if (e != null) e.preventDefault(); - this.$("input").focus(); - this.$("input").select(); - }, - - /* (event) Blur search */ - blur: function(e) { - if (e != null) e.preventDefault(); - this.$("input").blur(); - }, - - /* Do search */ - doSearch: function(query) { - var that = this; - var $results = this.$(".results"); - - if (query == this.query) return this; - - this.query = query; - this.nResults = 0; - this.clearResults(); - - if (this.query.length == 0) return this; - - search.query(this.query, function(category, results, query) { - if (this.query != query) return; - - var n = 0; - var $cat = $("
      ", { - "class": "cb-panel-list category" - }).hide().appendTo($results); - $("
    • ", { - "text": category.title, - "class": "header" - }).appendTo($cat); - - _.each(results, function(result) { - var li, i; - i = this.nResults; - this.nResults = this.nResults + 1; - n = n + 1; - li = $("
    • ", { - "class": "result", - "data-result": i, - "text": result.text, - "hover": function() { - that.selectResult(i); - } - }).appendTo($cat); - - if (result.image != null) { - $("", { - "src": result.image - }).prependTo(li) - } - $cat.show(); - - // Callback for click - if (result.callback != null) { - this.openCallback[i] = result.callback; - } - - // Reselect result - this.selectResult(this.selected); - }, this); - }, this); - return this; - }, - - /* Select a result */ - selectResult: function(i) { - this.selected = i; - if (this.selected < -1) this.selected = 0; - if (this.selected >= this.nResults) this.selected = this.nResults - 1; - - this.$(".result").removeClass("selected"); - this.$(".result[data-result='"+this.selected+"']").addClass("selected"); - - return this; - }, - - /* Clear results */ - clearResults: function() { - this.$(".results").empty(); - this.openCallback = {}; - return this; - }, - - /* Open a result */ - openResult: function(i) { - if (!_.isNumber(i)) { - i = $(i.currentTarget).data("result"); - } - if (i == -1) return this; - if (this.openCallback[i] != null) this.openCallback[i](); - return this; - }, - - /* Blur the input */ - inputBlur: function() { - this.$el.toggleClass("mode-results", false); - }, - - /* Focus the input */ - focusBlur: function() { - this.$el.toggleClass("mode-results", this.query.length > 0); - } - }); - - return PanelSearchView; -}); \ No newline at end of file diff --git a/addons/cb.project/autorun.js b/addons/cb.project/autorun.js deleted file mode 100644 index dc63d19a..00000000 --- a/addons/cb.project/autorun.js +++ /dev/null @@ -1,63 +0,0 @@ -define([ - 'ports' -], function(ports) { - var _ = codebox.require("hr/utils"); - var commands = codebox.require("core/commands/toolbar"); - var operations = codebox.require("core/operations"); - var box = codebox.require("core/box"); - var dialogs = codebox.require("utils/dialogs"); - var alerts = codebox.require("utils/alerts"); - var Command = codebox.require("models/command"); - - // Map type -> icon - var typeIcons = { - 'run': "fa-play", - 'build': "fa-cog fa-spin", - 'clean': "fa-eraser" - }; - - // Run command - var runCommand = commands.register("project.run", { - title: "Run", - icon: "play", - offline: false, - position: 1, - shortcuts: [ - "alt+r" - ] - }, function(options) { - options = options || {}; - return box.run(options).then(function(runInfo) { - var op = operations.start("project.run."+runInfo.shellId, null, { - 'title': runInfo.name+" running on port "+runInfo.port, - 'icon': typeIcons[runInfo.type] || "fa-play", - 'action': function() { - // Open the url - window.open(runInfo.url); - - // Check that port is still active - ports.update().then(function(ports) { - var _port = _.find(ports, function(proc) { - return proc.port == runInfo.port; - }); - if (!_port) { - op.destroy(); - } - }); - } - }); - - // Terminal is close: finish the operation - runInfo.terminal.on("tab:close", function() { - op.destroy(); - }); - ports.update(); - }, function(err) { - dialogs.alert("Error running this project", "An error occurred when trying to run this project: "+(err.message || err)); - }); - }); - - return { - 'command': runCommand - } -}); \ No newline at end of file diff --git a/addons/cb.project/client.js b/addons/cb.project/client.js deleted file mode 100644 index 9d4520f4..00000000 --- a/addons/cb.project/client.js +++ /dev/null @@ -1,72 +0,0 @@ -define([ - 'runner', - 'ports', - 'autorun', - 'samples' -], function(runner, ports, autorun, samples) { - var _ = codebox.require("hr/utils"); - var operations = codebox.require("core/operations"); - var app = codebox.require("core/app"); - var box = codebox.require("core/box"); - var menu = codebox.require("core/commands/menu"); - var dialogs = codebox.require("utils/dialogs"); - var alerts = codebox.require("utils/alerts"); - var Command = codebox.require("models/command"); - - // Add samples submenu - menu.getById("file").menuSection([ - samples.command - ]) - - // Add menu - menu.register("project", { - title: "Project", - offline: false - }).menuSection([ - autorun.command, - runner.command - ]).menuSection([ - Command.register("project.build", { - 'title': "Build", - 'offline': false, - 'action': function() { - return autorun.command.run({ - 'type': "build" - }); - }, - 'shortcuts': [ - "mod+b" - ] - }), - Command.register("project.clean", { - 'title': "Clean", - 'offline': false, - 'action': function() { - return autorun.command.run({ - 'type': "clean" - }); - }, - 'shortcuts': [ - "mod+shift+k" - ] - }) - ]).menuSection([ - { - 'type': "action", - 'title': "Refresh Ports", - 'offline': false, - 'action': ports.update - }, - ports.command - ]); - - // Auto-updates - box.on("box:project:define", function() { - runner.update(); - }); - - // Updates list - runner.update(); - ports.update(); - samples.update(); -}); \ No newline at end of file diff --git a/addons/cb.project/package.json b/addons/cb.project/package.json deleted file mode 100644 index e65a5a90..00000000 --- a/addons/cb.project/package.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "name": "cb.project", - "version": "0.1.0", - "title": "Project", - "description": "Project types manager: autorun, sample", - "homepage": "https://github.com/FriendCode/codebox", - "license": "Apache", - "author": { - "name": "Codebox", - "email": "contact@friendco.de", - "url": "https://www.codebox.io" - }, - "client": { - "main": "client" - } -} \ No newline at end of file diff --git a/addons/cb.project/ports.js b/addons/cb.project/ports.js deleted file mode 100644 index 4dedd142..00000000 --- a/addons/cb.project/ports.js +++ /dev/null @@ -1,42 +0,0 @@ -define([], function() { - var _ = codebox.require("hr/utils"); - var operations = codebox.require("core/operations"); - var box = codebox.require("core/box"); - var dialogs = codebox.require("utils/dialogs"); - var alerts = codebox.require("utils/alerts"); - var Command = codebox.require("models/command"); - - // HTTP Ports - var httpPorts = new Command({}, { - 'id': "run.ports.http", - 'title': "Running Ports", - 'type': "menu", - 'offline': false - }); - - // Update running ports list - var updatePorts = function() { - return box.procHttp().then(function(ports) { - httpPorts.menu.reset(_.map(ports, function(proc) { - return { - 'title': proc.port, - 'flags': proc.reachable ? "" : "disabled", - 'action': function() { - if (proc.reachable) { - window.open(proc.url); - } else { - dialogs.alert("Your server is not accessible ", "Your server is not accessible externally because it is bound to 'localhost', please bind it to '0.0.0.0' instead"); - } - } - }; - })); - - return ports; - }); - }; - - return { - 'command': httpPorts, - 'update': updatePorts - } -}); \ No newline at end of file diff --git a/addons/cb.project/runner.js b/addons/cb.project/runner.js deleted file mode 100644 index 0b263d9b..00000000 --- a/addons/cb.project/runner.js +++ /dev/null @@ -1,41 +0,0 @@ -define([ - 'autorun' -], function(autorun) { - var _ = codebox.require("hr/utils"); - var operations = codebox.require("core/operations"); - var box = codebox.require("core/box"); - var dialogs = codebox.require("utils/dialogs"); - var alerts = codebox.require("utils/alerts"); - var Command = codebox.require("models/command"); - - // Run commands - var runCommands = new Command({}, { - 'id': "project.action", - 'title': "Perform Action", - 'type': "menu", - 'offline': false - }); - - // Update runner list - var updateList = function() { - return box.runner().then(function(runner) { - runCommands.menu.reset(_.map(runner, function(_runner) { - return { - 'title': _runner.name, - 'action': function() { - autorun.command.run({ - 'id': _runner.id - }); - } - }; - })); - - return ports; - }); - }; - - return { - 'command': runCommands, - 'update': updateList - } -}); \ No newline at end of file diff --git a/addons/cb.project/samples.js b/addons/cb.project/samples.js deleted file mode 100644 index 813866a6..00000000 --- a/addons/cb.project/samples.js +++ /dev/null @@ -1,47 +0,0 @@ -define([], function() { - var _ = codebox.require("hr/utils"); - var dialogs = codebox.require("utils/dialogs"); - var box = codebox.require("core/box"); - var rpc = codebox.require("core/backends/rpc"); - var Command = codebox.require("models/command"); - - // HTTP Ports - var samplesMenu = new Command({}, { - 'title': "Use Sample Project", - 'type': "menu", - 'offline': false - }); - - // Update samples list - var updateSamples = function() { - return rpc.execute("project/supported").then(function(projectTypes) { - samplesMenu.menu.reset( - _.chain(projectTypes) - .map(function(projectType) { - if (!projectType.sample) return null; - - return { - 'title': projectType.name, - 'action': function() { - dialogs.confirm("Replace workspace contents with "+projectType.name+" sample?", - "WARNING: Using a sample will erase the current contents of your workspace. Use only if your workspace is empty or if you want to wipe it").then(function() { - return rpc.execute("project/useSample", { - 'sample': projectType.id - }); - }); - } - }; - }) - .compact() - .value() - ); - - return projectTypes; - }); - }; - - return { - 'command': samplesMenu, - 'update': updateSamples - } -}); \ No newline at end of file diff --git a/addons/cb.settings/client.js b/addons/cb.settings/client.js deleted file mode 100644 index 56283858..00000000 --- a/addons/cb.settings/client.js +++ /dev/null @@ -1,26 +0,0 @@ -define(["views/dialog"], function(SettingsDialog) { - var commands = codebox.require("core/commands/toolbar"); - var app = codebox.require("core/app"); - var dialogs = codebox.require("utils/dialogs"); - var menu = codebox.require("core/commands/menu"); - - // Add opening command - var command = commands.register("settings", { - title: "Settings", - icon: "cog", - shortcuts: [ - "mod+," - ], - visible: false, - position: 100, - offline: false - }, function(page) { - dialogs.open(SettingsDialog, { - 'page': page, - 'keyboardEnter': false - }); - }); - - menu.getById("file").menu.add(command); -}); - diff --git a/addons/cb.settings/package.json b/addons/cb.settings/package.json deleted file mode 100644 index 20348b78..00000000 --- a/addons/cb.settings/package.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "name": "cb.settings", - "version": "0.1.2", - "title": "Settings", - "description": "Configuration interface for your workspace.", - "homepage": "https://github.com/FriendCode/codebox", - "license": "Apache", - "author": { - "name": "Codebox", - "email": "contact@friendco.de", - "url": "https://www.codebox.io" - }, - "client": { - "main": "client" - } -} \ No newline at end of file diff --git a/addons/cb.settings/stylesheets/dialog.less b/addons/cb.settings/stylesheets/dialog.less deleted file mode 100644 index 49e53302..00000000 --- a/addons/cb.settings/stylesheets/dialog.less +++ /dev/null @@ -1,57 +0,0 @@ -.addon-settings-dialog { - .modal-dialog { - @media screen and (min-width: 768px) { - width: 760px; - } - } - - .modal-body { - padding: 0px; - position: relative; - width: 100%; - height: 100%; - - .settings-title { - opacity: 0.6; - } - - .settings-menu { - position: absolute; - top: 51px; - left: 0px; - width: 200px; - bottom: 0px; - overflow-y: auto; - background: #f8f8f8; - border-right: 1px solid #ddd; - - .nav-pills>li { - >a { - border-radius: 0px; - color: inherit; - border-left: 3px solid transparent; - } - - &.active { - >a { - border-left-color: #5E9EF3; - background: transparent; - } - } - } - } - - .settings-content { - margin-left: 200px; - min-height: 300px; - } - } - - .modal-footer { - margin-top: 0px; - } - - .settings-basepane { - margin: 20px; - } -} diff --git a/addons/cb.settings/templates/dialog.html b/addons/cb.settings/templates/dialog.html deleted file mode 100644 index 4a6fbc66..00000000 --- a/addons/cb.settings/templates/dialog.html +++ /dev/null @@ -1,34 +0,0 @@ -
      - -
      \ No newline at end of file diff --git a/addons/cb.settings/views/dialog.js b/addons/cb.settings/views/dialog.js deleted file mode 100644 index 147fe33e..00000000 --- a/addons/cb.settings/views/dialog.js +++ /dev/null @@ -1,66 +0,0 @@ -define([ - "text!templates/dialog.html", - "less!stylesheets/dialog.less" -], function(templateFile) { - var _ = codebox.require("hr/utils"); - var $ = codebox.require("hr/dom"); - var DialogView = codebox.require("views/dialogs/base"); - var settings = codebox.require("core/settings"); - - var SettingsDialog = DialogView.extend({ - className: "addon-settings-dialog modal fade", - templateLoader: "text", - template: templateFile, - events: _.extend({}, DialogView.prototype.events,{ - "submit form": "submit", - "shown.bs.tab a[data-toggle='tab']": "changeTab" - }), - - // Template settings - templateContext: function() { - return { - 'settings': settings, - 'tabs': _.pairs(settings.sections), - 'limit': 3 - } - }, - - // Finish rendering - finish: function() { - var that = this; - settings.each(function(tab) { - tab.render(); - tab.$el.appendTo(this.$("#settings-tab-"+tab.namespace)); - }, this); - setTimeout(function() { - if (that.options.page) { - that.$(".settings-menu a[href='#settings-tab-"+that.options.page+"']").tab('show'); - } else { - that.$(".settings-menu a:first").tab('show'); - } - }, 200); - return SettingsDialog.__super__.finish.apply(this, arguments); - }, - - // Update settings - submit: function(e) { - var that = this; - - if (e != null) { - e.preventDefault(); - e.stopPropagation(); - } - - settings.save().fin(function() { - that.close(); - }); - }, - - // Change tab - changeTab: function(e) { - this.$(".settings-title").text($(e.target).text()); - } - }); - - return SettingsDialog; -}); \ No newline at end of file diff --git a/addons/cb.terminal/client.js b/addons/cb.terminal/client.js deleted file mode 100644 index c8b26f2c..00000000 --- a/addons/cb.terminal/client.js +++ /dev/null @@ -1,115 +0,0 @@ -define([ - "vendors/sh", - "views/tab" -], function(Terminal, TerminalTab) { - var Command = codebox.require("models/command"); - var commands = codebox.require("core/commands/toolbar"); - var box = codebox.require("core/box"); - var tabs = codebox.require("core/tabs"); - var settings = codebox.require("core/settings"); - var menu = codebox.require("core/commands/menu"); - - // Add settings - settings.add({ - 'namespace': "terminal", - 'title': "Terminal", - 'defaults': { - 'font': "monospace", - 'size': 13, - 'line-height': 1.3, - 'theme': 'monokai_soda' - }, - 'fields': { - 'font': { - 'label': "Font", - 'type': "select", - 'options': { - 'monospace': "Monospace", - 'arial': "Arial", - 'Courier New': "Courier New", - "'MS Sans Serif', Geneva, sans-serif;": "MS Sans Serif", - "'Lucida Sans Unicode', 'Lucida Grande', sans-serif": "Lucida Sans Unicode", - 'monaco': "Monaco (Mac OS)", - 'menlo': "Menlo (Mac OS)", - 'Ubuntu Mono': "Ubuntu Mono (Ubuntu)", - 'Consolas': "Consolas (Windows)", - 'Lucida Console': "Lucida Console (Windows)" - }, - }, - 'size': { - 'label': 'Font size', - 'type': 'number', - 'min': 8, - 'max': 20, - 'step': 1 - }, - 'line-height': { - 'label': 'Line height', - 'type': 'number', - 'min': 1, - 'max': 1.9, - 'step': 0.1 - }, - 'theme': { - 'label': 'Theme', - 'type': 'select', - 'options': _.chain(Terminal.themes.defaults) - .clone() - .map(function(theme, name) { - return [name, name]; - }) - .object() - .value() - } - } - }); - - // Add opening command - var command = commands.register("terminal.open", { - title: "New Terminal", - icon: "terminal", - offline: false, - shortcuts: [ - "alt+t" - ] - }, function(shellId) { - // Create trminal tab - var tab = tabs.add(TerminalTab, { - 'shellId': shellId - }, { - 'section': "terminals" - }); - - // Return the tab - return tab; - }); - - // List terminals menu - var terminalsList = Command.register("terminal.list", { - title: "Open Terminals", - offline: false, - type: "menu" - }); - - var refreshList = function() { - return box.listShells().then(function(shellIds) { - terminalsList.menu.reset(_.map(shellIds, function(shellId) { - return { - title: shellId, - action: function() { - command.run(shellId) - } - } - })); - }); - }; - - // Reset list when events from shells: - box.on("box:shell:open box:shell:exit", refreshList); - - // Add the command to file/tools menu - menu.getById("file").menuSection([ - command, - terminalsList - ]); -}); \ No newline at end of file diff --git a/addons/cb.terminal/package.json b/addons/cb.terminal/package.json deleted file mode 100644 index 3f035d32..00000000 --- a/addons/cb.terminal/package.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "name": "cb.terminal", - "version": "0.0.5", - "title": "Terminal", - "description": "Terminal tab integration into your workspace.", - "homepage": "https://github.com/FriendCode/codebox", - "license": "Apache", - "author": { - "name": "Codebox", - "email": "contact@friendco.de", - "url": "https://www.codebox.io" - }, - "client": { - "main": "client" - } -} \ No newline at end of file diff --git a/addons/cb.terminal/stylesheets/tab.less b/addons/cb.terminal/stylesheets/tab.less deleted file mode 100644 index 576007d3..00000000 --- a/addons/cb.terminal/stylesheets/tab.less +++ /dev/null @@ -1,76 +0,0 @@ -.addon-terminal-tab { - position: absolute; - width: 100%; - height: 100%; - background: transparent; - - .tab-panel-body .tab-panel-inner.terminal-body { - background: #000; - border-color: #000; - overflow: auto; - cursor: text; - padding: 0px; - font-weight: bold; - padding: 3px; - overflow: hidden; - - * { - user-select: initial; - -webkit-user-select: initial; - } - - .terminal-container { - position: relative; - width: 100%; - height: 100%; - font-family: Menlo,Monaco,"DejaVu Sans Mono",Consolas,"Andale Mono",monospace; - } - .terminal-container div { - margin: 0px; - padding: 0px; - } - .terminal-container .terminal { - width: 100%; - height: 100%; - font-size: 13px; - line-height: 18px; - } - .terminal-container .terminal-input { - position: absolute; - top: 0; - left: -1000%; - background: rgba(255,255,255,0.75); - color: black; - border: 0; - outline: 0; - width: 100%; - } - .terminal-container .terminal-screen-keys { - position: absolute; - top: 0; - right: 0; - } - .terminal-container .terminal-screen-keys button { - background: -webkit-linear-gradient(top, #eeeef0, #d3d3d9); - border: 1px solid #58575e; - box-shadow: 0 2px 2px rgba(0,0,0,0.25), inset 0 -2px 0 rgba(0,0,0,0.25), inset 0 1px 0 #fff; - border: 1px solid #000; - border-radius: 2px; - padding: 8px; - font-size: 14px; - text-shadow: 0 1px 0 #fff; - } - .terminal-container .terminal-screen-keys button:focus, .terminal-container .terminal-screen-keys button.active { - outline: 0px; - background: -webkit-linear-gradient(top, #ccccd0, #a3a3a9); - } - .terminal-container .terminal-size-indicator { - position: absolute; - bottom: 0; - left: 0; - background-color: rgba(255,255,255,0.75); - color: black; - padding: 0 3px; - } - }; -} \ No newline at end of file diff --git a/addons/cb.terminal/vendors/sh.js b/addons/cb.terminal/vendors/sh.js deleted file mode 100644 index 7e7cca1e..00000000 --- a/addons/cb.terminal/vendors/sh.js +++ /dev/null @@ -1,2749 +0,0 @@ -!function(e){if("object"==typeof exports)module.exports=e();else if("function"==typeof define&&define.amd)define(e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.Terminal=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o= c.keyCode && -1 === [91, 92, 93, 144, 145].indexOf(c.keyCode)) && that.inputElement.focus(); - !Terminal.isMac && (k && c.shiftKey && document.execCommand) && (document.execCommand("copy", !0, null), events.cancel(c)) - }) - } -}; - -Terminal.prototype.open = function (parent) { - var that = this, - E = 0, - y; - this.element = document.createElement("div"); - this.element.className = "terminal"; - this.element.spellcheck = false; - for (this.children = []; E < this.rows; E++) y = document.createElement("div"), y.className = "terminal-row", y.setAttribute("data-row", (E + 1).toString()), this.element.appendChild(y), this.children.push(y); - - this.inputElement = document.createElement("textarea"); - this.inputElement.className = "terminal-input"; - this.inputElement.rows = "1"; - this.inputElement.spellcheck = false; - this.inputElement.autocorrect = "off"; - this.inputElement.autocapitalize = "off"; - - this.containerElement = document.createElement("div"); - this.containerElement.type = "text"; - this.containerElement.spellcheck = false; - this.containerElement.className = "terminal-container"; - this.containerElement.id = "terminal_" + s++; - - this.sizeIndicatorElement = document.createElement("div"); - this.sizeIndicatorElement.className = "terminal-size-indicator"; - this.sizeIndicatorElement.innerHTML = "80x25"; - this.sizeIndicatorElement.style.display = "none"; - - this.screenKeysElement = document.createElement("div"); - this.screenKeysElement.className = "terminal-screen-keys"; - - this.tabKeyElement = document.createElement("button"); - this.ctrlKeyElement = document.createElement("button"); - this.altKeyElement = document.createElement("button"); - this.escKeyElement = document.createElement("button"); - this.leftKeyElement = document.createElement("button"); - this.downKeyElement = document.createElement("button"); - this.upKeyElement = document.createElement("button"); - this.rightKeyElement = document.createElement("button"); - this.tabKeyElement.innerHTML = "Tab"; - this.ctrlKeyElement.innerHTML = "Ctrl"; - this.altKeyElement.innerHTML = "Alt"; - this.escKeyElement.innerHTML = "Esc"; - this.leftKeyElement.innerHTML = "\u2190"; - this.downKeyElement.innerHTML = "\u2193"; - this.upKeyElement.innerHTML = - "\u2191"; - this.rightKeyElement.innerHTML = "\u2192"; - - this.screenKeysElement.appendChild(this.tabKeyElement); - this.screenKeysElement.appendChild(this.ctrlKeyElement); - this.screenKeysElement.appendChild(this.altKeyElement); - this.screenKeysElement.appendChild(this.escKeyElement); - this.screenKeysElement.appendChild(this.leftKeyElement); - this.screenKeysElement.appendChild(this.downKeyElement); - this.screenKeysElement.appendChild(this.upKeyElement); - this.screenKeysElement.appendChild(this.rightKeyElement); - - this.containerElement.appendChild(this.element); - this.containerElement.appendChild(this.inputElement); - this.containerElement.appendChild(this.screenKeysElement); - this.containerElement.appendChild(this.sizeIndicatorElement); - - parent.appendChild(this.containerElement); - - this.screenKeysElement.style.display = navigator.userAgent.match(/(iPad|iPhone|Android)/) ? "block" : "none"; - this.refresh(0, this.rows - 1); - this.bindKeys(); - this.focus(); - - // If we click somewhere other than a - // terminal, unfocus the terminal. - events.on(document, 'mousedown', function(ev) { - if (!Terminal.focus) return; - - var el = ev.target || ev.srcElement; - if (!el) return; - - do { - if (el === Terminal.focus.element) return; - } while (el = el.parentNode); - - Terminal.focus.blur(); - }); - - events.on(this.element, "mousedown", function (ev) { - var button = ev.button != null - ? +ev.button - : ev.which != null - ? ev.which - 1 - : null; - - // Does IE9 do this? - if (Terminal.isMSIE) { - button = button === 1 ? 0 : button === 4 ? 1 : button; - } - - // If user select text - if (utils.getSelection()) return; - - // Not right button - if (button !== 2) return that.focus(); - - that.element.contentEditable = true; - that.element.focus(); - setTimeout(function() { - that.inputElement.focus(); - that.element.contentEditable = 'inherit'; // 'false'; - }, 1); - }, !0); - events.on(this.inputElement, "paste", function (c) { - setTimeout(function () { - that.commitInput("", c) - }, 20) - }); - this.bindMouse(); - null == Terminal.brokenBold && (Terminal.brokenBold = utils.isBoldBroken()); - this.element.style.backgroundColor = this.colors[256]; - this.element.style.color = this.colors[257]; -}; - -Terminal.prototype.sizeToFit = function () { - if (!utils.isVisible(this.element)) return; - - var maxW = 500; - var maxH = 500; - - var a = document.createElement("div"); - a.className = "terminal"; - a.style.width = "0"; - a.style.height = "0"; - a.style.visibility = "hidden"; - - var c = document.createElement("div"); - c.style.position = "absolute"; - c.innerHTML = "W"; - - a.appendChild(c); - this.containerElement.insertBefore(a, this.element.nextSibling); - - var k = this.element.clientWidth, - f = this.element.clientHeight, - v; - for (v = 1; maxW > v && !(c.innerHTML += "W", c.offsetWidth > k); v++); - - c.innerHTML = "W"; - for (k = 1; maxH > k && !(c.innerHTML += "
      W", c.offsetHeight > f); k++); - - c.parentNode.removeChild(c); - a.parentNode.removeChild(a); - this.resize(v, k) -}; - -Terminal.prototype.bindMouse = function () { - function a(a) { - var c, k, p, y; - switch (a.type) { - case "mousedown": - c = - null != a.button ? +a.button : null != a.which ? a.which - 1 : null;~ - navigator.userAgent.indexOf("MSIE") && (c = 1 === c ? 0 : 4 === c ? 1 : c); - break; - case "mouseup": - c = 3; - break; - case "DOMMouseScroll": - c = 0 > a.detail ? 64 : 65; - break; - case "mousewheel": - c = 0 < a.wheelDeltaY ? 64 : 65 - } - p = a.shiftKey ? 4 : 0; - y = a.metaKey ? 8 : 0; - k = a.ctrlKey ? 16 : 0; - p = p | y | k; - s.vt200Mouse ? p &= k : s.normalMouse || (p = 0); - c = 32 + (p << 2) + c; - if (k = u(a)) switch (f(c, k), a.type) { - case "mousedown": - F = c; - break; - case "mouseup": - F = 32 - } - } - - function c(a) { - var k = F; - (a = u(a)) && f(k + 32, a) - } - - function y(a, c) { - s.utfMouse ? 128 > c ? a.push(c) : - (2046 < c && (c = 2046), a.push(192 | c >> 6), a.push(128 | c & 63)) : (254 < c && (c = 254), a.push(c)) - } - - function f(a, c) { - if (s.vt300Mouse) { - a &= 3; - c.x -= 32; - c.y -= 32; - var f = "\u001b[24"; - if (0 === a) f += "1"; - else if (1 === a) f += "3"; - else if (2 === a) f += "5"; - else { - if (3 === a) return; - f += "0" - } - f += "~[" + c.x + "," + c.y + "]\r"; - s.send(f) - } else s.decLocator ? (a &= 3, c.x -= 32, c.y -= 32, 0 === a ? a = 2 : 1 === a ? a = 4 : 2 === a ? a = 6 : 3 === a && (a = 3), s.send("\u001b[" + a + ";" + (3 === a ? 4 : 0) + ";" + c.y + ";" + c.x + ";" + (c.page || 0) + "&w")) : s.urxvtMouse ? (c.x -= 32, c.y -= 32, s.send("\u001b[" + a + ";" + c.x + ";" + c.y + "M")) : - s.sgrMouse ? (c.x -= 32, c.y -= 32, s.send("\u001b[<" + (3 === (a & 3) ? a & -4 : a) + ";" + c.x + ";" + c.y + (3 === (a & 3) ? "m" : "M"))) : (f = [], y(f, a), y(f, c.x), y(f, c.y), s.send("\u001b[M" + String.fromCharCode.apply(String, f))) - } - - function u(a) { - if (null != a.pageX) { - for (var c = a.pageX, f = a.target; - "terminal-row" !== f.className;) - if (f = f.parentNode, null == f) return; - for (var k = f; k !== document.documentElement;) c -= k.offsetLeft, k = k.parentNode; - c = Math.ceil(c / f.offsetWidth * s.cols); - f = parseInt(f.getAttribute("data-row") || 1, 10); - 1 > c && (c = 1); - 1 > f && (f = 1); - c > s.cols && (c = s.cols); - f > s.rows && - (f = s.rows); - return { - x: c + 32, - y: f + 32, - down: "mousedown" === a.type, - up: "mouseup" === a.type, - wheel: a.type === p, - move: "mousemove" === a.type - } - } - } - var q = this.element, - s = this, - F = 32, - p = "onmousewheel" in window ? "mousewheel" : "DOMMouseScroll"; - events.on(q, "mousedown", function (f) { - if (s.mouseEvents) { - a(f); - s.selectionMode || s.focus(); - if (s.vt200Mouse) return a({ - __proto__: f, - type: "mouseup" - }), events.cancel(f); - s.normalMouse && events.on(document, "mousemove", c); - if (!s.x10Mouse) { - var p = function (f) { - a(f); - events.off(document, "mousemove", c); - events.off(document, "mouseup", p); - events.off(document, "mousedown", p); - return cancel(f) - }; - events.on(document, "mouseup", p); - events.on(document, "mousedown", p) - } - return events.cancel(f) - } - }); - events.on(q, "mouseup", function (a) { - window.getSelection && 0 < window.getSelection().toString().length && (s.selectionMode = !0); - setTimeout(function () { - window.getSelection && 0 === window.getSelection().toString().length && (s.selectionMode = !1) - }, 0) - }); - events.on(q, "touchend", function (a) { - s.selectionMode || s.focus(); - a.stopPropagation() - }); - events.on(q, "click", function (a) { - s.selectionMode || s.focus() - }); - events.on(q, p, function (c) { - if (s.mouseEvents && !s.x10Mouse && !s.vt300Mouse && !s.decLocator) return a(c), events.cancel(c) - }); - events.on(q, p, function (a) { - if (!s.mouseEvents && !s.applicationKeypad) return "DOMMouseScroll" === a.type ? s.scrollDisp(0 > a.detail ? -5 : 5) : s.scrollDisp(0 < a.wheelDeltaY ? -5 : 5), events.cancel(a) - }) -}; - -Terminal.prototype.destroy = function () { - this.writable = this.readable = !1; - this._events = {}; - this.handler = function () {}; - this.write = function () {} -}; - -Terminal.prototype.refresh = function (a, k) { - var y, f, v, z, s, u, p, q, t, x, F, A, H, L = Terminal.focus === this; - k - a >= this.rows / 2 && (H = this.element.parentNode) && H.removeChild(this.element); - p = this.cols; - for (f = a; f <= k; f++) { - y = f + this.ydisp; - z = this.lines[y]; - s = ""; - y = f === this.y && this.cursorState && - this.ydisp === this.ybase && !this.cursorHidden ? this.x : -1; - x = this.defAttr; - for (v = 0; v < p; v++) { - q = z[v][0]; - u = z[v][1]; - v === y && (t = q, q = -1); - q !== x && (x !== this.defAttr && (s += ""), q !== this.defAttr && (s += "> 9 & 511, x = t & 511) : (F = t & 511, x = t >> 9 & 511), A = t >> 18) : (F = q & 511, x = q >> 9 & 511, A = q >> 18), s += 'style="', !L && -1 === q && (s += "outline:1px solid " + this.colors[x] + ";"), A & 1 && (Terminal.brokenBold || (s += "font-weight:bold;"), 8 > x && (x += 8)), A & 2 && (s += "text-decoration:underline;"), 256 !== F && (s += "background-color:" + - this.colors[F] + ";"), 257 !== x && (s += "color:" + this.colors[x] + ";"), s += '">')); - switch (u) { - case "&": - s += "&"; - break; - case "<": - s += "<"; - break; - case ">": - s += ">"; - break; - default: - s = " " >= u ? s + " " : s + u - } - x = q - } - x !== this.defAttr && (s += ""); - this.children[f].innerHTML = s - } - H && H.appendChild(this.element) -}; - -Terminal.prototype.redrawCursor = function () { - this.refresh(this.y, this.y) -}; - -Terminal.prototype.showCursor = function () { - this.cursorState || (this.cursorState = 1); - this.redrawCursor() -}; - -Terminal.prototype.scroll = function () { - var a; - ++this.ybase === Terminal.scrollback && - (this.ybase = this.ybase / 2 | 0, this.lines = this.lines.slice(-(this.ybase + this.rows) + 1)); - this.ydisp = this.ybase; - a = this.ybase + this.rows - 1; - a -= this.rows - 1 - this.scrollBottom; - a === this.lines.length ? this.lines.push(this.blankLine()) : this.lines.splice(a, 0, this.blankLine()); - 0 !== this.scrollTop && (0 !== this.ybase && (this.ybase--, this.ydisp = this.ybase), this.lines.splice(this.ybase + this.scrollTop, 1)); - this.updateRange(this.scrollTop); - this.updateRange(this.scrollBottom) -}; - -Terminal.prototype.scrollDisp = function (a) { - this.ydisp += a; - this.ydisp > - this.ybase ? this.ydisp = this.ybase : 0 > this.ydisp && (this.ydisp = 0); - this.refresh(0, this.rows - 1) -}; - -Terminal.prototype.write = function (a) { - var k = a.length, - y = 0, - f; - this.refreshEnd = this.refreshStart = this.y; - this.ybase !== this.ydisp && (this.ydisp = this.ybase, this.maxRange()); - for (; y < k; y++) switch (f = a[y], this.state) { - case 0: - switch (f) { - case "\u0007": - this.bell(); - break; - case "\n": - case "\x0B": - case "\f": - this.convertEol && (this.x = 0); - this.y++; - this.y > this.scrollBottom && (this.y--, this.scroll()); - break; - case "\r": - this.x = 0; - break; - case "\b": - 0 < this.x && - this.x--; - break; - case "\t": - this.x = this.nextStop(); - break; - case "\u000e": - this.setgLevel(1); - break; - case "\u000f": - this.setgLevel(0); - break; - case "\u001b": - this.state = 1; - break; - default: - " " <= f && (this.charset && this.charset[f] && (f = this.charset[f]), this.x >= this.cols && (this.x = 0, this.y++, this.y > this.scrollBottom && (this.y--, this.scroll())), this.lines[this.y + this.ybase][this.x] = [this.curAttr, f], this.x++, this.updateRange(this.y)) - } - break; - case 1: - switch (f) { - case "[": - this.params = []; - this.currentParam = 0; - this.state = 2; - break; - case "]": - this.params = []; - this.currentParam = 0; - this.state = 3; - break; - case "P": - this.params = []; - this.currentParam = 0; - this.state = 5; - break; - case "_": - this.state = 6; - break; - case "^": - this.state = 6; - break; - case "c": - this.reset(); - break; - case "E": - this.x = 0; - case "D": - this.index(); - break; - case "M": - this.reverseIndex(); - break; - case "%": - this.setgLevel(0); - this.setgCharset(0, Terminal.charsets.US); - this.state = 0; - y++; - break; - case "(": - case ")": - case "*": - case "+": - case "-": - case ".": - switch (f) { - case "(": - this.gcharset = 0; - break; - case ")": - this.gcharset = 1; - break; - case "*": - this.gcharset = - 2; - break; - case "+": - this.gcharset = 3; - break; - case "-": - this.gcharset = 1; - break; - case ".": - this.gcharset = 2 - } - this.state = 4; - break; - case "/": - this.gcharset = 3; - this.state = 4; - y--; - break; - case "N": - break; - case "O": - break; - case "n": - this.setgLevel(2); - break; - case "o": - this.setgLevel(3); - break; - case "|": - this.setgLevel(3); - break; - case "}": - this.setgLevel(2); - break; - case "~": - this.setgLevel(1); - break; - case "7": - this.saveCursor(); - this.state = 0; - break; - case "8": - this.restoreCursor(); - this.state = 0; - break; - case "#": - this.state = 0; - y++; - break; - case "H": - this.tabSet(); - break; - case "=": - this.log("Serial port requested application keypad."); - this.applicationKeypad = !0; - this.state = 0; - break; - case ">": - this.log("Switching back to normal keypad."); - this.applicationKeypad = !1; - this.state = 0; - break; - default: - this.state = 0, this.error("Unknown ESC control: %s.", f) - } - break; - case 4: - switch (f) { - case "0": - f = Terminal.charsets.SCLD; - break; - case "A": - f = Terminal.charsets.UK; - break; - case "B": - f = Terminal.charsets.US; - break; - case "4": - f = Terminal.charsets.Dutch; - break; - case "C": - case "5": - f = Terminal.charsets.Finnish; - break; - case "R": - f = Terminal.charsets.French; - break; - case "Q": - f = Terminal.charsets.FrenchCanadian; - break; - case "K": - f = Terminal.charsets.German; - break; - case "Y": - f = Terminal.charsets.Italian; - break; - case "E": - case "6": - f = Terminal.charsets.NorwegianDanish; - break; - case "Z": - f = Terminal.charsets.Spanish; - break; - case "H": - case "7": - f = Terminal.charsets.Swedish; - break; - case "=": - f = Terminal.charsets.Swiss; - break; - case "/": - f = Terminal.charsets.ISOLatin; - y++; - break; - default: - f = Terminal.charsets.US - } - this.setgCharset(this.gcharset, f); - this.gcharset = null; - this.state = 0; - break; - case 3: - if ("\u001b" === f || "\u0007" === f) { - "\u001b" === f && y++; - this.params.push(this.currentParam); - switch (this.params[0]) { - case 0: - case 1: - case 2: - this.params[1] && (this.title = this.params[1], this.handleTitle(this.title)) - } - this.params = []; - this.state = this.currentParam = 0 - } else this.params.length ? this.currentParam += f : "0" <= f && "9" >= f ? this.currentParam = 10 * this.currentParam + f.charCodeAt(0) - 48 : ";" === f && (this.params.push(this.currentParam), this.currentParam = ""); - break; - case 2: - if ("?" === f || ">" === f || "!" === f) { - this.prefix = f; - break - } - if ("0" <= f && "9" >= f) { - this.currentParam = 10 * this.currentParam + f.charCodeAt(0) - 48; - break - } - if ("$" === - f || '"' === f || " " === f || "'" === f) { - this.postfix = f; - break - } - this.params.push(this.currentParam); - this.currentParam = 0; - if (";" === f) break; - this.state = 0; - switch (f) { - case "A": - this.cursorUp(this.params); - break; - case "B": - this.cursorDown(this.params); - break; - case "C": - this.cursorForward(this.params); - break; - case "D": - this.cursorBackward(this.params); - break; - case "H": - this.cursorPos(this.params); - break; - case "J": - this.eraseInDisplay(this.params); - break; - case "K": - this.eraseInLine(this.params); - break; - case "m": - this.charAttributes(this.params); - break; - case "n": - this.deviceStatus(this.params); - break; - case "@": - this.insertChars(this.params); - break; - case "E": - this.cursorNextLine(this.params); - break; - case "F": - this.cursorPrecedingLine(this.params); - break; - case "G": - this.cursorCharAbsolute(this.params); - break; - case "L": - this.insertLines(this.params); - break; - case "M": - this.deleteLines(this.params); - break; - case "P": - this.deleteChars(this.params); - break; - case "X": - this.eraseChars(this.params); - break; - case "`": - this.charPosAbsolute(this.params); - break; - case "a": - this.HPositionRelative(this.params); - break; - case "c": - this.sendDeviceAttributes(this.params); - break; - case "d": - this.linePosAbsolute(this.params); - break; - case "e": - this.VPositionRelative(this.params); - break; - case "f": - this.HVPosition(this.params); - break; - case "h": - this.setMode(this.params); - break; - case "l": - this.resetMode(this.params); - break; - case "r": - this.setScrollRegion(this.params); - break; - case "s": - this.saveCursor(this.params); - break; - case "u": - this.restoreCursor(this.params); - break; - case "I": - this.cursorForwardTab(this.params); - break; - case "S": - this.scrollUp(this.params); - break; - case "T": - 2 > this.params.length && !this.prefix && this.scrollDown(this.params); - break; - case "Z": - this.cursorBackwardTab(this.params); - break; - case "b": - this.repeatPrecedingCharacter(this.params); - break; - case "g": - this.tabClear(this.params); - break; - case "p": - switch (this.prefix) { - case "!": - this.softReset(this.params) - } - break; - default: - this.error("Unknown CSI code: %s.", f) - } - this.postfix = this.prefix = ""; - break; - case 5: - if ("\u001b" === f || "\u0007" === f) { - "\u001b" === f && y++; - switch (this.prefix) { - case "": - break; - case "$q": - f = this.currentParam; - var v = !1; - switch (f) { - case '"q': - f = '0"q'; - break; - case '"p': - f = '61"p'; - break; - case "r": - f = "" + (this.scrollTop + 1) + ";" + (this.scrollBottom + 1) + "r"; - break; - case "m": - f = "0m"; - break; - default: - this.error("Unknown DCS Pt: %s.", f), f = "" - } - this.send("\u001bP" + +v + "$r" + f + "\u001b\\"); - break; - case "+p": - break; - case "+q": - f = this.currentParam; - v = !1; - this.send("\u001bP" + +v + "+r" + f + "\u001b\\"); - break; - default: - this.error("Unknown DCS prefix: %s.", this.prefix) - } - this.currentParam = 0; - this.prefix = ""; - this.state = 0 - } else this.currentParam ? this.currentParam += - f : !this.prefix && "$" !== f && "+" !== f ? this.currentParam = f : 2 === this.prefix.length ? this.currentParam = f : this.prefix += f; - break; - case 6: - if ("\u001b" === f || "\u0007" === f) "\u001b" === f && y++, this.state = 0 - } - this.updateRange(this.y); - this.refresh(this.refreshStart, this.refreshEnd) -}; - -Terminal.prototype.writeln = function (a) { - this.write(a + "\r\n") -}; - -Terminal.prototype.keyDown = function (a) { - a = this.applyVirtualKey(a); - var c = this, - k = null; - switch (a.keyCode) { - - // backspace - case 8: - if (a.shiftKey) { - k = "\b"; - break - } else if (a.altKey) { - // Deletes previous word - k = '\x17'; - break; - } - k = "\u007f"; - break; - - // tab - case 9: - if (a.shiftKey) { - k = "\u001b[Z"; - break - } - k = - "\t"; - break; - - // return/enter - case 13: - k = "\r"; - break; - - // escape - case 27: - k = "\u001b"; - break; - - // left-arrow - case 37: - if (this.applicationCursor) { - k = "\u001bOD"; - break - } else if(a.altKey) { - k = '\x1bb'; - break - } - k = "\u001b[D"; - break; - - // right-arrow - case 39: - if (this.applicationCursor) { - k = "\u001bOC"; - break - } else if(a.altKey) { - k = '\x1bf'; - break - } - k = "\u001b[C"; - break; - - // up-arrow - case 38: - if (this.applicationCursor) { - k = "\u001bOA"; - break - } - if (a.ctrlKey) return this.scrollDisp(-1), t(a); - k = "\u001b[A"; - break; - - // down-arrow - case 40: - if (this.applicationCursor) { - k = "\u001bOB"; - break - } - if (a.ctrlKey) return this.scrollDisp(1), t(a); - k = "\u001b[B"; - break; - - // delete - case 46: - k = "\u001b[3~"; - break; - - // insert - case 45: - k = "\u001b[2~"; - break; - - // home - case 36: - if (this.applicationKeypad) { - k = - "\u001bOH"; - break - } - k = "\u001bOH"; - break; - - // end - case 35: - if (this.applicationKeypad) { - k = "\u001bOF"; - break - } - k = "\u001bOF"; - break; - - // page up - case 33: - if (a.shiftKey) return this.scrollDisp(-(this.rows - 1)), events.cancel(a); - k = "\u001b[5~"; - break; - - // page down - case 34: - if (a.shiftKey) return this.scrollDisp(this.rows - 1), events.cancel(a); - k = "\u001b[6~"; - break; - - // F1 - case 112: - k = "\u001bOP"; - break; - - // F2 - case 113: - k = "\u001bOQ"; - break; - - // F3 - case 114: - k = "\u001bOR"; - break; - - // F4 - case 115: - k = "\u001bOS"; - break; - - // F5 - case 116: - k = "\u001b[15~"; - break; - - // F6 - case 117: - k = "\u001b[17~"; - break; - - // F7 - case 118: - k = "\u001b[18~"; - break; - - // F8 - case 119: - k = "\u001b[19~"; - break; - - // F9 - case 120: - k = "\u001b[20~"; - break; - - // F10 - case 121: - k = "\u001b[21~"; - break; - - // F11 - case 122: - k = "\u001b[23~"; - break; - - // F12 - case 123: - k = "\u001b[24~"; - break; - default: - if (a.ctrlKey && !a.altKey)!Terminal.isMac && a.shiftKey && 86 === a.keyCode ? (k = "", setTimeout(function () { - c.commitInput("", a) - }, 20)) : 65 <= a.keyCode && 90 >= a.keyCode ? k = String.fromCharCode(a.keyCode - 64) : 32 === a.keyCode ? k = String.fromCharCode(0) : 51 <= a.keyCode && 55 >= a.keyCode ? k = String.fromCharCode(a.keyCode - 51 + 27) : 56 === a.keyCode ? k = String.fromCharCode(127) : 219 === a.keyCode ? k = String.fromCharCode(27) : 221 === a.keyCode && (k = String.fromCharCode(29)); - else if (Terminal.isMac && a.metaKey && 86 === a.keyCode) k = "", setTimeout(function () { - c.commitInput("", a) - }, 20); - else if (!a.ctrlKey && (!Terminal.isMac && a.altKey || Terminal.isMac && a.metaKey)) 65 <= a.keyCode && 90 >= a.keyCode ? k = "\u001b" + String.fromCharCode(a.keyCode + 32) : 192 === a.keyCode ? k = "\u001b`" : 48 <= a.keyCode && 57 >= a.keyCode && (k = "\u001b" + (a.keyCode - 48)) - } - if (k) return this.commitInput(k, a), events.cancel(a); - "" !== k && this.showBufferedText(); - return !0 -}; - -Terminal.prototype.showBufferedText = function () { - var a = this.inputElement; - setTimeout(function () { - 0 < a.value.length && -1 === a.className.indexOf(" visible") && - (a.className += " visible") - }, 0) -}; - -Terminal.prototype.commitInput = function (a, c) { - var k = this.inputElement.value; - 0 < k.length && (a = k + a, this.inputElement.value = "", this.inputElement.className = this.inputElement.className.replace(" visible", "")); - this.emit("key", a, c); - this.showCursor(); - this.handler(a) -}; - -Terminal.prototype.setgLevel = function (a) { - this.glevel = a; - this.charset = this.charsets[a] -}; - -Terminal.prototype.setgCharset = function (a, c) { - this.charsets[a] = c; - this.glevel === a && (this.charset = c) -}; - -Terminal.prototype.keyPress = function (a) { - a = this.applyVirtualKey(a); - var c; - if (a.metaKey && 118 === a.charCode) return !1; - events.cancel(a); - if (a.charCode) c = a.charCode; - else if (null == a.which) c = a.keyCode; - else if (0 !== a.which && 0 !== a.charCode) c = a.which; - else return !1; if (c && !a.ctrlKey || c && a.altKey && a.ctrlKey || c && a.altKey || c && a.altGraphKey) c = String.fromCharCode(c), this.commitInput(c, a); - return !1 -}; - -Terminal.prototype.send = function (a) { - var that = this; - this.queue || setTimeout(function () { - that.handler(Terminal.queue); - Terminal.queue = "" - }, 1); - this.queue += a; -}; - -Terminal.prototype.bell = function () { - if (Terminal.visualBell) { - var a = this; - this.element.style.borderColor = "white"; - setTimeout(function () { - a.element.style.borderColor = "" - }, 10); - Terminal.popOnBell && this.focus() - } -}; - -Terminal.prototype.log = function () { - if (Terminal.debug && console && console.log) { - var a = Array.prototype.slice.call(arguments); - console.log.apply(console, a) - } -}; - -Terminal.prototype.error = function () { - if (Terminal.debug && console && console.error) { - var a = Array.prototype.slice.call(arguments); - console.error.apply(console, a) - } -}; - -Terminal.prototype.resize = function (a, c) { - var k, f, v; - 1 > a && (a = 1); - 1 > c && (c = 1); - v = this.cols; - if (v < a) { - f = [this.defAttr, " "]; - for (k = this.lines.length; k--;) - for (; this.lines[k].length < - a;) this.lines[k].push(f) - } else if (v > a) - for (k = this.lines.length; k--;) - for (; this.lines[k].length > a;) this.lines[k].pop(); - this.setupStops(v); - this.cols = a; - v = this.rows; - if (v < c) - for (f = this.element; v++ < c;) this.lines.length < c + this.ybase && this.lines.push(this.blankLine()), this.children.length < c && (k = document.createElement("div"), k.className = "terminal-row", k.setAttribute("data-row", v.toString()), f.appendChild(k), this.children.push(k)); - else if (v > c) - for (; v-- > c;) this.lines.length > c + this.ybase && this.lines.shift(), this.children.length > - c && (f = this.children.pop()) && f.parentNode.removeChild(f); - this.rows = c; - this.y >= c && (this.y = c - 1); - this.x >= a && (this.x = a - 1); - this.scrollTop = 0; - this.scrollBottom = c - 1; - this.refresh(0, this.rows - 1); - this.normal = null; - this.showSize(a, c); - this.emit("resize", a, c) -}; - -Terminal.prototype.showSize = function (a, c) { - var k = this.sizeIndicatorElement; - k.innerHTML = a + "x" + c; - k.style.display = "block"; - void 0 != this.showSizeTimeout && clearTimeout(this.showSizeTimeout); - this.showSizeTimeout = setTimeout(function () { - k.style.display = "none" - }, 2E3) -}; - -Terminal.prototype.updateRange = - function (a) { - a < this.refreshStart && (this.refreshStart = a); - a > this.refreshEnd && (this.refreshEnd = a) -}; - -Terminal.prototype.maxRange = function () { - this.refreshStart = 0; - this.refreshEnd = this.rows - 1 -}; - -Terminal.prototype.setupStops = function (a) { - null != a ? this.tabs[a] || (a = this.prevStop(a)) : (this.tabs = {}, a = 0); - for (; a < this.cols; a += 8) this.tabs[a] = !0 -}; - -Terminal.prototype.prevStop = function (a) { - null == a && (a = this.x); - for (; !this.tabs[--a] && 0 < a;); - return a >= this.cols ? this.cols - 1 : 0 > a ? 0 : a -}; - -Terminal.prototype.nextStop = function (a) { - null == a && (a = this.x); - for (; !this.tabs[++a] && - a < this.cols;); - return a >= this.cols ? this.cols - 1 : 0 > a ? 0 : a -}; - -Terminal.prototype.eraseRight = function (a, c) { - for (var k = this.lines[this.ybase + c], f = [this.curAttr, " "]; a < this.cols; a++) k[a] = f; - this.updateRange(c) -}; - -Terminal.prototype.eraseLeft = function (a, c) { - var k = this.lines[this.ybase + c], - f = [this.curAttr, " "]; - for (a++; a--;) k[a] = f; - this.updateRange(c) -}; - -Terminal.prototype.eraseLine = function (a) { - this.eraseRight(0, a) -}; - -Terminal.prototype.blankLine = function (a) { - a = [a ? this.curAttr : this.defAttr, " "]; - for (var c = [], k = 0; k < this.cols; k++) c[k] = a; - return c -}; - -Terminal.prototype.ch = - function (a) { - return a ? [this.curAttr, " "] : [this.defAttr, " "] -}; - -Terminal.prototype.is = function (a) { - return 0 === ((this.termName || Terminal.termName) + "").indexOf(a) -}; - -Terminal.prototype.handler = function (a) { - this.emit("data", a) -}; - -Terminal.prototype.handleTitle = function (a) { - this.emit("title", a) -}; - -Terminal.prototype.index = function () { - this.y++; - this.y > this.scrollBottom && (this.y--, this.scroll()); - this.state = 0 -}; - -Terminal.prototype.reverseIndex = function () { - var a; - this.y--; - this.y < this.scrollTop && (this.y++, this.lines.splice(this.y + this.ybase, 0, this.blankLine(!0)), a = - this.rows - 1 - this.scrollBottom, this.lines.splice(this.rows - 1 + this.ybase - a + 1, 1), this.updateRange(this.scrollTop), this.updateRange(this.scrollBottom)); - this.state = 0 -}; - -Terminal.prototype.reset = function () { - Terminal.call(this, this.cols, this.rows); - this.refresh(0, this.rows - 1) -}; - -Terminal.prototype.tabSet = function () { - this.tabs[this.x] = !0; - this.state = 0 -}; - -Terminal.prototype.cursorUp = function (a) { - a = a[0]; - 1 > a && (a = 1); - this.y -= a; - 0 > this.y && (this.y = 0) -}; - -Terminal.prototype.cursorDown = function (a) { - a = a[0]; - 1 > a && (a = 1); - this.y += a; - this.y >= this.rows && (this.y = this.rows - - 1) -}; - -Terminal.prototype.cursorForward = function (a) { - a = a[0]; - 1 > a && (a = 1); - this.x += a; - this.x >= this.cols && (this.x = this.cols - 1) -}; - -Terminal.prototype.cursorBackward = function (a) { - a = a[0]; - 1 > a && (a = 1); - this.x -= a; - 0 > this.x && (this.x = 0) -}; - -Terminal.prototype.cursorPos = function (a) { - var c; - c = a[0] - 1; - a = 2 <= a.length ? a[1] - 1 : 0; - 0 > c ? c = 0 : c >= this.rows && (c = this.rows - 1); - 0 > a ? a = 0 : a >= this.cols && (a = this.cols - 1); - this.x = a; - this.y = c -}; - -Terminal.prototype.eraseInDisplay = function (a) { - switch (a[0]) { - case 0: - this.eraseRight(this.x, this.y); - for (a = this.y + 1; a < this.rows; a++) this.eraseLine(a); - break; - case 1: - this.eraseLeft(this.x, this.y); - for (a = this.y; a--;) this.eraseLine(a); - break; - case 2: - for (a = this.rows; a--;) this.eraseLine(a) - } -}; - -Terminal.prototype.eraseInLine = function (a) { - switch (a[0]) { - case 0: - this.eraseRight(this.x, this.y); - break; - case 1: - this.eraseLeft(this.x, this.y); - break; - case 2: - this.eraseLine(this.y) - } -}; - -Terminal.prototype.charAttributes = function (a) { - for (var c = a.length, k = 0, f, v; k < c; k++) - if (f = a[k], 30 <= f && 37 >= f) this.curAttr = this.curAttr & -261633 | f - 30 << 9; - else if (40 <= f && 47 >= f) this.curAttr = this.curAttr & -512 | f - 40; - else if (90 <= - f && 97 >= f) f += 8, this.curAttr = this.curAttr & -261633 | f - 90 << 9; - else if (100 <= f && 107 >= f) f += 8, this.curAttr = this.curAttr & -512 | f - 100; - else if (0 === f) this.curAttr = this.defAttr; - else if (1 === f) this.curAttr |= 262144; - else if (4 === f) this.curAttr |= 524288; - else if (7 === f || 27 === f) { - if (7 === f) { - if (this.curAttr >> 18 & 4) continue; - this.curAttr |= 1048576 - } else if (27 === f) { - if (~(this.curAttr >> 18) & 4) continue; - this.curAttr &= -1048577 - } - f = this.curAttr & 511; - v = this.curAttr >> 9 & 511; - this.curAttr = this.curAttr & -262144 | f << 9 | v - } else 22 === f ? this.curAttr &= -262145 : - 24 === f ? this.curAttr &= -524289 : 39 === f ? (this.curAttr &= -261633, this.curAttr |= (this.defAttr >> 9 & 511) << 9) : 49 === f ? (this.curAttr &= -512, this.curAttr |= this.defAttr & 511) : 38 === f ? 5 === a[k + 1] && (k += 2, f = a[k] & 255, this.curAttr = this.curAttr & -261633 | f << 9) : 48 === f && 5 === a[k + 1] && (k += 2, f = a[k] & 255, this.curAttr = this.curAttr & -512 | f) -}; - -Terminal.prototype.deviceStatus = function (a) { - if (this.prefix) { - if ("?" === this.prefix) switch (a[0]) { - case 6: - this.send("\u001b[?" + (this.y + 1) + ";" + (this.x + 1) + "R") - } - } else switch (a[0]) { - case 5: - this.send("\u001b[0n"); - break; - case 6: - this.send("\u001b[" + (this.y + 1) + ";" + (this.x + 1) + "R") - } -}; - -Terminal.prototype.insertChars = function (a) { - var c, k, f; - a = a[0]; - 1 > a && (a = 1); - c = this.y + this.ybase; - k = this.x; - for (f = [this.curAttr, " "]; a-- && k < this.cols;) this.lines[c].splice(k++, 0, f), this.lines[c].pop() -}; - -Terminal.prototype.cursorNextLine = function (a) { - a = a[0]; - 1 > a && (a = 1); - this.y += a; - this.y >= this.rows && (this.y = this.rows - 1); - this.x = 0 -}; - -Terminal.prototype.cursorPrecedingLine = function (a) { - a = a[0]; - 1 > a && (a = 1); - this.y -= a; - 0 > this.y && (this.y = 0); - this.x = 0 -}; - -Terminal.prototype.cursorCharAbsolute = - function (a) { - a = a[0]; - 1 > a && (a = 1); - this.x = a - 1 -}; - -Terminal.prototype.insertLines = function (a) { - var c, k; - a = a[0]; - 1 > a && (a = 1); - c = this.y + this.ybase; - k = this.rows - 1 - this.scrollBottom; - for (k = this.rows - 1 + this.ybase - k + 1; a--;) this.lines.splice(c, 0, this.blankLine(!0)), this.lines.splice(k, 1); - this.updateRange(this.y); - this.updateRange(this.scrollBottom) -}; - -Terminal.prototype.deleteLines = function (a) { - var c, k; - a = a[0]; - 1 > a && (a = 1); - c = this.y + this.ybase; - k = this.rows - 1 - this.scrollBottom; - for (k = this.rows - 1 + this.ybase - k; a--;) this.lines.splice(k + 1, 0, this.blankLine(!0)), - this.lines.splice(c, 1); - this.updateRange(this.y); - this.updateRange(this.scrollBottom) -}; - -Terminal.prototype.deleteChars = function (a) { - var c, k; - a = a[0]; - 1 > a && (a = 1); - c = this.y + this.ybase; - for (k = [this.curAttr, " "]; a--;) this.lines[c].splice(this.x, 1), this.lines[c].push(k) -}; - -Terminal.prototype.eraseChars = function (a) { - var c, k, f; - a = a[0]; - 1 > a && (a = 1); - c = this.y + this.ybase; - k = this.x; - for (f = [this.curAttr, " "]; a-- && k < this.cols;) this.lines[c][k++] = f -}; - -Terminal.prototype.charPosAbsolute = function (a) { - a = a[0]; - 1 > a && (a = 1); - this.x = a - 1; - this.x >= this.cols && (this.x = - this.cols - 1) -}; - -Terminal.prototype.HPositionRelative = function (a) { - a = a[0]; - 1 > a && (a = 1); - this.x += a; - this.x >= this.cols && (this.x = this.cols - 1) -}; - -Terminal.prototype.sendDeviceAttributes = function (a) { - 0 < a[0] || (this.prefix ? ">" === this.prefix && (this.is("xterm") ? this.send("\u001b[>0;276;0c") : this.is("rxvt-unicode") ? this.send("\u001b[>85;95;0c") : this.is("linux") ? this.send(a[0] + "c") : this.is("screen") && this.send("\u001b[>83;40003;0c")) : this.is("xterm") || this.is("rxvt-unicode") || this.is("screen") ? this.send("\u001b[?1;2c") : this.is("linux") && - this.send("\u001b[?6c")) -}; - -Terminal.prototype.linePosAbsolute = function (a) { - a = a[0]; - 1 > a && (a = 1); - this.y = a - 1; - this.y >= this.rows && (this.y = this.rows - 1) -}; - -Terminal.prototype.VPositionRelative = function (a) { - a = a[0]; - 1 > a && (a = 1); - this.y += a; - this.y >= this.rows && (this.y = this.rows - 1) -}; - -Terminal.prototype.HVPosition = function (a) { - 1 > a[0] && (a[0] = 1); - 1 > a[1] && (a[1] = 1); - this.y = a[0] - 1; - this.y >= this.rows && (this.y = this.rows - 1); - this.x = a[1] - 1; - this.x >= this.cols && (this.x = this.cols - 1) -}; - -Terminal.prototype.setMode = function (a) { - if ("object" === typeof a) - for (var k = a.length, v = - 0; v < k; v++) this.setMode(a[v]); - else if (this.prefix) { - if ("?" === this.prefix) switch (a) { - case 1: - this.applicationCursor = !0; - break; - case 2: - this.setgCharset(0, Terminal.charsets.US); - this.setgCharset(1, Terminal.charsets.US); - this.setgCharset(2, Terminal.charsets.US); - this.setgCharset(3, Terminal.charsets.US); - break; - case 3: - this.savedCols = this.cols; - this.resize(132, this.rows); - break; - case 6: - this.originMode = !0; - break; - case 7: - this.wraparoundMode = !0; - break; - case 9: - case 1E3: - case 1002: - case 1003: - this.x10Mouse = 9 === a; - this.vt200Mouse = 1E3 === a; - this.normalMouse = 1E3 < - a; - this.mouseEvents = !0; - this.element.style.cursor = "default"; - this.log("Binding to mouse events."); - break; - case 1004: - this.sendFocus = !0; - break; - case 1005: - this.utfMouse = !0; - break; - case 1006: - this.sgrMouse = !0; - break; - case 1015: - this.urxvtMouse = !0; - break; - case 25: - this.cursorHidden = !1; - break; - case 1049: - case 47: - case 1047: - this.normal || (a = { - lines: this.lines, - ybase: this.ybase, - ydisp: this.ydisp, - x: this.x, - y: this.y, - scrollTop: this.scrollTop, - scrollBottom: this.scrollBottom, - tabs: this.tabs - }, this.reset(), this.normal = a, this.showCursor()) - } - } else switch (a) { - case 4: - this.insertMode = !0 - } -}; - -Terminal.prototype.resetMode = function (a) { - if ("object" === typeof a) - for (var c = a.length, k = 0; k < c; k++) this.resetMode(a[k]); - else if (this.prefix) { - if ("?" === this.prefix) switch (a) { - case 1: - this.applicationCursor = !1; - break; - case 3: - 132 === this.cols && this.savedCols && this.resize(this.savedCols, this.rows); - delete this.savedCols; - break; - case 6: - this.originMode = !1; - break; - case 7: - this.wraparoundMode = !1; - break; - case 9: - case 1E3: - case 1002: - case 1003: - this.mouseEvents = this.normalMouse = this.vt200Mouse = this.x10Mouse = !1; - this.element.style.cursor = - ""; - break; - case 1004: - this.sendFocus = !1; - break; - case 1005: - this.utfMouse = !1; - break; - case 1006: - this.sgrMouse = !1; - break; - case 1015: - this.urxvtMouse = !1; - break; - case 25: - this.cursorHidden = !0; - break; - case 1049: - case 47: - case 1047: - this.normal && (this.lines = this.normal.lines, this.ybase = this.normal.ybase, this.ydisp = this.normal.ydisp, this.x = this.normal.x, this.y = this.normal.y, this.scrollTop = this.normal.scrollTop, this.scrollBottom = this.normal.scrollBottom, this.tabs = this.normal.tabs, this.normal = null, this.refresh(0, this.rows - 1), - this.showCursor()) - } - } else switch (a) { - case 4: - this.insertMode = !1 - } -}; - -Terminal.prototype.setScrollRegion = function (a) { - this.prefix || (this.scrollTop = (a[0] || 1) - 1, this.scrollBottom = (a[1] || this.rows) - 1, this.y = this.x = 0) -}; - -Terminal.prototype.saveCursor = function (a) { - this.savedX = this.x; - this.savedY = this.y -}; - -Terminal.prototype.restoreCursor = function (a) { - this.x = this.savedX || 0; - this.y = this.savedY || 0 -}; - -Terminal.prototype.cursorForwardTab = function (a) { - for (a = a[0] || 1; a--;) this.x = this.nextStop() -}; - -Terminal.prototype.scrollUp = function (a) { - for (a = a[0] || 1; a--;) this.lines.splice(this.ybase + - this.scrollTop, 1), this.lines.splice(this.ybase + this.scrollBottom, 0, this.blankLine()); - this.updateRange(this.scrollTop); - this.updateRange(this.scrollBottom) -}; - -Terminal.prototype.scrollDown = function (a) { - for (a = a[0] || 1; a--;) this.lines.splice(this.ybase + this.scrollBottom, 1), this.lines.splice(this.ybase + this.scrollTop, 0, this.blankLine()); - this.updateRange(this.scrollTop); - this.updateRange(this.scrollBottom) -}; - -Terminal.prototype.initMouseTracking = function (a) {}; -Terminal.prototype.resetTitleModes = function (a) {}; - -Terminal.prototype.cursorBackwardTab = - function (a) { - for (a = a[0] || 1; a--;) this.x = this.prevStop() -}; - -Terminal.prototype.repeatPrecedingCharacter = function (a) { - a = a[0] || 1; - for (var c = this.lines[this.ybase + this.y], k = c[this.x - 1] || [this.defAttr, " "]; a--;) c[this.x++] = k -}; - -Terminal.prototype.tabClear = function (a) { - a = a[0]; - 0 >= a ? delete this.tabs[this.x] : 3 === a && (this.tabs = {}) -}; - -Terminal.prototype.mediaCopy = function (a) {}; -Terminal.prototype.setResources = function (a) {}; -Terminal.prototype.disableModifiers = function (a) {}; -Terminal.prototype.setPointerMode = function (a) {}; - -Terminal.prototype.softReset = function (a) { - this.applicationCursor = - this.applicationKeypad = this.wraparoundMode = this.originMode = this.insertMode = this.cursorHidden = !1; - this.scrollTop = 0; - this.scrollBottom = this.rows - 1; - this.curAttr = this.defAttr; - this.x = this.y = 0; - this.charset = null; - this.glevel = 0; - this.charsets = [null] -}; - -Terminal.prototype.requestAnsiMode = function (a) {}; -Terminal.prototype.requestPrivateMode = function (a) {}; -Terminal.prototype.setConformanceLevel = function (a) {}; -Terminal.prototype.loadLEDs = function (a) {}; -Terminal.prototype.setCursorStyle = function (a) {}; -Terminal.prototype.setCharProtectionAttr = function (a) {}; -Terminal.prototype.restorePrivateValues = function (a) {}; - -Terminal.prototype.setAttrInRectangle = function (a) { - for (var c = a[0], k = a[1], f = a[2], v = a[3], s = a[4], z, u; c < f + 1; c++) { - z = this.lines[this.ybase + c]; - for (u = k; u < v; u++) z[u] = [s, z[u][1]] - } - this.updateRange(a[0]); - this.updateRange(a[2]) -}; - -Terminal.prototype.savePrivateValues = function (a) {}; -Terminal.prototype.manipulateWindow = function (a) {}; -Terminal.prototype.reverseAttrInRectangle = function (a) {}; -Terminal.prototype.setTitleModeFeature = function (a) {}; -Terminal.prototype.setWarningBellVolume = function (a) {}; -Terminal.prototype.setMarginBellVolume = function (a) {}; -Terminal.prototype.copyRectangle = function (a) {}; -Terminal.prototype.enableFilterRectangle = function (a) {}; -Terminal.prototype.requestParameters = function (a) {}; -Terminal.prototype.selectChangeExtent = function (a) {}; - -Terminal.prototype.fillRectangle = function (a) { - for (var c = a[0], k = a[1], f = a[2], v = a[3], s = a[4], z, u; k < v + 1; k++) { - z = this.lines[this.ybase + k]; - for (u = f; u < s; u++) z[u] = [z[u][0], String.fromCharCode(c)] - } - this.updateRange(a[1]); - this.updateRange(a[3]) -}; - -Terminal.prototype.enableLocatorReporting = function (a) {}; -Terminal.prototype.eraseRectangle = function (a) { - var c = a[0], - k = a[1], - f = a[2], - v = a[3], - s, z, u; - for (u = [this.curAttr, " "]; c < f + 1; c++) { - s = this.lines[this.ybase + c]; - for (z = k; z < v; z++) s[z] = u - } - this.updateRange(a[0]); - this.updateRange(a[2]) -}; - -Terminal.prototype.setLocatorEvents = function (a) {}; -Terminal.prototype.selectiveEraseRectangle = function (a) {}; -Terminal.prototype.requestLocatorPosition = function (a) {}; - -Terminal.prototype.insertColumns = function () { - for (var a = params[0], c = this.ybase + this.rows, k = [this.curAttr, " "], f; a--;) - for (f = this.ybase; f < c; f++) this.lines[f].splice(this.x + 1, 0, k), this.lines[f].pop(); - this.maxRange() -}; - -Terminal.prototype.deleteColumns = function () { - for (var a = - params[0], c = this.ybase + this.rows, k = [this.curAttr, " "], f; a--;) - for (f = this.ybase; f < c; f++) this.lines[f].splice(this.x, 1), this.lines[f].push(k); - this.maxRange() -}; - -Terminal.charsets = charsets; - -Terminal.isMac = ~navigator.userAgent.indexOf("Mac"); -Terminal.isMSIE = ~navigator.userAgent.indexOf("MSIE"); - -Terminal.themes = themes; - - -module.exports = Terminal; -},{"./charsets":1,"./events":2,"./themes":4,"./utils":5}],4:[function(_dereq_,module,exports){ - -var initColors = function (colors) { - function a(a, c, f) { - y.push("#" + k(a) + k(c) + k(f)) - } - - function k(a) { - a = a.toString(16); - return 2 > a.length ? "0" + a : a - } - var y = colors, - f = [0, 95, 135, 175, 215, 255], - v; - for (v = 0; 216 > v; v++) a(f[v / 36 % 6 | 0], f[v / 6 % 6 | 0], f[v % 6]); - for (v = 0; 24 > v; v++) f = 8 + 10 * v, a(f, f, f); - return y -}; - -// Return colors for a theme -var colors = function(theme) { - // Copy pallette - var colors = theme.palette.slice(0); - - // Set background and forground colors if available - colors[256] = theme.background || "#000000"; - colors[257] = theme.foreground || "#f0f0f0"; - - return initColors(colors); -}; - -var defaults = { - "default":{ - "palette": [ - "#000000", - "#c81908", - "#00c01d", - "#c8c221", - "#0033c5", - "#c73ac5", - "#00c6c7", - "#c7c7c7", - "#686868", - "#8a8a8a", - "#67f86e", - "#fff970", - "#6678fc", - "#ff7cfd", - "#65fdff", - "#ffffff" - ] - }, - "blazer":{ - "palette":[ - "#262626", - "#dbbdbd", - "#bddbbd", - "#dbdbbd", - "#bdbddb", - "#dbbddb", - "#bddbdb", - "#ffffff" - ], - "name":"blazer" - }, - "chalkboard":{ - "foreground":"#d9e6f2", - "background":"#29262f", - "cursor":"#d9e6f2", - "cursor_text":"#29262f", - "palette":[ - "#000000", - "#c37372", - "#72c373", - "#c2c372", - "#7372c3", - "#c372c2", - "#72c2c3", - "#d9d9d9", - "#323232", - "#dbaaaa", - "#aadbaa", - "#dadbaa", - "#aaaadb", - "#dbaada", - "#aadadb", - "#ffffff" - ], - "name":"chalkboard" - }, - "dark_pastel":{ - "foreground":"#ffffff", - "background":"#000000", - "cursor":"#bbbbbb", - "cursor_text":"#ffffff", - "palette":[ - "#000000", - "#ff5555", - "#55ff55", - "#ffff55", - "#5555ff", - "#ff55ff", - "#55ffff", - "#bbbbbb", - "#555555", - "#ff5555", - "#55ff55", - "#ffff55", - "#5555ff", - "#ff55ff", - "#55ffff", - "#ffffff" - ], - "name":"dark_pastel" - }, - "desert":{ - "foreground":"#ffffff", - "background":"#333333", - "cursor":"#00ff00", - "cursor_text":"#000000", - "palette":[ - "#4d4d4d", - "#ff2b2b", - "#98fb98", - "#f0e68c", - "#cd853f", - "#ffdead", - "#ffa0a0", - "#f5deb3", - "#555555", - "#ff5555", - "#55ff55", - "#ffff55", - "#87ceff", - "#ff55ff", - "#ffd700", - "#ffffff" - ], - "name":"desert" - }, - "espresso":{ - "foreground":"#ffffff", - "background":"#323232", - "cursor":"#d6d6d6", - "cursor_text":"#ffffff", - "palette":[ - "#343434", - "#d25151", - "#a5c261", - "#ffc66d", - "#6c99bb", - "#d197d9", - "#bed6ff", - "#eeeeec", - "#535353", - "#f00c0c", - "#c2e075", - "#e1e38b", - "#8ab7d9", - "#efb5f7", - "#dcf3ff", - "#ffffff" - ], - "name":"espresso" - }, - "github":{ - "foreground":"#3e3e3e", - "background":"#f4f4f4", - "cursor":"#3f3f3f", - "cursor_text":"#f4f4f4", - "palette":[ - "#3e3e3e", - "#970b16", - "#07962a", - "#f8eec7", - "#003e8a", - "#e94691", - "#89d1ec", - "#ffffff", - "#666666", - "#de0000", - "#87d5a2", - "#f1d007", - "#2e6cba", - "#ffa29f", - "#1cfafe", - "#ffffff" - ], - "name":"github" - }, - "grass":{ - "foreground":"#fff0a5", - "background":"#13773c", - "cursor":"#8c2800", - "cursor_text":"#ffffff", - "palette":[ - "#000000", - "#bb0000", - "#00bb00", - "#e7b000", - "#0000a3", - "#950061", - "#00bbbb", - "#bbbbbb", - "#555555", - "#bb0000", - "#00bb00", - "#e7b000", - "#0000bb", - "#ff55ff", - "#55ffff", - "#ffffff" - ], - "name":"grass" - }, - "homebrew":{ - "foreground":"#00ff00", - "background":"#000000", - "cursor":"#23ff18", - "cursor_text":"#ff0017", - "palette":[ - "#000000", - "#990000", - "#00a600", - "#999900", - "#0000b2", - "#b200b2", - "#00a6b2", - "#bfbfbf", - "#666666", - "#e50000", - "#00d900", - "#e5e500", - "#0000ff", - "#e500e5", - "#00e5e5", - "#e5e5e5" - ], - "name":"homebrew" - }, - "hurtado":{ - "foreground":"#dadbda", - "background":"#000000", - "cursor":"#bbbbbb", - "cursor_text":"#ffffff", - "palette":[ - "#575757", - "#ff1b00", - "#a5df55", - "#fbe74a", - "#486387", - "#fc5ef0", - "#85e9fe", - "#cbcbcb", - "#252525", - "#d41c00", - "#a5df55", - "#fbe749", - "#89bdff", - "#bf00c0", - "#85e9fe", - "#dbdbdb" - ], - "name":"hurtado" - }, - "idletoes":{ - "foreground":"#ffffff", - "background":"#323232", - "cursor":"#d6d6d6", - "cursor_text":"#000000", - "palette":[ - "#323232", - "#d25252", - "#7fe173", - "#ffc66d", - "#4098ff", - "#f57fff", - "#bed6ff", - "#eeeeec", - "#535353", - "#f07070", - "#9dff90", - "#ffe48b", - "#5eb7f7", - "#ff9dff", - "#dcf4ff", - "#ffffff" - ], - "name":"idletoes" - }, - "kibble":{ - "foreground":"#f7f7f7", - "background":"#0e100a", - "cursor":"#9fda9c", - "cursor_text":"#000000", - "palette":[ - "#4d4d4d", - "#c70031", - "#29cf13", - "#d8e30e", - "#3449d1", - "#8400ff", - "#0798ab", - "#e2d1e3", - "#5a5a5a", - "#f01578", - "#6ce05c", - "#f3f79e", - "#97a4f7", - "#c495f0", - "#68f2e0", - "#ffffff" - ], - "name":"kibble" - }, - "man_page":{ - "foreground":"#000000", - "background":"#fef49c", - "cursor":"#7f7f7f", - "cursor_text":"#000000", - "palette":[ - "#000000", - "#cc0000", - "#00a600", - "#999900", - "#0000b2", - "#b200b2", - "#00a6b2", - "#cccccc", - "#666666", - "#e50000", - "#00d900", - "#e5e500", - "#0000ff", - "#e500e5", - "#00e5e5", - "#e5e5e5" - ], - "name":"man_page" - }, - "monokai_soda":{ - "foreground":"#c4c4b5", - "background":"#191919", - "cursor":"#f6f6ec", - "cursor_text":"#c4c4b5", - "palette":[ - "#191919", - "#f3005f", - "#97e023", - "#fa8419", - "#9c64fe", - "#f3005f", - "#57d1ea", - "#c4c4b5", - "#615e4b", - "#f3005f", - "#97e023", - "#dfd561", - "#9c64fe", - "#f3005f", - "#57d1ea", - "#f6f6ee" - ], - "name":"monokai_soda" - }, - "neopolitan":{ - "foreground":"#ffffff", - "background":"#17130f", - "cursor":"#ffffff", - "cursor_text":"#ffffff", - "palette":[ - "#17130f", - "#800000", - "#61ce3c", - "#fbde2d", - "#253b76", - "#ff0080", - "#8da6ce", - "#f8f8f8", - "#17130f", - "#800000", - "#61ce3c", - "#fbde2d", - "#253b76", - "#ff0080", - "#8da6ce", - "#f8f8f8" - ], - "name":"neopolitan" - }, - "novel":{ - "foreground":"#3b2322", - "background":"#dfdbc3", - "cursor":"#73635a", - "cursor_text":"#000000", - "palette":[ - "#000000", - "#cc0000", - "#009600", - "#d06b00", - "#0000cc", - "#cc00cc", - "#0087cc", - "#cccccc", - "#7f7f7f", - "#cc0000", - "#009600", - "#d06b00", - "#0000cc", - "#cc00cc", - "#0086cb", - "#ffffff" - ], - "name":"novel" - }, - "ocean":{ - "foreground":"#ffffff", - "background":"#224fbc", - "cursor":"#7f7f7f", - "cursor_text":"#ffffff", - "palette":[ - "#000000", - "#990000", - "#00a600", - "#999900", - "#0000b2", - "#b200b2", - "#00a6b2", - "#bfbfbf", - "#666666", - "#e50000", - "#00d900", - "#e5e500", - "#0000ff", - "#e500e5", - "#00e5e5", - "#e5e5e5" - ], - "name":"ocean" - }, - "pro":{ - "foreground":"#f2f2f2", - "background":"#000000", - "cursor":"#4d4d4d", - "cursor_text":"#ffffff", - "palette":[ - "#000000", - "#990000", - "#00a600", - "#999900", - "#1f08db", - "#b200b2", - "#00a6b2", - "#bfbfbf", - "#666666", - "#e50000", - "#00d900", - "#e5e500", - "#0000ff", - "#e500e5", - "#00e5e5", - "#e5e5e5" - ], - "name":"pro" - }, - "red_sands":{ - "foreground":"#d7c9a7", - "background":"#79241e", - "cursor":"#ffffff", - "cursor_text":"#000000", - "palette":[ - "#000000", - "#ff3f00", - "#00bb00", - "#e7b000", - "#0071ff", - "#bb00bb", - "#00bbbb", - "#bbbbbb", - "#555555", - "#bb0000", - "#00bb00", - "#e7b000", - "#0071ae", - "#ff55ff", - "#55ffff", - "#ffffff" - ], - "name":"red_sands" - }, - "seafoam_pastel":{ - "foreground":"#d3e7d3", - "background":"#243434", - "cursor":"#576479", - "cursor_text":"#323232", - "palette":[ - "#757575", - "#825d4d", - "#718c61", - "#ada16d", - "#4d7b82", - "#8a7167", - "#719393", - "#e0e0e0", - "#8a8a8a", - "#cf9379", - "#98d9aa", - "#fae79d", - "#79c3cf", - "#d6b2a1", - "#ade0e0", - "#e0e0e0" - ], - "name":"seafoam_pastel" - }, - "solarized_darcula":{ - "foreground":"#d2d8d9", - "background":"#3d3f41", - "cursor":"#708183", - "cursor_text":"#002731", - "palette":[ - "#25292a", - "#f24840", - "#629655", - "#b68800", - "#2075c7", - "#797fd4", - "#15968d", - "#d2d8d9", - "#25292a", - "#f24840", - "#629655", - "#b68800", - "#2075c7", - "#797fd4", - "#15968d", - "#d2d8d9" - ], - "name":"solarized_darcula" - }, - "solarized_dark":{ - "foreground":"#708183", - "background":"#001e26", - "cursor":"#708183", - "cursor_text":"#002731", - "palette":[ - "#002731", - "#d01b24", - "#728905", - "#a57705", - "#2075c7", - "#c61b6e", - "#259185", - "#e9e2cb", - "#001e26", - "#bd3612", - "#465a61", - "#52676f", - "#708183", - "#5856b9", - "#81908f", - "#fcf4dc" - ], - "name":"solarized_dark" - }, - "solarized_light":{ - "foreground":"#52676f", - "background":"#fcf4dc", - "cursor":"#52676f", - "cursor_text":"#e9e2cb", - "palette":[ - "#002731", - "#d01b24", - "#728905", - "#a57705", - "#2075c7", - "#c61b6e", - "#259185", - "#e9e2cb", - "#001e26", - "#bd3612", - "#465a61", - "#52676f", - "#708183", - "#5856b9", - "#81908f", - "#fcf4dc" - ], - "name":"solarized_light" - }, - "symfonic":{ - "foreground":"#ffffff", - "background":"#000000", - "cursor":"#dc322f", - "cursor_text":"#ffffff", - "palette":[ - "#000000", - "#dc322f", - "#56db3a", - "#ff8400", - "#0084d4", - "#b729d9", - "#ccccff", - "#ffffff", - "#1b1d21", - "#dc322f", - "#56db3a", - "#ff8400", - "#0084d4", - "#b729d9", - "#ccccff", - "#ffffff" - ], - "name":"symfonic" - }, - "terminal_basic":{ - "foreground":"#000000", - "background":"#ffffff", - "cursor":"#7f7f7f", - "cursor_text":"#000000", - "palette":[ - "#000000", - "#990000", - "#00a600", - "#999900", - "#0000b2", - "#b200b2", - "#00a6b2", - "#bfbfbf", - "#666666", - "#e50000", - "#00d900", - "#e5e500", - "#0000ff", - "#e500e5", - "#00e5e5", - "#e5e5e5" - ], - "name":"terminal_basic" - }, - "vaughn":{ - "foreground":"#dcdccc", - "background":"#25234e", - "cursor":"#ff5555", - "cursor_text":"#ffffff", - "palette":[ - "#24234f", - "#705050", - "#60b48a", - "#dfaf8f", - "#5555ff", - "#f08cc3", - "#8cd0d3", - "#709080", - "#709080", - "#dca3a3", - "#60b48a", - "#f0dfaf", - "#5555ff", - "#ec93d3", - "#93e0e3", - "#ffffff" - ], - "name":"vaughn" - }, - "zenburn":{ - "foreground":"#dcdccc", - "background":"#3f3f3f", - "cursor":"#73635a", - "cursor_text":"#000000", - "palette":[ - "#4d4d4d", - "#705050", - "#60b48a", - "#f0dfaf", - "#506070", - "#dc8cc3", - "#8cd0d3", - "#dcdccc", - "#709080", - "#dca3a3", - "#c3bf9f", - "#e0cf9f", - "#94bff3", - "#ec93d3", - "#93e0e3", - "#ffffff" - ], - "name":"zenburn" - } -}; - -module.exports = { - 'defaults': defaults, - 'colors': colors -} -},{}],5:[function(_dereq_,module,exports){ -function inherits(a, c) { - function k() { - this.constructor = a - } - k.prototype = c.prototype; - a.prototype = new k -} - -function isVisible(el) { - var eap, - rect = el.getBoundingClientRect(), - docEl = document.documentElement, - vWidth = window.innerWidth || docEl.clientWidth, - vHeight = window.innerHeight || docEl.clientHeight, - efp = function (x, y) { return document.elementFromPoint(x, y) }, - contains = "contains" in el ? "contains" : "compareDocumentPosition", - has = contains == "contains" ? 1 : 0x10; - - // Return false if it's not in the viewport - if (rect.right < 0 || rect.bottom < 0 - || rect.left > vWidth || rect.top > vHeight) - return false; - - // Return true if any of its four corners are visible - return ( - (eap = efp(rect.left, rect.top)) == el || el[contains](eap) == has - || (eap = efp(rect.right, rect.top)) == el || el[contains](eap) == has - || (eap = efp(rect.right, rect.bottom)) == el || el[contains](eap) == has - || (eap = efp(rect.left, rect.bottom)) == el || el[contains](eap) == has - ); -} - -function getSelection() { - var html = ""; - if (typeof window.getSelection != "undefined") { - return window.getSelection().toString(); - } else if (typeof document.selection != "undefined") { - if (document.selection.type == "Text") { - return document.selection.createRange().htmlText; - } - } - return null; -} - -function isBoldBroken() { - var a = document.createElement("span"); - a.innerHTML = - "hello world"; - document.body.appendChild(a); - var c = a.scrollWidth; - a.style.fontWeight = "bold"; - var k = a.scrollWidth; - document.body.removeChild(a); - return c !== k -} - -module.exports = { - 'inherits': inherits, - 'isBoldBroken': isBoldBroken, - 'isVisible': isVisible, - 'getSelection': getSelection -}; -},{}]},{},[3]) -(3) -}); \ No newline at end of file diff --git a/addons/cb.terminal/views/tab.js b/addons/cb.terminal/views/tab.js deleted file mode 100644 index a366f66d..00000000 --- a/addons/cb.terminal/views/tab.js +++ /dev/null @@ -1,167 +0,0 @@ -define([ - "vendors/sh", - "less!stylesheets/tab.less" -], function(Terminal) { - var _ = codebox.require("hr/utils"); - var $ = codebox.require("hr/dom"); - var hr = codebox.require("hr/hr"); - var Tab = codebox.require("views/tabs/base"); - var box = codebox.require("core/box"); - var user = codebox.require("core/user"); - - var settings = user.settings("terminal"); - - var TerminalTab = Tab.extend({ - className: Tab.prototype.className+ " addon-terminal-tab", - defaults: { - shellId: null, - resize: true - }, - menuTitle: "Terminal", - events: { - 'contextmenu': "clickTerm", - 'click': "clickTerm", - 'touchstart': "clickTerm" - }, - - initialize: function(options) { - var that = this; - TerminalTab.__super__.initialize.apply(this, arguments); - this.connected = false; - - // Init menu - this.menu.menuSection([ - { - 'type': "checkbox", - 'title': "Exit", - 'action': function(state) { - that.closeTab(); - } - } - ]); - - // Init rendering - this.term_el = $("
      ", { - 'class': "tab-panel-inner terminal-body" - }).appendTo($("
      ", {"class": "tab-panel-body"}).appendTo(this.$el)).get(0); - - // New terminal - this.term = new Terminal({ - cols: 80, - rows: 24, - theme: settings.get("theme", 'default') - }); - this.term.open(this.term_el); - - this.interval = setInterval(_.bind(this.resize, this), 2000); - - // Init codebox stream - this.sessionId = this.options.shellId || _.uniqueId("term"); - this.shell = box.openShell({ - 'shellId': this.options.shellId ? this.sessionId : this.sessionId+"-"+(new Date()).getSeconds() - }); - - this.on("tab:close", function() { - clearInterval(this.interval); - this.shell.disconnect(); - this.term.destroy(); - }, this); - - this.on("tab:state", function(state) { - if (state) { - this.focus(); - } - }, this); - - this.setTabTitle("Terminal - "+this.sessionId); - - - this.shell.once('data', function() { - that.resize(); - }); - - this.shell.on('data', function(chunk) { - that.write(chunk); - }); - - this.shell.on("connect", function() { - that.connected = true; - that.trigger("terminal:ready"); - }, this); - - this.shell.on('disconnect', function() { - that.writeln("Connection closed"); - that.closeTab(); - }); - - // Connect term - this.term.on('data', function(data) { - that.shell.write(data); - }); - this.term.on("resize", function(w, h) { - that.shell.resize(w, h); - }); - - this.shell.connect(); - - setTimeout(function() { - that.focus(); - }, 300); - return this; - }, - - // Render - render: function() { - this.$el.css({ - "font-family": settings.get("font", "monospace"), - "font-size": settings.get("size", 13)+'px', - "line-height": settings.get("line-height", 1.3) - }); - $(this.term_el).css({ - 'background': this.term.colors[256], - 'border-color': this.term.colors[256] - }); - - return this.ready(); - }, - - // Resize the terminal - resize: function() { - if (!this.options.resize) { return false; } - - var w = this.$el.width(); - var h = this.$el.height(); - - if (w != this._width || h != this._height) { - this._width = w; - this._height = h; - this.term.sizeToFit(); - } - - return this; - }, - - // Focus - focus: function() { - this.term.focus(); - }, - - // Write - write: function(content) { - this.term.write(content); - return this; - }, - - // Write a line - writeln: function(line) { - return this.write(line+"\r\n"); - }, - - // Block propagation of clicks to sublevel - clickTerm: function(e) { - e.stopPropagation(); - } - }); - - return TerminalTab; -}); diff --git a/addons/cb.theme.dark/ace/theme.js b/addons/cb.theme.dark/ace/theme.js deleted file mode 100644 index 4c4c049f..00000000 --- a/addons/cb.theme.dark/ace/theme.js +++ /dev/null @@ -1,10 +0,0 @@ -define([ - "less!ace/theme.less" -], function(cssContent) { - - return { - 'isDark': true, - 'cssClass': "ace-codebox-dark", - 'cssText': cssContent - } -}); \ No newline at end of file diff --git a/addons/cb.theme.dark/ace/theme.less b/addons/cb.theme.dark/ace/theme.less deleted file mode 100644 index c824a690..00000000 --- a/addons/cb.theme.dark/ace/theme.less +++ /dev/null @@ -1,206 +0,0 @@ -.ace_editor.ace-codebox-dark { - background-color: #2b303b; - color: #C5C8C6; - - .ace_gutter { - background: #2b303b; - color: #757a84 - } - - .ace_print-margin { - width: 1px; - background: #333d46 - } - - .ace_cursor { - color: #AEAFAD - } - - .ace_marker-layer .ace_selection { - background: #3d4550; - } - - &.ace_multiselect .ace_selection.ace_start { - box-shadow: 0 0 3px 0px #1D1F21; - border-radius: 2px - } - - .ace_marker-layer .ace_step { - background: rgb(102, 82, 0) - } - - .ace_marker-layer .ace_bracket { - margin: -1px 0 0 -1px; - border: 1px solid #4B4E55 - } - - .ace_marker-layer .ace_active-line { - background: #333d46 - } - - .ace_gutter-active-line { - background-color: #333d46; - } - - .ace_marker-layer .ace_selected-word { - border: 1px solid #373B41 - } - - .ace_invisible { - color: #4B4E55 - } - - .ace_keyword, - .ace_meta, - .ace_storage, - .ace_storage.ace_type, - .ace_support.ace_type { - color: #B294BB - } - - .ace_keyword.ace_operator { - color: #8ABEB7 - } - - .ace_constant.ace_character, - .ace_constant.ace_language, - .ace_constant.ace_numeric, - .ace_keyword.ace_other.ace_unit, - .ace_support.ace_constant, - .ace_variable.ace_parameter { - color: #cc856c - } - - .ace_constant.ace_other { - color: #CED1CF - } - - .ace_invalid { - color: #CED2CF; - background-color: #DF5F5F - } - - .ace_invalid.ace_deprecated { - color: #CED2CF; - background-color: #B798BF - } - - .ace_fold { - background-color: #81A2BE; - border-color: #757a84 - } - - .ace_entity.ace_name.ace_function, - .ace_support.ace_function, - .ace_variable { - color: #81A2BE - } - - .ace_support.ace_class, - .ace_support.ace_type { - color: #F0C674 - } - - .ace_heading, - .ace_string { - color: #9dbe8c - } - - .ace_entity.ace_name.ace_tag, - .ace_entity.ace_other.ace_attribute-name, - .ace_meta.ace_tag, - .ace_string.ace_regexp, - .ace_variable { - color: #b55761 - } - - .ace_comment { - color: #969896 - } - - .ace_indent-guide { - background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAACCAYAAACZgbYnAAAAEklEQVQImWNgYGBgYHB3d/8PAAOIAdULw8qMAAAAAElFTkSuQmCC) right repeat-y; - } - - /* Autocomplete dialog */ - &.ace_autocomplete { - width: 280px; - z-index: 200000; - background: #323d46; - color: #65737e; - border: none; - position: fixed; - box-shadow: 2px 3px 5px rgba(0,0,0,.2); - line-height: 2; - - font-smoothing: subpixel-antialiased; - -webkit-font-smoothing: subpixel-antialiased; - - .ace_marker-layer .ace_active-line { - background-color: #4f5b67; - z-index: 1; - } - .ace_text-layer .ace_selected, - .ace_text-layer .ace_selected .ace_rightAlignedText{ - color: #a1adba; - } - .ace_line-hover { - border: none; - margin-top: -1px; - background: none; - } - .ace_line-hover { - position: absolute; - z-index: 2; - } - .ace_rightAlignedText { - color: #65737e; - font-style: italic; - display: inline-block; - position: absolute; - right: 4px; - text-align: right; - z-index: -1; - } - .ace_completion-highlight{ - color: #c0c5ce; - } - } - - /* Search dialog */ - .ace_search { - border-color: transparent; - background: #1c1f25; - color: #65737e; - - .ace_searchbtn_close { - &:hover { - background-color: #323d46; - color: #65737e; - } - } - - .ace_search_field { - background: #323d46; - color: #65737e; - border-color: transparent; - } - - .ace_search_form, .ace_replace_form { - background-color: #323d46; - color: #65737e; - border-color: transparent; - } - - .ace_button { - background-color: #323d46; - color: #65737e; - } - - .ace_searchbtn, .ace_replacebtn{ - background-color: #323d46; - color: #65737e; - border-color: transparent; - } - } -} diff --git a/addons/cb.theme.dark/main.js b/addons/cb.theme.dark/main.js deleted file mode 100644 index 807df313..00000000 --- a/addons/cb.theme.dark/main.js +++ /dev/null @@ -1,102 +0,0 @@ -define([ - 'ace/theme' -], function(aceTheme) { - var themes = codebox.require("core/themes"); - - var bgDark = "#222830"; - var colorDark = "#64737e"; - - var bgNormal = "#1c1f25"; - var colorNormal = "#dfe0e6"; - - var bgLight = "#2b303b"; - var colorLight = "#dadfe6"; - - themes.add({ - id: "dark", - title: "Dark", - - editor: { - 'theme': aceTheme - }, - styles: { - // Scrollbar - /*scrollbar: { - 'background': "transparent", - 'width': "10px", - - corner: { - - }, - - thumb: { - 'background': "#4b505b" - } - },*/ - - - // Top menubar - menubar: { - 'background': bgNormal, - 'color': colorNormal, - 'border-color': "#111", - - button: { - 'border-color': bgNormal, - 'border-bottom-color': "transparent" - } - }, - - // Lateral bar panels - lateralbar: { - 'background': bgDark, - - commands: { - 'background': bgDark, - 'color': colorLight - }, - body: { - 'color': colorDark - } - }, - - // Tabs - tabs: { - section: { - 'border-color': bgDark - }, - header: { - 'background': bgDark, - 'color': colorDark - }, - content: { - 'background': bgLight, - }, - tab: { - '&.active': { - 'background': bgLight, - 'color': colorLight - } - } - }, - - // Operations - operations: { - operation: { - 'background': bgLight, - 'color': "#fff", - 'border-color': "transparent" - } - }, - - // Alerts - alerts: { - alert: { - 'background': bgLight, - 'color': colorLight, - 'border-color': "transparent" - } - } - } - }); -}); \ No newline at end of file diff --git a/addons/cb.theme.dark/package.json b/addons/cb.theme.dark/package.json deleted file mode 100644 index d744af96..00000000 --- a/addons/cb.theme.dark/package.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "name": "cb.theme.dark", - "version": "0.0.1", - "title": "Dark Theme", - "description": "Dark and gray theme.", - "homepage": "https://github.com/FriendCode/codebox", - "license": "Apache", - "author": { - "name": "Codebox", - "email": "contact@friendco.de", - "url": "https://www.codebox.io" - }, - "client": { - "main": "main" - } -} \ No newline at end of file diff --git a/bin/codebox.js b/bin/codebox.js index aef2cb61..4710a5d6 100755 --- a/bin/codebox.js +++ b/bin/codebox.js @@ -1,155 +1,119 @@ -#!/usr/bin/env node +#! /usr/bin/env node -var Q = require('q'); -var _ = require('lodash'); -var cli = require('commander'); -var path = require('path'); +var _ = require("lodash"); +var path = require("path"); +var program = require('commander'); var open = require("open"); -var Gittle = require('gittle'); -var pkg = require('../package.json'); -var codebox = require("../index.js"); +var pkg = require("../package.json"); +var codebox = require("../lib"); -// Codebox git repo: use to identify the user -var codeboxGitRepo = new Gittle(path.resolve(__dirname, "..")); +var gitconfig = require('../lib/utils/gitconfig'); -// Options -cli.option('-p, --port [http port]', 'Port to run the IDE'); -cli.option('-n, --hostname [http hostname]', 'Hostname to run the IDE'); -cli.option('-t, --title [project title]', 'Title for the project.'); -cli.option('-s, --sample [project type]', 'Replace directory content by a sample (warning: erase content).'); -cli.option('-o, --open', 'Open the IDE in your favorite browser'); -cli.option('-e, --email [email address]', 'Email address to use as a default authentication'); -cli.option('-u, --users [list users]', 'List of coma seperated users and password (formatted as "username:passowrd")'); - - -// An authentication hook that uses a dictionary of users -function usersAuthHook(users) { - return function(data) { - if (!data.email || !data.token) { - return Q.reject(new Error("Need 'token' and 'email' for auth hook")); - } - - var userId = data.email; - - if (!users[userId] || data.token != users[userId]) { - return Q.reject(new Error("Invalid user !")); - } - - return { - 'userId': userId, - 'name': userId, - 'token': data.token, - 'email': data.email - }; - }; +function printError(err) { + console.log(err.stack || err.message || err); + process.exit(1); } -// Command 'run' -cli.command('run [folder]') -.description('Run a Codebox into a specific folder.') -.action(function(projectDirectory) { - var that = this; - var prepare = Q(); - - // Codebox.io settings - that.box = process.env.CODEBOXIO_BOXID; - that.key = process.env.CODEBOXIO_TOKEN; - that.codeboxio = process.env.CODEBOXIO_HOST || "https://api.codebox.io"; - - // Default options - that.directory = projectDirectory || process.env.WORKSPACE_DIR || "./"; - that.title = that.title || process.env.WORKSPACE_NAME; - that.port = that.port || process.env.PORT || 8000; - that.hostname = that.hostname || "0.0.0.0"; +program +.version(pkg.version) +.on('--help', function(){ + console.log(' Examples:'); + console.log(''); + console.log(' $ codebox run ./myfolder'); + console.log(''); +}); - var users = !that.users ? {} : _.object(_.map(that.users.split(','), function(x) { +//// Run Codebox +//// +program +.command('run [root]') +.description('run codebox') +.option('-t, --templates [list]', 'Configuration templates, separated by commas', "") +.option('-p, --port [port]', 'HTTP port', 3000) +.option('-o, --open', 'Open the IDE in your favorite browser') +.option('-e, --email [email address]', 'Email address to use as a default authentication') +.option('-u, --users [list users]', 'List of coma seperated users and password (formatted as "username:password")', function (val) { + return _.object(_.map((val || "").split(','), function(x) { // x === 'username:password' return x.split(':', 2); })); - - - var config = { - 'root': that.directory, - 'title': that.title, - 'server': { - 'port': parseInt(that.port), - 'hostname': that.hostname - }, - 'users': { - 'defaultEmail': that.email - }, - 'project': { - 'forceSample': that.sample +}, {}) +.action(function(root, opts) { + // Generate configration + var options = { + root: path.resolve(process.cwd(), root || "./"), + port: opts.port, + auth: { + users: opts.users } }; - // Use Codebox.io - if (that.box && that.codeboxio && that.key) { - _.extend(config, { - 'workspace': { - 'id': that.box - }, - 'hooks': { - 'auth': that.codeboxio+"/api/box/"+that.box+"/auth", - 'events': that.codeboxio+"/api/box/"+that.box+"/events", - 'settings': that.codeboxio+"/api/account/settings", - 'addons': that.codeboxio+"/api/addons/valid" - }, - 'webhook': { - 'authToken': that.key - }, - 'proc': { - 'urlPattern': 'http://web-%d.' + that.box + '.vm1.dynobox.io' - }, - 'users': { - // Don't use default git user - 'gitDefault': false - } + codebox.start(options) + .then(function() { + if (program.email) return program.email; + + // Path to user's .gitconfig file + var configPath = path.join( + process.env.HOME, + '.gitconfig' + ); + + // Codebox git repo: use to identify the user + return gitconfig(configPath) + .get("user") + .get("email") + .fail(function() { + return ""; }); - } else if(!_.isEmpty(users)) { - _.extend(config, { - 'public': false, - 'hooks': { - 'auth': usersAuthHook(users) - } - }); - } - - // Auth user using git - prepare.fin(function() { - // Start Codebox - return codebox.start(config).then(function() { - var url = "http://localhost:"+that.port; - - console.log("\nCodebox is running at",url); + }) + .then(function(email) { + var token = opts.users[email] || Math.random().toString(36).substring(7); + var url = "http://localhost:"+options.port; - if (that.open) { - open(url); - } - }, function(err) { - console.error('Error initializing CodeBox'); - console.error(err); - console.error(err.stack); + console.log("\nCodebox is running at", url); - // Kill process - process.exit(1); - }); + if (program.open) open(url+"/?email="+email+"&token="+token); }) + .fail(printError); }); -cli.on('--help', function(){ - console.log(' Version: %s', pkg.version); - console.log(''); - console.log(' Examples:'); - console.log(''); - console.log(' $ codebox run'); - console.log(' $ codebox run ./myProject'); - console.log(''); - console.log(' Use option --open to directly open the IDE in your browser:'); - console.log(' $ codebox run ./myProject --open'); - console.log(''); +//// Install packages +//// +program +.command('install') +.description('pre-install packages') +.option('-r, --root [path]', 'Root folder to store packages') +.option('-p, --packages ', 'Comma separated list of packages to install', function (val) { + return _.chain(val.split(",")) + .compact() + .map(function(pkgref) { + var parts = pkgref.split(":"); + var name = _.first(parts); + var url = parts.slice(1).join(":"); + if (!name || !url) throw "Packages need to be formatted as 'name:url'"; + + return [name,url]; + }) + .object() + .value() +}, []) +.action(function(opts) { + codebox.prepare({ + packages: { + root: opts.root? path.resolve(process.cwd(), opts.root) : undefined, + install: opts.packages, + defaults: null + } + }) + .then(function() { + process.exit(0); + }) + .fail(printError); }); -cli.version(pkg.version).parse(process.argv); -if (!cli.args.length) cli.help(); +program.parse(process.argv); + +if (!process.argv.slice(2).length) { + program.outputHelp(); +} diff --git a/client/collections/addons.js b/client/collections/addons.js deleted file mode 100644 index 49f32629..00000000 --- a/client/collections/addons.js +++ /dev/null @@ -1,201 +0,0 @@ -define([ - "hr/promise", - "hr/utils", - "hr/hr", - "core/backends/rpc", - "models/addon", - "utils/dialogs" -], function(Q, _, hr, rpc, Addon, dialogs) { - var Addons = hr.Collection.extend({ - model: Addon, - defaults: _.defaults({ - loader: "getInstalled", - loaderArgs: [], - }, hr.Collection.prototype.defaults), - - // Constructor - initialize: function() { - Addons.__super__.initialize.apply(this, arguments); - - this.resolved = {}; - this.provides = {}; - - return this; - }, - - // Get installed addons - getInstalled: function(options) { - var that = this; - - options = _.defaults(options || {}, {}); - - return rpc.execute("addons/list").then(function(data) { - that.add(_.values(data)); - }); - }, - - // Get by name - getByName: function(name) { - return this.find(function(addon) { - return addon.get("name") == name; - }); - }, - - // Check addons is installed - isInstalled: function(name) { - return this.getByName(name) != null; - }, - - // Check addons is a default addon - isDefault: function(name) { - var m = this.getByName(name); - if (m == null) return false; - return m.get("default"); - }, - - // Check is updated - isUpdated: function(addon) { - var m = this.getByName(addon.get("name")); - if (!m) return true; - return m.version() >= addon.version(); - }, - - // Get addon state - getState: function(name) { - var m = this.getByName(name); - if (m == null) return null; - return m.get("state"); - }, - - // Install an addon - install: function(git) { - var that = this; - - return rpc.execute("addons/install", { - 'git': git - }).then(function(data) { - that.reset([]); - return that.getInstalled(); - }); - }, - uninstall: function(name) { - var that = this; - - return rpc.execute("addons/uninstall", { - 'name': name - }).then(function() { - that.reset([]); - return that.getInstalled(); - }); - }, - - // Extract from engineer, order addons for loading - checkCycles: function() { - var that = this; - var plugins = this.map(function(addon, index) { - return { - name: addon.get("name"), - provides: addon.get("client.provides", []).concat(), - consumes: addon.get("client.consumes", []).concat(), - i: index - }; - }); - - var changed = true; - var sorted = []; - - while(plugins.length && changed) { - changed = false; - - plugins.concat().forEach(function(plugin) { - var consumes = plugin.consumes.concat(); - - var resolvedAll = true; - for (var i=0; i 0) { - var e = new Error("Error with "+_.size(errors)+" addons"); - e.addonsError = errors; - return Q.reject(e); - } - return Q(); - }); - } - }); - - return Addons; -}); \ No newline at end of file diff --git a/client/collections/changes.js b/client/collections/changes.js deleted file mode 100644 index 2105e18e..00000000 --- a/client/collections/changes.js +++ /dev/null @@ -1,27 +0,0 @@ -define([ - "hr/utils", - "hr/hr", - "models/change" -], function(_, hr, Change) { - var Changes = hr.Collection.extend({ - model: Change, - - // Sort comparator - comparator: function(command) { - return command.get("path", "").length; - }, - - // Apply all - applyAll: function() { - console.log("apply all changes", this.size()); - return this.reduce(function(prev, change) { - console.log("next ", change, prev); - return prev.then(function() { - return change.apply(); - }) - }, Q()); - } - }); - - return Changes; -}); \ No newline at end of file diff --git a/client/collections/commands.js b/client/collections/commands.js deleted file mode 100644 index 4c3780ac..00000000 --- a/client/collections/commands.js +++ /dev/null @@ -1,16 +0,0 @@ -define([ - "hr/utils", - "hr/hr", - "models/command" -], function(_, hr, Command) { - var Commands = hr.Collection.extend({ - model: Command, - - // Sort comparator - comparator: function(command) { - return command.get("position", 2); - } - }); - - return Commands; -}); \ No newline at end of file diff --git a/client/collections/files.js b/client/collections/files.js deleted file mode 100644 index 6c51e8dc..00000000 --- a/client/collections/files.js +++ /dev/null @@ -1,11 +0,0 @@ -define([ - "hr/utils", - "hr/hr", - "models/file" -], function(_, hr, File) { - var Files = hr.Collection.extend({ - model: File - }); - - return Files; -}); \ No newline at end of file diff --git a/client/collections/operations.js b/client/collections/operations.js deleted file mode 100644 index 0b415bd9..00000000 --- a/client/collections/operations.js +++ /dev/null @@ -1,66 +0,0 @@ -define([ - "hr/utils", - "hr/hr", - "hr/promise", - "models/operation", - "utils/dialogs" -], function(_, hr, Q, Operation, dialogs) { - var Operations = hr.Collection.extend({ - model: Operation, - - // Sort comparator - comparator: function(command) { - return command.get("progress", 0); - }, - - // Get by id - getById: function(opId) { - return this.find(function(op) { - return op.id == opId; - }); - }, - - // Start an operation - start: function(opId, startMethod, properties, options) { - var op, d; - - options = _.defaults({}, options || {}, { - 'unique': true - }); - - op = this.getById(opId); - - if (op) return Q.reject(new Error("An operation with this id is already running: "+opId)); - - op = new Operation({}, _.extend({ - 'id': opId - }, properties || {})); - - this.add(op); - - if (startMethod) { - d = startMethod(op); - - // Error during the operation - d.fail(function(err) { - dialogs.alert("Error during an operation ("+_.escape(opId)+")", err.message || err); - }); - - // Progress - d.progress(function(p) { - op.progress(p); - }); - - // Destroy the operation - d.fin(function() { - op.destroy(); - }); - return d; - } else { - return op; - } - } - }); - - return Operations; -}); \ No newline at end of file diff --git a/client/collections/users.js b/client/collections/users.js deleted file mode 100644 index 106c2c41..00000000 --- a/client/collections/users.js +++ /dev/null @@ -1,27 +0,0 @@ -define([ - "hr/utils", - "hr/hr", - "core/backends/rpc", - "models/user" -], function(_, hr, rpc, User) { - var Users = hr.Collection.extend({ - model: User, - - // Return an user from the collection by its user id - getById: function(userId) { - return this.find(function(model) { - return model.get("userId") == userId; - }) - }, - - // Get list of collaborators from the box - getCollaborators: function() { - var that = this; - return rpc.execute("users/list").then(function(data) { - that.reset(data); - }); - } - }); - - return Users; -}); \ No newline at end of file diff --git a/client/core/addons.js b/client/core/addons.js deleted file mode 100644 index 7702efe8..00000000 --- a/client/core/addons.js +++ /dev/null @@ -1,9 +0,0 @@ -define([ - 'hr/hr', - 'collections/addons' -], function (hr, Addons) { - // Collection for all installed addons - var addons = new Addons(); - - return addons; -}); \ No newline at end of file diff --git a/client/core/app.js b/client/core/app.js deleted file mode 100644 index c2b66bbe..00000000 --- a/client/core/app.js +++ /dev/null @@ -1,229 +0,0 @@ -define([ - 'hr/hr', - 'utils/url', - 'utils/dialogs', - 'utils/alerts', - 'utils/loading', - 'core/box', - 'core/session', - 'core/addons', - 'core/box', - 'core/files', - 'core/commands/toolbar', - 'core/commands/menu', - 'core/tabs', - 'core/panels', - 'core/operations', - 'core/localfs', - 'core/themes', - 'core/search/files', - 'core/search/tags' -], function (hr, url, dialogs, alerts, loading, -box, session, addons, box, files, commands, menu, tabs, panels, operations, localfs, themes) { - - // Define base application - var Application = hr.Application.extend({ - name: "Codebox", - template: "main.html", - metas: { - "robots": "noindex, nofollow", - "description": "Cloud IDE on a box.", - "apple-mobile-web-app-capable": "yes", - "apple-mobile-web-app-status-bar-style": "black", - "viewport": "width=device-width, initial-scale=1, user-scalable=no" - }, - links: { - "icon": hr.Urls.static("images/icons/32.png"), - "apple-touch-icon": hr.Urls.static("images/icons/ios.png") - }, - events: { - "click .cb-login .login-box #login-submit": "actionLoginBox" - }, - - // Constructor - initialize: function() { - Application.__super__.initialize.apply(this, arguments); - this._autologin = true; - this.loginError = null; - - // Tabs - tabs.on("tabs:default tabs:opennew", function() { - files.openNew(); - }, this); - - // Panels - panels.on("open", function() { - this.toggleMode("body-fullpage", false); - }, this); - panels.on("close", function() { - this.toggleMode("body-fullpage", true); - }, this); - - // Offline: state/update - hr.Offline.on("state", function(state) { - if (!state) { - alerts.show("Caution: Connection lost, Workspace is now in Offline mode", 5000); - } else { - alerts.show("Connection detected. Switching to Codebox online", 5000); - location.reload(); - } - }); - hr.Offline.on("update", function() { - location.reload(); - }); - - // Title changed - box.on("change:name", function() { - this.title(box.get("name")); - }, this); - - return this; - }, - - // Template rendering context - templateContext: function() { - return { - 'email': hr.Cookies.get("email"), - 'token': hr.Cookies.get("token"), - 'loginError': this.loginError - }; - }, - - // Render the application - render: function() { - var email = hr.Cookies.get("email"); - var password = hr.Cookies.get("token"); - - if (!box.isAuth() && ((email && password) || (email && box.get("public"))) && this._autologin) { - this.doLogin(email, password); - return; - } - return Application.__super__.render.apply(this, arguments); - }, - - // Finish rendering - finish: function() { - var that = this; - - if (box.isAuth()) { - // Add menu - menu.$el.appendTo(this.$(".cb-menubar")); - menu.render(); - - // Add commands - commands.$el.appendTo(this.$(".cb-commands")); - commands.render(); - - // Add tabs - tabs.$el.appendTo(this.$(".cb-body")); - tabs.render(); - - // Add panels - panels.$el.appendTo(this.$(".cb-panels")); - panels.render(); - - // Add operations - operations.$el.appendTo(this.$(".lateral-operations")); - operations.render(); - operations.on("add remove reset", function() { - setTimeout(function() { - that.$(".lateral-body").css("bottom", operations.$el.height()); - }, 200); - }); - - // Load addons - loading.show(addons.loadAll()).fail(function(err) { - return dialogs.alert("Error loading Add-ons", - "

      Error when initializing addons." + - " Please check addons states using the addons manager and reinstall problematic add-ons.

      " + - "

      Error message: "+ (err.message || err) +"

      " + - _.map(err.addonsError || [], function(error) { - return "

      - "+_.escape(error.addon)+": "+(error.error.message || error.error)+"

      "; - }).join("\n")); - }) - .fin(themes.init) - .fin(function() { - // Load new addons - addons.on("add", function(addon) { - addon.load(); - }); - - // Check update - hr.Offline.checkUpdate(); - - // Trigger event that app is ready - that.trigger("ready"); - - // Open new file if not files opened by addons - if (files.active.size() == 0) files.openNew(); - }); - } - return Application.__super__.finish.apply(this, arguments); - }, - - // Login to box - actionLoginBox: function(e) { - var that = this; - if (e) { - e.preventDefault(); - } - - var email = this.$(".login-box #login-email").val(); - var password = this.$(".login-box #login-token").val(); - - this.doLogin(email, password); - }, - - // Do login - doLogin: function(email, password) { - var that = this; - - // If public: generate a random password - if (box.get("public")) { - password = Math.random().toString(36).substring(8); - } - - // Clear errors - this.$(".login-box .form-group").removeClass("has-error"); - - // No email - if (!email) { - this.$(".login-box #login-email").parent(".form-group").addClass("has-error"); - return Q.reject(new Error("No email")); - } - - // No password - if (!password) { - this.$(".login-box #login-token").parent(".form-group").addClass("has-error"); - return Q.reject(new Error("No password")); - } - - return session.start(email, password).then(function() { - hr.Cookies.set("email", email); - hr.Cookies.set("token", password); - - that.render(); - }).fail(function(err) { - that._autologin = false; - that.loginError = err; - - loading.stop(); - that.render(); - }); - }, - - // Toggle mode - toggleMode: function(mode, st) { - $("#codebox").toggleClass("mode-"+mode, st); - st = this.hasMode(mode); - $(".cb-active-mode-"+mode).toggleClass("active", st); - $(".cb-inactive-mode-"+mode).toggleClass("active", !st); - }, - hasMode: function(mode, st) { - return $("#codebox").hasClass("mode-"+mode); - } - }); - - var app = new Application(); - return app; -}); diff --git a/client/core/backends/rpc.js b/client/core/backends/rpc.js deleted file mode 100644 index b61e572e..00000000 --- a/client/core/backends/rpc.js +++ /dev/null @@ -1,43 +0,0 @@ -define([ - 'hr/hr' -], function(hr) { - var rpc = new hr.Backend({ - prefix: "rpc" - }); - - rpc.defaultMethod({ - execute: function(args, options, method) { - options = _.defaults({}, options || {}, { - dataType: "json", - options: { - 'headers': { - 'Content-type': 'application/json' - } - } - }); - - return hr.Requests.post("rpc/"+method, JSON.stringify(args), options).then(function(data) { - if (!data.ok) return Q.reject(new Error(data.error)); - return Q(data.data); - }, function(err) { - try { - var errContent = JSON.parse(err.httpRes); - var e = new Error(errContent.error || err.message); - e.code = errContent.code || err.status || 500; - return Q.reject(e); - } catch(e) { - return Q.reject(err); - } - }); - } - }); - - // Cached methods - rpc.addCachedMethod('box/status'); - rpc.addCachedMethod('box/changes'); - rpc.addCachedMethod('auth/join'); - rpc.addCachedMethod('addons/list'); - rpc.addCachedMethod('users/list'); - - return rpc; -}); \ No newline at end of file diff --git a/client/core/backends/vfs.js b/client/core/backends/vfs.js deleted file mode 100644 index 610ff11c..00000000 --- a/client/core/backends/vfs.js +++ /dev/null @@ -1,156 +0,0 @@ -define([ - 'hr/utils', - 'hr/hr', - 'utils/url', - 'core/localfs' -], function(_, hr, Url, localfs) { - var logger = hr.Logger.addNamespace("vfs"); - - // Create backend - var vfs = new hr.Backend({ - prefix: "vfs" - }); - - // Emulate a vfs event - var triggerWatchEvent = function(name, path, data) { - var eventName = "watch.change."+name; - vfs.trigger("event:"+eventName, { - 'event': eventName, - 'data': _.extend({}, { - 'path': path, - 'change': name - }, data) - }); - }; - - // Refresh all vfs when offlien change - hr.Offline.on("state", function() { - triggerWatchEvent("folder", "/"); - }); - - // Map vfs method -> http request method - var methodsMap = { - "listdir": "getJSON", - "write": "put", - "mkdir": "put", - "create": "put", - "rename": "post", - "remove": "delete", - "read": "get" - }; - - // Base method when connection is on - vfs.defaultMethod({ - execute: function(args, options, method) { - if (args && method != "write") args = JSON.stringify(args); - if (!options.url) return Q.reject(new Error("VFS requests need 'url' option")); - if (!methodsMap[method]) return Q.reject(new Error("Invalid VFS request: "+method)); - - logger.log(method+": "+options.url); - return hr.Requests[methodsMap[method]](options.url, args, options); - }, - after: function(args, results, options, method) { - var path = localfs.urlToPath(options.url); - switch (method) { - case "remove": - triggerWatchEvent("delete", path); - break; - case "rename": - triggerWatchEvent("delete", args.renameFrom); - triggerWatchEvent("create", path); - break; - case "create": - triggerWatchEvent("create", path); - break; - case "mkdir": - triggerWatchEvent("create", path); - break; - case "write": - triggerWatchEvent("update", path); - break; - } - } - }); - - // Read a file content - vfs.addMethod('read', { - fallback: function(args, options) { - var path = localfs.urlToPath(options.url); - return localfs.read(path); - }, - after: function(args, results, options) { - - } - }); - - // Create a new file - vfs.addMethod('create', { - fallback: function(args, options) { - var path = localfs.urlToPath(options.url); - return localfs.create(path, args); - }, - after: function(args, results, options) { - localfs.autoSync(); - } - }); - - // Create a new directory - vfs.addMethod('mkdir', { - fallback: function(args, options) { - var path = localfs.urlToPath(options.url); - return localfs.mkdir(path, args); - }, - after: function(args, results, options) { - localfs.autoSync(); - } - }); - - // Write a file content - vfs.addMethod('write', { - fallback: function(args, options) { - var path = localfs.urlToPath(options.url); - return localfs.write(path, args); - }, - after: function(args, results, options) { - localfs.autoSync(); - } - }); - - // Rename a file - vfs.addMethod('rename', { - fallback: function(args, options) { - var to = localfs.urlToPath(options.url); - var from = args.renameFrom; - - if (!from) return Q.reject("need 'renameFrom'"); - return localfs.mv(from, to); - }, - after: function(args, results, options) { - localfs.autoSync(); - } - }); - - // Remove a file or directory - vfs.addMethod('remove', { - fallback: function(args, options) { - var path = localfs.urlToPath(options.url); - return localfs.rm(path, args); - }, - after: function(args, results, options) { - localfs.autoSync(); - } - }); - - // List a directory - vfs.addMethod('listdir', { - fallback: function(args, options) { - var path = localfs.urlToPath(options.url); - return localfs.ls(path); - }, - after: function(args, results, options) { - - } - }); - - return vfs; -}); \ No newline at end of file diff --git a/client/core/box.js b/client/core/box.js deleted file mode 100644 index cfdf1687..00000000 --- a/client/core/box.js +++ /dev/null @@ -1,20 +0,0 @@ -define([ - 'hr/promise', - 'hr/hr', - 'models/box', - 'core/search', - 'core/collaborators' -], function (Q, hr, Codebox, search, collaborators) { - // Current box - var box = new Codebox(); - - // Bind collaborators changement - box.on("box:users:add", function(e) { - collaborators.add(e.data); - }); - box.on("box:users:remove", function(e) { - collaborators.remove(collaborators.getById(e.data.userId)); - }); - - return box; -}); \ No newline at end of file diff --git a/client/core/collaborators.js b/client/core/collaborators.js deleted file mode 100644 index 7de8e885..00000000 --- a/client/core/collaborators.js +++ /dev/null @@ -1,19 +0,0 @@ -define([ - 'hr/utils', - 'hr/hr', - 'collections/users', - 'utils/alerts' -], function (_, hr, Users, alerts) { - // Collection for all current collaborators - var collaborators = new Users(); - - collaborators.on("add", function(user) { - alerts.show(user.get("name")+" just joined the workspace", 5000); - }); - - collaborators.on("remove", function(user) { - alerts.show(user.get("name")+" just left the workspace", 5000); - }); - - return collaborators; -}); \ No newline at end of file diff --git a/client/core/commands/menu.js b/client/core/commands/menu.js deleted file mode 100644 index c69b1ecc..00000000 --- a/client/core/commands/menu.js +++ /dev/null @@ -1,45 +0,0 @@ -define([ - 'hr/utils', - 'hr/hr', - 'views/commands/menubar', - 'core/box', - 'core/panels', - 'core/tabs', - 'core/session', - 'core/localfs', - 'core/settings' -], function (_, hr, MenubarView, box, panels, tabs, session, localfs, settings) { - // Collection for all menu commands - var menu = new MenubarView(); - - menu.register("view", { - title: "View", - position: 5 - }).menuSection({ - 'id': "themes.settings", - 'title': "Settings", - 'offline': false, - 'action': function() { - settings.open("themes"); - } - }).menuSection([ - panels.visibilityCommand, - panels.panelsCommand - ]).menuSection([ - tabs.layoutCommand - ]); - - menu.register("file", { - title: "File", - position: 0 - }).menuSection([{ - 'id': "quit", - 'title': "Quit", - 'shortcuts': ["alt+q"], - 'action': session.exit - }], { - 'position': 1000 - }); - - return menu; -}); \ No newline at end of file diff --git a/client/core/commands/toolbar.js b/client/core/commands/toolbar.js deleted file mode 100644 index 25d6de49..00000000 --- a/client/core/commands/toolbar.js +++ /dev/null @@ -1,31 +0,0 @@ -define([ - 'hr/utils', - 'hr/hr', - 'views/commands/toolbar', - 'core/search' -], function (_, hr, CommandsToolbar, search) { - // Collection for all toolbar commands - var commands = new CommandsToolbar(); - - // Add commands to search - search.handler({ - 'id': "commands", - 'title': "Commands" - }, function(query) { - return _.map(commands.collection.filter(function(command) { - return ( - command.get("title").toLowerCase().indexOf(query) != -1 - && command.get("search") - ); - }), function(command) { - return { - "text": command.get("title"), - "callback": _.bind(function() { - command.run(); - }, this) - } - }); - }); - - return commands; -}); \ No newline at end of file diff --git a/client/core/files.js b/client/core/files.js deleted file mode 100644 index e473def6..00000000 --- a/client/core/files.js +++ /dev/null @@ -1,219 +0,0 @@ -define([ - 'hr/promise', - 'hr/utils', - 'hr/hr', - 'models/file', - 'collections/files', - 'core/user', - 'core/box', - 'core/tabs', - 'core/settings', - 'utils/dialogs', - 'views/tabs/file', - 'views/files/base', - 'views/files/tab' -], function(Q, _, hr, File, Files, user, box, tabs, settings, dialogs, FileTab) { - var logging = hr.Logger.addNamespace("files"); - - // Settings for files manager - var settings = settings.add({ - 'namespace': "files", - 'title': "Files", - 'fields': {} - }); - var userSettings = user.settings("files"); - - // Recent files - var recentFiles = new Files(); - recentFiles.on("add", function() { - // Limit collection size - if (recentFiles.size() > 20) recentFiles.shift(); - }); - - // Active files - var activeFiles = new Files(); - - // Files handlers map - var handlers = {}; - - // Add handler - var addHandler = function(handlerId, handler) { - if (!handler - || !handlerId - || !handler.name - || !handler.valid - || (!handler.View && !handler.open)) { - throw "Invalid files handler format"; - } - - handler = _.defaults(handler, { - 'setActive': false - }); - - handler.id = handlerId; - - if (handler.View) { - handler.open = function(file) { - var path = file.path(); - var uniqueId = handler.id+":"+file.syncEnvId(); - - // Add files as open - if (handler.setActive) activeFiles.add(file); - - var tab = tabs.getActiveTabByType("directory"); - if (tab != null && !tabs.checkTabExists(uniqueId) && !file.isNewfile()) { - // Change current tab to open the file - tab.view.load(path, handler); - } else { - - // Add new tab - var tab = tabs.add(FileTab, { - "model": file, - "handler": handler - }, { - "uniqueId": uniqueId, - "type": "file", - }); - - // Focus tab -> set active file - tab.on("tab:state", function(state) { - if (state) box.setActiveFile(file); - }); - - // Close tab -> close active file - tab.on("tab:close", function(state) { - if (handler.setActive) activeFiles.remove(file); - }); - } - }; - } - - // Add settings - settings.setField(handlerId, { - 'label': handler.name, - 'type': "checkbox", - 'default': true - }); - - // Register handler - handlers[handlerId] = handler; - }; - - // Get handler for a file - var getHandlers = function(file, defaultHandler) { - return _.filter(handlers, function(handler) { - return userSettings.get(handler.id, true) && handler.valid(file); - }); - }; - - // get fallback handlers for a file - var getFallbacks = function(file) { - return _.filter(handlers, function(handler) { - return userSettings.get(handler.id, true) && handler.fallback == true; - }); - }; - - // Open file with handler - var openFileHandler = function(handler, file) { - // Add to recent files - if (!file.isNewfile()) recentFiles.add(file); - - return Q(handler.open(file)).then(function() { - box.setActiveFile(file); - }); - } - - // Select to open a file with any handler - var openFileWith = function(file) { - var choices = {}; - _.each(handlers, function(handler) { - choices[handler.id] = handler.name; - }); - - if (_.size(choices) == 0) { - return Q.reject(new Error("No handlers for this file")); - } - - return dialogs.select("Can't open this file", "Sorry, No handler has been found to open this file. Try to find and install an add-on to manage this file or select one of the following handlers:", choices).then(function(value) { - var handler = handlers[value]; - return Q(openFileHandler(handler, file)); - }); - }; - - // Open a file - var openFile = function(file, options) { - options = _.defaults({}, options || {}, { - 'userChoice': null, - 'useFallback': true - }); - - if (_.isString(file)) { - var nfile = new File({ - 'codebox': box - }); - return nfile.getByPath(file).then(function() { - return openFile(nfile); - }); - } - - var possibleHandlers = getHandlers(file); - - // get fallbacks - if (_.size(possibleHandlers) == 0 && options.useFallback) { - possibleHandlers = getFallbacks(); - } - - // All choices - if (_.size(possibleHandlers) == 0) { - return openFileWith(file); - } - - if (_.size(possibleHandlers) == 1 || (options.userChoice != true)) { - return Q(openFileHandler(_.first(possibleHandlers), file)); - } - - var choices = {}; - _.each(possibleHandlers, function(handler) { - choices[handler.id] = handler.name; - }) - - if (_.size(choices) == 0) { - return Q.reject(new Error("No handlers for this file")); - } - - return dialogs.select("Open with...", "Select one of the following handlers to open this file:", choices).then(function(value) { - var handler = handlers[value]; - return Q(openFileHandler(handler, file)); - }); - }; - - // Open a new file - var openNew = function(name, content) { - name = name || "untitled"; - - // Create a temporary file - var f = new File({ - 'codebox': box - }, { - 'name': name, - 'size': 0, - 'mtime': 0, - 'mime': "text/plain", - 'href': location.protocol+"//"+location.host+"/vfs/"+name, - 'exists': false - }); - - if (content) f.setCache(content); - - return openFile(f); - }; - - return { - 'addHandler': addHandler, - 'getHandlers': getHandlers, - 'open': openFile, - 'openNew': openNew, - 'recent': recentFiles, - 'active': activeFiles - }; -}); \ No newline at end of file diff --git a/client/core/globals.js b/client/core/globals.js deleted file mode 100644 index 2912459c..00000000 --- a/client/core/globals.js +++ /dev/null @@ -1,7 +0,0 @@ -define(['require'], function (require) { - window.codebox = { - 'require': require - }; - - return window.codebox; -}); \ No newline at end of file diff --git a/client/core/localfs.js b/client/core/localfs.js deleted file mode 100644 index 6e466245..00000000 --- a/client/core/localfs.js +++ /dev/null @@ -1,504 +0,0 @@ -define([ - 'hr/utils', - 'hr/hr', - 'utils/url', - 'vendors/filer', - 'core/operations', - 'utils/alerts', - 'collections/changes' -], function(_, hr, Url, Filer, operations, alerts, Changes) { - var logger = hr.Logger.addNamespace("localfs"); - - // Base folder for localfs - var base = "/"; - var _isInit = false; - var _syncIsEnable = false; - var _ignoredFiles = []; - var changes = new Changes(); - - // Constant mime type for a directory - var MIME_DIRECTORY = "inode/directory"; - - // Duration for sync (ms) - syncDuration = 1*60*1000; - - - // Create fs interface - var filer = new Filer(); - - var fsCall = function(method, args, context) { - if (!_syncIsEnable) return Q.reject(new Error("Offline synchronization is disabled")); - if (_.isUndefined(args)) args = []; - if (!_.isArray(args)) args = [args]; - - var d = Q.defer(); - args.push(function() { - if (arguments.length == 1) return d.resolve(arguments[0]); - d.resolve(arguments); - }); - args.push(function(err) { - logger.error("Error occurs: ", method.name, err); - d.reject(err); - }) - - try { - method.apply(context, args); - } catch(err) { - d.reject(err); - } - - return d.promise; - }; - - /* - * Init the localfs - */ - var initFs = function(baseDir) { - base = "/"+baseDir; - logger.log("base is", base); - return Q(); - }; - - /* - * Enable/Disable sync - */ - var enableSync = function(state) { - _syncIsEnable = state != undefined? state : true; - }; - - /* - * Set ignored files list - */ - var setIgnoredFiles = function(files) { - _ignoredFiles = files || []; - _ignoredFiles.push("/.git") - _ignoredFiles = _.compact(_ignoredFiles); - _ignoredFiles = _.uniq(_ignoredFiles); - _ignoredFiles = _.map(_ignoredFiles, function(p) { - if (p[0] != "/") p = "/"+p; - return p; - }); - }; - - var prepareFs = function() { - if (_isInit) return Q(); - return fsCall(filer.init, { - persistent: true, - size: 10 * 1024 * 1024 - }, filer) - .then(function() { - logger.log("fs is ready"); - _isInit = true; - return Q(); - }); - }; - - var needFsReady = function(fn) { - return function() { - var args = arguments; - return prepareFs().then(function() { - return fn.apply(fn, args); - }); - }; - } - - /* - * Adapt path - */ - var adaptPath = function(path) { - path = base+path; - path = path.replace("//", "/"); - return path; - } - - /* - * Convert a vfs url in a path - */ - var urlToPath = function(url) { - var path = url.replace("/vfs/", ""); - if (path.length == 0) path = '/'; - if (path[0] != '/') path = "/" + path; - return path; - }; - - /* - * Test if path is ignored files - */ - var isIgnoredFile = function(path) { - return _.reduce(_ignoredFiles, function(state, ignoredPath) { - if (state) return state; - if (path.indexOf(ignoredPath) == 0) return true; - }, false); - }; - - /* - * Return informations about a fileentry - */ - var getEntryInfos = needFsReady(function(fEntry) { - return fsCall(fEntry.getMetadata, [], fEntry).then(function(metadata) { - var path = fEntry.fullPath.replace(base, "/").replace("//", "/"); - var url = location.protocol+"//"+location.host+"/vfs"+path; - - if (fEntry.isDirectory) url = url + "/"; - - return { - "name": fEntry.name, - "size": metadata.size, - "mtime": metadata.modificationTime.getTime(), - "mime": fEntry.isDirectory ? MIME_DIRECTORY : "application/octet-stream", - "href": url, - "exportUrl": fEntry.toURL(), - "offline": true, - '_fullPath': path - }; - }) - }); - - /* - * List a directory - */ - var listDir = needFsReady(function(path, adapt) { - path = (adapt == false) ? path : adaptPath(path); - - logger.log("ls:", path); - return fsCall(filer.ls, path, filer).then(function(entries) { - return Q.all(_.map(entries, function(entry) { - return getEntryInfos(entry); - })) - }).then(function(entries) { - return entries; - }, function(err) { - logger.error("ls:", err); - }); - }); - - /* - * Create a file - */ - var createFile = needFsReady(function(path) { - path = adaptPath(path); - logger.log("create:", path); - return fsCall(filer.create, [path, true], filer); - }); - - /* - * Write file - */ - var writeFile = needFsReady(function(path, data) { - path = adaptPath(path); - logger.log("write:", path); - return fsCall(filer.write, [path, { - 'data': data || "" - }], filer); - }); - - /* - * Open a file - */ - var openFile = needFsReady(function(path) { - path = adaptPath(path); - logger.log("open:", path); - return fsCall(filer.getEntry, [path], filer).then(function(fEntry) { - return getEntryInfos(fEntry); - }) - }); - - /* - * Read a file - */ - var readFile = needFsReady(function(path) { - path = adaptPath(path); - logger.log("read:", path); - return fsCall(filer.open, [path], filer).then(function(file) { - var d = Q.defer(); - - var reader = new FileReader(); - reader.onerror = function(err) { - d.reject(err); - }; - reader.onload = function(e) { - d.resolve(reader.result); - }; - reader.readAsText(file); - - return d.promise; - }); - }); - - /* - * Create a file - */ - var createDirectory = needFsReady(function(path) { - path = adaptPath(path); - logger.log("mkdir:", path); - return fsCall(filer.mkdir, [path, false], filer); - }); - - /* - * Move a file - */ - var move = needFsReady(function(from, to) { - from = adaptPath(from); - to = adaptPath(to); - - logger.log("move:", from, "to", to); - return fsCall(filer.mv, [from, '.', to], filer); - }); - - /* - * Remove a file or directory - */ - var remove = needFsReady(function(path, adapt) { - path = (adapt == false) ? path : adaptPath(path); - - logger.log("remove:", path); - return fsCall(filer.rm, [path], filer); - }); - - /* - * Return changes - */ - var getChanges = needFsReady(function() { - var File = require("models/file"); - var box = require("core/box"); - changes.reset([]); - - if (!_syncIsEnable) return Q(changes); - - var addChange = function(path, type, args) { - if (isIgnoredFile(path)) { - return; - } - logger.log("change:",type,path); - changes.add(_.extend(args || {}, { - 'path': path, - 'time': Date.now(), - 'type': type || "M" - })); - } - - var getDirChanges = function(path) { - var localEntries, boxEntries, currentEntryInfos, fp; - if (isIgnoredFile(path)) { - return Q(); - } - - logger.log("get changes in:", path); - - // File in the workspace - fp = new File(); - - return openFile(path).then(function(infos) { - return listDir(path); - }).then(function(entries) { - // Entry in the browser - localEntries = entries; - - // Get file on the workspace - return fp.getByPath(path).fail(function() { - return Q(); - }); - }).then(function() { - if (fp.isDirectory()) { - return fp.listdir(); - } - return Q([]); - }).then(function(entries) { - // Entries on the boxes - boxEntries = entries; - }).then(function() { - // Eliminate old useless entries - return Q.all(_.map(boxEntries, function(boxFile) { - if (isIgnoredFile(boxFile.path())) return Q(); - - var localEntry = _.find(localEntries, function(localEntry) { - return localEntry.name == boxFile.get("name"); - }); - - // File don't exists and box file older than current directory - if (!localEntry && boxFile.get("mtime") < currentEntryInfos.mtime) { - // -> Remove the file on the box - addChange(boxFile.path(), "remove"); - } - - // Do nothing - return Q(); - })); - }).then(function() { - // Update entries and create new entries - return Q.all(_.map(localEntries, function(localEntry) { - var entryIsDir = localEntry.mime == MIME_DIRECTORY; - var boxFile = _.find(boxEntries, function(boxFile) { - return localEntry.name == boxFile.get("name"); - }); - - if (!boxFile) { - // Create file - if (!entryIsDir) { - addChange(localEntry._fullPath, "create"); - } else { - addChange(localEntry._fullPath, "mkdir"); - } - } else if (!entryIsDir && boxFile.get("mtime") < localEntry.mtime) { - // Check modification - return readFile(localEntry._fullPath).then(function(content) { - return boxFile.read().then(function(vfsContent) { - if (vfsContent == content) { - // Same content - return Q(); - } - addChange(localEntry._fullPath, "write", { - 'content': content - }); - }) - }); - } - - if (entryIsDir) { - return getDirChanges(localEntry._fullPath); - } - - // Do nothing - return Q(); - })); - }).fail(function(err) { - logger.error("Error during sync: ", err); - }); - }; - - return operations.start("files.sync.changes", function(op) { - return getDirChanges("/").then(function() { - return Q(changes); - }); - }, { - title: "Calculating Offline Changes" - }); - }); - - /* - * Sync a file in the box fs with the local fs - * - * this will download the files and saved them in the localfs - */ - var syncFileBoxToLocal = needFsReady(function() { - var box = require("core/box"); - - var doSync = function(fp) { - var path = fp.path(); - if (isIgnoredFile(path)) return Q(); - - logger.log("sync:box->local:", path); - - if (fp.isDirectory()) { - // Create the directory - return createDirectory(path).then(function() { - // List subfiles - return fp.listdir(); - }).then(function(files) { - // Recursively sync files and directory - return Q.all(_.map(files, function(f) { - return doSync(f); - })); - }); - } else { - // Read file content - return fp.read().then(function(content) { - // Write file content - return writeFile(path, content); - }); - } - }; - return operations.start("files.sync.download", function(op) { - logger.warn("Start sync: box->local"); - - return listDir("/", false).then(function(rootFiles) { - return Q.all(_.map(rootFiles, function(fp) { - return remove("/"+fp.name, false); - })); - }).then(function() { - return doSync(box.root); - }, function() { - return doSync(box.root) - }).then(function() { - changes.reset([]); - logger.warn("Finished sync: box->local"); - }); - }, { - title: "Updating Offline Cache" - }); - }); - - /* - * Global sync: - * -> if never sync: download everything - * -> if already sync: upload changes and download last changes - */ - var sync = needFsReady(function(options) { - options = _.defaults({}, options || {}, { - - }); - - var previousChanges = changes.size(); - - if (hr.Offline.isConnected()) { - var endT, startT = Date.now(); - return openFile("/").then(function(infos) { - return getChanges(); - }, function() { - return createDirectory("/"); - }).then(function() { - if (changes.size() > 0) { - if (changes.size() == previousChanges) return Q.reject(new Error("Offline changes not synced")); - alerts.show(changes.size()+" changes made offline need to be synced manually", 5000); - return Q.reject(new Error("Offline changes not synced")); - } - return syncFileBoxToLocal(); - }).then(function() { - //Calcul duration - endT = Date.now(); - syncDuration = _.max([endT - startT, 5000]); - updateAutoSync(); - return syncDuration; - }, function(err) { - logger.error("Sync error:", err); - }); - } else { - return Q.reject(new Error("Can't synchronize when offline")); - } - }); - - /* - * Auto sync allow to resync the localfs every interval - */ - var autoSync = null; - var updateAutoSync = function() { - syncDuration = _.max([syncDuration, 5*60*1000]); - logger.log("sync took ", syncDuration/1000,"seconds"); - autoSync = _.throttle(function() { - sync(); - }, 2*syncDuration); - }; - updateAutoSync(); - - return { - 'changes': changes, - 'urlToPath': urlToPath, - 'init': initFs, - 'ls': listDir, - 'create': createFile, - 'mkdir': createDirectory, - 'write': writeFile, - 'read': readFile, - 'mv': move, - 'rm': remove, - 'reset': syncFileBoxToLocal, - 'sync': sync, - 'autoSync': function() { - return autoSync(); - }, - 'enableSync': enableSync, - 'filer': filer, - 'syncDuration': syncDuration, - 'setIgnoredFiles': setIgnoredFiles - }; -}); \ No newline at end of file diff --git a/client/core/operations.js b/client/core/operations.js deleted file mode 100644 index 93892c0d..00000000 --- a/client/core/operations.js +++ /dev/null @@ -1,6 +0,0 @@ -define([ - 'views/operations/manager' -], function (Operations) { - var operations = new Operations(); - return operations; -}); \ No newline at end of file diff --git a/client/core/panels.js b/client/core/panels.js deleted file mode 100644 index b3aa8e03..00000000 --- a/client/core/panels.js +++ /dev/null @@ -1,6 +0,0 @@ -define([ - 'views/panels/manager' -], function (PanelsView) { - var panels = new PanelsView(); - return panels; -}); \ No newline at end of file diff --git a/client/core/search.js b/client/core/search.js deleted file mode 100644 index 25cd058e..00000000 --- a/client/core/search.js +++ /dev/null @@ -1,85 +0,0 @@ -define([ - 'hr/hr', - 'hr/dom', - 'hr/utils', - 'core/user', - 'core/settings' -],function(hr, $, _, user, settings) { - var logging = hr.Logger.addNamespace("search"); - - var Search = hr.Class.extend({ - defaults: {}, - - // Constructor - initialize: function(){ - Search.__super__.initialize.apply(this, arguments); - - // Search handlers - this.handlers = {}; - - // Settings - this.settings = settings.add({ - 'namespace': "search", - 'title': "Search", - 'fields': {} - }); - - return this; - }, - - /* - * Add a search handler - * @name: name for the search handler - * @getter: method which returns a promise with results - */ - handler: function(infos, getter) { - if (!infos.id || !infos.title) { - throw new Error("Need 'id' and 'title' to define a search handler"); - } - - // Define handler - this.handlers[infos.id] = _.defaults({ - 'getter': getter - }, infos, {}); - - // Define settings - this.settings.setField(infos.id, { - 'label': infos.title, - 'type': "checkbox", - 'default': true - }); - - logging.log("add search handler", infos.id); - - return this; - }, - - /* - * Search by query - */ - query: function(query, callback, context) { - callback = _.bind(callback, context); - - _.each(this.handlers, function(handler, name) { - if (!user.get("settings.search."+name, true)) { - return; - } - - var addResults = function(results) { - callback({ - 'title': handler.title - }, results, query); - }; - var d = handler.getter(query); - - if (_.isArray(d)) { - addResults(d); - } else { - d.done(addResults); - } - }, this); - } - }); - - return (new Search()); -}); \ No newline at end of file diff --git a/client/core/search/files.js b/client/core/search/files.js deleted file mode 100644 index ee877152..00000000 --- a/client/core/search/files.js +++ /dev/null @@ -1,27 +0,0 @@ -define([ - 'hr/promise', - 'hr/utils', - 'hr/hr', - 'core/box', - 'core/search', - 'core/files' -], function(Q, _, hr, box, search, files) { - // Search for files - search.handler({ - 'id': "files", - 'title': "Files" - }, function(query) { - return box.searchFiles(query).then(function(data) { - return Q(_.map(data.files, _.bind(function(path) { - var filename = _.last(path.split("/")); - if (filename.length == 0) filename = path; - return { - "text": filename, - "callback": _.bind(function() { - files.open(path); - }, this) - }; - }, this))); - }); - }); -}); \ No newline at end of file diff --git a/client/core/search/tags.js b/client/core/search/tags.js deleted file mode 100644 index 71266162..00000000 --- a/client/core/search/tags.js +++ /dev/null @@ -1,29 +0,0 @@ -define([ - 'hr/promise', - 'hr/utils', - 'hr/hr', - 'core/backends/rpc', - 'core/search', - 'core/files' -], function(Q, _, hr, rpc, search, files) { - var normalizeTag = function(tag) { - return { - "text": tag.name, - "callback": _.bind(function() { - files.open(tag.file); - }, this) - }; - }; - - // Search for files - search.handler({ - 'id': "tags", - 'title': "Tags" - }, function(query) { - return rpc.execute("codecomplete/get", { - 'query': query - }).then(function(data) { - return _.map(data.results, normalizeTag); - }); - }); -}); \ No newline at end of file diff --git a/client/core/session.js b/client/core/session.js deleted file mode 100644 index 3d843db9..00000000 --- a/client/core/session.js +++ /dev/null @@ -1,66 +0,0 @@ -define([ - "hr/utils", - "hr/hr", - "core/user", - "core/box", - "core/addons", - "core/collaborators", - "core/backends/rpc", - "core/localfs" -], function(_, hr, user, box, addons, collaborators, rpc, localfs) { - // Extend template context - hr.Template.extendContext({ - 'session': { - 'user': user, - 'box': box, - 'addons': addons, - 'collaborators': collaborators - } - }); - - // Redefine check for connection status - hr.Offline.check = function() { - return rpc.execute("box/ping").then(function(data) { - hr.Offline.setState(data.ping == true); - if (!hr.Offline.isConnected()) { - return Q.reject(new Error("No connected")); - } - }, function() { - hr.Offline.setState(false); - }) - }; - - return { - // Prepare session - prepare: function() { - return hr.Offline.check().then(function() { - return box.status(); - }).then(function() { - return localfs.init(box.get("name")); - }); - }, - - // Start session - start: function(email, token) { - var that = this; - - return box.auth({ - 'email': email, - 'token': token - }, user).then(function() { - // Get installed addons - return addons.getInstalled(); - }).then(function() { - // Get collaborators - return collaborators.getCollaborators(); - }); - }, - - // Logout - exit: function() { - hr.Cookies.remove("email"); - hr.Cookies.remove("token"); - location.reload(); - } - }; -}); \ No newline at end of file diff --git a/client/core/settings.js b/client/core/settings.js deleted file mode 100644 index e92c973e..00000000 --- a/client/core/settings.js +++ /dev/null @@ -1,78 +0,0 @@ -define([ - 'hr/hr', - 'models/command', - 'core/user', - 'views/settings/base' -], function (hr, Command, user, SettingsPageView) { - - /* - * This module define a unify way - * to manage user settings. - */ - - var logging = hr.Logger.addNamespace("settings"); - - var settings = { - sections: {}, - - /* - * Define a new settings tab - * Tab: View for the tab - */ - add: function(Tab, options) { - var section, namespace; - if (!_.isFunction(Tab)) { - options = Tab; - Tab = SettingsPageView; - } - - var tab = new Tab(options); - - var namespace = tab.namespace || "main"; - - logging.log("add settings tab", namespace); - settings.sections[namespace] = tab; - - var defaults = options.defaults || {}; - var currentValues = user.get("settings."+namespace, {}); - currentValues = _.defaults(currentValues, defaults); - user.set("settings."+namespace, currentValues); - - return tab; - }, - - /* - * For all tabs - */ - each: function(callback, context) { - _.each(settings.sections, callback, context); - }, - - /* - * Save settings - */ - save: function() { - var data = {}; - this.each(function(tab) { - data[tab.namespace] = tab.submit(); - }); - return user.saveSettings(_.extend({}, user.get("settings"), data)); - }, - - /* - * Open a settings page - */ - open: function(page) { - Command.run("settings", page); - }, - - /* - * User settings - */ - user: function(namespace) { - return user.settings(namespace); - } - }; - - return settings; -}); \ No newline at end of file diff --git a/client/core/tabs.js b/client/core/tabs.js deleted file mode 100644 index 561e1ec6..00000000 --- a/client/core/tabs.js +++ /dev/null @@ -1,6 +0,0 @@ -define([ - 'views/tabs/manager' -], function (TabsView) { - var tabs = new TabsView(); - return tabs; -}); \ No newline at end of file diff --git a/client/core/themes.js b/client/core/themes.js deleted file mode 100644 index 43d3443d..00000000 --- a/client/core/themes.js +++ /dev/null @@ -1,148 +0,0 @@ -define([ - 'hr/hr', - 'hr/dom', - 'hr/utils', - 'utils/css', - 'core/settings', - 'core/user' -], function (hr, $, _, css, settings, user) { - var logger = hr.Logger.addNamespace("themes"); - - - // User settings - var userSettings = user.settings("themes"); - - // Map of themes - var currentTheme = null; - var themes = {}; - - // CSS dom - var $css = $(" - - -

      Contact information

      -

      - E-mail: contact@friendco.de
      - Website: www.codebox.io -

      - -

      License

      -

      - Copyright 2014 FriendCode 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. -

      - - \ No newline at end of file diff --git a/desktop/css/style.css b/desktop/css/style.css deleted file mode 100644 index e330666b..00000000 --- a/desktop/css/style.css +++ /dev/null @@ -1,120 +0,0 @@ -body { - font-family: "Lucida Grande", "Lucida Sans Unicode", sans-serif; - font-size: 14px; - line-height: 1.428571429; - color: #111; - background: #EDEDED; -} - -* { - box-sizing: border-box; - margin: 0px; - padding: 0px; -} - -/* Body */ -#body { - position: fixed; - top: 0px; - bottom: 76px; - right: 0px; - left: 0px; - padding: 5px 10px; - overflow-y: auto; - background: #EDEDED; - border-bottom: 1px solid #959595; -} - -/* Alert */ -.alert { - color: #8a6d3b; - background-color: #fcf8e3; - border: 1px solid #eadbbc; - padding: 15px; - margin-bottom: 20px; - border-radius: 4px; - cursor: pointer; -} - -/* List of projects */ -#projects { - list-style: none; -} -#projects .empty-message { - text-transform: uppercase;; - text-align: center; - margin: 150px 20px; - font-size: 18px; - color: #ccc; -} - -#projects .project { - display: block; - background: #f5f5f5; - box-shadow: 0px 1px #fff inset; - border: 1px solid #ccc; - color: #333; - padding: 10px; - width: 100%; - height: 70px; - margin: 5px 0px; - overflow: hidden; - cursor: pointer; - color: #888; - border-radius: 4px; - font-size: 12px; -} -#projects .project:hover { - -} -#projects .project .project-title { - text-transform: uppercase; - font-size: 20px; - color: #555; - margin-bottom: 5px; -} -#projects .project .project-icon { - float: left; - margin: 9px 10px 0px 2px; - width: 32px; - -webkit-filter: grayscale(1); -} -#projects hr { - margin: 20px 10px; - border: 0px; - border-bottom: 1px solid #d8d8d8; - display: block; -} - -#footer { - position: fixed; - bottom: 0px; - right: 0px; - left: 0px; - text-align: center; -} - -#footer .btn { - margin: 10px; - display: inline-block; - padding: 12px 10px; - text-align: center; - font-size: 30px; - line-height: 30px; - color: #000; - border-radius: 4px; - border: 1px solid #9a9a9a; - background-image: -webkit-gradient(linear,left bottom,left top,color-stop(0, #EBEBEB),color-stop(0.5, #ECECEC),color-stop(0.5, #F3F3F3),color-stop(1, #FFFFFF)); - box-shadow: inset 0 1px 0 rgba(255,255,255,1), 0 1px 0 rgba(0,0,0,0.09); - text-decoration: none; - font-weight: bold; - color: #555; -} - -#footer #open-new { - width: 62%; -} - -#footer #open-menu { - width: 20%; -} diff --git a/desktop/icons/128.png b/desktop/icons/128.png deleted file mode 100644 index 594c7c1d..00000000 Binary files a/desktop/icons/128.png and /dev/null differ diff --git a/desktop/icons/folder.png b/desktop/icons/folder.png deleted file mode 100644 index 16a55f4c..00000000 Binary files a/desktop/icons/folder.png and /dev/null differ diff --git a/desktop/icons/mac.icns b/desktop/icons/mac.icns deleted file mode 100644 index c637f1bc..00000000 Binary files a/desktop/icons/mac.icns and /dev/null differ diff --git a/desktop/ide.html b/desktop/ide.html deleted file mode 100644 index 5c3cf157..00000000 --- a/desktop/ide.html +++ /dev/null @@ -1,27 +0,0 @@ - - - Codebox - - - - - - \ No newline at end of file diff --git a/desktop/index.html b/desktop/index.html deleted file mode 100644 index 23e8bdf9..00000000 --- a/desktop/index.html +++ /dev/null @@ -1,25 +0,0 @@ - - - Codebox - - - - - - -
      - - - -
        -
        - - - - - - - \ No newline at end of file diff --git a/desktop/js/dirname.js b/desktop/js/dirname.js deleted file mode 100644 index e9a58480..00000000 --- a/desktop/js/dirname.js +++ /dev/null @@ -1,4 +0,0 @@ -// We need to use this hack -// to workaround a shortcoming of node-webkit -exports.dirname = __dirname; - diff --git a/desktop/js/ide.js b/desktop/js/ide.js deleted file mode 100644 index e69aa64a..00000000 --- a/desktop/js/ide.js +++ /dev/null @@ -1,84 +0,0 @@ -// Port allocation -var gui = require('nw.gui'); -var lodash = require('lodash'); -var qClass = require('qpatch').qClass; -var harbor = qClass(require('harbor')); -var ports = new harbor(19000, 20000); - -// Local requires -var codebox = require('../index.js'); - -var win = gui.Window.get(); - -var startCodebox = function(path) { - console.log("start ide in ", path); - - // Claim port - return ports.claim(path) - .then(function(port) { - // Setup url - var url = "http://localhost:"+port; - return [port, url]; - }) - .spread(function (port, url) { - return codebox.start({ - 'root': path, - 'server': { - 'port': port - }, - 'addons': { - 'blacklist': ["cb.offline"] - } - }) - .then(function(box) { - return url+"?_t="+Date.now(); - }); - }) - .then(function(url) { - $("body").append(""); - }); -}; - -var queryString = function () { - // This function is anonymous, is executed immediately and - // the return value is assigned to QueryString! - var query_string = {}; - var query = window.location.search.substring(1); - var vars = query.split("&"); - for (var i=0;i type pairs - class2type = {}, - - // List of deleted data cache ids, so we can reuse them - core_deletedIds = [], - - core_version = "2.0.1", - - // Save a reference to some core methods - core_concat = core_deletedIds.concat, - core_push = core_deletedIds.push, - core_slice = core_deletedIds.slice, - core_indexOf = core_deletedIds.indexOf, - core_toString = class2type.toString, - core_hasOwn = class2type.hasOwnProperty, - core_trim = core_version.trim, - - // Define a local copy of jQuery - jQuery = function( selector, context ) { - // The jQuery object is actually just the init constructor 'enhanced' - return new jQuery.fn.init( selector, context, rootjQuery ); - }, - - // Used for matching numbers - core_pnum = /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source, - - // Used for splitting on whitespace - core_rnotwhite = /\S+/g, - - // A simple way to check for HTML strings - // Prioritize #id over to avoid XSS via location.hash (#9521) - // Strict HTML recognition (#11290: must start with <) - rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/, - - // Match a standalone tag - rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/, - - // Matches dashed string for camelizing - rmsPrefix = /^-ms-/, - rdashAlpha = /-([\da-z])/gi, - - // Used by jQuery.camelCase as callback to replace() - fcamelCase = function( all, letter ) { - return letter.toUpperCase(); - }, - - // The ready event handler and self cleanup method - completed = function() { - document.removeEventListener( "DOMContentLoaded", completed, false ); - window.removeEventListener( "load", completed, false ); - jQuery.ready(); - }; - -jQuery.fn = jQuery.prototype = { - // The current version of jQuery being used - jquery: core_version, - - constructor: jQuery, - init: function( selector, context, rootjQuery ) { - var match, elem; - - // HANDLE: $(""), $(null), $(undefined), $(false) - if ( !selector ) { - return this; - } - - // Handle HTML strings - if ( typeof selector === "string" ) { - if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) { - // Assume that strings that start and end with <> are HTML and skip the regex check - match = [ null, selector, null ]; - - } else { - match = rquickExpr.exec( selector ); - } - - // Match html or make sure no context is specified for #id - if ( match && (match[1] || !context) ) { - - // HANDLE: $(html) -> $(array) - if ( match[1] ) { - context = context instanceof jQuery ? context[0] : context; - - // scripts is true for back-compat - jQuery.merge( this, jQuery.parseHTML( - match[1], - context && context.nodeType ? context.ownerDocument || context : document, - true - ) ); - - // HANDLE: $(html, props) - if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) { - for ( match in context ) { - // Properties of context are called as methods if possible - if ( jQuery.isFunction( this[ match ] ) ) { - this[ match ]( context[ match ] ); - - // ...and otherwise set as attributes - } else { - this.attr( match, context[ match ] ); - } - } - } - - return this; - - // HANDLE: $(#id) - } else { - elem = document.getElementById( match[2] ); - - // Check parentNode to catch when Blackberry 4.6 returns - // nodes that are no longer in the document #6963 - if ( elem && elem.parentNode ) { - // Inject the element directly into the jQuery object - this.length = 1; - this[0] = elem; - } - - this.context = document; - this.selector = selector; - return this; - } - - // HANDLE: $(expr, $(...)) - } else if ( !context || context.jquery ) { - return ( context || rootjQuery ).find( selector ); - - // HANDLE: $(expr, context) - // (which is just equivalent to: $(context).find(expr) - } else { - return this.constructor( context ).find( selector ); - } - - // HANDLE: $(DOMElement) - } else if ( selector.nodeType ) { - this.context = this[0] = selector; - this.length = 1; - return this; - - // HANDLE: $(function) - // Shortcut for document ready - } else if ( jQuery.isFunction( selector ) ) { - return rootjQuery.ready( selector ); - } - - if ( selector.selector !== undefined ) { - this.selector = selector.selector; - this.context = selector.context; - } - - return jQuery.makeArray( selector, this ); - }, - - // Start with an empty selector - selector: "", - - // The default length of a jQuery object is 0 - length: 0, - - toArray: function() { - return core_slice.call( this ); - }, - - // Get the Nth element in the matched element set OR - // Get the whole matched element set as a clean array - get: function( num ) { - return num == null ? - - // Return a 'clean' array - this.toArray() : - - // Return just the object - ( num < 0 ? this[ this.length + num ] : this[ num ] ); - }, - - // Take an array of elements and push it onto the stack - // (returning the new matched element set) - pushStack: function( elems ) { - - // Build a new jQuery matched element set - var ret = jQuery.merge( this.constructor(), elems ); - - // Add the old object onto the stack (as a reference) - ret.prevObject = this; - ret.context = this.context; - - // Return the newly-formed element set - return ret; - }, - - // Execute a callback for every element in the matched set. - // (You can seed the arguments with an array of args, but this is - // only used internally.) - each: function( callback, args ) { - return jQuery.each( this, callback, args ); - }, - - ready: function( fn ) { - // Add the callback - jQuery.ready.promise().done( fn ); - - return this; - }, - - slice: function() { - return this.pushStack( core_slice.apply( this, arguments ) ); - }, - - first: function() { - return this.eq( 0 ); - }, - - last: function() { - return this.eq( -1 ); - }, - - eq: function( i ) { - var len = this.length, - j = +i + ( i < 0 ? len : 0 ); - return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] ); - }, - - map: function( callback ) { - return this.pushStack( jQuery.map(this, function( elem, i ) { - return callback.call( elem, i, elem ); - })); - }, - - end: function() { - return this.prevObject || this.constructor(null); - }, - - // For internal use only. - // Behaves like an Array's method, not like a jQuery method. - push: core_push, - sort: [].sort, - splice: [].splice -}; - -// Give the init function the jQuery prototype for later instantiation -jQuery.fn.init.prototype = jQuery.fn; - -jQuery.extend = jQuery.fn.extend = function() { - var options, name, src, copy, copyIsArray, clone, - target = arguments[0] || {}, - i = 1, - length = arguments.length, - deep = false; - - // Handle a deep copy situation - if ( typeof target === "boolean" ) { - deep = target; - target = arguments[1] || {}; - // skip the boolean and the target - i = 2; - } - - // Handle case when target is a string or something (possible in deep copy) - if ( typeof target !== "object" && !jQuery.isFunction(target) ) { - target = {}; - } - - // extend jQuery itself if only one argument is passed - if ( length === i ) { - target = this; - --i; - } - - for ( ; i < length; i++ ) { - // Only deal with non-null/undefined values - if ( (options = arguments[ i ]) != null ) { - // Extend the base object - for ( name in options ) { - src = target[ name ]; - copy = options[ name ]; - - // Prevent never-ending loop - if ( target === copy ) { - continue; - } - - // Recurse if we're merging plain objects or arrays - if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { - if ( copyIsArray ) { - copyIsArray = false; - clone = src && jQuery.isArray(src) ? src : []; - - } else { - clone = src && jQuery.isPlainObject(src) ? src : {}; - } - - // Never move original objects, clone them - target[ name ] = jQuery.extend( deep, clone, copy ); - - // Don't bring in undefined values - } else if ( copy !== undefined ) { - target[ name ] = copy; - } - } - } - } - - // Return the modified object - return target; -}; - -jQuery.extend({ - // Unique for each copy of jQuery on the page - expando: "jQuery" + ( core_version + Math.random() ).replace( /\D/g, "" ), - - noConflict: function( deep ) { - if ( window.$ === jQuery ) { - window.$ = _$; - } - - if ( deep && window.jQuery === jQuery ) { - window.jQuery = _jQuery; - } - - return jQuery; - }, - - // Is the DOM ready to be used? Set to true once it occurs. - isReady: false, - - // A counter to track how many items to wait for before - // the ready event fires. See #6781 - readyWait: 1, - - // Hold (or release) the ready event - holdReady: function( hold ) { - if ( hold ) { - jQuery.readyWait++; - } else { - jQuery.ready( true ); - } - }, - - // Handle when the DOM is ready - ready: function( wait ) { - - // Abort if there are pending holds or we're already ready - if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { - return; - } - - // Remember that the DOM is ready - jQuery.isReady = true; - - // If a normal DOM Ready event fired, decrement, and wait if need be - if ( wait !== true && --jQuery.readyWait > 0 ) { - return; - } - - // If there are functions bound, to execute - readyList.resolveWith( document, [ jQuery ] ); - - // Trigger any bound ready events - if ( jQuery.fn.trigger ) { - jQuery( document ).trigger("ready").off("ready"); - } - }, - - // See test/unit/core.js for details concerning isFunction. - // Since version 1.3, DOM methods and functions like alert - // aren't supported. They return false on IE (#2968). - isFunction: function( obj ) { - return jQuery.type(obj) === "function"; - }, - - isArray: Array.isArray, - - isWindow: function( obj ) { - return obj != null && obj === obj.window; - }, - - isNumeric: function( obj ) { - return !isNaN( parseFloat(obj) ) && isFinite( obj ); - }, - - type: function( obj ) { - if ( obj == null ) { - return String( obj ); - } - // Support: Safari <= 5.1 (functionish RegExp) - return typeof obj === "object" || typeof obj === "function" ? - class2type[ core_toString.call(obj) ] || "object" : - typeof obj; - }, - - isPlainObject: function( obj ) { - // Not plain objects: - // - Any object or value whose internal [[Class]] property is not "[object Object]" - // - DOM nodes - // - window - if ( jQuery.type( obj ) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { - return false; - } - - // Support: Firefox <20 - // The try/catch suppresses exceptions thrown when attempting to access - // the "constructor" property of certain host objects, ie. |window.location| - // https://bugzilla.mozilla.org/show_bug.cgi?id=814622 - try { - if ( obj.constructor && - !core_hasOwn.call( obj.constructor.prototype, "isPrototypeOf" ) ) { - return false; - } - } catch ( e ) { - return false; - } - - // If the function hasn't returned already, we're confident that - // |obj| is a plain object, created by {} or constructed with new Object - return true; - }, - - isEmptyObject: function( obj ) { - var name; - for ( name in obj ) { - return false; - } - return true; - }, - - error: function( msg ) { - throw new Error( msg ); - }, - - // data: string of html - // context (optional): If specified, the fragment will be created in this context, defaults to document - // keepScripts (optional): If true, will include scripts passed in the html string - parseHTML: function( data, context, keepScripts ) { - if ( !data || typeof data !== "string" ) { - return null; - } - if ( typeof context === "boolean" ) { - keepScripts = context; - context = false; - } - context = context || document; - - var parsed = rsingleTag.exec( data ), - scripts = !keepScripts && []; - - // Single tag - if ( parsed ) { - return [ context.createElement( parsed[1] ) ]; - } - - parsed = jQuery.buildFragment( [ data ], context, scripts ); - - if ( scripts ) { - jQuery( scripts ).remove(); - } - - return jQuery.merge( [], parsed.childNodes ); - }, - - parseJSON: JSON.parse, - - // Cross-browser xml parsing - parseXML: function( data ) { - var xml, tmp; - if ( !data || typeof data !== "string" ) { - return null; - } - - // Support: IE9 - try { - tmp = new DOMParser(); - xml = tmp.parseFromString( data , "text/xml" ); - } catch ( e ) { - xml = undefined; - } - - if ( !xml || xml.getElementsByTagName( "parsererror" ).length ) { - jQuery.error( "Invalid XML: " + data ); - } - return xml; - }, - - noop: function() {}, - - // Evaluates a script in a global context - globalEval: function( code ) { - var script, - indirect = eval; - - code = jQuery.trim( code ); - - if ( code ) { - // If the code includes a valid, prologue position - // strict mode pragma, execute code by injecting a - // script tag into the document. - if ( code.indexOf("use strict") === 1 ) { - script = document.createElement("script"); - script.text = code; - document.head.appendChild( script ).parentNode.removeChild( script ); - } else { - // Otherwise, avoid the DOM node creation, insertion - // and removal by using an indirect global eval - indirect( code ); - } - } - }, - - // Convert dashed to camelCase; used by the css and data modules - // Microsoft forgot to hump their vendor prefix (#9572) - camelCase: function( string ) { - return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); - }, - - nodeName: function( elem, name ) { - return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); - }, - - // args is for internal usage only - each: function( obj, callback, args ) { - var value, - i = 0, - length = obj.length, - isArray = isArraylike( obj ); - - if ( args ) { - if ( isArray ) { - for ( ; i < length; i++ ) { - value = callback.apply( obj[ i ], args ); - - if ( value === false ) { - break; - } - } - } else { - for ( i in obj ) { - value = callback.apply( obj[ i ], args ); - - if ( value === false ) { - break; - } - } - } - - // A special, fast, case for the most common use of each - } else { - if ( isArray ) { - for ( ; i < length; i++ ) { - value = callback.call( obj[ i ], i, obj[ i ] ); - - if ( value === false ) { - break; - } - } - } else { - for ( i in obj ) { - value = callback.call( obj[ i ], i, obj[ i ] ); - - if ( value === false ) { - break; - } - } - } - } - - return obj; - }, - - trim: function( text ) { - return text == null ? "" : core_trim.call( text ); - }, - - // results is for internal usage only - makeArray: function( arr, results ) { - var ret = results || []; - - if ( arr != null ) { - if ( isArraylike( Object(arr) ) ) { - jQuery.merge( ret, - typeof arr === "string" ? - [ arr ] : arr - ); - } else { - core_push.call( ret, arr ); - } - } - - return ret; - }, - - inArray: function( elem, arr, i ) { - return arr == null ? -1 : core_indexOf.call( arr, elem, i ); - }, - - merge: function( first, second ) { - var l = second.length, - i = first.length, - j = 0; - - if ( typeof l === "number" ) { - for ( ; j < l; j++ ) { - first[ i++ ] = second[ j ]; - } - } else { - while ( second[j] !== undefined ) { - first[ i++ ] = second[ j++ ]; - } - } - - first.length = i; - - return first; - }, - - grep: function( elems, callback, inv ) { - var retVal, - ret = [], - i = 0, - length = elems.length; - inv = !!inv; - - // Go through the array, only saving the items - // that pass the validator function - for ( ; i < length; i++ ) { - retVal = !!callback( elems[ i ], i ); - if ( inv !== retVal ) { - ret.push( elems[ i ] ); - } - } - - return ret; - }, - - // arg is for internal usage only - map: function( elems, callback, arg ) { - var value, - i = 0, - length = elems.length, - isArray = isArraylike( elems ), - ret = []; - - // Go through the array, translating each of the items to their - if ( isArray ) { - for ( ; i < length; i++ ) { - value = callback( elems[ i ], i, arg ); - - if ( value != null ) { - ret[ ret.length ] = value; - } - } - - // Go through every key on the object, - } else { - for ( i in elems ) { - value = callback( elems[ i ], i, arg ); - - if ( value != null ) { - ret[ ret.length ] = value; - } - } - } - - // Flatten any nested arrays - return core_concat.apply( [], ret ); - }, - - // A global GUID counter for objects - guid: 1, - - // Bind a function to a context, optionally partially applying any - // arguments. - proxy: function( fn, context ) { - var tmp, args, proxy; - - if ( typeof context === "string" ) { - tmp = fn[ context ]; - context = fn; - fn = tmp; - } - - // Quick check to determine if target is callable, in the spec - // this throws a TypeError, but we will just return undefined. - if ( !jQuery.isFunction( fn ) ) { - return undefined; - } - - // Simulated bind - args = core_slice.call( arguments, 2 ); - proxy = function() { - return fn.apply( context || this, args.concat( core_slice.call( arguments ) ) ); - }; - - // Set the guid of unique handler to the same of original handler, so it can be removed - proxy.guid = fn.guid = fn.guid || jQuery.guid++; - - return proxy; - }, - - // Multifunctional method to get and set values of a collection - // The value/s can optionally be executed if it's a function - access: function( elems, fn, key, value, chainable, emptyGet, raw ) { - var i = 0, - length = elems.length, - bulk = key == null; - - // Sets many values - if ( jQuery.type( key ) === "object" ) { - chainable = true; - for ( i in key ) { - jQuery.access( elems, fn, i, key[i], true, emptyGet, raw ); - } - - // Sets one value - } else if ( value !== undefined ) { - chainable = true; - - if ( !jQuery.isFunction( value ) ) { - raw = true; - } - - if ( bulk ) { - // Bulk operations run against the entire set - if ( raw ) { - fn.call( elems, value ); - fn = null; - - // ...except when executing function values - } else { - bulk = fn; - fn = function( elem, key, value ) { - return bulk.call( jQuery( elem ), value ); - }; - } - } - - if ( fn ) { - for ( ; i < length; i++ ) { - fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) ); - } - } - } - - return chainable ? - elems : - - // Gets - bulk ? - fn.call( elems ) : - length ? fn( elems[0], key ) : emptyGet; - }, - - now: Date.now, - - // A method for quickly swapping in/out CSS properties to get correct calculations. - // Note: this method belongs to the css module but it's needed here for the support module. - // If support gets modularized, this method should be moved back to the css module. - swap: function( elem, options, callback, args ) { - var ret, name, - old = {}; - - // Remember the old values, and insert the new ones - for ( name in options ) { - old[ name ] = elem.style[ name ]; - elem.style[ name ] = options[ name ]; - } - - ret = callback.apply( elem, args || [] ); - - // Revert the old values - for ( name in options ) { - elem.style[ name ] = old[ name ]; - } - - return ret; - } -}); - -jQuery.ready.promise = function( obj ) { - if ( !readyList ) { - - readyList = jQuery.Deferred(); - - // Catch cases where $(document).ready() is called after the browser event has already occurred. - // we once tried to use readyState "interactive" here, but it caused issues like the one - // discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15 - if ( document.readyState === "complete" ) { - // Handle it asynchronously to allow scripts the opportunity to delay ready - setTimeout( jQuery.ready ); - - } else { - - // Use the handy event callback - document.addEventListener( "DOMContentLoaded", completed, false ); - - // A fallback to window.onload, that will always work - window.addEventListener( "load", completed, false ); - } - } - return readyList.promise( obj ); -}; - -// Populate the class2type map -jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) { - class2type[ "[object " + name + "]" ] = name.toLowerCase(); -}); - -function isArraylike( obj ) { - var length = obj.length, - type = jQuery.type( obj ); - - if ( jQuery.isWindow( obj ) ) { - return false; - } - - if ( obj.nodeType === 1 && length ) { - return true; - } - - return type === "array" || type !== "function" && - ( length === 0 || - typeof length === "number" && length > 0 && ( length - 1 ) in obj ); -} - -// All jQuery objects should point back to these -rootjQuery = jQuery(document); -/*! - * Sizzle CSS Selector Engine v1.9.4-pre - * http://sizzlejs.com/ - * - * Copyright 2013 jQuery Foundation, Inc. and other contributors - * Released under the MIT license - * http://jquery.org/license - * - * Date: 2013-05-15 - */ -(function( window, undefined ) { - -var i, - support, - cachedruns, - Expr, - getText, - isXML, - compile, - outermostContext, - sortInput, - - // Local document vars - setDocument, - document, - docElem, - documentIsHTML, - rbuggyQSA, - rbuggyMatches, - matches, - contains, - - // Instance-specific data - expando = "sizzle" + -(new Date()), - preferredDoc = window.document, - dirruns = 0, - done = 0, - classCache = createCache(), - tokenCache = createCache(), - compilerCache = createCache(), - hasDuplicate = false, - sortOrder = function() { return 0; }, - - // General-purpose constants - strundefined = typeof undefined, - MAX_NEGATIVE = 1 << 31, - - // Instance methods - hasOwn = ({}).hasOwnProperty, - arr = [], - pop = arr.pop, - push_native = arr.push, - push = arr.push, - slice = arr.slice, - // Use a stripped-down indexOf if we can't use a native one - indexOf = arr.indexOf || function( elem ) { - var i = 0, - len = this.length; - for ( ; i < len; i++ ) { - if ( this[i] === elem ) { - return i; - } - } - return -1; - }, - - booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped", - - // Regular expressions - - // Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace - whitespace = "[\\x20\\t\\r\\n\\f]", - // http://www.w3.org/TR/css3-syntax/#characters - characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+", - - // Loosely modeled on CSS identifier characters - // An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors - // Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier - identifier = characterEncoding.replace( "w", "w#" ), - - // Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors - attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace + - "*(?:([*^$|!~]?=)" + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]", - - // Prefer arguments quoted, - // then not containing pseudos/brackets, - // then attribute selectors/non-parenthetical expressions, - // then anything else - // These preferences are here to reduce the number of selectors - // needing tokenize in the PSEUDO preFilter - pseudos = ":(" + characterEncoding + ")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|" + attributes.replace( 3, 8 ) + ")*)|.*)\\)|)", - - // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter - rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), - - rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), - rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ), - - rsibling = new RegExp( whitespace + "*[+~]" ), - rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*)" + whitespace + "*\\]", "g" ), - - rpseudo = new RegExp( pseudos ), - ridentifier = new RegExp( "^" + identifier + "$" ), - - matchExpr = { - "ID": new RegExp( "^#(" + characterEncoding + ")" ), - "CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ), - "TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ), - "ATTR": new RegExp( "^" + attributes ), - "PSEUDO": new RegExp( "^" + pseudos ), - "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + - "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + - "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), - "bool": new RegExp( "^(?:" + booleans + ")$", "i" ), - // For use in libraries implementing .is() - // We use this for POS matching in `select` - "needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + - whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) - }, - - rnative = /^[^{]+\{\s*\[native \w/, - - // Easily-parseable/retrievable ID or TAG or CLASS selectors - rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, - - rinputs = /^(?:input|select|textarea|button)$/i, - rheader = /^h\d$/i, - - rescape = /'|\\/g, - - // CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters - runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ), - funescape = function( _, escaped, escapedWhitespace ) { - var high = "0x" + escaped - 0x10000; - // NaN means non-codepoint - // Support: Firefox - // Workaround erroneous numeric interpretation of +"0x" - return high !== high || escapedWhitespace ? - escaped : - // BMP codepoint - high < 0 ? - String.fromCharCode( high + 0x10000 ) : - // Supplemental Plane codepoint (surrogate pair) - String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); - }; - -// Optimize for push.apply( _, NodeList ) -try { - push.apply( - (arr = slice.call( preferredDoc.childNodes )), - preferredDoc.childNodes - ); - // Support: Android<4.0 - // Detect silently failing push.apply - arr[ preferredDoc.childNodes.length ].nodeType; -} catch ( e ) { - push = { apply: arr.length ? - - // Leverage slice if possible - function( target, els ) { - push_native.apply( target, slice.call(els) ); - } : - - // Support: IE<9 - // Otherwise append directly - function( target, els ) { - var j = target.length, - i = 0; - // Can't trust NodeList.length - while ( (target[j++] = els[i++]) ) {} - target.length = j - 1; - } - }; -} - -function Sizzle( selector, context, results, seed ) { - var match, elem, m, nodeType, - // QSA vars - i, groups, old, nid, newContext, newSelector; - - if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) { - setDocument( context ); - } - - context = context || document; - results = results || []; - - if ( !selector || typeof selector !== "string" ) { - return results; - } - - if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) { - return []; - } - - if ( documentIsHTML && !seed ) { - - // Shortcuts - if ( (match = rquickExpr.exec( selector )) ) { - // Speed-up: Sizzle("#ID") - if ( (m = match[1]) ) { - if ( nodeType === 9 ) { - elem = context.getElementById( m ); - // Check parentNode to catch when Blackberry 4.6 returns - // nodes that are no longer in the document #6963 - if ( elem && elem.parentNode ) { - // Handle the case where IE, Opera, and Webkit return items - // by name instead of ID - if ( elem.id === m ) { - results.push( elem ); - return results; - } - } else { - return results; - } - } else { - // Context is not a document - if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) && - contains( context, elem ) && elem.id === m ) { - results.push( elem ); - return results; - } - } - - // Speed-up: Sizzle("TAG") - } else if ( match[2] ) { - push.apply( results, context.getElementsByTagName( selector ) ); - return results; - - // Speed-up: Sizzle(".CLASS") - } else if ( (m = match[3]) && support.getElementsByClassName && context.getElementsByClassName ) { - push.apply( results, context.getElementsByClassName( m ) ); - return results; - } - } - - // QSA path - if ( support.qsa && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) { - nid = old = expando; - newContext = context; - newSelector = nodeType === 9 && selector; - - // qSA works strangely on Element-rooted queries - // We can work around this by specifying an extra ID on the root - // and working up from there (Thanks to Andrew Dupont for the technique) - // IE 8 doesn't work on object elements - if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { - groups = tokenize( selector ); - - if ( (old = context.getAttribute("id")) ) { - nid = old.replace( rescape, "\\$&" ); - } else { - context.setAttribute( "id", nid ); - } - nid = "[id='" + nid + "'] "; - - i = groups.length; - while ( i-- ) { - groups[i] = nid + toSelector( groups[i] ); - } - newContext = rsibling.test( selector ) && context.parentNode || context; - newSelector = groups.join(","); - } - - if ( newSelector ) { - try { - push.apply( results, - newContext.querySelectorAll( newSelector ) - ); - return results; - } catch(qsaError) { - } finally { - if ( !old ) { - context.removeAttribute("id"); - } - } - } - } - } - - // All others - return select( selector.replace( rtrim, "$1" ), context, results, seed ); -} - -/** - * For feature detection - * @param {Function} fn The function to test for native support - */ -function isNative( fn ) { - return rnative.test( fn + "" ); -} - -/** - * Create key-value caches of limited size - * @returns {Function(string, Object)} Returns the Object data after storing it on itself with - * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) - * deleting the oldest entry - */ -function createCache() { - var keys = []; - - function cache( key, value ) { - // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) - if ( keys.push( key += " " ) > Expr.cacheLength ) { - // Only keep the most recent entries - delete cache[ keys.shift() ]; - } - return (cache[ key ] = value); - } - return cache; -} - -/** - * Mark a function for special use by Sizzle - * @param {Function} fn The function to mark - */ -function markFunction( fn ) { - fn[ expando ] = true; - return fn; -} - -/** - * Support testing using an element - * @param {Function} fn Passed the created div and expects a boolean result - */ -function assert( fn ) { - var div = document.createElement("div"); - - try { - return !!fn( div ); - } catch (e) { - return false; - } finally { - // Remove from its parent by default - if ( div.parentNode ) { - div.parentNode.removeChild( div ); - } - // release memory in IE - div = null; - } -} - -/** - * Adds the same handler for all of the specified attrs - * @param {String} attrs Pipe-separated list of attributes - * @param {Function} handler The method that will be applied if the test fails - * @param {Boolean} test The result of a test. If true, null will be set as the handler in leiu of the specified handler - */ -function addHandle( attrs, handler, test ) { - attrs = attrs.split("|"); - var current, - i = attrs.length, - setHandle = test ? null : handler; - - while ( i-- ) { - // Don't override a user's handler - if ( !(current = Expr.attrHandle[ attrs[i] ]) || current === handler ) { - Expr.attrHandle[ attrs[i] ] = setHandle; - } - } -} - -/** - * Fetches boolean attributes by node - * @param {Element} elem - * @param {String} name - */ -function boolHandler( elem, name ) { - // XML does not need to be checked as this will not be assigned for XML documents - var val = elem.getAttributeNode( name ); - return val && val.specified ? - val.value : - elem[ name ] === true ? name.toLowerCase() : null; -} - -/** - * Fetches attributes without interpolation - * http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx - * @param {Element} elem - * @param {String} name - */ -function interpolationHandler( elem, name ) { - // XML does not need to be checked as this will not be assigned for XML documents - return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 ); -} - -/** - * Uses defaultValue to retrieve value in IE6/7 - * @param {Element} elem - * @param {String} name - */ -function valueHandler( elem ) { - // Ignore the value *property* on inputs by using defaultValue - // Fallback to Sizzle.attr by returning undefined where appropriate - // XML does not need to be checked as this will not be assigned for XML documents - if ( elem.nodeName.toLowerCase() === "input" ) { - return elem.defaultValue; - } -} - -/** - * Checks document order of two siblings - * @param {Element} a - * @param {Element} b - * @returns Returns -1 if a precedes b, 1 if a follows b - */ -function siblingCheck( a, b ) { - var cur = b && a, - diff = cur && a.nodeType === 1 && b.nodeType === 1 && - ( ~b.sourceIndex || MAX_NEGATIVE ) - - ( ~a.sourceIndex || MAX_NEGATIVE ); - - // Use IE sourceIndex if available on both nodes - if ( diff ) { - return diff; - } - - // Check if b follows a - if ( cur ) { - while ( (cur = cur.nextSibling) ) { - if ( cur === b ) { - return -1; - } - } - } - - return a ? 1 : -1; -} - -/** - * Returns a function to use in pseudos for input types - * @param {String} type - */ -function createInputPseudo( type ) { - return function( elem ) { - var name = elem.nodeName.toLowerCase(); - return name === "input" && elem.type === type; - }; -} - -/** - * Returns a function to use in pseudos for buttons - * @param {String} type - */ -function createButtonPseudo( type ) { - return function( elem ) { - var name = elem.nodeName.toLowerCase(); - return (name === "input" || name === "button") && elem.type === type; - }; -} - -/** - * Returns a function to use in pseudos for positionals - * @param {Function} fn - */ -function createPositionalPseudo( fn ) { - return markFunction(function( argument ) { - argument = +argument; - return markFunction(function( seed, matches ) { - var j, - matchIndexes = fn( [], seed.length, argument ), - i = matchIndexes.length; - - // Match elements found at the specified indexes - while ( i-- ) { - if ( seed[ (j = matchIndexes[i]) ] ) { - seed[j] = !(matches[j] = seed[j]); - } - } - }); - }); -} - -/** - * Detect xml - * @param {Element|Object} elem An element or a document - */ -isXML = Sizzle.isXML = function( elem ) { - // documentElement is verified for cases where it doesn't yet exist - // (such as loading iframes in IE - #4833) - var documentElement = elem && (elem.ownerDocument || elem).documentElement; - return documentElement ? documentElement.nodeName !== "HTML" : false; -}; - -// Expose support vars for convenience -support = Sizzle.support = {}; - -/** - * Sets document-related variables once based on the current document - * @param {Element|Object} [doc] An element or document object to use to set the document - * @returns {Object} Returns the current document - */ -setDocument = Sizzle.setDocument = function( node ) { - var doc = node ? node.ownerDocument || node : preferredDoc; - - // If no document and documentElement is available, return - if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) { - return document; - } - - // Set our document - document = doc; - docElem = doc.documentElement; - - // Support tests - documentIsHTML = !isXML( doc ); - - /* Attributes - ---------------------------------------------------------------------- */ - - // Support: IE<8 - // Verify that getAttribute really returns attributes and not properties (excepting IE8 booleans) - support.attributes = assert(function( div ) { - - // Support: IE<8 - // Prevent attribute/property "interpolation" - div.innerHTML = ""; - addHandle( "type|href|height|width", interpolationHandler, div.firstChild.getAttribute("href") === "#" ); - - // Support: IE<9 - // Use getAttributeNode to fetch booleans when getAttribute lies - addHandle( booleans, boolHandler, div.getAttribute("disabled") == null ); - - div.className = "i"; - return !div.getAttribute("className"); - }); - - // Support: IE<9 - // Retrieving value should defer to defaultValue - support.input = assert(function( div ) { - div.innerHTML = ""; - div.firstChild.setAttribute( "value", "" ); - return div.firstChild.getAttribute( "value" ) === ""; - }); - - // IE6/7 still return empty string for value, - // but are actually retrieving the property - addHandle( "value", valueHandler, support.attributes && support.input ); - - /* getElement(s)By* - ---------------------------------------------------------------------- */ - - // Check if getElementsByTagName("*") returns only elements - support.getElementsByTagName = assert(function( div ) { - div.appendChild( doc.createComment("") ); - return !div.getElementsByTagName("*").length; - }); - - // Check if getElementsByClassName can be trusted - support.getElementsByClassName = assert(function( div ) { - div.innerHTML = "
        "; - - // Support: Safari<4 - // Catch class over-caching - div.firstChild.className = "i"; - // Support: Opera<10 - // Catch gEBCN failure to find non-leading classes - return div.getElementsByClassName("i").length === 2; - }); - - // Support: IE<10 - // Check if getElementById returns elements by name - // The broken getElementById methods don't pick up programatically-set names, - // so use a roundabout getElementsByName test - support.getById = assert(function( div ) { - docElem.appendChild( div ).id = expando; - return !doc.getElementsByName || !doc.getElementsByName( expando ).length; - }); - - // ID find and filter - if ( support.getById ) { - Expr.find["ID"] = function( id, context ) { - if ( typeof context.getElementById !== strundefined && documentIsHTML ) { - var m = context.getElementById( id ); - // Check parentNode to catch when Blackberry 4.6 returns - // nodes that are no longer in the document #6963 - return m && m.parentNode ? [m] : []; - } - }; - Expr.filter["ID"] = function( id ) { - var attrId = id.replace( runescape, funescape ); - return function( elem ) { - return elem.getAttribute("id") === attrId; - }; - }; - } else { - // Support: IE6/7 - // getElementById is not reliable as a find shortcut - delete Expr.find["ID"]; - - Expr.filter["ID"] = function( id ) { - var attrId = id.replace( runescape, funescape ); - return function( elem ) { - var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id"); - return node && node.value === attrId; - }; - }; - } - - // Tag - Expr.find["TAG"] = support.getElementsByTagName ? - function( tag, context ) { - if ( typeof context.getElementsByTagName !== strundefined ) { - return context.getElementsByTagName( tag ); - } - } : - function( tag, context ) { - var elem, - tmp = [], - i = 0, - results = context.getElementsByTagName( tag ); - - // Filter out possible comments - if ( tag === "*" ) { - while ( (elem = results[i++]) ) { - if ( elem.nodeType === 1 ) { - tmp.push( elem ); - } - } - - return tmp; - } - return results; - }; - - // Class - Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) { - if ( typeof context.getElementsByClassName !== strundefined && documentIsHTML ) { - return context.getElementsByClassName( className ); - } - }; - - /* QSA/matchesSelector - ---------------------------------------------------------------------- */ - - // QSA and matchesSelector support - - // matchesSelector(:active) reports false when true (IE9/Opera 11.5) - rbuggyMatches = []; - - // qSa(:focus) reports false when true (Chrome 21) - // We allow this because of a bug in IE8/9 that throws an error - // whenever `document.activeElement` is accessed on an iframe - // So, we allow :focus to pass through QSA all the time to avoid the IE error - // See http://bugs.jquery.com/ticket/13378 - rbuggyQSA = []; - - if ( (support.qsa = isNative(doc.querySelectorAll)) ) { - // Build QSA regex - // Regex strategy adopted from Diego Perini - assert(function( div ) { - // Select is set to empty string on purpose - // This is to test IE's treatment of not explicitly - // setting a boolean content attribute, - // since its presence should be enough - // http://bugs.jquery.com/ticket/12359 - div.innerHTML = ""; - - // Support: IE8 - // Boolean attributes and "value" are not treated correctly - if ( !div.querySelectorAll("[selected]").length ) { - rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" ); - } - - // Webkit/Opera - :checked should return selected option elements - // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked - // IE8 throws error here and will not see later tests - if ( !div.querySelectorAll(":checked").length ) { - rbuggyQSA.push(":checked"); - } - }); - - assert(function( div ) { - - // Support: Opera 10-12/IE8 - // ^= $= *= and empty values - // Should not select anything - // Support: Windows 8 Native Apps - // The type attribute is restricted during .innerHTML assignment - var input = doc.createElement("input"); - input.setAttribute( "type", "hidden" ); - div.appendChild( input ).setAttribute( "t", "" ); - - if ( div.querySelectorAll("[t^='']").length ) { - rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" ); - } - - // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) - // IE8 throws error here and will not see later tests - if ( !div.querySelectorAll(":enabled").length ) { - rbuggyQSA.push( ":enabled", ":disabled" ); - } - - // Opera 10-11 does not throw on post-comma invalid pseudos - div.querySelectorAll("*,:x"); - rbuggyQSA.push(",.*:"); - }); - } - - if ( (support.matchesSelector = isNative( (matches = docElem.webkitMatchesSelector || - docElem.mozMatchesSelector || - docElem.oMatchesSelector || - docElem.msMatchesSelector) )) ) { - - assert(function( div ) { - // Check to see if it's possible to do matchesSelector - // on a disconnected node (IE 9) - support.disconnectedMatch = matches.call( div, "div" ); - - // This should fail with an exception - // Gecko does not error, returns false instead - matches.call( div, "[s!='']:x" ); - rbuggyMatches.push( "!=", pseudos ); - }); - } - - rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") ); - rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") ); - - /* Contains - ---------------------------------------------------------------------- */ - - // Element contains another - // Purposefully does not implement inclusive descendent - // As in, an element does not contain itself - contains = isNative(docElem.contains) || docElem.compareDocumentPosition ? - function( a, b ) { - var adown = a.nodeType === 9 ? a.documentElement : a, - bup = b && b.parentNode; - return a === bup || !!( bup && bup.nodeType === 1 && ( - adown.contains ? - adown.contains( bup ) : - a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 - )); - } : - function( a, b ) { - if ( b ) { - while ( (b = b.parentNode) ) { - if ( b === a ) { - return true; - } - } - } - return false; - }; - - /* Sorting - ---------------------------------------------------------------------- */ - - // Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27) - // Detached nodes confoundingly follow *each other* - support.sortDetached = assert(function( div1 ) { - // Should return 1, but returns 4 (following) - return div1.compareDocumentPosition( doc.createElement("div") ) & 1; - }); - - // Document order sorting - sortOrder = docElem.compareDocumentPosition ? - function( a, b ) { - - // Flag for duplicate removal - if ( a === b ) { - hasDuplicate = true; - return 0; - } - - var compare = b.compareDocumentPosition && a.compareDocumentPosition && a.compareDocumentPosition( b ); - - if ( compare ) { - // Disconnected nodes - if ( compare & 1 || - (!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) { - - // Choose the first element that is related to our preferred document - if ( a === doc || contains(preferredDoc, a) ) { - return -1; - } - if ( b === doc || contains(preferredDoc, b) ) { - return 1; - } - - // Maintain original order - return sortInput ? - ( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) : - 0; - } - - return compare & 4 ? -1 : 1; - } - - // Not directly comparable, sort on existence of method - return a.compareDocumentPosition ? -1 : 1; - } : - function( a, b ) { - var cur, - i = 0, - aup = a.parentNode, - bup = b.parentNode, - ap = [ a ], - bp = [ b ]; - - // Exit early if the nodes are identical - if ( a === b ) { - hasDuplicate = true; - return 0; - - // Parentless nodes are either documents or disconnected - } else if ( !aup || !bup ) { - return a === doc ? -1 : - b === doc ? 1 : - aup ? -1 : - bup ? 1 : - sortInput ? - ( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) : - 0; - - // If the nodes are siblings, we can do a quick check - } else if ( aup === bup ) { - return siblingCheck( a, b ); - } - - // Otherwise we need full lists of their ancestors for comparison - cur = a; - while ( (cur = cur.parentNode) ) { - ap.unshift( cur ); - } - cur = b; - while ( (cur = cur.parentNode) ) { - bp.unshift( cur ); - } - - // Walk down the tree looking for a discrepancy - while ( ap[i] === bp[i] ) { - i++; - } - - return i ? - // Do a sibling check if the nodes have a common ancestor - siblingCheck( ap[i], bp[i] ) : - - // Otherwise nodes in our document sort first - ap[i] === preferredDoc ? -1 : - bp[i] === preferredDoc ? 1 : - 0; - }; - - return doc; -}; - -Sizzle.matches = function( expr, elements ) { - return Sizzle( expr, null, null, elements ); -}; - -Sizzle.matchesSelector = function( elem, expr ) { - // Set document vars if needed - if ( ( elem.ownerDocument || elem ) !== document ) { - setDocument( elem ); - } - - // Make sure that attribute selectors are quoted - expr = expr.replace( rattributeQuotes, "='$1']" ); - - if ( support.matchesSelector && documentIsHTML && - ( !rbuggyMatches || !rbuggyMatches.test( expr ) ) && - ( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) { - - try { - var ret = matches.call( elem, expr ); - - // IE 9's matchesSelector returns false on disconnected nodes - if ( ret || support.disconnectedMatch || - // As well, disconnected nodes are said to be in a document - // fragment in IE 9 - elem.document && elem.document.nodeType !== 11 ) { - return ret; - } - } catch(e) {} - } - - return Sizzle( expr, document, null, [elem] ).length > 0; -}; - -Sizzle.contains = function( context, elem ) { - // Set document vars if needed - if ( ( context.ownerDocument || context ) !== document ) { - setDocument( context ); - } - return contains( context, elem ); -}; - -Sizzle.attr = function( elem, name ) { - // Set document vars if needed - if ( ( elem.ownerDocument || elem ) !== document ) { - setDocument( elem ); - } - - var fn = Expr.attrHandle[ name.toLowerCase() ], - // Don't get fooled by Object.prototype properties (jQuery #13807) - val = ( fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ? - fn( elem, name, !documentIsHTML ) : - undefined ); - - return val === undefined ? - support.attributes || !documentIsHTML ? - elem.getAttribute( name ) : - (val = elem.getAttributeNode(name)) && val.specified ? - val.value : - null : - val; -}; - -Sizzle.error = function( msg ) { - throw new Error( "Syntax error, unrecognized expression: " + msg ); -}; - -/** - * Document sorting and removing duplicates - * @param {ArrayLike} results - */ -Sizzle.uniqueSort = function( results ) { - var elem, - duplicates = [], - j = 0, - i = 0; - - // Unless we *know* we can detect duplicates, assume their presence - hasDuplicate = !support.detectDuplicates; - sortInput = !support.sortStable && results.slice( 0 ); - results.sort( sortOrder ); - - if ( hasDuplicate ) { - while ( (elem = results[i++]) ) { - if ( elem === results[ i ] ) { - j = duplicates.push( i ); - } - } - while ( j-- ) { - results.splice( duplicates[ j ], 1 ); - } - } - - return results; -}; - -/** - * Utility function for retrieving the text value of an array of DOM nodes - * @param {Array|Element} elem - */ -getText = Sizzle.getText = function( elem ) { - var node, - ret = "", - i = 0, - nodeType = elem.nodeType; - - if ( !nodeType ) { - // If no nodeType, this is expected to be an array - for ( ; (node = elem[i]); i++ ) { - // Do not traverse comment nodes - ret += getText( node ); - } - } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { - // Use textContent for elements - // innerText usage removed for consistency of new lines (see #11153) - if ( typeof elem.textContent === "string" ) { - return elem.textContent; - } else { - // Traverse its children - for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { - ret += getText( elem ); - } - } - } else if ( nodeType === 3 || nodeType === 4 ) { - return elem.nodeValue; - } - // Do not include comment or processing instruction nodes - - return ret; -}; - -Expr = Sizzle.selectors = { - - // Can be adjusted by the user - cacheLength: 50, - - createPseudo: markFunction, - - match: matchExpr, - - attrHandle: {}, - - find: {}, - - relative: { - ">": { dir: "parentNode", first: true }, - " ": { dir: "parentNode" }, - "+": { dir: "previousSibling", first: true }, - "~": { dir: "previousSibling" } - }, - - preFilter: { - "ATTR": function( match ) { - match[1] = match[1].replace( runescape, funescape ); - - // Move the given value to match[3] whether quoted or unquoted - match[3] = ( match[4] || match[5] || "" ).replace( runescape, funescape ); - - if ( match[2] === "~=" ) { - match[3] = " " + match[3] + " "; - } - - return match.slice( 0, 4 ); - }, - - "CHILD": function( match ) { - /* matches from matchExpr["CHILD"] - 1 type (only|nth|...) - 2 what (child|of-type) - 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...) - 4 xn-component of xn+y argument ([+-]?\d*n|) - 5 sign of xn-component - 6 x of xn-component - 7 sign of y-component - 8 y of y-component - */ - match[1] = match[1].toLowerCase(); - - if ( match[1].slice( 0, 3 ) === "nth" ) { - // nth-* requires argument - if ( !match[3] ) { - Sizzle.error( match[0] ); - } - - // numeric x and y parameters for Expr.filter.CHILD - // remember that false/true cast respectively to 0/1 - match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) ); - match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" ); - - // other types prohibit arguments - } else if ( match[3] ) { - Sizzle.error( match[0] ); - } - - return match; - }, - - "PSEUDO": function( match ) { - var excess, - unquoted = !match[5] && match[2]; - - if ( matchExpr["CHILD"].test( match[0] ) ) { - return null; - } - - // Accept quoted arguments as-is - if ( match[3] && match[4] !== undefined ) { - match[2] = match[4]; - - // Strip excess characters from unquoted arguments - } else if ( unquoted && rpseudo.test( unquoted ) && - // Get excess from tokenize (recursively) - (excess = tokenize( unquoted, true )) && - // advance to the next closing parenthesis - (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) { - - // excess is a negative index - match[0] = match[0].slice( 0, excess ); - match[2] = unquoted.slice( 0, excess ); - } - - // Return only captures needed by the pseudo filter method (type and argument) - return match.slice( 0, 3 ); - } - }, - - filter: { - - "TAG": function( nodeNameSelector ) { - var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase(); - return nodeNameSelector === "*" ? - function() { return true; } : - function( elem ) { - return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; - }; - }, - - "CLASS": function( className ) { - var pattern = classCache[ className + " " ]; - - return pattern || - (pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) && - classCache( className, function( elem ) { - return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== strundefined && elem.getAttribute("class") || "" ); - }); - }, - - "ATTR": function( name, operator, check ) { - return function( elem ) { - var result = Sizzle.attr( elem, name ); - - if ( result == null ) { - return operator === "!="; - } - if ( !operator ) { - return true; - } - - result += ""; - - return operator === "=" ? result === check : - operator === "!=" ? result !== check : - operator === "^=" ? check && result.indexOf( check ) === 0 : - operator === "*=" ? check && result.indexOf( check ) > -1 : - operator === "$=" ? check && result.slice( -check.length ) === check : - operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 : - operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" : - false; - }; - }, - - "CHILD": function( type, what, argument, first, last ) { - var simple = type.slice( 0, 3 ) !== "nth", - forward = type.slice( -4 ) !== "last", - ofType = what === "of-type"; - - return first === 1 && last === 0 ? - - // Shortcut for :nth-*(n) - function( elem ) { - return !!elem.parentNode; - } : - - function( elem, context, xml ) { - var cache, outerCache, node, diff, nodeIndex, start, - dir = simple !== forward ? "nextSibling" : "previousSibling", - parent = elem.parentNode, - name = ofType && elem.nodeName.toLowerCase(), - useCache = !xml && !ofType; - - if ( parent ) { - - // :(first|last|only)-(child|of-type) - if ( simple ) { - while ( dir ) { - node = elem; - while ( (node = node[ dir ]) ) { - if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) { - return false; - } - } - // Reverse direction for :only-* (if we haven't yet done so) - start = dir = type === "only" && !start && "nextSibling"; - } - return true; - } - - start = [ forward ? parent.firstChild : parent.lastChild ]; - - // non-xml :nth-child(...) stores cache data on `parent` - if ( forward && useCache ) { - // Seek `elem` from a previously-cached index - outerCache = parent[ expando ] || (parent[ expando ] = {}); - cache = outerCache[ type ] || []; - nodeIndex = cache[0] === dirruns && cache[1]; - diff = cache[0] === dirruns && cache[2]; - node = nodeIndex && parent.childNodes[ nodeIndex ]; - - while ( (node = ++nodeIndex && node && node[ dir ] || - - // Fallback to seeking `elem` from the start - (diff = nodeIndex = 0) || start.pop()) ) { - - // When found, cache indexes on `parent` and break - if ( node.nodeType === 1 && ++diff && node === elem ) { - outerCache[ type ] = [ dirruns, nodeIndex, diff ]; - break; - } - } - - // Use previously-cached element index if available - } else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) { - diff = cache[1]; - - // xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...) - } else { - // Use the same loop as above to seek `elem` from the start - while ( (node = ++nodeIndex && node && node[ dir ] || - (diff = nodeIndex = 0) || start.pop()) ) { - - if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) { - // Cache the index of each encountered element - if ( useCache ) { - (node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ]; - } - - if ( node === elem ) { - break; - } - } - } - } - - // Incorporate the offset, then check against cycle size - diff -= last; - return diff === first || ( diff % first === 0 && diff / first >= 0 ); - } - }; - }, - - "PSEUDO": function( pseudo, argument ) { - // pseudo-class names are case-insensitive - // http://www.w3.org/TR/selectors/#pseudo-classes - // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters - // Remember that setFilters inherits from pseudos - var args, - fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || - Sizzle.error( "unsupported pseudo: " + pseudo ); - - // The user may use createPseudo to indicate that - // arguments are needed to create the filter function - // just as Sizzle does - if ( fn[ expando ] ) { - return fn( argument ); - } - - // But maintain support for old signatures - if ( fn.length > 1 ) { - args = [ pseudo, pseudo, "", argument ]; - return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? - markFunction(function( seed, matches ) { - var idx, - matched = fn( seed, argument ), - i = matched.length; - while ( i-- ) { - idx = indexOf.call( seed, matched[i] ); - seed[ idx ] = !( matches[ idx ] = matched[i] ); - } - }) : - function( elem ) { - return fn( elem, 0, args ); - }; - } - - return fn; - } - }, - - pseudos: { - // Potentially complex pseudos - "not": markFunction(function( selector ) { - // Trim the selector passed to compile - // to avoid treating leading and trailing - // spaces as combinators - var input = [], - results = [], - matcher = compile( selector.replace( rtrim, "$1" ) ); - - return matcher[ expando ] ? - markFunction(function( seed, matches, context, xml ) { - var elem, - unmatched = matcher( seed, null, xml, [] ), - i = seed.length; - - // Match elements unmatched by `matcher` - while ( i-- ) { - if ( (elem = unmatched[i]) ) { - seed[i] = !(matches[i] = elem); - } - } - }) : - function( elem, context, xml ) { - input[0] = elem; - matcher( input, null, xml, results ); - return !results.pop(); - }; - }), - - "has": markFunction(function( selector ) { - return function( elem ) { - return Sizzle( selector, elem ).length > 0; - }; - }), - - "contains": markFunction(function( text ) { - return function( elem ) { - return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; - }; - }), - - // "Whether an element is represented by a :lang() selector - // is based solely on the element's language value - // being equal to the identifier C, - // or beginning with the identifier C immediately followed by "-". - // The matching of C against the element's language value is performed case-insensitively. - // The identifier C does not have to be a valid language name." - // http://www.w3.org/TR/selectors/#lang-pseudo - "lang": markFunction( function( lang ) { - // lang value must be a valid identifier - if ( !ridentifier.test(lang || "") ) { - Sizzle.error( "unsupported lang: " + lang ); - } - lang = lang.replace( runescape, funescape ).toLowerCase(); - return function( elem ) { - var elemLang; - do { - if ( (elemLang = documentIsHTML ? - elem.lang : - elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) { - - elemLang = elemLang.toLowerCase(); - return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0; - } - } while ( (elem = elem.parentNode) && elem.nodeType === 1 ); - return false; - }; - }), - - // Miscellaneous - "target": function( elem ) { - var hash = window.location && window.location.hash; - return hash && hash.slice( 1 ) === elem.id; - }, - - "root": function( elem ) { - return elem === docElem; - }, - - "focus": function( elem ) { - return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex); - }, - - // Boolean properties - "enabled": function( elem ) { - return elem.disabled === false; - }, - - "disabled": function( elem ) { - return elem.disabled === true; - }, - - "checked": function( elem ) { - // In CSS3, :checked should return both checked and selected elements - // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked - var nodeName = elem.nodeName.toLowerCase(); - return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected); - }, - - "selected": function( elem ) { - // Accessing this property makes selected-by-default - // options in Safari work properly - if ( elem.parentNode ) { - elem.parentNode.selectedIndex; - } - - return elem.selected === true; - }, - - // Contents - "empty": function( elem ) { - // http://www.w3.org/TR/selectors/#empty-pseudo - // :empty is only affected by element nodes and content nodes(including text(3), cdata(4)), - // not comment, processing instructions, or others - // Thanks to Diego Perini for the nodeName shortcut - // Greater than "@" means alpha characters (specifically not starting with "#" or "?") - for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { - if ( elem.nodeName > "@" || elem.nodeType === 3 || elem.nodeType === 4 ) { - return false; - } - } - return true; - }, - - "parent": function( elem ) { - return !Expr.pseudos["empty"]( elem ); - }, - - // Element/input types - "header": function( elem ) { - return rheader.test( elem.nodeName ); - }, - - "input": function( elem ) { - return rinputs.test( elem.nodeName ); - }, - - "button": function( elem ) { - var name = elem.nodeName.toLowerCase(); - return name === "input" && elem.type === "button" || name === "button"; - }, - - "text": function( elem ) { - var attr; - // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc) - // use getAttribute instead to test this case - return elem.nodeName.toLowerCase() === "input" && - elem.type === "text" && - ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === elem.type ); - }, - - // Position-in-collection - "first": createPositionalPseudo(function() { - return [ 0 ]; - }), - - "last": createPositionalPseudo(function( matchIndexes, length ) { - return [ length - 1 ]; - }), - - "eq": createPositionalPseudo(function( matchIndexes, length, argument ) { - return [ argument < 0 ? argument + length : argument ]; - }), - - "even": createPositionalPseudo(function( matchIndexes, length ) { - var i = 0; - for ( ; i < length; i += 2 ) { - matchIndexes.push( i ); - } - return matchIndexes; - }), - - "odd": createPositionalPseudo(function( matchIndexes, length ) { - var i = 1; - for ( ; i < length; i += 2 ) { - matchIndexes.push( i ); - } - return matchIndexes; - }), - - "lt": createPositionalPseudo(function( matchIndexes, length, argument ) { - var i = argument < 0 ? argument + length : argument; - for ( ; --i >= 0; ) { - matchIndexes.push( i ); - } - return matchIndexes; - }), - - "gt": createPositionalPseudo(function( matchIndexes, length, argument ) { - var i = argument < 0 ? argument + length : argument; - for ( ; ++i < length; ) { - matchIndexes.push( i ); - } - return matchIndexes; - }) - } -}; - -// Add button/input type pseudos -for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) { - Expr.pseudos[ i ] = createInputPseudo( i ); -} -for ( i in { submit: true, reset: true } ) { - Expr.pseudos[ i ] = createButtonPseudo( i ); -} - -function tokenize( selector, parseOnly ) { - var matched, match, tokens, type, - soFar, groups, preFilters, - cached = tokenCache[ selector + " " ]; - - if ( cached ) { - return parseOnly ? 0 : cached.slice( 0 ); - } - - soFar = selector; - groups = []; - preFilters = Expr.preFilter; - - while ( soFar ) { - - // Comma and first run - if ( !matched || (match = rcomma.exec( soFar )) ) { - if ( match ) { - // Don't consume trailing commas as valid - soFar = soFar.slice( match[0].length ) || soFar; - } - groups.push( tokens = [] ); - } - - matched = false; - - // Combinators - if ( (match = rcombinators.exec( soFar )) ) { - matched = match.shift(); - tokens.push({ - value: matched, - // Cast descendant combinators to space - type: match[0].replace( rtrim, " " ) - }); - soFar = soFar.slice( matched.length ); - } - - // Filters - for ( type in Expr.filter ) { - if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || - (match = preFilters[ type ]( match ))) ) { - matched = match.shift(); - tokens.push({ - value: matched, - type: type, - matches: match - }); - soFar = soFar.slice( matched.length ); - } - } - - if ( !matched ) { - break; - } - } - - // Return the length of the invalid excess - // if we're just parsing - // Otherwise, throw an error or return tokens - return parseOnly ? - soFar.length : - soFar ? - Sizzle.error( selector ) : - // Cache the tokens - tokenCache( selector, groups ).slice( 0 ); -} - -function toSelector( tokens ) { - var i = 0, - len = tokens.length, - selector = ""; - for ( ; i < len; i++ ) { - selector += tokens[i].value; - } - return selector; -} - -function addCombinator( matcher, combinator, base ) { - var dir = combinator.dir, - checkNonElements = base && dir === "parentNode", - doneName = done++; - - return combinator.first ? - // Check against closest ancestor/preceding element - function( elem, context, xml ) { - while ( (elem = elem[ dir ]) ) { - if ( elem.nodeType === 1 || checkNonElements ) { - return matcher( elem, context, xml ); - } - } - } : - - // Check against all ancestor/preceding elements - function( elem, context, xml ) { - var data, cache, outerCache, - dirkey = dirruns + " " + doneName; - - // We can't set arbitrary data on XML nodes, so they don't benefit from dir caching - if ( xml ) { - while ( (elem = elem[ dir ]) ) { - if ( elem.nodeType === 1 || checkNonElements ) { - if ( matcher( elem, context, xml ) ) { - return true; - } - } - } - } else { - while ( (elem = elem[ dir ]) ) { - if ( elem.nodeType === 1 || checkNonElements ) { - outerCache = elem[ expando ] || (elem[ expando ] = {}); - if ( (cache = outerCache[ dir ]) && cache[0] === dirkey ) { - if ( (data = cache[1]) === true || data === cachedruns ) { - return data === true; - } - } else { - cache = outerCache[ dir ] = [ dirkey ]; - cache[1] = matcher( elem, context, xml ) || cachedruns; - if ( cache[1] === true ) { - return true; - } - } - } - } - } - }; -} - -function elementMatcher( matchers ) { - return matchers.length > 1 ? - function( elem, context, xml ) { - var i = matchers.length; - while ( i-- ) { - if ( !matchers[i]( elem, context, xml ) ) { - return false; - } - } - return true; - } : - matchers[0]; -} - -function condense( unmatched, map, filter, context, xml ) { - var elem, - newUnmatched = [], - i = 0, - len = unmatched.length, - mapped = map != null; - - for ( ; i < len; i++ ) { - if ( (elem = unmatched[i]) ) { - if ( !filter || filter( elem, context, xml ) ) { - newUnmatched.push( elem ); - if ( mapped ) { - map.push( i ); - } - } - } - } - - return newUnmatched; -} - -function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { - if ( postFilter && !postFilter[ expando ] ) { - postFilter = setMatcher( postFilter ); - } - if ( postFinder && !postFinder[ expando ] ) { - postFinder = setMatcher( postFinder, postSelector ); - } - return markFunction(function( seed, results, context, xml ) { - var temp, i, elem, - preMap = [], - postMap = [], - preexisting = results.length, - - // Get initial elements from seed or context - elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ), - - // Prefilter to get matcher input, preserving a map for seed-results synchronization - matcherIn = preFilter && ( seed || !selector ) ? - condense( elems, preMap, preFilter, context, xml ) : - elems, - - matcherOut = matcher ? - // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, - postFinder || ( seed ? preFilter : preexisting || postFilter ) ? - - // ...intermediate processing is necessary - [] : - - // ...otherwise use results directly - results : - matcherIn; - - // Find primary matches - if ( matcher ) { - matcher( matcherIn, matcherOut, context, xml ); - } - - // Apply postFilter - if ( postFilter ) { - temp = condense( matcherOut, postMap ); - postFilter( temp, [], context, xml ); - - // Un-match failing elements by moving them back to matcherIn - i = temp.length; - while ( i-- ) { - if ( (elem = temp[i]) ) { - matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem); - } - } - } - - if ( seed ) { - if ( postFinder || preFilter ) { - if ( postFinder ) { - // Get the final matcherOut by condensing this intermediate into postFinder contexts - temp = []; - i = matcherOut.length; - while ( i-- ) { - if ( (elem = matcherOut[i]) ) { - // Restore matcherIn since elem is not yet a final match - temp.push( (matcherIn[i] = elem) ); - } - } - postFinder( null, (matcherOut = []), temp, xml ); - } - - // Move matched elements from seed to results to keep them synchronized - i = matcherOut.length; - while ( i-- ) { - if ( (elem = matcherOut[i]) && - (temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) { - - seed[temp] = !(results[temp] = elem); - } - } - } - - // Add elements to results, through postFinder if defined - } else { - matcherOut = condense( - matcherOut === results ? - matcherOut.splice( preexisting, matcherOut.length ) : - matcherOut - ); - if ( postFinder ) { - postFinder( null, results, matcherOut, xml ); - } else { - push.apply( results, matcherOut ); - } - } - }); -} - -function matcherFromTokens( tokens ) { - var checkContext, matcher, j, - len = tokens.length, - leadingRelative = Expr.relative[ tokens[0].type ], - implicitRelative = leadingRelative || Expr.relative[" "], - i = leadingRelative ? 1 : 0, - - // The foundational matcher ensures that elements are reachable from top-level context(s) - matchContext = addCombinator( function( elem ) { - return elem === checkContext; - }, implicitRelative, true ), - matchAnyContext = addCombinator( function( elem ) { - return indexOf.call( checkContext, elem ) > -1; - }, implicitRelative, true ), - matchers = [ function( elem, context, xml ) { - return ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( - (checkContext = context).nodeType ? - matchContext( elem, context, xml ) : - matchAnyContext( elem, context, xml ) ); - } ]; - - for ( ; i < len; i++ ) { - if ( (matcher = Expr.relative[ tokens[i].type ]) ) { - matchers = [ addCombinator(elementMatcher( matchers ), matcher) ]; - } else { - matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches ); - - // Return special upon seeing a positional matcher - if ( matcher[ expando ] ) { - // Find the next relative operator (if any) for proper handling - j = ++i; - for ( ; j < len; j++ ) { - if ( Expr.relative[ tokens[j].type ] ) { - break; - } - } - return setMatcher( - i > 1 && elementMatcher( matchers ), - i > 1 && toSelector( - // If the preceding token was a descendant combinator, insert an implicit any-element `*` - tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" }) - ).replace( rtrim, "$1" ), - matcher, - i < j && matcherFromTokens( tokens.slice( i, j ) ), - j < len && matcherFromTokens( (tokens = tokens.slice( j )) ), - j < len && toSelector( tokens ) - ); - } - matchers.push( matcher ); - } - } - - return elementMatcher( matchers ); -} - -function matcherFromGroupMatchers( elementMatchers, setMatchers ) { - // A counter to specify which element is currently being matched - var matcherCachedRuns = 0, - bySet = setMatchers.length > 0, - byElement = elementMatchers.length > 0, - superMatcher = function( seed, context, xml, results, expandContext ) { - var elem, j, matcher, - setMatched = [], - matchedCount = 0, - i = "0", - unmatched = seed && [], - outermost = expandContext != null, - contextBackup = outermostContext, - // We must always have either seed elements or context - elems = seed || byElement && Expr.find["TAG"]( "*", expandContext && context.parentNode || context ), - // Use integer dirruns iff this is the outermost matcher - dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1); - - if ( outermost ) { - outermostContext = context !== document && context; - cachedruns = matcherCachedRuns; - } - - // Add elements passing elementMatchers directly to results - // Keep `i` a string if there are no elements so `matchedCount` will be "00" below - for ( ; (elem = elems[i]) != null; i++ ) { - if ( byElement && elem ) { - j = 0; - while ( (matcher = elementMatchers[j++]) ) { - if ( matcher( elem, context, xml ) ) { - results.push( elem ); - break; - } - } - if ( outermost ) { - dirruns = dirrunsUnique; - cachedruns = ++matcherCachedRuns; - } - } - - // Track unmatched elements for set filters - if ( bySet ) { - // They will have gone through all possible matchers - if ( (elem = !matcher && elem) ) { - matchedCount--; - } - - // Lengthen the array for every element, matched or not - if ( seed ) { - unmatched.push( elem ); - } - } - } - - // Apply set filters to unmatched elements - matchedCount += i; - if ( bySet && i !== matchedCount ) { - j = 0; - while ( (matcher = setMatchers[j++]) ) { - matcher( unmatched, setMatched, context, xml ); - } - - if ( seed ) { - // Reintegrate element matches to eliminate the need for sorting - if ( matchedCount > 0 ) { - while ( i-- ) { - if ( !(unmatched[i] || setMatched[i]) ) { - setMatched[i] = pop.call( results ); - } - } - } - - // Discard index placeholder values to get only actual matches - setMatched = condense( setMatched ); - } - - // Add matches to results - push.apply( results, setMatched ); - - // Seedless set matches succeeding multiple successful matchers stipulate sorting - if ( outermost && !seed && setMatched.length > 0 && - ( matchedCount + setMatchers.length ) > 1 ) { - - Sizzle.uniqueSort( results ); - } - } - - // Override manipulation of globals by nested matchers - if ( outermost ) { - dirruns = dirrunsUnique; - outermostContext = contextBackup; - } - - return unmatched; - }; - - return bySet ? - markFunction( superMatcher ) : - superMatcher; -} - -compile = Sizzle.compile = function( selector, group /* Internal Use Only */ ) { - var i, - setMatchers = [], - elementMatchers = [], - cached = compilerCache[ selector + " " ]; - - if ( !cached ) { - // Generate a function of recursive functions that can be used to check each element - if ( !group ) { - group = tokenize( selector ); - } - i = group.length; - while ( i-- ) { - cached = matcherFromTokens( group[i] ); - if ( cached[ expando ] ) { - setMatchers.push( cached ); - } else { - elementMatchers.push( cached ); - } - } - - // Cache the compiled function - cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); - } - return cached; -}; - -function multipleContexts( selector, contexts, results ) { - var i = 0, - len = contexts.length; - for ( ; i < len; i++ ) { - Sizzle( selector, contexts[i], results ); - } - return results; -} - -function select( selector, context, results, seed ) { - var i, tokens, token, type, find, - match = tokenize( selector ); - - if ( !seed ) { - // Try to minimize operations if there is only one group - if ( match.length === 1 ) { - - // Take a shortcut and set the context if the root selector is an ID - tokens = match[0] = match[0].slice( 0 ); - if ( tokens.length > 2 && (token = tokens[0]).type === "ID" && - support.getById && context.nodeType === 9 && documentIsHTML && - Expr.relative[ tokens[1].type ] ) { - - context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0]; - if ( !context ) { - return results; - } - selector = selector.slice( tokens.shift().value.length ); - } - - // Fetch a seed set for right-to-left matching - i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length; - while ( i-- ) { - token = tokens[i]; - - // Abort if we hit a combinator - if ( Expr.relative[ (type = token.type) ] ) { - break; - } - if ( (find = Expr.find[ type ]) ) { - // Search, expanding context for leading sibling combinators - if ( (seed = find( - token.matches[0].replace( runescape, funescape ), - rsibling.test( tokens[0].type ) && context.parentNode || context - )) ) { - - // If seed is empty or no tokens remain, we can return early - tokens.splice( i, 1 ); - selector = seed.length && toSelector( tokens ); - if ( !selector ) { - push.apply( results, seed ); - return results; - } - - break; - } - } - } - } - } - - // Compile and execute a filtering function - // Provide `match` to avoid retokenization if we modified the selector above - compile( selector, match )( - seed, - context, - !documentIsHTML, - results, - rsibling.test( selector ) - ); - return results; -} - -// Deprecated -Expr.pseudos["nth"] = Expr.pseudos["eq"]; - -// Easy API for creating new setFilters -function setFilters() {} -setFilters.prototype = Expr.filters = Expr.pseudos; -Expr.setFilters = new setFilters(); - -// One-time assignments - -// Sort stability -support.sortStable = expando.split("").sort( sortOrder ).join("") === expando; - -// Initialize against the default document -setDocument(); - -// Support: Chrome<<14 -// Always assume duplicates if they aren't passed to the comparison function -[0, 0].sort( sortOrder ); -support.detectDuplicates = hasDuplicate; - -jQuery.find = Sizzle; -jQuery.expr = Sizzle.selectors; -jQuery.expr[":"] = jQuery.expr.pseudos; -jQuery.unique = Sizzle.uniqueSort; -jQuery.text = Sizzle.getText; -jQuery.isXMLDoc = Sizzle.isXML; -jQuery.contains = Sizzle.contains; - - -})( window ); -// String to Object options format cache -var optionsCache = {}; - -// Convert String-formatted options into Object-formatted ones and store in cache -function createOptions( options ) { - var object = optionsCache[ options ] = {}; - jQuery.each( options.match( core_rnotwhite ) || [], function( _, flag ) { - object[ flag ] = true; - }); - return object; -} - -/* - * Create a callback list using the following parameters: - * - * options: an optional list of space-separated options that will change how - * the callback list behaves or a more traditional option object - * - * By default a callback list will act like an event callback list and can be - * "fired" multiple times. - * - * Possible options: - * - * once: will ensure the callback list can only be fired once (like a Deferred) - * - * memory: will keep track of previous values and will call any callback added - * after the list has been fired right away with the latest "memorized" - * values (like a Deferred) - * - * unique: will ensure a callback can only be added once (no duplicate in the list) - * - * stopOnFalse: interrupt callings when a callback returns false - * - */ -jQuery.Callbacks = function( options ) { - - // Convert options from String-formatted to Object-formatted if needed - // (we check in cache first) - options = typeof options === "string" ? - ( optionsCache[ options ] || createOptions( options ) ) : - jQuery.extend( {}, options ); - - var // Last fire value (for non-forgettable lists) - memory, - // Flag to know if list was already fired - fired, - // Flag to know if list is currently firing - firing, - // First callback to fire (used internally by add and fireWith) - firingStart, - // End of the loop when firing - firingLength, - // Index of currently firing callback (modified by remove if needed) - firingIndex, - // Actual callback list - list = [], - // Stack of fire calls for repeatable lists - stack = !options.once && [], - // Fire callbacks - fire = function( data ) { - memory = options.memory && data; - fired = true; - firingIndex = firingStart || 0; - firingStart = 0; - firingLength = list.length; - firing = true; - for ( ; list && firingIndex < firingLength; firingIndex++ ) { - if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) { - memory = false; // To prevent further calls using add - break; - } - } - firing = false; - if ( list ) { - if ( stack ) { - if ( stack.length ) { - fire( stack.shift() ); - } - } else if ( memory ) { - list = []; - } else { - self.disable(); - } - } - }, - // Actual Callbacks object - self = { - // Add a callback or a collection of callbacks to the list - add: function() { - if ( list ) { - // First, we save the current length - var start = list.length; - (function add( args ) { - jQuery.each( args, function( _, arg ) { - var type = jQuery.type( arg ); - if ( type === "function" ) { - if ( !options.unique || !self.has( arg ) ) { - list.push( arg ); - } - } else if ( arg && arg.length && type !== "string" ) { - // Inspect recursively - add( arg ); - } - }); - })( arguments ); - // Do we need to add the callbacks to the - // current firing batch? - if ( firing ) { - firingLength = list.length; - // With memory, if we're not firing then - // we should call right away - } else if ( memory ) { - firingStart = start; - fire( memory ); - } - } - return this; - }, - // Remove a callback from the list - remove: function() { - if ( list ) { - jQuery.each( arguments, function( _, arg ) { - var index; - while( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { - list.splice( index, 1 ); - // Handle firing indexes - if ( firing ) { - if ( index <= firingLength ) { - firingLength--; - } - if ( index <= firingIndex ) { - firingIndex--; - } - } - } - }); - } - return this; - }, - // Check if a given callback is in the list. - // If no argument is given, return whether or not list has callbacks attached. - has: function( fn ) { - return fn ? jQuery.inArray( fn, list ) > -1 : !!( list && list.length ); - }, - // Remove all callbacks from the list - empty: function() { - list = []; - firingLength = 0; - return this; - }, - // Have the list do nothing anymore - disable: function() { - list = stack = memory = undefined; - return this; - }, - // Is it disabled? - disabled: function() { - return !list; - }, - // Lock the list in its current state - lock: function() { - stack = undefined; - if ( !memory ) { - self.disable(); - } - return this; - }, - // Is it locked? - locked: function() { - return !stack; - }, - // Call all callbacks with the given context and arguments - fireWith: function( context, args ) { - args = args || []; - args = [ context, args.slice ? args.slice() : args ]; - if ( list && ( !fired || stack ) ) { - if ( firing ) { - stack.push( args ); - } else { - fire( args ); - } - } - return this; - }, - // Call all the callbacks with the given arguments - fire: function() { - self.fireWith( this, arguments ); - return this; - }, - // To know if the callbacks have already been called at least once - fired: function() { - return !!fired; - } - }; - - return self; -}; -jQuery.extend({ - - Deferred: function( func ) { - var tuples = [ - // action, add listener, listener list, final state - [ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ], - [ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ], - [ "notify", "progress", jQuery.Callbacks("memory") ] - ], - state = "pending", - promise = { - state: function() { - return state; - }, - always: function() { - deferred.done( arguments ).fail( arguments ); - return this; - }, - then: function( /* fnDone, fnFail, fnProgress */ ) { - var fns = arguments; - return jQuery.Deferred(function( newDefer ) { - jQuery.each( tuples, function( i, tuple ) { - var action = tuple[ 0 ], - fn = jQuery.isFunction( fns[ i ] ) && fns[ i ]; - // deferred[ done | fail | progress ] for forwarding actions to newDefer - deferred[ tuple[1] ](function() { - var returned = fn && fn.apply( this, arguments ); - if ( returned && jQuery.isFunction( returned.promise ) ) { - returned.promise() - .done( newDefer.resolve ) - .fail( newDefer.reject ) - .progress( newDefer.notify ); - } else { - newDefer[ action + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments ); - } - }); - }); - fns = null; - }).promise(); - }, - // Get a promise for this deferred - // If obj is provided, the promise aspect is added to the object - promise: function( obj ) { - return obj != null ? jQuery.extend( obj, promise ) : promise; - } - }, - deferred = {}; - - // Keep pipe for back-compat - promise.pipe = promise.then; - - // Add list-specific methods - jQuery.each( tuples, function( i, tuple ) { - var list = tuple[ 2 ], - stateString = tuple[ 3 ]; - - // promise[ done | fail | progress ] = list.add - promise[ tuple[1] ] = list.add; - - // Handle state - if ( stateString ) { - list.add(function() { - // state = [ resolved | rejected ] - state = stateString; - - // [ reject_list | resolve_list ].disable; progress_list.lock - }, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock ); - } - - // deferred[ resolve | reject | notify ] - deferred[ tuple[0] ] = function() { - deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments ); - return this; - }; - deferred[ tuple[0] + "With" ] = list.fireWith; - }); - - // Make the deferred a promise - promise.promise( deferred ); - - // Call given func if any - if ( func ) { - func.call( deferred, deferred ); - } - - // All done! - return deferred; - }, - - // Deferred helper - when: function( subordinate /* , ..., subordinateN */ ) { - var i = 0, - resolveValues = core_slice.call( arguments ), - length = resolveValues.length, - - // the count of uncompleted subordinates - remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0, - - // the master Deferred. If resolveValues consist of only a single Deferred, just use that. - deferred = remaining === 1 ? subordinate : jQuery.Deferred(), - - // Update function for both resolve and progress values - updateFunc = function( i, contexts, values ) { - return function( value ) { - contexts[ i ] = this; - values[ i ] = arguments.length > 1 ? core_slice.call( arguments ) : value; - if( values === progressValues ) { - deferred.notifyWith( contexts, values ); - } else if ( !( --remaining ) ) { - deferred.resolveWith( contexts, values ); - } - }; - }, - - progressValues, progressContexts, resolveContexts; - - // add listeners to Deferred subordinates; treat others as resolved - if ( length > 1 ) { - progressValues = new Array( length ); - progressContexts = new Array( length ); - resolveContexts = new Array( length ); - for ( ; i < length; i++ ) { - if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) { - resolveValues[ i ].promise() - .done( updateFunc( i, resolveContexts, resolveValues ) ) - .fail( deferred.reject ) - .progress( updateFunc( i, progressContexts, progressValues ) ); - } else { - --remaining; - } - } - } - - // if we're not waiting on anything, resolve the master - if ( !remaining ) { - deferred.resolveWith( resolveContexts, resolveValues ); - } - - return deferred.promise(); - } -}); -jQuery.support = (function( support ) { - var input = document.createElement("input"), - fragment = document.createDocumentFragment(), - div = document.createElement("div"), - select = document.createElement("select"), - opt = select.appendChild( document.createElement("option") ); - - // Finish early in limited environments - if ( !input.type ) { - return support; - } - - input.type = "checkbox"; - - // Support: Safari 5.1, iOS 5.1, Android 4.x, Android 2.3 - // Check the default checkbox/radio value ("" on old WebKit; "on" elsewhere) - support.checkOn = input.value !== ""; - - // Must access the parent to make an option select properly - // Support: IE9, IE10 - support.optSelected = opt.selected; - - // Will be defined later - support.reliableMarginRight = true; - support.boxSizingReliable = true; - support.pixelPosition = false; - - // Make sure checked status is properly cloned - // Support: IE9, IE10 - input.checked = true; - support.noCloneChecked = input.cloneNode( true ).checked; - - // Make sure that the options inside disabled selects aren't marked as disabled - // (WebKit marks them as disabled) - select.disabled = true; - support.optDisabled = !opt.disabled; - - // Check if an input maintains its value after becoming a radio - // Support: IE9, IE10 - input = document.createElement("input"); - input.value = "t"; - input.type = "radio"; - support.radioValue = input.value === "t"; - - // #11217 - WebKit loses check when the name is after the checked attribute - input.setAttribute( "checked", "t" ); - input.setAttribute( "name", "t" ); - - fragment.appendChild( input ); - - // Support: Safari 5.1, Android 4.x, Android 2.3 - // old WebKit doesn't clone checked state correctly in fragments - support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked; - - // Support: Firefox, Chrome, Safari - // Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP) - support.focusinBubbles = "onfocusin" in window; - - div.style.backgroundClip = "content-box"; - div.cloneNode( true ).style.backgroundClip = ""; - support.clearCloneStyle = div.style.backgroundClip === "content-box"; - - // Run tests that need a body at doc ready - jQuery(function() { - var container, marginDiv, - // Support: Firefox, Android 2.3 (Prefixed box-sizing versions). - divReset = "padding:0;margin:0;border:0;display:block;-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box", - body = document.getElementsByTagName("body")[ 0 ]; - - if ( !body ) { - // Return for frameset docs that don't have a body - return; - } - - container = document.createElement("div"); - container.style.cssText = "border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px"; - - // Check box-sizing and margin behavior. - body.appendChild( container ).appendChild( div ); - div.innerHTML = ""; - // Support: Firefox, Android 2.3 (Prefixed box-sizing versions). - div.style.cssText = "-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%"; - - // Workaround failing boxSizing test due to offsetWidth returning wrong value - // with some non-1 values of body zoom, ticket #13543 - jQuery.swap( body, body.style.zoom != null ? { zoom: 1 } : {}, function() { - support.boxSizing = div.offsetWidth === 4; - }); - - // Use window.getComputedStyle because jsdom on node.js will break without it. - if ( window.getComputedStyle ) { - support.pixelPosition = ( window.getComputedStyle( div, null ) || {} ).top !== "1%"; - support.boxSizingReliable = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px"; - - // Support: Android 2.3 - // Check if div with explicit width and no margin-right incorrectly - // gets computed margin-right based on width of container. (#3333) - // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right - marginDiv = div.appendChild( document.createElement("div") ); - marginDiv.style.cssText = div.style.cssText = divReset; - marginDiv.style.marginRight = marginDiv.style.width = "0"; - div.style.width = "1px"; - - support.reliableMarginRight = - !parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight ); - } - - body.removeChild( container ); - }); - - return support; -})( {} ); - -/* - Implementation Summary - - 1. Enforce API surface and semantic compatibility with 1.9.x branch - 2. Improve the module's maintainability by reducing the storage - paths to a single mechanism. - 3. Use the same single mechanism to support "private" and "user" data. - 4. _Never_ expose "private" data to user code (TODO: Drop _data, _removeData) - 5. Avoid exposing implementation details on user objects (eg. expando properties) - 6. Provide a clear path for implementation upgrade to WeakMap in 2014 -*/ -var data_user, data_priv, - rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/, - rmultiDash = /([A-Z])/g; - -function Data() { - // Support: Android < 4, - // Old WebKit does not have Object.preventExtensions/freeze method, - // return new empty object instead with no [[set]] accessor - Object.defineProperty( this.cache = {}, 0, { - get: function() { - return {}; - } - }); - - this.expando = jQuery.expando + Math.random(); -} - -Data.uid = 1; - -Data.accepts = function( owner ) { - // Accepts only: - // - Node - // - Node.ELEMENT_NODE - // - Node.DOCUMENT_NODE - // - Object - // - Any - return owner.nodeType ? - owner.nodeType === 1 || owner.nodeType === 9 : true; -}; - -Data.prototype = { - key: function( owner ) { - // We can accept data for non-element nodes in modern browsers, - // but we should not, see #8335. - // Always return the key for a frozen object. - if ( !Data.accepts( owner ) ) { - return 0; - } - - var descriptor = {}, - // Check if the owner object already has a cache key - unlock = owner[ this.expando ]; - - // If not, create one - if ( !unlock ) { - unlock = Data.uid++; - - // Secure it in a non-enumerable, non-writable property - try { - descriptor[ this.expando ] = { value: unlock }; - Object.defineProperties( owner, descriptor ); - - // Support: Android < 4 - // Fallback to a less secure definition - } catch ( e ) { - descriptor[ this.expando ] = unlock; - jQuery.extend( owner, descriptor ); - } - } - - // Ensure the cache object - if ( !this.cache[ unlock ] ) { - this.cache[ unlock ] = {}; - } - - return unlock; - }, - set: function( owner, data, value ) { - var prop, - // There may be an unlock assigned to this node, - // if there is no entry for this "owner", create one inline - // and set the unlock as though an owner entry had always existed - unlock = this.key( owner ), - cache = this.cache[ unlock ]; - - // Handle: [ owner, key, value ] args - if ( typeof data === "string" ) { - cache[ data ] = value; - - // Handle: [ owner, { properties } ] args - } else { - // Fresh assignments by object are shallow copied - if ( jQuery.isEmptyObject( cache ) ) { - jQuery.extend( this.cache[ unlock ], data ); - // Otherwise, copy the properties one-by-one to the cache object - } else { - for ( prop in data ) { - cache[ prop ] = data[ prop ]; - } - } - } - return cache; - }, - get: function( owner, key ) { - // Either a valid cache is found, or will be created. - // New caches will be created and the unlock returned, - // allowing direct access to the newly created - // empty data object. A valid owner object must be provided. - var cache = this.cache[ this.key( owner ) ]; - - return key === undefined ? - cache : cache[ key ]; - }, - access: function( owner, key, value ) { - // In cases where either: - // - // 1. No key was specified - // 2. A string key was specified, but no value provided - // - // Take the "read" path and allow the get method to determine - // which value to return, respectively either: - // - // 1. The entire cache object - // 2. The data stored at the key - // - if ( key === undefined || - ((key && typeof key === "string") && value === undefined) ) { - return this.get( owner, key ); - } - - // [*]When the key is not a string, or both a key and value - // are specified, set or extend (existing objects) with either: - // - // 1. An object of properties - // 2. A key and value - // - this.set( owner, key, value ); - - // Since the "set" path can have two possible entry points - // return the expected data based on which path was taken[*] - return value !== undefined ? value : key; - }, - remove: function( owner, key ) { - var i, name, camel, - unlock = this.key( owner ), - cache = this.cache[ unlock ]; - - if ( key === undefined ) { - this.cache[ unlock ] = {}; - - } else { - // Support array or space separated string of keys - if ( jQuery.isArray( key ) ) { - // If "name" is an array of keys... - // When data is initially created, via ("key", "val") signature, - // keys will be converted to camelCase. - // Since there is no way to tell _how_ a key was added, remove - // both plain key and camelCase key. #12786 - // This will only penalize the array argument path. - name = key.concat( key.map( jQuery.camelCase ) ); - } else { - camel = jQuery.camelCase( key ); - // Try the string as a key before any manipulation - if ( key in cache ) { - name = [ key, camel ]; - } else { - // If a key with the spaces exists, use it. - // Otherwise, create an array by matching non-whitespace - name = camel; - name = name in cache ? - [ name ] : ( name.match( core_rnotwhite ) || [] ); - } - } - - i = name.length; - while ( i-- ) { - delete cache[ name[ i ] ]; - } - } - }, - hasData: function( owner ) { - return !jQuery.isEmptyObject( - this.cache[ owner[ this.expando ] ] || {} - ); - }, - discard: function( owner ) { - if ( owner[ this.expando ] ) { - delete this.cache[ owner[ this.expando ] ]; - } - } -}; - -// These may be used throughout the jQuery core codebase -data_user = new Data(); -data_priv = new Data(); - - -jQuery.extend({ - acceptData: Data.accepts, - - hasData: function( elem ) { - return data_user.hasData( elem ) || data_priv.hasData( elem ); - }, - - data: function( elem, name, data ) { - return data_user.access( elem, name, data ); - }, - - removeData: function( elem, name ) { - data_user.remove( elem, name ); - }, - - // TODO: Now that all calls to _data and _removeData have been replaced - // with direct calls to data_priv methods, these can be deprecated. - _data: function( elem, name, data ) { - return data_priv.access( elem, name, data ); - }, - - _removeData: function( elem, name ) { - data_priv.remove( elem, name ); - } -}); - -jQuery.fn.extend({ - data: function( key, value ) { - var attrs, name, - elem = this[ 0 ], - i = 0, - data = null; - - // Gets all values - if ( key === undefined ) { - if ( this.length ) { - data = data_user.get( elem ); - - if ( elem.nodeType === 1 && !data_priv.get( elem, "hasDataAttrs" ) ) { - attrs = elem.attributes; - for ( ; i < attrs.length; i++ ) { - name = attrs[ i ].name; - - if ( name.indexOf( "data-" ) === 0 ) { - name = jQuery.camelCase( name.slice(5) ); - dataAttr( elem, name, data[ name ] ); - } - } - data_priv.set( elem, "hasDataAttrs", true ); - } - } - - return data; - } - - // Sets multiple values - if ( typeof key === "object" ) { - return this.each(function() { - data_user.set( this, key ); - }); - } - - return jQuery.access( this, function( value ) { - var data, - camelKey = jQuery.camelCase( key ); - - // The calling jQuery object (element matches) is not empty - // (and therefore has an element appears at this[ 0 ]) and the - // `value` parameter was not undefined. An empty jQuery object - // will result in `undefined` for elem = this[ 0 ] which will - // throw an exception if an attempt to read a data cache is made. - if ( elem && value === undefined ) { - // Attempt to get data from the cache - // with the key as-is - data = data_user.get( elem, key ); - if ( data !== undefined ) { - return data; - } - - // Attempt to get data from the cache - // with the key camelized - data = data_user.get( elem, camelKey ); - if ( data !== undefined ) { - return data; - } - - // Attempt to "discover" the data in - // HTML5 custom data-* attrs - data = dataAttr( elem, camelKey, undefined ); - if ( data !== undefined ) { - return data; - } - - // We tried really hard, but the data doesn't exist. - return; - } - - // Set the data... - this.each(function() { - // First, attempt to store a copy or reference of any - // data that might've been store with a camelCased key. - var data = data_user.get( this, camelKey ); - - // For HTML5 data-* attribute interop, we have to - // store property names with dashes in a camelCase form. - // This might not apply to all properties...* - data_user.set( this, camelKey, value ); - - // *... In the case of properties that might _actually_ - // have dashes, we need to also store a copy of that - // unchanged property. - if ( key.indexOf("-") !== -1 && data !== undefined ) { - data_user.set( this, key, value ); - } - }); - }, null, value, arguments.length > 1, null, true ); - }, - - removeData: function( key ) { - return this.each(function() { - data_user.remove( this, key ); - }); - } -}); - -function dataAttr( elem, key, data ) { - var name; - - // If nothing was found internally, try to fetch any - // data from the HTML5 data-* attribute - if ( data === undefined && elem.nodeType === 1 ) { - name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase(); - data = elem.getAttribute( name ); - - if ( typeof data === "string" ) { - try { - data = data === "true" ? true : - data === "false" ? false : - data === "null" ? null : - // Only convert to a number if it doesn't change the string - +data + "" === data ? +data : - rbrace.test( data ) ? JSON.parse( data ) : - data; - } catch( e ) {} - - // Make sure we set the data so it isn't changed later - data_user.set( elem, key, data ); - } else { - data = undefined; - } - } - return data; -} -jQuery.extend({ - queue: function( elem, type, data ) { - var queue; - - if ( elem ) { - type = ( type || "fx" ) + "queue"; - queue = data_priv.get( elem, type ); - - // Speed up dequeue by getting out quickly if this is just a lookup - if ( data ) { - if ( !queue || jQuery.isArray( data ) ) { - queue = data_priv.access( elem, type, jQuery.makeArray(data) ); - } else { - queue.push( data ); - } - } - return queue || []; - } - }, - - dequeue: function( elem, type ) { - type = type || "fx"; - - var queue = jQuery.queue( elem, type ), - startLength = queue.length, - fn = queue.shift(), - hooks = jQuery._queueHooks( elem, type ), - next = function() { - jQuery.dequeue( elem, type ); - }; - - // If the fx queue is dequeued, always remove the progress sentinel - if ( fn === "inprogress" ) { - fn = queue.shift(); - startLength--; - } - - hooks.cur = fn; - if ( fn ) { - - // Add a progress sentinel to prevent the fx queue from being - // automatically dequeued - if ( type === "fx" ) { - queue.unshift( "inprogress" ); - } - - // clear up the last queue stop function - delete hooks.stop; - fn.call( elem, next, hooks ); - } - - if ( !startLength && hooks ) { - hooks.empty.fire(); - } - }, - - // not intended for public consumption - generates a queueHooks object, or returns the current one - _queueHooks: function( elem, type ) { - var key = type + "queueHooks"; - return data_priv.get( elem, key ) || data_priv.access( elem, key, { - empty: jQuery.Callbacks("once memory").add(function() { - data_priv.remove( elem, [ type + "queue", key ] ); - }) - }); - } -}); - -jQuery.fn.extend({ - queue: function( type, data ) { - var setter = 2; - - if ( typeof type !== "string" ) { - data = type; - type = "fx"; - setter--; - } - - if ( arguments.length < setter ) { - return jQuery.queue( this[0], type ); - } - - return data === undefined ? - this : - this.each(function() { - var queue = jQuery.queue( this, type, data ); - - // ensure a hooks for this queue - jQuery._queueHooks( this, type ); - - if ( type === "fx" && queue[0] !== "inprogress" ) { - jQuery.dequeue( this, type ); - } - }); - }, - dequeue: function( type ) { - return this.each(function() { - jQuery.dequeue( this, type ); - }); - }, - // Based off of the plugin by Clint Helfers, with permission. - // http://blindsignals.com/index.php/2009/07/jquery-delay/ - delay: function( time, type ) { - time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; - type = type || "fx"; - - return this.queue( type, function( next, hooks ) { - var timeout = setTimeout( next, time ); - hooks.stop = function() { - clearTimeout( timeout ); - }; - }); - }, - clearQueue: function( type ) { - return this.queue( type || "fx", [] ); - }, - // Get a promise resolved when queues of a certain type - // are emptied (fx is the type by default) - promise: function( type, obj ) { - var tmp, - count = 1, - defer = jQuery.Deferred(), - elements = this, - i = this.length, - resolve = function() { - if ( !( --count ) ) { - defer.resolveWith( elements, [ elements ] ); - } - }; - - if ( typeof type !== "string" ) { - obj = type; - type = undefined; - } - type = type || "fx"; - - while( i-- ) { - tmp = data_priv.get( elements[ i ], type + "queueHooks" ); - if ( tmp && tmp.empty ) { - count++; - tmp.empty.add( resolve ); - } - } - resolve(); - return defer.promise( obj ); - } -}); -var nodeHook, boolHook, - rclass = /[\t\r\n\f]/g, - rreturn = /\r/g, - rfocusable = /^(?:input|select|textarea|button)$/i; - -jQuery.fn.extend({ - attr: function( name, value ) { - return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 ); - }, - - removeAttr: function( name ) { - return this.each(function() { - jQuery.removeAttr( this, name ); - }); - }, - - prop: function( name, value ) { - return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 ); - }, - - removeProp: function( name ) { - return this.each(function() { - delete this[ jQuery.propFix[ name ] || name ]; - }); - }, - - addClass: function( value ) { - var classes, elem, cur, clazz, j, - i = 0, - len = this.length, - proceed = typeof value === "string" && value; - - if ( jQuery.isFunction( value ) ) { - return this.each(function( j ) { - jQuery( this ).addClass( value.call( this, j, this.className ) ); - }); - } - - if ( proceed ) { - // The disjunction here is for better compressibility (see removeClass) - classes = ( value || "" ).match( core_rnotwhite ) || []; - - for ( ; i < len; i++ ) { - elem = this[ i ]; - cur = elem.nodeType === 1 && ( elem.className ? - ( " " + elem.className + " " ).replace( rclass, " " ) : - " " - ); - - if ( cur ) { - j = 0; - while ( (clazz = classes[j++]) ) { - if ( cur.indexOf( " " + clazz + " " ) < 0 ) { - cur += clazz + " "; - } - } - elem.className = jQuery.trim( cur ); - - } - } - } - - return this; - }, - - removeClass: function( value ) { - var classes, elem, cur, clazz, j, - i = 0, - len = this.length, - proceed = arguments.length === 0 || typeof value === "string" && value; - - if ( jQuery.isFunction( value ) ) { - return this.each(function( j ) { - jQuery( this ).removeClass( value.call( this, j, this.className ) ); - }); - } - if ( proceed ) { - classes = ( value || "" ).match( core_rnotwhite ) || []; - - for ( ; i < len; i++ ) { - elem = this[ i ]; - // This expression is here for better compressibility (see addClass) - cur = elem.nodeType === 1 && ( elem.className ? - ( " " + elem.className + " " ).replace( rclass, " " ) : - "" - ); - - if ( cur ) { - j = 0; - while ( (clazz = classes[j++]) ) { - // Remove *all* instances - while ( cur.indexOf( " " + clazz + " " ) >= 0 ) { - cur = cur.replace( " " + clazz + " ", " " ); - } - } - elem.className = value ? jQuery.trim( cur ) : ""; - } - } - } - - return this; - }, - - toggleClass: function( value, stateVal ) { - var type = typeof value, - isBool = typeof stateVal === "boolean"; - - if ( jQuery.isFunction( value ) ) { - return this.each(function( i ) { - jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal ); - }); - } - - return this.each(function() { - if ( type === "string" ) { - // toggle individual class names - var className, - i = 0, - self = jQuery( this ), - state = stateVal, - classNames = value.match( core_rnotwhite ) || []; - - while ( (className = classNames[ i++ ]) ) { - // check each className given, space separated list - state = isBool ? state : !self.hasClass( className ); - self[ state ? "addClass" : "removeClass" ]( className ); - } - - // Toggle whole class name - } else if ( type === core_strundefined || type === "boolean" ) { - if ( this.className ) { - // store className if set - data_priv.set( this, "__className__", this.className ); - } - - // If the element has a class name or if we're passed "false", - // then remove the whole classname (if there was one, the above saved it). - // Otherwise bring back whatever was previously saved (if anything), - // falling back to the empty string if nothing was stored. - this.className = this.className || value === false ? "" : data_priv.get( this, "__className__" ) || ""; - } - }); - }, - - hasClass: function( selector ) { - var className = " " + selector + " ", - i = 0, - l = this.length; - for ( ; i < l; i++ ) { - if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) { - return true; - } - } - - return false; - }, - - val: function( value ) { - var hooks, ret, isFunction, - elem = this[0]; - - if ( !arguments.length ) { - if ( elem ) { - hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ]; - - if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) { - return ret; - } - - ret = elem.value; - - return typeof ret === "string" ? - // handle most common string cases - ret.replace(rreturn, "") : - // handle cases where value is null/undef or number - ret == null ? "" : ret; - } - - return; - } - - isFunction = jQuery.isFunction( value ); - - return this.each(function( i ) { - var val; - - if ( this.nodeType !== 1 ) { - return; - } - - if ( isFunction ) { - val = value.call( this, i, jQuery( this ).val() ); - } else { - val = value; - } - - // Treat null/undefined as ""; convert numbers to string - if ( val == null ) { - val = ""; - } else if ( typeof val === "number" ) { - val += ""; - } else if ( jQuery.isArray( val ) ) { - val = jQuery.map(val, function ( value ) { - return value == null ? "" : value + ""; - }); - } - - hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; - - // If set returns undefined, fall back to normal setting - if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) { - this.value = val; - } - }); - } -}); - -jQuery.extend({ - valHooks: { - option: { - get: function( elem ) { - // attributes.value is undefined in Blackberry 4.7 but - // uses .value. See #6932 - var val = elem.attributes.value; - return !val || val.specified ? elem.value : elem.text; - } - }, - select: { - get: function( elem ) { - var value, option, - options = elem.options, - index = elem.selectedIndex, - one = elem.type === "select-one" || index < 0, - values = one ? null : [], - max = one ? index + 1 : options.length, - i = index < 0 ? - max : - one ? index : 0; - - // Loop through all the selected options - for ( ; i < max; i++ ) { - option = options[ i ]; - - // IE6-9 doesn't update selected after form reset (#2551) - if ( ( option.selected || i === index ) && - // Don't return options that are disabled or in a disabled optgroup - ( jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null ) && - ( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) { - - // Get the specific value for the option - value = jQuery( option ).val(); - - // We don't need an array for one selects - if ( one ) { - return value; - } - - // Multi-Selects return an array - values.push( value ); - } - } - - return values; - }, - - set: function( elem, value ) { - var optionSet, option, - options = elem.options, - values = jQuery.makeArray( value ), - i = options.length; - - while ( i-- ) { - option = options[ i ]; - if ( (option.selected = jQuery.inArray( jQuery(option).val(), values ) >= 0) ) { - optionSet = true; - } - } - - // force browsers to behave consistently when non-matching value is set - if ( !optionSet ) { - elem.selectedIndex = -1; - } - return values; - } - } - }, - - attr: function( elem, name, value ) { - var hooks, ret, - nType = elem.nodeType; - - // don't get/set attributes on text, comment and attribute nodes - if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { - return; - } - - // Fallback to prop when attributes are not supported - if ( typeof elem.getAttribute === core_strundefined ) { - return jQuery.prop( elem, name, value ); - } - - // All attributes are lowercase - // Grab necessary hook if one is defined - if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { - name = name.toLowerCase(); - hooks = jQuery.attrHooks[ name ] || - ( jQuery.expr.match.bool.test( name ) ? boolHook : nodeHook ); - } - - if ( value !== undefined ) { - - if ( value === null ) { - jQuery.removeAttr( elem, name ); - - } else if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { - return ret; - - } else { - elem.setAttribute( name, value + "" ); - return value; - } - - } else if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { - return ret; - - } else { - ret = jQuery.find.attr( elem, name ); - - // Non-existent attributes return null, we normalize to undefined - return ret == null ? - undefined : - ret; - } - }, - - removeAttr: function( elem, value ) { - var name, propName, - i = 0, - attrNames = value && value.match( core_rnotwhite ); - - if ( attrNames && elem.nodeType === 1 ) { - while ( (name = attrNames[i++]) ) { - propName = jQuery.propFix[ name ] || name; - - // Boolean attributes get special treatment (#10870) - if ( jQuery.expr.match.bool.test( name ) ) { - // Set corresponding property to false - elem[ propName ] = false; - } - - elem.removeAttribute( name ); - } - } - }, - - attrHooks: { - type: { - set: function( elem, value ) { - if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) { - // Setting the type on a radio button after the value resets the value in IE6-9 - // Reset value to default in case type is set after value during creation - var val = elem.value; - elem.setAttribute( "type", value ); - if ( val ) { - elem.value = val; - } - return value; - } - } - } - }, - - propFix: { - "for": "htmlFor", - "class": "className" - }, - - prop: function( elem, name, value ) { - var ret, hooks, notxml, - nType = elem.nodeType; - - // don't get/set properties on text, comment and attribute nodes - if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { - return; - } - - notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); - - if ( notxml ) { - // Fix name and attach hooks - name = jQuery.propFix[ name ] || name; - hooks = jQuery.propHooks[ name ]; - } - - if ( value !== undefined ) { - return hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ? - ret : - ( elem[ name ] = value ); - - } else { - return hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ? - ret : - elem[ name ]; - } - }, - - propHooks: { - tabIndex: { - get: function( elem ) { - return elem.hasAttribute( "tabindex" ) || rfocusable.test( elem.nodeName ) || elem.href ? - elem.tabIndex : - -1; - } - } - } -}); - -// Hooks for boolean attributes -boolHook = { - set: function( elem, value, name ) { - if ( value === false ) { - // Remove boolean attributes when set to false - jQuery.removeAttr( elem, name ); - } else { - elem.setAttribute( name, name ); - } - return name; - } -}; -jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) { - var getter = jQuery.expr.attrHandle[ name ] || jQuery.find.attr; - - jQuery.expr.attrHandle[ name ] = function( elem, name, isXML ) { - var fn = jQuery.expr.attrHandle[ name ], - ret = isXML ? - undefined : - /* jshint eqeqeq: false */ - // Temporarily disable this handler to check existence - (jQuery.expr.attrHandle[ name ] = undefined) != - getter( elem, name, isXML ) ? - - name.toLowerCase() : - null; - - // Restore handler - jQuery.expr.attrHandle[ name ] = fn; - - return ret; - }; -}); - -// Support: IE9+ -// Selectedness for an option in an optgroup can be inaccurate -if ( !jQuery.support.optSelected ) { - jQuery.propHooks.selected = { - get: function( elem ) { - var parent = elem.parentNode; - if ( parent && parent.parentNode ) { - parent.parentNode.selectedIndex; - } - return null; - } - }; -} - -jQuery.each([ - "tabIndex", - "readOnly", - "maxLength", - "cellSpacing", - "cellPadding", - "rowSpan", - "colSpan", - "useMap", - "frameBorder", - "contentEditable" -], function() { - jQuery.propFix[ this.toLowerCase() ] = this; -}); - -// Radios and checkboxes getter/setter -jQuery.each([ "radio", "checkbox" ], function() { - jQuery.valHooks[ this ] = { - set: function( elem, value ) { - if ( jQuery.isArray( value ) ) { - return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 ); - } - } - }; - if ( !jQuery.support.checkOn ) { - jQuery.valHooks[ this ].get = function( elem ) { - // Support: Webkit - // "" is returned instead of "on" if a value isn't specified - return elem.getAttribute("value") === null ? "on" : elem.value; - }; - } -}); -var rkeyEvent = /^key/, - rmouseEvent = /^(?:mouse|contextmenu)|click/, - rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, - rtypenamespace = /^([^.]*)(?:\.(.+)|)$/; - -function returnTrue() { - return true; -} - -function returnFalse() { - return false; -} - -function safeActiveElement() { - try { - return document.activeElement; - } catch ( err ) { } -} - -/* - * Helper functions for managing events -- not part of the public interface. - * Props to Dean Edwards' addEvent library for many of the ideas. - */ -jQuery.event = { - - global: {}, - - add: function( elem, types, handler, data, selector ) { - - var handleObjIn, eventHandle, tmp, - events, t, handleObj, - special, handlers, type, namespaces, origType, - elemData = data_priv.get( elem ); - - // Don't attach events to noData or text/comment nodes (but allow plain objects) - if ( !elemData ) { - return; - } - - // Caller can pass in an object of custom data in lieu of the handler - if ( handler.handler ) { - handleObjIn = handler; - handler = handleObjIn.handler; - selector = handleObjIn.selector; - } - - // Make sure that the handler has a unique ID, used to find/remove it later - if ( !handler.guid ) { - handler.guid = jQuery.guid++; - } - - // Init the element's event structure and main handler, if this is the first - if ( !(events = elemData.events) ) { - events = elemData.events = {}; - } - if ( !(eventHandle = elemData.handle) ) { - eventHandle = elemData.handle = function( e ) { - // Discard the second event of a jQuery.event.trigger() and - // when an event is called after a page has unloaded - return typeof jQuery !== core_strundefined && (!e || jQuery.event.triggered !== e.type) ? - jQuery.event.dispatch.apply( eventHandle.elem, arguments ) : - undefined; - }; - // Add elem as a property of the handle fn to prevent a memory leak with IE non-native events - eventHandle.elem = elem; - } - - // Handle multiple events separated by a space - types = ( types || "" ).match( core_rnotwhite ) || [""]; - t = types.length; - while ( t-- ) { - tmp = rtypenamespace.exec( types[t] ) || []; - type = origType = tmp[1]; - namespaces = ( tmp[2] || "" ).split( "." ).sort(); - - // There *must* be a type, no attaching namespace-only handlers - if ( !type ) { - continue; - } - - // If event changes its type, use the special event handlers for the changed type - special = jQuery.event.special[ type ] || {}; - - // If selector defined, determine special event api type, otherwise given type - type = ( selector ? special.delegateType : special.bindType ) || type; - - // Update special based on newly reset type - special = jQuery.event.special[ type ] || {}; - - // handleObj is passed to all event handlers - handleObj = jQuery.extend({ - type: type, - origType: origType, - data: data, - handler: handler, - guid: handler.guid, - selector: selector, - needsContext: selector && jQuery.expr.match.needsContext.test( selector ), - namespace: namespaces.join(".") - }, handleObjIn ); - - // Init the event handler queue if we're the first - if ( !(handlers = events[ type ]) ) { - handlers = events[ type ] = []; - handlers.delegateCount = 0; - - // Only use addEventListener if the special events handler returns false - if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { - if ( elem.addEventListener ) { - elem.addEventListener( type, eventHandle, false ); - } - } - } - - if ( special.add ) { - special.add.call( elem, handleObj ); - - if ( !handleObj.handler.guid ) { - handleObj.handler.guid = handler.guid; - } - } - - // Add to the element's handler list, delegates in front - if ( selector ) { - handlers.splice( handlers.delegateCount++, 0, handleObj ); - } else { - handlers.push( handleObj ); - } - - // Keep track of which events have ever been used, for event optimization - jQuery.event.global[ type ] = true; - } - - // Nullify elem to prevent memory leaks in IE - elem = null; - }, - - // Detach an event or set of events from an element - remove: function( elem, types, handler, selector, mappedTypes ) { - - var j, origCount, tmp, - events, t, handleObj, - special, handlers, type, namespaces, origType, - elemData = data_priv.hasData( elem ) && data_priv.get( elem ); - - if ( !elemData || !(events = elemData.events) ) { - return; - } - - // Once for each type.namespace in types; type may be omitted - types = ( types || "" ).match( core_rnotwhite ) || [""]; - t = types.length; - while ( t-- ) { - tmp = rtypenamespace.exec( types[t] ) || []; - type = origType = tmp[1]; - namespaces = ( tmp[2] || "" ).split( "." ).sort(); - - // Unbind all events (on this namespace, if provided) for the element - if ( !type ) { - for ( type in events ) { - jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); - } - continue; - } - - special = jQuery.event.special[ type ] || {}; - type = ( selector ? special.delegateType : special.bindType ) || type; - handlers = events[ type ] || []; - tmp = tmp[2] && new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ); - - // Remove matching events - origCount = j = handlers.length; - while ( j-- ) { - handleObj = handlers[ j ]; - - if ( ( mappedTypes || origType === handleObj.origType ) && - ( !handler || handler.guid === handleObj.guid ) && - ( !tmp || tmp.test( handleObj.namespace ) ) && - ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { - handlers.splice( j, 1 ); - - if ( handleObj.selector ) { - handlers.delegateCount--; - } - if ( special.remove ) { - special.remove.call( elem, handleObj ); - } - } - } - - // Remove generic event handler if we removed something and no more handlers exist - // (avoids potential for endless recursion during removal of special event handlers) - if ( origCount && !handlers.length ) { - if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) { - jQuery.removeEvent( elem, type, elemData.handle ); - } - - delete events[ type ]; - } - } - - // Remove the expando if it's no longer used - if ( jQuery.isEmptyObject( events ) ) { - delete elemData.handle; - data_priv.remove( elem, "events" ); - } - }, - - trigger: function( event, data, elem, onlyHandlers ) { - - var i, cur, tmp, bubbleType, ontype, handle, special, - eventPath = [ elem || document ], - type = core_hasOwn.call( event, "type" ) ? event.type : event, - namespaces = core_hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : []; - - cur = tmp = elem = elem || document; - - // Don't do events on text and comment nodes - if ( elem.nodeType === 3 || elem.nodeType === 8 ) { - return; - } - - // focus/blur morphs to focusin/out; ensure we're not firing them right now - if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { - return; - } - - if ( type.indexOf(".") >= 0 ) { - // Namespaced trigger; create a regexp to match event type in handle() - namespaces = type.split("."); - type = namespaces.shift(); - namespaces.sort(); - } - ontype = type.indexOf(":") < 0 && "on" + type; - - // Caller can pass in a jQuery.Event object, Object, or just an event type string - event = event[ jQuery.expando ] ? - event : - new jQuery.Event( type, typeof event === "object" && event ); - - // Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true) - event.isTrigger = onlyHandlers ? 2 : 3; - event.namespace = namespaces.join("."); - event.namespace_re = event.namespace ? - new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) : - null; - - // Clean up the event in case it is being reused - event.result = undefined; - if ( !event.target ) { - event.target = elem; - } - - // Clone any incoming data and prepend the event, creating the handler arg list - data = data == null ? - [ event ] : - jQuery.makeArray( data, [ event ] ); - - // Allow special events to draw outside the lines - special = jQuery.event.special[ type ] || {}; - if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) { - return; - } - - // Determine event propagation path in advance, per W3C events spec (#9951) - // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) - if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { - - bubbleType = special.delegateType || type; - if ( !rfocusMorph.test( bubbleType + type ) ) { - cur = cur.parentNode; - } - for ( ; cur; cur = cur.parentNode ) { - eventPath.push( cur ); - tmp = cur; - } - - // Only add window if we got to document (e.g., not plain obj or detached DOM) - if ( tmp === (elem.ownerDocument || document) ) { - eventPath.push( tmp.defaultView || tmp.parentWindow || window ); - } - } - - // Fire handlers on the event path - i = 0; - while ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) { - - event.type = i > 1 ? - bubbleType : - special.bindType || type; - - // jQuery handler - handle = ( data_priv.get( cur, "events" ) || {} )[ event.type ] && data_priv.get( cur, "handle" ); - if ( handle ) { - handle.apply( cur, data ); - } - - // Native handler - handle = ontype && cur[ ontype ]; - if ( handle && jQuery.acceptData( cur ) && handle.apply && handle.apply( cur, data ) === false ) { - event.preventDefault(); - } - } - event.type = type; - - // If nobody prevented the default action, do it now - if ( !onlyHandlers && !event.isDefaultPrevented() ) { - - if ( (!special._default || special._default.apply( eventPath.pop(), data ) === false) && - jQuery.acceptData( elem ) ) { - - // Call a native DOM method on the target with the same name name as the event. - // Don't do default actions on window, that's where global variables be (#6170) - if ( ontype && jQuery.isFunction( elem[ type ] ) && !jQuery.isWindow( elem ) ) { - - // Don't re-trigger an onFOO event when we call its FOO() method - tmp = elem[ ontype ]; - - if ( tmp ) { - elem[ ontype ] = null; - } - - // Prevent re-triggering of the same event, since we already bubbled it above - jQuery.event.triggered = type; - elem[ type ](); - jQuery.event.triggered = undefined; - - if ( tmp ) { - elem[ ontype ] = tmp; - } - } - } - } - - return event.result; - }, - - dispatch: function( event ) { - - // Make a writable jQuery.Event from the native event object - event = jQuery.event.fix( event ); - - var i, j, ret, matched, handleObj, - handlerQueue = [], - args = core_slice.call( arguments ), - handlers = ( data_priv.get( this, "events" ) || {} )[ event.type ] || [], - special = jQuery.event.special[ event.type ] || {}; - - // Use the fix-ed jQuery.Event rather than the (read-only) native event - args[0] = event; - event.delegateTarget = this; - - // Call the preDispatch hook for the mapped type, and let it bail if desired - if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { - return; - } - - // Determine handlers - handlerQueue = jQuery.event.handlers.call( this, event, handlers ); - - // Run delegates first; they may want to stop propagation beneath us - i = 0; - while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) { - event.currentTarget = matched.elem; - - j = 0; - while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) { - - // Triggered event must either 1) have no namespace, or - // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace). - if ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) { - - event.handleObj = handleObj; - event.data = handleObj.data; - - ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) - .apply( matched.elem, args ); - - if ( ret !== undefined ) { - if ( (event.result = ret) === false ) { - event.preventDefault(); - event.stopPropagation(); - } - } - } - } - } - - // Call the postDispatch hook for the mapped type - if ( special.postDispatch ) { - special.postDispatch.call( this, event ); - } - - return event.result; - }, - - handlers: function( event, handlers ) { - var i, matches, sel, handleObj, - handlerQueue = [], - delegateCount = handlers.delegateCount, - cur = event.target; - - // Find delegate handlers - // Black-hole SVG instance trees (#13180) - // Avoid non-left-click bubbling in Firefox (#3861) - if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) { - - for ( ; cur !== this; cur = cur.parentNode || this ) { - - // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) - if ( cur.disabled !== true || event.type !== "click" ) { - matches = []; - for ( i = 0; i < delegateCount; i++ ) { - handleObj = handlers[ i ]; - - // Don't conflict with Object.prototype properties (#13203) - sel = handleObj.selector + " "; - - if ( matches[ sel ] === undefined ) { - matches[ sel ] = handleObj.needsContext ? - jQuery( sel, this ).index( cur ) >= 0 : - jQuery.find( sel, this, null, [ cur ] ).length; - } - if ( matches[ sel ] ) { - matches.push( handleObj ); - } - } - if ( matches.length ) { - handlerQueue.push({ elem: cur, handlers: matches }); - } - } - } - } - - // Add the remaining (directly-bound) handlers - if ( delegateCount < handlers.length ) { - handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) }); - } - - return handlerQueue; - }, - - // Includes some event props shared by KeyEvent and MouseEvent - props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "), - - fixHooks: {}, - - keyHooks: { - props: "char charCode key keyCode".split(" "), - filter: function( event, original ) { - - // Add which for key events - if ( event.which == null ) { - event.which = original.charCode != null ? original.charCode : original.keyCode; - } - - return event; - } - }, - - mouseHooks: { - props: "button buttons clientX clientY offsetX offsetY pageX pageY screenX screenY toElement".split(" "), - filter: function( event, original ) { - var eventDoc, doc, body, - button = original.button; - - // Calculate pageX/Y if missing and clientX/Y available - if ( event.pageX == null && original.clientX != null ) { - eventDoc = event.target.ownerDocument || document; - doc = eventDoc.documentElement; - body = eventDoc.body; - - event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 ); - event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 ); - } - - // Add which for click: 1 === left; 2 === middle; 3 === right - // Note: button is not normalized, so don't use it - if ( !event.which && button !== undefined ) { - event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); - } - - return event; - } - }, - - fix: function( event ) { - if ( event[ jQuery.expando ] ) { - return event; - } - - // Create a writable copy of the event object and normalize some properties - var i, prop, copy, - type = event.type, - originalEvent = event, - fixHook = this.fixHooks[ type ]; - - if ( !fixHook ) { - this.fixHooks[ type ] = fixHook = - rmouseEvent.test( type ) ? this.mouseHooks : - rkeyEvent.test( type ) ? this.keyHooks : - {}; - } - copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; - - event = new jQuery.Event( originalEvent ); - - i = copy.length; - while ( i-- ) { - prop = copy[ i ]; - event[ prop ] = originalEvent[ prop ]; - } - - // Support: Cordova 2.5 (WebKit) (#13255) - // All events should have a target; Cordova deviceready doesn't - if ( !event.target ) { - event.target = document; - } - - // Support: Safari 6.0+, Chrome < 28 - // Target should not be a text node (#504, #13143) - if ( event.target.nodeType === 3 ) { - event.target = event.target.parentNode; - } - - return fixHook.filter? fixHook.filter( event, originalEvent ) : event; - }, - - special: { - load: { - // Prevent triggered image.load events from bubbling to window.load - noBubble: true - }, - focus: { - // Fire native event if possible so blur/focus sequence is correct - trigger: function() { - if ( this !== safeActiveElement() && this.focus ) { - this.focus(); - return false; - } - }, - delegateType: "focusin" - }, - blur: { - trigger: function() { - if ( this === safeActiveElement() && this.blur ) { - this.blur(); - return false; - } - }, - delegateType: "focusout" - }, - click: { - // For checkbox, fire native event so checked state will be right - trigger: function() { - if ( this.type === "checkbox" && this.click && jQuery.nodeName( this, "input" ) ) { - this.click(); - return false; - } - }, - - // For cross-browser consistency, don't fire native .click() on links - _default: function( event ) { - return jQuery.nodeName( event.target, "a" ); - } - }, - - beforeunload: { - postDispatch: function( event ) { - - // Support: Firefox 20+ - // Firefox doesn't alert if the returnValue field is not set. - if ( event.result !== undefined ) { - event.originalEvent.returnValue = event.result; - } - } - } - }, - - simulate: function( type, elem, event, bubble ) { - // Piggyback on a donor event to simulate a different one. - // Fake originalEvent to avoid donor's stopPropagation, but if the - // simulated event prevents default then we do the same on the donor. - var e = jQuery.extend( - new jQuery.Event(), - event, - { - type: type, - isSimulated: true, - originalEvent: {} - } - ); - if ( bubble ) { - jQuery.event.trigger( e, null, elem ); - } else { - jQuery.event.dispatch.call( elem, e ); - } - if ( e.isDefaultPrevented() ) { - event.preventDefault(); - } - } -}; - -jQuery.removeEvent = function( elem, type, handle ) { - if ( elem.removeEventListener ) { - elem.removeEventListener( type, handle, false ); - } -}; - -jQuery.Event = function( src, props ) { - // Allow instantiation without the 'new' keyword - if ( !(this instanceof jQuery.Event) ) { - return new jQuery.Event( src, props ); - } - - // Event object - if ( src && src.type ) { - this.originalEvent = src; - this.type = src.type; - - // Events bubbling up the document may have been marked as prevented - // by a handler lower down the tree; reflect the correct value. - this.isDefaultPrevented = ( src.defaultPrevented || - src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse; - - // Event type - } else { - this.type = src; - } - - // Put explicitly provided properties onto the event object - if ( props ) { - jQuery.extend( this, props ); - } - - // Create a timestamp if incoming event doesn't have one - this.timeStamp = src && src.timeStamp || jQuery.now(); - - // Mark it as fixed - this[ jQuery.expando ] = true; -}; - -// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding -// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html -jQuery.Event.prototype = { - isDefaultPrevented: returnFalse, - isPropagationStopped: returnFalse, - isImmediatePropagationStopped: returnFalse, - - preventDefault: function() { - var e = this.originalEvent; - - this.isDefaultPrevented = returnTrue; - - if ( e && e.preventDefault ) { - e.preventDefault(); - } - }, - stopPropagation: function() { - var e = this.originalEvent; - - this.isPropagationStopped = returnTrue; - - if ( e && e.stopPropagation ) { - e.stopPropagation(); - } - }, - stopImmediatePropagation: function() { - this.isImmediatePropagationStopped = returnTrue; - this.stopPropagation(); - } -}; - -// Create mouseenter/leave events using mouseover/out and event-time checks -// Support: Chrome 15+ -jQuery.each({ - mouseenter: "mouseover", - mouseleave: "mouseout" -}, function( orig, fix ) { - jQuery.event.special[ orig ] = { - delegateType: fix, - bindType: fix, - - handle: function( event ) { - var ret, - target = this, - related = event.relatedTarget, - handleObj = event.handleObj; - - // For mousenter/leave call the handler if related is outside the target. - // NB: No relatedTarget if the mouse left/entered the browser window - if ( !related || (related !== target && !jQuery.contains( target, related )) ) { - event.type = handleObj.origType; - ret = handleObj.handler.apply( this, arguments ); - event.type = fix; - } - return ret; - } - }; -}); - -// Create "bubbling" focus and blur events -// Support: Firefox, Chrome, Safari -if ( !jQuery.support.focusinBubbles ) { - jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { - - // Attach a single capturing handler while someone wants focusin/focusout - var attaches = 0, - handler = function( event ) { - jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); - }; - - jQuery.event.special[ fix ] = { - setup: function() { - if ( attaches++ === 0 ) { - document.addEventListener( orig, handler, true ); - } - }, - teardown: function() { - if ( --attaches === 0 ) { - document.removeEventListener( orig, handler, true ); - } - } - }; - }); -} - -jQuery.fn.extend({ - - on: function( types, selector, data, fn, /*INTERNAL*/ one ) { - var origFn, type; - - // Types can be a map of types/handlers - if ( typeof types === "object" ) { - // ( types-Object, selector, data ) - if ( typeof selector !== "string" ) { - // ( types-Object, data ) - data = data || selector; - selector = undefined; - } - for ( type in types ) { - this.on( type, selector, data, types[ type ], one ); - } - return this; - } - - if ( data == null && fn == null ) { - // ( types, fn ) - fn = selector; - data = selector = undefined; - } else if ( fn == null ) { - if ( typeof selector === "string" ) { - // ( types, selector, fn ) - fn = data; - data = undefined; - } else { - // ( types, data, fn ) - fn = data; - data = selector; - selector = undefined; - } - } - if ( fn === false ) { - fn = returnFalse; - } else if ( !fn ) { - return this; - } - - if ( one === 1 ) { - origFn = fn; - fn = function( event ) { - // Can use an empty set, since event contains the info - jQuery().off( event ); - return origFn.apply( this, arguments ); - }; - // Use same guid so caller can remove using origFn - fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); - } - return this.each( function() { - jQuery.event.add( this, types, fn, data, selector ); - }); - }, - one: function( types, selector, data, fn ) { - return this.on( types, selector, data, fn, 1 ); - }, - off: function( types, selector, fn ) { - var handleObj, type; - if ( types && types.preventDefault && types.handleObj ) { - // ( event ) dispatched jQuery.Event - handleObj = types.handleObj; - jQuery( types.delegateTarget ).off( - handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, - handleObj.selector, - handleObj.handler - ); - return this; - } - if ( typeof types === "object" ) { - // ( types-object [, selector] ) - for ( type in types ) { - this.off( type, selector, types[ type ] ); - } - return this; - } - if ( selector === false || typeof selector === "function" ) { - // ( types [, fn] ) - fn = selector; - selector = undefined; - } - if ( fn === false ) { - fn = returnFalse; - } - return this.each(function() { - jQuery.event.remove( this, types, fn, selector ); - }); - }, - - trigger: function( type, data ) { - return this.each(function() { - jQuery.event.trigger( type, data, this ); - }); - }, - triggerHandler: function( type, data ) { - var elem = this[0]; - if ( elem ) { - return jQuery.event.trigger( type, data, elem, true ); - } - } -}); -var isSimple = /^.[^:#\[\.,]*$/, - rparentsprev = /^(?:parents|prev(?:Until|All))/, - rneedsContext = jQuery.expr.match.needsContext, - // methods guaranteed to produce a unique set when starting from a unique set - guaranteedUnique = { - children: true, - contents: true, - next: true, - prev: true - }; - -jQuery.fn.extend({ - find: function( selector ) { - var i, - ret = [], - self = this, - len = self.length; - - if ( typeof selector !== "string" ) { - return this.pushStack( jQuery( selector ).filter(function() { - for ( i = 0; i < len; i++ ) { - if ( jQuery.contains( self[ i ], this ) ) { - return true; - } - } - }) ); - } - - for ( i = 0; i < len; i++ ) { - jQuery.find( selector, self[ i ], ret ); - } - - // Needed because $( selector, context ) becomes $( context ).find( selector ) - ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret ); - ret.selector = this.selector ? this.selector + " " + selector : selector; - return ret; - }, - - has: function( target ) { - var targets = jQuery( target, this ), - l = targets.length; - - return this.filter(function() { - var i = 0; - for ( ; i < l; i++ ) { - if ( jQuery.contains( this, targets[i] ) ) { - return true; - } - } - }); - }, - - not: function( selector ) { - return this.pushStack( winnow(this, selector || [], true) ); - }, - - filter: function( selector ) { - return this.pushStack( winnow(this, selector || [], false) ); - }, - - is: function( selector ) { - return !!winnow( - this, - - // If this is a positional/relative selector, check membership in the returned set - // so $("p:first").is("p:last") won't return true for a doc with two "p". - typeof selector === "string" && rneedsContext.test( selector ) ? - jQuery( selector ) : - selector || [], - false - ).length; - }, - - closest: function( selectors, context ) { - var cur, - i = 0, - l = this.length, - matched = [], - pos = ( rneedsContext.test( selectors ) || typeof selectors !== "string" ) ? - jQuery( selectors, context || this.context ) : - 0; - - for ( ; i < l; i++ ) { - for ( cur = this[i]; cur && cur !== context; cur = cur.parentNode ) { - // Always skip document fragments - if ( cur.nodeType < 11 && (pos ? - pos.index(cur) > -1 : - - // Don't pass non-elements to Sizzle - cur.nodeType === 1 && - jQuery.find.matchesSelector(cur, selectors)) ) { - - cur = matched.push( cur ); - break; - } - } - } - - return this.pushStack( matched.length > 1 ? jQuery.unique( matched ) : matched ); - }, - - // Determine the position of an element within - // the matched set of elements - index: function( elem ) { - - // No argument, return index in parent - if ( !elem ) { - return ( this[ 0 ] && this[ 0 ].parentNode ) ? this.first().prevAll().length : -1; - } - - // index in selector - if ( typeof elem === "string" ) { - return core_indexOf.call( jQuery( elem ), this[ 0 ] ); - } - - // Locate the position of the desired element - return core_indexOf.call( this, - - // If it receives a jQuery object, the first element is used - elem.jquery ? elem[ 0 ] : elem - ); - }, - - add: function( selector, context ) { - var set = typeof selector === "string" ? - jQuery( selector, context ) : - jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ), - all = jQuery.merge( this.get(), set ); - - return this.pushStack( jQuery.unique(all) ); - }, - - addBack: function( selector ) { - return this.add( selector == null ? - this.prevObject : this.prevObject.filter(selector) - ); - } -}); - -function sibling( cur, dir ) { - while ( (cur = cur[dir]) && cur.nodeType !== 1 ) {} - - return cur; -} - -jQuery.each({ - parent: function( elem ) { - var parent = elem.parentNode; - return parent && parent.nodeType !== 11 ? parent : null; - }, - parents: function( elem ) { - return jQuery.dir( elem, "parentNode" ); - }, - parentsUntil: function( elem, i, until ) { - return jQuery.dir( elem, "parentNode", until ); - }, - next: function( elem ) { - return sibling( elem, "nextSibling" ); - }, - prev: function( elem ) { - return sibling( elem, "previousSibling" ); - }, - nextAll: function( elem ) { - return jQuery.dir( elem, "nextSibling" ); - }, - prevAll: function( elem ) { - return jQuery.dir( elem, "previousSibling" ); - }, - nextUntil: function( elem, i, until ) { - return jQuery.dir( elem, "nextSibling", until ); - }, - prevUntil: function( elem, i, until ) { - return jQuery.dir( elem, "previousSibling", until ); - }, - siblings: function( elem ) { - return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem ); - }, - children: function( elem ) { - return jQuery.sibling( elem.firstChild ); - }, - contents: function( elem ) { - return jQuery.nodeName( elem, "iframe" ) ? - elem.contentDocument || elem.contentWindow.document : - jQuery.merge( [], elem.childNodes ); - } -}, function( name, fn ) { - jQuery.fn[ name ] = function( until, selector ) { - var matched = jQuery.map( this, fn, until ); - - if ( name.slice( -5 ) !== "Until" ) { - selector = until; - } - - if ( selector && typeof selector === "string" ) { - matched = jQuery.filter( selector, matched ); - } - - if ( this.length > 1 ) { - // Remove duplicates - if ( !guaranteedUnique[ name ] ) { - jQuery.unique( matched ); - } - - // Reverse order for parents* and prev-derivatives - if ( rparentsprev.test( name ) ) { - matched.reverse(); - } - } - - return this.pushStack( matched ); - }; -}); - -jQuery.extend({ - filter: function( expr, elems, not ) { - var elem = elems[ 0 ]; - - if ( not ) { - expr = ":not(" + expr + ")"; - } - - return elems.length === 1 && elem.nodeType === 1 ? - jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] : - jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) { - return elem.nodeType === 1; - })); - }, - - dir: function( elem, dir, until ) { - var matched = [], - truncate = until !== undefined; - - while ( (elem = elem[ dir ]) && elem.nodeType !== 9 ) { - if ( elem.nodeType === 1 ) { - if ( truncate && jQuery( elem ).is( until ) ) { - break; - } - matched.push( elem ); - } - } - return matched; - }, - - sibling: function( n, elem ) { - var matched = []; - - for ( ; n; n = n.nextSibling ) { - if ( n.nodeType === 1 && n !== elem ) { - matched.push( n ); - } - } - - return matched; - } -}); - -// Implement the identical functionality for filter and not -function winnow( elements, qualifier, not ) { - if ( jQuery.isFunction( qualifier ) ) { - return jQuery.grep( elements, function( elem, i ) { - /* jshint -W018 */ - return !!qualifier.call( elem, i, elem ) !== not; - }); - - } - - if ( qualifier.nodeType ) { - return jQuery.grep( elements, function( elem ) { - return ( elem === qualifier ) !== not; - }); - - } - - if ( typeof qualifier === "string" ) { - if ( isSimple.test( qualifier ) ) { - return jQuery.filter( qualifier, elements, not ); - } - - qualifier = jQuery.filter( qualifier, elements ); - } - - return jQuery.grep( elements, function( elem ) { - return ( core_indexOf.call( qualifier, elem ) >= 0 ) !== not; - }); -} -var rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, - rtagName = /<([\w:]+)/, - rhtml = /<|&#?\w+;/, - rnoInnerhtml = /<(?:script|style|link)/i, - manipulation_rcheckableType = /^(?:checkbox|radio)$/i, - // checked="checked" or checked - rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, - rscriptType = /^$|\/(?:java|ecma)script/i, - rscriptTypeMasked = /^true\/(.*)/, - rcleanScript = /^\s*\s*$/g, - - // We have to close these tags to support XHTML (#13200) - wrapMap = { - - // Support: IE 9 - option: [ 1, "" ], - - thead: [ 1, "", "
        " ], - col: [ 2, "", "
        " ], - tr: [ 2, "", "
        " ], - td: [ 3, "", "
        " ], - - _default: [ 0, "", "" ] - }; - -// Support: IE 9 -wrapMap.optgroup = wrapMap.option; - -wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; -wrapMap.th = wrapMap.td; - -jQuery.fn.extend({ - text: function( value ) { - return jQuery.access( this, function( value ) { - return value === undefined ? - jQuery.text( this ) : - this.empty().append( ( this[ 0 ] && this[ 0 ].ownerDocument || document ).createTextNode( value ) ); - }, null, value, arguments.length ); - }, - - append: function() { - return this.domManip( arguments, function( elem ) { - if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { - var target = manipulationTarget( this, elem ); - target.appendChild( elem ); - } - }); - }, - - prepend: function() { - return this.domManip( arguments, function( elem ) { - if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { - var target = manipulationTarget( this, elem ); - target.insertBefore( elem, target.firstChild ); - } - }); - }, - - before: function() { - return this.domManip( arguments, function( elem ) { - if ( this.parentNode ) { - this.parentNode.insertBefore( elem, this ); - } - }); - }, - - after: function() { - return this.domManip( arguments, function( elem ) { - if ( this.parentNode ) { - this.parentNode.insertBefore( elem, this.nextSibling ); - } - }); - }, - - // keepData is for internal use only--do not document - remove: function( selector, keepData ) { - var elem, - elems = selector ? jQuery.filter( selector, this ) : this, - i = 0; - - for ( ; (elem = elems[i]) != null; i++ ) { - if ( !keepData && elem.nodeType === 1 ) { - jQuery.cleanData( getAll( elem ) ); - } - - if ( elem.parentNode ) { - if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) { - setGlobalEval( getAll( elem, "script" ) ); - } - elem.parentNode.removeChild( elem ); - } - } - - return this; - }, - - empty: function() { - var elem, - i = 0; - - for ( ; (elem = this[i]) != null; i++ ) { - if ( elem.nodeType === 1 ) { - - // Prevent memory leaks - jQuery.cleanData( getAll( elem, false ) ); - - // Remove any remaining nodes - elem.textContent = ""; - } - } - - return this; - }, - - clone: function( dataAndEvents, deepDataAndEvents ) { - dataAndEvents = dataAndEvents == null ? false : dataAndEvents; - deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; - - return this.map( function () { - return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); - }); - }, - - html: function( value ) { - return jQuery.access( this, function( value ) { - var elem = this[ 0 ] || {}, - i = 0, - l = this.length; - - if ( value === undefined && elem.nodeType === 1 ) { - return elem.innerHTML; - } - - // See if we can take a shortcut and just use innerHTML - if ( typeof value === "string" && !rnoInnerhtml.test( value ) && - !wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) { - - value = value.replace( rxhtmlTag, "<$1>" ); - - try { - for ( ; i < l; i++ ) { - elem = this[ i ] || {}; - - // Remove element nodes and prevent memory leaks - if ( elem.nodeType === 1 ) { - jQuery.cleanData( getAll( elem, false ) ); - elem.innerHTML = value; - } - } - - elem = 0; - - // If using innerHTML throws an exception, use the fallback method - } catch( e ) {} - } - - if ( elem ) { - this.empty().append( value ); - } - }, null, value, arguments.length ); - }, - - replaceWith: function() { - var - // Snapshot the DOM in case .domManip sweeps something relevant into its fragment - args = jQuery.map( this, function( elem ) { - return [ elem.nextSibling, elem.parentNode ]; - }), - i = 0; - - // Make the changes, replacing each context element with the new content - this.domManip( arguments, function( elem ) { - var next = args[ i++ ], - parent = args[ i++ ]; - - if ( parent ) { - // Don't use the snapshot next if it has moved (#13810) - if ( next && next.parentNode !== parent ) { - next = this.nextSibling; - } - jQuery( this ).remove(); - parent.insertBefore( elem, next ); - } - // Allow new content to include elements from the context set - }, true ); - - // Force removal if there was no new content (e.g., from empty arguments) - return i ? this : this.remove(); - }, - - detach: function( selector ) { - return this.remove( selector, true ); - }, - - domManip: function( args, callback, allowIntersection ) { - - // Flatten any nested arrays - args = core_concat.apply( [], args ); - - var fragment, first, scripts, hasScripts, node, doc, - i = 0, - l = this.length, - set = this, - iNoClone = l - 1, - value = args[ 0 ], - isFunction = jQuery.isFunction( value ); - - // We can't cloneNode fragments that contain checked, in WebKit - if ( isFunction || !( l <= 1 || typeof value !== "string" || jQuery.support.checkClone || !rchecked.test( value ) ) ) { - return this.each(function( index ) { - var self = set.eq( index ); - if ( isFunction ) { - args[ 0 ] = value.call( this, index, self.html() ); - } - self.domManip( args, callback, allowIntersection ); - }); - } - - if ( l ) { - fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, !allowIntersection && this ); - first = fragment.firstChild; - - if ( fragment.childNodes.length === 1 ) { - fragment = first; - } - - if ( first ) { - scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); - hasScripts = scripts.length; - - // Use the original fragment for the last item instead of the first because it can end up - // being emptied incorrectly in certain situations (#8070). - for ( ; i < l; i++ ) { - node = fragment; - - if ( i !== iNoClone ) { - node = jQuery.clone( node, true, true ); - - // Keep references to cloned scripts for later restoration - if ( hasScripts ) { - // Support: QtWebKit - // jQuery.merge because core_push.apply(_, arraylike) throws - jQuery.merge( scripts, getAll( node, "script" ) ); - } - } - - callback.call( this[ i ], node, i ); - } - - if ( hasScripts ) { - doc = scripts[ scripts.length - 1 ].ownerDocument; - - // Reenable scripts - jQuery.map( scripts, restoreScript ); - - // Evaluate executable scripts on first document insertion - for ( i = 0; i < hasScripts; i++ ) { - node = scripts[ i ]; - if ( rscriptType.test( node.type || "" ) && - !data_priv.access( node, "globalEval" ) && jQuery.contains( doc, node ) ) { - - if ( node.src ) { - // Hope ajax is available... - jQuery._evalUrl( node.src ); - } else { - jQuery.globalEval( node.textContent.replace( rcleanScript, "" ) ); - } - } - } - } - } - } - - return this; - } -}); - -jQuery.each({ - appendTo: "append", - prependTo: "prepend", - insertBefore: "before", - insertAfter: "after", - replaceAll: "replaceWith" -}, function( name, original ) { - jQuery.fn[ name ] = function( selector ) { - var elems, - ret = [], - insert = jQuery( selector ), - last = insert.length - 1, - i = 0; - - for ( ; i <= last; i++ ) { - elems = i === last ? this : this.clone( true ); - jQuery( insert[ i ] )[ original ]( elems ); - - // Support: QtWebKit - // .get() because core_push.apply(_, arraylike) throws - core_push.apply( ret, elems.get() ); - } - - return this.pushStack( ret ); - }; -}); - -jQuery.extend({ - clone: function( elem, dataAndEvents, deepDataAndEvents ) { - var i, l, srcElements, destElements, - clone = elem.cloneNode( true ), - inPage = jQuery.contains( elem.ownerDocument, elem ); - - // Support: IE >= 9 - // Fix Cloning issues - if ( !jQuery.support.noCloneChecked && ( elem.nodeType === 1 || elem.nodeType === 11 ) && !jQuery.isXMLDoc( elem ) ) { - - // We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2 - destElements = getAll( clone ); - srcElements = getAll( elem ); - - for ( i = 0, l = srcElements.length; i < l; i++ ) { - fixInput( srcElements[ i ], destElements[ i ] ); - } - } - - // Copy the events from the original to the clone - if ( dataAndEvents ) { - if ( deepDataAndEvents ) { - srcElements = srcElements || getAll( elem ); - destElements = destElements || getAll( clone ); - - for ( i = 0, l = srcElements.length; i < l; i++ ) { - cloneCopyEvent( srcElements[ i ], destElements[ i ] ); - } - } else { - cloneCopyEvent( elem, clone ); - } - } - - // Preserve script evaluation history - destElements = getAll( clone, "script" ); - if ( destElements.length > 0 ) { - setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); - } - - // Return the cloned set - return clone; - }, - - buildFragment: function( elems, context, scripts, selection ) { - var elem, tmp, tag, wrap, contains, j, - i = 0, - l = elems.length, - fragment = context.createDocumentFragment(), - nodes = []; - - for ( ; i < l; i++ ) { - elem = elems[ i ]; - - if ( elem || elem === 0 ) { - - // Add nodes directly - if ( jQuery.type( elem ) === "object" ) { - // Support: QtWebKit - // jQuery.merge because core_push.apply(_, arraylike) throws - jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem ); - - // Convert non-html into a text node - } else if ( !rhtml.test( elem ) ) { - nodes.push( context.createTextNode( elem ) ); - - // Convert html into DOM nodes - } else { - tmp = tmp || fragment.appendChild( context.createElement("div") ); - - // Deserialize a standard representation - tag = ( rtagName.exec( elem ) || ["", ""] )[ 1 ].toLowerCase(); - wrap = wrapMap[ tag ] || wrapMap._default; - tmp.innerHTML = wrap[ 1 ] + elem.replace( rxhtmlTag, "<$1>" ) + wrap[ 2 ]; - - // Descend through wrappers to the right content - j = wrap[ 0 ]; - while ( j-- ) { - tmp = tmp.firstChild; - } - - // Support: QtWebKit - // jQuery.merge because core_push.apply(_, arraylike) throws - jQuery.merge( nodes, tmp.childNodes ); - - // Remember the top-level container - tmp = fragment.firstChild; - - // Fixes #12346 - // Support: Webkit, IE - tmp.textContent = ""; - } - } - } - - // Remove wrapper from fragment - fragment.textContent = ""; - - i = 0; - while ( (elem = nodes[ i++ ]) ) { - - // #4087 - If origin and destination elements are the same, and this is - // that element, do not do anything - if ( selection && jQuery.inArray( elem, selection ) !== -1 ) { - continue; - } - - contains = jQuery.contains( elem.ownerDocument, elem ); - - // Append to fragment - tmp = getAll( fragment.appendChild( elem ), "script" ); - - // Preserve script evaluation history - if ( contains ) { - setGlobalEval( tmp ); - } - - // Capture executables - if ( scripts ) { - j = 0; - while ( (elem = tmp[ j++ ]) ) { - if ( rscriptType.test( elem.type || "" ) ) { - scripts.push( elem ); - } - } - } - } - - return fragment; - }, - - cleanData: function( elems ) { - var data, elem, events, type, key, j, - special = jQuery.event.special, - i = 0; - - for ( ; (elem = elems[ i ]) !== undefined; i++ ) { - if ( Data.accepts( elem ) ) { - key = elem[ data_priv.expando ]; - - if ( key && (data = data_priv.cache[ key ]) ) { - events = Object.keys( data.events || {} ); - if ( events.length ) { - for ( j = 0; (type = events[j]) !== undefined; j++ ) { - if ( special[ type ] ) { - jQuery.event.remove( elem, type ); - - // This is a shortcut to avoid jQuery.event.remove's overhead - } else { - jQuery.removeEvent( elem, type, data.handle ); - } - } - } - if ( data_priv.cache[ key ] ) { - // Discard any remaining `private` data - delete data_priv.cache[ key ]; - } - } - } - // Discard any remaining `user` data - delete data_user.cache[ elem[ data_user.expando ] ]; - } - }, - - _evalUrl: function( url ) { - return jQuery.ajax({ - url: url, - type: "GET", - dataType: "script", - async: false, - global: false, - "throws": true - }); - } -}); - -// Support: 1.x compatibility -// Manipulating tables requires a tbody -function manipulationTarget( elem, content ) { - return jQuery.nodeName( elem, "table" ) && - jQuery.nodeName( content.nodeType === 1 ? content : content.firstChild, "tr" ) ? - - elem.getElementsByTagName("tbody")[0] || - elem.appendChild( elem.ownerDocument.createElement("tbody") ) : - elem; -} - -// Replace/restore the type attribute of script elements for safe DOM manipulation -function disableScript( elem ) { - elem.type = (elem.getAttribute("type") !== null) + "/" + elem.type; - return elem; -} -function restoreScript( elem ) { - var match = rscriptTypeMasked.exec( elem.type ); - - if ( match ) { - elem.type = match[ 1 ]; - } else { - elem.removeAttribute("type"); - } - - return elem; -} - -// Mark scripts as having already been evaluated -function setGlobalEval( elems, refElements ) { - var l = elems.length, - i = 0; - - for ( ; i < l; i++ ) { - data_priv.set( - elems[ i ], "globalEval", !refElements || data_priv.get( refElements[ i ], "globalEval" ) - ); - } -} - -function cloneCopyEvent( src, dest ) { - var i, l, type, pdataOld, pdataCur, udataOld, udataCur, events; - - if ( dest.nodeType !== 1 ) { - return; - } - - // 1. Copy private data: events, handlers, etc. - if ( data_priv.hasData( src ) ) { - pdataOld = data_priv.access( src ); - pdataCur = data_priv.set( dest, pdataOld ); - events = pdataOld.events; - - if ( events ) { - delete pdataCur.handle; - pdataCur.events = {}; - - for ( type in events ) { - for ( i = 0, l = events[ type ].length; i < l; i++ ) { - jQuery.event.add( dest, type, events[ type ][ i ] ); - } - } - } - } - - // 2. Copy user data - if ( data_user.hasData( src ) ) { - udataOld = data_user.access( src ); - udataCur = jQuery.extend( {}, udataOld ); - - data_user.set( dest, udataCur ); - } -} - - -function getAll( context, tag ) { - var ret = context.getElementsByTagName ? context.getElementsByTagName( tag || "*" ) : - context.querySelectorAll ? context.querySelectorAll( tag || "*" ) : - []; - - return tag === undefined || tag && jQuery.nodeName( context, tag ) ? - jQuery.merge( [ context ], ret ) : - ret; -} - -// Support: IE >= 9 -function fixInput( src, dest ) { - var nodeName = dest.nodeName.toLowerCase(); - - // Fails to persist the checked state of a cloned checkbox or radio button. - if ( nodeName === "input" && manipulation_rcheckableType.test( src.type ) ) { - dest.checked = src.checked; - - // Fails to return the selected option to the default selected state when cloning options - } else if ( nodeName === "input" || nodeName === "textarea" ) { - dest.defaultValue = src.defaultValue; - } -} -jQuery.fn.extend({ - wrapAll: function( html ) { - var wrap; - - if ( jQuery.isFunction( html ) ) { - return this.each(function( i ) { - jQuery( this ).wrapAll( html.call(this, i) ); - }); - } - - if ( this[ 0 ] ) { - - // The elements to wrap the target around - wrap = jQuery( html, this[ 0 ].ownerDocument ).eq( 0 ).clone( true ); - - if ( this[ 0 ].parentNode ) { - wrap.insertBefore( this[ 0 ] ); - } - - wrap.map(function() { - var elem = this; - - while ( elem.firstElementChild ) { - elem = elem.firstElementChild; - } - - return elem; - }).append( this ); - } - - return this; - }, - - wrapInner: function( html ) { - if ( jQuery.isFunction( html ) ) { - return this.each(function( i ) { - jQuery( this ).wrapInner( html.call(this, i) ); - }); - } - - return this.each(function() { - var self = jQuery( this ), - contents = self.contents(); - - if ( contents.length ) { - contents.wrapAll( html ); - - } else { - self.append( html ); - } - }); - }, - - wrap: function( html ) { - var isFunction = jQuery.isFunction( html ); - - return this.each(function( i ) { - jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html ); - }); - }, - - unwrap: function() { - return this.parent().each(function() { - if ( !jQuery.nodeName( this, "body" ) ) { - jQuery( this ).replaceWith( this.childNodes ); - } - }).end(); - } -}); -var curCSS, iframe, - // swappable if display is none or starts with table except "table", "table-cell", or "table-caption" - // see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display - rdisplayswap = /^(none|table(?!-c[ea]).+)/, - rmargin = /^margin/, - rnumsplit = new RegExp( "^(" + core_pnum + ")(.*)$", "i" ), - rnumnonpx = new RegExp( "^(" + core_pnum + ")(?!px)[a-z%]+$", "i" ), - rrelNum = new RegExp( "^([+-])=(" + core_pnum + ")", "i" ), - elemdisplay = { BODY: "block" }, - - cssShow = { position: "absolute", visibility: "hidden", display: "block" }, - cssNormalTransform = { - letterSpacing: 0, - fontWeight: 400 - }, - - cssExpand = [ "Top", "Right", "Bottom", "Left" ], - cssPrefixes = [ "Webkit", "O", "Moz", "ms" ]; - -// return a css property mapped to a potentially vendor prefixed property -function vendorPropName( style, name ) { - - // shortcut for names that are not vendor prefixed - if ( name in style ) { - return name; - } - - // check for vendor prefixed names - var capName = name.charAt(0).toUpperCase() + name.slice(1), - origName = name, - i = cssPrefixes.length; - - while ( i-- ) { - name = cssPrefixes[ i ] + capName; - if ( name in style ) { - return name; - } - } - - return origName; -} - -function isHidden( elem, el ) { - // isHidden might be called from jQuery#filter function; - // in that case, element will be second argument - elem = el || elem; - return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem ); -} - -// NOTE: we've included the "window" in window.getComputedStyle -// because jsdom on node.js will break without it. -function getStyles( elem ) { - return window.getComputedStyle( elem, null ); -} - -function showHide( elements, show ) { - var display, elem, hidden, - values = [], - index = 0, - length = elements.length; - - for ( ; index < length; index++ ) { - elem = elements[ index ]; - if ( !elem.style ) { - continue; - } - - values[ index ] = data_priv.get( elem, "olddisplay" ); - display = elem.style.display; - if ( show ) { - // Reset the inline display of this element to learn if it is - // being hidden by cascaded rules or not - if ( !values[ index ] && display === "none" ) { - elem.style.display = ""; - } - - // Set elements which have been overridden with display: none - // in a stylesheet to whatever the default browser style is - // for such an element - if ( elem.style.display === "" && isHidden( elem ) ) { - values[ index ] = data_priv.access( elem, "olddisplay", css_defaultDisplay(elem.nodeName) ); - } - } else { - - if ( !values[ index ] ) { - hidden = isHidden( elem ); - - if ( display && display !== "none" || !hidden ) { - data_priv.set( elem, "olddisplay", hidden ? display : jQuery.css(elem, "display") ); - } - } - } - } - - // Set the display of most of the elements in a second loop - // to avoid the constant reflow - for ( index = 0; index < length; index++ ) { - elem = elements[ index ]; - if ( !elem.style ) { - continue; - } - if ( !show || elem.style.display === "none" || elem.style.display === "" ) { - elem.style.display = show ? values[ index ] || "" : "none"; - } - } - - return elements; -} - -jQuery.fn.extend({ - css: function( name, value ) { - return jQuery.access( this, function( elem, name, value ) { - var styles, len, - map = {}, - i = 0; - - if ( jQuery.isArray( name ) ) { - styles = getStyles( elem ); - len = name.length; - - for ( ; i < len; i++ ) { - map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles ); - } - - return map; - } - - return value !== undefined ? - jQuery.style( elem, name, value ) : - jQuery.css( elem, name ); - }, name, value, arguments.length > 1 ); - }, - show: function() { - return showHide( this, true ); - }, - hide: function() { - return showHide( this ); - }, - toggle: function( state ) { - var bool = typeof state === "boolean"; - - return this.each(function() { - if ( bool ? state : isHidden( this ) ) { - jQuery( this ).show(); - } else { - jQuery( this ).hide(); - } - }); - } -}); - -jQuery.extend({ - // Add in style property hooks for overriding the default - // behavior of getting and setting a style property - cssHooks: { - opacity: { - get: function( elem, computed ) { - if ( computed ) { - // We should always get a number back from opacity - var ret = curCSS( elem, "opacity" ); - return ret === "" ? "1" : ret; - } - } - } - }, - - // Don't automatically add "px" to these possibly-unitless properties - cssNumber: { - "columnCount": true, - "fillOpacity": true, - "fontWeight": true, - "lineHeight": true, - "opacity": true, - "orphans": true, - "widows": true, - "zIndex": true, - "zoom": true - }, - - // Add in properties whose names you wish to fix before - // setting or getting the value - cssProps: { - // normalize float css property - "float": "cssFloat" - }, - - // Get and set the style property on a DOM Node - style: function( elem, name, value, extra ) { - // Don't set styles on text and comment nodes - if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { - return; - } - - // Make sure that we're working with the right name - var ret, type, hooks, - origName = jQuery.camelCase( name ), - style = elem.style; - - name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) ); - - // gets hook for the prefixed version - // followed by the unprefixed version - hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; - - // Check if we're setting a value - if ( value !== undefined ) { - type = typeof value; - - // convert relative number strings (+= or -=) to relative numbers. #7345 - if ( type === "string" && (ret = rrelNum.exec( value )) ) { - value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) ); - // Fixes bug #9237 - type = "number"; - } - - // Make sure that NaN and null values aren't set. See: #7116 - if ( value == null || type === "number" && isNaN( value ) ) { - return; - } - - // If a number was passed in, add 'px' to the (except for certain CSS properties) - if ( type === "number" && !jQuery.cssNumber[ origName ] ) { - value += "px"; - } - - // Fixes #8908, it can be done more correctly by specifying setters in cssHooks, - // but it would mean to define eight (for every problematic property) identical functions - if ( !jQuery.support.clearCloneStyle && value === "" && name.indexOf("background") === 0 ) { - style[ name ] = "inherit"; - } - - // If a hook was provided, use that value, otherwise just set the specified value - if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value, extra )) !== undefined ) { - style[ name ] = value; - } - - } else { - // If a hook was provided get the non-computed value from there - if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) { - return ret; - } - - // Otherwise just get the value from the style object - return style[ name ]; - } - }, - - css: function( elem, name, extra, styles ) { - var val, num, hooks, - origName = jQuery.camelCase( name ); - - // Make sure that we're working with the right name - name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) ); - - // gets hook for the prefixed version - // followed by the unprefixed version - hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; - - // If a hook was provided get the computed value from there - if ( hooks && "get" in hooks ) { - val = hooks.get( elem, true, extra ); - } - - // Otherwise, if a way to get the computed value exists, use that - if ( val === undefined ) { - val = curCSS( elem, name, styles ); - } - - //convert "normal" to computed value - if ( val === "normal" && name in cssNormalTransform ) { - val = cssNormalTransform[ name ]; - } - - // Return, converting to number if forced or a qualifier was provided and val looks numeric - if ( extra === "" || extra ) { - num = parseFloat( val ); - return extra === true || jQuery.isNumeric( num ) ? num || 0 : val; - } - return val; - } -}); - -curCSS = function( elem, name, _computed ) { - var width, minWidth, maxWidth, - computed = _computed || getStyles( elem ), - - // Support: IE9 - // getPropertyValue is only needed for .css('filter') in IE9, see #12537 - ret = computed ? computed.getPropertyValue( name ) || computed[ name ] : undefined, - style = elem.style; - - if ( computed ) { - - if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) { - ret = jQuery.style( elem, name ); - } - - // Support: Safari 5.1 - // A tribute to the "awesome hack by Dean Edwards" - // Safari 5.1.7 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels - // this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values - if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) { - - // Remember the original values - width = style.width; - minWidth = style.minWidth; - maxWidth = style.maxWidth; - - // Put in the new values to get a computed value out - style.minWidth = style.maxWidth = style.width = ret; - ret = computed.width; - - // Revert the changed values - style.width = width; - style.minWidth = minWidth; - style.maxWidth = maxWidth; - } - } - - return ret; -}; - - -function setPositiveNumber( elem, value, subtract ) { - var matches = rnumsplit.exec( value ); - return matches ? - // Guard against undefined "subtract", e.g., when used as in cssHooks - Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) : - value; -} - -function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) { - var i = extra === ( isBorderBox ? "border" : "content" ) ? - // If we already have the right measurement, avoid augmentation - 4 : - // Otherwise initialize for horizontal or vertical properties - name === "width" ? 1 : 0, - - val = 0; - - for ( ; i < 4; i += 2 ) { - // both box models exclude margin, so add it if we want it - if ( extra === "margin" ) { - val += jQuery.css( elem, extra + cssExpand[ i ], true, styles ); - } - - if ( isBorderBox ) { - // border-box includes padding, so remove it if we want content - if ( extra === "content" ) { - val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); - } - - // at this point, extra isn't border nor margin, so remove border - if ( extra !== "margin" ) { - val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); - } - } else { - // at this point, extra isn't content, so add padding - val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); - - // at this point, extra isn't content nor padding, so add border - if ( extra !== "padding" ) { - val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); - } - } - } - - return val; -} - -function getWidthOrHeight( elem, name, extra ) { - - // Start with offset property, which is equivalent to the border-box value - var valueIsBorderBox = true, - val = name === "width" ? elem.offsetWidth : elem.offsetHeight, - styles = getStyles( elem ), - isBorderBox = jQuery.support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box"; - - // some non-html elements return undefined for offsetWidth, so check for null/undefined - // svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285 - // MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668 - if ( val <= 0 || val == null ) { - // Fall back to computed then uncomputed css if necessary - val = curCSS( elem, name, styles ); - if ( val < 0 || val == null ) { - val = elem.style[ name ]; - } - - // Computed unit is not pixels. Stop here and return. - if ( rnumnonpx.test(val) ) { - return val; - } - - // we need the check for style in case a browser which returns unreliable values - // for getComputedStyle silently falls back to the reliable elem.style - valueIsBorderBox = isBorderBox && ( jQuery.support.boxSizingReliable || val === elem.style[ name ] ); - - // Normalize "", auto, and prepare for extra - val = parseFloat( val ) || 0; - } - - // use the active box-sizing model to add/subtract irrelevant styles - return ( val + - augmentWidthOrHeight( - elem, - name, - extra || ( isBorderBox ? "border" : "content" ), - valueIsBorderBox, - styles - ) - ) + "px"; -} - -// Try to determine the default display value of an element -function css_defaultDisplay( nodeName ) { - var doc = document, - display = elemdisplay[ nodeName ]; - - if ( !display ) { - display = actualDisplay( nodeName, doc ); - - // If the simple way fails, read from inside an iframe - if ( display === "none" || !display ) { - // Use the already-created iframe if possible - iframe = ( iframe || - jQuery("