<commit_before>#!/usr/bin/env node

var express = require('express');
var app = express();

// Whatever you do, make sure you adjust your port according to process.env.PORT
// Ayen requires this for BrowserSync proxying and Critical CSS
var port = parseInt(process.env.PORT, 10) || 80;

app.use(express.static(__dirname + '/../www'));

app.get('/api/example_endpoint', function (req, res) {
  res.status(200);
  res.send('{ "hello": "world" }');
  res.end();
});

if (app.get('env') === 'development') {
  app.use(require('errorhandler')());
}

app.listen(port);
console.log('Server running at http://localhost:' + port);

// Ayen needs to wait for your server to start before firing up BrowserSync.
// This line gives it the cue, but the wait times out after 4 seconds if the
// cue doesn't show up and BrowserSync is fired up anyway.
process.send('serverStarted');
<commit_msg>Made server executable<commit_after>#!/usr/bin/env node

var express = require('express');
var app = express();

// Whatever you do, make sure you adjust your port according to process.env.PORT
// Ayen requires this for BrowserSync proxying and Critical CSS
var port = parseInt(process.env.PORT, 10) || 80;

app.use(express.static(__dirname + '/../www'));

app.get('/api/example_endpoint', function (req, res) {
  res.status(200);
  res.send('{ "hello": "world" }');
  res.end();
});

if (app.get('env') === 'development') {
  app.use(require('errorhandler')());
}

app.listen(port);
console.log('Server running at http://localhost:' + port);

// Ayen needs to wait for your server to start before firing up BrowserSync.
// This line gives it the cue, but the wait times out after 4 seconds if the
// cue doesn't show up and BrowserSync is fired up anyway.
process.send('serverStarted');
<|endoftext|>


<commit_before>const test = require('tape')
const Promise = require('bluebird')
const moment = require('moment')
const enums = require('../src/enums')
const is = require('../src/is')
const testError = require('./test-error')
const testOptions = require('./test-options')
const connectionOptionsOnly = testOptions.connection()
const queueDefaultOptions = testOptions.queueDefault()
const customjobOptions = testOptions.jobOptionsHigh()
const testData = require('./test-options').testData
const jobOptions = require('../src/job-options')
const Queue = require('../src/queue')

module.exports = function () {
  return new Promise((resolve, reject) => {
    test('queue', (t) => {
      t.plan(600)

      let q = new Queue()

      let customJobOptions = {
        priority: 'high',
        timeout: 200,
        retryMax: 5,
        retryDelay: 400
      }

      // ---------- Event Handler Setup ----------
      let testEvents = false
      function errorEventHandler (err) {
        if (testEvents) {
          t.ok(is.string(err.message), `Event: error [${err.message}]`)
        }
      }
      function addEventHandlers () {
        testEvents = true
        q.on(enums.status.error, errorEventHandler)
      }
      function removeEventHandlers () {
        testEvents = false
        q.removeListener(enums.status.error, errorEventHandler)
      }

      q.ready.then((ready) => {
        addEventHandlers()
        t.ok(ready, 'Queue is ready')

        // ---------- Constructor with Default Options Tests ----------
        t.comment('queue: Constructor with Default Options')
        t.ok(q, 'Queue created with default options')
        t.equal(q.name, enums.options.name, 'Default queue name valid')
        t.ok(is.string(q.id), 'Queue id is valid')
        t.equal(q.host, enums.options.host, 'Default host name is valid')
        t.equal(q.port, enums.options.port, 'Default port is valid')
        t.equal(q.db, enums.options.db, 'Default db name is valid')
        t.ok(is.function(q.r), 'Queue r valid')
        t.ok(is.function(q.connection), 'Queue connection valid')
        t.ok(q.changeFeed, 'Queue change feed is enabled')
        t.ok(q.master, 'Queue is master queue')
        t.equal(q.masterInterval, enums.options.masterInterval, 'Queue masterInterval is valid')
        t.ok(is.object(q.jobOptions), 'Queue jobOptions is an object')
        t.equal(q.jobOptions.priority, enums.priorityFromValue(40), 'Default job priority is normal')
        t.equal(q.jobOptions.timeout, enums.options.timeout, 'Default job timeout is valid')
        t.equal(q.jobOptions.retryMax, enums.options.retryMax, 'Default job retryMax is valid')
        t.equal(q.jobOptions.retryDelay, enums.options.retryDelay, 'Default job retryDelay is valid')
        t.equal(q.removeFinishedJobs, enums.options.removeFinishedJobs, 'Default removeFinishedJobs is valid')
        t.equal(q.running, 0, 'Running jobs is zero')
        t.equal(q.concurrency, enums.options.concurrency, 'Default concurrency is valid')
        t.notOk(q.paused, 'Queue is not paused')
        t.ok(q.idle, 'Queue is idle')

        // ---------- Set Properties Tests ----------
        t.comment('queue: Set Properties')
        q.jobOptions = customJobOptions
        t.deepEqual(q.jobOptions, customJobOptions, 'Job options set successfully')
        q.jobOptions = null
        t.deepEqual(q.jobOptions, jobOptions(), 'Job options restored to default on invalid value')
        q.concurrency = 100
        t.equal(q.concurrency, 100, 'Queue concurrency set with valid value successfully')
        q.concurrency = -50
        t.equal(q.concurrency, 100, 'Queue concurrency unchanged with invalid value')
        q.concurrency = 1.5
        t.equal(q.concurrency, 100, 'Queue concurrency unchanged with invalid value')
        q.concurrency = 'string'
        t.equal(q.concurrency, 100, 'Queue concurrency unchanged with invalid value')

        // ---------- Create Job Tests ----------
        t.comment('queue: Create Job')
        let job = q.createJob(testData)
        t.ok(is.job(job), 'Queue createJob created a job object')
        t.equal(job.priority, enums.priorityFromValue(40), 'Queue created job with default priority')
        t.equal(job.timeout, enums.options.timeout, 'Queue created job with default timeout')
        t.equal(job.retryMax, enums.options.retryMax, 'Queue created job with default retryMax')
        t.equal(job.retryDelay, enums.options.retryDelay, 'Queue created job with default retryDelay')
        job = q.createJob(testData, customJobOptions)
        t.ok(is.job(job), 'Queue createJob created a job object')
        t.equal(job.priority, customJobOptions.priority, 'Queue created job with custom priority')
        t.equal(job.timeout, customJobOptions.timeout, 'Queue created job with custom timeout')
        t.equal(job.retryMax, customJobOptions.retryMax, 'Queue created job with custom retryMax')
        t.equal(job.retryDelay, customJobOptions.retryDelay, 'Queue created job with custom retryDelay')
        console.dir(job)

        removeEventHandlers()
      }).catch(err => testError(err, module, t))

      // q.on('ready', () => {
      //   t.pass('Event: Queue ready')
      // })
      // q.on('added', (job) => {
      //   t.pass('Queue added event called')
      // })
      // q.on('processing', (processingValue) => {
      //   t.pass('Queue processing event called')
      // })
      // q.on('progress', (progressValue) => {
      //   t.pass('Queue progress event called')
      // })
      // q.on('idle', (jobId) => {
      //   t.pass('Queue idle event called')
      // })
      // q.on('success', (jobId) => {
      //   t.pass('Queue success event called')
      // })
      // q.on('failed', (jobId) => {
      //   t.pass('Queue failure event called')
      // })
      // // q.on('retry', (jobId) => {
      // //   t.pass('Queue retry event called')
      // // })
      // q.on('job failed', (jobId) => {
      //   console.log('job failed: ' + jobId)
      //   t.pass('Queue idle event called')
      // })
      //
      //
      // q.process((job, next) => {
      //   console.log('~~~~~~~~~~ process ~~~~~~~~~~')
      //   console.log(job.id)
      //   setTimeout(() => {
      //     console.log('~~~~~~~~~~ process finished ~~~~~~~~~~')
      //     next(null, 'Job Completed')
      //   }, 3000)
      // })
      //
      // let jobs = []
      // // console.dir(JSON.parse(JSON.stringify(q)))
      // // let ej = q.createJob()
      // // ej.id = 'ba3002c6-193f-4957-bc13-a4c3871629d7'
      // // // jobs.push(ej)
      // // for (let i = 0; i < 4; i++) {
      //   jobs.push(q.createJob({foo: 1}))
      // // }
      //
      // q.addJob(jobs).then((result) => {
      //   console.log('~~~~~~~~~~ addJob result ~~~~~~~~~~')
      //   console.dir(JSON.parse(JSON.stringify(result)))
      // }).then(() => {
      //   return q.summary()
      // }).then((d) => {
      //   console.log('~~~~~~~~~~ summary ~~~~~~~~~~')
      //   console.dir(d)
      // }).then(() => {
      //   return q.drop(4000)
      // }).then((removeResult) => {
      //   console.log('~~~~~~~~~~ removeResult ~~~~~~~~~~')
      //   console.dir(removeResult)
      // }).catch(err => testError(err, module, t))
      //
      // q.jobOptions = customjobOptions
      // t.deepEqual(q.jobOptions, customjobOptions, 'Set default job options')
    })
  })
}
<commit_msg>more queue tests<commit_after>const test = require('tape')
const Promise = require('bluebird')
const moment = require('moment')
const enums = require('../src/enums')
const is = require('../src/is')
const testError = require('./test-error')
const testOptions = require('./test-options')
const connectionOptionsOnly = testOptions.connection()
const queueDefaultOptions = testOptions.queueDefault()
const customjobOptions = testOptions.jobOptionsHigh()
const testData = require('./test-options').testData
const jobOptions = require('../src/job-options')
const Queue = require('../src/queue')

