<commit_before>define(['lib/codemirror/lib/codemirror'], function(CodeMirror) {
(function() {
  "use strict";

  CodeMirror.showHint = function(cm, getHints, options) {
    // We want a single cursor position.
    if (cm.somethingSelected()) return;
    if (getHints == null) getHints = cm.getHelper(cm.getCursor(), "hint");
    if (getHints == null) return;

    if (cm.state.completionActive) cm.state.completionActive.close();

    var completion = cm.state.completionActive = new Completion(cm, getHints, options || {});
    CodeMirror.signal(cm, "startCompletion", cm);
    if (completion.options.async)
      getHints(cm, function(hints) { completion.showHints(hints); }, completion.options);
    else
      return completion.showHints(getHints(cm, completion.options));
  };

  function Completion(cm, getHints, options) {
    this.cm = cm;
    this.getHints = getHints;
    this.options = options;
    this.widget = this.onClose = null;
  }

  Completion.prototype = {
    close: function() {
      if (!this.active()) return;
      this.cm.state.completionActive = null;

      if (this.widget) this.widget.close();
      if (this.onClose) this.onClose();
      CodeMirror.signal(this.cm, "endCompletion", this.cm);
    },

    active: function() {
      return this.cm.state.completionActive == this;
    },

    pick: function(data, i) {
      var completion = data.list[i];
      if (completion.hint) completion.hint(this.cm, data, completion);
      else this.cm.replaceRange(getText(completion), data.from, data.to);
      this.close();
    },

    showHints: function(data) {
      if (!data || !data.list.length || !this.active()) return this.close();

      if (this.options.completeSingle != false && data.list.length == 1)
        this.pick(data, 0);
      else {
        if (data.list.length === 1) {
          if (this.cm.getTokenAt(this.cm.getCursor()).string === data.list[0].text) {
            return;
          }
        }
        this.showWidget(data);
      }
    },

    showWidget: function(data) {
      this.widget = new Widget(this, data);
      CodeMirror.signal(data, "shown");

      var debounce = null, completion = this, finished;
      var closeOn = this.options.closeCharacters || /[\s()\[\]{};:>,]/;
      var startPos = this.cm.getCursor(), startLen = this.cm.getLine(startPos.line).length;

      function done() {
        if (finished) return;
        finished = true;
        completion.close();
        completion.cm.off("cursorActivity", activity);
        if (data) CodeMirror.signal(data, "close");
      }

      function update() {
        if (finished) return;
        CodeMirror.signal(data, "update");
        if (completion.options.async)
          completion.getHints(completion.cm, finishUpdate, completion.options);
        else
          finishUpdate(completion.getHints(completion.cm, completion.options));
      }
      function finishUpdate(data_) {
        data = data_;
        if (finished) return;
        if (!data || !data.list.length) return done();
        completion.widget = new Widget(completion, data);
      }

      function activity() {
        clearTimeout(debounce);
        var pos = completion.cm.getCursor(), line = completion.cm.getLine(pos.line);
        if (pos.line != startPos.line || line.length - pos.ch != startLen - startPos.ch ||
            pos.ch < startPos.ch || completion.cm.somethingSelected() ||
            (pos.ch && closeOn.test(line.charAt(pos.ch - 1)))) {
          completion.close();
        } else {
          debounce = setTimeout(update, 170);
          if (completion.widget) completion.widget.close();
        }
      }
      this.cm.on("cursorActivity", activity);
      this.onClose = done;
    }
  };

  function getText(completion) {
    if (typeof completion == "string") return completion;
    else return completion.text;
  }

  function buildKeyMap(options, handle) {
    var baseMap = {
      Up: function() {handle.moveFocus(-1);},
      Down: function() {handle.moveFocus(1);},
      PageUp: function() {handle.moveFocus(-handle.menuSize() + 1, true);},
      PageDown: function() {handle.moveFocus(handle.menuSize() - 1, true);},
      Home: function() {handle.setFocus(0);},
      End: function() {handle.setFocus(handle.length - 1);},
      Enter: handle.pick,
      Tab: handle.pick,
      Esc: handle.close
    };
    var ourMap = options.customKeys ? {} : baseMap;
    function addBinding(key, val) {
      var bound;
      if (typeof val != "string")
        bound = function(cm) { return val(cm, handle); };
      // This mechanism is deprecated
      else if (baseMap.hasOwnProperty(val))
        bound = baseMap[val];
      else
        bound = val;
      ourMap[key] = bound;
    }
    if (options.customKeys)
      for (var key in options.customKeys) if (options.customKeys.hasOwnProperty(key))
        addBinding(key, options.customKeys[key]);
    if (options.extraKeys)
      for (var key in options.extraKeys) if (options.extraKeys.hasOwnProperty(key))
        addBinding(key, options.extraKeys[key]);
    return ourMap;
  }

  function Widget(completion, data) {
    this.completion = completion;
    this.data = data;
    var widget = this, cm = completion.cm, options = completion.options;

    var hints = this.hints = document.createElement("ul");
    hints.className = "CodeMirror-hints";
    this.selectedHint = 0;

    var completions = data.list;
    for (var i = 0; i < completions.length; ++i) {
      var elt = hints.appendChild(document.createElement("li")), cur = completions[i];
      var className = "CodeMirror-hint" + (i ? "" : " CodeMirror-hint-active");
      if (cur.className != null) className = cur.className + " " + className;
      elt.className = className;
      if (cur.render) cur.render(elt, data, cur);
      else elt.appendChild(document.createTextNode(cur.displayText || getText(cur)));
      elt.hintId = i;
    }

    var pos = cm.cursorCoords(options.alignWithWord !== false ? data.from : null);
    var left = pos.left, top = pos.bottom, below = true;
    hints.style.left = left + "px";
    hints.style.top = top + "px";
    // If we're at the edge of the screen, then we want the menu to appear on the left of the cursor.
    var winW = window.innerWidth || Math.max(document.body.offsetWidth, document.documentElement.offsetWidth);
    var winH = window.innerHeight || Math.max(document.body.offsetHeight, document.documentElement.offsetHeight);
    (options.container || document.body).appendChild(hints);
    var box = hints.getBoundingClientRect();
    var overlapX = box.right - winW, overlapY = box.bottom - winH;
    if (overlapX > 0) {
      if (box.right - box.left > winW) {
        hints.style.width = (winW - 5) + "px";
        overlapX -= (box.right - box.left) - winW;
      }
      hints.style.left = (left = pos.left - overlapX) + "px";
    }
    if (overlapY > 0) {
      var height = box.bottom - box.top;
      if (box.top - (pos.bottom - pos.top) - height > 0) {
        overlapY = height + (pos.bottom - pos.top);
        below = false;
      } else if (height > winH) {
        hints.style.height = (winH - 5) + "px";
        overlapY -= height - winH;
      }
      hints.style.top = (top = pos.bottom - overlapY) + "px";
    }

    cm.addKeyMap(this.keyMap = buildKeyMap(options, {
      moveFocus: function(n, avoidWrap) { widget.changeActive(widget.selectedHint + n, avoidWrap); },
      setFocus: function(n) { widget.changeActive(n); },
      menuSize: function() { return widget.screenAmount(); },
      length: completions.length,
      close: function() { completion.close(); },
      pick: function() { widget.pick(); }
    }));

    if (options.closeOnUnfocus !== false) {
      var closingOnBlur;
      cm.on("blur", this.onBlur = function() { closingOnBlur = setTimeout(function() { completion.close(); }, 100); });
      cm.on("focus", this.onFocus = function() { clearTimeout(closingOnBlur); });
    }

    var startScroll = cm.getScrollInfo();
    cm.on("scroll", this.onScroll = function() {
      var curScroll = cm.getScrollInfo(), editor = cm.getWrapperElement().getBoundingClientRect();
      var newTop = top + startScroll.top - curScroll.top;
      var point = newTop - (window.pageYOffset || (document.documentElement || document.body).scrollTop);
      if (!below) point += hints.offsetHeight;
      if (point <= editor.top || point >= editor.bottom) return completion.close();
      hints.style.top = newTop + "px";
      hints.style.left = (left + startScroll.left - curScroll.left) + "px";
    });

    CodeMirror.on(hints, "dblclick", function(e) {
      var t = e.target || e.srcElement;
      if (t.hintId != null) {widget.changeActive(t.hintId); widget.pick();}
    });
    CodeMirror.on(hints, "click", function(e) {
      var t = e.target || e.srcElement;
      if (t.hintId != null) widget.changeActive(t.hintId);
    });
    CodeMirror.on(hints, "mousedown", function() {
      setTimeout(function(){cm.focus();}, 20);
    });

    CodeMirror.signal(data, "select", completions[0], hints.firstChild);
    return true;
  }

  Widget.prototype = {
    close: function() {
      if (this.completion.widget != this) return;
      this.completion.widget = null;
      this.hints.parentNode.removeChild(this.hints);
      this.completion.cm.removeKeyMap(this.keyMap);

      var cm = this.completion.cm;
      if (this.completion.options.closeOnUnfocus !== false) {
        cm.off("blur", this.onBlur);
        cm.off("focus", this.onFocus);
      }
      cm.off("scroll", this.onScroll);
    },

    pick: function() {
      this.completion.pick(this.data, this.selectedHint);
    },

    changeActive: function(i, avoidWrap) {
      if (i >= this.data.list.length)
        i = avoidWrap ? this.data.list.length - 1 : 0;
      else if (i < 0)
        i = avoidWrap ? 0  : this.data.list.length - 1;
      if (this.selectedHint == i) return;
      var node = this.hints.childNodes[this.selectedHint];
      node.className = node.className.replace(" CodeMirror-hint-active", "");
      node = this.hints.childNodes[this.selectedHint = i];
      node.className += " CodeMirror-hint-active";
      if (node.offsetTop < this.hints.scrollTop)
        this.hints.scrollTop = node.offsetTop - 3;
      else if (node.offsetTop + node.offsetHeight > this.hints.scrollTop + this.hints.clientHeight)
        this.hints.scrollTop = node.offsetTop + node.offsetHeight - this.hints.clientHeight + 3;
      CodeMirror.signal(this.data, "select", this.data.list[this.selectedHint], node);
    },

    screenAmount: function() {
      return Math.floor(this.hints.clientHeight / this.hints.firstChild.offsetHeight) || 1;
    }
  };
})();
});
<commit_msg>bugfixed - sometimes completion popup remains unclosed<commit_after>define(['lib/codemirror/lib/codemirror'], function(CodeMirror) {
(function() {
  "use strict";

  CodeMirror.showHint = function(cm, getHints, options) {
    // We want a single cursor position.
    if (cm.somethingSelected()) return;
    if (getHints == null) getHints = cm.getHelper(cm.getCursor(), "hint");
    if (getHints == null) return;

    if (cm.state.completionActive) cm.state.completionActive.close();

    var completion = cm.state.completionActive = new Completion(cm, getHints, options || {});
    CodeMirror.signal(cm, "startCompletion", cm);
    if (completion.options.async)
      getHints(cm, function(hints) { completion.showHints(hints); }, completion.options);
    else
      return completion.showHints(getHints(cm, completion.options));
  };

  function Completion(cm, getHints, options) {
    this.cm = cm;
    this.getHints = getHints;
    this.options = options;
    this.widget = this.onClose = null;
  }

  Completion.prototype = {
    close: function() {
      if (!this.active()) return;
      this.cm.state.completionActive = null;

      if (this.widget) this.widget.close();
      if (this.onClose) this.onClose();
      CodeMirror.signal(this.cm, "endCompletion", this.cm);
    },

    active: function() {
      return this.cm.state.completionActive == this;
    },

    pick: function(data, i) {
      var completion = data.list[i];
      if (completion.hint) completion.hint(this.cm, data, completion);
      else this.cm.replaceRange(getText(completion), data.from, data.to);
      this.close();
    },

    showHints: function(data) {
      if (!data || !data.list.length || !this.active()) return this.close();

      if (this.options.completeSingle != false && data.list.length == 1)
        this.pick(data, 0);
      else {
        if (data.list.length === 1) {
          if (this.cm.getTokenAt(this.cm.getCursor()).string === data.list[0].text) {
            return;
          }
        }
        this.showWidget(data);
      }
    },

    showWidget: function(data) {
      this.widget = new Widget(this, data);
      CodeMirror.signal(data, "shown");

      var debounce = null, completion = this, finished;
      var closeOn = this.options.closeCharacters || /[\s()\[\]{};:>,]/;
      var startPos = this.cm.getCursor(), startLen = this.cm.getLine(startPos.line).length;

      function done() {
        if (finished) return;
        finished = true;
        completion.close();
        completion.cm.off("cursorActivity", activity);
        if (data) CodeMirror.signal(data, "close");
      }

      function update() {
        if (finished) return;
        CodeMirror.signal(data, "update");
        if (completion.options.async)
          completion.getHints(completion.cm, finishUpdate, completion.options);
        else
          finishUpdate(completion.getHints(completion.cm, completion.options));
      }
      function finishUpdate(data_) {
        data = data_;
        if (finished) return;
        if (!data || !data.list.length) return done();
        if (completion.widget) {
          completion.widget.close();
        }
        completion.widget = new Widget(completion, data);
      }

      function activity() {
        clearTimeout(debounce);
        var pos = completion.cm.getCursor(), line = completion.cm.getLine(pos.line);
        if (pos.line != startPos.line || line.length - pos.ch != startLen - startPos.ch ||
            pos.ch < startPos.ch || completion.cm.somethingSelected() ||
            (pos.ch && closeOn.test(line.charAt(pos.ch - 1)))) {
          completion.close();
        } else {
          debounce = setTimeout(update, 170);
          if (completion.widget) completion.widget.close();
        }
      }
      this.cm.on("cursorActivity", activity);
      this.onClose = done;
    }
  };

  function getText(completion) {
    if (typeof completion == "string") return completion;
    else return completion.text;
  }

  function buildKeyMap(options, handle) {
    var baseMap = {
      Up: function() {handle.moveFocus(-1);},
      Down: function() {handle.moveFocus(1);},
      PageUp: function() {handle.moveFocus(-handle.menuSize() + 1, true);},
      PageDown: function() {handle.moveFocus(handle.menuSize() - 1, true);},
      Home: function() {handle.setFocus(0);},
      End: function() {handle.setFocus(handle.length - 1);},
      Enter: handle.pick,
      Tab: handle.pick,
      Esc: handle.close
    };
    var ourMap = options.customKeys ? {} : baseMap;
    function addBinding(key, val) {
      var bound;
      if (typeof val != "string")
        bound = function(cm) { return val(cm, handle); };
      // This mechanism is deprecated
      else if (baseMap.hasOwnProperty(val))
        bound = baseMap[val];
      else
        bound = val;
      ourMap[key] = bound;
    }
    if (options.customKeys)
      for (var key in options.customKeys) if (options.customKeys.hasOwnProperty(key))
        addBinding(key, options.customKeys[key]);
    if (options.extraKeys)
      for (var key in options.extraKeys) if (options.extraKeys.hasOwnProperty(key))
        addBinding(key, options.extraKeys[key]);
    return ourMap;
  }

  function Widget(completion, data) {
    this.completion = completion;
    this.data = data;
    var widget = this, cm = completion.cm, options = completion.options;

    var hints = this.hints = document.createElement("ul");
    hints.className = "CodeMirror-hints";
    this.selectedHint = 0;

    var completions = data.list;
    for (var i = 0; i < completions.length; ++i) {
      var elt = hints.appendChild(document.createElement("li")), cur = completions[i];
      var className = "CodeMirror-hint" + (i ? "" : " CodeMirror-hint-active");
      if (cur.className != null) className = cur.className + " " + className;
      elt.className = className;
      if (cur.render) cur.render(elt, data, cur);
      else elt.appendChild(document.createTextNode(cur.displayText || getText(cur)));
      elt.hintId = i;
    }

    var pos = cm.cursorCoords(options.alignWithWord !== false ? data.from : null);
    var left = pos.left, top = pos.bottom, below = true;
    hints.style.left = left + "px";
    hints.style.top = top + "px";
    // If we're at the edge of the screen, then we want the menu to appear on the left of the cursor.
    var winW = window.innerWidth || Math.max(document.body.offsetWidth, document.documentElement.offsetWidth);
    var winH = window.innerHeight || Math.max(document.body.offsetHeight, document.documentElement.offsetHeight);
    (options.container || document.body).appendChild(hints);
    var box = hints.getBoundingClientRect();
    var overlapX = box.right - winW, overlapY = box.bottom - winH;
    if (overlapX > 0) {
      if (box.right - box.left > winW) {
        hints.style.width = (winW - 5) + "px";
        overlapX -= (box.right - box.left) - winW;
      }
      hints.style.left = (left = pos.left - overlapX) + "px";
    }
    if (overlapY > 0) {
      var height = box.bottom - box.top;
      if (box.top - (pos.bottom - pos.top) - height > 0) {
        overlapY = height + (pos.bottom - pos.top);
        below = false;
      } else if (height > winH) {
        hints.style.height = (winH - 5) + "px";
        overlapY -= height - winH;
      }
      hints.style.top = (top = pos.bottom - overlapY) + "px";
    }

    cm.addKeyMap(this.keyMap = buildKeyMap(options, {
      moveFocus: function(n, avoidWrap) { widget.changeActive(widget.selectedHint + n, avoidWrap); },
      setFocus: function(n) { widget.changeActive(n); },
      menuSize: function() { return widget.screenAmount(); },
      length: completions.length,
      close: function() { completion.close(); },
      pick: function() { widget.pick(); }
    }));

    if (options.closeOnUnfocus !== false) {
      var closingOnBlur;
      cm.on("blur", this.onBlur = function() { closingOnBlur = setTimeout(function() { completion.close(); }, 100); });
      cm.on("focus", this.onFocus = function() { clearTimeout(closingOnBlur); });
    }

    var startScroll = cm.getScrollInfo();
    cm.on("scroll", this.onScroll = function() {
      var curScroll = cm.getScrollInfo(), editor = cm.getWrapperElement().getBoundingClientRect();
      var newTop = top + startScroll.top - curScroll.top;
      var point = newTop - (window.pageYOffset || (document.documentElement || document.body).scrollTop);
      if (!below) point += hints.offsetHeight;
      if (point <= editor.top || point >= editor.bottom) return completion.close();
      hints.style.top = newTop + "px";
      hints.style.left = (left + startScroll.left - curScroll.left) + "px";
    });

    CodeMirror.on(hints, "dblclick", function(e) {
      var t = e.target || e.srcElement;
      if (t.hintId != null) {widget.changeActive(t.hintId); widget.pick();}
    });
    CodeMirror.on(hints, "click", function(e) {
      var t = e.target || e.srcElement;
      if (t.hintId != null) widget.changeActive(t.hintId);
    });
    CodeMirror.on(hints, "mousedown", function() {
      setTimeout(function(){cm.focus();}, 20);
    });

    CodeMirror.signal(data, "select", completions[0], hints.firstChild);
    return true;
  }

  Widget.prototype = {
    close: function() {
      if (this.completion.widget != this) return;
      this.completion.widget = null;
      this.hints.parentNode.removeChild(this.hints);
      this.completion.cm.removeKeyMap(this.keyMap);

      var cm = this.completion.cm;
      if (this.completion.options.closeOnUnfocus !== false) {
        cm.off("blur", this.onBlur);
        cm.off("focus", this.onFocus);
      }
      cm.off("scroll", this.onScroll);
    },

    pick: function() {
      this.completion.pick(this.data, this.selectedHint);
    },

    changeActive: function(i, avoidWrap) {
      if (i >= this.data.list.length)
        i = avoidWrap ? this.data.list.length - 1 : 0;
      else if (i < 0)
        i = avoidWrap ? 0  : this.data.list.length - 1;
      if (this.selectedHint == i) return;
      var node = this.hints.childNodes[this.selectedHint];
      node.className = node.className.replace(" CodeMirror-hint-active", "");
      node = this.hints.childNodes[this.selectedHint = i];
      node.className += " CodeMirror-hint-active";
      if (node.offsetTop < this.hints.scrollTop)
        this.hints.scrollTop = node.offsetTop - 3;
      else if (node.offsetTop + node.offsetHeight > this.hints.scrollTop + this.hints.clientHeight)
        this.hints.scrollTop = node.offsetTop + node.offsetHeight - this.hints.clientHeight + 3;
      CodeMirror.signal(this.data, "select", this.data.list[this.selectedHint], node);
    },

    screenAmount: function() {
      return Math.floor(this.hints.clientHeight / this.hints.firstChild.offsetHeight) || 1;
    }
  };
})();
});
<|endoftext|>


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

  CodeMirror.showHint = function(cm, getHints, options) {
    // We want a single cursor position.
    if (cm.somethingSelected()) return;

    if (cm.state.completionActive) cm.state.completionActive.close();

    var completion = cm.state.completionActive = new Completion(cm, getHints, options || {});
    CodeMirror.signal(cm, "startCompletion", cm);
    if (completion.options.async)
      getHints(cm, function(hints) { completion.showHints(hints); }, completion.options);
    else
      return completion.showHints(getHints(cm, completion.options));
  };

  function Completion(cm, getHints, options) {
    this.cm = cm;
    this.getHints = getHints;
    this.options = options;
    this.widget = null;
  }

  Completion.prototype = {
    close: function() {
      if (!this.active()) return;

      if (this.widget) this.widget.close();
      this.cm.state.completionActive = null;
      CodeMirror.signal(this.cm, "endCompletion", this.cm);
    },

    active: function() {
      return this.cm.state.completionActive == this;
    },

    pick: function(data, i) {
      var completion = data.list[i];
      if (completion.hint) completion.hint(this.cm, data, completion);
      else this.cm.replaceRange(getText(completion), data.from, data.to);
      this.close();
    },

    showHints: function(data) {
      if (!data || !data.list.length || !this.active()) return this.close();

      if (this.options.completeSingle != false && data.list.length == 1)
        this.pick(data, 0);
      else
        this.showWidget(data);
    },

    showWidget: function(data) {
      this.widget = new Widget(this, data);
      CodeMirror.signal(data, "shown");

      var debounce = null, completion = this, finished;
      var closeOn = this.options.closeCharacters || /[\s()\[\]{};:>,]/;
      var startPos = this.cm.getCursor(), startLen = this.cm.getLine(startPos.line).length;

      function done() {
        if (finished) return;
        finished = true;
        completion.close();
        completion.cm.off("cursorActivity", activity);
        CodeMirror.signal(data, "close");
      }
      function isDone() {
        if (finished) return true;
        if (!completion.widget) { done(); return true; }
      }

      function update() {
        if (isDone()) return;
        if (completion.options.async)
          completion.getHints(completion.cm, finishUpdate, completion.options);
        else
          finishUpdate(completion.getHints(completion.cm, completion.options));
      }
      function finishUpdate(data) {
        if (isDone()) return;
        if (!data || !data.list.length) return done();
        completion.widget.close();
        completion.widget = new Widget(completion, data);
      }

      function activity() {
        clearTimeout(debounce);
        var pos = completion.cm.getCursor(), line = completion.cm.getLine(pos.line);
        if (pos.line != startPos.line || line.length - pos.ch != startLen - startPos.ch ||
            pos.ch < startPos.ch || completion.cm.somethingSelected() ||
            (pos.ch && closeOn.test(line.charAt(pos.ch - 1))))
          completion.close();
        else
          debounce = setTimeout(update, 170);
      }
      this.cm.on("cursorActivity", activity);
    }
  };

  function getText(completion) {
    if (typeof completion == "string") return completion;
    else return completion.text;
  }

  function buildKeyMap(options, handle) {
    var baseMap = {
      Up: function() {handle.moveFocus(-1);},
      Down: function() {handle.moveFocus(1);},
      PageUp: function() {handle.moveFocus(-handle.menuSize());},
      PageDown: function() {handle.moveFocus(handle.menuSize());},
      Home: function() {handle.setFocus(0);},
      End: function() {handle.setFocus(handle.length);},
      Enter: handle.pick,
      Tab: handle.pick,
      Esc: handle.close
    };
    var ourMap = options.customKeys ? {} : baseMap;
    function addBinding(key, val) {
      var bound;
      if (typeof val != "string")
        bound = function(cm) { return val(cm, handle); };
      // This mechanism is deprecated
      else if (baseMap.hasOwnProperty(val))
        bound = baseMap[val];
      else
        bound = val;
      ourMap[key] = bound;
    }
    if (options.customKeys)
      for (var key in options.customKeys) if (options.customKeys.hasOwnProperty(key))
        addBinding(key, options.customKeys[key]);
    if (options.extraKeys)
      for (var key in options.extraKeys) if (options.extraKeys.hasOwnProperty(key))
        addBinding(key, options.extraKeys[key]);
    return ourMap;
  }

  function Widget(completion, data) {
    this.completion = completion;
    this.data = data;
    var widget = this, cm = completion.cm, options = completion.options;

    var hints = this.hints = document.createElement("ul");
    hints.className = "CodeMirror-hints";
    this.selectedHint = 0;

    var completions = data.list;
    for (var i = 0; i < completions.length; ++i) {
      var elt = hints.appendChild(document.createElement("li")), cur = completions[i];
      var className = "CodeMirror-hint" + (i ? "" : " CodeMirror-hint-active");
      if (cur.className != null) className = cur.className + " " + className;
      elt.className = className;
      if (cur.render) cur.render(elt, data, cur);
      else elt.appendChild(document.createTextNode(cur.displayText || getText(cur)));
      elt.hintId = i;
    }

    var pos = cm.cursorCoords(options.alignWithWord !== false ? data.from : null);
    var left = pos.left, top = pos.bottom, below = true;
    hints.style.left = left + "px";
    hints.style.top = top + "px";
    // If we're at the edge of the screen, then we want the menu to appear on the left of the cursor.
    var winW = window.innerWidth || Math.max(document.body.offsetWidth, document.documentElement.offsetWidth);
    var winH = window.innerHeight || Math.max(document.body.offsetHeight, document.documentElement.offsetHeight);
    var box = hints.getBoundingClientRect();
    var overlapX = box.right - winW, overlapY = box.bottom - winH;
    if (overlapX > 0) {
      if (box.right - box.left > winW) {
        hints.style.width = (winW - 5) + "px";
        overlapX -= (box.right - box.left) - winW;
      }
      hints.style.left = (left = pos.left - overlapX) + "px";
    }
    if (overlapY > 0) {
      var height = box.bottom - box.top;
      if (box.top - (pos.bottom - pos.top) - height > 0) {
        overlapY = height + (pos.bottom - pos.top);
        below = false;
      } else if (height > winH) {
        hints.style.height = (winH - 5) + "px";
        overlapY -= height - winH;
      }
      hints.style.top = (top = pos.bottom - overlapY) + "px";
    }
    (options.container || document.body).appendChild(hints);

    cm.addKeyMap(this.keyMap = buildKeyMap(options, {
      moveFocus: function(n) { widget.changeActive(widget.selectedHint + n); },
      setFocus: function(n) { widget.changeActive(n); },
      menuSize: function() { return widget.screenAmount(); },
      length: completions.length,
      close: function() { completion.close(); },
      pick: function() { widget.pick(); }
    }));

    if (options.closeOnUnfocus !== false) {
      var closingOnBlur;
      cm.on("blur", this.onBlur = function() { closingOnBlur = setTimeout(function() { completion.close(); }, 100); });
      cm.on("focus", this.onFocus = function() { clearTimeout(closingOnBlur); });
    }

    var startScroll = cm.getScrollInfo();
    cm.on("scroll", this.onScroll = function() {
      var curScroll = cm.getScrollInfo(), editor = cm.getWrapperElement().getBoundingClientRect();
      var newTop = top + startScroll.top - curScroll.top;
      var point = newTop - (window.pageYOffset || (document.documentElement || document.body).scrollTop);
      if (!below) point += hints.offsetHeight;
      if (point <= editor.top || point >= editor.bottom) return completion.close();
      hints.style.top = newTop + "px";
      hints.style.left = (left + startScroll.left - curScroll.left) + "px";
    });

    CodeMirror.on(hints, "dblclick", function(e) {
      var t = e.target || e.srcElement;
      if (t.hintId != null) {widget.changeActive(t.hintId); widget.pick();}
    });
    CodeMirror.on(hints, "click", function(e) {
      var t = e.target || e.srcElement;
      if (t.hintId != null) widget.changeActive(t.hintId);
    });
    CodeMirror.on(hints, "mousedown", function() {
      setTimeout(function(){cm.focus();}, 20);
    });

    CodeMirror.signal(data, "select", completions[0], hints.firstChild);
    return true;
  }

  Widget.prototype = {
    close: function() {
      if (this.completion.widget != this) return;
      this.completion.widget = null;
      this.hints.parentNode.removeChild(this.hints);
      this.completion.cm.removeKeyMap(this.keyMap);

      var cm = this.completion.cm;
      if (this.completion.options.closeOnUnfocus !== false) {
        cm.off("blur", this.onBlur);
        cm.off("focus", this.onFocus);
      }
      cm.off("scroll", this.onScroll);
    },

    pick: function() {
      this.completion.pick(this.data, this.selectedHint);
    },

    changeActive: function(i) {
      i = Math.max(0, Math.min(i, this.data.list.length - 1));
      if (this.selectedHint == i) return;
      var node = this.hints.childNodes[this.selectedHint];
      node.className = node.className.replace(" CodeMirror-hint-active", "");
      node = this.hints.childNodes[this.selectedHint = i];
      node.className += " CodeMirror-hint-active";
      if (node.offsetTop < this.hints.scrollTop)
        this.hints.scrollTop = node.offsetTop - 3;
      else if (node.offsetTop + node.offsetHeight > this.hints.scrollTop + this.hints.clientHeight)
        this.hints.scrollTop = node.offsetTop + node.offsetHeight - this.hints.clientHeight + 3;
      CodeMirror.signal(this.data, "select", this.data.list[this.selectedHint], node);
    },

    screenAmount: function() {
      return Math.floor(this.hints.clientHeight / this.hints.firstChild.offsetHeight) || 1;
    }
  };
})();
<commit_msg>[show-hint addon] Fix problem with close event firing too late<commit_after>(function() {
  "use strict";

  CodeMirror.showHint = function(cm, getHints, options) {
    // We want a single cursor position.
    if (cm.somethingSelected()) return;

    if (cm.state.completionActive) cm.state.completionActive.close();

    var completion = cm.state.completionActive = new Completion(cm, getHints, options || {});
    CodeMirror.signal(cm, "startCompletion", cm);
    if (completion.options.async)
      getHints(cm, function(hints) { completion.showHints(hints); }, completion.options);
    else
      return completion.showHints(getHints(cm, completion.options));
  };

  function Completion(cm, getHints, options) {
    this.cm = cm;
    this.getHints = getHints;
    this.options = options;
    this.widget = this.onClose = null;
  }

  Completion.prototype = {
    close: function() {
      if (!this.active()) return;

      if (this.widget) this.widget.close();
      if (this.onClose) this.onClose();
      this.cm.state.completionActive = null;
      CodeMirror.signal(this.cm, "endCompletion", this.cm);
    },

    active: function() {
      return this.cm.state.completionActive == this;
    },

    pick: function(data, i) {
      var completion = data.list[i];
      if (completion.hint) completion.hint(this.cm, data, completion);
      else this.cm.replaceRange(getText(completion), data.from, data.to);
      this.close();
    },

    showHints: function(data) {
      if (!data || !data.list.length || !this.active()) return this.close();

      if (this.options.completeSingle != false && data.list.length == 1)
        this.pick(data, 0);
      else
        this.showWidget(data);
    },

    showWidget: function(data) {
      this.widget = new Widget(this, data);
      CodeMirror.signal(data, "shown");

      var debounce = null, completion = this, finished;
      var closeOn = this.options.closeCharacters || /[\s()\[\]{};:>,]/;
      var startPos = this.cm.getCursor(), startLen = this.cm.getLine(startPos.line).length;

      function done() {
        if (finished) return;
        finished = true;
        completion.close();
        completion.cm.off("cursorActivity", activity);
        CodeMirror.signal(data, "close");
      }
      function isDone() {
        if (finished) return true;
        if (!completion.widget) { done(); return true; }
      }

      function update() {
        if (isDone()) return;
        if (completion.options.async)
          completion.getHints(completion.cm, finishUpdate, completion.options);
        else
          finishUpdate(completion.getHints(completion.cm, completion.options));
      }
      function finishUpdate(data) {
        if (isDone()) return;
        if (!data || !data.list.length) return done();
        completion.widget.close();
        completion.widget = new Widget(completion, data);
      }

      function activity() {
        clearTimeout(debounce);
        var pos = completion.cm.getCursor(), line = completion.cm.getLine(pos.line);
        if (pos.line != startPos.line || line.length - pos.ch != startLen - startPos.ch ||
            pos.ch < startPos.ch || completion.cm.somethingSelected() ||
            (pos.ch && closeOn.test(line.charAt(pos.ch - 1))))
          completion.close();
        else
          debounce = setTimeout(update, 170);
      }
      this.cm.on("cursorActivity", activity);
      this.onClose = done;
    }
  };

  function getText(completion) {
    if (typeof completion == "string") return completion;
    else return completion.text;
  }

  function buildKeyMap(options, handle) {
    var baseMap = {
      Up: function() {handle.moveFocus(-1);},
      Down: function() {handle.moveFocus(1);},
      PageUp: function() {handle.moveFocus(-handle.menuSize());},
      PageDown: function() {handle.moveFocus(handle.menuSize());},
      Home: function() {handle.setFocus(0);},
      End: function() {handle.setFocus(handle.length);},
      Enter: handle.pick,
      Tab: handle.pick,
      Esc: handle.close
    };
    var ourMap = options.customKeys ? {} : baseMap;
    function addBinding(key, val) {
      var bound;
      if (typeof val != "string")
        bound = function(cm) { return val(cm, handle); };
      // This mechanism is deprecated
      else if (baseMap.hasOwnProperty(val))
        bound = baseMap[val];
      else
        bound = val;
      ourMap[key] = bound;
    }
    if (options.customKeys)
      for (var key in options.customKeys) if (options.customKeys.hasOwnProperty(key))
        addBinding(key, options.customKeys[key]);
    if (options.extraKeys)
      for (var key in options.extraKeys) if (options.extraKeys.hasOwnProperty(key))
        addBinding(key, options.extraKeys[key]);
    return ourMap;
  }

  function Widget(completion, data) {
    this.completion = completion;
    this.data = data;
    var widget = this, cm = completion.cm, options = completion.options;

    var hints = this.hints = document.createElement("ul");
    hints.className = "CodeMirror-hints";
    this.selectedHint = 0;

    var completions = data.list;
    for (var i = 0; i < completions.length; ++i) {
      var elt = hints.appendChild(document.createElement("li")), cur = completions[i];
      var className = "CodeMirror-hint" + (i ? "" : " CodeMirror-hint-active");
      if (cur.className != null) className = cur.className + " " + className;
      elt.className = className;
      if (cur.render) cur.render(elt, data, cur);
      else elt.appendChild(document.createTextNode(cur.displayText || getText(cur)));
      elt.hintId = i;
    }

    var pos = cm.cursorCoords(options.alignWithWord !== false ? data.from : null);
    var left = pos.left, top = pos.bottom, below = true;
    hints.style.left = left + "px";
    hints.style.top = top + "px";
    // If we're at the edge of the screen, then we want the menu to appear on the left of the cursor.
    var winW = window.innerWidth || Math.max(document.body.offsetWidth, document.documentElement.offsetWidth);
    var winH = window.innerHeight || Math.max(document.body.offsetHeight, document.documentElement.offsetHeight);
    var box = hints.getBoundingClientRect();
    var overlapX = box.right - winW, overlapY = box.bottom - winH;
    if (overlapX > 0) {
      if (box.right - box.left > winW) {
        hints.style.width = (winW - 5) + "px";
        overlapX -= (box.right - box.left) - winW;
      }
      hints.style.left = (left = pos.left - overlapX) + "px";
    }
    if (overlapY > 0) {
      var height = box.bottom - box.top;
      if (box.top - (pos.bottom - pos.top) - height > 0) {
        overlapY = height + (pos.bottom - pos.top);
        below = false;
      } else if (height > winH) {
        hints.style.height = (winH - 5) + "px";
        overlapY -= height - winH;
      }
      hints.style.top = (top = pos.bottom - overlapY) + "px";
    }
    (options.container || document.body).appendChild(hints);

    cm.addKeyMap(this.keyMap = buildKeyMap(options, {
      moveFocus: function(n) { widget.changeActive(widget.selectedHint + n); },
      setFocus: function(n) { widget.changeActive(n); },
      menuSize: function() { return widget.screenAmount(); },
      length: completions.length,
      close: function() { completion.close(); },
      pick: function() { widget.pick(); }
    }));

    if (options.closeOnUnfocus !== false) {
      var closingOnBlur;
      cm.on("blur", this.onBlur = function() { closingOnBlur = setTimeout(function() { completion.close(); }, 100); });
      cm.on("focus", this.onFocus = function() { clearTimeout(closingOnBlur); });
    }

    var startScroll = cm.getScrollInfo();
    cm.on("scroll", this.onScroll = function() {
      var curScroll = cm.getScrollInfo(), editor = cm.getWrapperElement().getBoundingClientRect();
      var newTop = top + startScroll.top - curScroll.top;
      var point = newTop - (window.pageYOffset || (document.documentElement || document.body).scrollTop);
      if (!below) point += hints.offsetHeight;
      if (point <= editor.top || point >= editor.bottom) return completion.close();
      hints.style.top = newTop + "px";
      hints.style.left = (left + startScroll.left - curScroll.left) + "px";
    });

    CodeMirror.on(hints, "dblclick", function(e) {
      var t = e.target || e.srcElement;
      if (t.hintId != null) {widget.changeActive(t.hintId); widget.pick();}
    });
    CodeMirror.on(hints, "click", function(e) {
      var t = e.target || e.srcElement;
      if (t.hintId != null) widget.changeActive(t.hintId);
    });
    CodeMirror.on(hints, "mousedown", function() {
      setTimeout(function(){cm.focus();}, 20);
    });

    CodeMirror.signal(data, "select", completions[0], hints.firstChild);
    return true;
  }

  Widget.prototype = {
    close: function() {
      if (this.completion.widget != this) return;
      this.completion.widget = null;
      this.hints.parentNode.removeChild(this.hints);
      this.completion.cm.removeKeyMap(this.keyMap);

      var cm = this.completion.cm;
      if (this.completion.options.closeOnUnfocus !== false) {
        cm.off("blur", this.onBlur);
        cm.off("focus", this.onFocus);
      }
      cm.off("scroll", this.onScroll);
    },

    pick: function() {
      this.completion.pick(this.data, this.selectedHint);
    },

    changeActive: function(i) {
      i = Math.max(0, Math.min(i, this.data.list.length - 1));
      if (this.selectedHint == i) return;
      var node = this.hints.childNodes[this.selectedHint];
      node.className = node.className.replace(" CodeMirror-hint-active", "");
      node = this.hints.childNodes[this.selectedHint = i];
      node.className += " CodeMirror-hint-active";
      if (node.offsetTop < this.hints.scrollTop)
        this.hints.scrollTop = node.offsetTop - 3;
      else if (node.offsetTop + node.offsetHeight > this.hints.scrollTop + this.hints.clientHeight)
        this.hints.scrollTop = node.offsetTop + node.offsetHeight - this.hints.clientHeight + 3;
      CodeMirror.signal(this.data, "select", this.data.list[this.selectedHint], node);
    },

    screenAmount: function() {
      return Math.floor(this.hints.clientHeight / this.hints.firstChild.offsetHeight) || 1;
    }
  };
})();
<|endoftext|>


