<commit_before>import React from 'react';

import PreviewWindow from '../containers/PreviewWindow';
import Appbar from '../containers/Appbar';
import TimelineNodeOrganizer from '../containers/TimelineNodeOrganizer';
import TimelineNodeEditor from '../containers/TimelineNodeEditor';
import Authentications from '../containers/Authentications';
import Notifications from '../containers/Notifications';

import ZoomBar from './PreviewWindow/ZoomBar';
import { getFullScreenState, PreviewWindowContainerWidth } from './PreviewWindow';
import { WIDTH as EditorWidth } from './TimelineNodeEditor';
import { WIDTH as OrganizerWidth } from './TimelineNodeOrganizer';

import GeneralTheme from './theme.js';

const colors = GeneralTheme.colors;

const style = {
	App: utils.prefixer({
		width: '100%',
		height: '100%',
		display: 'flex',
		flexDirection: 'column',
	}),
	AppbarContainer: utils.prefixer({
		flexBasis: '56px',
		maxHeight: '56px',
		zIndex: 5,
		boxShadow: '0 2px 5px rgba(0,0,0, .26)',
	}),
	AppMainContainer: utils.prefixer({
		flexGrow: '1',
		width: '100%',
		height: '100%',
		display: 'flex',
		flexDirection: 'row',
	}),
	AppMainPreview: utils.prefixer({
		flexGrow: 1,
		backgroundColor: colors.background,
		height: "100%",
		overflow: 'hidden',
		display: 'flex',
		flexDirection: 'column',
		alignItems: 'center',
		justifyContent: 'center'
	})
}

const isValidSize = (v) => (v !== null && v !== undefined && v >= 0);
const limitToMax = (v, maxV) => (!isValidSize(v) || v > maxV ? maxV : v);

const checkValidSize = (s) => (s >= 0);

class App extends React.Component {

	constructor(props) {
		super(props);

		this.state = {
			timelineOrganizerDrawerToggle: true,
			timelineEditorDrawerToggle: false,
			zoomScale: 1,
			zoomWidth: null,
			zoomHeight: null,
			zoomWidthByUser: null,
			zoomHeightByUser: null,
			displayZoom: -1,
			test: 0
		}

		this.getMaxSize = () => {
			const {
				zoomWidth,
				zoomHeight,
				zoomWidthByUser,
				zoomHeightByUser,
				timelineOrganizerDrawerToggle : organizerOpened,
				timelineEditorDrawerToggle: editorOpened
			} = this.state;

			let left = organizerOpened ? OrganizerWidth : 0,
				right = editorOpened ? EditorWidth : 0,
				mainBodyWidth = this.AppPage.clientWidth - left - right,
				maxWidth = Math.round(mainBodyWidth * PreviewWindowContainerWidth),
				maxHeight = this.previewWindow.clientHeight;

			// let maxWidth = this.previewWindow.clientWidth,
			// 	maxHeight = this.previewWindow.clientHeight;

			return {
				zoomWidthByUser: limitToMax(zoomWidthByUser, maxWidth),
				zoomHeightByUser: limitToMax(zoomHeightByUser, maxHeight),
				zoomWidth: limitToMax(zoomWidth, maxWidth),
				zoomHeight: limitToMax(zoomHeight, maxHeight),
				maxZoomWidth: maxWidth,
				maxZoomHeight: maxHeight,
			}
		}

		this.updateMaxSize = () => {
			this.setState({
				...this.getMaxSize()
			})
		}

		this.openTimelineOgranizerDrawer = () => {
			this.setState({ timelineOrganizerDrawerToggle: true, }, this.updateMaxSize);
		}

		this.closeTimelineOgranizerDrawer = () => {
			this.setState({ timelineOrganizerDrawerToggle: false, }, this.updateMaxSize);
		}

		this.openTimelineEditorDrawer = () => {
			this.setState({ timelineEditorDrawerToggle: true, }, this.updateMaxSize);
		}

		this.closeTimelineEditorDrawer = () => {
			this.setState({ timelineEditorDrawerToggle: false, }, this.updateMaxSize);
		}

		this.setZoomWidth = (e) => {
			if (e.which === 13) {
				let {
					zoomScale: scale,
					zoomWidthByUser: desired,
					maxZoomWidth: max
				} = this.state;

				let newSize = desired * scale;
				if (newSize > max) scale = max / newSize;
				this.setState({
					zoomWidth: limitToMax(newSize, max),
					zoomScale: scale,
					displayZoom: -1,
				})
			}
		}

		this.setZoomHeight = (e) => {
			if (e.which === 13) {
				let {
					zoomScale: scale,
					zoomHeightByUser: desired,
					maxZoomHeight: max
				} = this.state;

				let newSize = desired * scale;
				if (newSize > max) scale = max / newSize;
				this.setState({
					zoomHeight: limitToMax(newSize, max),
					zoomScale: scale,
					displayZoom: -1,
				})
			}
		}

		this.setZoomScale = (scale) => {
			let {
				zoomWidthByUser,
				zoomHeightByUser,
				zoomScale
			} = this.state;

			this.setState({
				zoomScale: scale,
				zoomWidthByUser: Math.round(zoomWidthByUser / (scale/zoomScale)),
				zoomHeightByUser: Math.round(zoomHeightByUser / (scale/zoomScale)),
			});
		}

		this.onInputZoomHeight = (e) => {
			if (isValidSize(e.target.value)) {
				this.setState({
					zoomHeightByUser: e.target.value
				})
			}
		}

		this.onInputZoomWidth = (e) => {
			if (isValidSize(e.target.value)) {
				this.setState({
					zoomWidthByUser: e.target.value
				})
			}
		}

		this.setDisplayZoom = (event, index, value) => {
			this.setState({
				displayZoom: value
			})
			if (value >= 0) {
				this.setZoomScale(value);
			}
		}

		this.testBug = () => {
			this.setState({test: this.previewWindow.clientWidth},
				() => {
					console.log(
						`${this.state.test}, should be ${this.getMaxSize().maxZoomWidth}`
					);
				}
			);
		}

		this.getAuthenticationsClass = () => {
			return this.Authentications;
		}
	}

	componentWillMount() {
		window.addEventListener("resize", this.updateMaxSize);
	}

	componentDidMount() {
		this.updateMaxSize();
		// this.testBug();
	}

	componentWillUnmount() {
		window.removeEventListener("resize", this.updateMaxSize);
	}

	componentDidUpdate(prevProps, prevState) {
		if (prevProps.shouldEditorStayOpen !== this.props.shouldEditorStayOpen) {
			this.setState({
				timelineEditorDrawerToggle: this.props.shouldEditorStayOpen,
			});
		}
		if (prevProps.shouldOrganizerStayOpen !== this.props.shouldOrganizerStayOpen) {
			this.setState({
				timelineOrganizerDrawerToggle: this.props.shouldOrganizerStayOpen
			});
		}
	}

	render() {
		const {
			timelineOrganizerDrawerToggle,
			timelineOrganizerDrawerWidth,
			timelineEditorDrawerToggle,
			timelineEditorDrawerWidth,
			zoomScale,
			zoomWidth,
			zoomHeight,
			zoomWidthByUser,
			zoomHeightByUser,
			displayZoom
		} = this.state;

		const {
			openTimelineOgranizerDrawer,
			closeTimelineOgranizerDrawer,
			openTimelineEditorDrawer,
			closeTimelineEditorDrawer,
			onInputZoomHeight,
			onInputZoomWidth,
			setZoomHeight,
			setZoomWidth,
			setDisplayZoom,
		} = this;

		return (

 this.AppPage = el}>

					<Appbar
						drawerOpened={timelineOrganizerDrawerToggle}
						drawerOpenCallback={openTimelineOgranizerDrawer}
	  					drawerCloseCallback={closeTimelineOgranizerDrawer}
					/>

	  				<TimelineNodeOrganizer
	  					open={timelineOrganizerDrawerToggle}
	  					openTimelineEditorCallback={openTimelineEditorDrawer}
	  					closeTimelineEditorCallback={closeTimelineEditorDrawer}
	  				/>

		  				<ZoomBar
	  						zoomScale={zoomScale}
	  						zoomHeightByUser={zoomHeightByUser}
	  						zoomWidthByUser={zoomWidthByUser}
	  						displayZoom={displayZoom}
	  						setZoomHeight={setZoomHeight}
	  						setZoomWidth={setZoomWidth}
	  						onInputZoomHeight={onInputZoomHeight}
	  						onInputZoomWidth={onInputZoomWidth}
	  						setDisplayZoom={setDisplayZoom}
		  				/>
		  				<PreviewWindow
	  						zoomScale={zoomScale}
	  						zoomWidth={zoomWidth}
	  						zoomHeight={zoomHeight}
	  						sizeRef={el => this.previewWindow = el}
		  				/>

	  				<TimelineNodeEditor
	  					open={timelineEditorDrawerToggle}
	  					width={timelineEditorDrawerWidth}
	  					openTimelineEditorCallback={openTimelineEditorDrawer}
	  					closeTimelineEditorCallback={closeTimelineEditorDrawer}
	  				/>

	  			<Notifications />
	  			<Authentications />

  		);
	}
}

export default App;
<commit_msg>Fix import<commit_after>import React from 'react';

import PreviewWindow from '../containers/PreviewWindow';
import Appbar from '../containers/Appbar';
import TimelineNodeOrganizer from '../containers/TimelineNodeOrganizer';
import TimelineNodeEditor from '../containers/TimelineNodeEditor';
import Authentications from '../containers/Authentications';
import Notifications from '../containers/Notifications';

import ZoomBar from './PreviewWindow/ZoomBar';
import { getFullScreenState, PreviewWindowContainerWidth } from './PreviewWindow';
import { WIDTH as EditorWidth } from './TimelineNodeEditor/TimelineNodeEditor.jsx';
import { WIDTH as OrganizerWidth } from './TimelineNodeOrganizer/TimelineNodeOrganizer.jsx';

import GeneralTheme from './theme.js';

const colors = GeneralTheme.colors;

const style = {
	App: utils.prefixer({
		width: '100%',
		height: '100%',
		display: 'flex',
		flexDirection: 'column',
	}),
	AppbarContainer: utils.prefixer({
		flexBasis: '56px',
		maxHeight: '56px',
		zIndex: 5,
		boxShadow: '0 2px 5px rgba(0,0,0, .26)',
	}),
	AppMainContainer: utils.prefixer({
		flexGrow: '1',
		width: '100%',
		height: '100%',
		display: 'flex',
		flexDirection: 'row',
	}),
	AppMainPreview: utils.prefixer({
		flexGrow: 1,
		backgroundColor: colors.background,
		height: "100%",
		overflow: 'hidden',
		display: 'flex',
		flexDirection: 'column',
		alignItems: 'center',
		justifyContent: 'center'
	})
}