module.exports = function () {
  return new Promise((resolve, reject) => {
    test('queue', (t) => {
      t.plan(600)

      let q = new Queue()

      let job
      let customJobOptions = {
        priority: 'high',
        timeout: 200,
        retryMax: 5,
        retryDelay: 400
      }

      // ---------- Event Handler Setup ----------
      let testEvents = false
      function errorEventHandler (err) {
        if (testEvents) {
          t.ok(is.string(err.message), `Event: error [${err.message}]`)
        }
      }
      function addEventHandlers () {
        testEvents = true
        q.on(enums.status.error, errorEventHandler)
      }
      function removeEventHandlers () {
        testEvents = false
        q.removeListener(enums.status.error, errorEventHandler)
      }

      q.ready.then((ready) => {
        addEventHandlers()
        t.ok(ready, 'Queue is ready')

        // ---------- Constructor with Default Options Tests ----------
        t.comment('queue: Constructor with Default Options')
        t.ok(q, 'Queue created with default options')
        t.equal(q.name, enums.options.name, 'Default queue name valid')
        t.ok(is.string(q.id), 'Queue id is valid')
        t.equal(q.host, enums.options.host, 'Default host name is valid')
        t.equal(q.port, enums.options.port, 'Default port is valid')
        t.equal(q.db, enums.options.db, 'Default db name is valid')
        t.ok(is.function(q.r), 'Queue r valid')
        t.ok(is.function(q.connection), 'Queue connection valid')
        t.ok(q.changeFeed, 'Queue change feed is enabled')
        t.ok(q.master, 'Queue is master queue')
        t.equal(q.masterInterval, enums.options.masterInterval, 'Queue masterInterval is valid')
        t.ok(is.object(q.jobOptions), 'Queue jobOptions is an object')
        t.equal(q.jobOptions.priority, enums.priorityFromValue(40), 'Default job priority is normal')
        t.equal(q.jobOptions.timeout, enums.options.timeout, 'Default job timeout is valid')
        t.equal(q.jobOptions.retryMax, enums.options.retryMax, 'Default job retryMax is valid')
        t.equal(q.jobOptions.retryDelay, enums.options.retryDelay, 'Default job retryDelay is valid')
        t.equal(q.removeFinishedJobs, enums.options.removeFinishedJobs, 'Default removeFinishedJobs is valid')
        t.equal(q.running, 0, 'Running jobs is zero')
        t.equal(q.concurrency, enums.options.concurrency, 'Default concurrency is valid')
        t.notOk(q.paused, 'Queue is not paused')
        t.ok(q.idle, 'Queue is idle')

        // ---------- Set Properties Tests ----------
        t.comment('queue: Set Properties')
        q.jobOptions = customJobOptions
        t.deepEqual(q.jobOptions, customJobOptions, 'Job options set successfully')
        q.jobOptions = null
        t.deepEqual(q.jobOptions, jobOptions(), 'Job options restored to default on invalid value')
        q.concurrency = 100
        t.equal(q.concurrency, 100, 'Queue concurrency set with valid value successfully')
        q.concurrency = -50
        t.equal(q.concurrency, 100, 'Queue concurrency unchanged with invalid value')
        q.concurrency = 1.5
        t.equal(q.concurrency, 100, 'Queue concurrency unchanged with invalid value')
        q.concurrency = 'string'
        t.equal(q.concurrency, 100, 'Queue concurrency unchanged with invalid value')

        // ---------- Create Job Tests ----------
        t.comment('queue: Create Job')
        job = q.createJob(testData)
        t.ok(is.job(job), 'Queue createJob created a job object')
        t.equal(job.priority, enums.priorityFromValue(40), 'Queue created job with default priority')
        t.equal(job.timeout, enums.options.timeout, 'Queue created job with default timeout')
        t.equal(job.retryMax, enums.options.retryMax, 'Queue created job with default retryMax')
        t.equal(job.retryDelay, enums.options.retryDelay, 'Queue created job with default retryDelay')
        job = q.createJob(testData, customJobOptions)
        t.ok(is.job(job), 'Queue createJob created a job object')
        t.equal(job.priority, customJobOptions.priority, 'Queue created job with custom priority')
        t.equal(job.timeout, customJobOptions.timeout, 'Queue created job with custom timeout')
        t.equal(job.retryMax, customJobOptions.retryMax, 'Queue created job with custom retryMax')
        t.equal(job.retryDelay, customJobOptions.retryDelay, 'Queue created job with custom retryDelay')

        // ---------- Create Job Tests ----------
        t.comment('queue: Add Job')
        job = q.createJob(testData)
        return q.addJob(job)
      }).then((savedJobs) => {
        t.ok(is.array(savedJobs), 'Add job returns an array')
        t.ok(is.job(savedJobs[0]), 'Job saved successfully')
        t.equal(savedJobs[0].id, job.id, 'Job id is valid')
        t.equal(savedJobs[0].status, enums.status.added, 'Job status is valid')

        // ---------- Create Job Tests ----------
        t.comment('queue: Get Job')
        return q.getJob(savedJobs[0].id)
      }).then((savedJobs2) => {
        t.ok(is.array(savedJobs2), 'Get job returns an array')
        t.ok(is.job(savedJobs2[0]), 'Job retrieved successfully')
        t.equal(savedJobs2[0].id, job.id, 'Job id is valid')
        t.equal(savedJobs2[0].status, enums.status.added, 'Job status is valid')

        removeEventHandlers()
      }).catch(err => testError(err, module, t))

      // q.on('ready', () => {
      //   t.pass('Event: Queue ready')
      // })
      // q.on('added', (job) => {
      //   t.pass('Queue added event called')
      // })
      // q.on('processing', (processingValue) => {
      //   t.pass('Queue processing event called')
      // })
      // q.on('progress', (progressValue) => {
      //   t.pass('Queue progress event called')
      // })
      // q.on('idle', (jobId) => {
      //   t.pass('Queue idle event called')
      // })
      // q.on('success', (jobId) => {
      //   t.pass('Queue success event called')
      // })
      // q.on('failed', (jobId) => {
      //   t.pass('Queue failure event called')
      // })
      // // q.on('retry', (jobId) => {
      // //   t.pass('Queue retry event called')
      // // })
      // q.on('job failed', (jobId) => {
      //   console.log('job failed: ' + jobId)
      //   t.pass('Queue idle event called')
      // })
      //
      //
      // q.process((job, next) => {
      //   console.log('~~~~~~~~~~ process ~~~~~~~~~~')
      //   console.log(job.id)
      //   setTimeout(() => {
      //     console.log('~~~~~~~~~~ process finished ~~~~~~~~~~')
      //     next(null, 'Job Completed')
      //   }, 3000)
      // })
      //
      // let jobs = []
      // // console.dir(JSON.parse(JSON.stringify(q)))
      // // let ej = q.createJob()
      // // ej.id = 'ba3002c6-193f-4957-bc13-a4c3871629d7'
      // // // jobs.push(ej)
      // // for (let i = 0; i < 4; i++) {
      //   jobs.push(q.createJob({foo: 1}))
      // // }
      //
      // q.addJob(jobs).then((result) => {
      //   console.log('~~~~~~~~~~ addJob result ~~~~~~~~~~')
      //   console.dir(JSON.parse(JSON.stringify(result)))
      // }).then(() => {
      //   return q.summary()
      // }).then((d) => {
      //   console.log('~~~~~~~~~~ summary ~~~~~~~~~~')
      //   console.dir(d)
      // }).then(() => {
      //   return q.drop(4000)
      // }).then((removeResult) => {
      //   console.log('~~~~~~~~~~ removeResult ~~~~~~~~~~')
      //   console.dir(removeResult)
      // }).catch(err => testError(err, module, t))
      //
      // q.jobOptions = customjobOptions
      // t.deepEqual(q.jobOptions, customjobOptions, 'Set default job options')
    })
  })
}
<|endoftext|>


