<commit_before>

const expect = require('chai').expect;
const RG = require('../../../client/src/battles');

const worldConf = require('../../../client/data/conf.world');

const LocalStorage = require('node-localstorage').LocalStorage,
localStorage = new LocalStorage('./battles_local_storage');

const isGUICommand = () => {};
const doGUICommand = () => {};

describe('Function: Saving/restoring a game', function() {
    this.timeout(5000);
    // 1. Create a new game
    // 2. Do some stuff as user
    // 3. Save game
    // 4. Restore game
    // 5. Assert that changes were saved
    it('should be able to save/restore game for user', () => {
        const gameConf = {
            cols: 80,
            rows: 60,
            levels: 2,
            playerLevel: 'Medium',
            sqrPerMonster: 40,
            sqrPerItem: 100,
            debugMode: 'World',
            loadedPlayer: null,
            loadedLevel: null,
            playerName: 'Player1',
            world: worldConf
        };
        const fccGame = new RG.FCCGame();
        const game = fccGame.createNewGame(gameConf);
        game.setGUICallbacks(isGUICommand, doGUICommand);

        const gameSave = new RG.Game.Save();
        gameSave.setStorage(localStorage);

        gameSave.save(game);

        const restGame = gameSave.restorePlayer(gameConf.playerName);

        expect(restGame.getPlayer().getName()).to.equal(gameConf.playerName);

    });
});
<commit_msg>Corrected tests to work with new save game logic.<commit_after>
const expect = require('chai').expect;
const RG = require('../../../client/src/battles');

const worldConf = require('../../../client/data/conf.world');

const isGUICommand = () => {};
const doGUICommand = () => {};

describe('Function: Saving/restoring a game', function() {
    this.timeout(5000);
    // 1. Create a new game
    // 2. Do some stuff as user
    // 3. Save game
    // 4. Restore game
    // 5. Assert that changes were saved
    it('should be able to save/restore game for user', () => {
        const gameConf = {
            cols: 80,
            rows: 60,
            levels: 2,
            playerLevel: 'Medium',
            sqrPerMonster: 40,
            sqrPerItem: 100,
            debugMode: 'World',
            loadedPlayer: null,
            loadedLevel: null,
            playerName: 'Player1',
            world: worldConf
        };
        const fccGame = new RG.FCCGame();
        const game = fccGame.createNewGame(gameConf);
        game.setGUICallbacks(isGUICommand, doGUICommand);

        const json = game.toJSON();
        const fromJSON = new RG.Game.FromJSON();
        const restGame = fromJSON.createGame(json);

        expect(restGame.getPlayer().getName()).to.equal(gameConf.playerName);
    });
});
<|endoftext|>


<commit_before>/* eslint max-len: ["error", 100 ] */
/* global describe, beforeEach, afterEach, it, expect, jasmine */
'use strict';

describe('Narrative Smoketest', function() {

    var selenium = require('selenium-webdriver');
    var timeoutMilliSec = 10 * 1000;

    // Open up the local instance of the narrative from test/unit/run_tests.py
    beforeEach(function(done) {
        this.driver = new selenium.Builder()
            .withCapabilities(selenium.Capabilities.firefox())
            .build();
        this.driver.manage().timeouts().implicitlyWait(timeoutMilliSec);
        jasmine.DEFAULT_TIMEOUT_INTERVAL = timeoutMilliSec;
        this.driver.get('http://localhost:9999/narrative/tree?').then(done);
    });

    // Close the website after each test is run (so that it is opened fresh each time)
    afterEach(function(done) {
        this.driver.quit().then(done);
    });

    // Test to ensure we are on the home page by checking for sign-in button
    it('The sign-in button is visible', function(done) {
        var element = this.driver.findElement(selenium.By.id('signin-button'));
        expect(element).not.toBeNull();
        done();
        // element.getText().then( function(text){
        //     expect(text).toContain('Sign In');
        //     done();
        // });
    });

    // it('Clicking signin brings up modal dialog', function(done) {
    //     var element = this.driver.findElement(selenium.By.id('signin-button'));
    //     element.click();
    //     var element2 = this.driver.findElement(selenium.By.css('[data-id="user_id"]'));
    //     element2.isDisplayed().then(function( displayed) {
    //         expect(displayed).toBeTruthy();
    //         done();
    //     });
    //
    // });
});
<commit_msg>increased timeout interval for selenium.<commit_after>/* eslint max-len: ["error", 100 ] */
/* global describe, beforeEach, afterEach, it, expect, jasmine */
'use strict';

describe('Narrative Smoketest', function() {

    var selenium = require('selenium-webdriver');
    var timeoutMilliSec = 20 * 1000;

    // Open up the local instance of the narrative from test/unit/run_tests.py
    beforeEach(function(done) {
        this.driver = new selenium.Builder()
            .withCapabilities(selenium.Capabilities.firefox())
            .build();
        this.driver.manage().timeouts().implicitlyWait(timeoutMilliSec);
        jasmine.DEFAULT_TIMEOUT_INTERVAL = timeoutMilliSec;
        this.driver.get('http://localhost:9999/narrative/tree?').then(done);
    });

    // Close the website after each test is run (so that it is opened fresh each time)
    afterEach(function(done) {
        this.driver.quit().then(done);
    });

    // Test to ensure we are on the home page by checking for sign-in button
    it('The sign-in button is visible', function(done) {
        var element = this.driver.findElement(selenium.By.id('signin-button'));
        expect(element).not.toBeNull();
        console.log('got element');
        console.log(element);
        done();
        // element.getText().then( function(text){
        //     expect(text).toContain('Sign In');
        //     done();
        // });
    });

    // it('Clicking signin brings up modal dialog', function(done) {
    //     var element = this.driver.findElement(selenium.By.id('signin-button'));
    //     element.click();
    //     var element2 = this.driver.findElement(selenium.By.css('[data-id="user_id"]'));
    //     element2.isDisplayed().then(function( displayed) {
    //         expect(displayed).toBeTruthy();
    //         done();
    //     });
    //
    // });
});
<|endoftext|>


<commit_before>// @flow
import ClientApi from 'daedalus-client-api';
import { action } from 'mobx';
import Wallet from '../domain/Wallet';
import WalletTransaction from '../domain/WalletTransaction';
import type {
  createWalletRequest,
  getTransactionsRequest,
  createTransactionRequest,
} from './index';
import { user } from './fixtures';
import User from '../domain/User';
import Profile from '../domain/Profile';

const notYetImplemented = () => new Promise((resolve, reject) => reject(new Error('Api method not yet implemented')));

export default class CardanoClientApi {

  login() {
    // TODO: Implement when backend is ready for it
    return new Promise((resolve) => resolve(true));
  }

  getUser() {
    return new Promise((resolve) => {
      setTimeout(action(() => {
        resolve(new User(user.id, new Profile(user.profile)));
      }), 0);
    });
  }

  async getWallets() {
    const response = await ClientApi.getWallets();
    return response.map(data => this._createWalletFromData(data));
  }

  async getTransactions({ walletId, searchTerm, limit }: getTransactionsRequest) {
    const history = await ClientApi.searchHistory(walletId, searchTerm, limit)();
    console.log(history);
    return new Promise((resolve) => resolve({
      transactions: history.map(data => this._createTransactionFromData(data, walletId)),
      total: history.length
    }));
  }

  createUser() {
    return notYetImplemented();
  }

  async createWallet(request: createWalletRequest) {
    const response = await ClientApi.newWallet('CWTPersonal', 'ADA', request.name)();
    return this._createWalletFromData(response);
  }

  async createTransaction(request: createTransactionRequest) {
    const { sender, receiver, amount, currency, description, title } = request;
    const response = await ClientApi.sendExtended(sender, receiver, amount, currency, title, description)();
    return this._createTransactionFromData(response);
  }

  isValidAddress(currency: string, address: string) {
    return ClientApi.isValidAddress(currency, address)();
  }

  updateProfileField() {
    return notYetImplemented();
  }

  @action _createWalletFromData(data) {
    return new Wallet({
      id: data.cwAddress,
      address: data.cwAddress,
      amount: data.cwAmount.getCoin,
      type: data.cwMeta.cwType,
      currency: data.cwMeta.cwCurrency,
      name: data.cwMeta.cwName,
    });
  }

  @action _createTransactionFromData(data) {
    const isOutgoing = data.ctType.tag === 'CTOut';
    const coins = data.ctAmount.getCoin;
    const { ctmTitle, ctmDescription, ctmDate } = data.ctType.contents;
    return new WalletTransaction({
      id: data.ctId,
      title: ctmTitle,
      type: isOutgoing ? 'adaExpend' : 'adaIncome',
      currency: 'ada',
      amount: isOutgoing ? -1 * coins : coins,
      date: new Date(ctmDate * 1000),
      description: ctmDescription,
    });
  }
}

<commit_msg>update transaction search to new api results<commit_after>// @flow
import ClientApi from 'daedalus-client-api';
import { action } from 'mobx';
import Wallet from '../domain/Wallet';
import WalletTransaction from '../domain/WalletTransaction';
import type {
  createWalletRequest,
  getTransactionsRequest,
  createTransactionRequest,
} from './index';
import { user } from './fixtures';
import User from '../domain/User';
import Profile from '../domain/Profile';

const notYetImplemented = () => new Promise((resolve, reject) => reject(new Error('Api method not yet implemented')));

export default class CardanoClientApi {

  login() {
    // TODO: Implement when backend is ready for it
    return new Promise((resolve) => resolve(true));
  }

  getUser() {
    return new Promise((resolve) => {
      setTimeout(action(() => {
        resolve(new User(user.id, new Profile(user.profile)));
      }), 0);
    });
  }

  async getWallets() {
    const response = await ClientApi.getWallets();
    return response.map(data => this._createWalletFromData(data));
  }

  async getTransactions({ walletId, searchTerm, limit }: getTransactionsRequest) {
    const history = await ClientApi.searchHistory(walletId, searchTerm, limit)();
    return new Promise((resolve) => resolve({
      transactions: history[0].map(data => this._createTransactionFromData(data, walletId)),
      total: history[1]
    }));
  }

  createUser() {
    return notYetImplemented();
  }

  async createWallet(request: createWalletRequest) {
    const response = await ClientApi.newWallet('CWTPersonal', 'ADA', request.name)();
    return this._createWalletFromData(response);
  }