const isValidSize = (v) => (v !== null && v !== undefined && v >= 0);
const limitToMax = (v, maxV) => (!isValidSize(v) || v > maxV ? maxV : v);

const checkValidSize = (s) => (s >= 0);

class App extends React.Component {

	constructor(props) {
		super(props);

		this.state = {
			timelineOrganizerDrawerToggle: true,
			timelineEditorDrawerToggle: false,
			zoomScale: 1,
			zoomWidth: null,
			zoomHeight: null,
			zoomWidthByUser: null,
			zoomHeightByUser: null,
			displayZoom: -1,
			test: 0
		}

		this.getMaxSize = () => {
			const {
				zoomWidth,
				zoomHeight,
				zoomWidthByUser,
				zoomHeightByUser,
				timelineOrganizerDrawerToggle : organizerOpened,
				timelineEditorDrawerToggle: editorOpened
			} = this.state;

			let left = organizerOpened ? OrganizerWidth : 0,
				right = editorOpened ? EditorWidth : 0,
				mainBodyWidth = this.AppPage.clientWidth - left - right,
				maxWidth = Math.round(mainBodyWidth * PreviewWindowContainerWidth),
				maxHeight = this.previewWindow.clientHeight;

			// let maxWidth = this.previewWindow.clientWidth,
			// 	maxHeight = this.previewWindow.clientHeight;

			return {
				zoomWidthByUser: limitToMax(zoomWidthByUser, maxWidth),
				zoomHeightByUser: limitToMax(zoomHeightByUser, maxHeight),
				zoomWidth: limitToMax(zoomWidth, maxWidth),
				zoomHeight: limitToMax(zoomHeight, maxHeight),
				maxZoomWidth: maxWidth,
				maxZoomHeight: maxHeight,
			}
		}

		this.updateMaxSize = () => {
			this.setState(this.getMaxSize());
			console.log(this.getMaxSize())
		}

		this.openTimelineOgranizerDrawer = () => {
			this.setState({ timelineOrganizerDrawerToggle: true, }, this.updateMaxSize);
		}

		this.closeTimelineOgranizerDrawer = () => {
			this.setState({ timelineOrganizerDrawerToggle: false, }, this.updateMaxSize);
		}

		this.openTimelineEditorDrawer = () => {
			this.setState({ timelineEditorDrawerToggle: true, }, this.updateMaxSize);
		}

		this.closeTimelineEditorDrawer = () => {
			this.setState({ timelineEditorDrawerToggle: false, }, this.updateMaxSize);
		}

		this.setZoomWidth = (e) => {
			if (e.which === 13) {
				let {
					zoomScale: scale,
					zoomWidthByUser: desired,
					maxZoomWidth: max
				} = this.state;

				let newSize = desired * scale;
				if (newSize > max) scale = max / newSize;
				this.setState({
					zoomWidth: limitToMax(newSize, max),
					zoomScale: scale,
					displayZoom: -1,
				})
			}
		}

		this.setZoomHeight = (e) => {
			if (e.which === 13) {
				let {
					zoomScale: scale,
					zoomHeightByUser: desired,
					maxZoomHeight: max
				} = this.state;

				let newSize = desired * scale;
				if (newSize > max) scale = max / newSize;
				this.setState({
					zoomHeight: limitToMax(newSize, max),
					zoomScale: scale,
					displayZoom: -1,
				})
			}
		}

		this.setZoomScale = (scale) => {
			let {
				zoomWidthByUser,
				zoomHeightByUser,
				zoomScale
			} = this.state;

			this.setState({
				zoomScale: scale,
				zoomWidthByUser: Math.round(zoomWidthByUser / (scale/zoomScale)),
				zoomHeightByUser: Math.round(zoomHeightByUser / (scale/zoomScale)),
			});
		}

		this.onInputZoomHeight = (e) => {
			if (isValidSize(e.target.value)) {
				this.setState({
					zoomHeightByUser: e.target.value
				})
			}
		}

		this.onInputZoomWidth = (e) => {
			if (isValidSize(e.target.value)) {
				this.setState({
					zoomWidthByUser: e.target.value
				})
			}
		}

		this.setDisplayZoom = (event, index, value) => {
			this.setState({
				displayZoom: value
			})
			if (value >= 0) {
				this.setZoomScale(value);
			}
		}

		this.testBug = () => {
			this.setState({test: this.previewWindow.clientWidth},
				() => {
					console.log(
						`${this.state.test}, should be ${this.getMaxSize().maxZoomWidth}`
					);
				}
			);
		}

		this.getAuthenticationsClass = () => {
			return this.Authentications;
		}
	}

	componentWillMount() {
		window.addEventListener("resize", this.updateMaxSize);
	}

	componentDidMount() {
		this.updateMaxSize();
		// this.testBug();
	}

	componentWillUnmount() {
		window.removeEventListener("resize", this.updateMaxSize);
	}

	componentDidUpdate(prevProps, prevState) {
		if (prevProps.shouldEditorStayOpen !== this.props.shouldEditorStayOpen) {
			this.setState({
				timelineEditorDrawerToggle: this.props.shouldEditorStayOpen,
			});
		}
		if (prevProps.shouldOrganizerStayOpen !== this.props.shouldOrganizerStayOpen) {
			this.setState({
				timelineOrganizerDrawerToggle: this.props.shouldOrganizerStayOpen
			});
		}
	}

	render() {
		const {
			timelineOrganizerDrawerToggle,
			timelineOrganizerDrawerWidth,
			timelineEditorDrawerToggle,
			timelineEditorDrawerWidth,
			zoomScale,
			zoomWidth,
			zoomHeight,
			zoomWidthByUser,
			zoomHeightByUser,
			displayZoom
		} = this.state;

		const {
			openTimelineOgranizerDrawer,
			closeTimelineOgranizerDrawer,
			openTimelineEditorDrawer,
			closeTimelineEditorDrawer,
			onInputZoomHeight,
			onInputZoomWidth,
			setZoomHeight,
			setZoomWidth,
			setDisplayZoom,
		} = this;

		return (

 this.AppPage = el}>

					<Appbar
						drawerOpened={timelineOrganizerDrawerToggle}
						drawerOpenCallback={openTimelineOgranizerDrawer}
	  					drawerCloseCallback={closeTimelineOgranizerDrawer}
					/>

	  				<TimelineNodeOrganizer
	  					open={timelineOrganizerDrawerToggle}
	  					openTimelineEditorCallback={openTimelineEditorDrawer}
	  					closeTimelineEditorCallback={closeTimelineEditorDrawer}
	  				/>

		  				<ZoomBar
	  						zoomScale={zoomScale}
	  						zoomHeightByUser={zoomHeightByUser}
	  						zoomWidthByUser={zoomWidthByUser}
	  						displayZoom={displayZoom}
	  						setZoomHeight={setZoomHeight}
	  						setZoomWidth={setZoomWidth}
	  						onInputZoomHeight={onInputZoomHeight}
	  						onInputZoomWidth={onInputZoomWidth}
	  						setDisplayZoom={setDisplayZoom}
		  				/>
		  				<PreviewWindow
	  						zoomScale={zoomScale}
	  						zoomWidth={zoomWidth}
	  						zoomHeight={zoomHeight}
	  						sizeRef={el => this.previewWindow = el}
		  				/>

	  				<TimelineNodeEditor
	  					open={timelineEditorDrawerToggle}
	  					width={timelineEditorDrawerWidth}
	  					openTimelineEditorCallback={openTimelineEditorDrawer}
	  					closeTimelineEditorCallback={closeTimelineEditorDrawer}
	  				/>

	  			<Notifications />
	  			<Authentications />

  		);
	}
}

export default App;
<|endoftext|>


<commit_before>/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- /
/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */

'use strict';

function Icon(iconGrid, index) {
  this.iconGrid = iconGrid;
  this.index = index;
}

Icon.prototype = {
  update: function(img, label) {
    var iconGrid = this.iconGrid;
    var iconWidth = iconGrid.iconWidth;
    var iconHeight = iconGrid.iconHeight;
    var border = iconGrid.border;
    var sprite = this.sprite;
    if (!sprite) {
      var sceneGraph = iconGrid.sceneGraph;
      sprite = new Sprite(iconWidth, iconHeight);
      sceneGraph.add(sprite);
      this.sprite = sprite;
    }
    var ctx = sprite.getContext2D();
    ctx.drawImage(img, iconWidth * border, iconHeight * border,
                  iconWidth * (1 - border * 2),
                  iconHeight * (1 - border * 2));
    ctx.font = Math.floor(iconHeight * border * 0.7) + "pt Arial, sans-serif";
    ctx.textAlign = "center";
    ctx.fillStyle = "black";
    ctx.textBaseline = "top";
    ctx.fillText(label, iconWidth/2, iconHeight - iconHeight*border, iconWidth*0.9);
    this.reflow();
  },
  // return the X coordinate of the top left corner of a slot
  slotLeft: function() {
    var iconGrid = this.iconGrid;
    return iconGrid.itemBoxWidth * (this.index % iconGrid.columns);
  },
  // return the Y coordinate of the top left corner of a slot
  slotTop: function() {
    var iconGrid = this.iconGrid;
    var slot = this.index % iconGrid.itemsPerPage;
    return Math.floor(slot / iconGrid.columns) * iconGrid.itemBoxHeight;
  },
  reflow: function(animated) {
    var sprite = this.sprite;
    if (!sprite)
      return;
    var iconGrid = this.iconGrid;
    var duration = animated ? iconGrid.reflowTime : 0;
    var index = this.index;
    var itemsPerPage = iconGrid.itemsPerPage;
    var page = Math.floor(index / iconGrid.itemsPerPage);
    sprite.setPosition(page * iconGrid.containerWidth + this.slotLeft(),
                       this.slotTop(),
                       duration);
    sprite.setScale(1, duration);
  }
}

function IconGrid(canvas, iconWidth, iconHeight, border, reflowTime) {
  canvas.mozOpaque = true;

  this.iconWidth = iconWidth;
  this.iconHeight = iconHeight;
  this.reflowTime = reflowTime || 250;
  this.sceneGraph = new SceneGraph(canvas);
  this.border = border || 0.1;
  this.icons = [];

  // update the layout state
  this.reflow(canvas.width, canvas.height, false);

  // install event handlers
  canvas.addEventListener("touchstart", this, true);
  canvas.addEventListener("mousedown", this, true);
}

