<commit_before>/*********************************************************************************
 * Messaging Stub Class
 * For websocket
 */
function MessagingStub_Miguel() {
	this.ownRtcIdentity;
	this.credentials;
	this.websocket;

    this.conversations=new Array();
}

/**
 * SendMessage
 * @param message... Message
 */
MessagingStub_Miguel.prototype.sendMessage = function (message) {
    console.log("C->S: ", message);
    var full_message = new Object();
    full_message.type = "message";
    full_message.body = message;

    // Multicast support for INVITE and UPDATE
    if ((message.type == MessageType.INVITATION || message.type == MessageType.UPDATE) && message.body.peers) {
        this.conversations.forEach(function (element, index, array) {
            if (element.contextId == message.contextId) array.splice(index, 1);
        });
        var conversation = new Object();
        conversation.contextId = message.contextId;
        conversation.peers = message.body.peers;
        this.conversations.push(conversation);
    }

    // Multicast support if to is empty
    if (!message.to) {
        var peers;
        var that=this;
        this.conversations.forEach(function (element, index, array) {
            if (element.contextId == message.contextId) peers = element.peers;
        });
        message.from = message.from.rtcIdentity;
        if(peers){
        	peers.forEach(function (element, index, array) {
            	full_message.to = element;
            	that.websocket.send(JSON.stringify(full_message));
        	});
        }

        return
    }

    // From and To Identities are changed into strings containing rtcIdentities
    // If To is an array, it sends it to the first position
    message.from = message.from.rtcIdentity;
    if (message.to instanceof Array) {
        message.to.every(function (element, index, array) {
            array[index] = element.rtcIdentity;
        });
        full_message.to = message.to[0];
    } else {
        message.to = new Array(message.to.rtcIdentity);
        full_message.to = message.to[0];
    }
    this.websocket.send(JSON.stringify(full_message));
};

/**
 * Connect
 */
MessagingStub_Miguel.prototype.connect = function(ownRtcIdentity, credentials, callbackFunction) {
	this.ownRtcIdentity = ownRtcIdentity;
	this.credentials = credentials;

	//DEFINE THE HOST ADDR
	var signaling_server = "192.168.8.4:1337";
	//signaling_server="172.16.62.66:1337";
	signaling_server = "150.140.184.247:1337";

	// If connect was already executed succesfully, it won't try to connect again, just execute the callback.
	if (this.websocket) {
		console.log("Websocket connection already opened, executing callback function: ");
		callbackFunction();
		return;
	}

	console.log('Opening channel: ws://' + signaling_server);
	this.websocket = new WebSocket('ws://' + signaling_server);

	var socket = this.websocket;
	this.websocket.onopen = function() {
		var message = new Object();
		message.type = "login";
		message.from = ownRtcIdentity;
		socket.send(JSON.stringify(message));
		console.log("Websocket connection opened and logging in as: " + ownRtcIdentity);
		callbackFunction();
	};

	this.websocket.onerror = function() {
		console.log("Websocket connection error");
	};
	this.websocket.onclose = function() {
		console.log("Websocket connection closed");
	};

	var that = this;
	// Maps the websocket listener to the MessagingStub listeners, and notifies filtering
	// by contextId
	this.websocket.onmessage = function(full_message) {
		// IF it doesnt have contextID, it is the application.
		var message = JSON.parse(full_message.data).body;

		Idp.getInstance().createIdentity(message.from, function(identity) {
			message.from = identity;

			// createIdentities can take array or single rtcIdentity and always returns an Array in the callback result
			Idp.getInstance().createIdentities(message.to, function(identityArr) {
				message.to = identityArr;

				that.baseStub.deliverMessage(message);
			});
		});
	};
}

/**
 * Disconnects from the server.
 */
MessagingStub_Miguel.prototype.disconnect = function() {
	this.websocket.close();
	this.websocket = null;
	console.log("Websocket connection disconnected");
};<commit_msg>fixed address of messaging server<commit_after>/*********************************************************************************
 * Messaging Stub Class
 * For websocket
 */
function MessagingStub_Miguel() {
	this.ownRtcIdentity;
	this.credentials;
	this.websocket;

    this.conversations=new Array();
}

/**
 * SendMessage
 * @param message... Message
 */
MessagingStub_Miguel.prototype.sendMessage = function (message) {
    console.log("C->S: ", message);
    var full_message = new Object();
    full_message.type = "message";
    full_message.body = message;

    // Multicast support for INVITE and UPDATE
    if ((message.type == MessageType.INVITATION || message.type == MessageType.UPDATE) && message.body.peers) {
        this.conversations.forEach(function (element, index, array) {
            if (element.contextId == message.contextId) array.splice(index, 1);
        });
        var conversation = new Object();
        conversation.contextId = message.contextId;
        conversation.peers = message.body.peers;
        this.conversations.push(conversation);
    }

    // Multicast support if to is empty
    if (!message.to) {
        var peers;
        var that=this;
        this.conversations.forEach(function (element, index, array) {
            if (element.contextId == message.contextId) peers = element.peers;
        });
        message.from = message.from.rtcIdentity;
        if(peers){
        	peers.forEach(function (element, index, array) {
            	full_message.to = element;
            	that.websocket.send(JSON.stringify(full_message));
        	});
        }

        return
    }

    // From and To Identities are changed into strings containing rtcIdentities
    // If To is an array, it sends it to the first position
    message.from = message.from.rtcIdentity;
    if (message.to instanceof Array) {
        message.to.every(function (element, index, array) {
            array[index] = element.rtcIdentity;
        });
        full_message.to = message.to[0];
    } else {
        message.to = new Array(message.to.rtcIdentity);
        full_message.to = message.to[0];
    }
    this.websocket.send(JSON.stringify(full_message));
};

/**
 * Connect
 */
MessagingStub_Miguel.prototype.connect = function(ownRtcIdentity, credentials, callbackFunction) {
	this.ownRtcIdentity = ownRtcIdentity;
	this.credentials = credentials;

	//DEFINE THE HOST ADDR
	var signaling_server = "192.168.7.216:1337";
	//signaling_server="172.16.62.66:1337";
	//signaling_server = "150.140.184.247:1337";

	// If connect was already executed succesfully, it won't try to connect again, just execute the callback.
	if (this.websocket) {
		console.log("Websocket connection already opened, executing callback function: ");
		callbackFunction();
		return;
	}

	console.log('Opening channel: ws://' + signaling_server);
	this.websocket = new WebSocket('ws://' + signaling_server);

	var socket = this.websocket;
	this.websocket.onopen = function() {
		var message = new Object();
		message.type = "login";
		message.from = ownRtcIdentity;
		socket.send(JSON.stringify(message));
		console.log("Websocket connection opened and logging in as: " + ownRtcIdentity);
		callbackFunction();
	};

	this.websocket.onerror = function() {
		console.log("Websocket connection error");
	};
	this.websocket.onclose = function() {
		console.log("Websocket connection closed");
	};

	var that = this;
	// Maps the websocket listener to the MessagingStub listeners, and notifies filtering
	// by contextId
	this.websocket.onmessage = function(full_message) {
		// IF it doesnt have contextID, it is the application.
		var message = JSON.parse(full_message.data).body;

		Idp.getInstance().createIdentity(message.from, function(identity) {
			message.from = identity;

			// createIdentities can take array or single rtcIdentity and always returns an Array in the callback result
			Idp.getInstance().createIdentities(message.to, function(identityArr) {
				message.to = identityArr;

				that.baseStub.deliverMessage(message);
			});
		});
	};
}

/**
 * Disconnects from the server.
 */
MessagingStub_Miguel.prototype.disconnect = function() {
	this.websocket.close();
	this.websocket = null;
	console.log("Websocket connection disconnected");
};<|endoftext|>


<commit_before>/**
 * Created by lundfall on 02/06/2017.
 */
import Bowser           from 'bowser';
import Surface          from 'famous/core/Surface.js';
import ElementOutput    from 'famous/core/ElementOutput.js';

export let invalidateLayoutForElement = (element) => {
    var disp = element.style.display;
    element.style.display = 'none';
    var trick = element.offsetHeight;
    element.style.display = disp;
};

let browser = Bowser;

/* Firefox has an issue with new elements not being painted  */
if (browser.gecko) {
    let oldAllocateFunction = Surface.prototype.allocate;
    Surface.prototype.allocate = function (allocator) {
        let result = oldAllocateFunction.call(this, allocator);
        //TOOO find out exact cause why this is necessary
        setTimeout(() => invalidateLayoutForElement(result), 200);

        return result;
    }

}
/* Safari has an issue with elements coming back from scale 0 (context.hide==true) not being painted */
if (browser.safari) {
    let oldCommitFunction = ElementOutput.prototype.commit;
    ElementOutput.prototype.commit = function (context) {
        oldCommitFunction.call(this, context);
        if(this._wasHidden && !context.hide){
            invalidateLayoutForElement(this._element);
        }
        this._wasHidden = context.hide;
    }

}
<commit_msg>Added trueSizeCheck to be constant true due to funny behaviour on iPhone, not getting the size correctly initially<commit_after>/**
 * Created by lundfall on 02/06/2017.
 */
import Bowser           from 'bowser';
import Surface          from 'famous/core/Surface.js';
import ElementOutput    from 'famous/core/ElementOutput.js';

export let invalidateLayoutForElement = (element) => {
    var disp = element.style.display;
    element.style.display = 'none';
    var trick = element.offsetHeight;
    element.style.display = disp;
};

let browser = Bowser;

/* Firefox has an issue with new elements not being painted  */
if (browser.gecko) {
    let oldAllocateFunction = Surface.prototype.allocate;
    Surface.prototype.allocate = function (allocator) {
        let result = oldAllocateFunction.call(this, allocator);
        //TOOO find out exact cause why this is necessary
        setTimeout(() => invalidateLayoutForElement(result), 200);

        return result;
    }

}
/* Safari has an issue with elements coming back from scale 0 (context.hide==true) not being painted */
if (browser.safari) {
    let oldCommitFunction = ElementOutput.prototype.commit;
    ElementOutput.prototype.commit = function (context) {
        oldCommitFunction.call(this, context);

        if(browser.ios){
            this._trueSizeCheck = true;
        }
        if(this._wasHidden && !context.hide){
            invalidateLayoutForElement(this._element);
        }
        this._wasHidden = context.hide;
    }

}
<|endoftext|>


<commit_before>// @flow