<commit_before>/**
 * Pc2bimController
 */

var PC2BIM = require('../../bindings/pc2bim'),
  isThere = require('is-there');

var _SIMULATE_SUCCESS = false;

function pc2bimRun(config) {
  var pc2bim = new PC2BIM(config.duraarkStoragePath);
  return pc2bim.extract(config);
}

function startExtraction(derivativeState, config) {
  pc2bimRun(config).then(function(result) {
    console.log('Extraction finished: ' + JSON.stringify(result, null, 4));

    derivativeState.bimFilePath = result.bimFilePath;
    derivativeState.wallsFilePath = result.wallsFilePath;
    derivativeState.status = "finished";
    derivativeState.bimDownloadUrl = result.bimFilePath.replace('/duraark-storage', '');
    derivativeState.wallsDownloadUrl = result.wallsFilePath.replace('/duraark-storage', '');
    derivativeState.save().then(function(pc2bimRecord) {
      console.log('[Pc2bimController] Successfully reconstructed BIM model for: ' + pc2bimRecord.inputFile);
    });
  }).catch(function(err) {
    console.log('[Pc2bimController] Error:\n' + err);

    if (err === "") {
      err = "No explicit error given"
    }
    derivativeState.status = "error";
    derivativeState.errorText = err;

    derivativeState.save().then(function(pc2bimRecord) {
      console.log('[Pc2bimController] Error reconstructing BIM model for: ' + pc2bimRecord.inputFile);
      console.log('[Pc2bimController] Error details:\n' + pc2bimRecord.errorText);
    });
  });
}