  async createTransaction(request: createTransactionRequest) {
    const { sender, receiver, amount, currency, description, title } = request;
    const response = await ClientApi.sendExtended(sender, receiver, amount, currency, title, description)();
    return this._createTransactionFromData(response);
  }

  isValidAddress(currency: string, address: string) {
    return ClientApi.isValidAddress(currency, address)();
  }

  updateProfileField() {
    return notYetImplemented();
  }

  @action _createWalletFromData(data) {
    return new Wallet({
      id: data.cwAddress,
      address: data.cwAddress,
      amount: data.cwAmount.getCoin,
      type: data.cwMeta.cwType,
      currency: data.cwMeta.cwCurrency,
      name: data.cwMeta.cwName,
    });
  }

  @action _createTransactionFromData(data) {
    const isOutgoing = data.ctType.tag === 'CTOut';
    const coins = data.ctAmount.getCoin;
    const { ctmTitle, ctmDescription, ctmDate } = data.ctType.contents;
    return new WalletTransaction({
      id: data.ctId,
      title: ctmTitle,
      type: isOutgoing ? 'adaExpend' : 'adaIncome',
      currency: 'ada',
      amount: isOutgoing ? -1 * coins : coins,
      date: new Date(ctmDate * 1000),
      description: ctmDescription,
    });
  }
}

<|endoftext|>


<commit_before>class CodeView extends HTMLElement {
  constructor(codeViewData) {
    super();

    this.editorProperties = codeViewData.editorProperties;
    this.width = codeViewData.playbackNavigatorWidth;
    this.playbackEngine = codeViewData.playbackEngine;

    this.attachShadow({ mode: 'open' });
    this.shadowRoot.appendChild(this.getTemplate());
  }

  getTemplate() {
    const template = document.createElement('template');
    template.innerHTML = `

        <svg xmlns="http://www.w3.org/2000/svg" width="12" height="32" fill="gray" className="bi bi-grip-vertical" viewBox="4 2 8 8">
          <path d="M7 2a1 1 0 1 1-2 0 1 1 0 0 1 2 0zm3 0a1 1 0 1 1-2 0 1 1 0 0 1 2 0zM7 5a1 1 0 1 1-2 0 1 1 0 0 1 2 0zm3 0a1 1 0 1 1-2 0 1 1 0 0 1 2 0zM7 8a1 1 0 1 1-2 0 1 1 0 0 1 2 0zm3 0a1 1 0 1 1-2 0 1 1 0 0 1 2 0zm-3 3a1 1 0 1 1-2 0 1 1 0 0 1 2 0zm3 0a1 1 0 1 1-2 0 1 1 0 0 1 2 0zm-3 3a1 1 0 1 1-2 0 1 1 0 0 1 2 0zm3 0a1 1 0 1 1-2 0 1 1 0 0 1 2 0z" />
        </svg>

`;

    return template.content.cloneNode(true);
  }

  connectedCallback() {
    //set the initial width of the elements
    this.setWidthInPixels(this.width);

    //add the playback navigator
    const playbackNavigatorSlot = this.shadowRoot.querySelector('.playbackNavigatorSlot');
    const playbackNavigator = new PlaybackNavigator(this.playbackEngine);
    playbackNavigatorSlot.appendChild(playbackNavigator);

    //add the editor view
    const editorViewSlot = this.shadowRoot.querySelector('.editorViewSlot');
    const editorView = new EditorView({
      editorProperties: this.editorProperties,
      playbackEngine: this.playbackEngine
    });
    editorViewSlot.appendChild(editorView);

    //add the adjustable drag bar separating the playback nav and the editor view
    const dragBar = this.shadowRoot.querySelector('.dragBar');
    //events to handle dragging
    dragBar.addEventListener('mousedown', this.addMouseEventListeners);
    //for mobile devices add touch events too
    dragBar.addEventListener('touchstart', this.addTouchEventListeners);

    //double clicking the drag bar will divide the comment navigator and editor view 50/50
    dragBar.addEventListener('dblclick', (event)=>{
      const currentXPos = event.pageX;
      const codeView = this.shadowRoot.host;
      const screenWidthHalf = codeView.getBoundingClientRect().width / 2;
      if (screenWidthHalf != currentXPos){
        this.setWidthInPixels(screenWidthHalf);
      }
    });
  }

  disconnectedCallback() {
    const dragBar = this.shadowRoot.querySelector('.dragBar');
    dragBar.removeEventListener('mousedown', this.addMouseEventListeners);
    dragBar.removeEventListener('touchstart', this.addTouchEventListeners);
  }

  doDrag = event => {
    const codeView = this.shadowRoot.host;
    const codeViewWidth = codeView.getBoundingClientRect().width;
    const minWidth = .05 * codeViewWidth;
    const maxWidth = .95 * codeViewWidth;

    let newX = 0;
    //if this is a touch event
    if(event.touches) {
      newX = event.touches[0].pageX;
    } else { //it is a mouse down
      newX = event.pageX;
    }
    let newWidth = newX - codeView.offsetLeft;
    if(newWidth < minWidth) {
      newWidth = minWidth;
    } else if(newWidth >= maxWidth) {
      newWidth = maxWidth;
    }

    this.setWidthInPixels(newWidth);
    this.width = newWidth;
    this.sendEventNewWidth(newWidth);
  }

  stopDrag = event => {
    document.removeEventListener('mouseup', this.stopDrag, false);
    document.removeEventListener('mousemove', this.doDrag, false);

    document.removeEventListener('touchend', this.stopDrag, false);
    document.removeEventListener('touchmove', this.doDrag, false);
  }

  addMouseEventListeners = () => {
    document.addEventListener('mousemove', this.doDrag, false);
    document.addEventListener('mouseup', this.stopDrag, false);
  }

  addTouchEventListeners = () => {
    document.addEventListener('touchmove', this.doDrag, false);
    document.addEventListener('touchend', this.stopDrag, false);
  }

  setWidthInPixels(newWidth) {
    const codeView = this.shadowRoot.host;
    const codeViewWidth = codeView.getBoundingClientRect().width;

    const dragBar = this.shadowRoot.querySelector('.dragBar');
    const dragBarWidth = dragBar.getBoundingClientRect().width;

    const playbackNavigatorSlot = this.shadowRoot.querySelector('.playbackNavigatorSlot');
    const editorViewSlot = this.shadowRoot.querySelector('.editorViewSlot');

    playbackNavigatorSlot.style.width = newWidth + 'px';
    editorViewSlot.style.width = (codeViewWidth - dragBarWidth - newWidth) + 'px';
  }

  sendEventNewWidth(newWidth) {
    const event = new CustomEvent('code-view-width-change', {
      detail: {width: newWidth},
      bubbles: true,
      composed: true
    });
    this.dispatchEvent(event);
  }

  updateSliderMoved(isPaused=true) {
    const editorView = this.shadowRoot.querySelector('st-editor-view');
    editorView.update(isPaused);

    const playbackNavigator = this.shadowRoot.querySelector('st-playback-navigator');
    playbackNavigator.updateSliderMoved();
  }

  updateSelectedComment() {
    const editorView = this.shadowRoot.querySelector('st-editor-view');
    editorView.update();

    const playbackNavigator = this.shadowRoot.querySelector('st-playback-navigator');
    playbackNavigator.updateSelectedComment();
  }

  updateActiveFile() {
    const editorView = this.shadowRoot.querySelector('st-editor-view');
    editorView.updateActiveFile();

    const playbackNavigator = this.shadowRoot.querySelector('st-playback-navigator');
    playbackNavigator.updateActiveFile();
  }

  performSearch(searchText){
    const playbackNavigator = this.shadowRoot.querySelector('st-playback-navigator');
    playbackNavigator.performSearch(searchText);
  }
}