/*
Copyright 2016 Aviral Dasgupta
Copyright 2016 OpenMarket Ltd

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

import VectorBasePlatform, {updateCheckStatusEnum} from './VectorBasePlatform';
import dis from 'matrix-react-sdk/lib/dispatcher';
import { _t } from 'matrix-react-sdk/lib/languageHandler';
import Promise from 'bluebird';
import {remote, ipcRenderer} from 'electron';
import rageshake from '../rageshake';

remote.autoUpdater.on('update-downloaded', onUpdateDownloaded);

// try to flush the rageshake logs to indexeddb before quit.
ipcRenderer.on('before-quit', function () {
    console.log('riot-desktop closing');
    rageshake.flush();
});

function onUpdateDownloaded(ev: Event, releaseNotes: string, ver: string, date: Date, updateURL: string) {
    dis.dispatch({
        action: 'new_version',
        currentVersion: remote.app.getVersion(),
        newVersion: ver,
        releaseNotes: releaseNotes,
    });
}

function platformFriendlyName(): string {
    console.log(window.process);
    switch (window.process.platform) {
        case 'darwin':
            return 'macOS';
        case 'freebsd':
            return 'FreeBSD';
        case 'openbsd':
            return 'OpenBSD';
        case 'sunos':
            return 'SunOS';
        case 'win32':
            return 'Windows';
        default:
            // Sorry, Linux users: you get lumped into here,
            // but only because Linux's capitalisation is
            // normal. We do care about you.
            return window.process.platform[0].toUpperCase() + window.process.platform.slice(1);
    }
}

function _onAction(payload: Object) {
    // Whitelist payload actions, no point sending most across
    if (['call_state'].includes(payload.action)) {
        ipcRenderer.send('app_onAction', payload);
    }
}

function getUpdateCheckStatus(status) {
    if (status === true) {
        return { status: updateCheckStatusEnum.DOWNLOADING };
    } else if (status === false) {
        return { status: updateCheckStatusEnum.NOTAVAILABLE };
    } else {
        return {
            status: updateCheckStatusEnum.ERROR,
            detail: status,
        };
    }
}

export default class ElectronPlatform extends VectorBasePlatform {
    constructor() {
        super();
        dis.register(_onAction);
        this.updatable = Boolean(remote.autoUpdater.getFeedURL());

        /*
            IPC Call `check_updates` returns:
            true if there is an update available
            false if there is not
            or the error if one is encountered
         */
        ipcRenderer.on('check_updates', (event, status) => {
            if (!this.showUpdateCheck) return;
            dis.dispatch({
                action: 'check_updates',
                value: getUpdateCheckStatus(status),
            });
            this.showUpdateCheck = false;
        });

        this.startUpdateCheck = this.startUpdateCheck.bind(this);
        this.stopUpdateCheck = this.stopUpdateCheck.bind(this);
    }

    getHumanReadableName(): string {
        return 'Electron Platform'; // no translation required: only used for analytics
    }

    setNotificationCount(count: number) {
        if (this.notificationCount === count) return;
        super.setNotificationCount(count);

        ipcRenderer.send('setBadgeCount', count);
    }

    supportsNotifications(): boolean {
        return true;
    }

    maySendNotifications(): boolean {
        return true;
    }

    displayNotification(title: string, msg: string, avatarUrl: string, room: Object): Notification {
        // GNOME notification spec parses HTML tags for styling...
        // Electron Docs state all supported linux notification systems follow this markup spec
        // https://github.com/electron/electron/blob/master/docs/tutorial/desktop-environment-integration.md#linux
        // maybe we should pass basic styling (italics, bold, underline) through from MD
        // we only have to strip out < and > as the spec doesn't include anything about things like &
        // so we shouldn't assume that all implementations will treat those properly. Very basic tag parsing is done.
        if (window.process.platform === 'linux') {
            msg = msg.replace(/</g, '<').replace(/>/g, '>');
        }

        // Notifications in Electron use the HTML5 notification API
        const notification = new global.Notification(
            title,
            {
                body: msg,
                icon: avatarUrl,
                tag: 'vector',
                silent: true, // we play our own sounds
            },
        );

        notification.onclick = function() {
            dis.dispatch({
                action: 'view_room',
                room_id: room.roomId,
            });
            global.focus();
            const win = remote.getCurrentWindow();

            if (win.isMinimized()) win.restore();
            else if (!win.isVisible()) win.show();
            else win.focus();
        };

        return notification;
    }

    loudNotification(ev: Event, room: Object) {
        ipcRenderer.send('loudNotification');
    }

    clearNotification(notif: Notification) {
        notif.close();
    }

    getAppVersion(): Promise<string> {
        return Promise.resolve(remote.app.getVersion());
    }

    startUpdateCheck() {
        if (this.showUpdateCheck) return;
        super.startUpdateCheck();

        ipcRenderer.send('check_updates');
    }

    installUpdate() {
        // IPC to the main process to install the update, since quitAndInstall
        // doesn't fire the before-quit event so the main process needs to know
        // it should exit.
        ipcRenderer.send('install_update');
    }

    getDefaultDeviceDisplayName(): string {
        return _t('Riot Desktop on %(platformName)s', { platformName: platformFriendlyName() });
    }

    screenCaptureErrorString(): ?string {
        return null;
    }

    isElectron(): boolean { return true; }

    requestNotificationPermission(): Promise<string> {
        return Promise.resolve('granted');
    }

    reload() {
        remote.getCurrentWebContents().reload();
    }
}
<commit_msg>ElectronPlatform.js: Add Jitsi screensharing support<commit_after>// @flow

/*
Copyright 2016 Aviral Dasgupta
Copyright 2016 OpenMarket Ltd

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

import VectorBasePlatform, {updateCheckStatusEnum} from './VectorBasePlatform';
import dis from 'matrix-react-sdk/lib/dispatcher';
import { _t } from 'matrix-react-sdk/lib/languageHandler';
import Promise from 'bluebird';
import electron, {remote, ipcRenderer} from 'electron';
import rageshake from '../rageshake';

remote.autoUpdater.on('update-downloaded', onUpdateDownloaded);

// try to flush the rageshake logs to indexeddb before quit.
ipcRenderer.on('before-quit', function () {
    console.log('riot-desktop closing');
    rageshake.flush();
});

function onUpdateDownloaded(ev: Event, releaseNotes: string, ver: string, date: Date, updateURL: string) {
    dis.dispatch({
        action: 'new_version',
        currentVersion: remote.app.getVersion(),
        newVersion: ver,
        releaseNotes: releaseNotes,
    });
}

function platformFriendlyName(): string {
    console.log(window.process);
    switch (window.process.platform) {
        case 'darwin':
            return 'macOS';
        case 'freebsd':
            return 'FreeBSD';
        case 'openbsd':
            return 'OpenBSD';
        case 'sunos':
            return 'SunOS';
        case 'win32':
            return 'Windows';
        default:
            // Sorry, Linux users: you get lumped into here,
            // but only because Linux's capitalisation is
            // normal. We do care about you.
            return window.process.platform[0].toUpperCase() + window.process.platform.slice(1);
    }
}

function _onAction(payload: Object) {
    // Whitelist payload actions, no point sending most across
    if (['call_state'].includes(payload.action)) {
        ipcRenderer.send('app_onAction', payload);
    }
}

function getUpdateCheckStatus(status) {
    if (status === true) {
        return { status: updateCheckStatusEnum.DOWNLOADING };
    } else if (status === false) {
        return { status: updateCheckStatusEnum.NOTAVAILABLE };
    } else {
        return {
            status: updateCheckStatusEnum.ERROR,
            detail: status,
        };
    }
}

export default class ElectronPlatform extends VectorBasePlatform {
    constructor() {
        super();
        dis.register(_onAction);
        this.updatable = Boolean(remote.autoUpdater.getFeedURL());

        /*
            IPC Call `check_updates` returns:
            true if there is an update available
            false if there is not
            or the error if one is encountered
         */
        ipcRenderer.on('check_updates', (event, status) => {
            if (!this.showUpdateCheck) return;
            dis.dispatch({
                action: 'check_updates',
                value: getUpdateCheckStatus(status),
            });
            this.showUpdateCheck = false;
        });

        this.startUpdateCheck = this.startUpdateCheck.bind(this);
        this.stopUpdateCheck = this.stopUpdateCheck.bind(this);
    }

    getHumanReadableName(): string {
        return 'Electron Platform'; // no translation required: only used for analytics
    }

    setNotificationCount(count: number) {
        if (this.notificationCount === count) return;
        super.setNotificationCount(count);

        ipcRenderer.send('setBadgeCount', count);
    }

    supportsNotifications(): boolean {
        return true;
    }

    maySendNotifications(): boolean {
        return true;
    }

    displayNotification(title: string, msg: string, avatarUrl: string, room: Object): Notification {
        // GNOME notification spec parses HTML tags for styling...
        // Electron Docs state all supported linux notification systems follow this markup spec
        // https://github.com/electron/electron/blob/master/docs/tutorial/desktop-environment-integration.md#linux
        // maybe we should pass basic styling (italics, bold, underline) through from MD
        // we only have to strip out < and > as the spec doesn't include anything about things like &
        // so we shouldn't assume that all implementations will treat those properly. Very basic tag parsing is done.
        if (window.process.platform === 'linux') {
            msg = msg.replace(/</g, '<').replace(/>/g, '>');
        }

        // Notifications in Electron use the HTML5 notification API
        const notification = new global.Notification(
            title,
            {
                body: msg,
                icon: avatarUrl,
                tag: 'vector',
                silent: true, // we play our own sounds
            },
        );

        notification.onclick = function() {
            dis.dispatch({
                action: 'view_room',
                room_id: room.roomId,
            });
            global.focus();
            const win = remote.getCurrentWindow();

            if (win.isMinimized()) win.restore();
            else if (!win.isVisible()) win.show();
            else win.focus();
        };

        return notification;
    }

    loudNotification(ev: Event, room: Object) {
        ipcRenderer.send('loudNotification');
    }

    clearNotification(notif: Notification) {
        notif.close();
    }

    getAppVersion(): Promise<string> {
        return Promise.resolve(remote.app.getVersion());
    }

    startUpdateCheck() {
        if (this.showUpdateCheck) return;
        super.startUpdateCheck();

        ipcRenderer.send('check_updates');
    }

    installUpdate() {
        // IPC to the main process to install the update, since quitAndInstall
        // doesn't fire the before-quit event so the main process needs to know
        // it should exit.
        ipcRenderer.send('install_update');
    }

    getDefaultDeviceDisplayName(): string {
        return _t('Riot Desktop on %(platformName)s', { platformName: platformFriendlyName() });
    }

    screenCaptureErrorString(): ?string {
        return null;
    }

    isElectron(): boolean { return true; }

    requestNotificationPermission(): Promise<string> {
        return Promise.resolve('granted');
    }

    reload() {
        remote.getCurrentWebContents().reload();
    }

    /* BEGIN copied and slightly-modified code
     * setupScreenSharingForIframe function from:
     * https://github.com/jitsi/jitsi-meet-electron-utils
     * Copied directly here to avoid the need for a native electron module for
     * 'just a bit of JavaScript'
     * NOTE: Apache v2.0 licensed
     */
    setupScreenSharingForIframe(iframe: Object) {
        iframe.contentWindow.JitsiMeetElectron = {
            /**
             * Get sources available for screensharing. The callback is invoked
             * with an array of DesktopCapturerSources.
             *
             * @param {Function} callback - The success callback.
             * @param {Function} errorCallback - The callback for errors.
             * @param {Object} options - Configuration for getting sources.
             * @param {Array} options.types - Specify the desktop source types
             * to get, with valid sources being "window" and "screen".
             * @param {Object} options.thumbnailSize - Specify how big the
             * preview images for the sources should be. The valid keys are
             * height and width, e.g. { height: number, width: number}. By
             * default electron will return images with height and width of
             * 150px.
             */
            obtainDesktopStreams(callback, errorCallback, options = {}) {
                electron.desktopCapturer.getSources(options,
                    (error, sources) => {
                        if (error) {
                            errorCallback(error);
                            return;
                        }

                        callback(sources);
                    });
            },
        };
    }
    /* END of copied and slightly-modified code */
}
<|endoftext|>