/**
 * @apiDefine ExtractionSuccess
 * @apiSuccess (Response) {String} input Location of the input file.
 * @apiSuccess (Response) {String} output Location of the reconstructed output file.
 * @apiSuccess (Response) {String} error 'null' if extraction was successfull, otherwise contains error message.
 */

module.exports = {
  /**
   * @api {post} /pc2bim/ Extract BIM model
   * @apiVersion 0.8.0
   * @apiName PostPc2bim
   * @apiGroup PC2BIM
   * @apiPermission none
   *
   * @apiDescription Schedule the extraction of a BIM model as IFC file from a given E57 point cloud file.
   *
   * @apiParam (File) {String} path Location of the File as provided by the [DURAARK Sessions API](http://data.duraark.eu/services/api/sessions/).
   *
   * @apiUse ExtractionSuccess
   *
   * @apiSuccessExample Success-Response:
   *     HTTP/1.1 200 OK
   *     {
   *        "input": "/duraark-storage/files/Nygade_Scan1001.e57",
   *        "output": "/duraark-storage/files/Nygade_Scan1001_RECONSTRUCTED.ifc",
   *        "error": null
   *      }
   */
  create: function(req, res, next) {
    var inputFile = req.param('inputFile'),
      restart = req.param('restart'),
      duraarkStoragePath = process.env.DURAARK_STORAGE_PATH || '/duraark-storage',
      bimFilePath = inputFile.replace('.e57', '_RECONSTRUCTED.ifc').replace('master', 'derivative_copy'),
      wallsFilePath = inputFile.replace('.e57', '_wall.json').replace('master', 'tmp'),
      isAlreadyReconstructed = false;

    // console.log('duraarkStoragePath: ' + duraarkStoragePath);
    // console.log('inputFile: ' + inputFile);
    // console.log('restart: ' + restart);

    console.log('POST /pc2bim: Scheduled conversion from ' + inputFile);

    res.setTimeout(0);

    // Check if reconstructed IFC file is already present:
    isAlreadyReconstructed = isThere(bimFilePath) && isThere(wallsFilePath);

    // console.log('bim: ' + bimFilePath);
    // console.log('wall: ' + wallsFilePath);
    // console.log('bim there: ' + isThere(bimFilePath));
    // console.log('wall there: ' + isThere(wallsFilePath));
    //
    // console.log('[Pc2bim] Found existing reconstruction: ' + isAlreadyReconstructed);

    Pc2bim.findOne({
      "where": {
        "inputFile": {
          "equals": inputFile
        }
      }
    }).then(function(derivativeState) {
      // console.log('derivativeState: ' + JSON.stringify(derivativeState, null, 4));

      if (_SIMULATE_SUCCESS) {
        derivativeState.status = "finished";
        var url = derivativeState.inputFile.replace('.e57', '.ifc');
        url = url.replace('/duraark-storage', '');
        derivativeState.bimDownloadUrl = url;
        return res.send(derivativeState);
      }

      if (!derivativeState) {
        console.log('[Pc2bimController] No job found for input file: ' + inputFile);
        console.log('[Pc2bimController] Creating new database entry ...');
        Pc2bim.create({
          inputFile: inputFile,
          bimFilePath: null,
          wallsFilePath: null,
          status: 'pending',
          bimDownloadUrl: null
        }).then(function(derivativeState) {
          if (isAlreadyReconstructed) {
            console.log('[Pc2bimController] Found existing reconstruction, reusing:');
            console.log('[Pc2bimController]   * BIM model: ' + bimFilePath);
            console.log('[Pc2bimController]   * Wall JSON: ' + wallsFilePath);

            // Take the new database entry and update it with the existing data files:
            derivativeState.bimFilePath = bimFilePath;
            derivativeState.wallsFilePath = wallsFilePath;
            derivativeState.bimDownloadUrl = bimFilePath.replace('/duraark-storage', '');
            derivativeState.wallsDownloadUrl = wallsFilePath.replace('/duraark-storage', '');
            derivativeState.status = 'finished';

            derivativeState.save().catch(function(err) {
              console.log('[Pc2BimController] When this error occurs the database and client app are not syncronized correctly anymore ...')
              throw new Error(err);
            });

            console.log('[Pc2bimController] Updated database with existing data');

            // FIXXME: The 'save()' method above could go wrong. This return statement is directly triggered
            // here and not in the resolved promise above only because of the execution flow.
            return res.send(derivativeState).status(200);
          }

          var jobConfig = {
            inputFile: derivativeState.inputFile,
            bimFilePath: bimFilePath,
            wallsFilePath: wallsFilePath,
            duraarkStoragePath: duraarkStoragePath
          };

          console.log('[Pc2bimController] Starting new job: ' + JSON.stringify(config, null, 4));

          startExtraction(derivativeState, jobConfig);
        });

      } else {

        if (derivativeState.status === "finished") {
          console.log('[Pc2bimController] Found finished job: ' + JSON.stringify(derivativeState, null, 4));
          res.send(derivativeState).status(201);
        }

        if (derivativeState.status === "pending") {
          // console.log('[Pc2bimController] Job is pending: ' + JSON.stringify(derivativeState, null, 4));
          res.send(derivativeState).status(200);
        }

        if (derivativeState.status === "error") {
          console.log('[Pc2bimController] Found failed job: ' + JSON.stringify(derivativeState, null, 4));
          if (restart) {
            console.log('[Pc2bimController] Reschedule job as requested');
            startExtraction(derivativeState, {
              inputFile: derivativeState.inputFile,
              bimFilePath: bimFilePath,
              wallsFilePath: wallsFilePath,
              duraarkStoragePath: duraarkStoragePath
            });
          }
          res.send(derivativeState).status(200);
        }
      }
    }).catch(function(err) {
      console.log('[PC2BIMController] Internal error: ' + err);
    });
  }
}
<commit_msg>fix: wrong variable name<commit_after>/**
 * Pc2bimController
 */