window.customElements.define('st-code-view', CodeView);<commit_msg>Disable text selection while dragging the drag bar<commit_after>class CodeView extends HTMLElement {
  constructor(codeViewData) {
    super();

    this.editorProperties = codeViewData.editorProperties;
    this.width = codeViewData.playbackNavigatorWidth;
    this.playbackEngine = codeViewData.playbackEngine;

    this.attachShadow({ mode: 'open' });
    this.shadowRoot.appendChild(this.getTemplate());
  }

  getTemplate() {
    const template = document.createElement('template');
    template.innerHTML = `

        <svg xmlns="http://www.w3.org/2000/svg" width="12" height="32" fill="gray" className="bi bi-grip-vertical" viewBox="4 2 8 8">
          <path d="M7 2a1 1 0 1 1-2 0 1 1 0 0 1 2 0zm3 0a1 1 0 1 1-2 0 1 1 0 0 1 2 0zM7 5a1 1 0 1 1-2 0 1 1 0 0 1 2 0zm3 0a1 1 0 1 1-2 0 1 1 0 0 1 2 0zM7 8a1 1 0 1 1-2 0 1 1 0 0 1 2 0zm3 0a1 1 0 1 1-2 0 1 1 0 0 1 2 0zm-3 3a1 1 0 1 1-2 0 1 1 0 0 1 2 0zm3 0a1 1 0 1 1-2 0 1 1 0 0 1 2 0zm-3 3a1 1 0 1 1-2 0 1 1 0 0 1 2 0zm3 0a1 1 0 1 1-2 0 1 1 0 0 1 2 0z" />
        </svg>

`;

    return template.content.cloneNode(true);
  }

  connectedCallback() {
    //set the initial width of the elements
    this.setWidthInPixels(this.width);

    //add the playback navigator
    const playbackNavigatorSlot = this.shadowRoot.querySelector('.playbackNavigatorSlot');
    const playbackNavigator = new PlaybackNavigator(this.playbackEngine);
    playbackNavigatorSlot.appendChild(playbackNavigator);

    //add the editor view
    const editorViewSlot = this.shadowRoot.querySelector('.editorViewSlot');
    const editorView = new EditorView({
      editorProperties: this.editorProperties,
      playbackEngine: this.playbackEngine
    });
    editorViewSlot.appendChild(editorView);

    //add the adjustable drag bar separating the playback nav and the editor view
    const dragBar = this.shadowRoot.querySelector('.dragBar');
    //events to handle dragging
    dragBar.addEventListener('mousedown', this.addMouseEventListeners);
    //for mobile devices add touch events too
    dragBar.addEventListener('touchstart', this.addTouchEventListeners);

    //double clicking the drag bar will divide the comment navigator and editor view 50/50
    dragBar.addEventListener('dblclick', (event)=>{
      const currentXPos = event.pageX;
      const codeView = this.shadowRoot.host;
      const screenWidthHalf = codeView.getBoundingClientRect().width / 2;
      if (screenWidthHalf != currentXPos){
        this.setWidthInPixels(screenWidthHalf);
      }
    });
  }

  disconnectedCallback() {
    const dragBar = this.shadowRoot.querySelector('.dragBar');
    dragBar.removeEventListener('mousedown', this.addMouseEventListeners);
    dragBar.removeEventListener('touchstart', this.addTouchEventListeners);
  }

  doDrag = event => {
    const codeView = this.shadowRoot.host;
    const codeViewWidth = codeView.getBoundingClientRect().width;
    const minWidth = .05 * codeViewWidth;
    const maxWidth = .95 * codeViewWidth;

    let newX = 0;
    //if this is a touch event
    if(event.touches) {
      newX = event.touches[0].pageX;
    } else { //it is a mouse down
      newX = event.pageX;
    }
    let newWidth = newX - codeView.offsetLeft;
    if(newWidth < minWidth) {
      newWidth = minWidth;
    } else if(newWidth >= maxWidth) {
      newWidth = maxWidth;
    }

    this.setWidthInPixels(newWidth);
    this.width = newWidth;
    this.sendEventNewWidth(newWidth);
  }

  stopDrag = event => {
    document.removeEventListener('mouseup', this.stopDrag, false);
    document.removeEventListener('mousemove', this.doDrag, false);

    document.removeEventListener('touchend', this.stopDrag, false);
    document.removeEventListener('touchmove', this.doDrag, false);
  }

  addMouseEventListeners = () => {
    document.addEventListener('mousemove', this.doDrag, false);
    document.addEventListener('mouseup', this.stopDrag, false);
  }

  addTouchEventListeners = () => {
    document.addEventListener('touchmove', this.doDrag, false);
    document.addEventListener('touchend', this.stopDrag, false);
  }

  setWidthInPixels(newWidth) {
    const codeView = this.shadowRoot.host;
    const codeViewWidth = codeView.getBoundingClientRect().width;

    const dragBar = this.shadowRoot.querySelector('.dragBar');
    const dragBarWidth = dragBar.getBoundingClientRect().width;

    const playbackNavigatorSlot = this.shadowRoot.querySelector('.playbackNavigatorSlot');
    const editorViewSlot = this.shadowRoot.querySelector('.editorViewSlot');

    playbackNavigatorSlot.style.width = newWidth + 'px';
    editorViewSlot.style.width = (codeViewWidth - dragBarWidth - newWidth) + 'px';
  }

  sendEventNewWidth(newWidth) {
    const event = new CustomEvent('code-view-width-change', {
      detail: {width: newWidth},
      bubbles: true,
      composed: true
    });
    this.dispatchEvent(event);
  }

  updateSliderMoved(isPaused=true) {
    const editorView = this.shadowRoot.querySelector('st-editor-view');
    editorView.update(isPaused);

    const playbackNavigator = this.shadowRoot.querySelector('st-playback-navigator');
    playbackNavigator.updateSliderMoved();
  }

  updateSelectedComment() {
    const editorView = this.shadowRoot.querySelector('st-editor-view');
    editorView.update();

    const playbackNavigator = this.shadowRoot.querySelector('st-playback-navigator');
    playbackNavigator.updateSelectedComment();
  }

  updateActiveFile() {
    const editorView = this.shadowRoot.querySelector('st-editor-view');
    editorView.updateActiveFile();

    const playbackNavigator = this.shadowRoot.querySelector('st-playback-navigator');
    playbackNavigator.updateActiveFile();
  }

  performSearch(searchText){
    const playbackNavigator = this.shadowRoot.querySelector('st-playback-navigator');
    playbackNavigator.performSearch(searchText);
  }
}

window.customElements.define('st-code-view', CodeView);<|endoftext|>


<commit_before>import Ember from 'ember';
var Network = require('asNEAT/network')['default'];

export default Ember.Controller.extend({
  needs: ['application'],

  // set by route
  // {user, instruments: []}

  isCurrentUser: function() {
    var application = this.get('controllers.application');
    return this.get('user.id') ===
      application.get('currentUser.id');
  }.property(
    'user.id',
    'controllers.application.currentUser.id'),

  updateOnLogin: function() {
    var pageUserId = this.get('user.id'),
        currentUserId = this.get('controllers.application.currentUser.id');
    if (pageUserId === currentUserId) {
      this.set('instruments', this.store.find('instrument', {
        user: pageUserId
      }));
    }
  }.observes('controllers.application.currentUser.id'),

  instrumentParams: function() {
    var instruments = this.get('instruments');
    if (!instruments.toArray)
      return [];

    return _.map(instruments.toArray(),
      function(instrument) {
        return {
          instrumentNetwork: Network.createFromJSON(instrument.get('json')),
          selected: false,
          isLive: false,
          index: 0,
          instrumentModel: instrument
        };
    });
  }.property('instruments.@each')
});
<commit_msg>make first user's page instruments live<commit_after>import Ember from 'ember';
var Network = require('asNEAT/network')['default'];

export default Ember.Controller.extend({
  needs: ['application'],

  // set by route
  // {user, instruments: []}

  isCurrentUser: function() {
    var application = this.get('controllers.application');
    return this.get('user.id') ===
      application.get('currentUser.id');
  }.property(
    'user.id',
    'controllers.application.currentUser.id'),

  updateOnLogin: function() {
    var pageUserId = this.get('user.id'),
        currentUserId = this.get('controllers.application.currentUser.id');
    if (pageUserId === currentUserId) {
      this.set('instruments', this.store.find('instrument', {
        user: pageUserId
      }));
    }
  }.observes('controllers.application.currentUser.id'),

  instrumentParams: function() {
    var instruments = this.get('instruments');
    if (!instruments.toArray)
      return [];

    return _.map(instruments.toArray(),
      function(instrument, i) {
        return {
          instrumentNetwork: Network.createFromJSON(instrument.get('json')),
          selected: false,
          isLive: i===0,
          index: i,
          instrumentModel: instrument
        };
    });
  }.property('instruments.@each'),

  selectInitialInstrument: function() {
    var instruments = this.get('instrumentParams');
    if (instruments.length > 0)
      this.get('controllers.application')
          .set('activeInstrument', instruments[0]);
  }.observes('instrumentParams.@each'),
});
<|endoftext|>


<commit_before>/*!
 * ${copyright}
 */

/*
 * IMPORTANT: This is a private module, its API must not be used and is subject to change.
 * Code other than the Core tests must not yet introduce dependencies to this module.
 */

/*global QUnit, sinon, */