<commit_before>// @flow

/*
Copyright 2016 Aviral Dasgupta
Copyright 2016 OpenMarket Ltd

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

import VectorBasePlatform from './VectorBasePlatform';
import dis from 'matrix-react-sdk/lib/dispatcher';
import q from 'q';

const electron = require('electron');
const remote = electron.remote;

electron.remote.autoUpdater.on('update-downloaded', onUpdateDownloaded);

function onUpdateDownloaded(ev, releaseNotes, ver, date, updateURL) {
    dis.dispatch({
        action: 'new_version',
        currentVersion: electron.remote.app.getVersion(),
        newVersion: ver,
        releaseNotes: releaseNotes,
    });
}

function platformFriendlyName() {
    console.log(window.process);
    switch (window.process.platform) {
        case 'darwin':
            return 'macOS';
        case 'freebsd':
            return 'FreeBSD';
        case 'openbsd':
            return 'OpenBSD';
        case 'sunos':
            return 'SunOS';
        case 'win32':
            return 'Windows';
        default:
            // Sorry, Linux users: you get lumped into here,
            // but only because Linux's capitalisation is
            // normal. We do care about you.
            return window.process.platform[0].toUpperCase() + window.process.platform.slice(1);
    }
}

export default class ElectronPlatform extends VectorBasePlatform {
    setNotificationCount(count: number) {
        if (this.notificationCount === count) return;
        super.setNotificationCount(count);
        // this sometimes throws because electron is made of fail:
        // https://github.com/electron/electron/issues/7351
        // For now, let's catch the error, but I suspect it may
        // continue to fail and we might just have to accept that
        // electron's remote RPC is a non-starter for now and use IPC
        try {
            remote.app.setBadgeCount(count);
        } catch (e) {
            console.error("Failed to set notification count", e);
        }
    }

    supportsNotifications() : boolean {
        return true;
    }

    maySendNotifications() : boolean {
        return true;
    }

    displayNotification(title: string, msg: string, avatarUrl: string, room: Object): Notification {

        // GNOME notification spec parses HTML tags for styling...
        // Electron Docs state all supported linux notification systems follow this markup spec
        // https://github.com/electron/electron/blob/master/docs/tutorial/desktop-environment-integration.md#linux
        // maybe we should pass basic styling (italics, bold, underline) through from MD
        // we only have to strip out < and > as the spec doesn't include anything about things like &
        // so we shouldn't assume that all implementations will treat those properly. Very basic tag parsing is done.
        if (window.process.platform === 'linux') {
            msg = msg.replace(/</g, "<").replace(/>/g, ">");
        }

        // Notifications in Electron use the HTML5 notification API
        const notification = new global.Notification(
            title,
            {
                body: msg,
                icon: avatarUrl,
                tag: "vector",
                silent: true, // we play our own sounds
            }
        );

        notification.onclick = function() {
            dis.dispatch({
                action: 'view_room',
                room_id: room.roomId
            });
            global.focus();
            const currentWin = electron.remote.getCurrentWindow();
            currentWin.show();
            currentWin.restore();
            currentWin.focus();
        };

        return notification;
    }

    clearNotification(notif: Notification) {
        notif.close();
    }

    getAppVersion() {
        return q(electron.remote.app.getVersion());
    }

    pollForUpdate() {
        // In electron we control the update process ourselves, since
        // it needs to run in the main process, so we just run the timer
        // loop in the main electron process instead.
    }

    installUpdate() {
        // IPC to the main process to install the update, since quitAndInstall
        // doesn't fire the before-quit event so the main process needs to know
        // it should exit.
        electron.ipcRenderer.send('install_update');
    }

    getDefaultDeviceDisplayName() {
        return "Riot Desktop on " + platformFriendlyName();
    }

    screenCaptureErrorString() {
        return null;
    }

    requestNotificationPermission() : Promise {
        return q('granted');
    }

    reload() {
        electron.remote.getCurrentWebContents().reload();
    }
}
<commit_msg>change show logic to same as that of the tray icon<commit_after>// @flow

/*
Copyright 2016 Aviral Dasgupta
Copyright 2016 OpenMarket Ltd

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

import VectorBasePlatform from './VectorBasePlatform';
import dis from 'matrix-react-sdk/lib/dispatcher';
import q from 'q';

const electron = require('electron');
const remote = electron.remote;

electron.remote.autoUpdater.on('update-downloaded', onUpdateDownloaded);

function onUpdateDownloaded(ev, releaseNotes, ver, date, updateURL) {
    dis.dispatch({
        action: 'new_version',
        currentVersion: electron.remote.app.getVersion(),
        newVersion: ver,
        releaseNotes: releaseNotes,
    });
}

function platformFriendlyName() {
    console.log(window.process);
    switch (window.process.platform) {
        case 'darwin':
            return 'macOS';
        case 'freebsd':
            return 'FreeBSD';
        case 'openbsd':
            return 'OpenBSD';
        case 'sunos':
            return 'SunOS';
        case 'win32':
            return 'Windows';
        default:
            // Sorry, Linux users: you get lumped into here,
            // but only because Linux's capitalisation is
            // normal. We do care about you.
            return window.process.platform[0].toUpperCase() + window.process.platform.slice(1);
    }
}

export default class ElectronPlatform extends VectorBasePlatform {
    setNotificationCount(count: number) {
        if (this.notificationCount === count) return;
        super.setNotificationCount(count);
        // this sometimes throws because electron is made of fail:
        // https://github.com/electron/electron/issues/7351
        // For now, let's catch the error, but I suspect it may
        // continue to fail and we might just have to accept that
        // electron's remote RPC is a non-starter for now and use IPC
        try {
            remote.app.setBadgeCount(count);
        } catch (e) {
            console.error("Failed to set notification count", e);
        }
    }

    supportsNotifications() : boolean {
        return true;
    }

    maySendNotifications() : boolean {
        return true;
    }

    displayNotification(title: string, msg: string, avatarUrl: string, room: Object): Notification {

        // GNOME notification spec parses HTML tags for styling...
        // Electron Docs state all supported linux notification systems follow this markup spec
        // https://github.com/electron/electron/blob/master/docs/tutorial/desktop-environment-integration.md#linux
        // maybe we should pass basic styling (italics, bold, underline) through from MD
        // we only have to strip out < and > as the spec doesn't include anything about things like &
        // so we shouldn't assume that all implementations will treat those properly. Very basic tag parsing is done.
        if (window.process.platform === 'linux') {
            msg = msg.replace(/</g, "<").replace(/>/g, ">");
        }

        // Notifications in Electron use the HTML5 notification API
        const notification = new global.Notification(
            title,
            {
                body: msg,
                icon: avatarUrl,
                tag: "vector",
                silent: true, // we play our own sounds
            }
        );

        notification.onclick = function() {
            dis.dispatch({
                action: 'view_room',
                room_id: room.roomId,
            });
            global.focus();
            const win = electron.remote.getCurrentWindow();

            if (win.isMinimized()) win.restore();
            else if (!win.isVisible()) win.show();
            else win.focus();
        };

        return notification;
    }

    clearNotification(notif: Notification) {
        notif.close();
    }

    getAppVersion() {
        return q(electron.remote.app.getVersion());
    }

    pollForUpdate() {
        // In electron we control the update process ourselves, since
        // it needs to run in the main process, so we just run the timer
        // loop in the main electron process instead.
    }

    installUpdate() {
        // IPC to the main process to install the update, since quitAndInstall
        // doesn't fire the before-quit event so the main process needs to know
        // it should exit.
        electron.ipcRenderer.send('install_update');
    }

    getDefaultDeviceDisplayName() {
        return "Riot Desktop on " + platformFriendlyName();
    }

    screenCaptureErrorString() {
        return null;
    }

    requestNotificationPermission() : Promise {
        return q('granted');
    }

    reload() {
        electron.remote.getCurrentWebContents().reload();
    }
}
<|endoftext|>


<commit_before>define (function() {
  function Progress(size, color, progress, target) {
    this.size = size
    this.color = color
    this.progress = progress
    this.target = target

    this.draw = function() {
      target.innerHTML = '<canvas id="progressCircle"></canvas>'
      var canvasCSS = `
        #progressCircle {
          position: absolute;
          transform: rotate(-90deg) rotateX(180deg);
          top: 0px;
          left: 0px;
        }
      `
      var styleSheet = window.document.styleSheets[0]
      styleSheet.insertRule(canvasCSS, styleSheet.cssRules.length)

      this.canvas = document.getElementById('progressCircle')
      this.canvas.width = this.size
      this.canvas.height = this.size
      this.ctx = this.canvas.getContext('2d')
      this.ctx.clearRect(0, 0, window.innerWidth, window.innerHeight)
      this.ctx.beginPath()
      this.ctx.arc(
        this.canvas.width / 2,
        this.canvas.height / 2,
        this.size / 4,
        0,
        Math.PI*2*this.progress,
        false
      )
      this.ctx.lineWidth = this.size / 2
      this.ctx.strokeStyle = this.color
      this.ctx.stroke()
    }

    this.update = function(progress) {
      this.ctx.clearRect(0, 0, window.innerWidth, window.innerHeight)
      this.ctx.beginPath()
      this.ctx.arc(
        this.canvas.width / 2,
        this.canvas.height / 2,
        this.size / 4,
        0,
        Math.PI*2*progress,
        false
      )
      this.ctx.lineWidth = this.size / 2
      this.ctx.strokeStyle = this.color
      this.ctx.stroke()
    }

    this.handleResize = function(size) {

    }
  }
  return Progress
})
<commit_msg>updated handleResize<commit_after>define (function() {
  function Progress(size, color, progress, target) {
    this.size = size
    this.color = color
    this.progress = progress
    this.target = target

    this.draw = function() {
      target.innerHTML = '<canvas id="progressCircle"></canvas>'
      var canvasCSS = `
        #progressCircle {
          position: absolute;
          transform: rotate(-90deg) rotateX(180deg);
          top: 0px;
          left: 0px;
        }
      `
      var styleSheet = window.document.styleSheets[0]
      styleSheet.insertRule(canvasCSS, styleSheet.cssRules.length)

      this.canvas = document.getElementById('progressCircle')
      this.canvas.width = this.size
      this.canvas.height = this.size
      this.ctx = this.canvas.getContext('2d')
      this.ctx.clearRect(0, 0, window.innerWidth, window.innerHeight)
      this.ctx.beginPath()
      this.ctx.arc(
        this.canvas.width / 2,
        this.canvas.height / 2,
        this.size / 4,
        0,
        Math.PI*2*this.progress,
        false
      )
      this.ctx.lineWidth = this.size / 2
      this.ctx.strokeStyle = this.color
      this.ctx.stroke()
    }

    this.update = function(progress) {
      this.ctx.clearRect(0, 0, window.innerWidth, window.innerHeight)
      this.ctx.beginPath()
      this.ctx.arc(
        this.canvas.width / 2,
        this.canvas.height / 2,
        this.size / 4,
        0,
        Math.PI*2*progress,
        false
      )
      this.ctx.lineWidth = this.size / 2
      this.ctx.strokeStyle = this.color
      this.ctx.stroke()
    }

    this.handleResize = function(size, progress) {
      this.canvas.width = size
      this.canvas.height = size
      this.update()
    }
  }
  return Progress
})
<|endoftext|>


<commit_before>import Ember from 'ember';
import Loader from './-loader';
import PaginatedLoaderState from './-paginated-loader-state';

const {
  A,
  RSVP: { resolve }
} = Ember;

export default class PaginatedLoaderInternal extends Loader {

  /*
    opts: {
      autoload: true,
      owner: [ 'id' ],
      query(owner, state) {
        let id = owner.get('id');
        id(!id) {
          return;
        }
        if(state) {
          let foo = state.foo;
          ..
        }
        return { ddoc, view, start_key, start_docid, end_key };
      },
      loaded(docs) {
        let isMore = true;
        let state = { foo };
        return { isMore, state };
      }
    }
  */
  constructor(store, parent, database, owner, opts) {
    super(store, parent, database, owner, opts);
    this._loadState = null;
  }

  get loadState() {
    return this._loadState;
  }

  _notifyLoadStateChange() {
    this.parent._loaderLoadStateDidChange(this);
  }

  _createLoaderState() {
    return new PaginatedLoaderState(this);
  }

  _createModel() {
    return this.store._createPaginatedLoader(this);
  }

  _createQuery() {
    let { owner, opts, _loadState } = this;
    return opts.query(owner, _loadState);
  }

  //

  _scheduleLoadMore() {
    console.log('_scheduleLoadMore');
  }

  //

  loadMore() {
    return this._withRejectNotLoadable(() => this._scheduleLoadMore().promise);
  }

}