var PC2BIM = require('../../bindings/pc2bim'),
  isThere = require('is-there');

var _SIMULATE_SUCCESS = false;

function pc2bimRun(config) {
  var pc2bim = new PC2BIM(config.duraarkStoragePath);
  return pc2bim.extract(config);
}

function startExtraction(derivativeState, config) {
  pc2bimRun(config).then(function(result) {
    console.log('Extraction finished: ' + JSON.stringify(result, null, 4));

    derivativeState.bimFilePath = result.bimFilePath;
    derivativeState.wallsFilePath = result.wallsFilePath;
    derivativeState.status = "finished";
    derivativeState.bimDownloadUrl = result.bimFilePath.replace('/duraark-storage', '');
    derivativeState.wallsDownloadUrl = result.wallsFilePath.replace('/duraark-storage', '');
    derivativeState.save().then(function(pc2bimRecord) {
      console.log('[Pc2bimController] Successfully reconstructed BIM model for: ' + pc2bimRecord.inputFile);
    });
  }).catch(function(err) {
    console.log('[Pc2bimController] Error:\n' + err);

    if (err === "") {
      err = "No explicit error given"
    }
    derivativeState.status = "error";
    derivativeState.errorText = err;

    derivativeState.save().then(function(pc2bimRecord) {
      console.log('[Pc2bimController] Error reconstructing BIM model for: ' + pc2bimRecord.inputFile);
      console.log('[Pc2bimController] Error details:\n' + pc2bimRecord.errorText);
    });
  });
}