IconGrid.prototype = {
  add: function(src, label) {
    // Create the icon in the icon grid
    var icons = this.icons;
    var icon = new Icon(this, this.icons.length);
    icon.index = icons.length;
    icons.push(icon);
    // Load the image, sprite will be created when image load is complete
    var img = new Image();
    img.src = src;
    img.label = label;
    img.icon = icon;
    img.onload = function() {
      // Update the icon (this will trigger a reflow and a repaint)
      var icon = this.icon;
      icon.update(this, this.label);
    }
    return icon;
  },
  remove: function(icon) {
    this.icons.splice(icon.index);
    if (icon.sprite)
      sceneGraph.remove(icon.sprite);
  },
  // reflow the icon grid
  reflow: function(width, height, animated) {
    // first recalculate all the layout information
    this.containerWidth = width;
    this.containerHeight = height;
    this.panelWidth = this.containerWidth;
    this.pageIndicatorWidth = this.containerWidth;
    this.pageIndicatorHeight = Math.min(Math.max(this.containerHeight * 0.7, 14), 20);
    this.panelHeight = this.containerHeight - this.pageIndicatorHeight;
    this.columns = Math.floor(this.panelWidth / this.iconWidth);
    this.rows = Math.floor(this.panelHeight / this.iconHeight);
    this.itemsPerPage = this.rows * this.columns;
    this.itemBoxWidth = Math.floor(this.panelWidth / this.columns);
    this.itemBoxHeight = Math.floor(this.panelHeight / this.rows);

    // now reflow all the icons
    var icons = this.icons;
    for (var n = 0; n < icons.length; ++n)
      icons[n].reflow();
  },
  handleEvent: function(e) {
    switch (e.type) {
    case 'touchstart':
      if (e.touches.length == 1)
        this.onTouchStart(e.touches[0]);
      break;
    case 'mousedown':
      this.onTouchStart(e);
      break;
    }
  },
  onTouchStart: function(e) {
    this.sceneGraph.forHit(e.pageX, e.pageY, function(sprite) { console.log(sprite.label); });
  }
}

function OnLoad() {
  var fruits = [
               {
                 label: 'Strawberry',
                 src: 'images/strawberry.png'
               },
               {
                 label: 'Watermelon',
                 src: 'images/watermelon.png'
               },
               {
                 label: 'Apple',
                 src: 'images/apple.png'
               },
               {
                 label: 'Banana',
                 src: 'images/banana.png'
               },
               {
                 label: 'Grape',
                 src: 'images/grape.png'
               },
               {
                 label: 'Orange',
                 src: 'images/orange.png'
               },
               {
                 label: 'Papaya',
                 src: 'images/papaya.png'
               },
               {
                 label: 'Pineapple',
                 src: 'images/pineapple.png'
               }
              ];

  var icons = [];
  for (var n = 0; n < fruits.length; ++n)
    icons.push(fruits[n]);
  for (var n = 0; n < fruits.length; ++n)
    icons.push(fruits[n]);
  for (var n = 0; n < fruits.length; ++n)
    icons.push(fruits[n]);
  for (var n = 0; n < fruits.length; ++n)
    icons.push(fruits[n]);

  var iconGrid = new IconGrid(document.getElementById("screen"), 120, 120, 0.15, 500);
  for (var n = 0; n < icons.length; ++n)
    iconGrid.add(icons[n].src, icons[n].label);
}
<commit_msg>draw the sprite image before adding it to the scene graph (which is when we upload it to a texture)<commit_after>/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- /
/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */

'use strict';

function Icon(iconGrid, index) {
  this.iconGrid = iconGrid;
  this.index = index;
}

Icon.prototype = {
  update: function(img, label) {
    var iconGrid = this.iconGrid;
    var iconWidth = iconGrid.iconWidth;
    var iconHeight = iconGrid.iconHeight;
    var border = iconGrid.border;
    var sprite = this.sprite;
    var createSprite = !sprite;
    if (createSprite) {
      var sceneGraph = iconGrid.sceneGraph;
      sprite = new Sprite(iconWidth, iconHeight);
      this.sprite = sprite;
    }
    var ctx = sprite.getContext2D();
    ctx.drawImage(img, iconWidth * border, iconHeight * border,
                  iconWidth * (1 - border * 2),
                  iconHeight * (1 - border * 2));
    ctx.font = Math.floor(iconHeight * border * 0.7) + "pt Arial, sans-serif";
    ctx.textAlign = "center";
    ctx.fillStyle = "black";
    ctx.textBaseline = "top";
    ctx.fillText(label, iconWidth/2, iconHeight - iconHeight*border, iconWidth*0.9);

    if (createSprite) {
      sceneGraph.add(sprite);
    }
    this.reflow();
  },
  // return the X coordinate of the top left corner of a slot
  slotLeft: function() {
    var iconGrid = this.iconGrid;
    return iconGrid.itemBoxWidth * (this.index % iconGrid.columns);
  },
  // return the Y coordinate of the top left corner of a slot
  slotTop: function() {
    var iconGrid = this.iconGrid;
    var slot = this.index % iconGrid.itemsPerPage;
    return Math.floor(slot / iconGrid.columns) * iconGrid.itemBoxHeight;
  },
  reflow: function(animated) {
    var sprite = this.sprite;
    if (!sprite)
      return;
    var iconGrid = this.iconGrid;
    var duration = animated ? iconGrid.reflowTime : 0;
    var index = this.index;
    var itemsPerPage = iconGrid.itemsPerPage;
    var page = Math.floor(index / iconGrid.itemsPerPage);
    sprite.setPosition(page * iconGrid.containerWidth + this.slotLeft(),
                       this.slotTop(),
                       duration);
    sprite.setScale(1, duration);
  }
}

function IconGrid(canvas, iconWidth, iconHeight, border, reflowTime) {
  canvas.mozOpaque = true;

  this.iconWidth = iconWidth;
  this.iconHeight = iconHeight;
  this.reflowTime = reflowTime || 250;
  this.sceneGraph = new SceneGraph(canvas);
  this.border = border || 0.1;
  this.icons = [];

  // update the layout state
  this.reflow(canvas.width, canvas.height, false);

  // install event handlers
  canvas.addEventListener("touchstart", this, true);
  canvas.addEventListener("mousedown", this, true);
}

IconGrid.prototype = {
  add: function(src, label) {
    // Create the icon in the icon grid
    var icons = this.icons;
    var icon = new Icon(this, this.icons.length);
    icon.index = icons.length;
    icons.push(icon);
    // Load the image, sprite will be created when image load is complete
    var img = new Image();
    img.src = src;
    img.label = label;
    img.icon = icon;
    img.onload = function() {
      // Update the icon (this will trigger a reflow and a repaint)
      var icon = this.icon;
      icon.update(this, this.label);
    }
    return icon;
  },
  remove: function(icon) {
    this.icons.splice(icon.index);
    if (icon.sprite)
      sceneGraph.remove(icon.sprite);
  },
  // reflow the icon grid
  reflow: function(width, height, animated) {
    // first recalculate all the layout information
    this.containerWidth = width;
    this.containerHeight = height;
    this.panelWidth = this.containerWidth;
    this.pageIndicatorWidth = this.containerWidth;
    this.pageIndicatorHeight = Math.min(Math.max(this.containerHeight * 0.7, 14), 20);
    this.panelHeight = this.containerHeight - this.pageIndicatorHeight;
    this.columns = Math.floor(this.panelWidth / this.iconWidth);
    this.rows = Math.floor(this.panelHeight / this.iconHeight);
    this.itemsPerPage = this.rows * this.columns;
    this.itemBoxWidth = Math.floor(this.panelWidth / this.columns);
    this.itemBoxHeight = Math.floor(this.panelHeight / this.rows);

    // now reflow all the icons
    var icons = this.icons;
    for (var n = 0; n < icons.length; ++n)
      icons[n].reflow();
  },
  handleEvent: function(e) {
    switch (e.type) {
    case 'touchstart':
      if (e.touches.length == 1)
        this.onTouchStart(e.touches[0]);
      break;
    case 'mousedown':
      this.onTouchStart(e);
      break;
    }
  },
  onTouchStart: function(e) {
    this.sceneGraph.forHit(e.pageX, e.pageY, function(sprite) { console.log(sprite.label); });
  }
}

function OnLoad() {
  var fruits = [
               {
                 label: 'Strawberry',
                 src: 'images/strawberry.png'
               },
               {
                 label: 'Watermelon',
                 src: 'images/watermelon.png'
               },
               {
                 label: 'Apple',
                 src: 'images/apple.png'
               },
               {
                 label: 'Banana',
                 src: 'images/banana.png'
               },
               {
                 label: 'Grape',
                 src: 'images/grape.png'
               },
               {
                 label: 'Orange',
                 src: 'images/orange.png'
               },
               {
                 label: 'Papaya',
                 src: 'images/papaya.png'
               },
               {
                 label: 'Pineapple',
                 src: 'images/pineapple.png'
               }
              ];

  var icons = [];
  for (var n = 0; n < fruits.length; ++n)
    icons.push(fruits[n]);
  for (var n = 0; n < fruits.length; ++n)
    icons.push(fruits[n]);
  for (var n = 0; n < fruits.length; ++n)
    icons.push(fruits[n]);
  for (var n = 0; n < fruits.length; ++n)
    icons.push(fruits[n]);

  var iconGrid = new IconGrid(document.getElementById("screen"), 120, 120, 0.15, 500);
  for (var n = 0; n < icons.length; ++n)
    iconGrid.add(icons[n].src, icons[n].label);
}
<|endoftext|>


<commit_before>//= require ../support/jquery
//= require esphinx/support/object
//= require esphinx_ui

var
    jQuery,
    esPhinx;