/*

loadMore() {
  if(!this.state.isLoaded) {
    return this.load();
  }

  if(!this.state.isMore) {
    return resolve();
  }

  return this._scheduleLoadMore().promise;
}

_willLoad() {
  this._withState((state, changed) => state.onLoading(changed));
}

_invokeLoaded(array) {
  let docs = A(array.map(internal => internal.model(true)));
  let state = this._loadState || null;
  return this.opts.loaded(state, docs);
}

_didLoad(array) {
  let { state, isMore } = this._invokeLoaded(array);
  this._loadState = state || null;
  this._withState((state, changed) => state.onLoadedPaginated(isMore, changed));
  this._notifyLoadStateChange();
}

_loadDidFail(err) {
  this._withState((state, changed) => state.onError(err, changed));
}

_scheduleDocumentOperation(force) {
  let { database } = this;

  let query = this._query();

  if(force) {
    query.force = true;
  }

  const before = () => this._willLoad();
  const resolve = ({ result }) => this._didLoad(result);
  const reject = err => this._loadDidFail(err);

  return database._scheduleDocumentFindOperation(query, before, resolve, reject);
}

__scheduleLoad(more) {
  this._withState((state, changed) => state.onLoadScheduled(changed));
  let operation = this._createOperation({ more }, () => this._scheduleDocumentOperation(false));
  operation.invoke();
  return operation;
}

_scheduleLoad() {
  let operation = this._lastOperation();

  if(operation) {
    return operation;
  }

  return this.__scheduleLoad(false);
}

_scheduleForceReload() {
  this._loadState = null;
  this._withState((state, changed) => state.onReset(changed));
  this._notifyLoadStateChange();

  let operation = this._createOperation({ force: true }, () => this._scheduleDocumentOperation(true));
  operation.invoke();
  return operation;
}

_scheduleReload() {
  let operation = this._lastOperation();

  if(operation && (operation.opts.force || !this.state.isLoaded)) {
    return operation;
  }

  return this._scheduleForceReload();
}

_scheduleLoadMore() {
  let operation = this._lastOperation();

  if(operation && operation.opts.more) {
    return operation;
  }

  return this.__scheduleLoad(true);
}

_scheduleAutoload(except) {
  if(!this._needsAutoload()) {
    return;
  }
  this._withState((state, changed) => state.onLoadScheduled(changed), except);
  return this._scheduleLoad();
}

*/
<commit_msg>ordering<commit_after>import Ember from 'ember';
import Loader from './-loader';
import PaginatedLoaderState from './-paginated-loader-state';

const {
  A,
  RSVP: { resolve }
} = Ember;

export default class PaginatedLoaderInternal extends Loader {

  /*
    opts: {
      autoload: true,
      owner: [ 'id' ],
      query(owner, state) {
        let id = owner.get('id');
        id(!id) {
          return;
        }
        if(state) {
          let foo = state.foo;
          ..
        }
        return { ddoc, view, start_key, start_docid, end_key };
      },
      loaded(docs) {
        let isMore = true;
        let state = { foo };
        return { isMore, state };
      }
    }
  */
  constructor(store, parent, database, owner, opts) {
    super(store, parent, database, owner, opts);
    this._loadState = null;
  }

  get loadState() {
    return this._loadState;
  }

  _notifyLoadStateChange() {
    this.parent._loaderLoadStateDidChange(this);
  }

  _createLoaderState() {
    return new PaginatedLoaderState(this);
  }

  _createModel() {
    return this.store._createPaginatedLoader(this);
  }

  _createQuery() {
    let { owner, opts, _loadState } = this;
    return opts.query(owner, _loadState);
  }

  //

  loadMore() {
    return this._withRejectNotLoadable(() => this._scheduleLoadMore().promise);
  }

  //

  _scheduleLoadMore() {
    console.log('_scheduleLoadMore');
  }

}

/*

loadMore() {
  if(!this.state.isLoaded) {
    return this.load();
  }

  if(!this.state.isMore) {
    return resolve();
  }

  return this._scheduleLoadMore().promise;
}

_willLoad() {
  this._withState((state, changed) => state.onLoading(changed));
}

_invokeLoaded(array) {
  let docs = A(array.map(internal => internal.model(true)));
  let state = this._loadState || null;
  return this.opts.loaded(state, docs);
}

_didLoad(array) {
  let { state, isMore } = this._invokeLoaded(array);
  this._loadState = state || null;
  this._withState((state, changed) => state.onLoadedPaginated(isMore, changed));
  this._notifyLoadStateChange();
}

_loadDidFail(err) {
  this._withState((state, changed) => state.onError(err, changed));
}

_scheduleDocumentOperation(force) {
  let { database } = this;

  let query = this._query();

  if(force) {
    query.force = true;
  }

  const before = () => this._willLoad();
  const resolve = ({ result }) => this._didLoad(result);
  const reject = err => this._loadDidFail(err);

  return database._scheduleDocumentFindOperation(query, before, resolve, reject);
}

__scheduleLoad(more) {
  this._withState((state, changed) => state.onLoadScheduled(changed));
  let operation = this._createOperation({ more }, () => this._scheduleDocumentOperation(false));
  operation.invoke();
  return operation;
}

_scheduleLoad() {
  let operation = this._lastOperation();

  if(operation) {
    return operation;
  }

  return this.__scheduleLoad(false);
}

_scheduleForceReload() {
  this._loadState = null;
  this._withState((state, changed) => state.onReset(changed));
  this._notifyLoadStateChange();

  let operation = this._createOperation({ force: true }, () => this._scheduleDocumentOperation(true));
  operation.invoke();
  return operation;
}

_scheduleReload() {
  let operation = this._lastOperation();

  if(operation && (operation.opts.force || !this.state.isLoaded)) {
    return operation;
  }

  return this._scheduleForceReload();
}

_scheduleLoadMore() {
  let operation = this._lastOperation();

  if(operation && operation.opts.more) {
    return operation;
  }

  return this.__scheduleLoad(true);
}

_scheduleAutoload(except) {
  if(!this._needsAutoload()) {
    return;
  }
  this._withState((state, changed) => state.onLoadScheduled(changed), except);
  return this._scheduleLoad();
}

*/
<|endoftext|>


<commit_before>import Ember from 'ember';
import Loader from './-loader';
import PaginatedLoaderState from './-paginated-loader-state';

const {
  RSVP: { resolve }
} = Ember;

export default class PaginatedLoaderInternal extends Loader {

  /*
    opts: {
      autoload: true,
      owner: [ 'id' ],
      query(props) {
        return { id: props.id };
      }
    }
  */
  constructor(store, database, owner, opts) {
    super(store, database, owner, opts);
    this._loadState = null;
  }

  _createLoaderState() {
    return new PaginatedLoaderState();
  }

  _createModel() {
    return this.store._createPaginatedLoader(this);
  }

  //

  _willLoad() {
    this._withState((state, changed) => state.onLoading(changed));
  }