/**
 * @apiDefine ExtractionSuccess
 * @apiSuccess (Response) {String} input Location of the input file.
 * @apiSuccess (Response) {String} output Location of the reconstructed output file.
 * @apiSuccess (Response) {String} error 'null' if extraction was successfull, otherwise contains error message.
 */

module.exports = {
  /**
   * @api {post} /pc2bim/ Extract BIM model
   * @apiVersion 0.8.0
   * @apiName PostPc2bim
   * @apiGroup PC2BIM
   * @apiPermission none
   *
   * @apiDescription Schedule the extraction of a BIM model as IFC file from a given E57 point cloud file.
   *
   * @apiParam (File) {String} path Location of the File as provided by the [DURAARK Sessions API](http://data.duraark.eu/services/api/sessions/).
   *
   * @apiUse ExtractionSuccess
   *
   * @apiSuccessExample Success-Response:
   *     HTTP/1.1 200 OK
   *     {
   *        "input": "/duraark-storage/files/Nygade_Scan1001.e57",
   *        "output": "/duraark-storage/files/Nygade_Scan1001_RECONSTRUCTED.ifc",
   *        "error": null
   *      }
   */
  create: function(req, res, next) {
    var inputFile = req.param('inputFile'),
      restart = req.param('restart'),
      duraarkStoragePath = process.env.DURAARK_STORAGE_PATH || '/duraark-storage',
      bimFilePath = inputFile.replace('.e57', '_RECONSTRUCTED.ifc').replace('master', 'derivative_copy'),
      wallsFilePath = inputFile.replace('.e57', '_wall.json').replace('master', 'tmp'),
      isAlreadyReconstructed = false;

    // console.log('duraarkStoragePath: ' + duraarkStoragePath);
    // console.log('inputFile: ' + inputFile);
    // console.log('restart: ' + restart);

    console.log('POST /pc2bim: Scheduled conversion from ' + inputFile);

    res.setTimeout(0);

    // Check if reconstructed IFC file is already present:
    isAlreadyReconstructed = isThere(bimFilePath) && isThere(wallsFilePath);

    // console.log('bim: ' + bimFilePath);
    // console.log('wall: ' + wallsFilePath);
    // console.log('bim there: ' + isThere(bimFilePath));
    // console.log('wall there: ' + isThere(wallsFilePath));
    //
    // console.log('[Pc2bim] Found existing reconstruction: ' + isAlreadyReconstructed);

    Pc2bim.findOne({
      "where": {
        "inputFile": {
          "equals": inputFile
        }
      }
    }).then(function(derivativeState) {
      // console.log('derivativeState: ' + JSON.stringify(derivativeState, null, 4));

      if (_SIMULATE_SUCCESS) {
        derivativeState.status = "finished";
        var url = derivativeState.inputFile.replace('.e57', '.ifc');
        url = url.replace('/duraark-storage', '');
        derivativeState.bimDownloadUrl = url;
        return res.send(derivativeState);
      }

      if (!derivativeState) {
        console.log('[Pc2bimController] No job found for input file: ' + inputFile);
        console.log('[Pc2bimController] Creating new database entry ...');
        Pc2bim.create({
          inputFile: inputFile,
          bimFilePath: null,
          wallsFilePath: null,
          status: 'pending',
          bimDownloadUrl: null
        }).then(function(derivativeState) {
          if (isAlreadyReconstructed) {
            console.log('[Pc2bimController] Found existing reconstruction, reusing:');
            console.log('[Pc2bimController]   * BIM model: ' + bimFilePath);
            console.log('[Pc2bimController]   * Wall JSON: ' + wallsFilePath);

            // Take the new database entry and update it with the existing data files:
            derivativeState.bimFilePath = bimFilePath;
            derivativeState.wallsFilePath = wallsFilePath;
            derivativeState.bimDownloadUrl = bimFilePath.replace('/duraark-storage', '');
            derivativeState.wallsDownloadUrl = wallsFilePath.replace('/duraark-storage', '');
            derivativeState.status = 'finished';

            derivativeState.save().catch(function(err) {
              console.log('[Pc2BimController] When this error occurs the database and client app are not syncronized correctly anymore ...')
              throw new Error(err);
            });

            console.log('[Pc2bimController] Updated database with existing data');

            // FIXXME: The 'save()' method above could go wrong. This return statement is directly triggered
            // here and not in the resolved promise above only because of the execution flow.
            return res.send(derivativeState).status(200);
          }

          var jobConfig = {
            inputFile: derivativeState.inputFile,
            bimFilePath: bimFilePath,
            wallsFilePath: wallsFilePath,
            duraarkStoragePath: duraarkStoragePath
          };

          console.log('[Pc2bimController] Starting new job: ' + JSON.stringify(jobConfig, null, 4));

          startExtraction(derivativeState, jobConfig);
        });

      } else {

        if (derivativeState.status === "finished") {
          console.log('[Pc2bimController] Found finished job: ' + JSON.stringify(derivativeState, null, 4));
          res.send(derivativeState).status(201);
        }

        if (derivativeState.status === "pending") {
          // console.log('[Pc2bimController] Job is pending: ' + JSON.stringify(derivativeState, null, 4));
          res.send(derivativeState).status(200);
        }

        if (derivativeState.status === "error") {
          console.log('[Pc2bimController] Found failed job: ' + JSON.stringify(derivativeState, null, 4));
          if (restart) {
            console.log('[Pc2bimController] Reschedule job as requested');
            startExtraction(derivativeState, {
              inputFile: derivativeState.inputFile,
              bimFilePath: bimFilePath,
              wallsFilePath: wallsFilePath,
              duraarkStoragePath: duraarkStoragePath
            });
          }
          res.send(derivativeState).status(200);
        }
      }
    }).catch(function(err) {
      console.log('[PC2BIMController] Internal error: ' + err);
    });
  }
}
<|endoftext|>


