<commit_before>/* This is part of Pterosaur.
 *
 * Copyright (c) 2014 James Kolb <jck1089@gmail.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * This file incorporates work covered under the following copyright and permission notice:
 *   Copyright © 2006-2009 by Martin Stubenschrott <stubenschrott@vimperator.org>
 *   Copyright © 2007-2011 by Doug Kearns <dougkearns@gmail.com>
 *   Copyright © 2008-2011 by Kris Maglione <maglione.k at Gmail>
 *
 *   For a full list of authors, refer the AUTHORS file.
 *
 *   Permission is hereby granted, free of charge, to any person obtaining a
 *   copy of this software and associated documentation files (the "Software"),
 *   to deal in the Software without restriction, including without limitation
 *   the rights to use, copy, modify, merge, publish, distribute, sublicense,
 *   and/or sell copies of the Software, and to permit persons to whom the
 *   Software is furnished to do so, subject to the following conditions:
 *
 *   The above copyright notice and this permission notice shall be included in
 *   all copies or substantial portions of the Software.
 *
 *   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 *   IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 *   THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 *   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 *   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 *   DEALINGS IN THE SOFTWARE.
 */

"use strict";
var INFO =
["plugin", { name: "fullvim",
             version: "0.1",
             href: "http://github.com/ardagnir/pterosaur",
             summary: "All text is vim",
             xmlns: "dactyl" },
    ["author", { email: "jck1089@gmail.com" },
        "James Kolb"],
    ["license", { href: "http://www.gnu.org/licenses/agpl-3.0.html" },
        "Gnu AGPL v3"],
    ["project", { name: "Pentadactyl", "min-version": "1.0" }],
    ["p", {},
        "This plugin provides full vim functionality to all input text-boxes by running a vim process in the background."]];

function update(){
    if (pterosaurCleanupCheck !== options["fullvim"])
      cleanupPterosaur();

    if (!options["fullvim"] || dactyl.focusedElement.type === "password" || modes.main !== modes.INSERT && modes.main !== modes.AUTOCOMPLETE && modes.main !== modes.VIM_NORMAL) {
      if(pterFocused && modes.main !== modes.EX) {
        cleanupForTextbox();
        pterFocused = null
      }
      return;
    }

    if (dactyl.focusedElement !== pterFocused)
    {
      if(pterFocused)
        cleanupForTextbox();
      setupForTextbox();
    }

    let val = tmpfile.read();

    let metadata = metaTmpfile.read().split('\n');
    vimMode = metadata[0]
    if (vimMode === "n" && modes.main === modes.INSERT)
      modes.push(modes.VIM_NORMAL)

    if (vimMode === "i" && modes.main === modes.VIM_NORMAL)
      modes.pop()

    if (textBox) {
        if (savedCursorStart!=null && textBox.selectionStart != savedCursorStart || savedCursorEnd!=null && textBox.selectionEnd != savedCursorEnd ) {
          pterFocused = null;
          return;
        }

        if (savedText!=null && textBox.value != savedText) {
          pterFocused = null;
          return;
        }

        textBox.value = val;
        savedText = textBox.value;

        if(metadata.length>2)
          textBox.setSelectionRange(metadata[1], metadata[2]);

        savedCursorStart = textBox.selectionStart;
        savedCursorEnd = textBox.selectionEnd;

        if (true) {
            let elem = DOM(textBox);
            elem.attrNS(NS, "modifiable", true)
                .style.MozUserInput;
            elem.input().attrNS(NS, "modifiable", null);
        }
    }
    else {
        while (editor_.rootElement.firstChild)
            editor_.rootElement.removeChild(editor_.rootElement.firstChild);
        editor_.rootElement.innerHTML = val;
    }
}

function cleanupForTextbox() {
    if (tmpfile && tmpfile.exists())
        tmpfile.remove(false);
    if (metaTmpfile && metaTmpfile.exists())
        metaTmpfile.remove(false);
    tmpfile = null
}