(function ($module, $) {
    "use strict";

    var
        resolveArgs = function (jqObj, args) {
            if (args.addClass) {
                jqObj.addClass(args.addClass);
            }

            if (args.removeClass) {
                jqObj.addClass(args.removeClass);
            }
        },

        hide = function (jqObj, args) {
            // faltam testes para suporte a estilização. Talvez tenha de mapear as propriedades do css para ver se há transition, o tipo, caso tenha pegar os ms para usar no setTimeout
            jqObj.hide();

            if (args) {
                resolveArgs(jqObj, args);
            }
        },

        show = function (jqObj, args) {
            jqObj.show();

            if (args) {
                resolveArgs(jqObj, args);
            }
        },

        toggle = function (jqObj, args) {
            jqObj.css("position", "absolute");

            if (jqObj.is(":visible")) {
                hide(jqObj, args);
            }
            else {
                show(jqObj, args);
            }
        },

        // dar a oportunidade de informar as classes para o efeito
        closeAll = function (jqObj, args) {
            hide(jqObj, args);
        },

        resolveClass = function (className) {
            return '.' + className.replace(/ /, '.');
        };

    $module.extend({
        window: {
            tooltip: {

                // O próximo passo é testar se o evento é do mouse. Caso seja colocar um temporizador para desaparecer caso o ponteiro esteja fora do handler
                hideAll: function (e, tooltipId, args) {
                    var
                        target = $(e.target);

                    if (target.children(tooltipId).length === 0 && !target
                        .is(tooltipId)) {
                        closeAll(target.find(tooltipId), args);
                    }
                },

                tooltip: function () {

                    var
                        constructor = $module.window.tooltip.tooltip,
                        handler,
                        tooltipId,
                        args;

                    if (!(this instanceof constructor)) {
                        return new constructor(arguments);
                    } else {
                        args = arguments.flatten();
                        if (!handler) {
                            handler = args[0];
                        }

                        if (!tooltipId) {
                            tooltipId = args[1];
                        }
                    }

                    this.toggle = function (e, args) {
                        var
                            target = $(e.target),
                            tooltipTag = handler.find(tooltipId);

                        if (!target.is(resolveClass(tooltipTag
                            .attr("class")))) {
                            toggle(tooltipTag, args);
                        }
                    }

                    return this;
                }

            }
        }
    });

})(esPhinx.ui, jQuery);
<commit_msg>change constructor method name<commit_after>//= require ../support/jquery
//= require esphinx/support/object
//= require esphinx_ui

var
    jQuery,
    esPhinx;

(function ($module, $) {
    "use strict";

    var
        resolveArgs = function (jqObj, args) {
            if (args.addClass) {
                jqObj.addClass(args.addClass);
            }

            if (args.removeClass) {
                jqObj.addClass(args.removeClass);
            }
        },

        hide = function (jqObj, args) {
            // faltam testes para suporte a estilização. Talvez tenha de mapear as propriedades do css para ver se há transition, o tipo, caso tenha pegar os ms para usar no setTimeout
            jqObj.hide();

            if (args) {
                resolveArgs(jqObj, args);
            }
        },

        show = function (jqObj, args) {
            jqObj.show();

            if (args) {
                resolveArgs(jqObj, args);
            }
        },

        toggle = function (jqObj, args) {
            jqObj.css("position", "absolute");

            if (jqObj.is(":visible")) {
                hide(jqObj, args);
            }
            else {
                show(jqObj, args);
            }
        },

        // dar a oportunidade de informar as classes para o efeito
        closeAll = function (jqObj, args) {
            hide(jqObj, args);
        },

        resolveClass = function (className) {
            return '.' + className.replace(/ /, '.');
        };

    $module.extend({
        window: {
            tooltip: {

                // O próximo passo é testar se o evento é do mouse. Caso seja colocar um temporizador para desaparecer caso o ponteiro esteja fora do handler
                hideAll: function (e, tooltipId, args) {
                    var
                        target = $(e.target);

                    if (target.children(tooltipId).length === 0 && !target
                        .is(tooltipId)) {
                        closeAll(target.find(tooltipId), args);
                    }
                },

                new: function () {

                    var
                        constructor = $module.window.tooltip.new,
                        handler,
                        tooltipId,
                        args;

                    if (!(this instanceof constructor)) {
                        return new constructor(arguments);
                    } else {
                        args = arguments.flatten();
                        if (!handler) {
                            handler = args[0];
                        }

                        if (!tooltipId) {
                            tooltipId = args[1];
                        }
                    }

                    this.toggle = function (e, args) {
                        var
                            target = $(e.target),
                            tooltipTag = handler.find(tooltipId);

                        if (!target.is(resolveClass(tooltipTag
                            .attr("class")))) {
                            toggle(tooltipTag, args);
                        }
                    };

                    return this;
                }

            }
        }
    });

})(esPhinx.ui, jQuery);
<|endoftext|>


<commit_before>// Init session with users data or guest defaults.

'use strict';

var memoizee = require('memoizee');

module.exports = function (N) {

  // Find and cache usergroup ObjectId forever. Use only for 'protected' groups.
  //
  var findUsergroupId = memoizee(function (shortName, callback) {
    N.models.users.UserGroup.findIdByName(shortName, callback);
  }, { async: true });

  function initGuestSession(env, callback) {
    env.extras.puncher.start('load guest group id');

    findUsergroupId('guests', function (err, guestsId) {
      if (err) {
        callback(err);
        return;
      }

      env.user_info = {};
      env.user_info.hb = false;
      env.user_info.is_guest = true;
      env.user_info.is_member = true;

      // Fill user info for browser
      env.runtime.user_name = '';
      env.runtime.is_member = false;
      env.runtime.is_guest  = true;

      // Propose guest user info to the settings params.
      env.extras.settings.params.user_id       = 0;
      env.extras.settings.params.usergroup_ids = [ guestsId ];

      env.extras.puncher.stop();

      callback();
    });
  }

  // Fetch current user info. Fired before each server handler.
  N.wire.before('server_chain:*', { priority: -65 }, function current_user_load(env, callback) {
    // Not logged in - initialize guest session.
    if (!env.session || !env.session.user_id) {
      initGuestSession(env, callback);
      return;
    }

    env.extras.puncher.start('load user info');

    N.models.users.User
      .findById(env.session.user_id)
      .select('_id name usergroups locale')
      .setOptions({ lean: true })
      .exec(function (err, user) {

        env.extras.puncher.stop();

        if (err) {
          callback(err);
          return;
        }

        // User was deleted while session is still active - reinit as a guest.
        if (!user) {
          initGuestSession(env, callback);
          return;
        }

        if (user.locale) {
          env.session.locale = user.locale;
        }

        env.user_info = {};
        env.user_info.hb = user.hb;
        env.user_info.is_guest = false;
        env.user_info.is_member = true;

        // Fill user info for browser
        env.runtime.user_name = user.name;
        env.runtime.is_guest  = false;
        env.runtime.is_member = true;

        // Propose user info to the settings params.
        env.extras.settings.params.user_id       = user._id;
        env.extras.settings.params.usergroup_ids = user.usergroups;

        callback();
      });
  });
};
<commit_msg>Fixed guest user id to be mongo-like<commit_after>// Init session with users data or guest defaults.

'use strict';

var memoizee = require('memoizee');

module.exports = function (N) {

  // Find and cache usergroup ObjectId forever. Use only for 'protected' groups.
  //
  var findUsergroupId = memoizee(function (shortName, callback) {
    N.models.users.UserGroup.findIdByName(shortName, callback);
  }, { async: true });

  function initGuestSession(env, callback) {
    env.extras.puncher.start('load guest group id');

    findUsergroupId('guests', function (err, guestsId) {
      if (err) {
        callback(err);
        return;
      }

      env.user_info = {};
      env.user_info.hb = false;
      env.user_info.is_guest = true;
      env.user_info.is_member = true;

      // Fill user info for browser
      env.runtime.user_name = '';
      env.runtime.is_member = false;
      env.runtime.is_guest  = true;

      // Propose guest user info to the settings params.
      env.extras.settings.params.user_id       = '000000000000000000000000';
      env.extras.settings.params.usergroup_ids = [ guestsId ];

      env.extras.puncher.stop();

      callback();
    });
  }

  // Fetch current user info. Fired before each server handler.
  N.wire.before('server_chain:*', { priority: -65 }, function current_user_load(env, callback) {
    // Not logged in - initialize guest session.
    if (!env.session || !env.session.user_id) {
      initGuestSession(env, callback);
      return;
    }

    env.extras.puncher.start('load user info');

    N.models.users.User
      .findById(env.session.user_id)
      .select('_id name usergroups locale')
      .setOptions({ lean: true })
      .exec(function (err, user) {

        env.extras.puncher.stop();

        if (err) {
          callback(err);
          return;
        }

        // User was deleted while session is still active - reinit as a guest.
        if (!user) {
          initGuestSession(env, callback);
          return;
        }

        if (user.locale) {
          env.session.locale = user.locale;
        }

        env.user_info = {};
        env.user_info.hb = user.hb;
        env.user_info.is_guest = false;
        env.user_info.is_member = true;

        // Fill user info for browser
        env.runtime.user_name = user.name;
        env.runtime.is_guest  = false;
        env.runtime.is_member = true;

        // Propose user info to the settings params.
        env.extras.settings.params.user_id       = user._id;
        env.extras.settings.params.usergroup_ids = user.usergroups;

        callback();
      });
  });
};
<|endoftext|>


<commit_before>/* See license.txt for terms of usage */