<commit_before>define(function(require, exports, module) {
    main.consumes = [
        "Panel", "settings", "ui", "watcher", "menus", "tabManager", "find",
        "fs", "panels", "fs.cache", "preferences", "c9", "tree", "commands"
    ];
    main.provides = ["navigate"];
    return main;

    function main(options, imports, register) {
        var Panel    = imports.Panel;
        var settings = imports.settings;
        var ui       = imports.ui;
        var c9       = imports.c9;
        var fs       = imports.fs;
        var fsCache  = imports["fs.cache"];
        var tabs     = imports.tabManager;
        var menus    = imports.menus;
        var watcher  = imports.watcher;
        var panels   = imports.panels;
        var find     = imports.find;
        var filetree = imports.tree;
        var prefs    = imports.preferences;
        var commands = imports.commands;

        var markup   = require("text!./navigate.xml");
        var search   = require('./search');
        var Tree     = require("ace_tree/tree");
        var ListData = require("./dataprovider");
        var basename = require("path").basename;

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

        var plugin = new Panel("Ajax.org", main.consumes, {
            index        : options.index || 200,
            caption      : "Navigate",
            elementName  : "winGoToFile",
            minWidth     : 130,
            autohide     : true,
            where        : options.where || "left"
        });
        // var emit   = plugin.getEmitter();

        var winGoToFile, txtGoToFile, tree, ldSearch;
        var lastSearch, lastPreviewed;

        var dirty         = true;
        var arrayCache    = [];
        var timer;

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

            var command = plugin.setCommand({
                name    : "navigate",
                hint    : "search for a filename, line or symbol and jump to it",
                bindKey : { mac: "Command-E|Command-P", win: "Ctrl-E|Ctrl-P" }
            });

            commands.addCommand({
                name    : "navigate_altkey",
                hint    : "search for a filename, line or symbol and jump to it",
                bindKey : {
                    mac: "Command-O",
                    win: "Ctrl-O"
                },
                group : "Panels",
                exec  : function() {
                    command.exec();
                }
            }, plugin);

            panels.on("afterAnimate", function(){
                if (panels.isActive("navigate"))
                    tree && tree.resize();
            });

            // Menus
            var mnuItem = new apf.item({ command : "navigate" });
            menus.addItemByPath("File/Open...", mnuItem, 500, plugin);
            menus.addItemByPath("Goto/Goto File...", mnuItem.cloneNode(false), 100, plugin);

            // Settings
            settings.on("read", function(){
                settings.setDefaults("user/general", [["preview-navigate", "false"]]);
            }, plugin);

            // Prefs
            prefs.add({
                "General" : {
                    "General" : {
                        "Enable Preview on Navigation" : {
                            type     : "checkbox",
                            position : 2000,
                            path     : "user/general/@preview-navigate"
                        }
                    }
                }
            }, plugin);

            // Update when the fs changes
            fs.on("afterWriteFile", function(e){
                // Only mark dirty if file didn't exist yet
                if (arrayCache.indexOf(e.path) == -1)
                    markDirty(e);
            });
            fs.on("afterUnlink",    markDirty);
            fs.on("afterRmfile",    markDirty);
            fs.on("afterRmdir",     markDirty);
            fs.on("afterCopy",      markDirty);
            fs.on("afterRename",    markDirty);
            fs.on("afterSymlink",   markDirty);

            // Or when a watcher fires
            watcher.on("delete",     markDirty);
            watcher.on("directory",  markDirty);

            // Or when the user refreshes the tree
            filetree.on("refresh", markDirty);

            // Or when we change the visibility of hidden files
            fsCache.on("setShowHidden", markDirty);

            // Pre-load file list
            updateFileCache();
        }

        function offlineHandler(e){
            // Online
            if (e.state & c9.STORAGE) {
                txtGoToFile.enable();
                //@Harutyun This doesn't work
                // tree.enable();
            }
            // Offline
            else {
                // do not close panel while typing
                if (!txtGoToFile.ace.isFocused())
                    txtGoToFile.disable();
                //@Harutyun This doesn't work
                // tree.disable();
            }
        }

        var drawn = false;
        function draw(options){
            if (drawn) return;
            drawn = true;

            // Create UI elements
            ui.insertMarkup(options.aml, markup, plugin);

            // Import CSS
            ui.insertCss(require("text!./style.css"), plugin);

            var treeParent   = plugin.getElement("navigateList");
            txtGoToFile      = plugin.getElement("txtGoToFile");
            winGoToFile      = plugin.getElement("winGoToFile");
            txtGoToFile      = plugin.getElement("txtGoToFile");

            // Create the Ace Tree
            tree      = new Tree(treeParent.$int);
            ldSearch  = new ListData(arrayCache);
            ldSearch.search = search;

            // Assign the dataprovider
            tree.setDataProvider(ldSearch);

            tree.renderer.setScrollMargin(0, 10);

            // @TODO this is probably not sufficient
            window.addEventListener("resize", function(){ tree.resize() });

            tree.textInput = txtGoToFile.ace.textInput;

            txtGoToFile.ace.commands.addCommands([
                {
                    bindKey : "ESC",
                    exec    : function(){ plugin.hide(); }
                }, {
                    bindKey : "Enter",
                    exec    : function(){ openFile(true); }
                },
            ]);
            function forwardToTree() {
                tree.execCommand(this.name);
            }
            txtGoToFile.ace.commands.addCommands([
                "centerselection",
                "goToStart",
                "goToEnd",
                "pageup",
                "gotopageup",
                "scrollup",
                "scrolldown",
                "goUp",
                "goDown",
                "selectUp",
                "selectDown",
                "selectMoreUp",
                "selectMoreDown"
            ].map(function(name) {
                var command = tree.commands.byName[name];
                return {
                    name: command.name,
                    bindKey: command.editorKey || command.bindKey,
                    exec: forwardToTree
                }
            }));

            tree.on("click", function(ev){
                var e = ev.domEvent;
                if (!e.shiftKey && !e.metaKey  && !e.ctrlKey  && !e.altKey)
                if (tree.selection.getSelectedNodes().length === 1)
                    openFile(true);
            });

            tree.selection.$wrapAround = true;

            txtGoToFile.ace.on("input", function(e) {
                var val = txtGoToFile.getValue();
                filter(val);

                if (dirty && val.length > 0 && ldSearch.loaded) {
                    dirty = false;
                    updateFileCache(true);
                }
            });

            tree.selection.on("changeSelection", function(){ previewFile(); });

            function onblur(e){
                if (!winGoToFile.visible)
                    return;

                var to = e.toElement;
                if (!to || apf.isChildOf(winGoToFile, to, true)
                  || (lastPreviewed && tabs.previewTab
                  && tabs.previewTab === lastPreviewed
                  && (apf.isChildOf(lastPreviewed.aml.relPage, to, true)
                  || lastPreviewed.aml == to))) {
                    return;
                }

                // TODO add better support for overlay panels
                setTimeout(function(){ plugin.hide() }, 10);
            }

            apf.addEventListener("movefocus", onblur);

            // Focus the input field
            setTimeout(function(){
                txtGoToFile.focus();
            }, 10);

            // Offline
            c9.on("stateChange", offlineHandler, plugin);
            offlineHandler({ state: c9.status });
        }

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

        function reloadResults(){
            if (!winGoToFile) {
                plugin.once("draw", function(){
                    reloadResults();
                });
                return;
            }

            // Wait until window is visible
            if (!winGoToFile.visible) {
                winGoToFile.on("prop.visible", function visible(e){
                    if (e.value) {
                        reloadResults();
                        winGoToFile.off("prop.visible", visible);
                    }
                });
                return;
            }

            var sel = tree.selection.getSelectedNodes();
            if (lastSearch) {
                filter(lastSearch, sel.length);
            } else {
                ldSearch.updateData(arrayCache);
            }
        }

        function markDirty(options){
            // Ignore hidden files
            var path = options && options.path || "";
            if (path && !fsCache.showHidden && path.charAt(0) == ".")
                return;

            dirty = true;
            if (panels.isActive("navigate")) {
                clearTimeout(timer);
                timer = setTimeout(function(){ updateFileCache(true); }, 2000);
            }
        }

        function updateFileCache(isDirty){
            clearTimeout(timer);

            find.getFileList({
                path    : "/",
                nocache : isDirty,
                hidden  : fsCache.showHidden,
                buffer  : true
            }, function(err, data){
                if (err)
                    return;

                arrayCache = data.trim().split("\n");
                reloadResults();
            });

            dirty = false;
        }

        /**
         * Searches through the dataset
         *
         */
        function filter(keyword, nosel){
            keyword = keyword.replace(/\*/g, "");

            if (!arrayCache.length) {
                lastSearch = keyword;
                return;
            }

            // Needed for highlighting
            ldSearch.keyword = keyword;

            var searchResults;
            if (!keyword) {
                var result = arrayCache.slice();
                // More prioritization for already open files
                tabs.getTabs().forEach(function (tab) {
                    if (!tab.path
                      || tab.document.meta.preview) return;

                    var idx = result.indexOf(tab.path);
                    if (idx > -1) {
                        result.splice(idx, 1);
                        result.unshift(tab.path);
                    }
                });
                searchResults = result;
            }
            else {
                tree.provider.setScrollTop(0);
                searchResults = search.fileSearch(arrayCache, keyword);
            }

            lastSearch = keyword;

            if (searchResults)
                ldSearch.updateData(searchResults);

            if (nosel || !searchResults.length)
                return;

            var first = -1;
            if (keyword) {
                first = 0
                // See if there are open files that match the search results
                // and the first if in the displayed results
                var openTabs = tabs.getTabs(), hash = {};
                for (var i = openTabs.length - 1; i >= 0; i--) {
                    var tab = openTabs[i];
                    if (!tab.document.meta.preview && tab.path) {
                        if (basename(tab.path).indexOf(keyword) == 0)
                            hash[tab.path] = true;
                    }
                }

                // loop over all visible items. If we find a visible item
                // that is in the `hash`, select it and return.

                var last = tree.renderer.$size.height / tree.provider.rowHeight;
                for (var i = 0; i < last; i++) {
                    if (hash[ldSearch.visibleItems[i]]) {
                        first = i;
                        break;
                    }
                }
            }
            // select the first item in the list
            tree.select(tree.provider.getNodeAtIndex(first));
        }

        function openFile(noanim){
            if (!ldSearch.loaded)
                return false;

            var nodes = tree.selection.getSelectedNodes();
            var cursor = tree.selection.getCursor();

            // Cancel Preview and Keep the tab if there's only one
            if (tabs.preview({ cancel: true, keep : nodes.length == 1 }) === true)
                return plugin.hide();

            plugin.hide();

            var fn = function(){};
            for (var i = 0, l = nodes.length; i < l; i++) {
                var path  = "/" + nodes[i].id.replace(/^[\/]+/, "");

                tabs.open({
                    path   : path,
                    noanim : l > 1,
                    active : nodes[i].id === cursor.id
                }, fn);
            }

            lastPreviewed = null;
        }

        function previewFile(noanim){
            if (!settings.getBool("user/general/@preview-navigate"))
                return;

            if (!ldSearch.loaded)
                return false;

            var node = tree.selection.getCursor();
            var value = node && node.path;
            if (!value)
                return;

            var path  = "/" + value.replace(/^[\/]+/, "");
            lastPreviewed = tabs.preview({ path: path }, function(){});
        }

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

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

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

        });
        plugin.on("show", function(e){
            txtGoToFile.focus();
            txtGoToFile.select();
        });
        plugin.on("hide", function(e){
            // Cancel Preview
            tabs.preview({ cancel: true });
        });
        plugin.on("unload", function(){
            loaded = false;
            drawn  = false;
        });

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

        /**
         * Navigation panel. Allows a user to navigate to files by searching
         * for a fuzzy string that matches the path of the file.
         * @singleton
         * @extends Panel
         **/
        /**
         * @command navigate
         */
        /**
         * Fires when the navigate panel shows
         * @event showPanelNavigate
         * @member panels
         */
        /**
         * Fires when the navigate panel hides
         * @event hidePanelNavigate
         * @member panels
         */
        plugin.freezePublicAPI({
            /**
             * @property {Object}  The tree implementation
             * @private
             */
            get tree() { return tree; }
        });

        register(null, {
            navigate: plugin
        });
    }
});<commit_msg>Fixed all tests and added debug code for navigate<commit_after>define(function(require, exports, module) {
    main.consumes = [
        "Panel", "settings", "ui", "watcher", "menus", "tabManager", "find",
        "fs", "panels", "fs.cache", "preferences", "c9", "tree", "commands"
    ];
    main.provides = ["navigate"];
    return main;

    function main(options, imports, register) {
        var Panel    = imports.Panel;
        var settings = imports.settings;
        var ui       = imports.ui;
        var c9       = imports.c9;
        var fs       = imports.fs;
        var fsCache  = imports["fs.cache"];
        var tabs     = imports.tabManager;
        var menus    = imports.menus;
        var watcher  = imports.watcher;
        var panels   = imports.panels;
        var find     = imports.find;
        var filetree = imports.tree;
        var prefs    = imports.preferences;
        var commands = imports.commands;

        var markup   = require("text!./navigate.xml");
        var search   = require('./search');
        var Tree     = require("ace_tree/tree");
        var ListData = require("./dataprovider");
        var basename = require("path").basename;

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

        var plugin = new Panel("Ajax.org", main.consumes, {
            index        : options.index || 200,
            caption      : "Navigate",
            elementName  : "winGoToFile",
            minWidth     : 130,
            autohide     : true,
            where        : options.where || "left"
        });
        // var emit   = plugin.getEmitter();

        var winGoToFile, txtGoToFile, tree, ldSearch;
        var lastSearch, lastPreviewed;

        var dirty         = true;
        var arrayCache    = [];
        var timer;

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

            var command = plugin.setCommand({
                name    : "navigate",
                hint    : "search for a filename, line or symbol and jump to it",
                bindKey : { mac: "Command-E|Command-P", win: "Ctrl-E|Ctrl-P" }
            });

            commands.addCommand({
                name    : "navigate_altkey",
                hint    : "search for a filename, line or symbol and jump to it",
                bindKey : {
                    mac: "Command-O",
                    win: "Ctrl-O"
                },
                group : "Panels",
                exec  : function() {
                    command.exec();
                }
            }, plugin);

            panels.on("afterAnimate", function(){
                if (panels.isActive("navigate"))
                    tree && tree.resize();
            });

            // Menus
            var mnuItem = new apf.item({ command : "navigate" });
            menus.addItemByPath("File/Open...", mnuItem, 500, plugin);
            menus.addItemByPath("Goto/Goto File...", mnuItem.cloneNode(false), 100, plugin);

            // Settings
            settings.on("read", function(){
                settings.setDefaults("user/general", [["preview-navigate", "false"]]);
            }, plugin);

            // Prefs
            prefs.add({
                "General" : {
                    "General" : {
                        "Enable Preview on Navigation" : {
                            type     : "checkbox",
                            position : 2000,
                            path     : "user/general/@preview-navigate"
                        }
                    }
                }
            }, plugin);

            // Update when the fs changes
            fs.on("afterWriteFile", function(e){
                // Only mark dirty if file didn't exist yet
                if (arrayCache.indexOf(e.path) == -1)
                    markDirty(e);
            });
            fs.on("afterUnlink",    markDirty);
            fs.on("afterRmfile",    markDirty);
            fs.on("afterRmdir",     markDirty);
            fs.on("afterCopy",      markDirty);
            fs.on("afterRename",    markDirty);
            fs.on("afterSymlink",   markDirty);

            // Or when a watcher fires
            watcher.on("delete",     markDirty);
            watcher.on("directory",  markDirty);

            // Or when the user refreshes the tree
            filetree.on("refresh", markDirty);

            // Or when we change the visibility of hidden files
            fsCache.on("setShowHidden", markDirty);

            // Pre-load file list
            updateFileCache();
        }

        function offlineHandler(e){
            // Online
            if (e.state & c9.STORAGE) {
                txtGoToFile.enable();
                //@Harutyun This doesn't work
                // tree.enable();
            }
            // Offline
            else {
                // do not close panel while typing
                if (!txtGoToFile.ace.isFocused())
                    txtGoToFile.disable();
                //@Harutyun This doesn't work
                // tree.disable();
            }
        }

        var drawn = false;
        function draw(options){
            if (drawn) return;
            drawn = true;

            // Create UI elements
            ui.insertMarkup(options.aml, markup, plugin);

            // Import CSS
            ui.insertCss(require("text!./style.css"), plugin);

            var treeParent   = plugin.getElement("navigateList");
            txtGoToFile      = plugin.getElement("txtGoToFile");
            winGoToFile      = plugin.getElement("winGoToFile");
            txtGoToFile      = plugin.getElement("txtGoToFile");

            // Create the Ace Tree
            tree      = new Tree(treeParent.$int);
            ldSearch  = new ListData(arrayCache);
            ldSearch.search = search;

            // Assign the dataprovider
            tree.setDataProvider(ldSearch);

            tree.renderer.setScrollMargin(0, 10);

            // @TODO this is probably not sufficient
            window.addEventListener("resize", function(){ tree.resize() });

            tree.textInput = txtGoToFile.ace.textInput;

            txtGoToFile.ace.commands.addCommands([
                {
                    bindKey : "ESC",
                    exec    : function(){ plugin.hide(); }
                }, {
                    bindKey : "Enter",
                    exec    : function(){ openFile(true); }
                },
            ]);
            function forwardToTree() {
                tree.execCommand(this.name);
            }
            txtGoToFile.ace.commands.addCommands([
                "centerselection",
                "goToStart",
                "goToEnd",
                "pageup",
                "gotopageup",
                "scrollup",
                "scrolldown",
                "goUp",
                "goDown",
                "selectUp",
                "selectDown",
                "selectMoreUp",
                "selectMoreDown"
            ].map(function(name) {
                var command = tree.commands.byName[name];
                return {
                    name: command.name,
                    bindKey: command.editorKey || command.bindKey,
                    exec: forwardToTree
                }
            }));

            tree.on("click", function(ev){
                var e = ev.domEvent;
                if (!e.shiftKey && !e.metaKey  && !e.ctrlKey  && !e.altKey)
                if (tree.selection.getSelectedNodes().length === 1)
                    openFile(true);
            });

            tree.selection.$wrapAround = true;

            txtGoToFile.ace.on("input", function(e) {
                var val = txtGoToFile.getValue();
                filter(val);

                if (dirty && val.length > 0 && ldSearch.loaded) {
                    dirty = false;
                    updateFileCache(true);
                }
            });

            tree.selection.on("changeSelection", function(){ previewFile(); });

            function onblur(e){
                if (!winGoToFile.visible)
                    return;

                var to = e.toElement;
                if (!to || apf.isChildOf(winGoToFile, to, true)
                  || (lastPreviewed && tabs.previewTab
                  && tabs.previewTab === lastPreviewed
                  && (apf.isChildOf(lastPreviewed.aml.relPage, to, true)
                  || lastPreviewed.aml == to))) {
                    return;
                }

                // TODO add better support for overlay panels
                setTimeout(function(){ plugin.hide() }, 10);
            }

            apf.addEventListener("movefocus", onblur);

            // Focus the input field
            setTimeout(function(){
                txtGoToFile.focus();
            }, 10);

            // Offline
            c9.on("stateChange", offlineHandler, plugin);
            offlineHandler({ state: c9.status });
        }

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

        function reloadResults(){
            if (!winGoToFile) {
                plugin.once("draw", function(){
                    reloadResults();
                });
                return;
            }

            // Wait until window is visible
            if (!winGoToFile.visible) {
                winGoToFile.on("prop.visible", function visible(e){
                    if (e.value) {
                        reloadResults();
                        winGoToFile.off("prop.visible", visible);
                    }
                });
                return;
            }

            var sel = tree.selection.getSelectedNodes();
            if (lastSearch) {
                filter(lastSearch, sel.length);
            } else {
                ldSearch.updateData(arrayCache);
            }
        }

        function markDirty(options){
            // Ignore hidden files
            var path = options && options.path || "";
            if (path && !fsCache.showHidden && path.charAt(0) == ".")
                return;

            dirty = true;
            if (panels.isActive("navigate")) {
                clearTimeout(timer);
                timer = setTimeout(function(){ updateFileCache(true); }, 2000);
            }
        }

        function updateFileCache(isDirty){
            clearTimeout(timer);

            find.getFileList({
                path    : "/",
                nocache : isDirty,
                hidden  : fsCache.showHidden,
                buffer  : true
            }, function(err, data){
                if (err)
                    return;

                arrayCache = data.trim().split("\n");

                // Test for double results from server:
                var found = {};
                arrayCache.forEach(function(x){
                    if (found[x]) {
                        alert("Found duplicate navigate result");
                        debugger;
                    }
                    found[x] = true;
                });

                reloadResults();
            });

            dirty = false;
        }

        /**
         * Searches through the dataset
         *
         */
        function filter(keyword, nosel){
            keyword = keyword.replace(/\*/g, "");

            if (!arrayCache.length) {
                lastSearch = keyword;
                return;
            }

            // Needed for highlighting
            ldSearch.keyword = keyword;

            var searchResults;
            if (!keyword) {
                var result = arrayCache.slice();
                // More prioritization for already open files
                tabs.getTabs().forEach(function (tab) {
                    if (!tab.path
                      || tab.document.meta.preview) return;

                    var idx = result.indexOf(tab.path);
                    if (idx > -1) {
                        result.splice(idx, 1);
                        result.unshift(tab.path);
                    }
                });
                searchResults = result;
            }
            else {
                tree.provider.setScrollTop(0);
                searchResults = search.fileSearch(arrayCache, keyword);
            }

            lastSearch = keyword;

            if (searchResults)
                ldSearch.updateData(searchResults);

            if (nosel || !searchResults.length)
                return;

            var first = -1;
            if (keyword) {
                first = 0
                // See if there are open files that match the search results
                // and the first if in the displayed results
                var openTabs = tabs.getTabs(), hash = {};
                for (var i = openTabs.length - 1; i >= 0; i--) {
                    var tab = openTabs[i];
                    if (!tab.document.meta.preview && tab.path) {
                        if (basename(tab.path).indexOf(keyword) == 0)
                            hash[tab.path] = true;
                    }
                }

                // loop over all visible items. If we find a visible item
                // that is in the `hash`, select it and return.

                var last = tree.renderer.$size.height / tree.provider.rowHeight;
                for (var i = 0; i < last; i++) {
                    if (hash[ldSearch.visibleItems[i]]) {
                        first = i;
                        break;
                    }
                }
            }
            // select the first item in the list
            tree.select(tree.provider.getNodeAtIndex(first));
        }

        function openFile(noanim){
            if (!ldSearch.loaded)
                return false;

            var nodes = tree.selection.getSelectedNodes();
            var cursor = tree.selection.getCursor();

            // Cancel Preview and Keep the tab if there's only one
            if (tabs.preview({ cancel: true, keep : nodes.length == 1 }) === true)
                return plugin.hide();

            plugin.hide();

            var fn = function(){};
            for (var i = 0, l = nodes.length; i < l; i++) {
                var path  = "/" + nodes[i].id.replace(/^[\/]+/, "");

                tabs.open({
                    path   : path,
                    noanim : l > 1,
                    active : nodes[i].id === cursor.id
                }, fn);
            }

            lastPreviewed = null;
        }

        function previewFile(noanim){
            if (!settings.getBool("user/general/@preview-navigate"))
                return;

            if (!ldSearch.loaded)
                return false;

            var node = tree.selection.getCursor();
            var value = node && node.path;
            if (!value)
                return;

            var path  = "/" + value.replace(/^[\/]+/, "");
            lastPreviewed = tabs.preview({ path: path }, function(){});
        }

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

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

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

        });
        plugin.on("show", function(e){
            txtGoToFile.focus();
            txtGoToFile.select();
        });
        plugin.on("hide", function(e){
            // Cancel Preview
            tabs.preview({ cancel: true });
        });
        plugin.on("unload", function(){
            loaded = false;
            drawn  = false;
        });

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

        /**
         * Navigation panel. Allows a user to navigate to files by searching
         * for a fuzzy string that matches the path of the file.
         * @singleton
         * @extends Panel
         **/
        /**
         * @command navigate
         */
        /**
         * Fires when the navigate panel shows
         * @event showPanelNavigate
         * @member panels
         */
        /**
         * Fires when the navigate panel hides
         * @event hidePanelNavigate
         * @member panels
         */
        plugin.freezePublicAPI({
            /**
             * @property {Object}  The tree implementation
             * @private
             */
            get tree() { return tree; }
        });

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