<commit_before>'use strict';

angular.module('app.controllers')
    .controller('UploadController', ['$scope', '$state', '$config', '$http', 'fileModel', 'userModel', 'S3', function UploadController($scope, $state, $config, $http, model, user, s3) {
        // private
        var _this = {
            onCreate: function() {
                // Make sure to reset the scope
                $scope.clear();

                if(!model.getFile()) {
                    // Go home, you're drunk!!!
                    return $state.go('home');
                }

                // Set the title and the right bar button item
                $scope.setTitle('Foto toevoegen');
                $scope.setRightBarButtonItem({
                    title: 'Upload',
                    action: _this.upload,
                    enabled: $scope.progress === undefined
                });
            },
            upload: function() {
                if($scope.progress !== undefined) {
                    // This means we are already uploading
                    return;
                }

                // Set the description provided by the user
                model.setDescription($scope.description);

                if(!user.isValid()) {
                    // If the user is not valid, let him fill in the form first
                    return $state.go('user');
                }

                // Start uploading the file and listen to progress changes
                model.upload(_this.onProgressChanged)
                    .then(function(result) {
                        // Upload was successfull, reset the model first
                        model.reset();

                        // Go home
                        $state.go('home');
                    })
                    .catch(function(err) {
                        // Something went wrong, handle the error
                        console.error(err);
                    });
            },
            onProgressChanged: function(progress) {
                // Make the progress public
                $scope.progress = progress;

                if(progress >= 100) {
                    // If the progress is 100%, the API is called to store the data in the database so we
                    // better show a loading indicator.
                    $scope.loading(true);
                }
            }
        };

        // public
        $scope.file = model.getFile();
        $scope.description = model.getDescription();

        // Initialize the controller
        _this.onCreate();
    }]);<commit_msg>Fixed issue regarding double upload when pressing the button twice very quickly<commit_after>'use strict';