define([
    "firebug/lib/trace",
    "firebug/lib/url",
    "firebug/lib/string",
],
function(FBTrace, Url, Str) {

// ********************************************************************************************* //
// Constants

var Cc = Components.classes;
var Ci = Components.interfaces;
var Cu = Components.utils;

var Trace = FBTrace.to("DBG_PROFILER");
var TraceError = FBTrace.to("DBG_ERRORS");

// ********************************************************************************************* //
// Profiler engine based on JSD2 API

function ProfilerEngine(context)
{
    this.context = context
}

/**
 * @object Implements logic for collecting data about script execution. The object
 * collects the following information:
 * 1) Function call count
 * 2) Execution time (including and not including nested calls)
 * 3) Total execution time
 */
ProfilerEngine.prototype =
/** @lends ProfilerEngine */
{
    startProfiling: function()
    {
        // Collected profiling results are stored per 'script' in this structure.
        this.scripts = new Results();

        // Total profiling time (total executing time of the first executed frame).
        this.startTime = null;
        this.endTime = null;

        // Get debugger for profiled global (the current content window).
        this.dbg = this.getDebugger(this.context);

        // Hook function calls
        this.dbg.onEnterFrame = this.onEnterFrame.bind(this);
    },

    stopProfiling: function()
    {
        // Remove debugger hook.
        this.dbg.onEnterFrame = undefined;

        // Return total execution time.
        return this.endTime - this.startTime;
    },

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

    // xxxHonza: firebug/debugger/debuggerLib module should be used somehow
    getDebugger: function(context)
    {
        var jsDebugger = {};
        Cu.import("resource://gre/modules/jsdebugger.jsm", jsDebugger);

        var global = Cu.getGlobalForObject({});
        jsDebugger.addDebuggerToGlobal(global);

        return new global.Debugger(context.window);
    },

    enumerateScripts: function(callback)
    {
        for (var i=0; i<this.scripts.arr.length; i++)
        {
            var script = this.scripts.arr[i];

            // Compute own execution time (total nested execution time from nested frames
            // has been collected during the profiling session).
            script.totalOwnExecutionTime = script.totalExecutionTime -
                script.totalNestedExecutionTime;

            callback.enumerateScript(script);
        }
    },

    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
    // Handlers

    onEnterFrame: function(frame)
    {
        var now = this.now();

        // Remember the first start time to compute the total profiling time later.
        if (!this.startTime)
            this.startTime = now;

        // Collected data are sorted per script within a structure, see the scriptInfo below.
        // There is one info structure per script object.
        var script = frame.script;
        if (!script)
        {
            TraceError.sysout("profilerEngine.onEnterFrame; ERROR null script!");
            return;
        }

        var scriptInfo = this.scripts.get(script);
        if (!scriptInfo)
        {
            var url = script ? script.url : null;
            var name = frame.callee ? frame.callee.name : "<unknown>";

            scriptInfo = {
                callCount: 0,
                startLine: script ? script.startLine : -1,
                url: url,
                fileName: Url.getFileName(url),
                funcName: name,
                totalExecutionTime: 0,
                minExecutionTime: undefined,
                maxExecutionTime: undefined,
                totalNestedExecutionTime: 0,
            };

            this.scripts.set(script, scriptInfo);
        }

        scriptInfo.callCount++;

        // Hook 'onPop' so we can also get the end execution time.
        frame.onPop = this.onPopFrame.bind(this, frame, now, scriptInfo);
    },

    onPopFrame: function(frame, startTime, scriptInfo, completionValue)
    {
        this.endTime = this.now();

        // Compute total execution time for the script (frame).
        var elapsedTime = this.endTime - startTime;
        scriptInfo.totalExecutionTime += elapsedTime;

        var si = scriptInfo;

        // Update min execution time
        if (elapsedTime < si.minExecutionTime || typeof(si.minExecutionTime) == "undefined")
            si.minExecutionTime = elapsedTime;

        // Update max execution time
        if (elapsedTime > si.maxExecutionTime || typeof(si.maxExecutionTime) == "undefined")
            si.maxExecutionTime = elapsedTime;

        // Computing own-execution-time is a little more trickier.
        // 1) Younger frames are putting theirs total execution time to parent frames, where the
        // sum is computed. Consequently, the own execution time is computed as follows:
        // own-execution-time = total-execution-time - nested-execution-time;
        // 2) Frames with no nested calls will have: nested-execution-time == 0 and so,
        // own-execution-time == total-execution-time
        // 3) The own-execution-time computation is done in the end of the profiling session
        // when the consumer enumerates result scripts. See {@ProfilerEngine.enumerateScripts}.
        var olderScript = frame.older.script;
        if (!olderScript)
            return;

        var olderScriptInfo = this.scripts.get(olderScript);
        if (!olderScriptInfo)
        {
            TraceError.sysout("profilerEngine.onPopFrame; ERROR unknown older script!");
            return;
        }

        // Sum up nested (child) execution time.
        olderScriptInfo.totalNestedExecutionTime += elapsedTime;
    },

    now: function()
    {
        // Use performance.now() it's slower, but more precise
        // Don't forget that performance.now() is relative to navigationStart.
        var win = this.context.window;
        var now = win.performance.now();

        return win.performance.timing.navigationStart + now;
    },
};

// ********************************************************************************************* //
// Helper object for collecting results

function Results()
{
    this.arr = [];
    this.map = new Map();
}

Results.prototype =
{
    get: function(key)
    {
        return this.map.get(key);
    },

    set: function(key, value)
    {
        if (!this.map.has(key))
            this.arr.push(value);

        return this.map.set(key, value);
    },

    has: function(key)
    {
        return this.map.has(key);
    }
};

// ********************************************************************************************* //
// Registration

return ProfilerEngine;

// ********************************************************************************************* //
});
<commit_msg>Avoid NPE + tracing (related to issue 6496)<commit_after>/* See license.txt for terms of usage */

define([
    "firebug/lib/trace",
    "firebug/lib/url",
    "firebug/lib/string",
],
function(FBTrace, Url, Str) {

// ********************************************************************************************* //
// Constants

var Cc = Components.classes;
var Ci = Components.interfaces;
var Cu = Components.utils;

var Trace = FBTrace.to("DBG_PROFILER");
var TraceError = FBTrace.to("DBG_ERRORS");

// ********************************************************************************************* //
// Profiler engine based on JSD2 API

function ProfilerEngine(context)
{
    this.context = context
}

/**
 * @object Implements logic for collecting data about script execution. The object
 * collects the following information:
 * 1) Function call count
 * 2) Execution time (including and not including nested calls)
 * 3) Total execution time
 */
ProfilerEngine.prototype =
/** @lends ProfilerEngine */
{
    startProfiling: function()
    {
        // Collected profiling results are stored per 'script' in this structure.
        this.scripts = new Results();

        // Total profiling time (total executing time of the first executed frame).
        this.startTime = null;
        this.endTime = null;

        // Get debugger for profiled global (the current content window).
        this.dbg = this.getDebugger(this.context);

        // Hook function calls
        this.dbg.onEnterFrame = this.onEnterFrame.bind(this);
    },

    stopProfiling: function()
    {
        // Remove debugger hook.
        this.dbg.onEnterFrame = undefined;

        // Return total execution time.
        return this.endTime - this.startTime;
    },

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

    // xxxHonza: firebug/debugger/debuggerLib module should be used somehow
    getDebugger: function(context)
    {
        var jsDebugger = {};
        Cu.import("resource://gre/modules/jsdebugger.jsm", jsDebugger);

        var global = Cu.getGlobalForObject({});
        jsDebugger.addDebuggerToGlobal(global);

        return new global.Debugger(context.window);
    },

    enumerateScripts: function(callback)
    {
        for (var i=0; i<this.scripts.arr.length; i++)
        {
            var script = this.scripts.arr[i];

            // Compute own execution time (total nested execution time from nested frames
            // has been collected during the profiling session).
            script.totalOwnExecutionTime = script.totalExecutionTime -
                script.totalNestedExecutionTime;

            callback.enumerateScript(script);
        }
    },

    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
    // Handlers

    onEnterFrame: function(frame)
    {
        try
        {
            this.doEnterFrame(frame);
        }
        catch (e)
        {
            TraceError.sysout("profilerEngine.onEnterFrame; EXCEPTION", e);
        }
    },

    onPopFrame: function(frame, startTime, scriptInfo, completionValue)
    {
        try
        {
            this.doPopFrame(frame, startTime, scriptInfo, completionValue);
        }
        catch (e)
        {
            TraceError.sysout("profilerEngine.onPopFrame; EXCEPTION", e);
        }
    },

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

    doEnterFrame: function(frame)
    {
        var now = this.now();

        // Remember the first start time to compute the total profiling time later.
        if (!this.startTime)
            this.startTime = now;

        if (!frame.live)
        {
            TraceError.sysout("profilerEngine.onEnterFrame; ERROR frame not live!");
            return;
        }

        // Collected data are sorted per script, see the scriptInfo below.
        // There is one info structure per script object.
        var script = frame.script;
        if (!script)
        {
            TraceError.sysout("profilerEngine.onEnterFrame; ERROR null script!");
            return;
        }

        var scriptInfo = this.scripts.get(script);
        if (!scriptInfo)
        {
            var url = script.url;
            var name = frame.callee ? frame.callee.name : "anonymous";

            scriptInfo = {
                callCount: 0,
                startLine: script.startLine,
                url: url,
                fileName: Url.getFileName(url),
                funcName: name,
                totalExecutionTime: 0,
                minExecutionTime: undefined,
                maxExecutionTime: undefined,
                totalNestedExecutionTime: 0,
            };

            this.scripts.set(script, scriptInfo);
        }

        scriptInfo.callCount++;

        // Hook 'onPop' so we can also get the end execution time.
        frame.onPop = this.onPopFrame.bind(this, frame, now, scriptInfo);
    },

    doPopFrame: function(frame, startTime, scriptInfo, completionValue)
    {
        this.endTime = this.now();

        // Compute total execution time for the script (frame).
        var elapsedTime = this.endTime - startTime;
        scriptInfo.totalExecutionTime += elapsedTime;

        if (!frame.live)
        {
            TraceError.sysout("profilerEngine.onPopFrame; ERROR frame not live!");
            return;
        }

        var si = scriptInfo;

        // Update min execution time
        if (elapsedTime < si.minExecutionTime || typeof(si.minExecutionTime) == "undefined")
            si.minExecutionTime = elapsedTime;

        // Update max execution time
        if (elapsedTime > si.maxExecutionTime || typeof(si.maxExecutionTime) == "undefined")
            si.maxExecutionTime = elapsedTime;

        // Computing own-execution-time is a little more trickier.
        // 1) Younger frames are putting theirs total execution time to parent frames, where the
        // sum is computed. Consequently, the own execution time is computed as follows:
        // own-execution-time = total-execution-time - nested-execution-time;
        // 2) Frames with no nested calls will have: nested-execution-time == 0 and so,
        // own-execution-time == total-execution-time
        // 3) The own-execution-time computation is done in the end of the profiling session
        // when the consumer enumerates result scripts. See {@ProfilerEngine.enumerateScripts}.
        var olderScript = frame.older ? frame.older.script : null;
        if (!olderScript)
            return;

        var olderScriptInfo = this.scripts.get(olderScript);
        if (!olderScriptInfo)
        {
            TraceError.sysout("profilerEngine.onPopFrame; ERROR unknown older script!");
            return;
        }

        // Sum up nested (child) execution time.
        olderScriptInfo.totalNestedExecutionTime += elapsedTime;
    },

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

    now: function()
    {
        // Use performance.now() it's slower, but more precise
        // Don't forget that performance.now() is relative to navigationStart.
        var win = this.context.window;
        var now = win.performance.now();

        return win.performance.timing.navigationStart + now;
    },
};

// ********************************************************************************************* //
// Helper object for collecting results

function Results()
{
    this.arr = [];
    this.map = new Map();
}

Results.prototype =
{
    get: function(key)
    {
        return this.map.get(key);
    },

    set: function(key, value)
    {
        if (!this.map.has(key))
            this.arr.push(value);

        return this.map.set(key, value);
    },

    has: function(key)
    {
        return this.map.has(key);
    }
};

// ********************************************************************************************* //
// Registration

return ProfilerEngine;

// ********************************************************************************************* //
});
<|endoftext|>


<commit_before>/* See license.txt for terms of usage */