<commit_before>// test article api:

var
    _ = require('lodash'),
    async = require('async'),
    should = require('should');

var remote = require('./_test');

var log = console.log;

describe('#pages', function () {

    before(remote.setup);

    describe('#api', function () {

        it('should get empty pages', function (done) {
            remote.get(remote.guest, '/api/pages', null, function (r) {
                r.pages.should.be.an.Array.and.have.length(0);
                done();
            });
        });

        it('create page by editor', function (done) {
            remote.post(remote.editor, '/api/pages', {
                alias: 'by-editor',
                name: 'by editor',
                content: '...'
            }, function (r) {
                r.error.should.equal('permission:denied');
                r.message.should.be.ok;
                done();
            });
        });

        it('create duplicate pages by admin', function (done) {
            // create page:
            remote.post(remote.admin, '/api/pages', {
                alias: 'Duplicate',
                name: 'test duplicate',
                draft: 'true',
                content: 'first...'
            }, function (r) {
                r.alias.should.equal('duplicate');
                r.draft.should.be.ok;
                remote.post(remote.admin, '/api/pages', {
                    alias: 'duplicate',
                    name: 'second one',
                    content: 'second...'
                },function (r2) {
                    r2.error.should.equal('parameter:invalid');
                    done();
                });
            });
        });

        it('create and update page by admin', function (done) {
            // create page:
            remote.post(remote.admin, '/api/pages', {
                alias: ' Test ',
                name: 'Test Page   ',
                tags: ' aaa,\n BBB,  \t ccc,CcC',
                content: '  Long content...\n\n '
            }, function (r) {
                r.alias.should.equal('test');
                r.draft.should.not.be.ok;
                r.name.should.equal('Test Page');
                r.tags.should.equal('aaa,BBB,ccc');
                r.content.should.equal('Long content...');
                // update name:
                remote.post(remote.admin, '/api/pages/' + r.id, {
                    name: ' Name Changed '
                }, function (r2) {
                    r2.name.should.equal('Name Changed');
                    // update text:
                    remote.post(remote.admin, '/api/pages/' + r.id, {
                        content: ' content changed.\t '
                    }, function (r3) {
                        r3.content.should.equal('content changed.');
                        // update alias:
                        remote.post(remote.admin, '/api/pages/' + r.id, {
                            alias: 'Test-2',
                            tags: ' A, B, C, c, D, '
                        }, function (r4) {
                            r4.alias.should.equal('test-2');
                            r4.tags.should.equal('A,B,C,D');
                            r4.content.should.equal(r3.content);
                            done();
                        });
                    });
                });
            });
        });

        it('create and update alias but duplicate by admin', function (done) {
            // create page:
            async.series([
                function (callback) {
                    remote.post(remote.admin, '/api/pages', {
                        alias: 'abc',
                        name: 'abc',
                        content: 'abc...'
                    }, function (r) {
                        callback(null, r);
                    });
                },
                function (callback) {
                    remote.post(remote.admin, '/api/pages', {
                        alias: 'xyz',
                        name: 'xyz',
                        content: 'xyz...'
                    }, function (r) {
                        callback(null, r);
                    });
                }
            ], function (err, results) {
                if (err) {
                    return done(err);
                }
                // try update alias 'abc' to 'xyz':
                var id = results[0].id;
                remote.post(remote.admin, '/api/pages/' + id, {
                    alias: 'xyz'
                }, function (r) {
                    r.error.should.equal('parameter:invalid');
                    r.data.should.equal('alias');
                    done();
                });
            });
        });

        it('create page with wrong parameter by admin', function (done) {
            var create_missing_params = function (pname) {
                var r = {
                    name: 'Test',
                    alias: 'alias-x',
                    content: 'a long content...'
                };
                delete r[pname];
                return r;
            };
            var tests = _.map(['name', 'alias', 'content'], function (param) {
                return function (callback) {
                    remote.post(remote.admin, '/api/pages', create_missing_params(param), function (r) {
                        r.error.should.equal('parameter:invalid');
                        r.data.should.equal(param);
                        r.message.should.be.ok;
                        callback(null);
                    });
                };
            });
            async.series(tests, function (err, results) {
                done();
            });
        });
    });
});
<commit_msg>remove unused test<commit_after><|endoftext|>