angular.module('app.controllers')
    .controller('UploadController', ['$scope', '$state', '$config', '$http', 'fileModel', 'userModel', 'S3', function UploadController($scope, $state, $config, $http, model, user, s3) {
        var uploading = false;

        // private
        var _this = {
            onCreate: function() {
                // Make sure to reset the scope
                $scope.clear();

                if(!model.getFile()) {
                    // Go home, you're drunk!!!
                    return $state.go('home');
                }

                // Set the title and the right bar button item
                $scope.setTitle('Foto toevoegen');
                $scope.setRightBarButtonItem({
                    title: 'Upload',
                    action: _this.upload,
                    enabled: $scope.progress === undefined
                });
            },
            upload: function() {
                if(uploading) {
                    // This means we are already uploading
                    return;
                }

                // Set the uploading flag to true
                uploading = true;

                // Set the description provided by the user
                model.setDescription($scope.description);

                if(!user.isValid()) {
                    // Set the uploading flag back to false
                    uploading = false;

                    // If the user is not valid, let him fill in the form first
                    return $state.go('user');
                }

                // Start uploading the file and listen to progress changes
                model.upload(_this.onProgressChanged)
                    .then(function(result) {
                        // Upload was successfull, reset the model first
                        model.reset();

                        // Go home
                        $state.go('home');
                    })
                    .catch(function(err) {
                        uploading = false;

                        // Something went wrong, handle the error
                        console.error(err);
                    });
            },
            onProgressChanged: function(progress) {
                // Make the progress public
                $scope.progress = progress;

                if(progress >= 100) {
                    // If the progress is 100%, the API is called to store the data in the database so we
                    // better show a loading indicator.
                    $scope.loading(true);
                }
            }
        };

        // public
        $scope.file = model.getFile();
        $scope.description = model.getDescription();

        // Initialize the controller
        _this.onCreate();
    }]);<|endoftext|>


<commit_before>define([
	"Ember",
	"nwjs/argv",
	"utils/semver"
], function(
	Ember,
	argv,
	semver
) {

	var get = Ember.get;
	var set = Ember.set;
	var readOnly = Ember.computed.readOnly;

	return Ember.Service.extend({
		store   : Ember.inject.service(),
		metadata: Ember.inject.service(),
		modal   : Ember.inject.service(),

		config : readOnly( "metadata.config" ),
		version: readOnly( "metadata.package.version" ),

		// check again in x days (time in ms)
		time: function() {
			var days = Number( get( this, "config.version-check-days" ) );
			return 1000 * 3600 * 24 * days;
		}.property( "config.version-check-days" ),

		model: null,

		check: function() {
			// get the installed version
			var current = get( this, "version" );
			if ( !current ) { return; }

			var self  = this;
			var store = get( self, "store" );
			store.findRecord( "versioncheck", 1 )
				.then(function( record ) {
					// versioncheck record found

					set( self, "model", record );

					var version = get( record, "version" );
					// if version string is empty, go on (new version)
					// ignore if version string >= (not <) installed version metadata
					if ( version && semver.getMax([ version, current ]) === version ) {
						return true;
					}

					// NEW version -> upgrade record
					set( record, "version", current );
					record.save();

					// don't show modal if versioncheck is enabled (manual upgrades)
					// manual upgrades -> user has (most likely) seen changelog already
					if ( argv.versioncheck ) {
						return true;
					}

					// show changelog modal dialog
					get( self, "modal" ).openModal( "changelog", self );

				}, function() {
					// no versioncheck record found: first run

					// unload automatically created record and create a new one instead
					var record = store.peekRecord( "versioncheck", 1 );
					if ( record ) {
						store.unloadRecord( record );
					}
					record = store.createRecord( "versioncheck", {
						id     : 1,
						version: current
					});
					record.save();

					set( self, "model", record );

					// show first run modal dialog
					get( self, "modal" ).openModal( "firstrun", self );
				})
				.then(function( modalSkipped ) {
					if ( !modalSkipped ) { return; }
					// go on with new version check if no modal has been opened
					self.checkForNewRelease();
				});
		},

		checkForNewRelease: function() {
			// don't check for new releases if disabled
			if ( !argv.versioncheck ) { return; }

			var checkagain = get( this, "model.checkagain" );
			if ( checkagain <= +new Date() ) {
				this.getReleases();
			}
		},

		getReleases: function() {
			get( this, "store" ).findAll( "githubReleases", { reload: true } )
				.then(function( releases ) {
					// filter records first
					return releases.toArray().filter(function( release ) {
						// ignore drafts
						return !get( release, "draft" );
					});
				})
				.then( this.checkReleases.bind( this ) );
		},

		checkReleases: function( releases ) {
			function getVers( record ) {
				return get( record, "tag_name" );
			}

			// create a fake record for the current version and save a reference
			var current = { tag_name: "v" + get( this, "version" ) };
			// find out the maximum of fetched releases
			var maximum = semver.getMax( releases, getVers );
			// and compare it with the current version
			var latest  = semver.getMax( [ current, maximum ], getVers );

			// no new release? check again in a few days
			if ( current === latest || getVers( current ) === getVers( latest ) ) {
				return this.send( "releaseIgnore" );
			}

			// ask the user what to do
			get( this, "modal" ).openModal( "newrelease", this, {
				versionOutdated: getVers( current ),
				versionLatest  : getVers( latest ),
				downloadURL    : get( latest, "html_url" )
			});
		},

		ignore: function() {
			var record     = get( this, "model" );
			var time       = get( this, "time" );
			var checkagain = +new Date() + time;

			record.set( "checkagain", checkagain );

			return record.save();
		}
	});

});
<commit_msg>Fix invalid releaseIgnore call<commit_after>define([
	"Ember",
	"nwjs/argv",
	"utils/semver"
], function(
	Ember,
	argv,
	semver
) {

	var get = Ember.get;
	var set = Ember.set;
	var readOnly = Ember.computed.readOnly;

	return Ember.Service.extend({
		store   : Ember.inject.service(),
		metadata: Ember.inject.service(),
		modal   : Ember.inject.service(),

		config : readOnly( "metadata.config" ),
		version: readOnly( "metadata.package.version" ),

		// check again in x days (time in ms)
		time: function() {
			var days = Number( get( this, "config.version-check-days" ) );
			return 1000 * 3600 * 24 * days;
		}.property( "config.version-check-days" ),

		model: null,

		check: function() {
			// get the installed version
			var current = get( this, "version" );
			if ( !current ) { return; }

			var self  = this;
			var store = get( self, "store" );
			store.findRecord( "versioncheck", 1 )
				.then(function( record ) {
					// versioncheck record found

					set( self, "model", record );

					var version = get( record, "version" );
					// if version string is empty, go on (new version)
					// ignore if version string >= (not <) installed version metadata
					if ( version && semver.getMax([ version, current ]) === version ) {
						return true;
					}

					// NEW version -> upgrade record
					set( record, "version", current );
					record.save();

					// don't show modal if versioncheck is enabled (manual upgrades)
					// manual upgrades -> user has (most likely) seen changelog already
					if ( argv.versioncheck ) {
						return true;
					}

					// show changelog modal dialog
					get( self, "modal" ).openModal( "changelog", self );

				}, function() {
					// no versioncheck record found: first run

					// unload automatically created record and create a new one instead
					var record = store.peekRecord( "versioncheck", 1 );
					if ( record ) {
						store.unloadRecord( record );
					}
					record = store.createRecord( "versioncheck", {
						id     : 1,
						version: current
					});
					record.save();

					set( self, "model", record );

					// show first run modal dialog
					get( self, "modal" ).openModal( "firstrun", self );
				})
				.then(function( modalSkipped ) {
					if ( !modalSkipped ) { return; }
					// go on with new version check if no modal has been opened
					self.checkForNewRelease();
				});
		},

		checkForNewRelease: function() {
			// don't check for new releases if disabled
			if ( !argv.versioncheck ) { return; }

			var checkagain = get( this, "model.checkagain" );
			if ( checkagain <= +new Date() ) {
				this.getReleases();
			}
		},

		getReleases: function() {
			get( this, "store" ).findAll( "githubReleases", { reload: true } )
				.then(function( releases ) {
					// filter records first
					return releases.toArray().filter(function( release ) {
						// ignore drafts
						return !get( release, "draft" );
					});
				})
				.then( this.checkReleases.bind( this ) );
		},

		checkReleases: function( releases ) {
			function getVers( record ) {
				return get( record, "tag_name" );
			}

			// create a fake record for the current version and save a reference
			var current = { tag_name: "v" + get( this, "version" ) };
			// find out the maximum of fetched releases
			var maximum = semver.getMax( releases, getVers );
			// and compare it with the current version
			var latest  = semver.getMax( [ current, maximum ], getVers );

			// no new release? check again in a few days
			if ( current === latest || getVers( current ) === getVers( latest ) ) {
				return this.ignore();
			}

			// ask the user what to do
			get( this, "modal" ).openModal( "newrelease", this, {
				versionOutdated: getVers( current ),
				versionLatest  : getVers( latest ),
				downloadURL    : get( latest, "html_url" )
			});
		},

		ignore: function() {
			var record     = get( this, "model" );
			var time       = get( this, "time" );
			var checkagain = +new Date() + time;

			record.set( "checkagain", checkagain );

			return record.save();
		}
	});

});
<|endoftext|>