define([
    "firebug/lib/trace",
    "firebug/lib/options",
    "firebug/lib/locale",
    "firebug/firefox/browserOverlayLib",
],
function(FBTrace, Options, Locale, BrowserOverlayLib) {
with (BrowserOverlayLib) {

// ********************************************************************************************* //
// Constants

// ********************************************************************************************* //
// Firefox Toolbar Buttons

var BrowserToolbar =
{
    overlay: function(doc, version)
    {
        this.overlayToolbarButtons(doc, version);
        this.customizeToolbar(doc);
    },

    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
    // Firebug Start Button Popup Menu

    overlayToolbarButtons: function(doc, version)
    {
        $toolbarButton(doc, "firebug-inspectorButton", {
            label: "firebug.Inspect",
            tooltiptext: "firebug.InspectElement",
            observes: "cmd_firebug_toggleInspecting",
            // Needed for the 'Customize Toolbar' dialog
            style: "list-style-image: url(chrome://firebug/skin/inspect.png); " +
                "-moz-image-region: rect(0, 16px, 16px, 0);"
        });

        // Start Button Tooltip. As soon as Firebug is fully loaded, the tooltip content will be
        // generated by firebug/firefox/start-button/startButtonOverlay module.
        $menupopupOverlay(doc, $(doc, "mainPopupSet"), [
            $tooltip(doc, {
                "class": "firebugButtonTooltip",
                id: "firebug-buttonTooltip",
                orient: "vertical",
            }, [
                $label(doc, {
                    "class": "version",
                    "value": "Firebug " + version
                }),
                $label(doc, {
                    "class": "status",
                    "value": Locale.$STR("startbutton.tip.deactivated")
                })
            ])
        ]);

        $toolbarItem(doc, "firebug-badged-button", {},
            [
                $el(doc, "stack", {id: "firebug-error-badge"},
                    [
                        $el(doc, "label", {
                            id: "firebug-error-label",
                            value: 0,
                            tooltiptext: "3 errors"
                        })
                    ]
                ),
                // TODO: why contextmenu doesn't work without cloning
                $toolbarButton(doc, "firebug-button", {
                    label: "firebug.Firebug",
                    tooltip: "firebug-buttonTooltip",
                    type: "menu-button",
                    command: "cmd_firebug_toggleFirebug",
                    contextmenu: "fbStatusContextMenu",
                    observes: "firebugStatus",
                    // Needed for the 'Customize Toolbar' dialog
                    style: "list-style-image: url(chrome://firebug/skin/firebug16.png); " +
                        "-moz-image-region: rect(0, 16px, 16px, 0);"
                }, [$(doc, "fbStatusContextMenu").cloneNode(true)])
            ]
        );
    },

    customizeToolbar: function(doc)
    {
        // Appends Firebug start button into Firefox toolbar automatically after installation.
        // The button is appended only once - if the user removes it, it isn't appended again.
        // TODO: merge into $toolbarButton?
        // toolbarpalette check is for seamonkey, where it is in the document
        if ((!$(doc, "firebug-button") ||
            $(doc, "firebug-button").parentNode.tagName == "toolbarpalette")
            && !Options.get("toolbarCustomizationDone"))
        {
            Options.set("toolbarCustomizationDone", true);

            // Get the current navigation bar button set (a string of button IDs) and append
            // ID of the Firebug start button into it.
            var startButtonId = "firebug-button";
            var navBarId = "nav-bar";
            var navBar = $(doc, navBarId);
            var currentSet = navBar.currentSet;

            if (FBTrace.DBG_INITIALIZE)
                FBTrace.sysout("Startbutton; curSet (before modification): " + currentSet);

            // Append only if the button is not already there.
            var curSet = currentSet.split(",");
            if (curSet.indexOf(startButtonId) == -1)
            {
                navBar.insertItem(startButtonId);
                navBar.setAttribute("currentset", navBar.currentSet);
                navBar.ownerDocument.persist("nav-bar", "currentset");

                // Check whether insertItem really works
                var curSet = navBar.currentSet.split(",");
                if (curSet.indexOf(startButtonId) == -1)
                    FBTrace.sysout("Startbutton; navBar.insertItem doesn't work", curSet);

                if (FBTrace.DBG_INITIALIZE)
                {
                    FBTrace.sysout("Startbutton; curSet (after modification): " +
                        navBar.currentSet);
                }

                try
                {
                    // The current global scope is browser.xul.
                    BrowserToolboxCustomizeDone(true);
                }
                catch (e)
                {
                    if (FBTrace.DBG_ERRORS)
                        FBTrace.sysout("startButton; appendToToolbar EXCEPTION " + e, e);
                }
            }

            // Don't forget to show the navigation bar - just in case it's hidden.
            navBar.removeAttribute("collapsed");
            doc.persist(navBarId, "collapsed");
        }
    }
};

// ********************************************************************************************* //
// Registration

return BrowserToolbar;

// ********************************************************************************************* //
}});
<commit_msg>Issue 4001 (Part 3): Allowed clicking the error badge to jump to the Console panel<commit_after>/* See license.txt for terms of usage */

define([
    "firebug/lib/trace",
    "firebug/lib/options",
    "firebug/lib/locale",
    "firebug/firefox/browserOverlayLib",
],
function(FBTrace, Options, Locale, BrowserOverlayLib) {
with (BrowserOverlayLib) {

// ********************************************************************************************* //
// Constants

// ********************************************************************************************* //
// Firefox Toolbar Buttons

var BrowserToolbar =
{
    overlay: function(doc, version)
    {
        this.overlayToolbarButtons(doc, version);
        this.customizeToolbar(doc);
    },

    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
    // Firebug Start Button Popup Menu

    overlayToolbarButtons: function(doc, version)
    {
        $toolbarButton(doc, "firebug-inspectorButton", {
            label: "firebug.Inspect",
            tooltiptext: "firebug.InspectElement",
            observes: "cmd_firebug_toggleInspecting",
            // Needed for the 'Customize Toolbar' dialog
            style: "list-style-image: url(chrome://firebug/skin/inspect.png); " +
                "-moz-image-region: rect(0, 16px, 16px, 0);"
        });

        // Start Button Tooltip. As soon as Firebug is fully loaded, the tooltip content will be
        // generated by firebug/firefox/start-button/startButtonOverlay module.
        $menupopupOverlay(doc, $(doc, "mainPopupSet"), [
            $tooltip(doc, {
                "class": "firebugButtonTooltip",
                id: "firebug-buttonTooltip",
                orient: "vertical",
            }, [
                $label(doc, {
                    "class": "version",
                    "value": "Firebug " + version
                }),
                $label(doc, {
                    "class": "status",
                    "value": Locale.$STR("startbutton.tip.deactivated")
                })
            ])
        ]);

        $toolbarItem(doc, "firebug-badged-button", {},
            [
                $el(doc, "stack",{
                        id: "firebug-error-badge",
                        onclick: "Firebug.toggleBar(true, 'console');"
                    }, [
                        $el(doc, "label", {
                            id: "firebug-error-label",
                            value: 0,
                            tooltiptext: "3 errors"
                        })
                    ]
                ),
                // TODO: why contextmenu doesn't work without cloning
                $toolbarButton(doc, "firebug-button", {
                    label: "firebug.Firebug",
                    tooltip: "firebug-buttonTooltip",
                    type: "menu-button",
                    command: "cmd_firebug_toggleFirebug",
                    contextmenu: "fbStatusContextMenu",
                    observes: "firebugStatus",
                    // Needed for the 'Customize Toolbar' dialog
                    style: "list-style-image: url(chrome://firebug/skin/firebug16.png); " +
                        "-moz-image-region: rect(0, 16px, 16px, 0);"
                }, [$(doc, "fbStatusContextMenu").cloneNode(true)])
            ]
        );
    },

    customizeToolbar: function(doc)
    {
        // Appends Firebug start button into Firefox toolbar automatically after installation.
        // The button is appended only once - if the user removes it, it isn't appended again.
        // TODO: merge into $toolbarButton?
        // toolbarpalette check is for seamonkey, where it is in the document
        if ((!$(doc, "firebug-button") ||
            $(doc, "firebug-button").parentNode.tagName == "toolbarpalette")
            && !Options.get("toolbarCustomizationDone"))
        {
            Options.set("toolbarCustomizationDone", true);

            // Get the current navigation bar button set (a string of button IDs) and append
            // ID of the Firebug start button into it.
            var startButtonId = "firebug-button";
            var navBarId = "nav-bar";
            var navBar = $(doc, navBarId);
            var currentSet = navBar.currentSet;

            if (FBTrace.DBG_INITIALIZE)
                FBTrace.sysout("Startbutton; curSet (before modification): " + currentSet);

            // Append only if the button is not already there.
            var curSet = currentSet.split(",");
            if (curSet.indexOf(startButtonId) == -1)
            {
                navBar.insertItem(startButtonId);
                navBar.setAttribute("currentset", navBar.currentSet);
                navBar.ownerDocument.persist("nav-bar", "currentset");

                // Check whether insertItem really works
                var curSet = navBar.currentSet.split(",");
                if (curSet.indexOf(startButtonId) == -1)
                    FBTrace.sysout("Startbutton; navBar.insertItem doesn't work", curSet);

                if (FBTrace.DBG_INITIALIZE)
                {
                    FBTrace.sysout("Startbutton; curSet (after modification): " +
                        navBar.currentSet);
                }

                try
                {
                    // The current global scope is browser.xul.
                    BrowserToolboxCustomizeDone(true);
                }
                catch (e)
                {
                    if (FBTrace.DBG_ERRORS)
                        FBTrace.sysout("startButton; appendToToolbar EXCEPTION " + e, e);
                }
            }

            // Don't forget to show the navigation bar - just in case it's hidden.
            navBar.removeAttribute("collapsed");
            doc.persist(navBarId, "collapsed");
        }
    }
};

// ********************************************************************************************* //
// Registration

return BrowserToolbar;

// ********************************************************************************************* //
}});
<|endoftext|>


<commit_before>/**
  *  gollum.dialog.js
  *
  *  Used for dialogs. Duh.
  *
  */