<commit_before>'use strict';

angular.module('emuwebApp')
	.service('DragnDropService', function DragnDropService($q, $rootScope, appStateService, modalService, DataService, Validationservice, ConfigProviderService, DragnDropDataService, Iohandlerservice, viewState, Soundhandlerservice, Binarydatamaniphelper, browserDetector, Wavparserservice, Textgridparserservice, loadedMetaDataService) {
		// shared service object
		var sServObj = {};
		sServObj.drandropBundles = [];
		sServObj.bundleList = [];
		sServObj.sessionName = 'File(s)';
		sServObj.maxDroppedBundles = 10;

		///////////////////////////////
		// public api

		///////////////////
		// drag n drop data
		sServObj.setData = function (bundles) {
		    var prom = [];
		    var count = 0;

			angular.forEach(bundles, function (bundle, i) {
			    sServObj.setDragnDropData(bundle[0], i, 'wav', bundle[1]);
			    sServObj.setDragnDropData(bundle[0], i, 'annotation', bundle[2]);
			    count = i;
			});
			if(count<=sServObj.maxDroppedBundles) {
				sServObj.convertDragnDropData(sServObj.drandropBundles, 0).then( function() {
					loadedMetaDataService.setBundleList(sServObj.bundleList);
					loadedMetaDataService.setCurBndlName(sServObj.bundleList[DragnDropDataService.sessionDefault]);
					loadedMetaDataService.setDemoDbName(sServObj.bundleList[DragnDropDataService.sessionDefault]);
					sServObj.handleLocalFiles();
					return true;
				});
			}
			else {
			    return false;
			}
		};

		sServObj.resetToInitState = function () {
			sServObj.drandropBundles = [];
			sServObj.bundleList = [];
			sServObj.sessionName = 'File(s)';
			sServObj.maxDroppedBundles = 10;
		};

		/**
		 * setter sServObj.drandropBundles
		 */
		sServObj.setDragnDropData = function (bundle, i, type, data) {
			DragnDropDataService.setDefaultSession(i);
			if(sServObj.drandropBundles[i] === undefined) {
			    sServObj.drandropBundles[i] = {};
			    DragnDropDataService.convertedBundles[i] = {};
			    DragnDropDataService.convertedBundles[i].name = bundle;
			    sServObj.bundleList.push({
			        name: bundle,
			        session: sServObj.sessionName
			    });

			}
			if(type === 'wav') {
				sServObj.drandropBundles[i].wav = data;
			}
			else if(type === 'annotation') {
				sServObj.drandropBundles[i].annotation = data;
			}
		};

		/**
		 * getter sServObj.drandropBundles
		 */
		sServObj.getDragnDropData = function (bundle, type) {
			if(type === 'wav') {
			    return sServObj.drandropBundles[bundle].wav;
			}
			else if(type === 'annotation') {
			    return sServObj.drandropBundles[bundle].annotation;
			}
			else {
			    return false;
			}
		};

		sServObj.generateDrop = function (data) {
			var objURL;
		    if (typeof URL !== 'object' && typeof webkitURL !== 'undefined') {
		        objURL = webkitURL.createObjectURL(sServObj.getBlob(data));
		    } else {
		        objURL = URL.createObjectURL(sServObj.getBlob(data));
		    }
		    return objURL;
		};

		/**
		 *
		 */
		sServObj.getBlob = function(data){
		    var blob;
		    try {
		        blob = new Blob([data], {type: 'text/plain'});
		    } catch (e) { // Backwards-compatibility
		        window.BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder;
		        blob = new BlobBuilder();
		        blob.append(data);
		        blob = blob.getBlob();
		    }
		    return blob;
		};

		sServObj.convertDragnDropData = function (bundles, i) {
		    var defer = $q.defer();
		    var data = sServObj.drandropBundles[i];
		    var reader = new FileReader();
		    var reader2 = new FileReader();
		    var res;
		    if(bundles.length>i) {
		        if(data.wav!==undefined) {
		            reader.readAsArrayBuffer(data.wav);
		            reader.onloadend = function (evt) {
						if (evt.target.readyState == FileReader.DONE) {
							if (browserDetector.isBrowser.Firefox()) {
								res = evt.target.result;
							} else {
								res = evt.currentTarget.result;
							}
							Wavparserservice.parseWavArrBuf(res).then(function (wavJSO) {
								if(DragnDropDataService.convertedBundles[i] === undefined) {
									DragnDropDataService.convertedBundles[i] = {};
								}
								DragnDropDataService.convertedBundles[i].mediaFile = {};
								Soundhandlerservice.wavJSO = wavJSO;
								DragnDropDataService.convertedBundles[i].mediaFile.data = Binarydatamaniphelper.arrayBufferToBase64(wavJSO.origArrBuf);
								DragnDropDataService.convertedBundles[i].mediaFile.encoding = 'BASE64';
								DragnDropDataService.convertedBundles[i].ssffFiles =  [];
								var bundle = data.wav.name.substr(0, data.wav.name.lastIndexOf('.'));
								if(data.annotation===undefined) {
									DragnDropDataService.convertedBundles[i].annotation = {
										levels: [],
										links: [],
										sampleRate: wavJSO.SampleRate,
										annotates: bundle,
										name: bundle
									};
									sServObj.convertDragnDropData(bundles, i+1).then( function () {
										defer.resolve();
									});
								}
								else {
								    if(data.annotation.type === 'textgrid') {
										reader2.readAsText(data.annotation.file);
										reader2.onloadend = function (evt) {
											if (evt.target.readyState == FileReader.DONE) {
												Textgridparserservice.asyncParseTextGrid(evt.currentTarget.result, data.wav.name, bundle).then(function (parseMess) {
													DragnDropDataService.convertedBundles[i].annotation =  parseMess;
													sServObj.convertDragnDropData(bundles, i+1).then( function () {
														defer.resolve();
													});
												});
											}
										};
								    }
								    else if(data.annotation.type === 'annotation') {
										reader2.readAsText(data.annotation.file);
										reader2.onloadend = function (evt) {
											if (evt.target.readyState == FileReader.DONE) {
												DragnDropDataService.convertedBundles[i].annotation = angular.fromJson(evt.currentTarget.result);
												sServObj.convertDragnDropData(bundles, i+1).then( function () {
													defer.resolve();
												});
											}
										};
								    }
								}
							});
						}
					};
				}
            }
            else {
                defer.resolve();
                return defer.promise;
            }
			return defer.promise;
		};

		/**
		 * handling local file drops after loading them
		 */
        sServObj.handleLocalFiles = function () {
            var validRes;
            var wav = DragnDropDataService.convertedBundles[DragnDropDataService.sessionDefault].mediaFile.data;
            var ab = Binarydatamaniphelper.base64ToArrayBuffer(wav);
						var annotation = { levels: [], links: []};
						if(DragnDropDataService.convertedBundles[DragnDropDataService.sessionDefault].annotation !== undefined) {
							annotation = DragnDropDataService.convertedBundles[DragnDropDataService.sessionDefault].annotation;
						}
            viewState.showDropZone = false;
            viewState.setState('loadingSaving');
            // reset history
            viewState.somethingInProgress = true;
            viewState.somethingInProgressTxt = 'Loading local File: ' + wav.name;
            Iohandlerservice.httpGetPath('configFiles/standalone_emuwebappConfig.json').then(function (resp) {
                // first element of perspectives is default perspective
                viewState.curPerspectiveIdx = 0;
                ConfigProviderService.setVals(resp.data.EMUwebAppConfig);
                delete resp.data.EMUwebAppConfig; // delete to avoid duplicate
                validRes = Validationservice.validateJSO('emuwebappConfigSchema', ConfigProviderService.vals);
                if (validRes === true) {
                    ConfigProviderService.curDbConfig = resp.data;
                    viewState.somethingInProgressTxt = 'Parsing WAV file...';
										Wavparserservice.parseWavArrBuf(ab).then(function (messWavParser) {
											var wavJSO = messWavParser;
											viewState.curViewPort.sS = 0;
											viewState.curViewPort.eS = wavJSO.Data.length;
											viewState.curViewPort.selectS = -1;
											viewState.curViewPort.selectE = -1;
											viewState.curClickSegments = [];
											viewState.curClickLevelName = undefined;
											viewState.curClickLevelType = undefined;
											loadedMetaDataService.setCurBndl(DragnDropDataService.convertedBundles[DragnDropDataService.sessionDefault]);
											viewState.resetSelect();
											viewState.curPerspectiveIdx = 0;
											DataService.setLevelData(annotation.levels);
											var lNames = [];
											var levelDefs = [];
											annotation.levels.forEach(function (l) {
												if(l.type === 'SEGMENT' || l.type === 'EVENT') {
													lNames.push(l.name);
													levelDefs.push({
														'name': l.name,
														'type': l.type,
														'attributeDefinitions': {
															'name': l.name,
															'type': 'string'
														}
													});
												}
											});

											// set level defs
											ConfigProviderService.curDbConfig.levelDefinitions = levelDefs;
											viewState.setCurLevelAttrDefs(ConfigProviderService.curDbConfig.levelDefinitions);
											ConfigProviderService.setPerspectivesOrder(viewState.curPerspectiveIdx, lNames);
											//ConfigProviderService.vals.perspectives[viewState.curPerspectiveIdx].levelCanvases.order = lNames;
											Soundhandlerservice.wavJSO = wavJSO;

											// set all ssff files
											viewState.somethingInProgressTxt = 'Parsing SSFF files...';
											var validRes = Validationservice.validateJSO('annotationFileSchema', annotation);
											if (validRes === true) {
												DataService.setLinkData(annotation.links);
												viewState.setState('labeling');
												viewState.somethingInProgress = false;
												viewState.somethingInProgressTxt = 'Done!';
											} else {
												modalService.open('views/error.html', 'Error validating annotation file: ' + JSON.stringify(validRes, null, 4)).then(function () {
													appStateService.resetToInitState();
													sServObj.resetToInitState();
												});
											}
									}, function (errMess) {
											modalService.open('views/error.html', 'Error parsing wav file: ' + errMess).then(function () {
												appStateService.resetToInitState();
												sServObj.resetToInitState();
											});
										});

                }

            });
            viewState.somethingInProgress = false;
        };

		return sServObj;
	});