  _didLoad(array) {
    let { state, isMore } = this.opts.loaded(array.map(internal => internal.model(true)));
    this._loadState = state;
    this._withState((state, changed) => state.onLoadedPaginated(isMore, changed));
  }

  _loadDidFail(err) {
    this._withState((state, changed) => state.onError(err, changed));
  }

  _scheduleDocumentOperation(force) {
    let { database, owner, _loadState, opts } = this;

    let query = opts.query.call(owner, owner, _loadState);

    if(force) {
      query.force = true;
    }

    const before = () => this._willLoad();
    const resolve = ({ result }) => this._didLoad(result);
    const reject = err => this._loadDidFail(err);

    return database._scheduleDocumentFindOperation(query, before, resolve, reject);
  }

  // _scheduleLoad(force, reuse, except) {
  //   console.log(`_scheduleLoad force=${force}, reuse=${reuse}, except=${except}`);
  //   // TODO: force, reuse -- use type arg with 'load', 'reload', 'autoload'

  //   this._withState((state, changed) => state.onLoadScheduled(changed), except);

  //   let operation = this._createOperation(() => this._scheduleDocumentOperation(force));
  //   operation.invoke();
  //   return operation;
  // }

  __scheduleLoad(more) {
    this._withState((state, changed) => state.onLoadScheduled(changed));
    let operation = this._createOperation({ more }, () => this._scheduleDocumentOperation(false));
    operation.invoke();
    return operation;
  }

  _scheduleLoad() {
    let operation = this._lastOperation();

    if(operation) {
      return operation;
    }

    return this.__scheduleLoad(false);
  }

  _scheduleForceReload() {
    this._loadState = null;
    this._withState((state, changed) => state.onReset(changed));
    let operation = this._createOperation({ force: true }, () => this._scheduleDocumentOperation(true));
    operation.invoke();
    return operation;
  }

  _scheduleReload() {
    let operation = this._lastOperation();

    if(operation && (operation.opts.force || !this.state.isLoaded)) {
      return operation;
    }

    return this._scheduleForceReload();
  }

  _scheduleLoadMore() {
    let operation = this._lastOperation();

    if(operation && operation.opts.more) {
      return operation;
    }

    return this.__scheduleLoad(true);
  }

  _scheduleAutoload(except) {
    if(!this._needsAutoload()) {
      return;
    }
    this._withState((state, changed) => state.onLoadScheduled(changed), except);
    return this._scheduleLoad();
  }

  //

  loadMore() {
    if(!this.state.isLoaded) {
      return this.load();
    }

    if(!this.state.isMore) {
      return resolve();
    }

    return this._scheduleLoadMore().promise;
  }

}
<commit_msg>fix and cleanup<commit_after>import Ember from 'ember';
import Loader from './-loader';
import PaginatedLoaderState from './-paginated-loader-state';

const {
  A,
  RSVP: { resolve }
} = Ember;

export default class PaginatedLoaderInternal extends Loader {

  /*
    opts: {
      autoload: true,
      owner: [ 'id' ],
      query(props, state) {
        return { id: props.id };
      },
      loaded(docs) {
        let isMore = true;
        let state = { foo };
        return { isMore, state };
      }
    }
  */
  constructor(store, database, owner, opts) {
    super(store, database, owner, opts);
    this._loadState = null;
  }

  _createLoaderState() {
    return new PaginatedLoaderState();
  }

  _createModel() {
    return this.store._createPaginatedLoader(this);
  }

  //

  _willLoad() {
    this._withState((state, changed) => state.onLoading(changed));
  }

  _invokeLoaded(array) {
    let docs = A(array.map(internal => internal.model(true)));
    return this.opts.loaded(docs);
  }

  _didLoad(array) {
    let { state, isMore } = this._invokeLoaded(array);
    this._loadState = state;
    this._withState((state, changed) => state.onLoadedPaginated(isMore, changed));
  }

  _loadDidFail(err) {
    this._withState((state, changed) => state.onError(err, changed));
  }

  _scheduleDocumentOperation(force) {
    let { database, owner, _loadState, opts } = this;

    let query = opts.query.call(owner, owner, _loadState);

    if(force) {
      query.force = true;
    }

    const before = () => this._willLoad();
    const resolve = ({ result }) => this._didLoad(result);
    const reject = err => this._loadDidFail(err);

    return database._scheduleDocumentFindOperation(query, before, resolve, reject);
  }

  __scheduleLoad(more) {
    this._withState((state, changed) => state.onLoadScheduled(changed));
    let operation = this._createOperation({ more }, () => this._scheduleDocumentOperation(false));
    operation.invoke();
    return operation;
  }

  _scheduleLoad() {
    let operation = this._lastOperation();

    if(operation) {
      return operation;
    }

    return this.__scheduleLoad(false);
  }

  _scheduleForceReload() {
    this._loadState = null;
    this._withState((state, changed) => state.onReset(changed));
    let operation = this._createOperation({ force: true }, () => this._scheduleDocumentOperation(true));
    operation.invoke();
    return operation;
  }

  _scheduleReload() {
    let operation = this._lastOperation();

    if(operation && (operation.opts.force || !this.state.isLoaded)) {
      return operation;
    }

    return this._scheduleForceReload();
  }

  _scheduleLoadMore() {
    let operation = this._lastOperation();

    if(operation && operation.opts.more) {
      return operation;
    }

    return this.__scheduleLoad(true);
  }

  _scheduleAutoload(except) {
    if(!this._needsAutoload()) {
      return;
    }
    this._withState((state, changed) => state.onLoadScheduled(changed), except);
    return this._scheduleLoad();
  }

  //

  loadMore() {
    if(!this.state.isLoaded) {
      return this.load();
    }

    if(!this.state.isMore) {
      return resolve();
    }

    return this._scheduleLoadMore().promise;
  }

}
<|endoftext|>


<commit_before>/*---------------------------------------------------------
 * OpenERP diagram library
 *---------------------------------------------------------*/