(function($) {

  var Dialog = {

    debugOn: false,
    markupCreated: false,
    markup: '',

    attachEvents: function( evtOK ) {
      $('#gollum-dialog-action-ok').click(function( e ) {
        Dialog.eventOK( e, evtOK );
      });
      $('#gollum-dialog-action-cancel').click( Dialog.eventCancel );
      $('#gollum-dialog-dialog input[type="text"]').keydown(function( e ) {
        if ( e.keyCode == 13 ) {
          Dialog.eventOK( e, evtOK );
        }
      });
    },

    detachEvents: function() {
      $('#gollum-dialog-action-ok').unbind('click');
      $('#gollum-dialog-action-cancel').unbind('click');
    },

    createFieldMarkup: function( fieldArray ) {
      var fieldMarkup = '<fieldset>';
      for ( var i=0; i < fieldArray.length; i++ ) {
        if ( typeof fieldArray[i] == 'object' ) {
          fieldMarkup += '
';
          switch ( fieldArray[i].type ) {

          case 'text':
            fieldMarkup += Dialog.createFieldText( fieldArray[i] );
            break;

          case 'file':
            fieldMarkup += Dialog.createFieldFile( fieldArray[i] );
            break;

          default:
            break;

          }
          fieldMarkup += '
';
        }

      }
      fieldMarkup += '</fieldset>';
      return fieldMarkup;
    },

    createFieldText: function( fieldAttributes ) {
      var html = '';

      if ( fieldAttributes.name ) {
        html += '' + fieldAttributes.name + '';
      }

      html += '<input type="text"';

      if ( fieldAttributes.id ) {
        html += ' name="' + fieldAttributes.id + '"'
        if ( fieldAttributes.type == 'code' ) {
          html+= ' class="code"';
        }
        if ( fieldAttributes.defaultValue ) {
          html+= ' value="' + fieldAttributes.defaultValue.split('"').join('"') + '"';
        }
        html += ' id="gollum-dialog-dialog-generated-field-' +
          fieldAttributes.id + '">';
      }

      if( fieldAttributes.context ){
        html += '' + fieldAttributes.context + '';
      }

      return html;
    },

    createFieldFile: function( fieldAttributes ) {
      // Not actually a field, but an embedded form.
      var html = '';

      var id = fieldAttributes.id || 'upload';
      var name = fieldAttributes.name || 'file';
      var action = fieldAttributes.action || 'uploadFile';

      html += '<form method=post enctype="multipart/form-data" ' +
        'action="' + action + '" ' + 'id="' + id + '">';
      html += '<input type=file name="' + name + '">';
      html += '</form>';

      return html;
    },

    createMarkup: function( title, body ) {
      Dialog.markupCreated = true;
      if ($.facebox) {
        return '
' +
               '

' +
               title +'

' +
               '
' + body + '
' +
               '
' +
               'Cancel' +
               'OK' +
               '
' +
               '
';
      } else {
        return '
' +
               '
' +
               '
' +
               '

' +
               title +'

' +
               '
' + body + '
' +
               '
' +
               'Cancel' +
               'OK' +
               '
' +
               '
' +
               '
' +
               '
';
      }
    },

    eventCancel: function( e ) {
      e.preventDefault();
      debug('Cancelled dialog.');
      Dialog.hide();
    },

    eventOK: function( e, evtOK ) {
      e.preventDefault();

      var results = [];
      // get the results from each field and build them into the object
      $('#gollum-dialog-dialog-body input').each(function() {
        results[$(this).attr('name')] = $(this).val();
      });

      // pass them to evtOK if it exists (which it should)
      if ( evtOK &&
           typeof evtOK == 'function' ) {
        evtOK( results );
      }
      Dialog.hide();
    },

    hide: function() {
      if ( $.facebox ) {
        Dialog.markupCreated = false;
        $(document).trigger('close.facebox');
        Dialog.detachEvents();
      } else {
        if ( $.browser.msie ) {
          $('#gollum-dialog-dialog').hide().removeClass('active');
          $('select').css('visibility', 'visible');
        } else {
          $('#gollum-dialog-dialog').animate({ opacity: 0 }, {
            duration: 200,
            complete: function() {
              $('#gollum-dialog-dialog').removeClass('active');
            }
          });
        }
      }
    },

    init: function( argObject ) {
      var title = '';
      var body = '';

      // bail out if necessary
      if ( !argObject ||
           typeof argObject != 'object' ) {
        debug('Editor Dialog: Cannot init; invalid init object');
        return;
      }

      if ( argObject.body && typeof argObject.body == 'string' ) {
        body = '
' + argObject.body + '
';
      }

      // alright, build out fields
      if ( argObject.fields && typeof argObject.fields == 'object' ) {
        body += Dialog.createFieldMarkup( argObject.fields );
      }

      if ( argObject.title && typeof argObject.title == 'string' ) {
        title = argObject.title;
      }

      if ( Dialog.markupCreated ) {
        if ($.facebox) {
          $(document).trigger('close.facebox');
        } else {
          $('#gollum-dialog-dialog').remove();
        }
      }

      Dialog.markup = Dialog.createMarkup( title, body );

      if ($.facebox) {
        $(document).bind('reveal.facebox', function() {
          if ( argObject.OK &&
               typeof argObject.OK == 'function' ) {
            Dialog.attachEvents( argObject.OK );
            $($('#facebox input[type="text"]').get(0)).focus();
          }
        });
      } else {
        $('body').append( Dialog.markup );
        if ( argObject.OK &&
             typeof argObject.OK == 'function' ) {
          Dialog.attachEvents( argObject.OK );
        }
      }

      Dialog.show();
    },

    show: function() {
      if ( !Dialog.markupCreated ) {
        debug('Dialog: No markup to show. Please use init first.');
      } else {
        debug('Showing dialog');
        if ($.facebox) {
          $.facebox( Dialog.markup );
        } else {
          if ( $.browser.msie ) {
            $('#gollum-dialog.dialog').addClass('active');
            Dialog.position();
            $('select').css('visibility', 'hidden');
          } else {
            $('#gollum-dialog.dialog').css('display', 'none');
            $('#gollum-dialog-dialog').animate({ opacity: 0 }, {
              duration: 0,
              complete: function() {
                $('#gollum-dialog-dialog').css('display', 'block');
                Dialog.position(); // position this thing
                $('#gollum-dialog-dialog').animate({ opacity: 1 }, {
                duration: 500
                });
                $($('#gollum-dialog-dialog input[type="text"]').get(0)).focus();
              }
            });
          }
        }
      }
    },

    position: function() {
      var dialogHeight = $('#gollum-dialog-dialog-inner').height();
      $('#gollum-dialog-dialog-inner')
        .css('height', dialogHeight + 'px')
        .css('margin-top', -1 * parseInt( dialogHeight / 2 ));
    }
  };

  if ($.facebox) {
    $(document).bind('reveal.facebox', function() {
      $('#facebox img.close_image').remove();
    });
  }

  var debug = function(m) {
    if ( Dialog.debugOn
         && typeof console != 'undefined' ) {
      console.log( m );
    }
  };

  $.GollumDialog = Dialog;

})(jQuery);
<commit_msg>Use correct path for uploadFile action even when looking at a page in a folder<commit_after>/**
  *  gollum.dialog.js
  *
  *  Used for dialogs. Duh.
  *
  */

(function($) {

  var Dialog = {

    debugOn: false,
    markupCreated: false,
    markup: '',

    attachEvents: function( evtOK ) {
      $('#gollum-dialog-action-ok').click(function( e ) {
        Dialog.eventOK( e, evtOK );
      });
      $('#gollum-dialog-action-cancel').click( Dialog.eventCancel );
      $('#gollum-dialog-dialog input[type="text"]').keydown(function( e ) {
        if ( e.keyCode == 13 ) {
          Dialog.eventOK( e, evtOK );
        }
      });
    },

    detachEvents: function() {
      $('#gollum-dialog-action-ok').unbind('click');
      $('#gollum-dialog-action-cancel').unbind('click');
    },

    createFieldMarkup: function( fieldArray ) {
      var fieldMarkup = '<fieldset>';
      for ( var i=0; i < fieldArray.length; i++ ) {
        if ( typeof fieldArray[i] == 'object' ) {
          fieldMarkup += '
';
          switch ( fieldArray[i].type ) {

          case 'text':
            fieldMarkup += Dialog.createFieldText( fieldArray[i] );
            break;

          case 'file':
            fieldMarkup += Dialog.createFieldFile( fieldArray[i] );
            break;

          default:
            break;

          }
          fieldMarkup += '
';
        }

      }
      fieldMarkup += '</fieldset>';
      return fieldMarkup;
    },

    createFieldText: function( fieldAttributes ) {
      var html = '';

      if ( fieldAttributes.name ) {
        html += '' + fieldAttributes.name + '';
      }

      html += '<input type="text"';

      if ( fieldAttributes.id ) {
        html += ' name="' + fieldAttributes.id + '"'
        if ( fieldAttributes.type == 'code' ) {
          html+= ' class="code"';
        }
        if ( fieldAttributes.defaultValue ) {
          html+= ' value="' + fieldAttributes.defaultValue.split('"').join('"') + '"';
        }
        html += ' id="gollum-dialog-dialog-generated-field-' +
          fieldAttributes.id + '">';
      }

      if( fieldAttributes.context ){
        html += '' + fieldAttributes.context + '';
      }

      return html;
    },

    createFieldFile: function( fieldAttributes ) {
      // Not actually a field, but an embedded form.
      var html = '';

      var id = fieldAttributes.id || 'upload';
      var name = fieldAttributes.name || 'file';
      var action = fieldAttributes.action || '/uploadFile';

      html += '<form method=post enctype="multipart/form-data" ' +
        'action="' + action + '" ' + 'id="' + id + '">';
      html += '<input type=file name="' + name + '">';
      html += '</form>';

      return html;
    },

    createMarkup: function( title, body ) {
      Dialog.markupCreated = true;
      if ($.facebox) {
        return '
' +
               '

' +
               title +'

' +
               '
' + body + '
' +
               '
' +
               'Cancel' +
               'OK' +
               '
' +
               '
';
      } else {
        return '
' +
               '
' +
               '
' +
               '

' +
               title +'

' +
               '
' + body + '
' +
               '
' +
               'Cancel' +
               'OK' +
               '
' +
               '
' +
               '
' +
               '
';
      }
    },

    eventCancel: function( e ) {
      e.preventDefault();
      debug('Cancelled dialog.');
      Dialog.hide();
    },

    eventOK: function( e, evtOK ) {
      e.preventDefault();

      var results = [];
      // get the results from each field and build them into the object
      $('#gollum-dialog-dialog-body input').each(function() {
        results[$(this).attr('name')] = $(this).val();
      });

      // pass them to evtOK if it exists (which it should)
      if ( evtOK &&
           typeof evtOK == 'function' ) {
        evtOK( results );
      }
      Dialog.hide();
    },

    hide: function() {
      if ( $.facebox ) {
        Dialog.markupCreated = false;
        $(document).trigger('close.facebox');
        Dialog.detachEvents();
      } else {
        if ( $.browser.msie ) {
          $('#gollum-dialog-dialog').hide().removeClass('active');
          $('select').css('visibility', 'visible');
        } else {
          $('#gollum-dialog-dialog').animate({ opacity: 0 }, {
            duration: 200,
            complete: function() {
              $('#gollum-dialog-dialog').removeClass('active');
            }
          });
        }
      }
    },

    init: function( argObject ) {
      var title = '';
      var body = '';

      // bail out if necessary
      if ( !argObject ||
           typeof argObject != 'object' ) {
        debug('Editor Dialog: Cannot init; invalid init object');
        return;
      }

      if ( argObject.body && typeof argObject.body == 'string' ) {
        body = '
' + argObject.body + '
';
      }

      // alright, build out fields
      if ( argObject.fields && typeof argObject.fields == 'object' ) {
        body += Dialog.createFieldMarkup( argObject.fields );
      }

      if ( argObject.title && typeof argObject.title == 'string' ) {
        title = argObject.title;
      }

      if ( Dialog.markupCreated ) {
        if ($.facebox) {
          $(document).trigger('close.facebox');
        } else {
          $('#gollum-dialog-dialog').remove();
        }
      }

      Dialog.markup = Dialog.createMarkup( title, body );

      if ($.facebox) {
        $(document).bind('reveal.facebox', function() {
          if ( argObject.OK &&
               typeof argObject.OK == 'function' ) {
            Dialog.attachEvents( argObject.OK );
            $($('#facebox input[type="text"]').get(0)).focus();
          }
        });
      } else {
        $('body').append( Dialog.markup );
        if ( argObject.OK &&
             typeof argObject.OK == 'function' ) {
          Dialog.attachEvents( argObject.OK );
        }
      }

      Dialog.show();
    },

    show: function() {
      if ( !Dialog.markupCreated ) {
        debug('Dialog: No markup to show. Please use init first.');
      } else {
        debug('Showing dialog');
        if ($.facebox) {
          $.facebox( Dialog.markup );
        } else {
          if ( $.browser.msie ) {
            $('#gollum-dialog.dialog').addClass('active');
            Dialog.position();
            $('select').css('visibility', 'hidden');
          } else {
            $('#gollum-dialog.dialog').css('display', 'none');
            $('#gollum-dialog-dialog').animate({ opacity: 0 }, {
              duration: 0,
              complete: function() {
                $('#gollum-dialog-dialog').css('display', 'block');
                Dialog.position(); // position this thing
                $('#gollum-dialog-dialog').animate({ opacity: 1 }, {
                duration: 500
                });
                $($('#gollum-dialog-dialog input[type="text"]').get(0)).focus();
              }
            });
          }
        }
      }
    },

    position: function() {
      var dialogHeight = $('#gollum-dialog-dialog-inner').height();
      $('#gollum-dialog-dialog-inner')
        .css('height', dialogHeight + 'px')
        .css('margin-top', -1 * parseInt( dialogHeight / 2 ));
    }
  };

  if ($.facebox) {
    $(document).bind('reveal.facebox', function() {
      $('#facebox img.close_image').remove();
    });
  }

  var debug = function(m) {
    if ( Dialog.debugOn
         && typeof console != 'undefined' ) {
      console.log( m );
    }
  };

  $.GollumDialog = Dialog;

})(jQuery);
<|endoftext|>