<commit_msg>Fixes #129 show hierarchy button when dropping annot son<commit_after>'use strict';

angular.module('emuwebApp')
	.service('DragnDropService', function DragnDropService($q, $rootScope, appStateService, modalService, DataService, Validationservice, ConfigProviderService, DragnDropDataService, Iohandlerservice, viewState, Soundhandlerservice, Binarydatamaniphelper, browserDetector, Wavparserservice, Textgridparserservice, loadedMetaDataService) {
		// shared service object
		var sServObj = {};
		sServObj.drandropBundles = [];
		sServObj.bundleList = [];
		sServObj.sessionName = 'File(s)';
		sServObj.maxDroppedBundles = 10;

		///////////////////////////////
		// public api

		///////////////////
		// drag n drop data
		sServObj.setData = function (bundles) {
		    var prom = [];
		    var count = 0;

			angular.forEach(bundles, function (bundle, i) {
			    sServObj.setDragnDropData(bundle[0], i, 'wav', bundle[1]);
			    sServObj.setDragnDropData(bundle[0], i, 'annotation', bundle[2]);
			    count = i;
			});
			if(count<=sServObj.maxDroppedBundles) {
				sServObj.convertDragnDropData(sServObj.drandropBundles, 0).then( function() {
					loadedMetaDataService.setBundleList(sServObj.bundleList);
					loadedMetaDataService.setCurBndlName(sServObj.bundleList[DragnDropDataService.sessionDefault]);
					loadedMetaDataService.setDemoDbName(sServObj.bundleList[DragnDropDataService.sessionDefault]);
					sServObj.handleLocalFiles();
					return true;
				});
			}
			else {
			    return false;
			}
		};

		sServObj.resetToInitState = function () {
			sServObj.drandropBundles = [];
			sServObj.bundleList = [];
			sServObj.sessionName = 'File(s)';
			sServObj.maxDroppedBundles = 10;
		};

		/**
		 * setter sServObj.drandropBundles
		 */
		sServObj.setDragnDropData = function (bundle, i, type, data) {
			DragnDropDataService.setDefaultSession(i);
			if(sServObj.drandropBundles[i] === undefined) {
			    sServObj.drandropBundles[i] = {};
			    DragnDropDataService.convertedBundles[i] = {};
			    DragnDropDataService.convertedBundles[i].name = bundle;
			    sServObj.bundleList.push({
			        name: bundle,
			        session: sServObj.sessionName
			    });

			}
			if(type === 'wav') {
				sServObj.drandropBundles[i].wav = data;
			}
			else if(type === 'annotation') {
				sServObj.drandropBundles[i].annotation = data;
			}
		};

		/**
		 * getter sServObj.drandropBundles
		 */
		sServObj.getDragnDropData = function (bundle, type) {
			if(type === 'wav') {
			    return sServObj.drandropBundles[bundle].wav;
			}
			else if(type === 'annotation') {
			    return sServObj.drandropBundles[bundle].annotation;
			}
			else {
			    return false;
			}
		};

		sServObj.generateDrop = function (data) {
			var objURL;
		    if (typeof URL !== 'object' && typeof webkitURL !== 'undefined') {
		        objURL = webkitURL.createObjectURL(sServObj.getBlob(data));
		    } else {
		        objURL = URL.createObjectURL(sServObj.getBlob(data));
		    }
		    return objURL;
		};

		/**
		 *
		 */
		sServObj.getBlob = function(data){
		    var blob;
		    try {
		        blob = new Blob([data], {type: 'text/plain'});
		    } catch (e) { // Backwards-compatibility
		        window.BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder;
		        blob = new BlobBuilder();
		        blob.append(data);
		        blob = blob.getBlob();
		    }
		    return blob;
		};

		sServObj.convertDragnDropData = function (bundles, i) {
		    var defer = $q.defer();
		    var data = sServObj.drandropBundles[i];
		    var reader = new FileReader();
		    var reader2 = new FileReader();
		    var res;
		    if(bundles.length>i) {
		        if(data.wav!==undefined) {
		            reader.readAsArrayBuffer(data.wav);
		            reader.onloadend = function (evt) {
						if (evt.target.readyState == FileReader.DONE) {
							if (browserDetector.isBrowser.Firefox()) {
								res = evt.target.result;
							} else {
								res = evt.currentTarget.result;
							}
							Wavparserservice.parseWavArrBuf(res).then(function (wavJSO) {
								if(DragnDropDataService.convertedBundles[i] === undefined) {
									DragnDropDataService.convertedBundles[i] = {};
								}
								DragnDropDataService.convertedBundles[i].mediaFile = {};
								Soundhandlerservice.wavJSO = wavJSO;
								DragnDropDataService.convertedBundles[i].mediaFile.data = Binarydatamaniphelper.arrayBufferToBase64(wavJSO.origArrBuf);
								DragnDropDataService.convertedBundles[i].mediaFile.encoding = 'BASE64';
								DragnDropDataService.convertedBundles[i].ssffFiles =  [];
								var bundle = data.wav.name.substr(0, data.wav.name.lastIndexOf('.'));
								if(data.annotation===undefined) {
									DragnDropDataService.convertedBundles[i].annotation = {
										levels: [],
										links: [],
										sampleRate: wavJSO.SampleRate,
										annotates: bundle,
										name: bundle
									};
									sServObj.convertDragnDropData(bundles, i+1).then( function () {
										defer.resolve();
									});
								}
								else {
								    if(data.annotation.type === 'textgrid') {
										reader2.readAsText(data.annotation.file);
										reader2.onloadend = function (evt) {
											if (evt.target.readyState == FileReader.DONE) {
												Textgridparserservice.asyncParseTextGrid(evt.currentTarget.result, data.wav.name, bundle).then(function (parseMess) {
													DragnDropDataService.convertedBundles[i].annotation =  parseMess;
													sServObj.convertDragnDropData(bundles, i+1).then( function () {
														defer.resolve();
													});
												});
											}
										};
								    }
								    else if(data.annotation.type === 'annotation') {
										ConfigProviderService.vals.activeButtons.showHierarchy = true;
										reader2.readAsText(data.annotation.file);
										reader2.onloadend = function (evt) {
											if (evt.target.readyState == FileReader.DONE) {
												DragnDropDataService.convertedBundles[i].annotation = angular.fromJson(evt.currentTarget.result);
												sServObj.convertDragnDropData(bundles, i+1).then( function () {
													defer.resolve();
												});
											}
										};
								    }
								}
							});
						}
					};
				}
            }
            else {
                defer.resolve();
                return defer.promise;
            }
			return defer.promise;
		};

		/**
		 * handling local file drops after loading them
		 */
        sServObj.handleLocalFiles = function () {
            var validRes;
            var wav = DragnDropDataService.convertedBundles[DragnDropDataService.sessionDefault].mediaFile.data;
            var ab = Binarydatamaniphelper.base64ToArrayBuffer(wav);
						var annotation = { levels: [], links: []};
						if(DragnDropDataService.convertedBundles[DragnDropDataService.sessionDefault].annotation !== undefined) {
							annotation = DragnDropDataService.convertedBundles[DragnDropDataService.sessionDefault].annotation;
						}
            viewState.showDropZone = false;
            viewState.setState('loadingSaving');
            // reset history
            viewState.somethingInProgress = true;
            viewState.somethingInProgressTxt = 'Loading local File: ' + wav.name;
            Iohandlerservice.httpGetPath('configFiles/standalone_emuwebappConfig.json').then(function (resp) {
                // first element of perspectives is default perspective
                viewState.curPerspectiveIdx = 0;
                ConfigProviderService.setVals(resp.data.EMUwebAppConfig);
                delete resp.data.EMUwebAppConfig; // delete to avoid duplicate
                validRes = Validationservice.validateJSO('emuwebappConfigSchema', ConfigProviderService.vals);
                if (validRes === true) {
                    ConfigProviderService.curDbConfig = resp.data;
                    viewState.somethingInProgressTxt = 'Parsing WAV file...';
										Wavparserservice.parseWavArrBuf(ab).then(function (messWavParser) {
											var wavJSO = messWavParser;
											viewState.curViewPort.sS = 0;
											viewState.curViewPort.eS = wavJSO.Data.length;
											viewState.curViewPort.selectS = -1;
											viewState.curViewPort.selectE = -1;
											viewState.curClickSegments = [];
											viewState.curClickLevelName = undefined;
											viewState.curClickLevelType = undefined;
											loadedMetaDataService.setCurBndl(DragnDropDataService.convertedBundles[DragnDropDataService.sessionDefault]);
											viewState.resetSelect();
											viewState.curPerspectiveIdx = 0;
											DataService.setLevelData(annotation.levels);
											var lNames = [];
											var levelDefs = [];
											annotation.levels.forEach(function (l) {
												if(l.type === 'SEGMENT' || l.type === 'EVENT') {
													lNames.push(l.name);
													levelDefs.push({
														'name': l.name,
														'type': l.type,
														'attributeDefinitions': {
															'name': l.name,
															'type': 'string'
														}
													});
												}
											});

											// set level defs
											ConfigProviderService.curDbConfig.levelDefinitions = levelDefs;
											viewState.setCurLevelAttrDefs(ConfigProviderService.curDbConfig.levelDefinitions);
											ConfigProviderService.setPerspectivesOrder(viewState.curPerspectiveIdx, lNames);
											//ConfigProviderService.vals.perspectives[viewState.curPerspectiveIdx].levelCanvases.order = lNames;
											Soundhandlerservice.wavJSO = wavJSO;

											// set all ssff files
											viewState.somethingInProgressTxt = 'Parsing SSFF files...';
											var validRes = Validationservice.validateJSO('annotationFileSchema', annotation);
											if (validRes === true) {
												DataService.setLinkData(annotation.links);
												viewState.setState('labeling');
												viewState.somethingInProgress = false;
												viewState.somethingInProgressTxt = 'Done!';
											} else {
												modalService.open('views/error.html', 'Error validating annotation file: ' + JSON.stringify(validRes, null, 4)).then(function () {
													appStateService.resetToInitState();
													sServObj.resetToInitState();
												});
											}
									}, function (errMess) {
											modalService.open('views/error.html', 'Error parsing wav file: ' + errMess).then(function () {
												appStateService.resetToInitState();
												sServObj.resetToInitState();
											});
										});

                }

            });
            viewState.somethingInProgress = false;
        };

		return sServObj;
	});