(function(deps, callback) {

	"use strict";

	//extract base URL from script tag
	var oScriptTag, mMatch, sBaseUrl, bCoverage;

	oScriptTag = document.querySelector("[src$='runTest.js']");
	if (oScriptTag) {
		mMatch = /^([^?#]*\/)?runTest.js/.exec(oScriptTag.getAttribute("src"));
		if (mMatch) {
			sBaseUrl = mMatch[1] + "../../../../";
		}
	}

	if (sBaseUrl == null) {
		throw new Error("runTest.js: could not identify script tag!");
	}

	bCoverage = /(?:^|\?|&)coverage(?:&|=|$)/.test(window.location.search);

	function loadScripts(urls, callback) {
		var pending = urls.length,
			errors = 0;

		function listener(e) {
			pending--;
			if ( e.type === 'error' ) {
				errors++;
			}
			e.target.removeEventListener("load", listener);
			e.target.removeEventListener("error", listener);
			if ( pending === 0 && errors === 0 && callback ) {
				callback();
			}
		}

		for ( var i = 0; i < urls.length; i++ ) {
			var script = document.createElement("script");
			script.addEventListener("load", listener);
			script.addEventListener("error", listener);
			script.src = sBaseUrl + urls[i];
			document.head.appendChild(script);
		}
	}

	// cascade 1: polyfills, can all be loaded in parallel
	loadScripts([
		"sap/ui/thirdparty/baseuri.js",
		"sap/ui/thirdparty/es6-promise.js",
		"sap/ui/thirdparty/es6-string-methods.js",
		"sap/ui/thirdparty/es6-object-assign.js"
	], function() {
		// cascade 2: the loader
		loadScripts([
			"ui5loader.js"
		], function() {
			// cascade 3: the loader configuration script
			sap.ui.loader.config({
				async: !bCoverage // run sync when client side coverage is requested
			});
			loadScripts([
				"ui5loader-autoconfig.js"
			], function() {
				sap.ui.require(deps, callback);
			});
		});
	});

}([
	"sap/base/util/UriParameters",
	"sap/ui/test/starter/_utils"
], function(UriParameters, utils) {
	"use strict";

	function makeArray(arg) {
		return Array.isArray(arg) ? arg : [arg];
	}

	function requireP(deps) {
		return new Promise(function(resolve, reject) {
			sap.ui.require(makeArray(deps), function() {
				resolve(arguments);
			}, reject);
		});
	}

	function copyFiltered(target, source, filter) {
		if ( source ) {
			for ( var key in source ) {
				if ( Object.prototype.hasOwnProperty.call(filter, key) ) {
					target[key] = source[key];
				}
			}
		}
		return target;
	}

	function ensureDOM() {
		function insertDIV(id) {
			if ( document.body.querySelector("#" + id) == null ) {
				var elem = document.createElement("div");
				elem.id = id;
				document.body.insertBefore(elem, document.body.firstChild);
			}
		}

		return utils.whenDOMReady().then(function() {
			/* Prepare body: Add QUnit DOM if missing, add CSS, ... */
			insertDIV("qunit");
			insertDIV("qunit-fixture");
		});
	}

	/*
	 * @const
	 */
	var QUNIT_KNOWN_OPTIONS = {
		altertitle: 1,
		collapse: 1,
		filter: 1,
		fixture: 1,
		hidepassed: 1,
		maxDepth: 1,
		module: 1,
		moduleId: 1,
		notrycatch: 1,
		noglobals: 1,
		seed: 1,
		reorder: 1,
		requireExpects: 1,
		testId: 1,
		testTimeout: 1,
		scrolltop: 1
	};

	function initTestModule(oConfig) {
		var pQUnit, pSinon, pSinonQUnitBridge, pSinonConfig, pCoverage, pTestEnv,
			sQUnit, aJUnitDoneCallbacks;

		document.title = oConfig.title;

		// first configure the loader if needed
		if ( oConfig.loader ) {
			sap.ui.loader.config(oConfig.loader);
		}

		if ( oConfig.qunit.version === "edge" || oConfig.qunit.version === true ) {
			oConfig.qunit.version = 2;
		}
		if ( typeof oConfig.qunit.version === "number" ) {

			// QUnit configuration can be set in advance, we always disable the autostart
			window.QUnit = window.QUnit || {};
			QUnit.config = QUnit.config || {};
			if ( oConfig.qunit != null && typeof oConfig.qunit === 'object' ) {
				copyFiltered(QUnit.config, oConfig.qunit, QUNIT_KNOWN_OPTIONS);
			}
			QUnit.config.autostart = false;

			// now load QUnit, its CSS + the reporter bridge
			pQUnit = new Promise(function(resolve, reject) {
				if ( oConfig.qunit.version === 1 ) {
					utils.addStylesheet("sap/ui/thirdparty/qunit.css");
					resolve( requireP(sQUnit = "sap/ui/thirdparty/qunit") );
				} else if ( oConfig.qunit.version === 2 ) {
					utils.addStylesheet("sap/ui/thirdparty/qunit-2.css");
					resolve( requireP(sQUnit = "sap/ui/thirdparty/qunit-2") );
				} else {
					throw new TypeError("unsupported qunit version " + oConfig.qunit.version);
				}
			}).then(function() {
				// install a mock version of the qunit-reporter-junit API to collect jUnitDone callbacks
				aJUnitDoneCallbacks = [];
				QUnit.jUnitDone = function(cb) {
					aJUnitDoneCallbacks.push(cb);
				};
				return requireP("sap/ui/qunit/qunit-junit");
			}).then(function() {
				delete QUnit.jUnitDone;
				return requireP("sap/ui/thirdparty/qunit-reporter-junit");
			}).then(function() {
				// now register the collected callbacks with the real qunit-reporter-junit API
				aJUnitDoneCallbacks.forEach(function(cb) {
					QUnit.jUnitDone(cb);
				});
				aJUnitDoneCallbacks = undefined;
			});
		}

		if ( oConfig.sinon.version === "edge" || oConfig.sinon.version === true ) {
			oConfig.sinon.version = 4;
		}
		if ( typeof oConfig.sinon.version === "number" ) {
			var bridge;
			if ( oConfig.sinon.version === 1 ) {
				pSinon = requireP("sap/ui/thirdparty/sinon");
				bridge = "sap/ui/thirdparty/sinon-qunit";
			} else if ( oConfig.sinon.version === 4 ) {
				pSinon = requireP("sap/ui/thirdparty/sinon-4");
				bridge = "sap/ui/qunit/sinon-qunit-bridge";
			} else {
				throw new TypeError("unsupported sinon version " + oConfig.sinon.version);
			}

			if ( oConfig.sinon.qunitBridge && pQUnit ) {
				pSinonQUnitBridge = Promise.all([
					pQUnit,
					pSinon
				]).then(function() {
					return requireP(bridge);
				});
			}

			// sinon configuration must be applied only after sinon AND bridge have been loaded,
			// they both set their own defaults
			if ( oConfig.sinon != null && typeof oConfig.sinon === 'object' ) {
				pSinonConfig = Promise.all([
					pSinon,
					pSinonQUnitBridge
				]).then(function() {
					// copy only settings that are listed in sinon.defaultConfig
					sinon.config = copyFiltered(sinon.config || {}, oConfig.sinon, sinon.defaultConfig);
					return arguments;
				});
			}

		} else if ( sQUnit ) {
			// shim dependencies for the bridges, based on the selected QUnit version
			// might be needed if tests load the bridge on their own
			sap.ui.loader.config({
				shim: {
					"sap/ui/thirdparty/sinon-qunit": {
						deps: [sQUnit, "sap/ui/thirdparty/sinon"]
					},
					"sap/ui/qunit/sinon-qunit-bridge": {
						deps: [sQUnit, "sap/ui/thirdparty/sinon-4"]
					}
				}
			});
		}

		pCoverage = pQUnit.then(function() {
			if ( QUnit.urlParams.coverage ) {
				// when coverage has been activated in a QUnit page via checkbox,
				// then load blanket, configure it, then load the QUnit plugin
				return requireP("sap/ui/thirdparty/blanket").then(function() {
					if ( oConfig.coverage && window.blanket ) {
						if (oConfig.coverage.only != null) {
							window.blanket.options("sap-ui-cover-only", oConfig.coverage.only);
						}
						if (oConfig.coverage.never != null) {
							window.blanket.options("sap-ui-cover-never", oConfig.coverage.never);
						}
						if (oConfig.coverage.branchTracking) {
							window.blanket.options("branchTracking", true);
						}
					}
					return requireP("sap/ui/qunit/qunit-coverage");
				}).then(function() {
					// when coverage is active, qunit-coverage sets autostart to true again
					QUnit.config.autostart = false;
				});
			} else {
				// otherwise load only the QUnit plugin
				return requireP(["sap/ui/qunit/qunit-coverage"]);
			}
		});

		pTestEnv = Promise.all([
			pQUnit,
			pSinon,
			pSinonQUnitBridge,
			pSinonConfig,
			pCoverage
		]);

		if ( oConfig.beforeBootstrap ) {
			pTestEnv = pTestEnv.then(function() {
				return requireP(oConfig.beforeBootstrap);
			});
		}

		// copy UI5 configuration
		window["sap-ui-config"] = oConfig.ui5 || {};
		if ( Array.isArray(window["sap-ui-config"].libs) ) {
			window["sap-ui-config"].libs = window["sap-ui-config"].libs.join(",");
		}

		if ( oConfig.bootCore ) {
			pTestEnv = pTestEnv.then(function() {
				return new Promise(function(resolve, reject) {
					sap.ui.require(["sap/ui/core/Core"], function(core) {
						core.boot();
						core.attachInit(resolve);
					});
				});
			});
		}

		return pTestEnv.then(function() {
			if (oConfig.autostart) {
				// first load the tests, then ensure DOM then start tests
				return requireP( oConfig.module ). // Note: accepts single module or array
					then(function(aTestModules) {
						return Promise.all(aTestModules);
					}).then(function() {
						return ensureDOM();
					}).then(function() {
						QUnit.start();
					});
			} else {
				// first ensure the DOM then load tests as tests will start QUnit already
				return ensureDOM().then(function() {
					return requireP( oConfig.module ). // Note: accepts single module or array
						then(function(aTestModules) {
							return Promise.all(aTestModules);
						});
				});
			}
		});

	}

	var oParams = new UriParameters(window.location.href),
		sSuiteName = utils.getAttribute('data-sap-ui-testsuite') || oParams.get("testsuite"),
		sTestName = utils.getAttribute('data-sap-ui-test') || oParams.get("test");

	utils.getSuiteConfig(sSuiteName).then(function(oSuiteConfig) {
		var oTestConfig = oSuiteConfig.tests[sTestName];
		if (!oTestConfig) {
			throw new TypeError("Invalid test name");
		}

		return initTestModule(oTestConfig);
	}).catch(function(oErr) {
		console.error(oErr.stack || oErr); // eslint-disable-line no-console
		utils.whenDOMReady().then(function() {
			document.body.innerHTML = "
" + utils.encode(oErr.stack || oErr.message || String(oErr)) + "
";
		});
	});

}));
<commit_msg>[INTERNAL][FIX] Test Starter: make recent improvement work on IE11<commit_after>/*!
 * ${copyright}
 */

/*
 * IMPORTANT: This is a private module, its API must not be used and is subject to change.
 * Code other than the Core tests must not yet introduce dependencies to this module.
 */

/*global QUnit, sinon, */

(function(deps, callback) {

	"use strict";

	//extract base URL from script tag
	var oScriptTag, mMatch, sBaseUrl, bCoverage;

	oScriptTag = document.querySelector("[src$='runTest.js']");
	if (oScriptTag) {
		mMatch = /^([^?#]*\/)?runTest.js/.exec(oScriptTag.getAttribute("src"));
		if (mMatch) {
			sBaseUrl = mMatch[1] + "../../../../";
		}
	}

	if (sBaseUrl == null) {
		throw new Error("runTest.js: could not identify script tag!");
	}

	bCoverage = /(?:^|\?|&)coverage(?:&|=|$)/.test(window.location.search);

	function loadScripts(urls, callback) {
		var pending = urls.length,
			errors = 0;

		function listener(e) {
			pending--;
			if ( e.type === 'error' ) {
				errors++;
			}
			e.target.removeEventListener("load", listener);
			e.target.removeEventListener("error", listener);
			if ( pending === 0 && errors === 0 && callback ) {
				callback();
			}
		}

		for ( var i = 0; i < urls.length; i++ ) {
			var script = document.createElement("script");
			script.addEventListener("load", listener);
			script.addEventListener("error", listener);
			script.src = sBaseUrl + urls[i];
			document.head.appendChild(script);
		}
	}

	// cascade 1: polyfills, can all be loaded in parallel
	loadScripts([
		"sap/ui/thirdparty/baseuri.js",
		"sap/ui/thirdparty/es6-promise.js",
		"sap/ui/thirdparty/es6-string-methods.js",
		"sap/ui/thirdparty/es6-object-assign.js"
	], function() {
		// cascade 2: the loader
		loadScripts([
			"ui5loader.js"
		], function() {
			// cascade 3: the loader configuration script
			sap.ui.loader.config({
				async: !bCoverage // run sync when client side coverage is requested
			});
			loadScripts([
				"ui5loader-autoconfig.js"
			], function() {
				sap.ui.require(deps, callback);
			});
		});
	});

}([
	"sap/base/util/UriParameters",
	"sap/ui/test/starter/_utils"
], function(UriParameters, utils) {
	"use strict";

	function makeArray(arg) {
		return Array.isArray(arg) ? arg : [arg];
	}

	function requireP(deps) {
		return new Promise(function(resolve, reject) {
			sap.ui.require(makeArray(deps), function() {
				resolve(Array.prototype.slice.call(arguments));
			}, reject);
		});
	}

	function copyFiltered(target, source, filter) {
		if ( source ) {
			for ( var key in source ) {
				if ( Object.prototype.hasOwnProperty.call(filter, key) ) {
					target[key] = source[key];
				}
			}
		}
		return target;
	}

	function ensureDOM() {
		function insertDIV(id) {
			if ( document.body.querySelector("#" + id) == null ) {
				var elem = document.createElement("div");
				elem.id = id;
				document.body.insertBefore(elem, document.body.firstChild);
			}
		}

		return utils.whenDOMReady().then(function() {
			/* Prepare body: Add QUnit DOM if missing, add CSS, ... */
			insertDIV("qunit");
			insertDIV("qunit-fixture");
		});
	}

	/*
	 * @const
	 */
	var QUNIT_KNOWN_OPTIONS = {
		altertitle: 1,
		collapse: 1,
		filter: 1,
		fixture: 1,
		hidepassed: 1,
		maxDepth: 1,
		module: 1,
		moduleId: 1,
		notrycatch: 1,
		noglobals: 1,
		seed: 1,
		reorder: 1,
		requireExpects: 1,
		testId: 1,
		testTimeout: 1,
		scrolltop: 1
	};

	function initTestModule(oConfig) {
		var pQUnit, pSinon, pSinonQUnitBridge, pSinonConfig, pCoverage, pTestEnv,
			sQUnit, aJUnitDoneCallbacks;

		document.title = oConfig.title;

		// first configure the loader if needed
		if ( oConfig.loader ) {
			sap.ui.loader.config(oConfig.loader);
		}

		if ( oConfig.qunit.version === "edge" || oConfig.qunit.version === true ) {
			oConfig.qunit.version = 2;
		}
		if ( typeof oConfig.qunit.version === "number" ) {

			// QUnit configuration can be set in advance, we always disable the autostart
			window.QUnit = window.QUnit || {};
			QUnit.config = QUnit.config || {};
			if ( oConfig.qunit != null && typeof oConfig.qunit === 'object' ) {
				copyFiltered(QUnit.config, oConfig.qunit, QUNIT_KNOWN_OPTIONS);
			}
			QUnit.config.autostart = false;

			// now load QUnit, its CSS + the reporter bridge
			pQUnit = new Promise(function(resolve, reject) {
				if ( oConfig.qunit.version === 1 ) {
					utils.addStylesheet("sap/ui/thirdparty/qunit.css");
					resolve( requireP(sQUnit = "sap/ui/thirdparty/qunit") );
				} else if ( oConfig.qunit.version === 2 ) {
					utils.addStylesheet("sap/ui/thirdparty/qunit-2.css");
					resolve( requireP(sQUnit = "sap/ui/thirdparty/qunit-2") );
				} else {
					throw new TypeError("unsupported qunit version " + oConfig.qunit.version);
				}
			}).then(function() {
				// install a mock version of the qunit-reporter-junit API to collect jUnitDone callbacks
				aJUnitDoneCallbacks = [];
				QUnit.jUnitDone = function(cb) {
					aJUnitDoneCallbacks.push(cb);
				};
				return requireP("sap/ui/qunit/qunit-junit");
			}).then(function() {
				delete QUnit.jUnitDone;
				return requireP("sap/ui/thirdparty/qunit-reporter-junit");
			}).then(function() {
				// now register the collected callbacks with the real qunit-reporter-junit API
				aJUnitDoneCallbacks.forEach(function(cb) {
					QUnit.jUnitDone(cb);
				});
				aJUnitDoneCallbacks = undefined;
			});
		}

		if ( oConfig.sinon.version === "edge" || oConfig.sinon.version === true ) {
			oConfig.sinon.version = 4;
		}
		if ( typeof oConfig.sinon.version === "number" ) {
			var bridge;
			if ( oConfig.sinon.version === 1 ) {
				pSinon = requireP("sap/ui/thirdparty/sinon");
				bridge = "sap/ui/thirdparty/sinon-qunit";
			} else if ( oConfig.sinon.version === 4 ) {
				pSinon = requireP("sap/ui/thirdparty/sinon-4");
				bridge = "sap/ui/qunit/sinon-qunit-bridge";
			} else {
				throw new TypeError("unsupported sinon version " + oConfig.sinon.version);
			}

			if ( oConfig.sinon.qunitBridge && pQUnit ) {
				pSinonQUnitBridge = Promise.all([
					pQUnit,
					pSinon
				]).then(function() {
					return requireP(bridge);
				});
			}

			// sinon configuration must be applied only after sinon AND bridge have been loaded,
			// they both set their own defaults
			if ( oConfig.sinon != null && typeof oConfig.sinon === 'object' ) {
				pSinonConfig = Promise.all([
					pSinon,
					pSinonQUnitBridge
				]).then(function() {
					// copy only settings that are listed in sinon.defaultConfig
					sinon.config = copyFiltered(sinon.config || {}, oConfig.sinon, sinon.defaultConfig);
					return arguments;
				});
			}

		} else if ( sQUnit ) {
			// shim dependencies for the bridges, based on the selected QUnit version
			// might be needed if tests load the bridge on their own
			sap.ui.loader.config({
				shim: {
					"sap/ui/thirdparty/sinon-qunit": {
						deps: [sQUnit, "sap/ui/thirdparty/sinon"]
					},
					"sap/ui/qunit/sinon-qunit-bridge": {
						deps: [sQUnit, "sap/ui/thirdparty/sinon-4"]
					}
				}
			});
		}

		pCoverage = pQUnit.then(function() {
			if ( QUnit.urlParams.coverage ) {
				// when coverage has been activated in a QUnit page via checkbox,
				// then load blanket, configure it, then load the QUnit plugin
				return requireP("sap/ui/thirdparty/blanket").then(function() {
					if ( oConfig.coverage && window.blanket ) {
						if (oConfig.coverage.only != null) {
							window.blanket.options("sap-ui-cover-only", oConfig.coverage.only);
						}
						if (oConfig.coverage.never != null) {
							window.blanket.options("sap-ui-cover-never", oConfig.coverage.never);
						}
						if (oConfig.coverage.branchTracking) {
							window.blanket.options("branchTracking", true);
						}
					}
					return requireP("sap/ui/qunit/qunit-coverage");
				}).then(function() {
					// when coverage is active, qunit-coverage sets autostart to true again
					QUnit.config.autostart = false;
				});
			} else {
				// otherwise load only the QUnit plugin
				return requireP(["sap/ui/qunit/qunit-coverage"]);
			}
		});

		pTestEnv = Promise.all([
			pQUnit,
			pSinon,
			pSinonQUnitBridge,
			pSinonConfig,
			pCoverage
		]);

		if ( oConfig.beforeBootstrap ) {
			pTestEnv = pTestEnv.then(function() {
				return requireP(oConfig.beforeBootstrap);
			});
		}

		// copy UI5 configuration
		window["sap-ui-config"] = oConfig.ui5 || {};
		if ( Array.isArray(window["sap-ui-config"].libs) ) {
			window["sap-ui-config"].libs = window["sap-ui-config"].libs.join(",");
		}

		if ( oConfig.bootCore ) {
			pTestEnv = pTestEnv.then(function() {
				return new Promise(function(resolve, reject) {
					sap.ui.require(["sap/ui/core/Core"], function(core) {
						core.boot();
						core.attachInit(resolve);
					});
				});
			});
		}

		return pTestEnv.then(function() {
			if (oConfig.autostart) {
				// first load the tests, then ensure DOM then start tests
				return requireP( oConfig.module ). // Note: accepts single module or array
					then(function(aTestModules) {
						return Promise.all(aTestModules);
					}).then(function() {
						return ensureDOM();
					}).then(function() {
						QUnit.start();
					});
			} else {
				// first ensure the DOM then load tests as tests will start QUnit already
				return ensureDOM().then(function() {
					return requireP( oConfig.module ). // Note: accepts single module or array
						then(function(aTestModules) {
							return Promise.all(aTestModules);
						});
				});
			}
		});

	}

	var oParams = new UriParameters(window.location.href),
		sSuiteName = utils.getAttribute('data-sap-ui-testsuite') || oParams.get("testsuite"),
		sTestName = utils.getAttribute('data-sap-ui-test') || oParams.get("test");

	utils.getSuiteConfig(sSuiteName).then(function(oSuiteConfig) {
		var oTestConfig = oSuiteConfig.tests[sTestName];
		if (!oTestConfig) {
			throw new TypeError("Invalid test name");
		}

		return initTestModule(oTestConfig);
	}).catch(function(oErr) {
		console.error(oErr.stack || oErr); // eslint-disable-line no-console
		utils.whenDOMReady().then(function() {
			document.body.innerHTML = "
" + utils.encode(oErr.stack || oErr.message || String(oErr)) + "
";
		});
	});

}));
<|endoftext|>


<commit_before>const RepositoryPrototype       = require('./repositoryPrototype');
const DB                        = require('./db');
const Errors                    = require('./../errors');

const Repositories = () => {};

Repositories.create = function (tableName, repositoryDefinition){
    if(!tableName){
        throw new Errors.Fatal(`Table name is missing in repository definition`);
    }

    const className = tableName[0].toUpperCase() + tableName.slice(1);
    const Repository = (new Function(`return function Repository${className} (){this.__table__ = '${tableName}'}`))();
    Repository.prototype = Object.create(RepositoryPrototype);
    Repository.prototype.db = DB;
    Object.assign(Repository.prototype, repositoryDefinition || {});

    return new Repository();
};

module.exports = Repositories;<commit_msg>Normalize request information<commit_after>const Errors                    = use('core/errors');

const RepositoryPrototype       = require('./repositoryPrototype');
const DB                        = require('./db');

const Repositories = () => {};

Repositories.create = function (tableName, repositoryDefinition){
    if(!tableName){
        throw new Errors.Fatal(`Table name is missing in repository definition`);
    }

    const className = tableName[0].toUpperCase() + tableName.slice(1);
    const Repository = (new Function(`return function Repository${className} (){this.__table__ = '${tableName}'}`))();
    Repository.prototype = Object.create(RepositoryPrototype);
    Repository.prototype.db = DB;
    Object.assign(Repository.prototype, repositoryDefinition || {});

    return new Repository();
};

module.exports = Repositories;<|endoftext|>


<commit_before>const path = require('path');
const test = require('tap').test;
const makeTestStorage = require('../fixtures/make-test-storage');
const extract = require('../fixtures/extract');
const VirtualMachine = require('../../src/index');
const Thread = require('../../src/engine/thread');
const Runtime = require('../../src/engine/runtime');

const projectUri = path.resolve(__dirname, '../fixtures/default.sb2');
const project = extract(projectUri);

const checkMonitorThreadPresent = (t, threads) => {
    t.equal(threads.length, 1);
    const monitorThread = threads[0];
    t.equal(monitorThread.stackClick, false);
    t.equal(monitorThread.updateMonitor, true);
    t.equal(monitorThread.topBlock.toString(), 'sensing_timer');
};

/**
 * Creates a monitor and then checks if it gets run every frame.
 */
/* TODO: when loadProject loads monitors, we can create a project with a monitor and will
 * not have to do the create monitor step manually.
 */
test('monitor thread runs every frame', t => {
    const vm = new VirtualMachine();
    vm.attachStorage(makeTestStorage());

    // Start VM, load project, and run
    t.doesNotThrow(() => {
        // Note: don't run vm.start(), we handle calling _step() manually in this test
        vm.runtime.currentStepTime = Runtime.THREAD_STEP_INTERVAL;

        // Manually populate the monitor block and set its isMonitored to true.
        vm.runtime.monitorBlocks.createBlock({
            id: 'sensing_timer',
            opcode: 'sensing_timer',
            inputs: {},
            fields: {},
            next: null,
            topLevel: true,
            parent: null,
            shadow: false,
            isMonitored: true,
            x: '0',
            y: '0'
        });

        vm.clear();
        vm.setCompatibilityMode(false);
        vm.setTurboMode(false);

        vm.loadProject(project).then(() => {
            t.equal(vm.runtime.threads.length, 0);

            vm.runtime._step();
            checkMonitorThreadPresent(t, vm.runtime.threads);
            t.assert(vm.runtime.threads[0].status === Thread.STATUS_DONE);

            // Check that both are added again when another step is taken
            vm.runtime._step();
            checkMonitorThreadPresent(t, vm.runtime.threads);
            t.assert(vm.runtime.threads[0].status === Thread.STATUS_DONE);
            t.end();
        });
    });
});

/**
 * If the monitor doesn't finish evaluating within one frame, it shouldn't be added again
 * on the next frame. (We skip execution by setting the step time to 0)
 */
test('monitor thread not added twice', t => {
    const vm = new VirtualMachine();
    vm.attachStorage(makeTestStorage());

    // Start VM, load project, and run
    t.doesNotThrow(() => {
        // Note: don't run vm.start(), we handle calling _step() manually in this test
        vm.runtime.currentStepTime = 0;

        // Manually populate the monitor block and set its isMonitored to true.
        vm.runtime.monitorBlocks.createBlock({
            id: 'sensing_timer',
            opcode: 'sensing_timer',
            inputs: {},
            fields: {},
            next: null,
            topLevel: true,
            parent: null,
            shadow: false,
            isMonitored: true,
            x: '0',
            y: '0'
        });

        vm.clear();
        vm.setCompatibilityMode(false);
        vm.setTurboMode(false);

        vm.loadProject(project).then(() => {
            t.equal(vm.runtime.threads.length, 0);

            debugger;
            vm.runtime._step();
            checkMonitorThreadPresent(t, vm.runtime.threads);
            t.assert(vm.runtime.threads[0].status === Thread.STATUS_RUNNING);
            const prevThread = vm.runtime.threads[0];

            // Check that both are added again when another step is taken
            vm.runtime._step();
            checkMonitorThreadPresent(t, vm.runtime.threads);
            t.equal(vm.runtime.threads[0], prevThread);
            t.end();
        });
    });
});
<commit_msg>remove debugger<commit_after>const path = require('path');
const test = require('tap').test;
const makeTestStorage = require('../fixtures/make-test-storage');
const extract = require('../fixtures/extract');
const VirtualMachine = require('../../src/index');
const Thread = require('../../src/engine/thread');
const Runtime = require('../../src/engine/runtime');

const projectUri = path.resolve(__dirname, '../fixtures/default.sb2');
const project = extract(projectUri);

const checkMonitorThreadPresent = (t, threads) => {
    t.equal(threads.length, 1);
    const monitorThread = threads[0];
    t.equal(monitorThread.stackClick, false);
    t.equal(monitorThread.updateMonitor, true);
    t.equal(monitorThread.topBlock.toString(), 'sensing_timer');
};

/**
 * Creates a monitor and then checks if it gets run every frame.
 */
/* TODO: when loadProject loads monitors, we can create a project with a monitor and will
 * not have to do the create monitor step manually.
 */
test('monitor thread runs every frame', t => {
    const vm = new VirtualMachine();
    vm.attachStorage(makeTestStorage());

    // Start VM, load project, and run
    t.doesNotThrow(() => {
        // Note: don't run vm.start(), we handle calling _step() manually in this test
        vm.runtime.currentStepTime = Runtime.THREAD_STEP_INTERVAL;

        // Manually populate the monitor block and set its isMonitored to true.
        vm.runtime.monitorBlocks.createBlock({
            id: 'sensing_timer',
            opcode: 'sensing_timer',
            inputs: {},
            fields: {},
            next: null,
            topLevel: true,
            parent: null,
            shadow: false,
            isMonitored: true,
            x: '0',
            y: '0'
        });

        vm.clear();
        vm.setCompatibilityMode(false);
        vm.setTurboMode(false);

        vm.loadProject(project).then(() => {
            t.equal(vm.runtime.threads.length, 0);

            vm.runtime._step();
            checkMonitorThreadPresent(t, vm.runtime.threads);
            t.assert(vm.runtime.threads[0].status === Thread.STATUS_DONE);

            // Check that both are added again when another step is taken
            vm.runtime._step();
            checkMonitorThreadPresent(t, vm.runtime.threads);
            t.assert(vm.runtime.threads[0].status === Thread.STATUS_DONE);
            t.end();
        });
    });
});

/**
 * If the monitor doesn't finish evaluating within one frame, it shouldn't be added again
 * on the next frame. (We skip execution by setting the step time to 0)
 */
test('monitor thread not added twice', t => {
    const vm = new VirtualMachine();
    vm.attachStorage(makeTestStorage());

    // Start VM, load project, and run
    t.doesNotThrow(() => {
        // Note: don't run vm.start(), we handle calling _step() manually in this test
        vm.runtime.currentStepTime = 0;

        // Manually populate the monitor block and set its isMonitored to true.
        vm.runtime.monitorBlocks.createBlock({
            id: 'sensing_timer',
            opcode: 'sensing_timer',
            inputs: {},
            fields: {},
            next: null,
            topLevel: true,
            parent: null,
            shadow: false,
            isMonitored: true,
            x: '0',
            y: '0'
        });

        vm.clear();
        vm.setCompatibilityMode(false);
        vm.setTurboMode(false);

        vm.loadProject(project).then(() => {
            t.equal(vm.runtime.threads.length, 0);

            vm.runtime._step();
            checkMonitorThreadPresent(t, vm.runtime.threads);
            t.assert(vm.runtime.threads[0].status === Thread.STATUS_RUNNING);
            const prevThread = vm.runtime.threads[0];

            // Check that both are added again when another step is taken
            vm.runtime._step();
            checkMonitorThreadPresent(t, vm.runtime.threads);
            t.equal(vm.runtime.threads[0], prevThread);
            t.end();
        });
    });
});
<|endoftext|>


<commit_before>describe('http reasons', function () {
    var http = require('http'),

        server,
        testrun;

    before(function (done) {
        var port,
            self = this;

        server = http.createServer();

        server.on('request', function (req, res) {
            res.end(res.writeHead(400, 'Some Custom Reason'));
        });

        server.on('listening', function () {
            port = server.address().port;
            self.run({
                collection: {
                    item: {
                        request: 'http://localhost:' + port + '/'
                    }
                }
            }, function (err, results) {
                testrun = results;
                done(err);
            });
        });

        server.listen(0, 'localhost');
    });

    it('must have started and completed the test run', function () {
        expect(testrun).be.ok();
        expect(testrun.done.calledOnce).be.ok();
        expect(testrun.start.calledOnce).be.ok();
    });

    it('must receive the correct reason phrase from the server', function () {
        var responseCode = testrun.request.getCall(0).args[5].responseCode;

        expect(responseCode).to.eql({
            code: 400,
            name: 'Some Custom Reason',
            detail: 'The request cannot be fulfilled due to bad syntax.',
            fromServer: true
        });
    });

    after(function () {
        server.close();
    });
});
<commit_msg>Breaking test change - test callback parameter now does not return legacy response.<commit_after>describe('http reasons', function () {
    var http = require('http'),

        server,
        testrun;

    before(function (done) {
        var port,
            self = this;

        server = http.createServer();

        server.on('request', function (req, res) {
            res.end(res.writeHead(400, 'Some Custom Reason'));
        });

        server.on('listening', function () {
            port = server.address().port;
            self.run({
                collection: {
                    item: {
                        request: 'http://localhost:' + port + '/'
                    }
                }
            }, function (err, results) {
                testrun = results;
                done(err);
            });
        });

        server.listen(0, 'localhost');
    });

    it('must have started and completed the test run', function () {
        expect(testrun).be.ok();
        expect(testrun.done.calledOnce).be.ok();
        expect(testrun.start.calledOnce).be.ok();
    });

    it('must receive the correct reason phrase from the server', function () {
        var response = testrun.request.getCall(0).args[2];

        expect(response.code).be(400);
        expect(response.status).be('Some Custom Reason');
        expect(response.details()).to.eql({
            code: 400,
            name: 'Some Custom Reason',
            detail: 'The request cannot be fulfilled due to bad syntax.'
        });
    });

    after(function () {
        server.close();
    });
});
<|endoftext|>


<commit_before>/*========================================================================

   This file is part of the GOsa project -  http://gosa-project.org

   Copyright:
      (C) 2010-2012 GONICUS GmbH, Germany, http://www.gonicus.de

   License:
      LGPL-2.1: http://www.gnu.org/licenses/lgpl-2.1.html

   See the LICENSE file in the project's top-level directory for details.

======================================================================== */

/* ************************************************************************

#asset(gosa/*)

************************************************************************ */

qx.Class.define("gosa.view.Tree",
{
  extend : qx.ui.tabview.Page,

  construct : function(parent)
  {
    // Call super class and configure ourselfs
    this.base(arguments, "", gosa.Config.getImagePath("apps/tree.png", 32));
    this.parent = parent;
    this.getChildControl("button").getChildControl("label").exclude();
    this.setLayout(new qx.ui.layout.Canvas());
    this.addListenerOnce("appear", this.load, this);
    this._rpc = gosa.io.Rpc.getInstance();

    gosa.io.Sse.getInstance().addListener("objectRemoved", this.__reloadTree, this);
    gosa.io.Sse.getInstance().addListener("objectCreated", this.__reloadTree, this);
    gosa.io.Sse.getInstance().addListener("objectModified", this.__reloadTree, this);
  },

  members : {

    parent : null,
    _deleteButton : null,
    _rpc : null,

    _createChildControlImpl : function(id, hash) {

      var control = null;

      switch(id) {

        case "tree":
          var root = new gosa.data.model.TreeResultItem(this.tr("Root"));
          root.setType("root");     // Required to show the icon
          root.load();  // Required to auto fetch children

          control = new qx.ui.tree.VirtualTree(root, "title", "children");
          control.setMinWidth(260);
          control.setSelectionMode("multi");
          this.__applyTreeDelegate(control);
          this.getChildControl("splitpane").add(control, 1);
          // Act on tree selection to automatically update the list
          control.getSelection().addListener("change", this.__refreshTable, this);
          break;

        case "splitpane":
          console.log("adding and creating splitpane");
          control = new qx.ui.splitpane.Pane("horizontal");
          this.add(control, {top: 0, bottom: 0, left:0, right: 0});
          break;

        // Create the action-bar for the list panel
        case "listcontainer":
          control = new qx.ui.container.Composite(new qx.ui.layout.VBox(5));
          var toolbar = new qx.ui.toolbar.ToolBar;
          var menuPart = new qx.ui.toolbar.Part;
          var menuPart2 = new qx.ui.toolbar.Part;
          var actionMenuButton = new qx.ui.toolbar.MenuButton("Action");
          var createMenuButton = new qx.ui.toolbar.MenuButton("Create");
          var filterMenuButton = new qx.ui.toolbar.MenuButton("Show");
          menuPart.add(actionMenuButton);
          menuPart.add(createMenuButton);
          menuPart.add(filterMenuButton);
          menuPart2.add(new qx.ui.form.TextField().set({placeholder: this.tr("Search ..")}).set({enabled: false}));
          toolbar.add(menuPart2);
          toolbar.add(menuPart);

          var actionMenu = new qx.ui.menu.Menu();
          actionMenuButton.setMenu(actionMenu);
          var deleteButton = this._deleteButton = new qx.ui.menu.Button(this.tr("Delete"));
          actionMenu.add(deleteButton);
          deleteButton.setEnabled(false);

          deleteButton.addListener("execute", this._onDeleteObject, this);

          var createMenu = this.getChildControl("createMenu");
          createMenuButton.setMenu(createMenu);

          toolbar.setEnabled(true);
          control.add(toolbar);
          this.getChildControl("splitpane").add(control, 2);
          break;

        case "createMenu":
          control = new qx.ui.menu.Menu();
          break;

        case "table":
          // Create the table
          var tableModel = this._tableModel = new qx.ui.table.model.Simple();
          tableModel.setColumns([ "-", this.tr("Name"), this.tr("Description"), this.tr("DN"), this.tr("Actions"), this.tr("UUID")]);
          var customModel = {
            tableColumnModel : function(obj){
              return new qx.ui.table.columnmodel.Resize(obj);
            }
          };
          var table = new qx.ui.table.Table(tableModel, customModel);
          this.getChildControl("listcontainer").add(table, {flex: 1});
          var that = this;
          table.addListener('dblclick', function(){
            table.getSelectionModel().iterateSelection(function(index) {
              that.parent.search.openObject(tableModel.getRowData(index)[3]);
            });
          }, this);

          table.getSelectionModel().addListener("changeSelection", function() {
            // TODO: check if the selected object is deletable, check ACL too?
            this._deleteButton.setEnabled(table.getSelectionModel().getSelectedCount() > 0);
          }, this);

          var ImageByType = qx.Class.define("ImageByType",{
            extend : qx.ui.table.cellrenderer.Image,
            members :      {
              _getImageInfos : function(cellInfo){
                var path = gosa.Config.spath + "/" + gosa.Config.getTheme() + "/resources/images/objects/16/" + cellInfo['value'].toLowerCase() + ".png";
                path = document.URL.replace(/\/[^\/]*[a-zA-Z]\/.*/, "") + path;
                cellInfo['value'] = path;
                return(this.base(arguments, cellInfo));
              }
            }
          });

          var Action = qx.Class.define("Action",{
            extend : qx.ui.table.cellrenderer.Boolean,
            members :      {
              _getImageInfos : function(cellInfo){
                cellInfo['value'] =  gosa.Config.spath + "/" + gosa.Config.getTheme() + "/resources/images/objects/16/" + cellInfo['value'].toLowerCase() + ".png";
                return(this.base(arguments, cellInfo));
              }
            }
          });

          table.getSelectionModel().setSelectionMode(qx.ui.table.selection.Model.SINGLE_SELECTION);
          var tcm = table.getTableColumnModel();
          var resizeBehavior = tcm.getBehavior();
          resizeBehavior.setWidth(0, 25);
          resizeBehavior.setWidth(1, "1*");
          resizeBehavior.setWidth(2, "1*");
          resizeBehavior.setWidth(3, "1*");
          tcm.setColumnVisible(3, false);
          tcm.setColumnVisible(5, false);
          tcm.setDataCellRenderer(0, new ImageByType());

          control = table;
          break;

      }

      return control || this.base(arguments, id, hash);
    },

    __applyTreeDelegate : function(tree) {
      // Special delegation handling
      var delegate = {

        // Bind properties from the item to the tree-widget and vice versa
        bindItem : function(controller, item, index){
          controller.bindDefaultProperties(item, index);
          controller.bindPropertyReverse("open", "open", null, item, index);
          controller.bindProperty("open", "open", null, item, index);
          controller.bindProperty("dn", "toolTipText", null, item, index);

          // Handle images
          controller.bindProperty("", "icon", {converter: function(item){
            if (!item.isLoading()){
              if(item.getType()){
                var path = gosa.Config.spath + "/" + gosa.Config.getTheme() + "/resources/images/objects/22/" + item.getType().toLowerCase() + ".png";
                path = document.URL.replace(/\/[^\/]*[a-zA-Z]\/.*/, "") + path;
                return path;
              }
              return(gosa.Config.getImagePath("actions/document-edit.png", 22));
            } else {
              return(gosa.Config.getImagePath("status/loading.gif", 22));
            }
          }}, item, index);
        }
      };
      tree.setDelegate(delegate);
    },

    load : function(){

      // Create the Tree
      var tree = this.getChildControl("tree");
      tree.addListener("updatedItems", this.__refreshTable, this);
      this.getChildControl("listcontainer");
      this.getChildControl("table");
      this.__updateCreateMenu();
      this.__refreshTable();
    },

    __updateCreateMenu : function() {
      // load object types
      this._rpc.cA(function(result, error){
        if(error){
          new gosa.ui.dialogs.Error(error.message).open();
        } else {
          result.sort();
          for (var index in result) {
            var name = result[index];
            var button = new qx.ui.menu.Button(name);
            button.setUserData("type", name);
            this.getChildControl("createMenu").add(button);
            button.addListener("execute", this._onCreateObject, this);
          }
        }
      }, this, "getAvailableObjectNames", true);
    },

    __refreshTable : function() {
      var sel = this.getChildControl("tree").getSelection();

      var done = [];
      var tableModel = this.getChildControl("table").getTableModel();
      tableModel.setData([]);
      var f = function(item){
        if(!qx.lang.Array.contains(done, item)){
          tableModel.addRows([item.getTableRow()]);
          done.push(item);
        }
      };

      var f2 = function(index){
        sel.getItem(index).load(function(){
          if(sel.getItem(index).getChildren()){
            sel.getItem(index).getChildren().forEach(f);
          }
          if(sel.getItem(index).getLeafs()){
            sel.getItem(index).getLeafs().forEach(f);
          }
        },this);
      };
      for(var i=0; i<sel.getLength(); i++){
        f2(i);
      }
    },

    __reloadTree : function() {
      var queue = this.getChildControl("tree").getSelection().length;
      this.getChildControl("tree").getSelection().forEach(function(sel) {
        sel.addListenerOnce("updatedItems", function() {
          queue--;
          if (queue === 0) {
            this.__refreshTable();
          }
        }, this);
        sel.reload();
      }, this);
    },

    _onCreateObject : function(ev) {
      var button = ev.getTarget();

      // get currently selected dn in tree
      var selection = this.getChildControl("tree").getSelection();
      var dns = new qx.data.Array();
      selection.forEach(function(sel) {
        if (!dns.contains(sel.getDn())) {
          dns.push(sel.getDn());
        }
      }, this);
      // TODO: how to handle multiple dns
      this.parent.search.openObject(dns.getItem(0), button.getUserData("type"));
    },

    _onDeleteObject : function() {
      // get currently selected dn in tree
      this.getChildControl("table").getSelectionModel().iterateSelection(function(index) {
        this.parent.search.removeObject(this.getChildControl("table").getTableModel().getRowData(index)[5]);
      }, this);
    }
  },

  destruct : function() {
    this._rpc = null;
    this._disposeObjects("_deleteButton");

    gosa.io.Sse.getInstance().removeListener("objectRemoved", this.__reloadTree, this);
    gosa.io.Sse.getInstance().removeListener("objectCreated", this.__reloadTree, this);
    gosa.io.Sse.getInstance().removeListener("objectModified", this.__reloadTree, this);
  }
});
<commit_msg>disable create-button when nothing is selected<commit_after>/*========================================================================

   This file is part of the GOsa project -  http://gosa-project.org

   Copyright:
      (C) 2010-2012 GONICUS GmbH, Germany, http://www.gonicus.de

   License:
      LGPL-2.1: http://www.gnu.org/licenses/lgpl-2.1.html

   See the LICENSE file in the project's top-level directory for details.

======================================================================== */

/* ************************************************************************

#asset(gosa/*)

************************************************************************ */

qx.Class.define("gosa.view.Tree",
{
  extend : qx.ui.tabview.Page,

  construct : function(parent)
  {
    // Call super class and configure ourselfs
    this.base(arguments, "", gosa.Config.getImagePath("apps/tree.png", 32));
    this.parent = parent;
    this.getChildControl("button").getChildControl("label").exclude();
    this.setLayout(new qx.ui.layout.Canvas());
    this.addListenerOnce("appear", this.load, this);
    this._rpc = gosa.io.Rpc.getInstance();

    gosa.io.Sse.getInstance().addListener("objectRemoved", this.__reloadTree, this);
    gosa.io.Sse.getInstance().addListener("objectCreated", this.__reloadTree, this);
    gosa.io.Sse.getInstance().addListener("objectModified", this.__reloadTree, this);
  },

  members : {

    parent : null,
    _deleteButton : null,
    _rpc : null,

    _createChildControlImpl : function(id, hash) {

      var control = null;

      switch(id) {

        case "tree":
          var root = new gosa.data.model.TreeResultItem(this.tr("Root"));
          root.setType("root");     // Required to show the icon
          root.load();  // Required to auto fetch children

          control = new qx.ui.tree.VirtualTree(root, "title", "children");
          control.setMinWidth(260);
          control.setSelectionMode("multi");
          this.__applyTreeDelegate(control);
          this.getChildControl("splitpane").add(control, 1);
          // Act on tree selection to automatically update the list
          control.getSelection().addListener("change", this.__refreshTable, this);
          break;

        case "splitpane":
          console.log("adding and creating splitpane");
          control = new qx.ui.splitpane.Pane("horizontal");
          this.add(control, {top: 0, bottom: 0, left:0, right: 0});
          break;

        // Create the action-bar for the list panel
        case "listcontainer":
          control = new qx.ui.container.Composite(new qx.ui.layout.VBox(5));
          control.add(this.getChildControl("toolbar"));
          this.getChildControl("splitpane").add(control, 2);
          break;

        case "toolbar":
          control = new qx.ui.toolbar.ToolBar;
          var menuPart = new qx.ui.toolbar.Part;
          var menuPart2 = new qx.ui.toolbar.Part;
          var actionMenuButton = new qx.ui.toolbar.MenuButton("Action");
          var createMenuButton = this._createMenuButton = new qx.ui.toolbar.MenuButton("Create");
          var filterMenuButton = new qx.ui.toolbar.MenuButton("Show");
          menuPart.add(actionMenuButton);
          menuPart.add(createMenuButton);
          menuPart.add(filterMenuButton);
          menuPart2.add(new qx.ui.form.TextField().set({placeholder: this.tr("Search ..")}).set({enabled: false}));
          control.add(menuPart2);
          control.add(menuPart);

          var actionMenu = new qx.ui.menu.Menu();
          actionMenuButton.setMenu(actionMenu);
          var deleteButton = this._deleteButton = new qx.ui.menu.Button(this.tr("Delete"));
          actionMenu.add(deleteButton);
          deleteButton.setEnabled(false);

          deleteButton.addListener("execute", this._onDeleteObject, this);

          var createMenu = this.getChildControl("createMenu");
          createMenuButton.setMenu(createMenu);
          break;

        case "createMenu":
          control = new qx.ui.menu.Menu();
          break;

        case "table":
          // Create the table
          var tableModel = this._tableModel = new qx.ui.table.model.Simple();
          tableModel.setColumns([ "-", this.tr("Name"), this.tr("Description"), this.tr("DN"), this.tr("Actions"), this.tr("UUID")]);
          var customModel = {
            tableColumnModel : function(obj){
              return new qx.ui.table.columnmodel.Resize(obj);
            }
          };
          var table = new qx.ui.table.Table(tableModel, customModel);
          this.getChildControl("listcontainer").add(table, {flex: 1});
          var that = this;
          table.addListener('dblclick', function(){
            table.getSelectionModel().iterateSelection(function(index) {
              that.parent.search.openObject(tableModel.getRowData(index)[3]);
            });
          }, this);

          table.getSelectionModel().addListener("changeSelection", function() {
            // TODO: check if the selected object is deletable, check ACL too?
            this._deleteButton.setEnabled(table.getSelectionModel().getSelectedCount() > 0);
          }, this);

          var ImageByType = qx.Class.define("ImageByType",{
            extend : qx.ui.table.cellrenderer.Image,
            members :      {
              _getImageInfos : function(cellInfo){
                var path = gosa.Config.spath + "/" + gosa.Config.getTheme() + "/resources/images/objects/16/" + cellInfo['value'].toLowerCase() + ".png";
                path = document.URL.replace(/\/[^\/]*[a-zA-Z]\/.*/, "") + path;
                cellInfo['value'] = path;
                return(this.base(arguments, cellInfo));
              }
            }
          });

          var Action = qx.Class.define("Action",{
            extend : qx.ui.table.cellrenderer.Boolean,
            members :      {
              _getImageInfos : function(cellInfo){
                cellInfo['value'] =  gosa.Config.spath + "/" + gosa.Config.getTheme() + "/resources/images/objects/16/" + cellInfo['value'].toLowerCase() + ".png";
                return(this.base(arguments, cellInfo));
              }
            }
          });

          table.getSelectionModel().setSelectionMode(qx.ui.table.selection.Model.SINGLE_SELECTION);
          var tcm = table.getTableColumnModel();
          var resizeBehavior = tcm.getBehavior();
          resizeBehavior.setWidth(0, 25);
          resizeBehavior.setWidth(1, "1*");
          resizeBehavior.setWidth(2, "1*");
          resizeBehavior.setWidth(3, "1*");
          tcm.setColumnVisible(3, false);
          tcm.setColumnVisible(5, false);
          tcm.setDataCellRenderer(0, new ImageByType());

          control = table;
          break;

      }

      return control || this.base(arguments, id, hash);
    },

    __applyTreeDelegate : function(tree) {
      // Special delegation handling
      var delegate = {

        // Bind properties from the item to the tree-widget and vice versa
        bindItem : function(controller, item, index){
          controller.bindDefaultProperties(item, index);
          controller.bindPropertyReverse("open", "open", null, item, index);
          controller.bindProperty("open", "open", null, item, index);
          controller.bindProperty("dn", "toolTipText", null, item, index);

          // Handle images
          controller.bindProperty("", "icon", {converter: function(item){
            if (!item.isLoading()){
              if(item.getType()){
                var path = gosa.Config.spath + "/" + gosa.Config.getTheme() + "/resources/images/objects/22/" + item.getType().toLowerCase() + ".png";
                path = document.URL.replace(/\/[^\/]*[a-zA-Z]\/.*/, "") + path;
                return path;
              }
              return(gosa.Config.getImagePath("actions/document-edit.png", 22));
            } else {
              return(gosa.Config.getImagePath("status/loading.gif", 22));
            }
          }}, item, index);
        }
      };
      tree.setDelegate(delegate);
    },

    load : function(){

      // Create the Tree
      var tree = this.getChildControl("tree");
      tree.addListener("updatedItems", this.__refreshTable, this);
      this.getChildControl("listcontainer");
      this.getChildControl("table");
      this.__updateCreateMenu();
      this.__refreshTable();
    },

    __updateCreateMenu : function() {
      // load object types
      this._rpc.cA(function(result, error){
        if(error){
          new gosa.ui.dialogs.Error(error.message).open();
        } else {
          result.sort();
          for (var index in result) {
            var name = result[index];
            var button = new qx.ui.menu.Button(name);
            button.setUserData("type", name);
            this.getChildControl("createMenu").add(button);
            button.addListener("execute", this._onCreateObject, this);
          }
        }
      }, this, "getAvailableObjectNames", true);
    },

    __refreshTable : function() {
      var sel = this.getChildControl("tree").getSelection();
      this._createMenuButton.setEnabled(sel.length > 0);

      var done = [];
      var tableModel = this.getChildControl("table").getTableModel();
      tableModel.setData([]);
      var f = function(item){
        if(!qx.lang.Array.contains(done, item)){
          tableModel.addRows([item.getTableRow()]);
          done.push(item);
        }
      };

      var f2 = function(index){
        sel.getItem(index).load(function(){
          if(sel.getItem(index).getChildren()){
            sel.getItem(index).getChildren().forEach(f);
          }
          if(sel.getItem(index).getLeafs()){
            sel.getItem(index).getLeafs().forEach(f);
          }
        },this);
      };
      for(var i=0; i<sel.getLength(); i++){
        f2(i);
      }
    },

    __reloadTree : function() {
      var queue = this.getChildControl("tree").getSelection().length;
      this.getChildControl("tree").getSelection().forEach(function(sel) {
        sel.addListenerOnce("updatedItems", function() {
          queue--;
          if (queue === 0) {
            this.__refreshTable();
          }
        }, this);
        sel.reload();
      }, this);
    },

    _onCreateObject : function(ev) {
      var button = ev.getTarget();

      // get currently selected dn in tree
      var selection = this.getChildControl("tree").getSelection();
      var dns = new qx.data.Array();
      selection.forEach(function(sel) {
        if (!dns.contains(sel.getDn())) {
          dns.push(sel.getDn());
        }
      }, this);
      // TODO: how to handle multiple dns
      this.parent.search.openObject(dns.getItem(0), button.getUserData("type"));
    },

    _onDeleteObject : function() {
      // get currently selected dn in tree
      this.getChildControl("table").getSelectionModel().iterateSelection(function(index) {
        this.parent.search.removeObject(this.getChildControl("table").getTableModel().getRowData(index)[5]);
      }, this);
    }
  },

  destruct : function() {
    this._rpc = null;
    this._disposeObjects("_deleteButton", "_createMenuButton");

    gosa.io.Sse.getInstance().removeListener("objectRemoved", this.__reloadTree, this);
    gosa.io.Sse.getInstance().removeListener("objectCreated", this.__reloadTree, this);
    gosa.io.Sse.getInstance().removeListener("objectModified", this.__reloadTree, this);
  }
});
<|endoftext|>