<commit_before>'use strict';

/**
 * Module dependencies.
 */
var _ = require('lodash'),
	mongoose = require('mongoose'),
	User = mongoose.model('User');

/**
 * User middleware
 */
exports.userByID = function(req, res, next, id) {
	User.findOne({
		_id: id
	}).exec(function(err, user) {
		if (err) return next(err);
		if (!user) return next(new Error('Failed to load User ' + id));
		req.profile = user;
		next();
	});
};

/**
 * Require login routing middleware
 */
exports.requiresLogin = function(req, res, next) {
	if (!req.isAuthenticated()) {
		return res.status(401).send({
			message: 'User is not logged in'
		});
	}

	next();
};

/**
 * User authorizations routing middleware
 */
exports.hasAuthorization = function(roles) {
	var _this = this;

	return function(req, res, next) {
		_this.requiresLogin(req, res, function() {
			if (_.intersection(req.user.roles, roles).length) {
				return next();
			} else {
				return res.status(403).send({
					message: 'User is not authorized'
				});
			}
		});
	};
};<commit_msg>Removed unnecessary authentication II<commit_after>'use strict';

/**
 * Module dependencies.
 */
var _ = require('lodash'),
	mongoose = require('mongoose'),
	User = mongoose.model('User');

/**
 * User middleware
 */
exports.userByID = function(req, res, next, id) {
	User.findOne({
		_id: id
	}).exec(function(err, user) {
		if (err) return next(err);
		if (!user) return next(new Error('Failed to load User ' + id));
		req.profile = user;
		next();
	});
};

/**
 * Require login routing middleware
 */
exports.requiresLogin = function(req, res, next) {
	/**
	if (!req.isAuthenticated()) {
		return res.status(401).send({
			message: 'User is not logged in'
		});
	}
	*/

	next();
};

/**
 * User authorizations routing middleware
 */
exports.hasAuthorization = function(roles) {
	var _this = this;

	return function(req, res, next) {
		_this.requiresLogin(req, res, function() {
			if (_.intersection(req.user.roles, roles).length) {
				return next();
			} else {
				return res.status(403).send({
					message: 'User is not authorized'
				});
			}
		});
	};
};<|endoftext|>


<commit_before>const smash = require("../../../../smash.js");
const logger = smash.logger("EventType");
const errorUtil = new smash.SmashError(logger);

class EventType {
    constructor(route, callback) {
        if(arguments.length > 2) {
            throw new Error("Too much parameters. EventType() must only have 2 parameters at most, has : " + errorUtil.typeOf(arguments.length));
        }
        if(arguments.length < 1) {
if (arguments.length < 1 || arguments.length > 2) {
            throw new Error("EventType(optionalRoute, callback) could have 1 or 2 parameters, has : " + arguments.length + " parameter(s)");
        }
        }
        if(arguments.length === 1) {
        this._task = null;
            if (typeof arguments[0] !== 'function') {
                throw new Error("First parameter of EventType() must be a function, " + errorUtil.typeOf(arguments[0]));
            }
            if (arguments[0].length !== 1) {
                throw new Error("First parameter of EventType() must be a function witch takes 1 parameter: Event, " + arguments[0].length + " given");
            }
            this._callback = arguments[0];
        }
        if(arguments.length === 2) {
            if (typeof route !== 'object') {
                throw new Error("First parameter of EventType() must be an object, " + errorUtil.typeOf(route));
            }
            if (typeof route.task !== 'string') {
                throw new Error("First parameter of EventType() must have a string property called type, " + errorUtil.typeOf(route.task));
            }
            this._task = route.task;

            if (typeof callback !== 'function') {
                throw new Error("Second parameter of EventType() must be a function, " + errorUtil.typeOf(callback));
            }
            if (callback.length !== 1) {
                throw new Error("Second parameter of EventType() must be a function witch takes 1 parameter: Event, " + callback.length + " given");
            }
            this._callback = callback;
        }
    }

    get callback() {
        return this._callback;
    }

    get task() {
        return this._task;
    }

    match(event) {
        if(this.task) {
            if(event["CodePipeline.job"].data.actionConfiguration.configuration.UserParameters != undefined) {
                return this._task === event["CodePipeline.job"].data.actionConfiguration.configuration.UserParameters;
            } else {
                return false;
            }
        } else {
            if (event["CodePipeline.job"].data.actionConfiguration.configuration.UserParameters != undefined) {
                return false;
            } else {
                return true;
            }
if (event["CodePipeline.job"].data.actionConfiguration.configuration.UserParameters) {
            return this.task === event["CodePipeline.job"].data.actionConfiguration.configuration.UserParameters;
        } else if (this.task === null) {
            return true;
        }
        return false;
    }
}

module.exports = EventType;
<commit_msg>Update lib/middleware/codePipelineJobEvent/lib/eventType.js<commit_after>const smash = require("../../../../smash.js");
const logger = smash.logger("EventType");
const errorUtil = new smash.SmashError(logger);

class EventType {
    constructor(route, callback) {
        if(arguments.length > 2) {
            throw new Error("Too much parameters. EventType() must only have 2 parameters at most, has : " + errorUtil.typeOf(arguments.length));
        }
        if(arguments.length < 1) {
if (arguments.length < 1 || arguments.length > 2) {
            throw new Error("EventType(optionalRoute, callback) could have 1 or 2 parameters, has : " + arguments.length + " parameter(s)");
        }
        }
        if(arguments.length === 1) {
        this._task = null;
            if (typeof arguments[0] !== 'function') {
                throw new Error("First parameter of EventType() must be a function, " + errorUtil.typeOf(arguments[0]));
            }
            if (arguments[0].length !== 1) {
                throw new Error("First parameter of EventType() must be a function witch takes 1 parameter: Event, " + arguments[0].length + " given");
            }
            this._callback = arguments[0];
        }
        } else  {
            if (typeof route !== 'object') {
                throw new Error("First parameter of EventType() must be an object, " + errorUtil.typeOf(route));
            }
            if (typeof route.task !== 'string') {
                throw new Error("First parameter of EventType() must have a string property called type, " + errorUtil.typeOf(route.task));
            }
            this._task = route.task;

            if (typeof callback !== 'function') {
                throw new Error("Second parameter of EventType() must be a function, " + errorUtil.typeOf(callback));
            }
            if (callback.length !== 1) {
                throw new Error("Second parameter of EventType() must be a function witch takes 1 parameter: Event, " + callback.length + " given");
            }
            this._callback = callback;
        }
    }

    get callback() {
        return this._callback;
    }

    get task() {
        return this._task;
    }

    match(event) {
        if(this.task) {
            if(event["CodePipeline.job"].data.actionConfiguration.configuration.UserParameters != undefined) {
                return this._task === event["CodePipeline.job"].data.actionConfiguration.configuration.UserParameters;
            } else {
                return false;
            }
        } else {
            if (event["CodePipeline.job"].data.actionConfiguration.configuration.UserParameters != undefined) {
                return false;
            } else {
                return true;
            }
if (event["CodePipeline.job"].data.actionConfiguration.configuration.UserParameters) {
            return this.task === event["CodePipeline.job"].data.actionConfiguration.configuration.UserParameters;
        } else if (this.task === null) {
            return true;
        }
        return false;
    }
}

module.exports = EventType;
<|endoftext|>