<|endoftext|>


<commit_before>import PublicPath from '/PublicPath'
import styles from './style.css'

export default function Link({ title, to, active }) {
  return (
    <PublicPath.Consumer>
      { publicPath => <a href={`${publicPath}${to.slice(1)}`} onClick={onClick} className={active && styles.active}>{title} }
    </PublicPath.Consumer>
  )

  function onClick(e) {
    e.preventDefault()
    window.history.pushState(null, title, e.currentTarget.href)
  }
}
<commit_msg>fixed a react warning involving a boolean as classname<commit_after>import PublicPath from '/PublicPath'
import styles from './style.css'

export default function Link({ title, to, active }) {
  return (
    <PublicPath.Consumer>
      { publicPath => <a href={`${publicPath}${to.slice(1)}`} onClick={onClick} className={active ? styles.active : ''}>{title} }
    </PublicPath.Consumer>
  )

  function onClick(e) {
    e.preventDefault()
    window.history.pushState(null, title, e.currentTarget.href)
  }
}
<|endoftext|>


<commit_before>(function () {
    'use strict';

    angular
        .module('promort.viewer.directives')
        .directive('viewerNavigationPanel', viewerNavigationPanel)
        .directive('simpleViewer', simpleViewer)
        .directive('annotationsViewer', annotationsViewer);

    function viewerNavigationPanel() {
        var directive = {
            replace: true,
            restrict: 'E',
            templateUrl: '/static/templates/viewer/navigation_panel.html'
        };
        return directive;
    }

    function simpleViewer() {
        var directive = {
            replace: true,
            controller: 'SimpleViewerController',
            controllerAs: 'svc',
            restrict: 'E',
            templateUrl: '/static/templates/viewer/simple_viewer.html',
            link: function(scope, element, attrs) {
                function setViewerHeight() {
                    // set viewer's height to maximize page's vertical space
                    var used_v_space = $('#index_navbar').height() + $('#qc_header').height();
                    var $vcont = $('#viewer_container');
                    var bottom_border = parseInt($vcont.css('marginBottom')) +
                            parseInt($vcont.css('marginTop')) +
                            parseInt($vcont.css('paddingTop')) +
                            parseInt($vcont.css('paddingBottom')) + 50;
                    console.log(bottom_border);

                    var available_v_space = $(window).height() - (used_v_space + bottom_border);
                    var $qfc = $('#qc_form_container');
                    if (available_v_space < $qfc.height()) {
                        available_v_space = $qfc.height();
                    }

                    $('#simple_viewer').height(available_v_space);
                }

                setViewerHeight();
                $(window).resize(setViewerHeight);
                $('#goodQuality').click(setViewerHeight);
                $('#badQuality').click(setViewerHeight);

                scope.$on('viewer.controller_initialized', function() {
                    var viewer_config = {
                        'showNavigator': true,
                        'showFullPageControl': false
                    };

                    var ome_seadragon_viewer = new ViewerController(
                        'simple_viewer',
                        scope.svc.getStaticFilesURL(),
                        scope.svc.getDZIURL(),
                        viewer_config
                    );
                    ome_seadragon_viewer.buildViewer();

                    ome_seadragon_viewer.viewer.addHandler('open', function() {
                        ome_seadragon_viewer.setMinDZILevel(8);
                    });

                    var scalebar_config = {
                        'xOffset': 10,
                        'yOffset': 10,
                        'barThickness': 5,
                        'color': '#777',
                        'fontColor': '#000',
                        'backgroundColor': 'rgba(255, 255, 255, 0.5)'
                    };
                    ome_seadragon_viewer.enableScalebar(
                        scope.svc.getSlideMicronsPerPixel(), scalebar_config
                    );
                });
            }
        };
        return directive;
    }

    function annotationsViewer() {
        var directive = {
            replace: true,
            controller: 'AnnotationsViewerController',
            controllerAs: 'avc',
            restrict: 'E',
            templateUrl: '/static/templates/viewer/rois_viewer.html',
            link: function(scope, element, attrs) {
                scope.$on('viewer.controller_initialized', function() {
                    console.log('ome_seadragon viewer with annotations - INITIALIZING');

                    var viewer_config = {
                        'showNavigator': true,
                        'showFullPageControl': false,
                        'animationTime': 0.01
                    };
                    var ome_seadragon_viewer = new ViewerController(
                        'viewer',
                        scope.avc.getStaticFilesURL(),
                        scope.avc.getDZIURL(),
                        viewer_config
                    );
                    ome_seadragon_viewer.buildViewer();

                    ome_seadragon_viewer.viewer.addHandler('open', function() {
                        ome_seadragon_viewer.setMinDZILevel(8);

                        var annotations_canvas = new AnnotationsController('rois_canvas');
                        annotations_canvas.buildAnnotationsCanvas(ome_seadragon_viewer);
                        ome_seadragon_viewer.addAnnotationsController(annotations_canvas, true);

                        var tools_manager = new AnnotationsEventsController(annotations_canvas);
                        // initialize polygon, freehand drawing and measuring tools
                        var shape_config = {'fill_alpha': 0.01, 'stroke_width': 40};
                        tools_manager.initializePolygonDrawingTool(shape_config);
                        tools_manager.initializeFreehandDrawingTool(shape_config);
                        tools_manager.initializeMeasuringTool();

                        console.log('Registering components');
                        scope.avc.registerComponents(ome_seadragon_viewer,
                            annotations_canvas, tools_manager);
                    });

                    var scalebar_config = {
                        'xOffset': 10,
                        'yOffset': 10,
                        'barThickness': 5,
                        'color': '#777',
                        'fontColor': '#000',
                        'backgroundColor': 'rgba(255, 255, 255, 0.5)'
                    };
                    ome_seadragon_viewer.enableScalebar(
                        scope.avc.getSlideMicronsPerPixel(), scalebar_config
                    );
                });
            }
        };
        return directive;
    }
})();<commit_msg>bug fix<commit_after>(function () {
    'use strict';

    angular
        .module('promort.viewer.directives')
        .directive('viewerNavigationPanel', viewerNavigationPanel)
        .directive('simpleViewer', simpleViewer)
        .directive('annotationsViewer', annotationsViewer);

    function viewerNavigationPanel() {
        var directive = {
            replace: true,
            restrict: 'E',
            templateUrl: '/static/templates/viewer/navigation_panel.html'
        };
        return directive;
    }

    function simpleViewer() {
        var directive = {
            replace: true,
            controller: 'SimpleViewerController',
            controllerAs: 'svc',
            restrict: 'E',
            templateUrl: '/static/templates/viewer/simple_viewer.html',
            link: function(scope, element, attrs) {
                function setViewerHeight() {
                    // set viewer's height to maximize page's vertical space
                    var used_v_space = $('#index_navbar').height() + $('#qc_header').height();
                    var $vcont = $('#viewer_container');
                    var bottom_border = parseInt($vcont.css('marginBottom')) +
                            parseInt($vcont.css('marginTop')) +
                            parseInt($vcont.css('paddingTop')) +
                            parseInt($vcont.css('paddingBottom')) + 50;
                    console.log(bottom_border);

                    var available_v_space = $(window).height() - (used_v_space + bottom_border);
                    var $qfc = $('#qc_form_container');
                    if (available_v_space < $qfc.height()) {
                        available_v_space = $qfc.height();
                    }

                    $('#simple_viewer').height(available_v_space);
                }

                setViewerHeight();
                $(window).resize(setViewerHeight);
                $('#goodQuality').click(setViewerHeight);
                $('#badQuality').click(setViewerHeight);

                scope.$on('viewer.controller_initialized', function() {
                    var viewer_config = {
                        'showNavigator': true,
                        'showFullPageControl': false
                    };

                    var ome_seadragon_viewer = new ViewerController(
                        'simple_viewer',
                        scope.svc.getStaticFilesURL(),
                        scope.svc.getDZIURL(),
                        viewer_config
                    );
                    ome_seadragon_viewer.buildViewer();

                    ome_seadragon_viewer.viewer.addHandler('open', function() {
                        ome_seadragon_viewer.setMinDZILevel(8);
                    });

                    var scalebar_config = {
                        'xOffset': 10,
                        'yOffset': 10,
                        'barThickness': 5,
                        'color': '#777',
                        'fontColor': '#000',
                        'backgroundColor': 'rgba(255, 255, 255, 0.5)'
                    };
                    ome_seadragon_viewer.enableScalebar(
                        scope.svc.getSlideMicronsPerPixel(), scalebar_config
                    );
                });
            }
        };
        return directive;
    }

    function annotationsViewer() {
        var directive = {
            replace: true,
            controller: 'AnnotationsViewerController',
            controllerAs: 'avc',
            restrict: 'E',
            templateUrl: '/static/templates/viewer/rois_viewer.html',
            link: function(scope, element, attrs) {
                scope.$on('viewer.controller_initialized', function() {
                    console.log('ome_seadragon viewer with annotations - INITIALIZING');

                    var viewer_config = {
                        'showNavigator': true,
                        'showFullPageControl': false,
                        'animationTime': 0.01
                    };
                    var ome_seadragon_viewer = new ViewerController(
                        'viewer',
                        scope.avc.getStaticFilesURL(),
                        scope.avc.getDZIURL(),
                        viewer_config
                    );
                    ome_seadragon_viewer.buildViewer();

                    ome_seadragon_viewer.viewer.addHandler('open', function() {
                        ome_seadragon_viewer.setMinDZILevel(8);

                        var annotations_canvas = new AnnotationsController('rois_canvas');
                        annotations_canvas.buildAnnotationsCanvas(ome_seadragon_viewer);
                        ome_seadragon_viewer.addAnnotationsController(annotations_canvas, true);

                        var tools_manager = new AnnotationsEventsController(annotations_canvas);
                        // initialize polygon, freehand drawing and measuring tools
                        var shape_config = {'fill_alpha': 0.01, 'stroke_width': 40};
                        tools_manager.initializePolygonDrawingTool(shape_config);
                        tools_manager.initializeFreehandDrawingTool(shape_config);
                        tools_manager.initializeMeasuringTool();

                        console.log('Registering components');
                        scope.avc.registerComponents(ome_seadragon_viewer,
                            annotations_canvas, tools_manager);

                        var scalebar_config = {
                            'xOffset': 10,
                            'yOffset': 10,
                            'barThickness': 5,
                            'color': '#777',
                            'fontColor': '#000',
                            'backgroundColor': 'rgba(255, 255, 255, 0.5)'
                        };
                        ome_seadragon_viewer.enableScalebar(
                            scope.avc.getSlideMicronsPerPixel(), scalebar_config
                        );
                    });
                });
            }
        };
        return directive;
    }
})();<|endoftext|>