openerp.web_diagram = function (instance) {
var QWeb = instance.web.qweb,
      _t = instance.web._t,
     _lt = instance.web._lt;
instance.web.views.add('diagram', 'instance.web.DiagramView');
instance.web.DiagramView = instance.web.View.extend({
    display_name: _lt('Diagram'),
    searchable: false,
    init: function(parent, dataset, view_id, options) {
        this._super(parent);
        this.set_default_options(options);
        this.view_manager = parent;
        this.dataset = dataset;
        this.model = this.dataset.model;
        this.view_id = view_id;
        this.domain = this.dataset._domain || [];
        this.context = {};
        this.ids = this.dataset.ids;
    },
    start: function() {
        return this.rpc("/web_diagram/diagram/load", {"model": this.model, "view_id": this.view_id}, this.on_loaded);
    },

    toTitleCase: function(str) {
        return str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
    },

    on_loaded: function(result) {

        var self = this;
        if(this.ids && this.ids.length) {
            this.id = this.ids[self.dataset.index || 0];
        }

        this.fields_view = result.fields_view,
        this.view_id = this.fields_view.view_id,
        this.fields = this.fields_view.fields,
        this.nodes = this.fields_view.arch.children[0],
        this.connectors = this.fields_view.arch.children[1],
        this.node = this.nodes.attrs.object,
        this.connector = this.connectors.attrs.object;
        this.labels = _.filter(this.fields_view.arch.children, function(label) {
            return label.tag == "label";
        });

        this.$el.html(QWeb.render("DiagramView", {'widget': this}));
        this.$el.addClass(this.fields_view.arch.attrs['class']);

        _.each(self.labels,function(label){
            html_label = '
' + label.attrs.string + "
";
            self.$el.find('.oe_diagram_header').append(html_label);
        })

        this.$el.find('div.oe_diagram_pager button[data-pager-action]').click(function() {
            var action = $(this).data('pager-action');
            self.execute_pager_action(action);
        });

        this.do_update_pager();

        // New Node,Edge
        this.$el.find('#new_node.oe_diagram_button_new').click(function(){self.add_node();});

        if(this.id) {
            self.get_diagram_info();
        }

    },

    get_diagram_info: function() {
        var self = this;
        var params = {
            'id': this.id,
            'model': this.model,
            'node': this.node,
            'connector': this.connector,
            'bgcolor': this.nodes.attrs.bgcolor,
            'shape': this.nodes.attrs.shape,
            'src_node': this.connectors.attrs.source,
            'des_node': this.connectors.attrs.destination,
            'label': this.connectors.attrs.label || false,
            'visible_nodes': [],
            'invisible_nodes': [],
            'node_fields': [],
            'connectors': [],
            'connectors_fields': []
        };

        _.each(this.nodes.children, function(child) {
            if(child.attrs.invisible == '1')
                params['invisible_nodes'].push(child.attrs.name);
            else {
                params['visible_nodes'].push(child.attrs.name);
                params['node_fields'].push(self.fields[child.attrs.name]['string']|| this.toTitleCase(child.attrs.name));
            }
        });

        _.each(this.connectors.children, function(conn) {
            params['connectors_fields'].push(self.fields[conn.attrs.name]['string']|| this.toTitleCase(conn.attrs.name));
            params['connectors'].push(conn.attrs.name);
        });

        this.rpc(
            '/web_diagram/diagram/get_diagram_info',params).then(function(result) {
                self.draw_diagram(result);
            }
        );
    },

    on_diagram_loaded: function(record) {
        var id_record = record['id'];
        if(id_record) {
            this.id = id_record;
            this.get_diagram_info();
            this.do_push_state({id:record.id});
        }
    },

    do_load_state: function(state, warm) {
        if (state && !this.dataset.get_id_index(state.id)) {
            this.dataset.ids.push(state.id);
        }
        this.dataset.select_id(state.id);
        if (warm) {
            this.do_show();
        }
     },

    // Set-up the drawing elements of the diagram
    draw_diagram: function(result) {
        var self = this;
        var res_nodes  = result['nodes'];
        var res_edges  = result['conn'];
        this.parent_field = result.parent_field;
        this.$el.find('h3.oe_diagram_title').text(result.name);

        var id_to_node = {};

        var style = {
            edge_color: "#A0A0A0",
            edge_label_color: "#555",
            edge_label_font_size: 10,
            edge_width: 2,
            edge_spacing: 100,
            edge_loop_radius: 100,

            node_label_color: "#333",
            node_label_font_size: 12,
            node_outline_color: "#333",
            node_outline_width: 1,
            node_selected_color: "#0097BE",
            node_selected_width: 2,
            node_size_x: 110,
            node_size_y: 80,
            connector_active_color: "#FFF",
            connector_radius: 4,

            close_button_radius: 8,
            close_button_color: "#333",
            close_button_x_color: "#FFF",

            gray: "#DCDCDC",
            white: "#FFF",

            viewport_margin: 50
        };

        // remove previous diagram
        var canvas = self.$el.find('div.oe_diagram_diagram')
                             .empty().get(0);

        var r  = new Raphael(canvas, '100%','100%');

        var graph  = new CuteGraph(r,style,canvas.parentNode);

        var confirm_dialog = $('#dialog').dialog({
            autoOpen: false,
            title: _t("Are you sure?") });

        _.each(res_nodes, function(node) {
            var n = new CuteNode(
                graph,
                node.x + 50,  //FIXME the +50 should be in the layout algorithm
                node.y + 50,
                CuteGraph.wordwrap(node.name, 14),
                node.shape === 'rectangle' ? 'rect' : 'circle',
                node.color === 'white' ? style.white : style.gray);

            n.id = node.id;
            id_to_node[node.id] = n;
        });

        _.each(res_edges, function(edge) {
            var e =  new CuteEdge(
                graph,
                CuteGraph.wordwrap(edge.signal, 32),
                id_to_node[edge.s_id],
                id_to_node[edge.d_id] || id_to_node[edge.s_id]  );  //WORKAROUND
            e.id = edge.id;
        });

        CuteNode.double_click_callback = function(cutenode){
            self.edit_node(cutenode.id);
        };
        var i = 0;
        CuteNode.destruction_callback = function(cutenode){
            if(!confirm(_t("Deleting this node cannot be undone.\nIt will also delete all connected transitions.\n\nAre you sure ?"))){
                return $.Deferred().reject().promise();
            }
            return new instance.web.DataSet(self,self.node).unlink([cutenode.id]);
        };
        CuteEdge.double_click_callback = function(cuteedge){
            self.edit_connector(cuteedge.id);
        };

        CuteEdge.creation_callback = function(node_start, node_end){
            return {label:_t("")};
        };
        CuteEdge.new_edge_callback = function(cuteedge){
            self.add_connector(cuteedge.get_start().id,
                               cuteedge.get_end().id,
                               cuteedge);
        };
        CuteEdge.destruction_callback = function(cuteedge){
            if(!confirm(_t("Deleting this transition cannot be undone.\n\nAre you sure ?"))){
                return $.Deferred().reject().promise();
            }
            return new instance.web.DataSet(self,self.connector).unlink([cuteedge.id]);
        };

    },

    // Creates a popup to edit the content of the node with id node_id
    edit_node: function(node_id){
        var self = this;
        var title = _t('Activity');
        var pop = new instance.web.form.FormOpenPopup(self);

        pop.show_element(
                self.node,
                node_id,
                self.context || self.dataset.context,
                {
                    title: _t("Open: ") + title
                }
            );
        pop.on('on_write_complete', self, function() {
            self.dataset.read_index(_.keys(self.fields_view.fields)).pipe(self.on_diagram_loaded);
            });

        var form_fields = [self.parent_field];
        var form_controller = pop.view_form;

       form_controller.on("load_record", self, function(){
            _.each(form_fields, function(fld) {
                if (!(fld in form_controller.fields)) { return; }
                var field = form_controller.fields[fld];
                field.$input.prop('disabled', true);
                field.$drop_down.unbind();
            });
         });

    },

    // Creates a popup to add a node to the diagram
    add_node: function(){
        var self = this;
        var title = _t('Activity');
        var pop = new instance.web.form.SelectCreatePopup(self);
        pop.select_element(
            self.node,
            {
                title: _t("Create:") + title,
                initial_view: 'form',
                disable_multiple_selection: true
            },
            self.dataset.domain,
            self.context || self.dataset.context
        );
        pop.on("elements_selected", self, function(element_ids) {
            self.dataset.read_index(_.keys(self.fields_view.fields)).pipe(self.on_diagram_loaded);
        });

        var form_controller = pop.view_form;
        var form_fields = [this.parent_field];

        form_controller.on("load_record", self, function(){
            _.each(form_fields, function(fld) {
                if (!(fld in form_controller.fields)) { return; }
                var field = form_controller.fields[fld];
                field.set_value(self.id);
                field.dirty = true;
            });
        });
    },

    // Creates a popup to edit the connector of id connector_id
    edit_connector: function(connector_id){
        var self = this;
        var title = _t('Transition');
        var pop = new instance.web.form.FormOpenPopup(self);
        pop.show_element(
            self.connector,
            parseInt(connector_id,10),      //FIXME Isn't connector_id supposed to be an int ?
            self.context || self.dataset.context,
            {
                title: _t("Open: ") + title
            }
        );
        pop.on('on_write_complete', self, function() {
            self.dataset.read_index(_.keys(self.fields_view.fields)).pipe(self.on_diagram_loaded);
        });
    },

    // Creates a popup to add a connector from node_source_id to node_dest_id.
    // dummy_cuteedge if not null, will be removed form the graph after the popup is closed.
    add_connector: function(node_source_id, node_dest_id, dummy_cuteedge){
        var self = this;
        var title = _t('Transition');
        var pop = new instance.web.form.SelectCreatePopup(self);

        pop.select_element(
            self.connector,
            {
                title: _t("Create:") + title,
                initial_view: 'form',
                disable_multiple_selection: true
            },
            this.dataset.domain,
            this.context || this.dataset.context
        );
        pop.on("elements_selected", self, function(element_ids) {
            self.dataset.read_index(_.keys(self.fields_view.fields)).pipe(self.on_diagram_loaded);
        });
        // We want to destroy the dummy edge after a creation cancel. This destroys it even if we save the changes.
        // This is not a problem since the diagram is completely redrawn on saved changes.
        pop.$el.bind("dialogbeforeclose",function(){
            if(dummy_cuteedge){
                dummy_cuteedge.remove();
            }
        });

        var form_controller = pop.view_form;

       form_controller.on("load_record", self, function(){
            form_controller.fields[self.connectors.attrs.source].set_value(node_source_id);
            form_controller.fields[self.connectors.attrs.source].dirty = true;
            form_controller.fields[self.connectors.attrs.destination].set_value(node_dest_id);
            form_controller.fields[self.connectors.attrs.destination].dirty = true;
       });
    },

    execute_pager_action: function(action) {
        switch (action) {
            case 'first':
                this.dataset.index = 0;
                break;
            case 'previous':
                this.dataset.previous();
                break;
            case 'next':
                this.dataset.next();
                break;
            case 'last':
                this.dataset.index = this.dataset.ids.length - 1;
                break;
        }
        var loaded = this.dataset.read_index(_.keys(this.fields_view.fields))
                .pipe(this.on_diagram_loaded);
        this.do_update_pager();
        return loaded;
    },

    do_update_pager: function(hide_index) {
        var $pager = this.$el.find('div.oe_diagram_pager');
        var index = hide_index ? '-' : this.dataset.index + 1;
        if(!this.dataset.count) {
            this.dataset.count = this.dataset.ids.length;
        }
        $pager.find('span.oe_pager_index').html(index);
        $pager.find('span.oe_pager_count').html(this.dataset.count);
    },

    do_show: function() {
        this.do_push_state({});
        return $.when(this._super(), this.execute_pager_action('reload'));
    }
});
};

// vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax:
<commit_msg>[IMP] Improved state in diagram<commit_after>/*---------------------------------------------------------
 * OpenERP diagram library
 *---------------------------------------------------------*/