function setupForTextbox() {
    pterFocused = dactyl.focusedElement;
    savedText = null;
    savedCursorStart = null;
    savedCursorEnd = null;

    textBox = config.isComposeWindow ? null : dactyl.focusedElement;

    if (!DOM(textBox).isInput)
        textBox = null;
    let line, column;

    if (textBox) {
        var text = textBox.value;
        var pre = text.substr(0, textBox.selectionStart);
    }
    else {
        var editor_ = window.GetCurrentEditor ? GetCurrentEditor()
                                              : Editor.getEditor(document.commandDispatcher.focusedWindow);
        dactyl.assert(editor_);
        text = Array.map(editor_.rootElement.childNodes,
                         e => DOM.stringify(e, true))
                    .join("");

        if (!editor_.selection.rangeCount)
            var sel = "";
        else {
            let range = RangeFind.nodeContents(editor_.rootElement);
            let end = editor_.selection.getRangeAt(0);
            range.setEnd(end.startContainer, end.startOffset);
            pre = DOM.stringify(range, true);
            if (range.startContainer instanceof Text)
                pre = pre.replace(/^(?:<[^>"]+>)+/, "");
            if (range.endContainer instanceof Text)
                pre = pre.replace(/(?:<\/[^>"]+>)+$/, "");
        }
    }
    line = 1 + pre.replace(/[^\n]/g, "").length;
    column = 1 + pre.replace(/[^]*\n/, "").length;

    let origGroup = DOM(textBox).highlight.toString();
    tmpfile = io.createTempFile("txt", "-pterosaur"+buffer.uri.host);
    metaTmpfile = io.createTempFile("txt", "-pterosaur"+buffer.uri.host+"-meta");
    if (!tmpfile)
        throw Error(_("io.cantCreateTempFile"));

    if (!metaTmpfile)
        throw Error(_("io.cantCreateTempFile"));

    if (!tmpfile.write(text))
        throw Error(_("io.cantEncode"));

    var vimCommand;

    vimCommand = 'vim --servername pterosaur --remote-expr "SwitchPterosaurFile(<line>,<column>,\'<file>\',\'<metaFile>\')"';

    vimCommand = vimCommand.replace(/<metaFile>/, metaTmpfile.path);
    vimCommand = vimCommand.replace(/<file>/, tmpfile.path);
    vimCommand = vimCommand.replace(/<column>/, column);
    vimCommand = vimCommand.replace(/<line>/, line);

    io.system(vimCommand);
}

modes.INSERT.params.onKeyPress = function(eventList) {
    const KILL = false, PASS = true;

    if (!options["fullvim"] || dactyl.focusedElement.type === "password")
      return PASS;

    let inputChar = DOM.Event.stringify(eventList[0])

    if (/^<(?:.-)*(?:BS|lt|Up|Down|Left|Right|Space|Return|Del|Tab|C-h|C-w|C-u|C-k|C-r)>$/.test(inputChar)) {
      //Currently, this also refreshes. I need to disable that.
      if (inputChar==="<Space>")
        io.system("printf ' ' > /tmp/pterosaur_fifo");
      else if (inputChar==="<BS>")
        io.system("printf '\\b' > /tmp/pterosaur_fifo");
      else if (inputChar==="<Return>") {
        io.system("printf '\\r' > /tmp/pterosaur_fifo");
        return PASS;
      }
      else if (inputChar==="<Tab>")
        return PASS;
      else if (inputChar==="<Up>")
        io.system("printf '\\e[A' > /tmp/pterosaur_fifo");
      else if (inputChar==="<Down>")
        io.system("printf '\\e[B' > /tmp/pterosaur_fifo");
      else if (inputChar==="<Right>")
        io.system("printf '\\e[C' > /tmp/pterosaur_fifo");
      else if (inputChar==="<Left>")
        io.system("printf '\\e[D' > /tmp/pterosaur_fifo");
      else if (inputChar==="<lt>")
        io.system("printf '<' > /tmp/pterosaur_fifo");
    }
    else if (/\:|\?|\//.test(inputChar) && vimMode!='i' && vimMode!='R')
    {
      CommandExMode().open("vimdo " + inputChar);
    }
    else {
      if (inputChar == '%')
        io.system('printf "%%" > /tmp/pterosaur_fifo');
      else if (inputChar == '\\')
        io.system("printf '\\\\' > /tmp/pterosaur_fifo");
      else
        io.system('printf "' + inputChar + '" > /tmp/pterosaur_fifo');
    }

    return KILL;
}

function cleanupPterosaur()
{
    if (options["fullvim"]) {
        mappings.builtin.remove(modes.INSERT, "<Space>");
        mappings.builtin.remove(modes.INSERT, "<Return>");
    }
    else {
        mappings.builtin.add([modes.INSERT],
            ["<Space>", "<Return>"], "Expand Insert mode abbreviation",
            function () {
                editor.expandAbbreviation(modes.INSERT);
                return Events.PASS_THROUGH;
        });
    }
    pterosaurCleanupCheck = options["fullvim"];
}

io.system("mkfifo /tmp/pterosaur_fifo");

//TODO: This is an ugly hack. Also, the cat is necessary
io.system("$(while killall -0 firefox; do sleep 1; done) | cat > /tmp/pterosaur_fifo &");

//TODO: Also an ugly hack. Also the --remote is only there because on some computers vim won't create a server outside a terminal unless it has a --remote.
io.system('sh -c \'while [ "$(vim --servername pterosaur --remote-expr 1)" != 1 ] && killall -0 firefox; do vim --servername pterosaur +"set autoread" +"set noswapfile" +"set shortmess+=A" --remote /tmp/pentatdactyl-pterosuar </tmp/pterosaur_fifo > /dev/null; done\' &');

//If this doesn't match options["fullvim"] we need to perform cleanup
var pterosaurCleanupCheck = false;

group.options.add(["fullvim"], "Edit all text inputs using vim", "boolean", false);

modes.addMode("VIM_NORMAL", {
  char: "N",
  desription: "Vim normal mode",
  bases: [modes.INSERT]
})

mappings.builtin.add(
    [modes.INSERT, modes.VIM_NORMAL],
    ["<C-r>"],
    "Override refresh and send <C-r> to vim.",
    function(){
      io.system('printf "\x12" > /tmp/pterosaur_fifo');
    },
    {noTransaction: true});

commands.add(["vim[do]"],
    "Send command to vim",
    function (args) {
        dactyl.focus(pterFocused);
        let command = args.join(" ").replace(/%/g,"%%").replace(/\\/g,'\\\\');
        io.system("printf '" + command + "\r' > /tmp/pterosaur_fifo");
    }, {
      argCount: "+",
      literal: 0
    });

var savedText = null;
var savedCursorStart = null;
var savedCursorEnd = null;
var vimMode = 'i';
var pterFocused = null;
var tmpfile = null;
var metaTmpfile = null;
var textBox;

let timer =  window.setInterval(update, 100);
<commit_msg>Fixed double quotes<commit_after>/* This is part of Pterosaur.
 *
 * Copyright (c) 2014 James Kolb <jck1089@gmail.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * This file incorporates work covered under the following copyright and permission notice:
 *   Copyright © 2006-2009 by Martin Stubenschrott <stubenschrott@vimperator.org>
 *   Copyright © 2007-2011 by Doug Kearns <dougkearns@gmail.com>
 *   Copyright © 2008-2011 by Kris Maglione <maglione.k at Gmail>
 *
 *   For a full list of authors, refer the AUTHORS file.
 *
 *   Permission is hereby granted, free of charge, to any person obtaining a
 *   copy of this software and associated documentation files (the "Software"),
 *   to deal in the Software without restriction, including without limitation
 *   the rights to use, copy, modify, merge, publish, distribute, sublicense,
 *   and/or sell copies of the Software, and to permit persons to whom the
 *   Software is furnished to do so, subject to the following conditions:
 *
 *   The above copyright notice and this permission notice shall be included in
 *   all copies or substantial portions of the Software.
 *
 *   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 *   IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 *   THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 *   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 *   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 *   DEALINGS IN THE SOFTWARE.
 */

"use strict";
var INFO =
["plugin", { name: "fullvim",
             version: "0.1",
             href: "http://github.com/ardagnir/pterosaur",
             summary: "All text is vim",
             xmlns: "dactyl" },
    ["author", { email: "jck1089@gmail.com" },
        "James Kolb"],
    ["license", { href: "http://www.gnu.org/licenses/agpl-3.0.html" },
        "Gnu AGPL v3"],
    ["project", { name: "Pentadactyl", "min-version": "1.0" }],
    ["p", {},
        "This plugin provides full vim functionality to all input text-boxes by running a vim process in the background."]];

function update(){
    if (pterosaurCleanupCheck !== options["fullvim"])
      cleanupPterosaur();

    if (!options["fullvim"] || dactyl.focusedElement.type === "password" || modes.main !== modes.INSERT && modes.main !== modes.AUTOCOMPLETE && modes.main !== modes.VIM_NORMAL) {
      if(pterFocused && modes.main !== modes.EX) {
        cleanupForTextbox();
        pterFocused = null
      }
      return;
    }

    if (dactyl.focusedElement !== pterFocused)
    {
      if(pterFocused)
        cleanupForTextbox();
      setupForTextbox();
    }

    let val = tmpfile.read();

    let metadata = metaTmpfile.read().split('\n');
    vimMode = metadata[0]
    if (vimMode === "n" && modes.main === modes.INSERT)
      modes.push(modes.VIM_NORMAL)

    if (vimMode === "i" && modes.main === modes.VIM_NORMAL)
      modes.pop()

    if (textBox) {
        if (savedCursorStart!=null && textBox.selectionStart != savedCursorStart || savedCursorEnd!=null && textBox.selectionEnd != savedCursorEnd ) {
          pterFocused = null;
          return;
        }

        if (savedText!=null && textBox.value != savedText) {
          pterFocused = null;
          return;
        }

        textBox.value = val;
        savedText = textBox.value;

        if(metadata.length>2)
          textBox.setSelectionRange(metadata[1], metadata[2]);

        savedCursorStart = textBox.selectionStart;
        savedCursorEnd = textBox.selectionEnd;

        if (true) {
            let elem = DOM(textBox);
            elem.attrNS(NS, "modifiable", true)
                .style.MozUserInput;
            elem.input().attrNS(NS, "modifiable", null);
        }
    }
    else {
        while (editor_.rootElement.firstChild)
            editor_.rootElement.removeChild(editor_.rootElement.firstChild);
        editor_.rootElement.innerHTML = val;
    }
}

function cleanupForTextbox() {
    if (tmpfile && tmpfile.exists())
        tmpfile.remove(false);
    if (metaTmpfile && metaTmpfile.exists())
        metaTmpfile.remove(false);
    tmpfile = null
}

function setupForTextbox() {
    pterFocused = dactyl.focusedElement;
    savedText = null;
    savedCursorStart = null;
    savedCursorEnd = null;

    textBox = config.isComposeWindow ? null : dactyl.focusedElement;

    if (!DOM(textBox).isInput)
        textBox = null;
    let line, column;

    if (textBox) {
        var text = textBox.value;
        var pre = text.substr(0, textBox.selectionStart);
    }
    else {
        var editor_ = window.GetCurrentEditor ? GetCurrentEditor()
                                              : Editor.getEditor(document.commandDispatcher.focusedWindow);
        dactyl.assert(editor_);
        text = Array.map(editor_.rootElement.childNodes,
                         e => DOM.stringify(e, true))
                    .join("");

        if (!editor_.selection.rangeCount)
            var sel = "";
        else {
            let range = RangeFind.nodeContents(editor_.rootElement);
            let end = editor_.selection.getRangeAt(0);
            range.setEnd(end.startContainer, end.startOffset);
            pre = DOM.stringify(range, true);
            if (range.startContainer instanceof Text)
                pre = pre.replace(/^(?:<[^>"]+>)+/, "");
            if (range.endContainer instanceof Text)
                pre = pre.replace(/(?:<\/[^>"]+>)+$/, "");
        }
    }
    line = 1 + pre.replace(/[^\n]/g, "").length;
    column = 1 + pre.replace(/[^]*\n/, "").length;

    let origGroup = DOM(textBox).highlight.toString();
    tmpfile = io.createTempFile("txt", "-pterosaur"+buffer.uri.host);
    metaTmpfile = io.createTempFile("txt", "-pterosaur"+buffer.uri.host+"-meta");
    if (!tmpfile)
        throw Error(_("io.cantCreateTempFile"));

    if (!metaTmpfile)
        throw Error(_("io.cantCreateTempFile"));

    if (!tmpfile.write(text))
        throw Error(_("io.cantEncode"));

    var vimCommand;

    vimCommand = 'vim --servername pterosaur --remote-expr "SwitchPterosaurFile(<line>,<column>,\'<file>\',\'<metaFile>\')"';

    vimCommand = vimCommand.replace(/<metaFile>/, metaTmpfile.path);
    vimCommand = vimCommand.replace(/<file>/, tmpfile.path);
    vimCommand = vimCommand.replace(/<column>/, column);
    vimCommand = vimCommand.replace(/<line>/, line);

    io.system(vimCommand);
}

modes.INSERT.params.onKeyPress = function(eventList) {
    const KILL = false, PASS = true;

    if (!options["fullvim"] || dactyl.focusedElement.type === "password")
      return PASS;

    let inputChar = DOM.Event.stringify(eventList[0])

    if (/^<(?:.-)*(?:BS|lt|Up|Down|Left|Right|Space|Return|Del|Tab|C-h|C-w|C-u|C-k|C-r)>$/.test(inputChar)) {
      //Currently, this also refreshes. I need to disable that.
      if (inputChar==="<Space>")
        io.system("printf ' ' > /tmp/pterosaur_fifo");
      else if (inputChar==="<BS>")
        io.system("printf '\\b' > /tmp/pterosaur_fifo");
      else if (inputChar==="<Return>") {
        io.system("printf '\\r' > /tmp/pterosaur_fifo");
        return PASS;
      }
      else if (inputChar==="<Tab>")
        return PASS;
      else if (inputChar==="<Up>")
        io.system("printf '\\e[A' > /tmp/pterosaur_fifo");
      else if (inputChar==="<Down>")
        io.system("printf '\\e[B' > /tmp/pterosaur_fifo");
      else if (inputChar==="<Right>")
        io.system("printf '\\e[C' > /tmp/pterosaur_fifo");
      else if (inputChar==="<Left>")
        io.system("printf '\\e[D' > /tmp/pterosaur_fifo");
      else if (inputChar==="<lt>")
        io.system("printf '<' > /tmp/pterosaur_fifo");
    }
    else if (/\:|\?|\//.test(inputChar) && vimMode!='i' && vimMode!='R')
    {
      CommandExMode().open("vimdo " + inputChar);
    }
    else {
      if (inputChar == '%')
        io.system('printf "%%" > /tmp/pterosaur_fifo');
      else if (inputChar == '\\')
        io.system("printf '\\\\' > /tmp/pterosaur_fifo");
      else if (inputChar == '"')
        io.system("printf '\"' > /tmp/pterosaur_fifo");
      else
        io.system('printf "' + inputChar + '" > /tmp/pterosaur_fifo');
    }

    return KILL;
}

function cleanupPterosaur()
{
    if (options["fullvim"]) {
        mappings.builtin.remove(modes.INSERT, "<Space>");
        mappings.builtin.remove(modes.INSERT, "<Return>");
    }
    else {
        mappings.builtin.add([modes.INSERT],
            ["<Space>", "<Return>"], "Expand Insert mode abbreviation",
            function () {
                editor.expandAbbreviation(modes.INSERT);
                return Events.PASS_THROUGH;
        });
    }
    pterosaurCleanupCheck = options["fullvim"];
}

io.system("mkfifo /tmp/pterosaur_fifo");

//TODO: This is an ugly hack. Also, the cat is necessary
io.system("$(while killall -0 firefox; do sleep 1; done) | cat > /tmp/pterosaur_fifo &");

//TODO: Also an ugly hack. Also the --remote is only there because on some computers vim won't create a server outside a terminal unless it has a --remote.
io.system('sh -c \'while [ "$(vim --servername pterosaur --remote-expr 1)" != 1 ] && killall -0 firefox; do vim --servername pterosaur +"set autoread" +"set noswapfile" +"set shortmess+=A" --remote /tmp/pentatdactyl-pterosuar </tmp/pterosaur_fifo > /dev/null; done\' &');

//If this doesn't match options["fullvim"] we need to perform cleanup
var pterosaurCleanupCheck = false;

group.options.add(["fullvim"], "Edit all text inputs using vim", "boolean", false);

modes.addMode("VIM_NORMAL", {
  char: "N",
  desription: "Vim normal mode",
  bases: [modes.INSERT]
})

mappings.builtin.add(
    [modes.INSERT, modes.VIM_NORMAL],
    ["<C-r>"],
    "Override refresh and send <C-r> to vim.",
    function(){
      io.system('printf "\x12" > /tmp/pterosaur_fifo');
    },
    {noTransaction: true});

commands.add(["vim[do]"],
    "Send command to vim",
    function (args) {
        dactyl.focus(pterFocused);
        let command = args.join(" ").replace(/%/g,"%%").replace(/\\/g,'\\\\');
        io.system("printf '" + command + "\r' > /tmp/pterosaur_fifo");
    }, {
      argCount: "+",
      literal: 0
    });

var savedText = null;
var savedCursorStart = null;
var savedCursorEnd = null;
var vimMode = 'i';
var pterFocused = null;
var tmpfile = null;
var metaTmpfile = null;
var textBox;

let timer =  window.setInterval(update, 100);
<|endoftext|>


<commit_before>var _ = require('underscore');
var Model = require('../core/model');
var WindshaftFiltersBoundingBoxFilter = require('../windshaft/filters/bounding-box');

/**
 * Default dataview model
 */
module.exports = Model.extend({
  defaults: {
    url: '',
    data: [],
    sync_on_data_change: true,
    sync_on_bbox_change: true,
    enabled: true
  },

  url: function () {
    var params = [];
    if (this.get('boundingBox')) {
      params.push('bbox=' + this.get('boundingBox'));
    }
    return this.get('url') + '?' + params.join('&');
  },

  initialize: function (attrs, opts) {
    attrs = attrs || {};
    opts = opts || {};

    if (!opts.map) {
      throw new Error('map is required');
    }
    if (!opts.windshaftMap) {
      throw new Error('windshaftMap is required');
    }

    if (!attrs.id) {
      this.set('id', attrs.type + '-' + this.cid);
    }

    this.layer = opts.layer;
    this._map = opts.map;
    this._windshaftMap = opts.windshaftMap;

    // filter is optional, so have to guard before using it
    this.filter = opts.filter;
    if (this.filter) {
      this.filter.set('dataviewId', this.id);
    }

    this._initBinds();
    this._updateBoundingBox();
  },

  _initBinds: function () {
    this.listenTo(this._windshaftMap, 'instanceCreated', this._onNewWindshaftMapInstance);

    this.listenToOnce(this, 'change:url', function () {
      this.fetch({
        success: this._onChangeBinds.bind(this)
      });
    });

    // Retrigger an event when the filter changes
    if (this.filter) {
      this.listenTo(this.filter, 'change', this._onFilterChanged);
    }
  },

  /**
   * @private
   */
  _onFilterChanged: function () {
    this._reloadMap();
  },

  /**
   * @protected
   */
  _reloadMap: function () {
    this._map.reload({
      sourceLayerId: this.layer.get('id')
    });
  },

  _onNewWindshaftMapInstance: function (windshaftMapInstance, sourceLayerId) {
    var url = windshaftMapInstance.getDataviewURL({
      dataviewId: this.get('id'),
      protocol: 'http'
    });

    if (url) {
      var silent = (sourceLayerId && sourceLayerId !== this.layer.get('id'));

      // TODO: Instead of setting the url here, we could invoke fetch directly
      this.set('url', url, { silent: silent });
    }
  },

  _onMapBoundsChanged: function () {
    this._updateBoundingBox();
  },

  _updateBoundingBox: function () {
    var boundingBoxFilter = new WindshaftFiltersBoundingBoxFilter(this._map.getViewBounds());
    this.set('boundingBox', boundingBoxFilter.toString());
  },

  _onChangeBinds: function () {
    var BOUNDING_BOX_FILTER_WAIT = 500;
    this.listenTo(this._map, 'change:center change:zoom', _.debounce(this._onMapBoundsChanged.bind(this), BOUNDING_BOX_FILTER_WAIT));

    this.on('change:url', function () {
      if (this._shouldFetchOnURLChange()) {
        this.fetch();
      }
    }, this);
    this.on('change:boundingBox', function () {
      if (this._shouldFetchOnBoundingBoxChange()) {
        this.fetch();
      }
    }, this);

    this.on('change:enabled', function (mdl, isEnabled) {
      if (isEnabled) {
        if (mdl.changedAttributes(this._previousAttrs)) {
          this.fetch();
        }
      } else {
        this._previousAttrs = {
          url: this.get('url'),
          boundingBox: this.get('boundingBox')
        };
      }
    }, this);
  },

  _shouldFetchOnURLChange: function () {
    return this.get('sync_on_data_change') && this.get('enabled');
  },

  _shouldFetchOnBoundingBoxChange: function () {
    return this.get('enabled') && this.get('sync_on_bbox_change');
  },

  refresh: function () {
    this.fetch();
  },

  update: function (attrs) {
    attrs = _.pick(attrs, this.constructor.ATTRS_NAMES);
    this.set(attrs);
  },

  getData: function () {
    return this.get('data');
  },

  getPreviousData: function () {
    return this.previous('data');
  },

  fetch: function (opts) {
    opts = opts || {};
    this.trigger('loading', this);
    return Model.prototype.fetch.call(this, _.extend(opts, {
      error: function () {
        this.trigger('error');
      }.bind(this)
    }));
  },

  toJSON: function () {
    throw new Error('toJSON should be defined for each dataview');
  },

  remove: function () {
    if (this.filter) {
      this.filter.remove();
    }
    this.trigger('destroy', this);
    this.stopListening();
  }
},

  // Class props
  {
    ATTRS_NAMES: [
      'type',
      'sync_on_data_change',
      'sync_on_bbox_change',
      'enabled'
    ]
  }
);
<commit_msg>Make ID to be passable to dataview<commit_after>var _ = require('underscore');
var Model = require('../core/model');
var WindshaftFiltersBoundingBoxFilter = require('../windshaft/filters/bounding-box');

/**
 * Default dataview model
 */
module.exports = Model.extend({
  defaults: {
    url: '',
    data: [],
    sync_on_data_change: true,
    sync_on_bbox_change: true,
    enabled: true
  },

  url: function () {
    var params = [];
    if (this.get('boundingBox')) {
      params.push('bbox=' + this.get('boundingBox'));
    }
    return this.get('url') + '?' + params.join('&');
  },

  initialize: function (attrs, opts) {
    attrs = attrs || {};
    opts = opts || {};

    if (!opts.map) {
      throw new Error('map is required');
    }
    if (!opts.windshaftMap) {
      throw new Error('windshaftMap is required');
    }

    if (!attrs.id) {
      this.set('id', attrs.type + '-' + this.cid);
    }

    this.layer = opts.layer;
    this._map = opts.map;
    this._windshaftMap = opts.windshaftMap;

    // filter is optional, so have to guard before using it
    this.filter = opts.filter;
    if (this.filter) {
      this.filter.set('dataviewId', this.id);
    }

    this._initBinds();
    this._updateBoundingBox();
  },

  _initBinds: function () {
    this.listenTo(this._windshaftMap, 'instanceCreated', this._onNewWindshaftMapInstance);

    this.listenToOnce(this, 'change:url', function () {
      this.fetch({
        success: this._onChangeBinds.bind(this)
      });
    });

    // Retrigger an event when the filter changes
    if (this.filter) {
      this.listenTo(this.filter, 'change', this._onFilterChanged);
    }
  },

  /**
   * @private
   */
  _onFilterChanged: function () {
    this._reloadMap();
  },

  /**
   * @protected
   */
  _reloadMap: function () {
    this._map.reload({
      sourceLayerId: this.layer.get('id')
    });
  },

  _onNewWindshaftMapInstance: function (windshaftMapInstance, sourceLayerId) {
    var url = windshaftMapInstance.getDataviewURL({
      dataviewId: this.get('id'),
      protocol: 'http'
    });

    if (url) {
      var silent = (sourceLayerId && sourceLayerId !== this.layer.get('id'));

      // TODO: Instead of setting the url here, we could invoke fetch directly
      this.set('url', url, { silent: silent });
    }
  },

  _onMapBoundsChanged: function () {
    this._updateBoundingBox();
  },

  _updateBoundingBox: function () {
    var boundingBoxFilter = new WindshaftFiltersBoundingBoxFilter(this._map.getViewBounds());
    this.set('boundingBox', boundingBoxFilter.toString());
  },

  _onChangeBinds: function () {
    var BOUNDING_BOX_FILTER_WAIT = 500;
    this.listenTo(this._map, 'change:center change:zoom', _.debounce(this._onMapBoundsChanged.bind(this), BOUNDING_BOX_FILTER_WAIT));

    this.on('change:url', function () {
      if (this._shouldFetchOnURLChange()) {
        this.fetch();
      }
    }, this);
    this.on('change:boundingBox', function () {
      if (this._shouldFetchOnBoundingBoxChange()) {
        this.fetch();
      }
    }, this);

    this.on('change:enabled', function (mdl, isEnabled) {
      if (isEnabled) {
        if (mdl.changedAttributes(this._previousAttrs)) {
          this.fetch();
        }
      } else {
        this._previousAttrs = {
          url: this.get('url'),
          boundingBox: this.get('boundingBox')
        };
      }
    }, this);
  },

  _shouldFetchOnURLChange: function () {
    return this.get('sync_on_data_change') && this.get('enabled');
  },

  _shouldFetchOnBoundingBoxChange: function () {
    return this.get('enabled') && this.get('sync_on_bbox_change');
  },

  refresh: function () {
    this.fetch();
  },

  update: function (attrs) {
    attrs = _.pick(attrs, this.constructor.ATTRS_NAMES);
    this.set(attrs);
  },

  getData: function () {
    return this.get('data');
  },

  getPreviousData: function () {
    return this.previous('data');
  },

  fetch: function (opts) {
    opts = opts || {};
    this.trigger('loading', this);
    return Model.prototype.fetch.call(this, _.extend(opts, {
      error: function () {
        this.trigger('error');
      }.bind(this)
    }));
  },

  toJSON: function () {
    throw new Error('toJSON should be defined for each dataview');
  },

  remove: function () {
    if (this.filter) {
      this.filter.remove();
    }
    this.trigger('destroy', this);
    this.stopListening();
  }
},

  // Class props
  {
    ATTRS_NAMES: [
      'id',
      'sync_on_data_change',
      'sync_on_bbox_change',
      'enabled'
    ]
  }
);
<|endoftext|>


<commit_before>'use strict';

module.exports = function (config) {
  var configuration = {
    basePath: '.',

    frameworks: ['jasmine-ajax', 'jasmine'],

    files: [
      // paths loaded by Karma
      {pattern: 'node_modules/reflect-metadata/Reflect.js', included: true, watched: true},
      {pattern: 'node_modules/systemjs/dist/system.src.js', included: true, watched: false},
      {pattern: 'node_modules/zone.js/dist/zone.js', included: true, watched: true},
      {pattern: 'node_modules/rxjs/**/*.js', included: false, watched: false},
      {pattern: 'node_modules/rxjs/**/*.map', included: false, watched: false},
      {pattern: 'node_modules/@angular/**/*.js', included: false, watched: false},
      {pattern: 'node_modules/@angular/**/*.map', included: false, watched: false},
      {pattern: 'node_modules/ng2-alfresco-core/dist/**/*.js', included: false, served: true, watched: false},
      {pattern: 'node_modules/ng2-translate/**/*.js', included: false, served: true, watched: false},

      {pattern: 'karma-test-shim.js', included: true, watched: true},

      // paths loaded via module imports
      {pattern: 'dist/**/*.js', included: false, watched: true},
      {pattern: 'dist/**/*.html', included: true, served: true, watched: true},
      {pattern: 'dist/**/*.css', included: true, served: true, watched: true},

      // paths to support debugging with source maps in dev tools
      {pattern: 'src/**/*.ts', included: false, watched: false},
      {pattern: 'dist/**/*.js.map', included: false, watched: false}
    ],

    // proxied base paths
    proxies: {
      // required for component assets fetched by Angular's compiler
      '/src/': '/base/src/'
    },

    port: 9876,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_DEBUG,

    colors: true,

    autoWatch: true,

    browsers: ['Chrome'],

    customLaunchers: {
      Chrome_travis_ci: {
        base: 'Chrome',
        flags: ['--no-sandbox']
      }
    },

    // Karma plugins loaded
    plugins: [
      'karma-jasmine',
      'karma-coverage',
      'karma-jasmine-ajax',
      'karma-chrome-launcher',
      'karma-mocha-reporter',
      'karma-jasmine-html-reporter'
    ],

    // Coverage reporter generates the coverage
    reporters: ['mocha', 'coverage', 'kjhtml'],

    // Source files that you wanna generate coverage for.
    // Do not include tests or libraries (these files will be instrumented by Istanbul)
    preprocessors: {
      'dist/**/!(*spec).js': ['coverage']
    },

    coverageReporter: {
      dir: 'coverage/',
      subdir: 'report',
      reporters: [
        {type: 'text'},
        {type: 'json', file: 'coverage-final.json'},
        {type: 'html'}
      ]
    }
  }

  if (process.env.TRAVIS) {
    configuration.browsers = ['Chrome_travis_ci'];
  }

  config.set(configuration)
};
<commit_msg>Less detailed log output for Upload tests<commit_after>'use strict';

module.exports = function (config) {
  var configuration = {
    basePath: '.',

    frameworks: ['jasmine-ajax', 'jasmine'],

    files: [
      // paths loaded by Karma
      {pattern: 'node_modules/reflect-metadata/Reflect.js', included: true, watched: true},
      {pattern: 'node_modules/systemjs/dist/system.src.js', included: true, watched: false},
      {pattern: 'node_modules/zone.js/dist/zone.js', included: true, watched: true},
      {pattern: 'node_modules/rxjs/**/*.js', included: false, watched: false},
      {pattern: 'node_modules/rxjs/**/*.map', included: false, watched: false},
      {pattern: 'node_modules/@angular/**/*.js', included: false, watched: false},
      {pattern: 'node_modules/@angular/**/*.map', included: false, watched: false},
      {pattern: 'node_modules/ng2-alfresco-core/dist/**/*.js', included: false, served: true, watched: false},
      {pattern: 'node_modules/ng2-translate/**/*.js', included: false, served: true, watched: false},

      {pattern: 'karma-test-shim.js', included: true, watched: true},

      // paths loaded via module imports
      {pattern: 'dist/**/*.js', included: false, watched: true},
      {pattern: 'dist/**/*.html', included: true, served: true, watched: true},
      {pattern: 'dist/**/*.css', included: true, served: true, watched: true},

      // paths to support debugging with source maps in dev tools
      {pattern: 'src/**/*.ts', included: false, watched: false},
      {pattern: 'dist/**/*.js.map', included: false, watched: false}
    ],

    // proxied base paths
    proxies: {
      // required for component assets fetched by Angular's compiler
      '/src/': '/base/src/'
    },

    port: 9876,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,

    colors: true,

    autoWatch: true,

    browsers: ['Chrome'],

    customLaunchers: {
      Chrome_travis_ci: {
        base: 'Chrome',
        flags: ['--no-sandbox']
      }
    },

    // Karma plugins loaded
    plugins: [
      'karma-jasmine',
      'karma-coverage',
      'karma-jasmine-ajax',
      'karma-chrome-launcher',
      'karma-mocha-reporter',
      'karma-jasmine-html-reporter'
    ],

    // Coverage reporter generates the coverage
    reporters: ['mocha', 'coverage', 'kjhtml'],

    // Source files that you wanna generate coverage for.
    // Do not include tests or libraries (these files will be instrumented by Istanbul)
    preprocessors: {
      'dist/**/!(*spec).js': ['coverage']
    },

    coverageReporter: {
      dir: 'coverage/',
      subdir: 'report',
      reporters: [
        {type: 'text'},
        {type: 'json', file: 'coverage-final.json'},
        {type: 'html'}
      ]
    }
  }

  if (process.env.TRAVIS) {
    configuration.browsers = ['Chrome_travis_ci'];
  }

  config.set(configuration)
};
<|endoftext|>


<commit_before>// Thanks to: https://github.com/calebroseland/vue-dom-portal

const objectAssign = require('object-assign')
/**
 * Get target DOM Node
 * @param {(Node|string|Boolean)} [node=document.body] DOM Node, CSS selector, or Boolean
 * @return {Node} The target that the el will be appended to
 */
function getTarget (node) {
  if (node === void 0) {
    return document.body
  }

  if (typeof node === 'string' && node.indexOf('?') === 0) {
    return document.body
  } else if (typeof node === 'string' && node.indexOf('?') > 0) {
    node = node.split('?')[0]
  }

  if (node === 'body' || node === true) {
    return document.body
  }

  return node instanceof window.Node ? node : document.querySelector(node)
}

function getShouldUpdate (node) {
  // do not updated by default
  if (!node) {
    return false
  }
  if (typeof node === 'string' && node.indexOf('?') > 0) {
    try {
      const config = JSON.parse(node.split('?')[1])
      return config.autoUpdate || false
    } catch (e) {
      return false
    }
  }
  return false
}

const directive = {
  inserted (el, { value }, vnode) {
    el.className = el.className ? el.className + ' v-transfer-dom' : 'v-transfer-dom'
    const parentNode = el.parentNode
    var home = document.createComment('')
    var hasMovedOut = false

    if (value !== false) {
      parentNode.replaceChild(home, el) // moving out, el is no longer in the document
      getTarget(value).appendChild(el) // moving into new place
      hasMovedOut = true
    }
    if (!el.__transferDomData) {
      el.__transferDomData = {
        parentNode: parentNode,
        home: home,
        target: getTarget(value),
        hasMovedOut: hasMovedOut
      }
    }
  },
  componentUpdated (el, { value }) {
    const shouldUpdate = getShouldUpdate(value)
    if (!shouldUpdate) {
      return
    }
    // need to make sure children are done updating (vs. `update`)
    var ref$1 = el.__transferDomData
    // homes.get(el)
    var parentNode = ref$1.parentNode
    var home = ref$1.home
    var hasMovedOut = ref$1.hasMovedOut // recall where home is

    if (!hasMovedOut && value) {
      // remove from document and leave placeholder
      parentNode.replaceChild(home, el)
      // append to target
      getTarget(value).appendChild(el)
      el.__transferDomData = objectAssign({}, el.__transferDomData, { hasMovedOut: true, target: getTarget(value) })
    } else if (hasMovedOut && value === false) {
      // previously moved, coming back home
      parentNode.replaceChild(el, home)
      el.__transferDomData = objectAssign({}, el.__transferDomData, { hasMovedOut: false, target: getTarget(value) })
    } else if (value) {
      // already moved, going somewhere else
      getTarget(value).appendChild(el)
    }
  },
  unbind: function unbind (el, binding) {
    el.className = el.className.replace('v-transfer-dom', '')
    if (el.__transferDomData && el.__transferDomData.hasMovedOut === true) {
      el.__transferDomData.parentNode && el.__transferDomData.parentNode.appendChild(el)
    }
    el.__transferDomData = null
  }
}

module.exports = directive
<commit_msg>transfer-dom: change to es6 module style<commit_after>// Thanks to: https://github.com/calebroseland/vue-dom-portal

const objectAssign = require('object-assign')
/**
 * Get target DOM Node
 * @param {(Node|string|Boolean)} [node=document.body] DOM Node, CSS selector, or Boolean
 * @return {Node} The target that the el will be appended to
 */
function getTarget (node) {
  if (node === void 0) {
    return document.body
  }

  if (typeof node === 'string' && node.indexOf('?') === 0) {
    return document.body
  } else if (typeof node === 'string' && node.indexOf('?') > 0) {
    node = node.split('?')[0]
  }

  if (node === 'body' || node === true) {
    return document.body
  }

  return node instanceof window.Node ? node : document.querySelector(node)
}

function getShouldUpdate (node) {
  // do not updated by default
  if (!node) {
    return false
  }
  if (typeof node === 'string' && node.indexOf('?') > 0) {
    try {
      const config = JSON.parse(node.split('?')[1])
      return config.autoUpdate || false
    } catch (e) {
      return false
    }
  }
  return false
}

const directive = {
  inserted (el, { value }, vnode) {
    el.className = el.className ? el.className + ' v-transfer-dom' : 'v-transfer-dom'
    const parentNode = el.parentNode
    var home = document.createComment('')
    var hasMovedOut = false

    if (value !== false) {
      parentNode.replaceChild(home, el) // moving out, el is no longer in the document
      getTarget(value).appendChild(el) // moving into new place
      hasMovedOut = true
    }
    if (!el.__transferDomData) {
      el.__transferDomData = {
        parentNode: parentNode,
        home: home,
        target: getTarget(value),
        hasMovedOut: hasMovedOut
      }
    }
  },
  componentUpdated (el, { value }) {
    const shouldUpdate = getShouldUpdate(value)
    if (!shouldUpdate) {
      return
    }
    // need to make sure children are done updating (vs. `update`)
    var ref$1 = el.__transferDomData
    // homes.get(el)
    var parentNode = ref$1.parentNode
    var home = ref$1.home
    var hasMovedOut = ref$1.hasMovedOut // recall where home is

    if (!hasMovedOut && value) {
      // remove from document and leave placeholder
      parentNode.replaceChild(home, el)
      // append to target
      getTarget(value).appendChild(el)
      el.__transferDomData = objectAssign({}, el.__transferDomData, { hasMovedOut: true, target: getTarget(value) })
    } else if (hasMovedOut && value === false) {
      // previously moved, coming back home
      parentNode.replaceChild(el, home)
      el.__transferDomData = objectAssign({}, el.__transferDomData, { hasMovedOut: false, target: getTarget(value) })
    } else if (value) {
      // already moved, going somewhere else
      getTarget(value).appendChild(el)
    }
  },
  unbind: function unbind (el, binding) {
    el.className = el.className.replace('v-transfer-dom', '')
    if (el.__transferDomData && el.__transferDomData.hasMovedOut === true) {
      el.__transferDomData.parentNode && el.__transferDomData.parentNode.appendChild(el)
    }
    el.__transferDomData = null
  }
}

export default directive
<|endoftext|>


<commit_before>MWF.xDesktop.requireApp("process.Xform", "$Input", null, false);
MWF.xApplication.process.Xform.Select = MWF.APPSelect =  new Class({
	Implements: [Events],
	Extends: MWF.APP$Input,
	iconStyle: "selectIcon",

    initialize: function(node, json, form, options){
        this.node = $(node);
        this.node.store("module", this);
        this.json = json;
        this.form = form;
        this.field = true;
    },
    _loadNode: function(){
        if (this.readonly|| this.json.isReadonly){
            this._loadNodeRead();
        }else{
            this._loadNodeEdit();
        }
    },
    _loadNodeRead: function(){
        this.node.empty();
		this.node.set({
			"nodeId": this.json.id,
			"MWFType": this.json.type
		});
        var optionItems = this.getOptions();
        var value = this.getValue();
        if (value){
            if (typeOf(value)!=="array") value = [value];
            var texts = [];
            optionItems.each(function(item){
                var tmps = item.split("|");
                var t = tmps[0];
                var v = tmps[1] || t;

                if (v){

                    if (value.indexOf(v)!=-1){
                        texts.push(t);
                    }
                }

            });
            this.node.set("text", texts.join(", "));
        }
    },
	_loadDomEvents: function(){
		Object.each(this.json.events, function(e, key){
			if (e.code){
				if (this.options.moduleEvents.indexOf(key)===-1){
					this.node.addEvent(key, function(event){
						return this.form.Macro.fire(e.code, this, event);
					}.bind(this));
				}
			}
		}.bind(this));
	},
    _loadEvents: function(){
        Object.each(this.json.events, function(e, key){
            if (e.code){
                if (this.options.moduleEvents.indexOf(key)!=-1){
                    this.addEvent(key, function(event){
                        return this.form.Macro.fire(e.code, this, event);
                    }.bind(this));
                }else{
                    this.node.addEvent(key, function(event){
                        return this.form.Macro.fire(e.code, this, event);
                    }.bind(this));
                }
            }
        }.bind(this));
    },
	addModuleEvent: function(key, fun){
		if (this.options.moduleEvents.indexOf(key)!==-1){
			this.addEvent(key, function(event){
				return (fun) ? fun(this, event) : null;
			}.bind(this));
		}else{
			this.node.addEvent(key, function(event){
				return (fun) ? fun(this, event) : null;
			}.bind(this));
		}
	},
    _loadStyles: function(){
    	if (this.areaNode){
            if (this.json.styles) if (this.areaNode) this.areaNode.setStyles(this.json.styles);
            if (this.json.inputStyles) this.node.setStyles(this.json.inputStyles);
		}else{
            if (this.json.styles) this.node.setStyles(this.json.styles);
		}
    },
	_resetNodeEdit: function(){
		this.node.empty();
		var select = new Element("select");
		select.set(this.json.properties);
		select.inject(this.node);
	},
    _loadNodeEdit: function(){
		if (!this.json.preprocessing) this._resetNodeEdit();

		var select = this.node.getFirst();
		this.areaNode = this.node;
		this.node = select;

		this.node.set({
			"id": this.json.id,
			"MWFType": this.json.type,
			"styles": {
				"margin-right": "12px"
			}
		});

		this.setOptions();
        this.node.addEvent("change", function(){
			var v = this.getInputData("change");
			this._setBusinessData(v);
            this.validationMode();
            if (this.validation()) this._setBusinessData(v);
        }.bind(this));

	},
    resetOption: function(){
        this.node.empty();
        this.setOptions();
		this.fireEvent("resetOption")
    },
	getOptions: function(){
		if (this.json.itemType == "values"){
			return this.json.itemValues;
		}else{
			return this.form.Macro.exec(((this.json.itemScript) ? this.json.itemScript.code : ""), this);
		}
		return [];
	},
	setOptions: function(){
		var optionItems = this.getOptions();
		this._setOptions(optionItems);
	},
	_setOptions: function(optionItems){
		var p = o2.promiseAll(optionItems).then(function(options){
			this.moduleSelectAG = null;
			if (!options) options = [];
			if (o2.typeOf(options)==="array"){
				options.each(function(item){
					var tmps = item.split("|");
					var text = tmps[0];
					var value = tmps[1] || text;

					var option = new Element("option", {
						"value": value,
						"text": text
					}).inject(this.node);
				}.bind(this));
				this.fireEvent("setOptions", [options])
			}
		}.bind(this), function(){
			this.moduleSelectAG = null;
		}.bind(this));
		this.moduleSelectAG = p;
		if (p) p.then(function(){
			this.moduleSelectAG = null;
		}.bind(this), function(){
			this.moduleSelectAG = null;
		}.bind(this));

		// this.moduleSelectAG = o2.AG.all(optionItems).then(function(options){
		// 	this.moduleSelectAG = null;
		// 	if (!options) options = [];
		// 	if (o2.typeOf(options)==="array"){
		// 		options.each(function(item){
		// 			var tmps = item.split("|");
		// 			var text = tmps[0];
		// 			var value = tmps[1] || text;
		//
		// 			var option = new Element("option", {
		// 				"value": value,
		// 				"text": text
		// 			}).inject(this.node);
		// 		}.bind(this));
		// 		this.fireEvent("setOptions", [options])
		// 	}
		// }.bind(this));
		// if (this.moduleSelectAG) this.moduleSelectAG.then(function(){
		// 	this.moduleSelectAG = null;
		// }.bind(this));
	},
	// __setOptions: function(){
	// 	var optionItems = this.getOptions();
    //     if (!optionItems) optionItems = [];
    //     if (o2.typeOf(optionItems)==="array"){
	// 		optionItems.each(function(item){
	// 			var tmps = item.split("|");
	// 			var text = tmps[0];
	// 			var value = tmps[1] || text;
	//
	// 			var option = new Element("option", {
	// 				"value": value,
	// 				"text": text
	// 			}).inject(this.node);
	// 		}.bind(this));
	// 		this.fireEvent("setOptions", [optionItems])
	// 	}
	// },
	addOption: function(text, value){
        var option = new Element("option", {
            "value": value || text,
            "text": text
        }).inject(this.node);
		this.fireEvent("addOption", [text, value])
	},

	_setValue: function(value, m){
		var mothed = m || "__setValue";
		if (!!value){
			var p = o2.promiseAll(value).then(function(v){
				if (o2.typeOf(v)=="array") v = v[0];
				if (this.moduleSelectAG){
					this.moduleValueAG = this.moduleSelectAG;
					this.moduleSelectAG.then(function(){
						this[mothed](v);
						return v;
					}.bind(this), function(){});
				}else{
					this[mothed](v)
				}
				return v;
			}.bind(this), function(){});

			this.moduleValueAG = p;
			if (this.moduleValueAG) this.moduleValueAG.then(function(){
				this.moduleValueAG = null;
			}.bind(this), function(){
				this.moduleValueAG = null;
			}.bind(this));
		}else{
			this[mothed](value);
		}

		// this.moduleValueAG = o2.AG.all(value).then(function(v){
		// 	if (o2.typeOf(v)=="array") v = v[0];
		// 	if (this.moduleSelectAG){
		// 		this.moduleValueAG = this.moduleSelectAG;
		// 		this.moduleSelectAG.then(function(){
		// 			this.__setValue(v);
		// 		}.bind(this));
		// 	}else{
		// 		this.__setValue(v)
		// 	}
		// 	return v;
		// }.bind(this));

		// if (value && value.isAG){
		// 	this.moduleValueAG = o2.AG.all(value),then(function(v){
		// 		this._setValue(v);
		// 	}.bind(this));
		// 	// this.moduleValueAG = value;
		// 	// value.addResolve(function(v){
		// 	// 	this._setValue(v);
		// 	// }.bind(this));
		// }else{
		//
		// }
	},
	__setValue: function(value){
		if (!this.readonly && !this.json.isReadonly ) {
			this._setBusinessData(value);
			for (var i=0; i<this.node.options.length; i++){
				var option = this.node.options[i];
				if (option.value==value){
					option.selected = true;
					//	break;
				}else{
					option.selected = false;
				}
			}
		}
		this.moduleValueAG = null;
	},

	// _setValue: function(value){
	// 	if (!this.readonly && !this.json.isReadonly ) {
    //         this._setBusinessData(value);
    //         for (var i=0; i<this.node.options.length; i++){
    //             var option = this.node.options[i];
    //             if (option.value==value){
    //                 option.selected = true;
    //                 //	break;
    //             }else{
    //                 option.selected = false;
    //             }
    //         }
    //     }
	// 	//this.node.set("value", value);
	// },
	getTextData: function(){
		var value = [];
		var text = [];
		if (this.readonly|| this.json.isReadonly){
			var ops = this.getOptionsObj();
			var data = this._getBusinessData();
			var d = typeOf(data) === "array" ? data : [data];
			d.each( function (v) {
				var idx = ops.valueList.indexOf( v );
				value.push( v || "" );
				text.push( idx > -1 ? ops.textList[idx] : (v || "") );
			});
		}else{
			var ops = this.node.getElements("option");
			ops.each(function(op){
				if (op.selected){
					var v = op.get("value");
					var t = op.get("text");
					value.push(v || "");
					text.push(t || v || "");
				}
			});
		}
		if (!value.length) value = [""];
		if (!text.length) text = [""];
		return {"value": value, "text": text};
	},
    getInputData: function(){
		var ops = this.node.getElements("option");
		var value = [];
		ops.each(function(op){
			if (op.selected){
				var v = op.get("value");
				if (v) value.push(v);
			}
		});
        if (!value.length) return null;
		return (value.length==1) ? value[0] : value;
	},
    resetData: function(){

        this.setData(this.getValue());
    },
	getOptionsObj : function(){
		var textList = [];
		var valueList = [];
		var optionItems = this.getOptions();
		if (!optionItems) optionItems = [];
		if (o2.typeOf(optionItems)==="array"){
			optionItems.each(function(item){
				var tmps = item.split("|");
				textList.push( tmps[0] );
				valueList.push( tmps[1] || tmps[0] );
			}.bind(this));
		}
		return { textList : textList, valueList : valueList };
	},

	setData: function(data){
		return this._setValue(data, "__setData");
		// if (data && data.isAG){
		// 	this.moduleValueAG = o2.AG.all(data).then(function(v){
		// 		if (o2.typeOf(v)=="array") v = v[0];
		// 		this.__setData(v);
		// 	}.bind(this));
		// }else{
		// 	this.__setData(data);
		// }
		// if (data && data.isAG){
		// 	this.moduleValueAG = data;
		// 	data.addResolve(function(v){
		// 		this.setData(v);
		// 	}.bind(this));
		// }else{
		// 	this.__setData(data);
		// 	this.moduleValueAG = null;
		// }
	},

	__setData: function(data){
        this._setBusinessData(data);
		if (this.readonly|| this.json.isReadonly){
			var d = typeOf(data) === "array" ? data : [data];
			var ops = this.getOptionsObj();
			var result = [];
			d.each( function (v) {
				var idx = ops.valueList.indexOf( v );
				result.push( idx > -1 ? ops.textList[idx] : v);
			})
			this.node.set("text", result.join(","));
		}else{
			var ops = this.node.getElements("option");
			ops.each(function(op){
				if (typeOf(data)=="array"){
					if (data.indexOf(op.get("value"))!=-1){
						op.set("selected", true);
					}else{
						op.set("selected", false);
					}
				}else{
					if (data == op.get("value")){
						op.set("selected", true);
					}else{
						op.set("selected", false);
					}
				}
			});
			this.validationMode();
		}
		this.fireEvent("setData", [data]);
	}

});
<commit_msg>修复下拉框只读情况下<commit_after>MWF.xDesktop.requireApp("process.Xform", "$Input", null, false);
MWF.xApplication.process.Xform.Select = MWF.APPSelect =  new Class({
	Implements: [Events],
	Extends: MWF.APP$Input,
	iconStyle: "selectIcon",

    initialize: function(node, json, form, options){
        this.node = $(node);
        this.node.store("module", this);
        this.json = json;
        this.form = form;
        this.field = true;
    },
    _loadNode: function(){
        if (this.readonly|| this.json.isReadonly){
            this._loadNodeRead();
        }else{
            this._loadNodeEdit();
        }
    },
    _loadNodeRead: function(){
        this.node.empty();
		this.node.set({
			"nodeId": this.json.id,
			"MWFType": this.json.type
		});
        var optionItems = this.getOptions();
        var value = this.getValue();
        if (value){
            if (typeOf(value)!=="array") value = [value];
            var texts = [];
            optionItems.each(function(item){
                var tmps = item.split("|");
                var t = tmps[0];
                var v = tmps[1] || t;

                if (v){

                    if (value.indexOf(v)!=-1){
                        texts.push(t);
                    }
                }

            });
            this.node.set("text", texts.join(", "));
        }
    },
	_loadDomEvents: function(){
		Object.each(this.json.events, function(e, key){
			if (e.code){
				if (this.options.moduleEvents.indexOf(key)===-1){
					this.node.addEvent(key, function(event){
						return this.form.Macro.fire(e.code, this, event);
					}.bind(this));
				}
			}
		}.bind(this));
	},
    _loadEvents: function(){
        Object.each(this.json.events, function(e, key){
            if (e.code){
                if (this.options.moduleEvents.indexOf(key)!=-1){
                    this.addEvent(key, function(event){
                        return this.form.Macro.fire(e.code, this, event);
                    }.bind(this));
                }else{
                    this.node.addEvent(key, function(event){
                        return this.form.Macro.fire(e.code, this, event);
                    }.bind(this));
                }
            }
        }.bind(this));
    },
	addModuleEvent: function(key, fun){
		if (this.options.moduleEvents.indexOf(key)!==-1){
			this.addEvent(key, function(event){
				return (fun) ? fun(this, event) : null;
			}.bind(this));
		}else{
			this.node.addEvent(key, function(event){
				return (fun) ? fun(this, event) : null;
			}.bind(this));
		}
	},
    _loadStyles: function(){
    	if (this.areaNode){
            if (this.json.styles) if (this.areaNode) this.areaNode.setStyles(this.json.styles);
            if (this.json.inputStyles) this.node.setStyles(this.json.inputStyles);
		}else{
            if (this.json.styles) this.node.setStyles(this.json.styles);
		}
    },
	_resetNodeEdit: function(){
		this.node.empty();
		var select = new Element("select");
		select.set(this.json.properties);
		select.inject(this.node);
	},
    _loadNodeEdit: function(){
		if (!this.json.preprocessing) this._resetNodeEdit();

		var select = this.node.getFirst();
		this.areaNode = this.node;
		this.node = select;

		this.node.set({
			"id": this.json.id,
			"MWFType": this.json.type,
			"styles": {
				"margin-right": "12px"
			}
		});

		this.setOptions();
        this.node.addEvent("change", function(){
			var v = this.getInputData("change");
			this._setBusinessData(v);
            this.validationMode();
            if (this.validation()) this._setBusinessData(v);
        }.bind(this));

	},
    resetOption: function(){
        this.node.empty();
        this.setOptions();
		this.fireEvent("resetOption")
    },
	getOptions: function(){
		if (this.json.itemType == "values"){
			return this.json.itemValues;
		}else{
			return this.form.Macro.exec(((this.json.itemScript) ? this.json.itemScript.code : ""), this);
		}
		return [];
	},
	setOptions: function(){
		var optionItems = this.getOptions();
		this._setOptions(optionItems);
	},
	_setOptions: function(optionItems){
		var p = o2.promiseAll(optionItems).then(function(options){
			this.moduleSelectAG = null;
			if (!options) options = [];
			if (o2.typeOf(options)==="array"){
				options.each(function(item){
					var tmps = item.split("|");
					var text = tmps[0];
					var value = tmps[1] || text;

					var option = new Element("option", {
						"value": value,
						"text": text
					}).inject(this.node);
				}.bind(this));
				this.fireEvent("setOptions", [options])
			}
		}.bind(this), function(){
			this.moduleSelectAG = null;
		}.bind(this));
		this.moduleSelectAG = p;
		if (p) p.then(function(){
			this.moduleSelectAG = null;
		}.bind(this), function(){
			this.moduleSelectAG = null;
		}.bind(this));

		// this.moduleSelectAG = o2.AG.all(optionItems).then(function(options){
		// 	this.moduleSelectAG = null;
		// 	if (!options) options = [];
		// 	if (o2.typeOf(options)==="array"){
		// 		options.each(function(item){
		// 			var tmps = item.split("|");
		// 			var text = tmps[0];
		// 			var value = tmps[1] || text;
		//
		// 			var option = new Element("option", {
		// 				"value": value,
		// 				"text": text
		// 			}).inject(this.node);
		// 		}.bind(this));
		// 		this.fireEvent("setOptions", [options])
		// 	}
		// }.bind(this));
		// if (this.moduleSelectAG) this.moduleSelectAG.then(function(){
		// 	this.moduleSelectAG = null;
		// }.bind(this));
	},
	// __setOptions: function(){
	// 	var optionItems = this.getOptions();
    //     if (!optionItems) optionItems = [];
    //     if (o2.typeOf(optionItems)==="array"){
	// 		optionItems.each(function(item){
	// 			var tmps = item.split("|");
	// 			var text = tmps[0];
	// 			var value = tmps[1] || text;
	//
	// 			var option = new Element("option", {
	// 				"value": value,
	// 				"text": text
	// 			}).inject(this.node);
	// 		}.bind(this));
	// 		this.fireEvent("setOptions", [optionItems])
	// 	}
	// },
	addOption: function(text, value){
        var option = new Element("option", {
            "value": value || text,
            "text": text
        }).inject(this.node);
		this.fireEvent("addOption", [text, value])
	},

	_setValue: function(value, m){
		var mothed = m || "__setValue";
		if (!!value){
			var p = o2.promiseAll(value).then(function(v){
				if (o2.typeOf(v)=="array") v = v[0];
				if (this.moduleSelectAG){
					this.moduleValueAG = this.moduleSelectAG;
					this.moduleSelectAG.then(function(){
						this[mothed](v);
						return v;
					}.bind(this), function(){});
				}else{
					this[mothed](v)
				}
				return v;
			}.bind(this), function(){});

			this.moduleValueAG = p;
			if (this.moduleValueAG) this.moduleValueAG.then(function(){
				this.moduleValueAG = null;
			}.bind(this), function(){
				this.moduleValueAG = null;
			}.bind(this));
		}else{
			this[mothed](value);
		}

		// this.moduleValueAG = o2.AG.all(value).then(function(v){
		// 	if (o2.typeOf(v)=="array") v = v[0];
		// 	if (this.moduleSelectAG){
		// 		this.moduleValueAG = this.moduleSelectAG;
		// 		this.moduleSelectAG.then(function(){
		// 			this.__setValue(v);
		// 		}.bind(this));
		// 	}else{
		// 		this.__setValue(v)
		// 	}
		// 	return v;
		// }.bind(this));

		// if (value && value.isAG){
		// 	this.moduleValueAG = o2.AG.all(value),then(function(v){
		// 		this._setValue(v);
		// 	}.bind(this));
		// 	// this.moduleValueAG = value;
		// 	// value.addResolve(function(v){
		// 	// 	this._setValue(v);
		// 	// }.bind(this));
		// }else{
		//
		// }
	},
	__setValue: function(value){
		if (!this.readonly && !this.json.isReadonly ) {
			this._setBusinessData(value);
			for (var i=0; i<this.node.options.length; i++){
				var option = this.node.options[i];
				if (option.value==value){
					option.selected = true;
					//	break;
				}else{
					option.selected = false;
				}
			}
		}
		this.moduleValueAG = null;
	},

	// _setValue: function(value){
	// 	if (!this.readonly && !this.json.isReadonly ) {
    //         this._setBusinessData(value);
    //         for (var i=0; i<this.node.options.length; i++){
    //             var option = this.node.options[i];
    //             if (option.value==value){
    //                 option.selected = true;
    //                 //	break;
    //             }else{
    //                 option.selected = false;
    //             }
    //         }
    //     }
	// 	//this.node.set("value", value);
	// },
	getTextData: function(){
		var value = [];
		var text = [];
		if (this.readonly|| this.json.isReadonly){
			var ops = this.getOptionsObj();
			var data = this._getBusinessData();
			var d = typeOf(data) === "array" ? data : [data];
			d.each( function (v) {
				var idx = ops.valueList.indexOf( v );
				value.push( v || "" );
				text.push( idx > -1 ? ops.textList[idx] : (v || "") );
			});
		}else{
			var ops = this.node.getElements("option");
			ops.each(function(op){
				if (op.selected){
					var v = op.get("value");
					var t = op.get("text");
					value.push(v || "");
					text.push(t || v || "");
				}
			});
		}
		if (!value.length) value = [""];
		if (!text.length) text = [""];
		return {"value": value, "text": text};
	},
    getInputData: function(){
		if( this.readonly || this.json.isReadonly ){
			return this._getBusinessData();
		}else{
			var ops = this.node.getElements("option");
			var value = [];
			ops.each(function(op){
				if (op.selected){
					var v = op.get("value");
					if (v) value.push(v);
				}
			});
			if (!value.length) return null;
			return (value.length==1) ? value[0] : value;
		}
	},
    resetData: function(){

        this.setData(this.getValue());
    },
	getOptionsObj : function(){
		var textList = [];
		var valueList = [];
		var optionItems = this.getOptions();
		if (!optionItems) optionItems = [];
		if (o2.typeOf(optionItems)==="array"){
			optionItems.each(function(item){
				var tmps = item.split("|");
				textList.push( tmps[0] );
				valueList.push( tmps[1] || tmps[0] );
			}.bind(this));
		}
		return { textList : textList, valueList : valueList };
	},

	setData: function(data){
		return this._setValue(data, "__setData");
		// if (data && data.isAG){
		// 	this.moduleValueAG = o2.AG.all(data).then(function(v){
		// 		if (o2.typeOf(v)=="array") v = v[0];
		// 		this.__setData(v);
		// 	}.bind(this));
		// }else{
		// 	this.__setData(data);
		// }
		// if (data && data.isAG){
		// 	this.moduleValueAG = data;
		// 	data.addResolve(function(v){
		// 		this.setData(v);
		// 	}.bind(this));
		// }else{
		// 	this.__setData(data);
		// 	this.moduleValueAG = null;
		// }
	},

	__setData: function(data){
        this._setBusinessData(data);
		if (this.readonly|| this.json.isReadonly){
			var d = typeOf(data) === "array" ? data : [data];
			var ops = this.getOptionsObj();
			var result = [];
			d.each( function (v) {
				var idx = ops.valueList.indexOf( v );
				result.push( idx > -1 ? ops.textList[idx] : v);
			})
			this.node.set("text", result.join(","));
		}else{
			var ops = this.node.getElements("option");
			ops.each(function(op){
				if (typeOf(data)=="array"){
					if (data.indexOf(op.get("value"))!=-1){
						op.set("selected", true);
					}else{
						op.set("selected", false);
					}
				}else{
					if (data == op.get("value")){
						op.set("selected", true);
					}else{
						op.set("selected", false);
					}
				}
			});
			this.validationMode();
		}
		this.fireEvent("setData", [data]);
	}

});
<|endoftext|>


<commit_before>/*
 * dropdownToggle - Provides dropdown menu functionality
 * @restrict class or attribute
 * @example:

   My Dropdown Menu

       {{choice.text}}

 */
angular.module('mm.foundation.dropdownToggle', [ 'mm.foundation.position', 'mm.foundation.mediaQueries' ])

.directive('dropdownToggle', ['$document', '$location', '$position', 'mediaQueries', function ($document, $location, $position, mediaQueries) {
  var openElement = null,
      closeMenu   = angular.noop;
  return {
    restrict: 'CA',
    scope: {
      dropdownToggle: '@'
    },
    link: function(scope, element, attrs) {
      var dropdown = angular.element($document[0].querySelector(scope.dropdownToggle));

      scope.$watch('$location.path', function() { closeMenu(); });
      element.bind('click', function (event) {
        dropdown = angular.element($document[0].querySelector(scope.dropdownToggle));
        var elementWasOpen = (element === openElement);

        event.preventDefault();
        event.stopPropagation();

        if (!!openElement) {
          closeMenu();
        }

        if (!elementWasOpen && !element.hasClass('disabled') && !element.prop('disabled')) {
          dropdown.css('display', 'block');

          var offset = $position.offset(element);
          var parentOffset = $position.offset(angular.element(dropdown[0].offsetParent));

          var offsetTop = offset.top - parentOffset.top + offset.height + 'px';

          if (mediaQueries.small() && !mediaQueries.medium()) {
            var dropdownWidth = dropdown.prop('offsetWidth');
            var offsetLeft = Math.max((parentOffset.width - dropdownWidth) / 2, 8);
            dropdown.css({
              position: 'absolute',
              width: '95%',
              'max-width': 'none',
              top: offsetTop,
              left: offsetLeft + 'px'
            });
          }
          else {
            dropdown.css({
              position: null,
              'max-width': null,
              left: offset.left - parentOffset.left + 'px',
              top: offsetTop
            });
          }

          openElement = element;
          closeMenu = function (event) {
            $document.unbind('click', closeMenu);
            dropdown.css('display', 'none');
            closeMenu = angular.noop;
            openElement = null;
          };
          $document.bind('click', closeMenu);
        }
      });

      if (dropdown) {
        dropdown.css('display', 'none');
      }
    }
  };
}]);
<commit_msg>fix(dropdownToggle): Dont overflow screen rightwards<commit_after>/*
 * dropdownToggle - Provides dropdown menu functionality
 * @restrict class or attribute
 * @example:

   My Dropdown Menu

       {{choice.text}}

 */
angular.module('mm.foundation.dropdownToggle', [ 'mm.foundation.position', 'mm.foundation.mediaQueries' ])

.controller('DropdownToggleController', ['$scope', '$attrs', 'mediaQueries', function($scope, $attrs, mediaQueries) {
  this.small = function() {
    return mediaQueries.small() && !mediaQueries.medium();
  }
}])

.directive('dropdownToggle', ['$document', '$window', '$location', '$position', function ($document, $window, $location, $position) {
  var openElement = null,
      closeMenu   = angular.noop;
  return {
    restrict: 'CA',
    scope: {
      dropdownToggle: '@'
    },
    controller: 'DropdownToggleController',
    link: function(scope, element, attrs, controller) {
      var dropdown = angular.element($document[0].querySelector(scope.dropdownToggle));

      scope.$watch('$location.path', function() { closeMenu(); });
      element.bind('click', function (event) {
        dropdown = angular.element($document[0].querySelector(scope.dropdownToggle));
        var elementWasOpen = (element === openElement);

        event.preventDefault();
        event.stopPropagation();

        if (!!openElement) {
          closeMenu();
        }

        if (!elementWasOpen && !element.hasClass('disabled') && !element.prop('disabled')) {
          dropdown.css('display', 'block');

          var offset = $position.offset(element);
          var parentOffset = $position.offset(angular.element(dropdown[0].offsetParent));

          var offsetTop = offset.top - parentOffset.top + offset.height + 'px';
          var dropdownWidth = dropdown.prop('offsetWidth');

          if (controller.small()) {
            var offsetLeft = Math.max((parentOffset.width - dropdownWidth) / 2, 8);
            dropdown.css({
              position: 'absolute',
              width: '95%',
              'max-width': 'none',
              top: offsetTop,
              left: offsetLeft + 'px'
            });
          }
          else {
            var offsetLeft = Math.round(offset.left - parentOffset.left);
            var rightThreshold = $window.innerWidth - dropdownWidth - 8;
            if (offsetLeft > rightThreshold) {
                offsetLeft = rightThreshold;
                dropdown.removeClass('left').addClass('right');
            }
            dropdown.css({
              position: null,
              'max-width': null,
              left: offsetLeft + 'px',
              top: offsetTop
            });
          }

          openElement = element;
          closeMenu = function (event) {
            $document.unbind('click', closeMenu);
            dropdown.css('display', 'none');
            closeMenu = angular.noop;
            openElement = null;
          };
          $document.bind('click', closeMenu);
        }
      });

      if (dropdown) {
        dropdown.css('display', 'none');
      }
    }
  };
}]);
<|endoftext|>


<commit_before>var appContext = "/opennms/";

function spaceTrans(stringIn) {
	var result = ""
	for (var i = 0; i < stringIn.length; i++) {
		if (stringIn.charAt(i) == " ") {
			result += "_x0020_"
		} else {
			result += stringIn.charAt(i)
		}
	}
	return result;
}

function escapeSpecialChars(strInput)
{
	strInput=strInput.replace(/&/g,"&");
	strInput=strInput.replace(/</g,"<");
	strInput=strInput.replace(/>/g,">");
	strInput=strInput.replace(/"/g,'"');
	strInput=strInput.replace(/'/g,"'");

	return(strInput);
}

function replaceSpecialChars(myString) {
		if(myString!=null){
			for (i=161;i<256;i++) {
				re = new RegExp("&#"+i+";","g");
				myString = myString.replace(re,String.fromCharCode(i));
			}
		}
		return myString;
}

function assArrayPopulate(arrayKeys,arrayValues) {
	var returnArray = new Array();
	if (arrayKeys.length != arrayValues.length) {
		alert("Error: arrays do not have same length");
	}
	else {
		for (i=0;i<arrayKeys.length;i++) {
			returnArray[arrayKeys[i]] = arrayValues[i];
		}
	}
	return returnArray;
}

function httpRequest()
{
    var xmlhttp;
    try {
        xmlhttp = new XMLHttpRequest();
    } catch (e) {
        xmlhttp = false;
    }
    if (!xmlhttp) {
        try {
            xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
            if (!xmlhttp) {
                try {
                    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e) {
                    xmlhttp = false;
                }
            }
        } catch (e) {
            xmlhttp = false;
        }
    }
    return xmlhttp;
}

function parseUri(sourceUri){
    var uriPartNames = ["source","protocol","authority","domain","port","path","directoryPath","fileName","query","anchor"];
    var uriParts = new RegExp("^(?:([^:/?#.]+):)?(?://)?(([^:/?#]*)(?::(\\d*))?)?((/(?:[^?#](?![^?#/]*\\.[^?#/.]+(?:[\\?#]|$)))*/?)?([^?#/]*))?(?:\\?([^#]*))?(?:#(.*))?").exec(sourceUri);
    var uri = {};

    for(var i = 0; i < 10; i++){
        uri[uriPartNames[i]] = (uriParts[i] ? uriParts[i] : "");
    }
    if(uri.directoryPath.length > 0){
        uri.directoryPath = uri.directoryPath.replace(/\/?$/, "/");
    }

    return uri;
}

function postMapRequest(url,data,handler,type,enc){
	postMapRequestAll(url,"GET", data,handler,type,enc, true);
}

function postMapRequestAll(url,method,data,handler,type,enc,async){
	   var uriObj = parseUri(document.URL);
	   var appdomain = uriObj.protocol+"://"+uriObj.authority;
	   var instantiationSuccess = true;
       var xmlhttp = new httpRequest();
       if (xmlhttp) {
           try{
	            xmlhttp.open(method, appContext+url, async);
	            xmlhttp.onreadystatechange = function() {
	                if (xmlhttp.readyState == 4) {
	                    handler({status:xmlhttp.status, content:xmlhttp.responseText, contentType:xmlhttp.getResponseHeader("Content-Type")});
	                }
	         	}
             	xmlhttp.send(data);
           }catch(e){
           		instantiationSuccess = false;
           }
       	}

   		if(instantiationSuccess==false){
	   		alert("Sorry, your browser/SVG viewer does not support XMLHttpRequest/ActiveXObject!");
   		}
}

//functions for matching ip with range in input
function ipmatch(ip, ipLike){
	var ottectsLike = ipLike.split(".");
	var ottectsIp = ip.split(".");
	return (ottectMatch(parseInt(ottectsIp[0]),ottectsLike[0]) && ottectMatch(parseInt(ottectsIp[1]), ottectsLike[1]) && ottectMatch(parseInt(ottectsIp[2]),ottectsLike[2]) && ottectMatch(parseInt(ottectsIp[3]),ottectsLike[3]) )

}

function ottectMatch(ott, ottLike){
	//alert(ott+" "+ ottLike);
	try{
	if(ottLike=="*"){
		if(ott<=255 && ott>=0)

		 	return true;

		return false;
	}
	if(ottLike.indexOf("-")>=0){
		var range = ottLike.split("-")
		var start=parseInt(range[0]);
		var end=parseInt(range[1]);
		if(start>end  || start>255 || end >255 ||start<0 || end<0)
			 return false;
		if(ott>=start && ott<=end)
			return true;
		return false;
	}
	if(ott==parseInt(ottLike))
		return true;
	return false;
	}catch(e){
		return false;
	}
}

function isValidOttect(ott){
	if(ott=="*"){
		return true;
	}
	if(ott.indexOf('-')>=0){
		var ottRange = ott.split('-');
		if(ottRange.length>2)
			return false;
		var start=parseInt(ottRange[0]);
		var end=parseInt(ottRange[1]);
		if(start<=end  && start<=255 && end <=255 && start>=0 && end>=0)
			 return true;

	}
	if(parseInt(ott)>=0 && parseInt(ott)<=255)
		return true;
	return false;
}

function isValidRange(range){
	var ottects = range.split(".");
	if(ottects.length!=4){
		return false;
	}
	return (isValidOttect(ottects[0]) && isValidOttect(ottects[1]) && isValidOttect(ottects[2]) && isValidOttect(ottects[3]));
}

function trimAll(sString)
{
	while (sString.substring(0,1) == ' ')
	{
		sString = sString.substring(1, sString.length);
	}
	while (sString.substring(sString.length-1, sString.length) == ' ')
	{
		sString = sString.substring(0,sString.length-1);
	}
	return sString;
}

function testResponse(action, response){
		var tmpStr=response.substring(0,action.length+2);
		if(tmpStr==(action+"OK"))
			return true;
		return false;
}

function openLink( link, params){
           var uriObj = parseUri(unescape(link));
	   if ( uriObj.protocol =='' ) {
	   	uriObj = parseUri(document.URL);
	   	var appdomain = uriObj.protocol+"://"+uriObj.authority;
       		open(appdomain+appContext+unescape(link), '', params);
           } else {
       		open(unescape(link), '', params);
           }
}
<commit_msg>If you want to use telnet in context menu now no unneeded window is required<commit_after>var appContext = "/opennms/";

function spaceTrans(stringIn) {
	var result = ""
	for (var i = 0; i < stringIn.length; i++) {
		if (stringIn.charAt(i) == " ") {
			result += "_x0020_"
		} else {
			result += stringIn.charAt(i)
		}
	}
	return result;
}

function escapeSpecialChars(strInput)
{
	strInput=strInput.replace(/&/g,"&");
	strInput=strInput.replace(/</g,"<");
	strInput=strInput.replace(/>/g,">");
	strInput=strInput.replace(/"/g,'"');
	strInput=strInput.replace(/'/g,"'");

	return(strInput);
}

function replaceSpecialChars(myString) {
		if(myString!=null){
			for (i=161;i<256;i++) {
				re = new RegExp("&#"+i+";","g");
				myString = myString.replace(re,String.fromCharCode(i));
			}
		}
		return myString;
}

function assArrayPopulate(arrayKeys,arrayValues) {
	var returnArray = new Array();
	if (arrayKeys.length != arrayValues.length) {
		alert("Error: arrays do not have same length");
	}
	else {
		for (i=0;i<arrayKeys.length;i++) {
			returnArray[arrayKeys[i]] = arrayValues[i];
		}
	}
	return returnArray;
}

function httpRequest()
{
    var xmlhttp;
    try {
        xmlhttp = new XMLHttpRequest();
    } catch (e) {
        xmlhttp = false;
    }
    if (!xmlhttp) {
        try {
            xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
            if (!xmlhttp) {
                try {
                    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e) {
                    xmlhttp = false;
                }
            }
        } catch (e) {
            xmlhttp = false;
        }
    }
    return xmlhttp;
}

function parseUri(sourceUri){
    var uriPartNames = ["source","protocol","authority","domain","port","path","directoryPath","fileName","query","anchor"];
    var uriParts = new RegExp("^(?:([^:/?#.]+):)?(?://)?(([^:/?#]*)(?::(\\d*))?)?((/(?:[^?#](?![^?#/]*\\.[^?#/.]+(?:[\\?#]|$)))*/?)?([^?#/]*))?(?:\\?([^#]*))?(?:#(.*))?").exec(sourceUri);
    var uri = {};

    for(var i = 0; i < 10; i++){
        uri[uriPartNames[i]] = (uriParts[i] ? uriParts[i] : "");
    }
    if(uri.directoryPath.length > 0){
        uri.directoryPath = uri.directoryPath.replace(/\/?$/, "/");
    }

    return uri;
}

function postMapRequest(url,data,handler,type,enc){
	postMapRequestAll(url,"GET", data,handler,type,enc, true);
}

function postMapRequestAll(url,method,data,handler,type,enc,async){
	   var uriObj = parseUri(document.URL);
	   var appdomain = uriObj.protocol+"://"+uriObj.authority;
	   var instantiationSuccess = true;
       var xmlhttp = new httpRequest();
       if (xmlhttp) {
           try{
	            xmlhttp.open(method, appContext+url, async);
	            xmlhttp.onreadystatechange = function() {
	                if (xmlhttp.readyState == 4) {
	                    handler({status:xmlhttp.status, content:xmlhttp.responseText, contentType:xmlhttp.getResponseHeader("Content-Type")});
	                }
	         	}
             	xmlhttp.send(data);
           }catch(e){
           		instantiationSuccess = false;
           }
       	}

   		if(instantiationSuccess==false){
	   		alert("Sorry, your browser/SVG viewer does not support XMLHttpRequest/ActiveXObject!");
   		}
}

//functions for matching ip with range in input
function ipmatch(ip, ipLike){
	var ottectsLike = ipLike.split(".");
	var ottectsIp = ip.split(".");
	return (ottectMatch(parseInt(ottectsIp[0]),ottectsLike[0]) && ottectMatch(parseInt(ottectsIp[1]), ottectsLike[1]) && ottectMatch(parseInt(ottectsIp[2]),ottectsLike[2]) && ottectMatch(parseInt(ottectsIp[3]),ottectsLike[3]) )

}

function ottectMatch(ott, ottLike){
	//alert(ott+" "+ ottLike);
	try{
	if(ottLike=="*"){
		if(ott<=255 && ott>=0)

		 	return true;

		return false;
	}
	if(ottLike.indexOf("-")>=0){
		var range = ottLike.split("-")
		var start=parseInt(range[0]);
		var end=parseInt(range[1]);
		if(start>end  || start>255 || end >255 ||start<0 || end<0)
			 return false;
		if(ott>=start && ott<=end)
			return true;
		return false;
	}
	if(ott==parseInt(ottLike))
		return true;
	return false;
	}catch(e){
		return false;
	}
}

function isValidOttect(ott){
	if(ott=="*"){
		return true;
	}
	if(ott.indexOf('-')>=0){
		var ottRange = ott.split('-');
		if(ottRange.length>2)
			return false;
		var start=parseInt(ottRange[0]);
		var end=parseInt(ottRange[1]);
		if(start<=end  && start<=255 && end <=255 && start>=0 && end>=0)
			 return true;

	}
	if(parseInt(ott)>=0 && parseInt(ott)<=255)
		return true;
	return false;
}

function isValidRange(range){
	var ottects = range.split(".");
	if(ottects.length!=4){
		return false;
	}
	return (isValidOttect(ottects[0]) && isValidOttect(ottects[1]) && isValidOttect(ottects[2]) && isValidOttect(ottects[3]));
}

function trimAll(sString)
{
	while (sString.substring(0,1) == ' ')
	{
		sString = sString.substring(1, sString.length);
	}
	while (sString.substring(sString.length-1, sString.length) == ' ')
	{
		sString = sString.substring(0,sString.length-1);
	}
	return sString;
}

function testResponse(action, response){
		var tmpStr=response.substring(0,action.length+2);
		if(tmpStr==(action+"OK"))
			return true;
		return false;
}

function openLink( link, params){
           var uriObj = parseUri(unescape(link));
	   if ( uriObj.protocol =='' ) {
	   	uriObj = parseUri(document.URL);
	   	var appdomain = uriObj.protocol+"://"+uriObj.authority;
       		open(appdomain+appContext+unescape(link), '', params);
           } else {
		if ( uriObj.protocol =='telnet' ) {
			window.location=unescape(link);
		} else {
       			open(unescape(link), '', params);
		}
           }
}
<|endoftext|>


<commit_before>var hostspotlighter = new function()
{
  const
  INITIAL_DIMENSION_COLOR = [54, 68, 130, .3 * 255],
  INITIAL_PADDING_COLOR = [54, 68, 130, .5 * 255],
  INITIAL_BORDER_COLOR = [54, 68, 130, .7 * 255],
  INITIAL_MARGIN_COLOR = [54, 68, 130, .9 * 255],
  INITIAL_FRAME_COLOR = [54, 68, 130, 1 * 255],
  INITIAL_GRID_COLOR = [170, 33, 18, .3 * 255];

  var self = this;
  var dimension_color = 0;
  var padding_color = 0;
  var border_color = 0;
  var margin_color = 0;
  var frame_color = 0;
  var grid_color = 0;

  var parse_int_16 = function(str)
  {
    return parseInt(str, 16);
  };

  var convert_hex = function(hex)
  {
    if(hex && hex.length == 8)
    {
      return /(..)(..)(..)(..)/.exec(hex).slice(1).map(parse_int_16);
    }
    return 0;
  }

  var convert_rgba = function(arr)
  {
    var i = 4, ret = 0;
    if(arr && arr.length == 4)
    {
      for( ; i--; )
      {
        ret += arr[3-i] << (i * 8);
      }
    }
    return ret;
  }

  var set_initial_values = function()
  {
    dimension_color = convert_rgba(INITIAL_DIMENSION_COLOR);
    padding_color = convert_rgba(INITIAL_PADDING_COLOR);
    border_color = convert_rgba(INITIAL_BORDER_COLOR);
    margin_color = convert_rgba(INITIAL_MARGIN_COLOR);
    frame_color = convert_rgba(INITIAL_FRAME_COLOR);
    grid_color = convert_rgba(INITIAL_GRID_COLOR);
  }

  this.setRGBA = function(target, rgba_arr)
  {

  }

  this.setHex = function(target, hex)
  {

  }

  this.spotlight = function(node_id, scroll_into_view)
  {
    services['ecmascript-debugger'].post
    (
      "<spotlight-objects>" +
        "<spotlight-object>" +
          "<object-id>" + node_id + "</object-id>" +
          "<scroll-into-view>" + ( scroll_into_view && 1 || 0 ) + "</scroll-into-view>" +
          "<box>" +
            "<box-type>2</box-type>" +
            "<fill-color>" + border_color + "</fill-color>" +
            "<frame-color>" + frame_color + "</frame-color>" +
            "<grid-color>" + grid_color + "</grid-color>" +
          "</box>"  +
          "<box>" +
            "<box-type>1</box-type>" +
            "<fill-color>" + padding_color + "</fill-color>" +
          "</box>"  +
          "<box>" +
            "<box-type>0</box-type>" +
            "<fill-color>" + dimension_color + "</fill-color>" +
          "</box>"  +
        "</spotlight-object>" +
      "</spotlight-objects>"
    );
  }

  this.clearSpotlight = function()
  {
    services['ecmascript-debugger'].post("<spotlight-objects/>");
  }

  set_initial_values();
}<commit_msg>added BOM to hostspotlighter.js<commit_after>var hostspotlighter = new function()
{
  const
  INITIAL_DIMENSION_COLOR = [54, 68, 130, .3 * 255],
  INITIAL_PADDING_COLOR = [54, 68, 130, .5 * 255],
  INITIAL_BORDER_COLOR = [54, 68, 130, .7 * 255],
  INITIAL_MARGIN_COLOR = [54, 68, 130, .9 * 255],
  INITIAL_FRAME_COLOR = [54, 68, 130, 1 * 255],
  INITIAL_GRID_COLOR = [170, 33, 18, .3 * 255];

  var self = this;
  var dimension_color = 0;
  var padding_color = 0;
  var border_color = 0;
  var margin_color = 0;
  var frame_color = 0;
  var grid_color = 0;

  var parse_int_16 = function(str)
  {
    return parseInt(str, 16);
  };

  var convert_hex = function(hex)
  {
    if(hex && hex.length == 8)
    {
      return /(..)(..)(..)(..)/.exec(hex).slice(1).map(parse_int_16);
    }
    return 0;
  }

  var convert_rgba = function(arr)
  {
    var i = 4, ret = 0;
    if(arr && arr.length == 4)
    {
      for( ; i--; )
      {
        ret += arr[3-i] << (i * 8);
      }
    }
    return ret;
  }

  var set_initial_values = function()
  {
    dimension_color = convert_rgba(INITIAL_DIMENSION_COLOR);
    padding_color = convert_rgba(INITIAL_PADDING_COLOR);
    border_color = convert_rgba(INITIAL_BORDER_COLOR);
    margin_color = convert_rgba(INITIAL_MARGIN_COLOR);
    frame_color = convert_rgba(INITIAL_FRAME_COLOR);
    grid_color = convert_rgba(INITIAL_GRID_COLOR);
  }

  this.setRGBA = function(target, rgba_arr)
  {

  }

  this.setHex = function(target, hex)
  {

  }

  this.spotlight = function(node_id, scroll_into_view)
  {
    services['ecmascript-debugger'].post
    (
      "<spotlight-objects>" +
        "<spotlight-object>" +
          "<object-id>" + node_id + "</object-id>" +
          "<scroll-into-view>" + ( scroll_into_view && 1 || 0 ) + "</scroll-into-view>" +
          "<box>" +
            "<box-type>2</box-type>" +
            "<fill-color>" + border_color + "</fill-color>" +
            "<frame-color>" + frame_color + "</frame-color>" +
            "<grid-color>" + grid_color + "</grid-color>" +
          "</box>"  +
          "<box>" +
            "<box-type>1</box-type>" +
            "<fill-color>" + padding_color + "</fill-color>" +
          "</box>"  +
          "<box>" +
            "<box-type>0</box-type>" +
            "<fill-color>" + dimension_color + "</fill-color>" +
          "</box>"  +
        "</spotlight-object>" +
      "</spotlight-objects>"
    );
  }

  this.clearSpotlight = function()
  {
    services['ecmascript-debugger'].post("<spotlight-objects/>");
  }

  set_initial_values();
}<|endoftext|>