<commit_before>/* Copyright by Steamed Pears, 2013. For licensing information,
   see the LICENCE file in the root directory of this project. */
/******************************************************************************
* tutorial.js                                                                 *
*                                                                             *
* This module provides an API for interacting with the tutorial model.        *
******************************************************************************/

define([
  "jquery",
  "intro"
], function($,intro) {
  var tutorial = {};

  // save some DOM elements
  var tutorialBtn, codeArea, commentArea;

  // initialization
  $(document).ready(function() {
    tutorialBtn = $("#tutorial-btn");
    codeArea = $('#code');
    commentArea = $('#comment-new');
  });

  function removeAllAttributes() {
    codeArea.removeAttr('data-intro');
    commentArea.removeAttr('data-intro');
    codeArea.removeAttr('data-step');
    commentArea.removeAttr('data-step');
  }

  function codeMode() {
    $(document).ready(function() {
      // set up the code mode of the tutorial
      tutorialBtn.click(function() {
        console.log('starting code tutorial');

        removeAllAttributes();

        codeArea.attr('data-step','1');
        codeArea.attr('data-intro','Enter the text you would like to be reviewed');

        intro().start();
      });
    });
  }
  tutorial.codeMode = codeMode;

  function commentMode() {
    $(document).ready(function() {
      // set up the comment mode of the tutorial
      tutorialBtn.click(function() {
        console.log('starting comment tutorial');

        removeAllAttributes();

        codeArea.attr('data-step','1');
        codeArea.attr('data-intro','Select the text you would like to review');

        commentArea.attr('data-step','2');
        commentArea.attr('data-intro','Review the text you have selected');

        intro().start();
      });
    });
  }
  tutorial.commentMode = commentMode;

  return tutorial;
});

/* Local Variables:         */
/* espresso-indent-level: 2 */
/* tab-width: 8             */
/* indent-tabs-mode: nil    */
/* fill-column: 80          */
/* End:                     */
/* vim: set softtabstop=2 shiftwidth=2 tabstop=8 expandtab textwidth=80: */
<commit_msg>Removed debug output<commit_after>/* Copyright by Steamed Pears, 2013. For licensing information,
   see the LICENCE file in the root directory of this project. */
/******************************************************************************
* tutorial.js                                                                 *
*                                                                             *
* This module provides an API for interacting with the tutorial model.        *
******************************************************************************/

define([
  "jquery",
  "intro"
], function($,intro) {
  var tutorial = {};

  // save some DOM elements
  var tutorialBtn, codeArea, commentArea;

  // initialization
  $(document).ready(function() {
    tutorialBtn = $("#tutorial-botn");
    codeArea = $('#code');
    commentArea = $('#comment-new');
  });

  function removeAllAttributes() {
    codeArea.removeAttr('data-intro');
    commentArea.removeAttr('data-intro');
    codeArea.removeAttr('data-step');
    commentArea.removeAttr('data-step');
  }

  function codeMode() {
    $(document).ready(function() {
      // set up the code mode of the tutorial
      tutorialBtn.click(function() {
        removeAllAttributes();

        codeArea.attr('data-step','1');
        codeArea.attr('data-intro','Enter the text you would like to be reviewed');

        intro().start();
      });
    });
  }
  tutorial.codeMode = codeMode;

  function commentMode() {
    $(document).ready(function() {
      // set up the comment mode of the tutorial
      tutorialBtn.click(function() {
        removeAllAttributes();

        codeArea.attr('data-step','1');
        codeArea.attr('data-intro','Select the text you would like to review');

        commentArea.attr('data-step','2');
        commentArea.attr('data-intro','Review the text you have selected');

        intro().start();
      });
    });
  }
  tutorial.commentMode = commentMode;

  return tutorial;
});

/* Local Variables:         */
/* espresso-indent-level: 2 */
/* tab-width: 8             */
/* indent-tabs-mode: nil    */
/* fill-column: 80          */
/* End:                     */
/* vim: set softtabstop=2 shiftwidth=2 tabstop=8 expandtab textwidth=80: */
<|endoftext|>