openerp.web_diagram = function (instance) {
var QWeb = instance.web.qweb,
      _t = instance.web._t,
     _lt = instance.web._lt;
instance.web.views.add('diagram', 'instance.web.DiagramView');
instance.web.DiagramView = instance.web.View.extend({
    display_name: _lt('Diagram'),
    searchable: false,
    init: function(parent, dataset, view_id, options) {
        this._super(parent);
        this.set_default_options(options);
        this.view_manager = parent;
        this.dataset = dataset;
        this.model = this.dataset.model;
        this.view_id = view_id;
        this.domain = this.dataset._domain || [];
        this.context = {};
        this.ids = this.dataset.ids;
    },
    start: function() {
        return this.rpc("/web_diagram/diagram/load", {"model": this.model, "view_id": this.view_id}, this.on_loaded);
    },

    toTitleCase: function(str) {
        return str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
    },

    on_loaded: function(result) {

        var self = this;
        if(this.ids && this.ids.length) {
            this.id = this.ids[self.dataset.index || 0];
        }

        this.fields_view = result.fields_view,
        this.view_id = this.fields_view.view_id,
        this.fields = this.fields_view.fields,
        this.nodes = this.fields_view.arch.children[0],
        this.connectors = this.fields_view.arch.children[1],
        this.node = this.nodes.attrs.object,
        this.connector = this.connectors.attrs.object;
        this.labels = _.filter(this.fields_view.arch.children, function(label) {
            return label.tag == "label";
        });

        this.$el.html(QWeb.render("DiagramView", {'widget': this}));
        this.$el.addClass(this.fields_view.arch.attrs['class']);

        _.each(self.labels,function(label){
            html_label = '
' + label.attrs.string + "
";
            self.$el.find('.oe_diagram_header').append(html_label);
        })

        this.$el.find('div.oe_diagram_pager button[data-pager-action]').click(function() {
            var action = $(this).data('pager-action');
            self.execute_pager_action(action);
        });

        this.do_update_pager();

        // New Node,Edge
        this.$el.find('#new_node.oe_diagram_button_new').click(function(){self.add_node();});

        if(this.id) {
            self.get_diagram_info();
        }

    },

    get_diagram_info: function() {
        var self = this;
        var params = {
            'id': this.id,
            'model': this.model,
            'node': this.node,
            'connector': this.connector,
            'bgcolor': this.nodes.attrs.bgcolor,
            'shape': this.nodes.attrs.shape,
            'src_node': this.connectors.attrs.source,
            'des_node': this.connectors.attrs.destination,
            'label': this.connectors.attrs.label || false,
            'visible_nodes': [],
            'invisible_nodes': [],
            'node_fields': [],
            'connectors': [],
            'connectors_fields': []
        };

        _.each(this.nodes.children, function(child) {
            if(child.attrs.invisible == '1')
                params['invisible_nodes'].push(child.attrs.name);
            else {
                params['visible_nodes'].push(child.attrs.name);
                params['node_fields'].push(self.fields[child.attrs.name]['string']|| this.toTitleCase(child.attrs.name));
            }
        });

        _.each(this.connectors.children, function(conn) {
            params['connectors_fields'].push(self.fields[conn.attrs.name]['string']|| this.toTitleCase(conn.attrs.name));
            params['connectors'].push(conn.attrs.name);
        });

        this.rpc(
            '/web_diagram/diagram/get_diagram_info',params).then(function(result) {
                self.draw_diagram(result);
            }
        );
    },

    on_diagram_loaded: function(record) {
        var id_record = record['id'];
        if (id_record) {
            this.id = id_record;
            this.get_diagram_info();
            this.do_push_state({id: id_record});
        } else {
            this.do_push_state({});
        }
    },

    do_load_state: function(state, warm) {
        if (state && state.id) {
            if (!this.dataset.get_id_index(state.id)) {
                this.dataset.ids.push(state.id);
            }
            this.dataset.select_id(state.id);
            if (warm) {
                this.do_show();
            }
        }
     },

    // Set-up the drawing elements of the diagram
    draw_diagram: function(result) {
        var self = this;
        var res_nodes  = result['nodes'];
        var res_edges  = result['conn'];
        this.parent_field = result.parent_field;
        this.$el.find('h3.oe_diagram_title').text(result.name);

        var id_to_node = {};

        var style = {
            edge_color: "#A0A0A0",
            edge_label_color: "#555",
            edge_label_font_size: 10,
            edge_width: 2,
            edge_spacing: 100,
            edge_loop_radius: 100,

            node_label_color: "#333",
            node_label_font_size: 12,
            node_outline_color: "#333",
            node_outline_width: 1,
            node_selected_color: "#0097BE",
            node_selected_width: 2,
            node_size_x: 110,
            node_size_y: 80,
            connector_active_color: "#FFF",
            connector_radius: 4,

            close_button_radius: 8,
            close_button_color: "#333",
            close_button_x_color: "#FFF",

            gray: "#DCDCDC",
            white: "#FFF",

            viewport_margin: 50
        };

        // remove previous diagram
        var canvas = self.$el.find('div.oe_diagram_diagram')
                             .empty().get(0);

        var r  = new Raphael(canvas, '100%','100%');

        var graph  = new CuteGraph(r,style,canvas.parentNode);

        var confirm_dialog = $('#dialog').dialog({
            autoOpen: false,
            title: _t("Are you sure?") });

        _.each(res_nodes, function(node) {
            var n = new CuteNode(
                graph,
                node.x + 50,  //FIXME the +50 should be in the layout algorithm
                node.y + 50,
                CuteGraph.wordwrap(node.name, 14),
                node.shape === 'rectangle' ? 'rect' : 'circle',
                node.color === 'white' ? style.white : style.gray);

            n.id = node.id;
            id_to_node[node.id] = n;
        });

        _.each(res_edges, function(edge) {
            var e =  new CuteEdge(
                graph,
                CuteGraph.wordwrap(edge.signal, 32),
                id_to_node[edge.s_id],
                id_to_node[edge.d_id] || id_to_node[edge.s_id]  );  //WORKAROUND
            e.id = edge.id;
        });

        CuteNode.double_click_callback = function(cutenode){
            self.edit_node(cutenode.id);
        };
        var i = 0;
        CuteNode.destruction_callback = function(cutenode){
            if(!confirm(_t("Deleting this node cannot be undone.\nIt will also delete all connected transitions.\n\nAre you sure ?"))){
                return $.Deferred().reject().promise();
            }
            return new instance.web.DataSet(self,self.node).unlink([cutenode.id]);
        };
        CuteEdge.double_click_callback = function(cuteedge){
            self.edit_connector(cuteedge.id);
        };

        CuteEdge.creation_callback = function(node_start, node_end){
            return {label:_t("")};
        };
        CuteEdge.new_edge_callback = function(cuteedge){
            self.add_connector(cuteedge.get_start().id,
                               cuteedge.get_end().id,
                               cuteedge);
        };
        CuteEdge.destruction_callback = function(cuteedge){
            if(!confirm(_t("Deleting this transition cannot be undone.\n\nAre you sure ?"))){
                return $.Deferred().reject().promise();
            }
            return new instance.web.DataSet(self,self.connector).unlink([cuteedge.id]);
        };

    },

    // Creates a popup to edit the content of the node with id node_id
    edit_node: function(node_id){
        var self = this;
        var title = _t('Activity');
        var pop = new instance.web.form.FormOpenPopup(self);

        pop.show_element(
                self.node,
                node_id,
                self.context || self.dataset.context,
                {
                    title: _t("Open: ") + title
                }
            );
        pop.on('on_write_complete', self, function() {
            self.dataset.read_index(_.keys(self.fields_view.fields)).pipe(self.on_diagram_loaded);
            });

        var form_fields = [self.parent_field];
        var form_controller = pop.view_form;

       form_controller.on("load_record", self, function(){
            _.each(form_fields, function(fld) {
                if (!(fld in form_controller.fields)) { return; }
                var field = form_controller.fields[fld];
                field.$input.prop('disabled', true);
                field.$drop_down.unbind();
            });
         });

    },

    // Creates a popup to add a node to the diagram
    add_node: function(){
        var self = this;
        var title = _t('Activity');
        var pop = new instance.web.form.SelectCreatePopup(self);
        pop.select_element(
            self.node,
            {
                title: _t("Create:") + title,
                initial_view: 'form',
                disable_multiple_selection: true
            },
            self.dataset.domain,
            self.context || self.dataset.context
        );
        pop.on("elements_selected", self, function(element_ids) {
            self.dataset.read_index(_.keys(self.fields_view.fields)).pipe(self.on_diagram_loaded);
        });

        var form_controller = pop.view_form;
        var form_fields = [this.parent_field];

        form_controller.on("load_record", self, function(){
            _.each(form_fields, function(fld) {
                if (!(fld in form_controller.fields)) { return; }
                var field = form_controller.fields[fld];
                field.set_value(self.id);
                field.dirty = true;
            });
        });
    },

    // Creates a popup to edit the connector of id connector_id
    edit_connector: function(connector_id){
        var self = this;
        var title = _t('Transition');
        var pop = new instance.web.form.FormOpenPopup(self);
        pop.show_element(
            self.connector,
            parseInt(connector_id,10),      //FIXME Isn't connector_id supposed to be an int ?
            self.context || self.dataset.context,
            {
                title: _t("Open: ") + title
            }
        );
        pop.on('on_write_complete', self, function() {
            self.dataset.read_index(_.keys(self.fields_view.fields)).pipe(self.on_diagram_loaded);
        });
    },

    // Creates a popup to add a connector from node_source_id to node_dest_id.
    // dummy_cuteedge if not null, will be removed form the graph after the popup is closed.
    add_connector: function(node_source_id, node_dest_id, dummy_cuteedge){
        var self = this;
        var title = _t('Transition');
        var pop = new instance.web.form.SelectCreatePopup(self);

        pop.select_element(
            self.connector,
            {
                title: _t("Create:") + title,
                initial_view: 'form',
                disable_multiple_selection: true
            },
            this.dataset.domain,
            this.context || this.dataset.context
        );
        pop.on("elements_selected", self, function(element_ids) {
            self.dataset.read_index(_.keys(self.fields_view.fields)).pipe(self.on_diagram_loaded);
        });
        // We want to destroy the dummy edge after a creation cancel. This destroys it even if we save the changes.
        // This is not a problem since the diagram is completely redrawn on saved changes.
        pop.$el.bind("dialogbeforeclose",function(){
            if(dummy_cuteedge){
                dummy_cuteedge.remove();
            }
        });

        var form_controller = pop.view_form;

       form_controller.on("load_record", self, function(){
            form_controller.fields[self.connectors.attrs.source].set_value(node_source_id);
            form_controller.fields[self.connectors.attrs.source].dirty = true;
            form_controller.fields[self.connectors.attrs.destination].set_value(node_dest_id);
            form_controller.fields[self.connectors.attrs.destination].dirty = true;
       });
    },

    execute_pager_action: function(action) {
        switch (action) {
            case 'first':
                this.dataset.index = 0;
                break;
            case 'previous':
                this.dataset.previous();
                break;
            case 'next':
                this.dataset.next();
                break;
            case 'last':
                this.dataset.index = this.dataset.ids.length - 1;
                break;
        }
        var loaded = this.dataset.read_index(_.keys(this.fields_view.fields))
                .pipe(this.on_diagram_loaded);
        this.do_update_pager();
        return loaded;
    },

    do_update_pager: function(hide_index) {
        var $pager = this.$el.find('div.oe_diagram_pager');
        var index = hide_index ? '-' : this.dataset.index + 1;
        if(!this.dataset.count) {
            this.dataset.count = this.dataset.ids.length;
        }
        $pager.find('span.oe_pager_index').html(index);
        $pager.find('span.oe_pager_count').html(this.dataset.count);
    },

    do_show: function() {
        this.do_push_state({});
        return $.when(this._super(), this.execute_pager_action('reload'));
    }
});
};

// vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax:
<|endoftext|>