<commit_before>'use strict';

module.exports = {
  'periodicjs.ext.reactadmin': {
    'manifests':[
      'node_modules/periodicjs.ext.reactadmin/adminclient/src/content/config/manifest.json',
      'node_modules/periodicjs.ext.reactadmin/views/home/',
      'node_modules/periodicjs.ext.reactadmin/views/account/',
      'node_modules/periodicjs.ext.reactadmin/views/test/',
    ],
    'unauthenticated_manifests':[
      'node_modules/periodicjs.ext.reactadmin/views/unauth/'
    ],
    'navigation':'node_modules/periodicjs.ext.reactadmin/adminclient/src/content/config/navigation.json',
    'components':{
      // 'login':'/content/themes/periodicjs.theme.default/views/auth/loginDISABLED.manifest.json',
      'main':{
        // 'header':'node_modules/periodicjs.ext.reactadmin/adminclient/src/content/config/header.js',
        'footer':'node_modules/periodicjs.ext.reactadmin/adminclient/src/content/config/footer.js',
      },
      'error':{
        '404':'node_modules/periodicjs.ext.reactadmin/adminclient/src/content/config/manifests/dynamic404.json',
        '400':'node_modules/periodicjs.ext.reactadmin/adminclient/src/content/config/manifests/dynamic400.json',
      },
    },
  },
};
<commit_msg>updated<commit_after>'use strict';

module.exports = {
  'periodicjs.ext.reactadmin': {
    'manifests':[
      'node_modules/periodicjs.ext.reactadmin/adminclient/src/content/config/manifest.json',
      'node_modules/periodicjs.ext.reactadmin/views/home/',
      'node_modules/periodicjs.ext.reactadmin/views/account/',
      'node_modules/periodicjs.ext.reactadmin/views/test/',
    ],
    'unauthenticated_manifests':[
    ],
    'navigation':'node_modules/periodicjs.ext.reactadmin/adminclient/src/content/config/navigation.json',
    'components':{
      // 'login':'/content/themes/periodicjs.theme.default/views/auth/loginDISABLED.manifest.json',
      'main':{
        // 'header':'node_modules/periodicjs.ext.reactadmin/adminclient/src/content/config/header.js',
        'footer':'node_modules/periodicjs.ext.reactadmin/adminclient/src/content/config/footer.js',
      },
      'error':{
        '404':'node_modules/periodicjs.ext.reactadmin/adminclient/src/content/config/manifests/dynamic404.json',
        '400':'node_modules/periodicjs.ext.reactadmin/adminclient/src/content/config/manifests/dynamic400.json',
      },
    },
  },
};
<|endoftext|>


<commit_before>'use strict'

const { asyncify } = require('async')
const osom = require('osom')

const cleanTitle = require('./clean-title')
const serializer = require('./serializer')

const validate = osom({
  /* common */
  title: {
    required: true,
    type: String,
    transform: [cleanTitle]
    // TODO: Add a max title size (like 140 chars)
  },
  category: {
    required: true,
    type: Array
  },
  seller: {
    required: true,
    type: String
  },
  provider: {
    required: true,
    type: String
  },
  path: {
    type: String
  },
  link: {
    required: true,
    type: String
  },
  createdAt: {
    required: true,
    type: Number
  },
  updatedAt: {
    type: Number
  },

  /** identify:common **/
  brand: String,
  model: String,
  price: {
    required: true,
    type: Number,
    validate: price => price > 1
  },
  year: Number,

  'mast.size': Number,

  'sail.size': Number,

  'board.size': Number,

  'boom.size': String,
  'boom.type': String,

  'fin.size': Number,
  'fin.type': String,

  'mast.carbon': Number,
  'mast.type': String
})

const validateAsync = asyncify(validate)

function validator (schema, cb) {
  schema = serializer(schema)
  return validateAsync(schema, cb)
}

module.exports = validator
<commit_msg>Transform seller<commit_after>'use strict'

const { asyncify } = require('async')
const osom = require('osom')

const cleanTitle = require('./clean-title')
const serializer = require('./serializer')

const validate = osom({
  /* common */
  title: {
    required: true,
    type: String,
    transform: [cleanTitle]
    // TODO: Add a max title size (like 140 chars)
  },
  category: {
    required: true,
    type: Array
  },
  seller: {
    required: true,
    type: String,
    transform: [
      (seller) => seller === 'particular' ? seller : 'store'
    ]
  },
  provider: {
    required: true,
    type: String
  },
  path: {
    type: String
  },
  link: {
    required: true,
    type: String
  },
  createdAt: {
    required: true,
    type: Number
  },
  updatedAt: {
    type: Number
  },

  /** identify:common **/
  brand: String,
  model: String,
  price: {
    required: true,
    type: Number,
    validate: price => price > 1
  },
  year: Number,

  'mast.size': Number,

  'sail.size': Number,

  'board.size': Number,

  'boom.size': String,
  'boom.type': String,

  'fin.size': Number,
  'fin.type': String,

  'mast.carbon': Number,
  'mast.type': String
})

const validateAsync = asyncify(validate)

function validator (schema, cb) {
  schema = serializer(schema)
  return validateAsync(schema, cb)
}

module.exports = validator
<|endoftext|>


<commit_before>'use strict'

const CONFIG = require('config')['shorte.st']
CONFIG.token = process.env[CONFIG.token]

const shortestAPI = require('shortest-api')
const shortest = shortestAPI(CONFIG)

const cleanTitle = require('./clean-title')
const { asyncify } = require('async')
const osom = require('osom')

const validate = osom({
  /* common */
  title: {
    required: true,
    type: String,
    transform: [cleanTitle]
  },
  category: {
    required: true,
    type: String
  },
  type: {
    required: true,
    type: String
  },
  provider: {
    required: true,
    type: String
  },
  url: {
    required: true,
    type: String
  },
  createdAt: {
    required: true,
    type: Number
  },
  updatedAt: {
    required: true,
    type: Number
  },

  /** identify:common **/
  brand: String,
  model: String,
  price: Number,
  year: Number,

  /* identify:board */
  litres: Number,

  /* identify:sail */
  size: Number
})

const validateAsync = asyncify(validate)

function validator (schema, cb) {
  validateAsync(schema, function (err, instance) {
    if (err) return cb(err, instance)
    shortest(instance.url, function (err, shortenURL) {
      if (err) return cb(err)
      instance.shortenURL = shortenURL
      return cb(null, instance)
    })
  })
}

module.exports = validator
<commit_msg>shortenURL → shortenUrl<commit_after>'use strict'

const CONFIG = require('config')['shorte.st']
CONFIG.token = process.env[CONFIG.token]

const shortestAPI = require('shortest-api')
const shortest = shortestAPI(CONFIG)

const cleanTitle = require('./clean-title')
const { asyncify } = require('async')
const osom = require('osom')

const validate = osom({
  /* common */
  title: {
    required: true,
    type: String,
    transform: [cleanTitle]
  },
  category: {
    required: true,
    type: String
  },
  type: {
    required: true,
    type: String
  },
  provider: {
    required: true,
    type: String
  },
  url: {
    required: true,
    type: String
  },
  createdAt: {
    required: true,
    type: Number
  },
  updatedAt: {
    required: true,
    type: Number
  },

  /** identify:common **/
  brand: String,
  model: String,
  price: Number,
  year: Number,

  /* identify:board */
  litres: Number,

  /* identify:sail */
  size: Number
})

const validateAsync = asyncify(validate)

function validator (schema, cb) {
  validateAsync(schema, function (err, instance) {
    if (err) return cb(err, instance)
    shortest(instance.url, function (err, shortenUrl) {
      if (err) return cb(err)
      instance.shortenUrl = shortenUrl
      return cb(null, instance)
    })
  })
}

module.exports = validator
<|endoftext|>