<commit_before>/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (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.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is Ajax.org Code Editor (ACE).
 *
 * The Initial Developer of the Original Code is
 * Ajax.org B.V.
 * Portions created by the Initial Developer are Copyright (C) 2010
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *      Fabian Jakobs <fabian AT ajax DOT org>
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */

var copy = require('dryice').copy;

var gcliHome = __dirname;

console.log('# Building GCLI');

var project = copy.createCommonJsProject([
    gcliHome + '/mini',
    gcliHome + '/lib'
]);

function filterTextPlugin(text) {
    return text.replace(/(['"])text\!/g, "$1text/");
}

var gcli = copy.createDataObject();
copy({
    source: [ 'build/mini_require.js' ],
    dest: gcli
});
copy({
    source: [
        copy.source.commonjs({
            project: project,
            require: [ "cockpit/index" ]
        })
    ],
    filter: [ copy.filter.moduleDefines ],
    dest: gcli
});
copy({
    source: {
        root: project,
        include: /.*\.css$|.*\.html$/,
        exclude: /tests?\//
    },
    filter: [ copy.filter.addDefines ],
    dest: gcli
});
copy({
    source: {
        root: project,
        include: /.*\.png$|.*\.gif$/,
        exclude: /tests?\//
    },
    filter: [ copy.filter.base64 ],
    dest: gcli
});

// Create the compressed and uncompressed output files
copy({
    source: gcli,
    filter: [ copy.filter.uglifyjs, filterTextPlugin ],
    dest: 'build/gcli.js'
});
copy({
    source: gcli,
    filter: [ filterTextPlugin ],
    dest: 'build/gcli-uncompressed.js'
});
<commit_msg>modified build script to build for ff separately from browser<commit_after>/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (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.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is Ajax.org Code Editor (ACE).
 *
 * The Initial Developer of the Original Code is
 * Ajax.org B.V.
 * Portions created by the Initial Developer are Copyright (C) 2010
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *      Fabian Jakobs <fabian AT ajax DOT org>
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */

var copy = require('dryice').copy;

// SETUP
var gcliHome = __dirname;
var project = copy.createCommonJsProject([
  gcliHome + '/mini',
  gcliHome + '/lib'
]);

// Grab and process all the Javascript
var javascript = copy.createDataObject();
copy({
  source: [ copy.source.commonjs({ project: project, require: [ "cockpit/index" ] }) ],
  filter: [ copy.filter.moduleDefines ],
  dest: javascript
});

// Process the CSS/HTML/PNG/GIF
var resources = copy.createDataObject();
copy({
  source: { root: project, include: /.*\.css$|.*\.html$/, exclude: /tests?\// },
  filter: [ copy.filter.addDefines ],
  dest: resources
});
copy({
  source: { root: project, include: /.*\.png$|.*\.gif$/, exclude: /tests?\// },
  filter: [ copy.filter.base64 ],
  dest: resources
});

// Mini require as used in a web page
var require = copy.createDataObject();
copy({
  source: [ 'build/mini_require.js' ],
  dest: require
});

// Mini require as used in Firefox
var ffrequire = copy.createDataObject();
copy({
  source: [ 'build/ff_require.js' ],
  dest: ffrequire
});

// Create the compressed and uncompressed output files

copy({
  source: [ require, javascript, resources ],
  filter: [ copy.filter.uglifyjs, filterTextPlugin ],
  dest: 'build/gcli.js'
});
copy({
  source: [ require, javascript, resources ],
  filter: [ filterTextPlugin ],
  dest: 'build/gcli-uncompressed.js'
});
copy({
  source: [ ffrequire, javascript, resources ],
  filter: [ filterTextPlugin ],
  dest: 'build/gcli-ff.js'
});

function filterTextPlugin(text) {
  return text.replace(/(['"])text\!/g, "$1text/");
}
<|endoftext|>


<commit_before>#!/usr/bin/env node
/* ***** BEGIN LICENSE BLOCK *****
 * Distributed under the BSD license:
 *
 * Copyright (c) 2010, Ajax.org B.V.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of Ajax.org B.V. nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * ***** END LICENSE BLOCK ***** */

var fs = require("fs");
if (!fs.existsSync)
    fs.existsSync = require("path").existsSync;
var copy = require('dryice').copy;

var ACE_HOME = __dirname;
var BUILD_DIR = ACE_HOME + "/build";

function main(args) {
    var type = "minimal";
    args = args.map(function(x) {
        if (x[0] == "-" && x[1] != "-")
            return "-" + x;
        return x;
    });

    if (args[2] && (args[2][0] != "-" || args[2].indexOf("h") != -1))
        type = args[2];

    var i = args.indexOf("--target");
    if (i != -1 && args[i+1])
        BUILD_DIR = args[i+1];

    if (args.indexOf("--h") == -1) {
        if (type == "minimal") {
            buildAce({
                compress: args.indexOf("--m") != -1,
                noconflict: args.indexOf("--nc") != -1,
                shrinkwrap: args.indexOf("--s") != -1
            });
        } else if (type == "normal") {
            ace();
        } else if (type == "demo") {
            demo();
        } else if (type == "bm") {
            bookmarklet();
        } else if (type == "full") {
            ace();
            demo();
            bookmarklet();
        }
    }

    console.log("--- Ace Dryice Build Tool ---");
    console.log("");
    console.log("Options:");
    console.log("  minimal     Places necessary Ace files out in build dir; uses configuration flags below [default]");
    console.log("  normal      Runs four Ace builds--minimal, minimal-noconflict, minimal-min, and minimal-noconflict-min");
    console.log("  demo        Runs demo build of Ace");
    console.log("  bm          Runs bookmarklet build of Ace");
    console.log("  full        all of above");
    console.log("args:");
    console.log("  --target ./path   path to build folder");
    console.log("flags:");
    console.log("  --h                print this help");
    console.log("  --m                minify");
    console.log("  --nc               namespace require");
    console.log("  --s                shrinkwrap (combines all output files into one)");
    console.log("");
    if (BUILD_DIR)
        console.log(" output generated in " + type + __dirname + "/" + BUILD_DIR)
}

function bookmarklet() {
    var targetDir = BUILD_DIR + "/textarea";
    copy({
        source: "build_support/editor_textarea.html",
        dest:   targetDir + '/editor.html'
    });
    copy({
        source: "build_support/style.css",
        dest:   targetDir + '/style.css'
    });

    buildAce({
        targetDir: targetDir + "/src",
        ns: "__ace_shadowed__",
        exportModule: "ace/ext/textarea",
        compress: false,
        noconflict: true,
        suffix: "",
        name: "ace-bookmarklet",
        workers: [],
        keybindings: []
    });
}

function ace() {
    console.log('# ace ---------');

    // uncompressed
    buildAce({
        compress: false,
        noconflict: false
    });
    buildAce({
        compress: false,
        noconflict: true
    });

    // compressed
    buildAce({
        compress: true,
        noconflict: false
    });
    buildAce({
        compress: true,
        noconflict: true
    });

    console.log('# ace License | Readme | Changelog ---------');

    copy({
        source: ACE_HOME + "/build_support/editor.html",
        dest:   BUILD_DIR + "/editor.html"
    });
    copy({
        source: ACE_HOME + "/LICENSE",
        dest:   BUILD_DIR + "/LICENSE"
    });
    copy({
        source: ACE_HOME + "/ChangeLog.txt",
        dest:   BUILD_DIR + "/ChangeLog.txt"
    });
}

function demo() {
    console.log('# kitchen sink ---------');

    var version, ref;
    try {
        version = JSON.parse(fs.readFileSync(ACE_HOME + "/package.json")).version;
        ref = fs.readFileSync(ACE_HOME + "/.git-ref").toString();
    } catch(e) {
        ref = "";
        version = "";
    }
    var changeComments = function(data) {
            return (data
                .replace(/<!\-\-DEVEL[\d\D]*?DEVEL\-\->/g, "")
                .replace(/PACKAGE\-\->|<!\-\-PACKAGE/g, "")
                .replace(/\/\*DEVEL[\d\D]*?DEVEL\*\//g, "")
                .replace(/PACKAGE\*\/|\/\*PACKAGE/g, "")
                .replace("%version%", version)
                .replace("%commit%", ref)
            );
        }

    copy({
        source: ACE_HOME + "/kitchen-sink.html",
        dest:   BUILD_DIR + "/kitchen-sink.html",
        filter: [changeComments,  function(data) {
            return data.replace(/"(demo|build)\//g, "\"");
        }]
    });

    copy({
        source: ACE_HOME + "/demo/kitchen-sink/styles.css",
        dest:   BUILD_DIR + "/kitchen-sink/styles.css",
        filter: [ changeComments ]
    });

    fs.readdirSync(ACE_HOME +"/demo/kitchen-sink/docs/").forEach(function(x) {
        copy({
            source: ACE_HOME +"/demo/kitchen-sink/docs/" + x,
            dest:   BUILD_DIR + "/kitchen-sink/docs/" + x
        });
    });

    var demo = copy.createDataObject();
    copy({
        source: ACE_HOME + "/demo/kitchen-sink/demo.js",
        dest: demo,
        filter: [changeComments, function(data) {
            return data.replace(/"(demo|build)\//g, "\"");
        }, function(data) {
            return data.replace("define(", "define('kitchen-sink/demo',");
        }]
    });
    copy({
        source: ACE_HOME + "/lib/ace/split.js",
        dest: demo,
        filter: [changeComments, function(data) {
            return data.replace("define(", "define('ace/split',");
        }]
    });
    copy({
        source: demo,
        dest:   BUILD_DIR + "/kitchen-sink/demo.js",
    });

    copyFileSync(ACE_HOME + "/demo/kitchen-sink/logo.png", BUILD_DIR + "/kitchen-sink/logo.png");
}

function buildAce(options) {
    var aceProject = {
        roots: [ACE_HOME + '/lib', ACE_HOME + '/demo'],
        textPluginPattern: /^ace\/requirejs\/text!/
    };

    var defaults = {
        targetDir: BUILD_DIR + "/src",
        ns: "ace",
        exportModule: "ace/ace",
        requires: null,
        compress: false,
        noconflict: false,
        suffix: null,
        name: "ace",
        modes: fs.readdirSync(ACE_HOME + "/lib/ace/mode").map(function(x) {
                if (x.slice(-3) == ".js" && !/_highlight_rules|_test|_worker|xml_util|_outdent|behaviour/.test(x))
                    return x.slice(0, -3);
            }).filter(function(x) { return !!x; }),
        themes: fs.readdirSync(ACE_HOME + "/lib/ace/theme").map(function(x){
                return x.slice(-3) == ".js" && x.slice(0, -3);
            }).filter(function(x){ return !!x; }),
        workers: ["javascript", "coffee", "css", "json", "xquery"],
        keybindings: ["vim", "emacs"]
    };

    for(var key in defaults)
        if (!options.hasOwnProperty(key))
            options[key] = defaults[key];

    if (options.suffix == null) {
        options.suffix = "";
        if (options.compress)
            options.suffix += "-min";
        if (options.noconflict)
            options.suffix += "-noconflict";
    }

    if (!options.requires)
        options.requires = [options.exportModule];

    var filters = [
        copy.filter.moduleDefines,
        filterTextPlugin,
        removeUseStrict,
        removeLicenceCmments
    ];

    if (options.noconflict) {
        filters.push(namespace(options.ns));
        if (options.exportModule)
            var exportFilter = exportAce(options.ns, options.exportModule, options.ns);
    } else if (options.exportModule) {
        var exportFilter = exportAce(options.ns, options.exportModule);
    }

    if (options.compress)
        filters.push(copy.filter.uglifyjs);

    var targetDir = options.targetDir + options.suffix;
    var name = options.name;

    var project = copy.createCommonJsProject(aceProject);
    var ace = copy.createDataObject();
    copy({
        source: [ACE_HOME + "/build_support/mini_require.js"],
        dest: ace
    });
    copy({
        source: [{
            project: project,
            require: options.requires
        }],
        filter: [ copy.filter.moduleDefines ],
        dest: ace
    });

    copy({
        source: ace,
        filter: exportFilter ? filters.concat(exportFilter) : filters,
        dest:   targetDir + '/' + name + ".js"
    });

    console.log('# ace modes ---------');

    project.assumeAllFilesLoaded();
    options.modes.forEach(function(mode) {
        console.log("mode " + mode);
        copy({
            source: [{
                project: cloneProject(project),
                require: [ 'ace/mode/' + mode ]
            }],
            filter: filters,
            dest:   targetDir + "/mode-" + mode + ".js"
        });
    });

    console.log('# ace themes ---------');

    project.assumeAllFilesLoaded();
    options.themes.forEach(function(theme) {
        console.log("theme " + theme);
        /*copy({
            source: [{
                project: cloneProject(project),
                require: ["ace/theme/" + theme]
            }],
            filter: filters,
            dest:   targetDir + "/theme-" + theme + ".js"
        });*/
        // use this instead, to not create separate modules for js and css
        var themePath = ACE_HOME + "/lib/ace/theme/" + theme
        var js = fs.readFileSync(themePath + ".js", "utf8");
        js = js.replace("define(", "define('ace/theme/" + theme + "', ['require', 'exports', 'module', 'ace/lib/dom'], ");

        if (fs.existsSync(themePath + ".css", "utf8")) {
            var css = fs.readFileSync(themePath + ".css", "utf8")
            js = js.replace(/require\(.ace\/requirejs\/text!.*?\)/, quoteString(css))
        }
        filters.forEach(function(f) {js = f(js); });

        fs.writeFileSync(targetDir + "/theme-" + theme + ".js", js);
    });

    console.log('# ace key bindings ---------');

    // copy key bindings
    project.assumeAllFilesLoaded();
    options.keybindings.forEach(function(keybinding) {
        copy({
            source: [{
                project: cloneProject(project),
                require: [ 'ace/keyboard/' + keybinding ]
            }],
            filter: filters,
            dest: targetDir + "/keybinding-" + keybinding + ".js"
        });
    });

    console.log('# ace worker ---------');

    filters = [
        copy.filter.moduleDefines,
        filterTextPlugin,
        removeUseStrict,
        removeLicenceCmments
    ];

    options.workers.forEach(function(mode) {
        console.log("worker for " + mode + " mode");
        var worker = copy.createDataObject();
        var workerProject = copy.createCommonJsProject({
            roots: [ ACE_HOME + '/lib' ],
            textPluginPattern: /^ace\/requirejs\/text!/
        });
        copy({
            source: [{
                project: workerProject,
                require: [
                    'ace/lib/fixoldbrowsers',
                    'ace/lib/event_emitter',
                    'ace/lib/oop',
                    'ace/mode/' + mode + '_worker'
                ]
            }],
            filter: filters,
            dest: worker
        });
        copy({
            source: [
                ACE_HOME + "/lib/ace/worker/worker.js",
                worker
            ],
            filter: options.compress ? [copy.filter.uglifyjs] : [],
            dest: targetDir + "/worker-" + mode + ".js"
        });
    });

    console.log('# combining files into one ---------');

    if (options.shrinkwrap) {
        copy({
          source: { root:targetDir, exclude:/^worker-/ },
          dest: BUILD_DIR + '/ace-min.js'
        });
    }
}

// TODO: replace with project.clone once it is fixed in dryice
function cloneProject(project) {
    var clone = copy.createCommonJsProject({
        roots: project.roots,
        ignores: project.ignoreRequires,
        textPluginPattern: project.textPluginPattern
    });

    Object.keys(project.currentModules).forEach(function(module) {
        clone.currentModules[module] = project.currentModules[module];
    });

    Object.keys(project.ignoredModules).forEach(function(module) {
        clone.ignoredModules[module] = project.ignoredModules[module];
    });

    return clone;
}
function copyFileSync(srcFile, destFile) {
    var BUF_LENGTH = 64*1024,
        buf = new Buffer(BUF_LENGTH),
        bytesRead = BUF_LENGTH,
        pos = 0,
        fdr = null,
        fdw = null;

    fdr = fs.openSync(srcFile, 'r');
    fdw = fs.openSync(destFile, 'w');

    while (bytesRead === BUF_LENGTH) {
        bytesRead = fs.readSync(fdr, buf, 0, BUF_LENGTH, pos);
        fs.writeSync(fdw, buf, 0, bytesRead);
        pos += bytesRead;
    }

    fs.closeSync(fdr);
    fs.closeSync(fdw);
}

function quoteString(str) {
    return '"' + str.replace(/\\/, "\\\\").replace(/"/g, '\\"').replace(/\n/g, "\\\n") + '"';
}

function filterTextPlugin(text) {
    return text.replace(/(['"])ace\/requirejs\/text\!/g, "$1text!");
}

function removeUseStrict(text) {
    return text.replace(/['"]use strict['"];/g, "");
}

function removeLicenceCmments(text) {
    return text.replace(/(;)\s*\/\*[\d\D]*?\*\//g, "$1");
}

function namespace(ns) {
    return function(text) {
        text = text
            .toString()
            .replace('var ACE_NAMESPACE = "";', 'var ACE_NAMESPACE = "' + ns +'";')
            .replace(/\bdefine\(/g, ns + ".define(");

        return text;
    };
}

function exportAce(ns, module, requireBase) {
    requireBase = requireBase || "window";
    module = module || "ace/ace";
    return function(text) {

        var template = function() {
            (function() {
                REQUIRE_NS.require(["MODULE"], function(a) {
                    a && a.config.init();
                    if (!window.NS)
                        window.NS = {};
                    for (var key in a) if (a.hasOwnProperty(key))
                        NS[key] = a[key];
                });
            })();
        };

        return (text + ";" + template
            .toString()
            .replace(/MODULE/g, module)
            .replace(/REQUIRE_NS/g, requireBase)
            .replace(/NS/g, ns)
            .slice(13, -1)
        );
    };
}

if (!module.parent)
    main(process.argv);
else
    exports.buildAce = buildAce;
<commit_msg>Add \-<commit_after>#!/usr/bin/env node
/* ***** BEGIN LICENSE BLOCK *****
 * Distributed under the BSD license:
 *
 * Copyright (c) 2010, Ajax.org B.V.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of Ajax.org B.V. nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * ***** END LICENSE BLOCK ***** */

var fs = require("fs");
if (!fs.existsSync)
    fs.existsSync = require("path").existsSync;
var copy = require('dryice').copy;

var ACE_HOME = __dirname;
var BUILD_DIR = ACE_HOME + "/build";

function main(args) {
    var type = "minimal";
    args = args.map(function(x) {
        if (x[0] == "-" && x[1] != "-")
            return "-" + x;
        return x;
    });

    if (args[2] && (args[2][0] != "-" || args[2].indexOf("h") != -1))
        type = args[2];

    var i = args.indexOf("--target");
    if (i != -1 && args[i+1])
        BUILD_DIR = args[i+1];

    if (args.indexOf("--h") == -1) {
        if (type == "minimal") {
            buildAce({
                compress: args.indexOf("--m") != -1,
                noconflict: args.indexOf("--nc") != -1,
                shrinkwrap: args.indexOf("--s") != -1
            });
        } else if (type == "normal") {
            ace();
        } else if (type == "demo") {
            demo();
        } else if (type == "bm") {
            bookmarklet();
        } else if (type == "full") {
            ace();
            demo();
            bookmarklet();
        }
    }

    console.log("--- Ace Dryice Build Tool ---");
    console.log("");
    console.log("Options:");
    console.log("  minimal     Places necessary Ace files out in build dir; uses configuration flags below [default]");
    console.log("  normal      Runs four Ace builds--minimal, minimal-noconflict, minimal-min, and minimal-noconflict-min");
    console.log("  demo        Runs demo build of Ace");
    console.log("  bm          Runs bookmarklet build of Ace");
    console.log("  full        all of above");
    console.log("args:");
    console.log("  --target ./path   path to build folder");
    console.log("flags:");
    console.log("  --h                print this help");
    console.log("  --m                minify");
    console.log("  --nc               namespace require");
    console.log("  --s                shrinkwrap (combines all output files into one)");
    console.log("");
    if (BUILD_DIR)
        console.log(" output generated in " + type + __dirname + "/" + BUILD_DIR)
}

function bookmarklet() {
    var targetDir = BUILD_DIR + "/textarea";
    copy({
        source: "build_support/editor_textarea.html",
        dest:   targetDir + '/editor.html'
    });
    copy({
        source: "build_support/style.css",
        dest:   targetDir + '/style.css'
    });

    buildAce({
        targetDir: targetDir + "/src",
        ns: "__ace_shadowed__",
        exportModule: "ace/ext/textarea",
        compress: false,
        noconflict: true,
        suffix: "",
        name: "ace-bookmarklet",
        workers: [],
        keybindings: []
    });
}

function ace() {
    console.log('# ace ---------');

    // uncompressed
    buildAce({
        compress: false,
        noconflict: false
    });
    buildAce({
        compress: false,
        noconflict: true
    });

    // compressed
    buildAce({
        compress: true,
        noconflict: false
    });
    buildAce({
        compress: true,
        noconflict: true
    });

    console.log('# ace License | Readme | Changelog ---------');

    copy({
        source: ACE_HOME + "/build_support/editor.html",
        dest:   BUILD_DIR + "/editor.html"
    });
    copy({
        source: ACE_HOME + "/LICENSE",
        dest:   BUILD_DIR + "/LICENSE"
    });
    copy({
        source: ACE_HOME + "/ChangeLog.txt",
        dest:   BUILD_DIR + "/ChangeLog.txt"
    });
}

function demo() {
    console.log('# kitchen sink ---------');

    var version, ref;
    try {
        version = JSON.parse(fs.readFileSync(ACE_HOME + "/package.json")).version;
        ref = fs.readFileSync(ACE_HOME + "/.git-ref").toString();
    } catch(e) {
        ref = "";
        version = "";
    }
    var changeComments = function(data) {
            return (data
                .replace(/<!\-\-DEVEL[\d\D]*?DEVEL\-\->/g, "")
                .replace(/PACKAGE\-\->|<!\-\-PACKAGE/g, "")
                .replace(/\/\*DEVEL[\d\D]*?DEVEL\*\//g, "")
                .replace(/PACKAGE\*\/|\/\*PACKAGE/g, "")
                .replace("%version%", version)
                .replace("%commit%", ref)
            );
        }

    copy({
        source: ACE_HOME + "/kitchen-sink.html",
        dest:   BUILD_DIR + "/kitchen-sink.html",
        filter: [changeComments,  function(data) {
            return data.replace(/"(demo|build)\//g, "\"");
        }]
    });

    copy({
        source: ACE_HOME + "/demo/kitchen-sink/styles.css",
        dest:   BUILD_DIR + "/kitchen-sink/styles.css",
        filter: [ changeComments ]
    });

    fs.readdirSync(ACE_HOME +"/demo/kitchen-sink/docs/").forEach(function(x) {
        copy({
            source: ACE_HOME +"/demo/kitchen-sink/docs/" + x,
            dest:   BUILD_DIR + "/kitchen-sink/docs/" + x
        });
    });

    var demo = copy.createDataObject();
    copy({
        source: ACE_HOME + "/demo/kitchen-sink/demo.js",
        dest: demo,
        filter: [changeComments, function(data) {
            return data.replace(/"(demo|build)\//g, "\"");
        }, function(data) {
            return data.replace("define(", "define('kitchen-sink/demo',");
        }]
    });
    copy({
        source: ACE_HOME + "/lib/ace/split.js",
        dest: demo,
        filter: [changeComments, function(data) {
            return data.replace("define(", "define('ace/split',");
        }]
    });
    copy({
        source: demo,
        dest:   BUILD_DIR + "/kitchen-sink/demo.js",
    });

    copyFileSync(ACE_HOME + "/demo/kitchen-sink/logo.png", BUILD_DIR + "/kitchen-sink/logo.png");
}

function buildAce(options) {
    var aceProject = {
        roots: [ACE_HOME + '/lib', ACE_HOME + '/demo'],
        textPluginPattern: /^ace\/requirejs\/text!/
    };

    var defaults = {
        targetDir: BUILD_DIR + "/src",
        ns: "ace",
        exportModule: "ace/ace",
        requires: null,
        compress: false,
        noconflict: false,
        suffix: null,
        name: "ace",
        modes: fs.readdirSync(ACE_HOME + "/lib/ace/mode").map(function(x) {
                if (x.slice(-3) == ".js" && !/_highlight_rules|_test|_worker|xml_util|_outdent|behaviour/.test(x))
                    return x.slice(0, -3);
            }).filter(function(x) { return !!x; }),
        themes: fs.readdirSync(ACE_HOME + "/lib/ace/theme").map(function(x){
                return x.slice(-3) == ".js" && x.slice(0, -3);
            }).filter(function(x){ return !!x; }),
        workers: ["javascript", "coffee", "css", "json", "xquery"],
        keybindings: ["vim", "emacs"]
    };

    for(var key in defaults)
        if (!options.hasOwnProperty(key))
            options[key] = defaults[key];

    if (options.suffix == null) {
        options.suffix = "";
        if (options.compress)
            options.suffix += "-min";
        if (options.noconflict)
            options.suffix += "-noconflict";
    }

    if (!options.requires)
        options.requires = [options.exportModule];

    var filters = [
        copy.filter.moduleDefines,
        filterTextPlugin,
        removeUseStrict,
        removeLicenceCmments
    ];

    if (options.noconflict) {
        filters.push(namespace(options.ns));
        if (options.exportModule)
            var exportFilter = exportAce(options.ns, options.exportModule, options.ns);
    } else if (options.exportModule) {
        var exportFilter = exportAce(options.ns, options.exportModule);
    }

    if (options.compress)
        filters.push(copy.filter.uglifyjs);

    var targetDir = options.targetDir + options.suffix;
    var name = options.name;

    var project = copy.createCommonJsProject(aceProject);
    var ace = copy.createDataObject();
    copy({
        source: [ACE_HOME + "/build_support/mini_require.js"],
        dest: ace
    });
    copy({
        source: [{
            project: project,
            require: options.requires
        }],
        filter: [ copy.filter.moduleDefines ],
        dest: ace
    });

    copy({
        source: ace,
        filter: exportFilter ? filters.concat(exportFilter) : filters,
        dest:   targetDir + '/' + name + ".js"
    });

    console.log('# ace modes ---------');

    project.assumeAllFilesLoaded();
    options.modes.forEach(function(mode) {
        console.log("mode " + mode);
        copy({
            source: [{
                project: cloneProject(project),
                require: [ 'ace/mode/' + mode ]
            }],
            filter: filters,
            dest:   targetDir + "/mode-" + mode + ".js"
        });
    });

    console.log('# ace themes ---------');

    project.assumeAllFilesLoaded();
    options.themes.forEach(function(theme) {
        console.log("theme " + theme);
        /*copy({
            source: [{
                project: cloneProject(project),
                require: ["ace/theme/" + theme]
            }],
            filter: filters,
            dest:   targetDir + "/theme-" + theme + ".js"
        });*/
        // use this instead, to not create separate modules for js and css
        var themePath = ACE_HOME + "/lib/ace/theme/" + theme
        var js = fs.readFileSync(themePath + ".js", "utf8");
        js = js.replace("define(", "define('ace/theme/" + theme + "', ['require', 'exports', 'module', 'ace/lib/dom'], ");

        if (fs.existsSync(themePath + ".css", "utf8")) {
            var css = fs.readFileSync(themePath + ".css", "utf8")
            js = js.replace(/require\(.ace\/requirejs\/text!.*?\)/, quoteString(css))
        }
        filters.forEach(function(f) {js = f(js); });

        fs.writeFileSync(targetDir + "/theme-" + theme + ".js", js);
    });

    console.log('# ace key bindings ---------');

    // copy key bindings
    project.assumeAllFilesLoaded();
    options.keybindings.forEach(function(keybinding) {
        copy({
            source: [{
                project: cloneProject(project),
                require: [ 'ace/keyboard/' + keybinding ]
            }],
            filter: filters,
            dest: targetDir + "/keybinding-" + keybinding + ".js"
        });
    });

    console.log('# ace worker ---------');

    filters = [
        copy.filter.moduleDefines,
        filterTextPlugin,
        removeUseStrict,
        removeLicenceCmments
    ];

    options.workers.forEach(function(mode) {
        console.log("worker for " + mode + " mode");
        var worker = copy.createDataObject();
        var workerProject = copy.createCommonJsProject({
            roots: [ ACE_HOME + '/lib' ],
            textPluginPattern: /^ace\/requirejs\/text!/
        });
        copy({
            source: [{
                project: workerProject,
                require: [
                    'ace/lib/fixoldbrowsers',
                    'ace/lib/event_emitter',
                    'ace/lib/oop',
                    'ace/mode/' + mode + '_worker'
                ]
            }],
            filter: filters,
            dest: worker
        });
        copy({
            source: [
                ACE_HOME + "/lib/ace/worker/worker.js",
                worker
            ],
            filter: options.compress ? [copy.filter.uglifyjs] : [],
            dest: targetDir + "/worker-" + mode + ".js"
        });
    });

    console.log('# combining files into one ---------');

    if (options.shrinkwrap) {
        copy({
          source: { root:targetDir, exclude:/^worker\-/ },
          dest: BUILD_DIR + '/ace-min.js'
        });
    }
}

// TODO: replace with project.clone once it is fixed in dryice
function cloneProject(project) {
    var clone = copy.createCommonJsProject({
        roots: project.roots,
        ignores: project.ignoreRequires,
        textPluginPattern: project.textPluginPattern
    });

    Object.keys(project.currentModules).forEach(function(module) {
        clone.currentModules[module] = project.currentModules[module];
    });

    Object.keys(project.ignoredModules).forEach(function(module) {
        clone.ignoredModules[module] = project.ignoredModules[module];
    });

    return clone;
}
function copyFileSync(srcFile, destFile) {
    var BUF_LENGTH = 64*1024,
        buf = new Buffer(BUF_LENGTH),
        bytesRead = BUF_LENGTH,
        pos = 0,
        fdr = null,
        fdw = null;

    fdr = fs.openSync(srcFile, 'r');
    fdw = fs.openSync(destFile, 'w');

    while (bytesRead === BUF_LENGTH) {
        bytesRead = fs.readSync(fdr, buf, 0, BUF_LENGTH, pos);
        fs.writeSync(fdw, buf, 0, bytesRead);
        pos += bytesRead;
    }

    fs.closeSync(fdr);
    fs.closeSync(fdw);
}

function quoteString(str) {
    return '"' + str.replace(/\\/, "\\\\").replace(/"/g, '\\"').replace(/\n/g, "\\\n") + '"';
}

function filterTextPlugin(text) {
    return text.replace(/(['"])ace\/requirejs\/text\!/g, "$1text!");
}

function removeUseStrict(text) {
    return text.replace(/['"]use strict['"];/g, "");
}

function removeLicenceCmments(text) {
    return text.replace(/(;)\s*\/\*[\d\D]*?\*\//g, "$1");
}

function namespace(ns) {
    return function(text) {
        text = text
            .toString()
            .replace('var ACE_NAMESPACE = "";', 'var ACE_NAMESPACE = "' + ns +'";')
            .replace(/\bdefine\(/g, ns + ".define(");

        return text;
    };
}

function exportAce(ns, module, requireBase) {
    requireBase = requireBase || "window";
    module = module || "ace/ace";
    return function(text) {

        var template = function() {
            (function() {
                REQUIRE_NS.require(["MODULE"], function(a) {
                    a && a.config.init();
                    if (!window.NS)
                        window.NS = {};
                    for (var key in a) if (a.hasOwnProperty(key))
                        NS[key] = a[key];
                });
            })();
        };

        return (text + ";" + template
            .toString()
            .replace(/MODULE/g, module)
            .replace(/REQUIRE_NS/g, requireBase)
            .replace(/NS/g, ns)
            .slice(13, -1)
        );
    };
}

if (!module.parent)
    main(process.argv);
else
    exports.buildAce = buildAce;
<|endoftext|>


<commit_before>/*
---

script: Expression.js

description: Adds layout capabilities to widget (parse and render widget trees from objects)

license: Public domain (http://unlicense.org).

authors: Yaroslaff Fedin

requires:
  - LSD.Module
  - LSD.Module.Events
  - LSD.Layout
  - LSD.Layout.Branch
  - LSD.Layout.Microdata
  - LSD.Layout.Promise

provides:
  - LSD.Module.Layout

...
*/

LSD.Module.Layout = new Class({
  /*
  options: {
    traverse: true,
    extract: true
  },
  */

  constructors: {
    layout: function(options) {
      if (!options.document && !this.document && LSD.document)
        this.properties.set('document', LSD.document);
      this.layouts = {};
    }
  },

  addLayout: function(name, layout, parent, memo) {
    if (!memo) memo = {};
    var old = this.layouts[name];
    if (old) {
      this.document.layout.add(old, parent, memo)
    } else {
      var first = layout.push && layout.length && layout[0];
      var method = (first && first.nodeType && ((first.nodeType != 1) || (!first.lsd))) ? 'children' : 'render';
      old = this.layouts[name] = this.document.layout[method](layout, parent, memo);
    }
    if (memo.promised) {
      memo.promised = false;
      console.error('promise')
      this.addEvent('DOMChildNodesRendered:once', function() {
        this.document.layout.realize(old)
      });
    }
    return this.layouts[name];
  },

  removeLayout: function(name, layout, parent, memo) {
    return this.document.layout.remove(this.layouts[name] || layout, parent, memo);
  },

  buildLayout: function(layout, parent, memo) {
    return this.document.layout[layout.charAt ? 'selector' : 'render'](layout, (!parent && parent !== false) ? this : parent, memo)
  }
});

LSD.Module.Layout.events = {
  /*
    Builds children after element is built
  */
  build: function() {
    if (this.properties.layout) {
      this.addLayout('options', this.properties.layout, [this, this.getWrapper()], {lazy: true});
    }
    if (this.origin && !this.options.clone && this.origin.parentNode && this.origin != this.element)
      this.element.replaces(this.origin);
    if ((!this.options.lazy && this.options.traverse !== false) || (this.origin && !this.element)) {
      var nodes = LSD.slice((this.origin || this.element).childNodes);
      var opts = {}
      if (this.options.context) opts.context = this.options.context;
      if (this.options.clone) opts.clone = this.options.clone;
      if (nodes.length) this.addLayout('children', nodes, [this, this.getWrapper()], opts);
      this.fireEvent('DOMChildNodesRendered');
    }
  },
  /*
    Destroys the built layout with the widget
  */
  destroy: function() {
    if (this.layouts.children) this.removeLayout('children');
    if (this.layouts.options) this.removeLayout('options');
  },
  /*
    Augments all parsed HTML that goes through standart .write() interface
  */
  write: function(node) {
    this.addLayout('written', node, [this, this.getWrapper()]);
  },
  /*
    Augments all inserted nodes that come from partial html updates
  */
  DOMNodeInserted: function(node) {
    this.buildLayout(node, [this, this.getWrapper()]);
  },
  DOMNodeInsertedBefore: function(node, target) {
    this.buildLayout(node, [this, this.getWrapper()], null, {before: target});
  }
};

LSD.Module.Events.addEvents.call(LSD.Module.Layout.prototype, LSD.Module.Layout.events);

Object.append(LSD.Options, {
  layout: {
    add: function(value) {
      this.properties.set('layout', value);
    },
    remove: function(value) {
      this.properties.unset('layout', value);
    }
  }
});<commit_msg>Remove trace<commit_after>/*
---

script: Expression.js

description: Adds layout capabilities to widget (parse and render widget trees from objects)

license: Public domain (http://unlicense.org).

authors: Yaroslaff Fedin

requires:
  - LSD.Module
  - LSD.Module.Events
  - LSD.Layout
  - LSD.Layout.Branch
  - LSD.Layout.Microdata
  - LSD.Layout.Promise

provides:
  - LSD.Module.Layout

...
*/

LSD.Module.Layout = new Class({
  /*
  options: {
    traverse: true,
    extract: true
  },
  */

  constructors: {
    layout: function(options) {
      if (!options.document && !this.document && LSD.document)
        this.properties.set('document', LSD.document);
      this.layouts = {};
    }
  },

  addLayout: function(name, layout, parent, memo) {
    if (!memo) memo = {};
    var old = this.layouts[name];
    if (old) {
      this.document.layout.add(old, parent, memo)
    } else {
      var first = layout.push && layout.length && layout[0];
      var method = (first && first.nodeType && ((first.nodeType != 1) || (!first.lsd))) ? 'children' : 'render';
      old = this.layouts[name] = this.document.layout[method](layout, parent, memo);
    }
    if (memo.promised) {
      memo.promised = false;
      this.addEvent('DOMChildNodesRendered:once', function() {
        this.document.layout.realize(old)
      });
    }
    return this.layouts[name];
  },

  removeLayout: function(name, layout, parent, memo) {
    return this.document.layout.remove(this.layouts[name] || layout, parent, memo);
  },

  buildLayout: function(layout, parent, memo) {
    return this.document.layout[layout.charAt ? 'selector' : 'render'](layout, (!parent && parent !== false) ? this : parent, memo)
  }
});

LSD.Module.Layout.events = {
  /*
    Builds children after element is built
  */
  build: function() {
    if (this.properties.layout) {
      this.addLayout('options', this.properties.layout, [this, this.getWrapper()], {lazy: true});
    }
    if (this.origin && !this.options.clone && this.origin.parentNode && this.origin != this.element)
      this.element.replaces(this.origin);
    if ((!this.options.lazy && this.options.traverse !== false) || (this.origin && !this.element)) {
      var nodes = LSD.slice((this.origin || this.element).childNodes);
      var opts = {}
      if (this.options.context) opts.context = this.options.context;
      if (this.options.clone) opts.clone = this.options.clone;
      if (nodes.length) this.addLayout('children', nodes, [this, this.getWrapper()], opts);
      this.fireEvent('DOMChildNodesRendered');
    }
  },
  /*
    Destroys the built layout with the widget
  */
  destroy: function() {
    if (this.layouts.children) this.removeLayout('children');
    if (this.layouts.options) this.removeLayout('options');
  },
  /*
    Augments all parsed HTML that goes through standart .write() interface
  */
  write: function(node) {
    this.addLayout('written', node, [this, this.getWrapper()]);
  },
  /*
    Augments all inserted nodes that come from partial html updates
  */
  DOMNodeInserted: function(node) {
    this.buildLayout(node, [this, this.getWrapper()]);
  },
  DOMNodeInsertedBefore: function(node, target) {
    this.buildLayout(node, [this, this.getWrapper()], null, {before: target});
  }
};

LSD.Module.Events.addEvents.call(LSD.Module.Layout.prototype, LSD.Module.Layout.events);

Object.append(LSD.Options, {
  layout: {
    add: function(value) {
      this.properties.set('layout', value);
    },
    remove: function(value) {
      this.properties.unset('layout', value);
    }
  }
});<|endoftext|>


<commit_before>function (head, req) {

    var baseUri, prefix, typeLiterals, tripleIterator, formatTriple, xmlEscape;

    /**
     * The base URI.
     */
    if (req.query.hasOwnProperty("base_uri") === true && req.query["base_uri"] !== "") {
        baseUri = req.query["base_uri"];
    } else {
     // "Host" is a mandatory header since HTTP/1.1.
        baseUri = "http://" + req.headers["Host"] + "/" + req.info.db_name + "/_design/sessel/_rewrite/";
    }

    /**
     * The prefix of the base URI.
     */
     if (req.query.hasOwnProperty("prefix") === true && req.query.prefix !== "") {
        prefix = req.query["prefix"];
     } else {
        prefix = "sessel";
     }

    /**
     * Flag to type literals.
     */
     if (req.query.hasOwnProperty("type_literals") === true && req.query["type_literals"] === "true") {
        typeLiterals = true;
     } else {
        typeLiterals = false;
     }

    /**
     * Iterate over triples.
     * @param callback Function to apply to each triple.
     */
    tripleIterator = function (callback) {
        var row;
        while (row = getRow()) {
            callback(row.key, row.value);
        }
    };

    /**
     * Format triple.
     * @param triple
     * @param annotations
     * @param [opts]
     *        - prefixes Table of prefixes to build QNames.
     *        - typeLiterals True if literals should be typed.
     * @return Formatted triple
     */
    formatTriple = function (triple, annotations, opts) {
        var prefixes, typeLiterals, formattedTriple;
        opts = opts || {};
        prefixes = opts.prefixes || null;
        typeLiterals = opts.typeLiterals || false;
        formattedTriple = [];
        if (prefixes !== null && prefixes[baseUri] !== undefined) {
         // Use QNames if the URI can be resolved to a prefix.
            formattedTriple[0] = prefixes[baseUri] + ":" + triple[0];
            formattedTriple[1] = prefixes[baseUri + "vocab/#"] + ":" + triple[1];
        } else {
         // Use a URI if no suitable prefix can be found.
            formattedTriple[0] = "<" + baseUri + triple[0] + ">";
            formattedTriple[1] = "<" + baseUri + "vocab/#" + triple[1] + ">";
        }
        switch (annotations.objectType) {
            case "object":
            case "array":
            case "null":
             // Escape quotation marks.
                formattedTriple[2] = "\"" + triple[2].replace(/\\/g, "\\\\").replace(/"/g, "\\\"") + "\"";
                break;
            case "_attachment":
             // Expand URLs to attachments.
                formattedTriple[2] = "\"" + baseUri + triple[0] + "/" + triple[2] + "\"";
                break;
            default:
                formattedTriple[2] = triple[2];
                break;
        }
     // Type literals.
        if (typeLiterals === true) {
            switch (annotations.objectType) {
                case "string":
                case "object":
                case "array":
                case "null":
                case "_attachment":
                    formattedTriple[2] += "^^<http://www.w3.org/2001/XMLSchema#string>";
                    break;
                case "number":
                 // Wrap number into quotation marks first.
                    formattedTriple[2] = "\"" + formattedTriple[2] + "\"";
                    if (triple[2] % 1 === 0) {
                        formattedTriple[2] += "^^<http://www.w3.org/2001/XMLSchema#integer>";
                    } else {
                        formattedTriple[2] += "^^<http://www.w3.org/2001/XMLSchema#double>";
                    }
                    break;
                case "boolean":
                    formattedTriple[2] = "\"" + formattedTriple[2] + "\"";
                    formattedTriple[2] += "^^<http://www.w3.org/2001/XMLSchema#boolean>";
                    break;
            }
        }
        return formattedTriple;
    };

    /**
     * Needed to generate RDF/XML.
     */
    xmlEscape = function (doc) {
        doc = doc.replace(/&/g, "&");
        doc = doc.replace(/</g, "<");
        doc = doc.replace(/>/g, ">");
        doc = doc.replace(/"/g, """);
        doc = doc.replace(/'/g, "'");
        return doc;
    };

    /**
     * Output N-Triples.
     * "The Internet media type / MIME type of N-Triples is text/plain." (doh)
     * TODO: "Character encoding is 7-bit US-ASCII."
     */
    registerType("nt", "text/plain");
    provides("nt", function () {
        start({
            "headers": {
                "Content-Disposition": "attachment; filename=" + req.info.db_name + ".nt"
            }
        });
        tripleIterator(function (triple, annotations) {
            var formattedTriple;
            formattedTriple = formatTriple(triple, annotations, {
                typeLiterals: typeLiterals
            });
            if (typeLiterals === false) {
                switch (annotations.objectType) {
                    case "number":
                    case "boolean":
                        formattedTriple[2] = "\"" + formattedTriple[2] + "\"";
                        break;
                }
            }
            send(formattedTriple.join(" ") + " .\n");
        });
    });

    /**
     * Output Turtle (Terse RDF Triple Language).
     */
    registerType("ttl", "text/turtle");
    provides("ttl", function () {
        var prefixes, firstSubject, currentSubject;
        start({
            "headers": {
                "Content-Disposition": "attachment; filename=" + req.info.db_name + ".ttl"
            }
        });
        prefixes = {};
        prefixes[baseUri] = prefix;
        prefixes[baseUri + "vocab/#"] = prefix + "Vocab";
        Object.keys(prefixes).forEach(function (uri) {
            send("@prefix " + prefixes[uri] + ": <" + uri + "> .\n");
        });
        firstSubject = true;
        tripleIterator(function (triple, annotations) {
            var formattedTriple;
            formattedTriple = formatTriple(triple, annotations, {
                prefixes: prefixes,
                typeLiterals: typeLiterals
            });
         // Abbreviate Turtle.
            if (firstSubject === true || currentSubject !== formattedTriple[0]) {
             // Skip first period.
                if (firstSubject === true) {
                    firstSubject = false;
                } else {
                    send(" .\n");
                }
             // Send the full triple.
                send(formattedTriple.join(" "));
            } else {
             // Send the abbreviated triple.
                send(" ;\n    " + formattedTriple[1] + " " + formattedTriple[2]);
            }
            currentSubject = formattedTriple[0];
        });
     // Send the final period.
        send(" .");
    });

    /**
     * Output RDF/XML.
     */
    registerType("rdf", "application/rdf+xml");
    provides("rdf", function () {
        start({
            "headers": {
                "Content-Disposition": "attachment; filename=" + req.info.db_name + ".rdf"
            }
        });
        send("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
        send("<rdf:RDF\n");
        send("  xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"\n");
        send("  xmlns:xsd=\"http://www.w3.org/2001/XMLSchema#\"\n");
        send("  xmlns:" + prefix + "=\"" + baseUri + "\"\n");
        send("  xmlns:" + prefix + "Vocab=\"" + baseUri + "vocab/#\"");
        send(">\n");
        tripleIterator(function (triple, annotations) {
            var description, object, type;
         // Remove quotation marks from string object literals
            switch (annotations.objectType) {
                case "string":
                    object = triple[2].replace(/"([^"]*)"/, "$1");
                    break;
                case "_attachment":
                    object = baseUri + triple[0] + "/" + triple[2].replace(/"([^"]*)"/, "$1");
                    break;
                default:
                    object = triple[2];
                    break;
            }
         // Type literal.
            switch (annotations.objectType) {
                case "string":
                case "object":
                case "array":
                case "null":
                case "_attachment":
                    type = "xsd:string";
                    break;
                case "number":
                    if (triple[2] % 1 === 0) {
                        type = "xsd:integer";
                    } else {
                        type = "xsd:double";
                    }
                    break;
                case "boolean":
                    type = "xsd:boolean";
                    break;
                default:
                    type = null;
                    break;
            }
         // Escape object literals.
            description = [
                "  <rdf:Description rdf:about=\"" + baseUri + triple[0] + "\">",
                "    <" + prefix + "Vocab:" + triple[1] + ((type !== null) ? " rdf:datatype=\"" + type + "\">" : ">") + xmlEscape(object) + "</" + prefix + "Vocab:" + triple[1] + ">",
                "  </rdf:Description>"
            ].join("\n");
            send(description + "\n");
        });
        send("</rdf:RDF>");
    });

    /**
     * Output HTML.
     */
    provides("html", function () {
        send("<DOCTYPE html>");
        send("<meta charset=\"UTF-8\" />");
        send("<title>" + req.info.db_name + " – Sessel</title>");
        send("
");
        tripleIterator(function (triple, annotations) {
            var subject, predicate, object;
            subject = baseUri + triple[0];
            predicate = baseUri + "vocab/#" + triple[1];
            object = triple[2];
            send("
");
            send("<" + subject + "> ");
            send("<" + predicate + "> ");
            send(object);
            send("
");
        });
        send("
");
    });

}
<commit_msg>Improve HTML output.<commit_after>function (head, req) {

    var baseUri, prefix, typeLiterals, tripleIterator, formatTriple, xmlEscape;

    /**
     * The base URI.
     */
    if (req.query.hasOwnProperty("base_uri") === true && req.query["base_uri"] !== "") {
        baseUri = req.query["base_uri"];
    } else {
     // "Host" is a mandatory header since HTTP/1.1.
        baseUri = "http://" + req.headers["Host"] + "/" + req.info.db_name + "/_design/sessel/_rewrite/";
    }

    /**
     * The prefix of the base URI.
     */
     if (req.query.hasOwnProperty("prefix") === true && req.query.prefix !== "") {
        prefix = req.query["prefix"];
     } else {
        prefix = "sessel";
     }

    /**
     * Flag to type literals.
     */
     if (req.query.hasOwnProperty("type_literals") === true && req.query["type_literals"] === "true") {
        typeLiterals = true;
     } else {
        typeLiterals = false;
     }

    /**
     * Iterate over triples.
     * @param callback Function to apply to each triple.
     */
    tripleIterator = function (callback) {
        var row;
        while (row = getRow()) {
            callback(row.key, row.value);
        }
    };

    /**
     * Format triple.
     * @param triple
     * @param annotations
     * @param [opts]
     *        - prefixes Table of prefixes to build QNames.
     *        - typeLiterals True if literals should be typed.
     * @return Formatted triple
     */
    formatTriple = function (triple, annotations, opts) {
        var prefixes, typeLiterals, formattedTriple;
        opts = opts || {};
        prefixes = opts.prefixes || null;
        typeLiterals = opts.typeLiterals || false;
        formattedTriple = [];
        if (prefixes !== null && prefixes[baseUri] !== undefined) {
         // Use QNames if the URI can be resolved to a prefix.
            formattedTriple[0] = prefixes[baseUri] + ":" + triple[0];
            formattedTriple[1] = prefixes[baseUri + "vocab/#"] + ":" + triple[1];
        } else {
         // Use a URI if no suitable prefix can be found.
            formattedTriple[0] = "<" + baseUri + triple[0] + ">";
            formattedTriple[1] = "<" + baseUri + "vocab/#" + triple[1] + ">";
        }
        switch (annotations.objectType) {
            case "object":
            case "array":
            case "null":
             // Escape quotation marks.
                formattedTriple[2] = "\"" + triple[2].replace(/\\/g, "\\\\").replace(/"/g, "\\\"") + "\"";
                break;
            case "_attachment":
             // Expand URLs to attachments.
                formattedTriple[2] = "\"" + baseUri + triple[0] + "/" + triple[2] + "\"";
                break;
            default:
                formattedTriple[2] = triple[2];
                break;
        }
     // Type literals.
        if (typeLiterals === true) {
            switch (annotations.objectType) {
                case "string":
                case "object":
                case "array":
                case "null":
                case "_attachment":
                    formattedTriple[2] += "^^<http://www.w3.org/2001/XMLSchema#string>";
                    break;
                case "number":
                 // Wrap number into quotation marks first.
                    formattedTriple[2] = "\"" + formattedTriple[2] + "\"";
                    if (triple[2] % 1 === 0) {
                        formattedTriple[2] += "^^<http://www.w3.org/2001/XMLSchema#integer>";
                    } else {
                        formattedTriple[2] += "^^<http://www.w3.org/2001/XMLSchema#double>";
                    }
                    break;
                case "boolean":
                    formattedTriple[2] = "\"" + formattedTriple[2] + "\"";
                    formattedTriple[2] += "^^<http://www.w3.org/2001/XMLSchema#boolean>";
                    break;
            }
        }
        return formattedTriple;
    };

    /**
     * Needed to generate RDF/XML.
     */
    xmlEscape = function (doc) {
        doc = doc.replace(/&/g, "&");
        doc = doc.replace(/</g, "<");
        doc = doc.replace(/>/g, ">");
        doc = doc.replace(/"/g, """);
        doc = doc.replace(/'/g, "'");
        return doc;
    };

    /**
     * Output N-Triples.
     * "The Internet media type / MIME type of N-Triples is text/plain." (doh)
     * TODO: "Character encoding is 7-bit US-ASCII."
     */
    registerType("nt", "text/plain");
    provides("nt", function () {
        start({
            "headers": {
                "Content-Disposition": "attachment; filename=" + req.info.db_name + ".nt"
            }
        });
        tripleIterator(function (triple, annotations) {
            var formattedTriple;
            formattedTriple = formatTriple(triple, annotations, {
                typeLiterals: typeLiterals
            });
            if (typeLiterals === false) {
                switch (annotations.objectType) {
                    case "number":
                    case "boolean":
                        formattedTriple[2] = "\"" + formattedTriple[2] + "\"";
                        break;
                }
            }
            send(formattedTriple.join(" ") + " .\n");
        });
    });

    /**
     * Output Turtle (Terse RDF Triple Language).
     */
    registerType("ttl", "text/turtle");
    provides("ttl", function () {
        var prefixes, firstSubject, currentSubject;
        start({
            "headers": {
                "Content-Disposition": "attachment; filename=" + req.info.db_name + ".ttl"
            }
        });
        prefixes = {};
        prefixes[baseUri] = prefix;
        prefixes[baseUri + "vocab/#"] = prefix + "Vocab";
        Object.keys(prefixes).forEach(function (uri) {
            send("@prefix " + prefixes[uri] + ": <" + uri + "> .\n");
        });
        firstSubject = true;
        tripleIterator(function (triple, annotations) {
            var formattedTriple;
            formattedTriple = formatTriple(triple, annotations, {
                prefixes: prefixes,
                typeLiterals: typeLiterals
            });
         // Abbreviate Turtle.
            if (firstSubject === true || currentSubject !== formattedTriple[0]) {
             // Skip first period.
                if (firstSubject === true) {
                    firstSubject = false;
                } else {
                    send(" .\n");
                }
             // Send the full triple.
                send(formattedTriple.join(" "));
            } else {
             // Send the abbreviated triple.
                send(" ;\n    " + formattedTriple[1] + " " + formattedTriple[2]);
            }
            currentSubject = formattedTriple[0];
        });
     // Send the final period.
        send(" .");
    });

    /**
     * Output RDF/XML.
     */
    registerType("rdf", "application/rdf+xml");
    provides("rdf", function () {
        start({
            "headers": {
                "Content-Disposition": "attachment; filename=" + req.info.db_name + ".rdf"
            }
        });
        send("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
        send("<rdf:RDF\n");
        send("  xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"\n");
        send("  xmlns:xsd=\"http://www.w3.org/2001/XMLSchema#\"\n");
        send("  xmlns:" + prefix + "=\"" + baseUri + "\"\n");
        send("  xmlns:" + prefix + "Vocab=\"" + baseUri + "vocab/#\"");
        send(">\n");
        tripleIterator(function (triple, annotations) {
            var description, object, type;
         // Remove quotation marks from string object literals
            switch (annotations.objectType) {
                case "string":
                    object = triple[2].replace(/"([^"]*)"/, "$1");
                    break;
                case "_attachment":
                    object = baseUri + triple[0] + "/" + triple[2].replace(/"([^"]*)"/, "$1");
                    break;
                default:
                    object = triple[2];
                    break;
            }
         // Type literal.
            switch (annotations.objectType) {
                case "string":
                case "object":
                case "array":
                case "null":
                case "_attachment":
                    type = "xsd:string";
                    break;
                case "number":
                    if (triple[2] % 1 === 0) {
                        type = "xsd:integer";
                    } else {
                        type = "xsd:double";
                    }
                    break;
                case "boolean":
                    type = "xsd:boolean";
                    break;
                default:
                    type = null;
                    break;
            }
         // Escape object literals.
            description = [
                "  <rdf:Description rdf:about=\"" + baseUri + triple[0] + "\">",
                "    <" + prefix + "Vocab:" + triple[1] + ((type !== null) ? " rdf:datatype=\"" + type + "\">" : ">") + xmlEscape(object) + "</" + prefix + "Vocab:" + triple[1] + ">",
                "  </rdf:Description>"
            ].join("\n");
            send(description + "\n");
        });
        send("</rdf:RDF>");
    });

    /**
     * Output HTML.
     */
    provides("html", function () {
        var firstSubject, currentSubject;
        firstSubject = true;
        send("<DOCTYPE html>\n");
        send("<meta charset=\"UTF-8\" />\n");
        send("<title>" + req.info.db_name + " – Sessel</title>\n");
        tripleIterator(function (triple, annotations) {
            var subject, predicate, object;
            subject = baseUri + triple[0];
            predicate = baseUri + "vocab/#" + triple[1];
            object = triple[2];
            if (firstSubject === true || currentSubject !== triple[0]) {
             // Skip first period.
                if (firstSubject === true) {
                    firstSubject = false;
                } else {
                    send("
\n");
                }
                send("
<" + subject + ">
\n");
                send("
\n");
            }
            send("
<" + predicate + ">: " + object + "
\n");
            currentSubject = triple[0];
        });
        send("
\n");
    });

}
<|endoftext|>


<commit_before>(function() {
  'use strict';
  /* Directives */
  angular.module('blindMaps.directives', [])

  .directive('placeLabel', function() {
    return {
      restrict : 'A',
      template : ' {{place.name}}',
      compile : function(element) {
        element.addClass('label');
        element.addClass('label-default');
      }
    };
  })

  .directive('blindMap', ['mapControler', 'places', 'singleWindowResizeFn', 'getMapResizeFunction', '$parse',
      function(mapControler, places, singleWindowResizeFn, getMapResizeFunction, $parse) {
    return {
      restrict : 'E',
      template : '
' +
                  '
' +
                      '

' +
                  '
' +
                  '

' +
                  '
' +
                    '' +
                      '' +
                    '' +
                    '' +
                      ' ' +
                    '' +
                  '
' +
                  '

'+
                '
',
      link : function($scope, elem, attrs) {
        $scope.loading = true;
        $scope.name = places.getName($scope.part);
        $scope.practice = !attrs.showTooltips;
        var showTooltips = attrs.showTooltips !== undefined;

        var map = mapControler($scope.part, showTooltips, elem, function(m) {
          $scope.loading = false;
          var resize = getMapResizeFunction(m, elem, $scope.practice);
          singleWindowResizeFn(resize);
          resize();
          $scope.$eval(attrs.callback);
          $scope.$digest();
        });
        var model = $parse(attrs.map);
        //Set scope variable for the map
        model.assign($scope, map);
      },
      replace : true
    };
  }])

  .directive('zoomButtons', function() {
    return {
      restrict : 'C',
      template : '
' +
                    '' +
                      '' +
                    '' +
                      '' +
                  '
'
    };
  })

  .directive('email', function() {
    return {
      restrict : 'C',
      compile : function(elem) {
        var emailAddress = elem.html();
        emailAddress = emailAddress.replace('{zavinac}', '@');
        emailAddress = '' + emailAddress +
  '';
        elem.html(emailAddress);
      }
    };
  })

  .directive('atooltip', function() {
    return {
      restrict : 'C',
      link : function($scope, elem, attrs) {
        elem.tooltip({ 'placement' : attrs.placement || 'bottom' });
      }
    };
  })

  .directive('dropLogin', function() {
    return {
      restrict : 'C',
      compile : function(elem) {
        elem.bind('click', function() {
          elem.tooltip('destroy');
          elem.parent().find('.tooltip').remove();
        });
      }
    };
  })

  .directive('points', ['$timeout', 'events', function($timeout, events) {
    return {
      scope : true,
      restrict : 'C',
      link : function($scope, elem) {
        events.on('userUpdated', function(user) {
          $scope.user = user;
          if (user.points == 1) {
            $timeout(function() {
              elem.tooltip('show');
            }, 0);
          }
        });
      }
    };
  }])

  .directive('dropLogin',['$timeout', 'events', function($timeout, events) {
    return {
      restrict : 'C',
      link : function($scope, elem) {
        events.on('questionSetFinished', function(points) {
          if (10 < points && points <= 20) {
            $timeout(function() {
              elem.tooltip('show');
            }, 0);
          }
        });
      }
    };
  }])

  .directive('mapProgress', [function() {
    return {
      restrict : 'C',
      template : '
' +
                    '
' +
                    '
' +
                    '
' +
                    '
' +
                  '
',
      link : function($scope, elem, attrs) {
        $scope.count = attrs.count;
        attrs.$observe('skills', function(skills) {
          if(skills !== '') {
            $scope.skills = angular.fromJson(skills);
            elem.tooltip({
              html : true,
              placement: 'bottom',
              title : '
' +
                     'Naučeno: ' +
                     '' +
                       '' +
                       $scope.skills.learned + ' / ' + $scope.count +
                     '' +
                   '
' +
                   '
' +
                     'Procvičováno: ' +
                     '' +
                       '' +
                       $scope.skills.practiced + ' / ' + $scope.count +
                     '' +
                   '
'
            });
          }
        });
      }
    };
  }]);
}());
<commit_msg>Knowledge map place labels tooltips added.<commit_after>(function() {
  'use strict';
  /* Directives */
  angular.module('blindMaps.directives', [])

  .directive('placeLabel', ['colorScale', function(colorScale) {
    return {
      restrict : 'A',
      template : ' {{place.name}}',
      link : function($scope, elem) {
        elem.addClass('label');
        elem.addClass('label-default');
        elem.tooltip({
          html : true,
          placement: 'bottom',
          title : '
' +
                ' Odhad znalosti ' +
                '' +
                  '' +
                  10 * $scope.place.probability + ' / 10 ' +
                '' +
               '
'
        });
      }
    };
  }])

  .directive('blindMap', ['mapControler', 'places', 'singleWindowResizeFn', 'getMapResizeFunction', '$parse',
      function(mapControler, places, singleWindowResizeFn, getMapResizeFunction, $parse) {
    return {
      restrict : 'E',
      template : '
' +
                  '
' +
                      '

' +
                  '
' +
                  '

' +
                  '
' +
                    '' +
                      '' +
                    '' +
                    '' +
                      ' ' +
                    '' +
                  '
' +
                  '

'+
                '
',
      link : function($scope, elem, attrs) {
        $scope.loading = true;
        $scope.name = places.getName($scope.part);
        $scope.practice = !attrs.showTooltips;
        var showTooltips = attrs.showTooltips !== undefined;

        var map = mapControler($scope.part, showTooltips, elem, function(m) {
          $scope.loading = false;
          var resize = getMapResizeFunction(m, elem, $scope.practice);
          singleWindowResizeFn(resize);
          resize();
          $scope.$eval(attrs.callback);
          $scope.$digest();
        });
        var model = $parse(attrs.map);
        //Set scope variable for the map
        model.assign($scope, map);
      },
      replace : true
    };
  }])

  .directive('zoomButtons', function() {
    return {
      restrict : 'C',
      template : '
' +
                    '' +
                      '' +
                    '' +
                      '' +
                  '
'
    };
  })

  .directive('email', function() {
    return {
      restrict : 'C',
      compile : function(elem) {
        var emailAddress = elem.html();
        emailAddress = emailAddress.replace('{zavinac}', '@');
        emailAddress = '' + emailAddress +
  '';
        elem.html(emailAddress);
      }
    };
  })

  .directive('atooltip', function() {
    return {
      restrict : 'C',
      link : function($scope, elem, attrs) {
        elem.tooltip({ 'placement' : attrs.placement || 'bottom' });
      }
    };
  })

  .directive('dropLogin', function() {
    return {
      restrict : 'C',
      compile : function(elem) {
        elem.bind('click', function() {
          elem.tooltip('destroy');
          elem.parent().find('.tooltip').remove();
        });
      }
    };
  })

  .directive('points', ['$timeout', 'events', function($timeout, events) {
    return {
      scope : true,
      restrict : 'C',
      link : function($scope, elem) {
        events.on('userUpdated', function(user) {
          $scope.user = user;
          if (user.points == 1) {
            $timeout(function() {
              elem.tooltip('show');
            }, 0);
          }
        });
      }
    };
  }])

  .directive('dropLogin',['$timeout', 'events', function($timeout, events) {
    return {
      restrict : 'C',
      link : function($scope, elem) {
        events.on('questionSetFinished', function(points) {
          if (10 < points && points <= 20) {
            $timeout(function() {
              elem.tooltip('show');
            }, 0);
          }
        });
      }
    };
  }])

  .directive('mapProgress', [function() {
    return {
      restrict : 'C',
      template : '
' +
                    '
' +
                    '
' +
                    '
' +
                    '
' +
                  '
',
      link : function($scope, elem, attrs) {
        $scope.count = attrs.count;
        attrs.$observe('skills', function(skills) {
          if(skills !== '') {
            $scope.skills = angular.fromJson(skills);
            elem.tooltip({
              html : true,
              placement: 'bottom',
              title : '
' +
                     'Naučeno: ' +
                     '' +
                       '' +
                       $scope.skills.learned + ' / ' + $scope.count +
                     '' +
                   '
' +
                   '
' +
                     'Procvičováno: ' +
                     '' +
                       '' +
                       $scope.skills.practiced + ' / ' + $scope.count +
                     '' +
                   '
'
            });
          }
        });
      }
    };
  }]);
}());
<|endoftext|>


<commit_before>import { Material } from './Material.js';
import { UniformsUtils } from '../renderers/shaders/UniformsUtils.js';

/**
 * @author alteredq / http://alteredqualia.com/
 *
 * parameters = {
 *  defines: { "label" : "value" },
 *  uniforms: { "parameter1": { value: 1.0 }, "parameter2": { value2: 2 } },
 *
 *  fragmentShader: <string>,
 *  vertexShader: <string>,
 *
 *  wireframe: <boolean>,
 *  wireframeLinewidth: <float>,
 *
 *  lights: <bool>,
 *
 *  skinning: <bool>,
 *  morphTargets: <bool>,
 *  morphNormals: <bool>
 * }
 */

function ShaderMaterial( parameters ) {

	Material.call( this );

	this.type = 'ShaderMaterial';

	this.defines = {};
	this.uniforms = {};

	this.vertexShader = 'void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}';
	this.fragmentShader = 'void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}';

	this.linewidth = 1;

	this.wireframe = false;
	this.wireframeLinewidth = 1;

	this.fog = false; // set to use scene fog
	this.lights = false; // set to use scene lights
	this.clipping = false; // set to use user-defined clipping planes

	this.skinning = false; // set to use skinning attribute streams
	this.morphTargets = false; // set to use morph targets
	this.morphNormals = false; // set to use morph normals

	this.extensions = {
		derivatives: false, // set to use derivatives
		fragDepth: false, // set to use fragment depth values
		drawBuffers: false, // set to use draw buffers
		shaderTextureLOD: false // set to use shader texture LOD
	};

	// When rendered geometry doesn't include these attributes but the material does,
	// use these default values in WebGL. This avoids errors when buffer data is missing.
	this.defaultAttributeValues = {
		'color': [ 1, 1, 1 ],
		'uv': [ 0, 0 ],
		'uv2': [ 0, 0 ]
	};

	this.index0AttributeName = undefined;
	this.uniformsNeedUpdate = false;

	if ( parameters !== undefined ) {

		if ( parameters.attributes !== undefined ) {

			console.error( 'THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.' );

		}

		this.setValues( parameters );

	}

}

ShaderMaterial.prototype = Object.create( Material.prototype );
ShaderMaterial.prototype.constructor = ShaderMaterial;

ShaderMaterial.prototype.isShaderMaterial = true;

ShaderMaterial.prototype.copy = function ( source ) {

	Material.prototype.copy.call( this, source );

	this.fragmentShader = source.fragmentShader;
	this.vertexShader = source.vertexShader;

	this.uniforms = UniformsUtils.clone( source.uniforms );

	this.defines = Object.assign( {}, source.defines );

	this.wireframe = source.wireframe;
	this.wireframeLinewidth = source.wireframeLinewidth;

	this.lights = source.lights;
	this.clipping = source.clipping;

	this.skinning = source.skinning;

	this.morphTargets = source.morphTargets;
	this.morphNormals = source.morphNormals;

	this.extensions = source.extensions;

	return this;

};

ShaderMaterial.prototype.toJSON = function ( meta ) {

	var data = Material.prototype.toJSON.call( this, meta );

	data.uniforms = {};

	for ( var name in this.uniforms ) {

		var uniform = this.uniforms[ name ];
		var value = uniform.value;

		if ( value.isTexture ) {

			data.uniforms[ name ] = {
				type: 't',
				value: value.toJSON( meta ).uuid
			};

		} else if ( value.isColor ) {

			data.uniforms[ name ] = {
				type: 'c',
				value: value.getHex()
			};

		} else if ( value.isVector2 ) {

			data.uniforms[ name ] = {
				type: 'v2',
				value: value.toArray()
			};

		} else if ( value.isVector3 ) {

			data.uniforms[ name ] = {
				type: 'v3',
				value: value.toArray()
			};

		} else if ( value.isVector4 ) {

			data.uniforms[ name ] = {
				type: 'v4',
				value: value.toArray()
			};

		} else if ( value.isMatrix4 ) {

			data.uniforms[ name ] = {
				type: 'm4',
				value: value.toArray()
			};

		} else {

			data.uniforms[ name ] = {
				value: value
			};

		}

	}

	data.vertexShader = this.vertexShader;
	data.fragmentShader = this.fragmentShader;

	return data;

};

export { ShaderMaterial };
<commit_msg>ShaderMaterial: Added note about uniform types<commit_after>import { Material } from './Material.js';
import { UniformsUtils } from '../renderers/shaders/UniformsUtils.js';

/**
 * @author alteredq / http://alteredqualia.com/
 *
 * parameters = {
 *  defines: { "label" : "value" },
 *  uniforms: { "parameter1": { value: 1.0 }, "parameter2": { value2: 2 } },
 *
 *  fragmentShader: <string>,
 *  vertexShader: <string>,
 *
 *  wireframe: <boolean>,
 *  wireframeLinewidth: <float>,
 *
 *  lights: <bool>,
 *
 *  skinning: <bool>,
 *  morphTargets: <bool>,
 *  morphNormals: <bool>
 * }
 */

function ShaderMaterial( parameters ) {

	Material.call( this );

	this.type = 'ShaderMaterial';

	this.defines = {};
	this.uniforms = {};

	this.vertexShader = 'void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}';
	this.fragmentShader = 'void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}';

	this.linewidth = 1;

	this.wireframe = false;
	this.wireframeLinewidth = 1;

	this.fog = false; // set to use scene fog
	this.lights = false; // set to use scene lights
	this.clipping = false; // set to use user-defined clipping planes

	this.skinning = false; // set to use skinning attribute streams
	this.morphTargets = false; // set to use morph targets
	this.morphNormals = false; // set to use morph normals

	this.extensions = {
		derivatives: false, // set to use derivatives
		fragDepth: false, // set to use fragment depth values
		drawBuffers: false, // set to use draw buffers
		shaderTextureLOD: false // set to use shader texture LOD
	};

	// When rendered geometry doesn't include these attributes but the material does,
	// use these default values in WebGL. This avoids errors when buffer data is missing.
	this.defaultAttributeValues = {
		'color': [ 1, 1, 1 ],
		'uv': [ 0, 0 ],
		'uv2': [ 0, 0 ]
	};

	this.index0AttributeName = undefined;
	this.uniformsNeedUpdate = false;

	if ( parameters !== undefined ) {

		if ( parameters.attributes !== undefined ) {

			console.error( 'THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.' );

		}

		this.setValues( parameters );

	}

}

ShaderMaterial.prototype = Object.create( Material.prototype );
ShaderMaterial.prototype.constructor = ShaderMaterial;

ShaderMaterial.prototype.isShaderMaterial = true;

ShaderMaterial.prototype.copy = function ( source ) {

	Material.prototype.copy.call( this, source );

	this.fragmentShader = source.fragmentShader;
	this.vertexShader = source.vertexShader;

	this.uniforms = UniformsUtils.clone( source.uniforms );

	this.defines = Object.assign( {}, source.defines );

	this.wireframe = source.wireframe;
	this.wireframeLinewidth = source.wireframeLinewidth;

	this.lights = source.lights;
	this.clipping = source.clipping;

	this.skinning = source.skinning;

	this.morphTargets = source.morphTargets;
	this.morphNormals = source.morphNormals;

	this.extensions = source.extensions;

	return this;

};

ShaderMaterial.prototype.toJSON = function ( meta ) {

	var data = Material.prototype.toJSON.call( this, meta );

	data.uniforms = {};

	for ( var name in this.uniforms ) {

		var uniform = this.uniforms[ name ];
		var value = uniform.value;

		if ( value.isTexture ) {

			data.uniforms[ name ] = {
				type: 't',
				value: value.toJSON( meta ).uuid
			};

		} else if ( value.isColor ) {

			data.uniforms[ name ] = {
				type: 'c',
				value: value.getHex()
			};

		} else if ( value.isVector2 ) {

			data.uniforms[ name ] = {
				type: 'v2',
				value: value.toArray()
			};

		} else if ( value.isVector3 ) {

			data.uniforms[ name ] = {
				type: 'v3',
				value: value.toArray()
			};

		} else if ( value.isVector4 ) {

			data.uniforms[ name ] = {
				type: 'v4',
				value: value.toArray()
			};

		} else if ( value.isMatrix4 ) {

			data.uniforms[ name ] = {
				type: 'm4',
				value: value.toArray()
			};

		} else {

			data.uniforms[ name ] = {
				value: value
			};

			// note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far

		}

	}

	data.vertexShader = this.vertexShader;
	data.fragmentShader = this.fragmentShader;

	return data;

};

export { ShaderMaterial };
<|endoftext|>


<commit_before>var request = require('request');
var cheerio = require('cheerio');
var Promise = require('promise');
var requestp = require('../../requestp');

/* Resource for ligamagic */
module.exports = {
  find : function(cardname, proxy) {
    // Add some way to get the card with this resource
    console.log("Looking for " + cardname);
    console.log("Proxy: " + proxy);
    return new Promise(function(resolve, reject) {
      var request_options = {
        headers: {
          'User-Agent' : 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.155 Safari/537.36',
          'Accept' : 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'
        },
        url: "http://ligamagic.com.br/?view=cards%2Fsearch&card=" + cardname
      };
      requestp(request_options)
        .then(function(body) {

          if(body.indexOf("0-0") !== -1)
            reject("Card not found");

          //read the data
          var $ = cheerio.load(body);
          var title = $(".cardTitle").text();
          var card_sets_obj = {};
          var card_set_array = [];
          var card = {};
          var moeda = "BRL";
          $(".overview td").each(function(i, elem) {
            var card_set = $("a", elem).attr("href");
            card_set = card_set.split("%3d")[1];
            card_sets_obj[card_set] = {}; //No prices found yet!
            card_sets_obj[card_set][moeda] = []; //Set prices as USD

            //@TODO:  Stop reading from the Javascript at the end of the page
            //        and scrappe the page instead. Dumbass! There's a table
            //        with the prices, lel!

            //Find the minor price for the card
            var regexMinorPrice = new RegExp("VETprecoMenor\\[" + i.toString() + "\\]\\s+=\\s+\"(.*)\";", "i");
            var minorPrice = body.match(regexMinorPrice)[1].replace(',', '.');
            card_sets_obj[card_set][moeda].push(minorPrice);

            //Find the medium price for the card
            var regexMediumPrice = new RegExp("VETprecoMedio\\[" + i.toString() + "\\]\\s+=\\s+\"(.*)\";", "i");
            var mediumPrice = body.match(regexMediumPrice)[1].replace(',', '.');
            card_sets_obj[card_set][moeda].push(mediumPrice);

            //Find the major price for the card
            var regexMajorPrice = new RegExp("VETprecoMaior\\[" + i.toString() + "\\]\\s+=\\s+\"(.*)\";", "i");
            var majorPrice = body.match(regexMajorPrice)[1].replace(',', '.');
            card_sets_obj[card_set][moeda].push(majorPrice);
          });

          card["title"] = title;
          card["prices"] = card_sets_obj;
          card["sets"] = Object.keys(card_sets_obj);
          card["currencies"] = [moeda];
          card["url"] = request_options["url"];

          resolve(card);
          //resolve("Misterious card info!");
        }, function(err) {
          reject(err); //Cascading promises
        });
    });
  }
}
<commit_msg>Changing price fetch for LigaMagic<commit_after>var request = require('request');
var cheerio = require('cheerio');
var Promise = require('promise');
var requestp = require('../../requestp');

/* Resource for ligamagic */
module.exports = {
  find : function(cardname, proxy) {
    // Add some way to get the card with this resource
    console.log("Looking for " + cardname);
    console.log("Proxy: " + proxy);
    return new Promise(function(resolve, reject) {
      var request_options = {
        headers: {
          'User-Agent' : 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.155 Safari/537.36',
          'Accept' : 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'
        },
        url: "http://ligamagic.com.br/?view=cards%2Fsearch&card=" + cardname
      };
      requestp(request_options)
        .then(function(body) {

          if(body.indexOf("0-0") !== -1)
            reject("Card not found");

          //read the data
          var $ = cheerio.load(body);
          var title = $(".nome-auxiliar").eq(0).text();
          var card_sets_obj = {};
          var card_set_array = [];
          var card = {};
          var curency = "BRL";
          $(".card-image .edicoes li").each(function(i, elem) {

            //@TODO:  Stop reading from the Javascript at the end of the page
            //        and scrappe the page instead. Dumbass! There's a table
            //        with the prices, lel!

            var regexSetInfo = new RegExp("vetPorEdicao\\[" + i.toString() + "\\]=\\[(.*?)\\];", "i");
            var setInfo = JSON.parse("[" + body.match(regexSetInfo)[1] + "]");

            card_set = setInfo[6];
            card_sets_obj[card_set] = {}; //No prices found yet!
            card_sets_obj[card_set][curency] = []; //Set prices as USD

            // Minor, medium and major price for the card, and also set info
            card_sets_obj[card_set][curency].push(setInfo[5].replace(',', '.'));
            card_sets_obj[card_set][curency].push(setInfo[4].replace(',', '.'));
            card_sets_obj[card_set][curency].push(setInfo[3].replace(',', '.'));
          });

          card["title"] = title;
          card["prices"] = card_sets_obj;
          card["sets"] = Object.keys(card_sets_obj);
          card["currencies"] = [curency];
          card["url"] = request_options["url"];

          resolve(card);
          //resolve("Misterious card info!");
        }, function(err) {
          reject(err); //Cascading promises
        });
    });
  }
}
<|endoftext|>