<commit_before>(function() {
    var Agora = this.Agora,
        app = this.app;

    /*
     * Agora calendar widget scope
    */

    (function() {
        var ElectionModel = Backbone.Model.extend({});
        var ElectionsCollection = Backbone.Collection.extend({
            model: ElectionModel
        });

        Agora.CalendarWidgetView = Backbone.View.extend({
            el: "#agora-calendar",

            events: {
                "keyup .election-search-query": "onSearchChange"
            },

            initialize: function() {
                _.bindAll(this);
                this.template = _.template($("#template-election").html());
                this.collection = new ElectionsCollection();
                this.collection.on('reset', this.resetCollection);

                var ajax = new Ajax();
                ajax.on('success', this.initializeSuccess);
                ajax.get(this.$el.data('url'));

                // Debouncing
                this.onSearchChange = _.debounce(this.onSearchChange, 400);
            },

            initializeSuccess: function(xhr) {
                if (xhr.status === 200) {
                    var data = JSON.parse(xhr.responseText);
                    this.collection.reset(data.objects);
                }
            },

            onSearchChange: function(event) {
                var target = $(event.currentTarget);
                var data = {"q": target.val()};

                var ajax = new Ajax();
                ajax.on('success', this.initializeSuccess);
                ajax.get(this.$el.data('url'), data);
                console.log("onSearchChange: " + target.val());
            },

            resetCollection: function(collection) {
                this.$(".list-container").empty();

                var data = collection.groupBy(function(item) {
                    var date = item.get('voting_extended_until_date');
                    if (date) {
                        return date.split("T")[0];
                    } else {
                        return null;
                    }
                });

                _.each(_.pairs(data), function(item) {
                    var key = item[0],
                        val = item[1];

                    var date = moment(key);
                    var dom = this.template({"datetime":date.format("LL"), "items": val});

                    this.$(".list-container").append(dom);
                }, this);
            }
        });
    }).call(this);

    /*
     * Generic view for all infinite scroll lists.
     * DEPRECATED
    */
    Agora.InfiniteScrollListView = Backbone.View.extend({
        el: "#activity-list",

        events: {
            "click a.endless_more": "onMoreClicked"
        },

        initialize: function() {
            _.bindAll(this);
            $(window).scroll(this.infiniteScroll);
        },

        infiniteScroll: function() {
            var doc = $(document), win = $(window);
            var margin = this.$el.data('endless-smargin') || 1;

            if ((doc.height() - win.height() - win.scrollTop()) <= margin) {
                this.$("a.endless_more").click();
            }
        },

        onMoreClicked: function(event) {
            console.log("onMoreClicked");
            event.preventDefault();

            var target = $(event.currentTarget).hide();
            target.closest('.endless_container').find('.endless_loading').show();

            var data = "querystring_key=" + target.attr('rel').split(' ')[0];
            var ajax = new Ajax();

            ajax.on("success", this.loadMoreSuccess);

            ajax.setContext({target:target});
            ajax.get(target.attr('href'), data);
        },

        loadMoreSuccess: function(xhr, message, ctx) {
            var data = xhr.responseText;
            ctx.target.closest('.endless_container').before(data);
            ctx.target.closest('.endless_container').remove();
        }
    });

    /*
     * Generic view for all search pages.
    */

    (function() {
        var ItemModel = Backbone.Model.extend({});

        var ItemCollection = Backbone.Collection.extend({
            model: ItemModel
        });

        Agora.GenericListView = Backbone.View.extend({
            el: "#activity-list",

            events: {
                "click a.endless_more": "onMoreClicked"
            },

            setup: function() {
                this.url = this.$el.data('url');
                this.method = this.$el.data('method') || 'get';
            },

            setupTemplates: function() {
                if (this.templateEl !== undefined) {
                    this.template = _.template($(this.templateEl).html());
                }
            },

            initialize: function() {
                _.bindAll(this);
                this.firstLoadSuccess = false;
                this.finished = false;

                this.collection = new ItemCollection();
                this.collection.on('reset', this.collectionReset);
                this.collection.on('add', this.addItem);
                this.endlessDom = this.$(".endless-container");

                this.offset = 0;
                this.limit = 20;

                this.setup();
                this.setupTemplates();
                this.requestObjects();

                $(window).scroll(this.infiniteScroll);
            },

            requestObjects: function() {
                if (!this.finished) {
                    var ajax = new Ajax();
                    ajax.on('success', this.requestSuccess);

                    var params = _.extend({}, {limit:this.limit, offset: this.offset},
                                                                this.params || {});
                    this.offset += this.limit;

                    if (this.method === 'get') {
                        ajax.get(this.url, params);
                    } else if (this.method === 'post') {
                        ajax.post(this.url, params);
                    }
                }
            },

            setEndlessFinishDom: function() {
                this.endlessDom.find("a.endless_more").replaceWith("No more results");
            },

            requestSuccess: function(xhr) {
                if (xhr.status === 200) {
                    var data = JSON.parse(xhr.responseText);

                    if (data.objects.length === 0) {
                        this.setEndlessFinishDom();
                        this.finished = true;
                    } else {
                        if (!this.firstLoadSuccess) {
                            this.firstLoadSuccess = true;
                            this.collection.reset(data.objects);
                        } else {
                            _.each(data.objects, function(item) {
                                this.collection.add(item);
                            }, this);
                        }

                        this.endlessDom.appendTo(this.$el);
                    }
                }
            },

            collectionReset: function(collection) {
                this.$el.empty();
                collection.each(this.addItem);
            },

            renderItem: function(model) {
                if (this.template !== undefined) {
                    return this.template(model.toJSON());
                } else {
                    return "
REIMPLEMENT THIS
";
                }
            },

            addItem: function(model) {
                var html = this.renderItem(model);
                this.$el.append(html);
            },

            infiniteScroll: function() {
                var doc = $(document), win = $(window);
                var margin = this.$el.data('margin') || 300;

                if ((doc.height() - win.height() - win.scrollTop()) <= margin) {
                    this.$("a.endless_more").click();
                }
            },

            onMoreClicked: function(event) {
                event.preventDefault();
                this.requestObjects();
            }
        });
        Agora.ActivityListView = Agora.GenericListView.extend({
            el: "#activity-list",

            setup: function() {
                this.url = this.$el.data('url');
                this.method = this.$el.data('method') || 'get';
                this.templates = {}
            },

            renderItem: function(model) {
                var json = model.toJSON();
                if (!this.templates[json.type_name]) {
                    this.templates[json.type_name] = _.template(
                        $('#template-action_' + json.type_name).html()
                            || '<#template-action_' + json.type_name
                            + ' not found>'
                    );
                }
                return this.templates[json.type_name](json);
            }
        });
    }).call(this);
}).call(this);
<commit_msg>fixing calendar view dates<commit_after>(function() {
    var Agora = this.Agora,
        app = this.app;

    /*
     * Agora calendar widget scope
    */

    (function() {
        var ElectionModel = Backbone.Model.extend({});
        var ElectionsCollection = Backbone.Collection.extend({
            model: ElectionModel
        });

        Agora.CalendarWidgetView = Backbone.View.extend({
            el: "#agora-calendar",

            events: {
                "keyup .election-search-query": "onSearchChange"
            },

            initialize: function() {
                _.bindAll(this);
                this.template = _.template($("#template-election").html());
                this.collection = new ElectionsCollection();
                this.collection.on('reset', this.resetCollection);

                var ajax = new Ajax();
                ajax.on('success', this.initializeSuccess);
                ajax.get(this.$el.data('url'));

                // Debouncing
                this.onSearchChange = _.debounce(this.onSearchChange, 400);
            },

            initializeSuccess: function(xhr) {
                if (xhr.status === 200) {
                    var data = JSON.parse(xhr.responseText);
                    this.collection.reset(data.objects);
                }
            },

            onSearchChange: function(event) {
                var target = $(event.currentTarget);
                var data = {"q": target.val()};

                var ajax = new Ajax();
                ajax.on('success', this.initializeSuccess);
                ajax.get(this.$el.data('url'), data);
                console.log("onSearchChange: " + target.val());
            },

            resetCollection: function(collection) {
                this.$(".list-container").empty();

                var data = collection.groupBy(function(item) {
                    var date = item.get('voting_extended_until_date') ||
                        item.get('voting_ends_at_date') ||
                        item.get('voting_starts_at_date');
                    if (date) {
                        return date.split("T")[0];
                    } else {
                        return null;
                    }
                });

                _.each(_.pairs(data), function(item) {
                    var key = item[0],
                        val = item[1];

                    var date = moment(key);
                    var dom = this.template({"datetime":date.format("LL"), "items": val});

                    this.$(".list-container").append(dom);
                }, this);
            }
        });
    }).call(this);

    /*
     * Generic view for all search pages.
    */

    (function() {
        var ItemModel = Backbone.Model.extend({});

        var ItemCollection = Backbone.Collection.extend({
            model: ItemModel
        });

        Agora.GenericListView = Backbone.View.extend({
            el: "#activity-list",

            events: {
                "click a.endless_more": "onMoreClicked"
            },

            setup: function() {
                this.url = this.$el.data('url');
                this.method = this.$el.data('method') || 'get';
            },

            setupTemplates: function() {
                if (this.templateEl !== undefined) {
                    this.template = _.template($(this.templateEl).html());
                }
            },

            initialize: function() {
                _.bindAll(this);
                this.firstLoadSuccess = false;
                this.finished = false;

                this.collection = new ItemCollection();
                this.collection.on('reset', this.collectionReset);
                this.collection.on('add', this.addItem);
                this.endlessDom = this.$(".endless-container");

                this.offset = 0;
                this.limit = 20;

                this.setup();
                this.setupTemplates();
                this.requestObjects();

                $(window).scroll(this.infiniteScroll);
            },

            requestObjects: function() {
                if (!this.finished) {
                    var ajax = new Ajax();
                    ajax.on('success', this.requestSuccess);

                    var params = _.extend({}, {limit:this.limit, offset: this.offset},
                                                                this.params || {});
                    this.offset += this.limit;

                    if (this.method === 'get') {
                        ajax.get(this.url, params);
                    } else if (this.method === 'post') {
                        ajax.post(this.url, params);
                    }
                }
            },

            setEndlessFinishDom: function() {
                this.endlessDom.find("a.endless_more").replaceWith("No more results");
            },

            requestSuccess: function(xhr) {
                if (xhr.status === 200) {
                    var data = JSON.parse(xhr.responseText);

                    if (data.objects.length === 0) {
                        this.setEndlessFinishDom();
                        this.finished = true;
                    } else {
                        if (!this.firstLoadSuccess) {
                            this.firstLoadSuccess = true;
                            this.collection.reset(data.objects);
                        } else {
                            _.each(data.objects, function(item) {
                                this.collection.add(item);
                            }, this);
                        }

                        this.endlessDom.appendTo(this.$el);
                    }
                }
            },

            collectionReset: function(collection) {
                this.$el.empty();
                collection.each(this.addItem);
            },

            renderItem: function(model) {
                if (this.template !== undefined) {
                    return this.template(model.toJSON());
                } else {
                    return "
REIMPLEMENT THIS
";
                }
            },

            addItem: function(model) {
                var html = this.renderItem(model);
                this.$el.append(html);
            },

            infiniteScroll: function() {
                var doc = $(document), win = $(window);
                var margin = this.$el.data('margin') || 300;

                if ((doc.height() - win.height() - win.scrollTop()) <= margin) {
                    this.$("a.endless_more").click();
                }
            },

            onMoreClicked: function(event) {
                event.preventDefault();
                this.requestObjects();
            }
        });
        Agora.ActivityListView = Agora.GenericListView.extend({
            el: "#activity-list",

            setup: function() {
                this.url = this.$el.data('url');
                this.method = this.$el.data('method') || 'get';
                this.templates = {}
            },

            renderItem: function(model) {
                var json = model.toJSON();
                if (!this.templates[json.type_name]) {
                    this.templates[json.type_name] = _.template(
                        $('#template-action_' + json.type_name).html()
                            || '<#template-action_' + json.type_name
                            + ' not found>'
                    );
                }
                return this.templates[json.type_name](json);
            }
        });
    }).call(this);
}).call(this);
<|endoftext|>