<commit_before>/**
 * @file Molecular Surface Representation
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */

import { RepresentationRegistry } from '../globals'
import { defaults } from '../utils'
import StructureRepresentation from './structure-representation.js'
import MolecularSurface from '../surface/molecular-surface.js'
import SurfaceBuffer from '../buffer/surface-buffer.js'
import ContourBuffer from '../buffer/contour-buffer.js'
import DoubleSidedBuffer from '../buffer/doublesided-buffer'
import Selection from '../selection/selection.js'

/**
 * Molecular Surface Representation
 */
class MolecularSurfaceRepresentation extends StructureRepresentation {
  constructor (structure, viewer, params) {
    super(structure, viewer, params)

    this.type = 'surface'

    this.parameters = Object.assign({

      surfaceType: {
        type: 'select',
        rebuild: true,
        options: {
          'vws': 'vws',
          'sas': 'sas',
          'ms': 'ms',
          'ses': 'ses',
          'av': 'av'
        }
      },
      probeRadius: {
        type: 'number',
        precision: 1,
        max: 20,
        min: 0,
        rebuild: true
      },
      smooth: {
        type: 'integer',
        precision: 1,
        max: 10,
        min: 0,
        rebuild: true
      },
      scaleFactor: {
        type: 'number',
        precision: 1,
        max: 5,
        min: 0,
        rebuild: true
      },
      cutoff: {
        type: 'number',
        precision: 2,
        max: 50,
        min: 0,
        rebuild: true
      },
      contour: {
        type: 'boolean', rebuild: true
      },
      background: {
        type: 'boolean', rebuild: true  // FIXME
      },
      opaqueBack: {
        type: 'boolean', buffer: true
      },
      filterSele: {
        type: 'text', rebuild: true
      },
      colorVolume: {
        type: 'hidden'
      },
      useWorker: {
        type: 'boolean', rebuild: true
      }

    }, this.parameters, {

      radiusType: null,
      radius: null,
      scale: null

    })

    this.__infoList = []

    // TODO find a more direct way
    this.structure.signals.refreshed.add(function () {
      this.__forceNewMolsurf = true
    }, this)

    this.init(params)
  }

  init (params) {
    const p = params || {}
    p.colorScheme = defaults(p.colorScheme, 'uniform')
    p.colorValue = defaults(p.colorValue, 0xDDDDDD)
    p.disablePicking = defaults(p.disablePicking, true)

    this.surfaceType = defaults(p.surfaceType, 'ms')
    this.probeRadius = defaults(p.probeRadius, 1.4)
    this.smooth = defaults(p.smooth, 2)
    this.scaleFactor = defaults(p.scaleFactor, 2.0)
    this.cutoff = defaults(p.cutoff, 0.0)
    this.contour = defaults(p.contour, false)
    this.background = defaults(p.background, false)
    this.opaqueBack = defaults(p.opaqueBack, true)
    this.filterSele = defaults(p.filterSele, '')
    this.colorVolume = defaults(p.colorVolume, undefined)
    this.useWorker = defaults(p.useWorker, true)

    super.init(params)
  }

  prepareData (sview, i, callback) {
    let info = this.__infoList[ i ]
    if (!info) {
      info = {}
      this.__infoList[ i ] = info
    }

    if (!info.molsurf || info.sele !== sview.selection.string) {
      if (this.filterSele) {
        const sviewFilter = sview.structure.getView(new Selection(this.filterSele))
        const bbSize = sviewFilter.boundingBox.getSize()
        const maxDim = Math.max(bbSize.x, bbSize.y, bbSize.z)
        const asWithin = sview.getAtomSetWithinPoint(sviewFilter.center, (maxDim / 2) + 6.0)
        sview = sview.getView(
          new Selection(sview.getAtomSetWithinSelection(asWithin, 3).toSeleString())
        )
      }

      info.sele = sview.selection.string
      info.molsurf = new MolecularSurface(sview)

      const p = this.getSurfaceParams()
      const onSurfaceFinish = function (surface) {
        info.surface = surface
        callback(i)
      }

      if (this.useWorker) {
        info.molsurf.getSurfaceWorker(p, onSurfaceFinish)
      } else {
        onSurfaceFinish(info.molsurf.getSurface(p))
      }
    } else {
      callback(i)
    }
  }

  prepare (callback) {
    if (this.__forceNewMolsurf || this.__sele !== this.selection.string ||
          this.__surfaceParams !== JSON.stringify(this.getSurfaceParams())) {
      this.__infoList.forEach(info => {
        info.molsurf.dispose()
      })
      this.__infoList.length = 0
    }

    if (this.structureView.atomCount === 0) {
      callback()
      return
    }

    const after = function () {
      this.__sele = this.selection.string
      this.__surfaceParams = JSON.stringify(this.getSurfaceParams())
      this.__forceNewMolsurf = false
      callback()
    }.bind(this)

    const name = this.assembly === 'default' ? this.defaultAssembly : this.assembly
    const assembly = this.structure.biomolDict[ name ]

    if (assembly) {
      assembly.partList.forEach((part, i) => {
        const sview = part.getView(this.structureView)
        this.prepareData(sview, i, (_i) => {
          if (_i === assembly.partList.length - 1) after()
        })
      })
    } else {
      this.prepareData(this.structureView, 0, after)
    }
  }

  createData (sview, i) {
    const info = this.__infoList[ i ]
    const surface = info.surface

    const surfaceData = {
      position: surface.getPosition(),
      color: surface.getColor(this.getColorParams()),
      index: surface.getFilteredIndex(this.filterSele, sview)
    }

    const bufferList = []

    if (surface.contour) {
      const contourBuffer = new ContourBuffer(
        surfaceData,
        this.getBufferParams({
          wireframe: false
        })
      )

      bufferList.push(contourBuffer)
    } else {
      surfaceData.normal = surface.getNormal()
      surfaceData.picking = surface.getPicking(sview.getStructure())

      const surfaceBuffer = new SurfaceBuffer(
        surfaceData,
        this.getBufferParams({
          background: this.background,
          opaqueBack: this.opaqueBack,
          dullInterior: false
        })
      )

      const doubleSidedBuffer = new DoubleSidedBuffer(surfaceBuffer)

      bufferList.push(doubleSidedBuffer)
    }

    return { bufferList, info }
  }

  updateData (what, data) {
    const surfaceData = {}

    if (what.position) {
      this.__forceNewMolsurf = true
      this.build()
      return
    }

    if (what.color) {
      surfaceData.color = data.info.surface.getColor(this.getColorParams())
    }

    if (what.index) {
      surfaceData.index = data.info.surface.getFilteredIndex(this.filterSele, data.sview)
    }

    data.bufferList[ 0 ].setAttributes(surfaceData)
  }

  setParameters (params, what, rebuild) {
    what = what || {}

    if (params && params.filterSele) {
      what.index = true
    }

    if (params && params.colorVolume !== undefined) {
      what.color = true
    }

    // forbid setting wireframe to true when contour is true
    if (params && params.wireframe && (
          params.contour || (params.contour === undefined && this.contour)
        )
    ) {
      params.wireframe = false
    }

    super.setParameters(params, what, rebuild)

    return this
  }

  getSurfaceParams (params) {
    const p = Object.assign({
      type: this.surfaceType,
      probeRadius: this.probeRadius,
      scaleFactor: this.scaleFactor,
      smooth: this.smooth && !this.contour,
      cutoff: this.cutoff,
      contour: this.contour,
      useWorker: this.useWorker
    }, params)

    return p
  }

  getColorParams () {
    const p = super.getColorParams()

    p.volume = this.colorVolume

    return p
  }

  clear () {
    super.clear()
  }

  dispose () {
    this.__infoList.forEach(info => {
      info.molsurf.dispose()
    })
    this.__infoList.length = 0

    super.dispose()
  }
}

RepresentationRegistry.add('surface', MolecularSurfaceRepresentation)

export default MolecularSurfaceRepresentation
<commit_msg>fix getAtomRadius for molsurf repr<commit_after>/**
 * @file Molecular Surface Representation
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */

import { RepresentationRegistry } from '../globals'
import { defaults } from '../utils'
import StructureRepresentation from './structure-representation.js'
import MolecularSurface from '../surface/molecular-surface.js'
import SurfaceBuffer from '../buffer/surface-buffer.js'
import ContourBuffer from '../buffer/contour-buffer.js'
import DoubleSidedBuffer from '../buffer/doublesided-buffer'
import Selection from '../selection/selection.js'

/**
 * Molecular Surface Representation
 */
class MolecularSurfaceRepresentation extends StructureRepresentation {
  constructor (structure, viewer, params) {
    super(structure, viewer, params)

    this.type = 'surface'

    this.parameters = Object.assign({

      surfaceType: {
        type: 'select',
        rebuild: true,
        options: {
          'vws': 'vws',
          'sas': 'sas',
          'ms': 'ms',
          'ses': 'ses',
          'av': 'av'
        }
      },
      probeRadius: {
        type: 'number',
        precision: 1,
        max: 20,
        min: 0,
        rebuild: true
      },
      smooth: {
        type: 'integer',
        precision: 1,
        max: 10,
        min: 0,
        rebuild: true
      },
      scaleFactor: {
        type: 'number',
        precision: 1,
        max: 5,
        min: 0,
        rebuild: true
      },
      cutoff: {
        type: 'number',
        precision: 2,
        max: 50,
        min: 0,
        rebuild: true
      },
      contour: {
        type: 'boolean', rebuild: true
      },
      background: {
        type: 'boolean', rebuild: true  // FIXME
      },
      opaqueBack: {
        type: 'boolean', buffer: true
      },
      filterSele: {
        type: 'text', rebuild: true
      },
      colorVolume: {
        type: 'hidden'
      },
      useWorker: {
        type: 'boolean', rebuild: true
      }

    }, this.parameters, {

      radiusType: null,
      radius: null,
      scale: null

    })

    this.__infoList = []

    // TODO find a more direct way
    this.structure.signals.refreshed.add(function () {
      this.__forceNewMolsurf = true
    }, this)

    this.init(params)
  }

  init (params) {
    const p = params || {}
    p.colorScheme = defaults(p.colorScheme, 'uniform')
    p.colorValue = defaults(p.colorValue, 0xDDDDDD)
    p.disablePicking = defaults(p.disablePicking, true)

    this.surfaceType = defaults(p.surfaceType, 'ms')
    this.probeRadius = defaults(p.probeRadius, 1.4)
    this.smooth = defaults(p.smooth, 2)
    this.scaleFactor = defaults(p.scaleFactor, 2.0)
    this.cutoff = defaults(p.cutoff, 0.0)
    this.contour = defaults(p.contour, false)
    this.background = defaults(p.background, false)
    this.opaqueBack = defaults(p.opaqueBack, true)
    this.filterSele = defaults(p.filterSele, '')
    this.colorVolume = defaults(p.colorVolume, undefined)
    this.useWorker = defaults(p.useWorker, true)

    super.init(params)
  }

  prepareData (sview, i, callback) {
    let info = this.__infoList[ i ]
    if (!info) {
      info = {}
      this.__infoList[ i ] = info
    }

    if (!info.molsurf || info.sele !== sview.selection.string) {
      if (this.filterSele) {
        const sviewFilter = sview.structure.getView(new Selection(this.filterSele))
        const bbSize = sviewFilter.boundingBox.getSize()
        const maxDim = Math.max(bbSize.x, bbSize.y, bbSize.z)
        const asWithin = sview.getAtomSetWithinPoint(sviewFilter.center, (maxDim / 2) + 6.0)
        sview = sview.getView(
          new Selection(sview.getAtomSetWithinSelection(asWithin, 3).toSeleString())
        )
      }

      info.sele = sview.selection.string
      info.molsurf = new MolecularSurface(sview)

      const p = this.getSurfaceParams()
      const onSurfaceFinish = function (surface) {
        info.surface = surface
        callback(i)
      }

      if (this.useWorker) {
        info.molsurf.getSurfaceWorker(p, onSurfaceFinish)
      } else {
        onSurfaceFinish(info.molsurf.getSurface(p))
      }
    } else {
      callback(i)
    }
  }

  prepare (callback) {
    if (this.__forceNewMolsurf || this.__sele !== this.selection.string ||
          this.__surfaceParams !== JSON.stringify(this.getSurfaceParams())) {
      this.__infoList.forEach(info => {
        info.molsurf.dispose()
      })
      this.__infoList.length = 0
    }

    if (this.structureView.atomCount === 0) {
      callback()
      return
    }

    const after = function () {
      this.__sele = this.selection.string
      this.__surfaceParams = JSON.stringify(this.getSurfaceParams())
      this.__forceNewMolsurf = false
      callback()
    }.bind(this)

    const name = this.assembly === 'default' ? this.defaultAssembly : this.assembly
    const assembly = this.structure.biomolDict[ name ]

    if (assembly) {
      assembly.partList.forEach((part, i) => {
        const sview = part.getView(this.structureView)
        this.prepareData(sview, i, (_i) => {
          if (_i === assembly.partList.length - 1) after()
        })
      })
    } else {
      this.prepareData(this.structureView, 0, after)
    }
  }

  createData (sview, i) {
    const info = this.__infoList[ i ]
    const surface = info.surface

    const surfaceData = {
      position: surface.getPosition(),
      color: surface.getColor(this.getColorParams()),
      index: surface.getFilteredIndex(this.filterSele, sview)
    }

    const bufferList = []

    if (surface.contour) {
      const contourBuffer = new ContourBuffer(
        surfaceData,
        this.getBufferParams({
          wireframe: false
        })
      )

      bufferList.push(contourBuffer)
    } else {
      surfaceData.normal = surface.getNormal()
      surfaceData.picking = surface.getPicking(sview.getStructure())

      const surfaceBuffer = new SurfaceBuffer(
        surfaceData,
        this.getBufferParams({
          background: this.background,
          opaqueBack: this.opaqueBack,
          dullInterior: false
        })
      )

      const doubleSidedBuffer = new DoubleSidedBuffer(surfaceBuffer)

      bufferList.push(doubleSidedBuffer)
    }

    return { bufferList, info }
  }

  updateData (what, data) {
    const surfaceData = {}

    if (what.position) {
      this.__forceNewMolsurf = true
      this.build()
      return
    }

    if (what.color) {
      surfaceData.color = data.info.surface.getColor(this.getColorParams())
    }

    if (what.index) {
      surfaceData.index = data.info.surface.getFilteredIndex(this.filterSele, data.sview)
    }

    data.bufferList[ 0 ].setAttributes(surfaceData)
  }

  setParameters (params, what, rebuild) {
    what = what || {}

    if (params && params.filterSele) {
      what.index = true
    }

    if (params && params.colorVolume !== undefined) {
      what.color = true
    }

    // forbid setting wireframe to true when contour is true
    if (params && params.wireframe && (
          params.contour || (params.contour === undefined && this.contour)
        )
    ) {
      params.wireframe = false
    }

    super.setParameters(params, what, rebuild)

    return this
  }

  getSurfaceParams (params) {
    const p = Object.assign({
      type: this.surfaceType,
      probeRadius: this.probeRadius,
      scaleFactor: this.scaleFactor,
      smooth: this.smooth && !this.contour,
      cutoff: this.cutoff,
      contour: this.contour,
      useWorker: this.useWorker
    }, params)

    return p
  }

  getColorParams () {
    const p = super.getColorParams()

    p.volume = this.colorVolume

    return p
  }

  getAtomRadius () {
    return 0
  }

  clear () {
    super.clear()
  }

  dispose () {
    this.__infoList.forEach(info => {
      info.molsurf.dispose()
    })
    this.__infoList.length = 0

    super.dispose()
  }
}

RepresentationRegistry.add('surface', MolecularSurfaceRepresentation)

export default MolecularSurfaceRepresentation
<|endoftext|>


<commit_before>import React, { Component } from 'react'
import { Link } from 'react-router-dom'

// quill
import ReactQuill from 'react-quill'

// html parser
import ReactHtmlParser from 'react-html-parser'

// material ui dialog box to submit story
import RaisedButton from 'material-ui/RaisedButton'
import FlatButton from 'material-ui/FlatButton'
import Dialog from 'material-ui/Dialog'
import TextField from 'material-ui/TextField'

import firebase from 'app/fire'
import 'firebase/database'

import { dialogStyle } from '../stylesheets/MatUIStyle'

import { saveCard, publishCard } from '../utils/write.js'

export default class WriteSpace extends Component {
  constructor(props) {
    super(props)
    this.state = {
      openSubmit: false,
      dirtyText: false,
      dirtyTitle: false,
      editTitle: true,
      published: false,
      // saveCard & publishCard depend on the state below not being refactored
      cardId: '',
      card: {
        userId: 1,
        text: '',
        branchTitle: '',
        rootTitle: '',
        prevCard: '',
        nextCard: ''
      }
      // end saveCard & publishCard needs

      // TODO: implement warnings
      // to check for inputs -- can't be blank
      // and can't be more than 500 characters
    }
  }

  componentDidMount() {
    if (this.props.isBranch) {
      this.setState({
        card: Object.assign({}, this.state.card, {
          userId: 1, // will get via props maybe
          rootTitle: this.props.match.params.rootId,
          prevCard: this.props.match.params.cardId,
        })
      })
    }

    // this is to check if someone is editing a saved, unpublished card. deal with is published logic.
    if (this.state.cardId != '') {
      firebase.database().ref('storyCard').child(this.state.cardId).once('value', snap => {
        if (!snap.val().published) {
          this.setState({card: snap.val()})
        } else {
          this.setState({
            card: Object.assign({}, snap.val(), {
              text: '
This card has already been published.
'.concat(snap.val().text)
            })
          })
        }
      })
    }
  }

  changeStoryText = (value) => {
    this.setState({
      dirtyText: true,
      card: Object.assign({}, this.state.card, {text: value})
    })
  }

  changeBranchTitle = (evt) => {
    this.setState({
      dirtyText: true,
      card: Object.assign({}, this.state.card, {branchTitle: evt.target.value})
    })
  }

  // change Title from H2 to Input field
  editTitle = () => {
    this.setState({
      editTitle: true
    })
  }

  saveTitle = () => {
    const cardKey = saveCard(this.state.card, this.state.cardId)
    this.setState({
      editTitle: false,
      cardId: cardKey
    })
  }

  // clear story and submit story handlers
  clearStory = () => {
    this.setState({
      card: Object.assign({}, this.state.card, {text: ''})
    })
  }

  saveStory = (evt) => {
    evt.preventDefault()

    if (this.state.card.branchTitle == '') {
      alert('Please give your story a title.')
    } else {
      const cardKey = saveCard(this.state.card, this.state.cardId) // imported from functions folder. returns card ID

      this.setState({
        dirtyText: false,
        dirtyTitle: false,
        editTitle: false,
        cardId: cardKey
      })
    }
  }

  publishStory = (evt) => {
    evt.preventDefault()

    if (this.state.card.branchTitle == '') {
      alert('Please give your story a title.')
    } else {
      const cardKey = publishCard(this.state.card, this.state.cardId) // imported from functions folder. returns card ID

      this.setState({
        openSubmit: false,
        dirtyText: false,
        dirtyTitle: false,
        editTitle: false,
        cardId: '',
        card: Object.assign({}, this.state.card, {
          userId: 1,
          text: '',
          rootTitle: this.state.card.rootTitle ||this.state.card.branchTitle,
          prevCard: cardKey,
          nextCard: ''
        })
      })
    }
  }

  // to open/close dialog box on sumit story
  handleOpen = () => {
    if (this.state.card.branchTitle == '') {
      alert('Please give your story a title.')
    } else {
      this.setState({openSubmit: true})
    }
  }
  handleClose = () => { this.setState({openSubmit: false}) }

  render() {
    // actions to submit/cancel story submission
    const actionsDialog = [
      <FlatButton key='cancel' label="Cancel" primary={true} onClick={this.handleClose} />,
      <FlatButton key='submit' label="Publish Card & Continue Story" primary={true} keyboardFocused={true} onClick={this.publishStory} />,
    ]

    return (

          {
            this.state.editTitle
            ?

                  <input type="text"
                    className="form-control"
                    value={this.state.card.branchTitle}
                    placeholder="Story Title"
                    id="titleField"
                    onChange={this.changeBranchTitle} />

                  {
                    (this.state.card.branchTitle != '')
                    ? <Link to="#" onClick={this.saveTitle}>
                        (save title)
                      </Link>
                    : <Link to="#">

                      </Link>
                  }

            :

{this.state.card.branchTitle}

                  <Link to="#" onClick={this.editTitle}>
                    (edit title)
                  </Link>

          }

          {
            (this.state.card.rootTitle != '') && (

...A branch of {this.state.card.rootTitle}

            )
          }

            <ReactQuill value={this.state.card.text}
              onChange={this.changeStoryText}
              className="container container-fluid" />

              <RaisedButton key='save'
                label="SAVE CARD"
                backgroundColor="#D2B48C"
                onClick={this.saveStory}
                disabled={!this.state.card.text.length} />
              <RaisedButton key='submit'
                label="PUBLISH CARD & CONTINUE STORY"
                backgroundColor="#D2B48C"
                onClick={this.handleOpen}
                disabled={!this.state.card.text.length} />
              <RaisedButton key='clear'
                label="CLEAR"
                backgroundColor="#B83939"
                onClick={this.clearStory} />

        <Dialog
          title="Submit a New Story"
          actions={actionsDialog}
          modal={false}
          open={this.state.openSubmit}
          onRequestClose={this.handleClose}
          contentStyle={dialogStyle}
          autoScrollBodyContent={true}
        >
          <form onSubmit={this.publishStory} />

{this.state.card.branchTitle}

          { ReactHtmlParser(this.state.card.text) }
        </Dialog>

    )
  }
}

// <TextField
// hintText="Name Your Story Line"
// floatingLabelText="Title"
// name="title"
// fullWidth={true}
// multiLine={true}
// onChange={this.changeTitle}
// />
<commit_msg>chore: import auth into writeSpace<commit_after>import React, { Component } from 'react'
import { Link } from 'react-router-dom'

// quill
import ReactQuill from 'react-quill'

// html parser
import ReactHtmlParser from 'react-html-parser'

// material ui dialog box to submit story
import RaisedButton from 'material-ui/RaisedButton'
import FlatButton from 'material-ui/FlatButton'
import Dialog from 'material-ui/Dialog'
import TextField from 'material-ui/TextField'

//firebase
import firebase from 'app/fire'
import 'firebase/database'
const auth = firebase.auth()

import { dialogStyle } from '../stylesheets/MatUIStyle'

import { saveCard, publishCard } from '../utils/write.js'

export default class WriteSpace extends Component {
  constructor(props) {
    super(props)
    this.state = {
      openSubmit: false,
      dirtyText: false,
      dirtyTitle: false,
      editTitle: true,
      published: false,
      // saveCard & publishCard depend on the state below not being refactored
      cardId: '',
      card: {
        userId: 1,
        text: '',
        branchTitle: '',
        rootTitle: '',
        prevCard: '',
        nextCard: ''
      }
      // end saveCard & publishCard needs

      // TODO: implement warnings
      // to check for inputs -- can't be blank
      // and can't be more than 500 characters
    }
  }

  componentDidMount() {
    if (this.props.isBranch) {
      this.setState({
        card: Object.assign({}, this.state.card, {
          userId: 1, // will get via props maybe
          rootTitle: this.props.match.params.rootId,
          prevCard: this.props.match.params.cardId,
        })
      })
    }

    // this is to check if someone is editing a saved, unpublished card. deal with is published logic.
    if (this.state.cardId != '') {
      firebase.database().ref('storyCard').child(this.state.cardId).once('value', snap => {
        if (!snap.val().published) {
          this.setState({card: snap.val()})
        } else {
          this.setState({
            card: Object.assign({}, snap.val(), {
              text: '
This card has already been published.
'.concat(snap.val().text)
            })
          })
        }
      })
    }
  }

  changeStoryText = (value) => {
    this.setState({
      dirtyText: true,
      card: Object.assign({}, this.state.card, {text: value})
    })
  }

  changeBranchTitle = (evt) => {
    this.setState({
      dirtyText: true,
      card: Object.assign({}, this.state.card, {branchTitle: evt.target.value})
    })
  }

  // change Title from H2 to Input field
  editTitle = () => {
    this.setState({
      editTitle: true
    })
  }

  saveTitle = () => {
    const cardKey = saveCard(this.state.card, this.state.cardId)
    this.setState({
      editTitle: false,
      cardId: cardKey
    })
  }

  // clear story and submit story handlers
  clearStory = () => {
    this.setState({
      card: Object.assign({}, this.state.card, {text: ''})
    })
  }

  saveStory = (evt) => {
    evt.preventDefault()

    if (this.state.card.branchTitle == '') {
      alert('Please give your story a title.')
    } else {
      const cardKey = saveCard(this.state.card, this.state.cardId) // imported from functions folder. returns card ID

      this.setState({
        dirtyText: false,
        dirtyTitle: false,
        editTitle: false,
        cardId: cardKey
      })
    }
  }

  publishStory = (evt) => {
    evt.preventDefault()

    if (this.state.card.branchTitle == '') {
      alert('Please give your story a title.')
    } else {
      const cardKey = publishCard(this.state.card, this.state.cardId) // imported from functions folder. returns card ID

      this.setState({
        openSubmit: false,
        dirtyText: false,
        dirtyTitle: false,
        editTitle: false,
        cardId: '',
        card: Object.assign({}, this.state.card, {
          userId: 1,
          text: '',
          rootTitle: this.state.card.rootTitle ||this.state.card.branchTitle,
          prevCard: cardKey,
          nextCard: ''
        })
      })
    }
  }

  // to open/close dialog box on sumit story
  handleOpen = () => {
    if (this.state.card.branchTitle == '') {
      alert('Please give your story a title.')
    } else {
      this.setState({openSubmit: true})
    }
  }
  handleClose = () => { this.setState({openSubmit: false}) }

  render() {
    // actions to submit/cancel story submission
    const actionsDialog = [
      <FlatButton key='cancel' label="Cancel" primary={true} onClick={this.handleClose} />,
      <FlatButton key='submit' label="Publish Card & Continue Story" primary={true} keyboardFocused={true} onClick={this.publishStory} />,
    ]

    return (

          {
            this.state.editTitle
            ?

                  <input type="text"
                    className="form-control"
                    value={this.state.card.branchTitle}
                    placeholder="Story Title"
                    id="titleField"
                    onChange={this.changeBranchTitle} />

                  {
                    (this.state.card.branchTitle != '')
                    ? <Link to="#" onClick={this.saveTitle}>
                        (save title)
                      </Link>
                    : <Link to="#">

                      </Link>
                  }

            :

{this.state.card.branchTitle}

                  <Link to="#" onClick={this.editTitle}>
                    (edit title)
                  </Link>

          }

          {
            (this.state.card.rootTitle != '') && (

...A branch of {this.state.card.rootTitle}

            )
          }

            <ReactQuill value={this.state.card.text}
              onChange={this.changeStoryText}
              className="container container-fluid" />

              <RaisedButton key='save'
                label="SAVE CARD"
                backgroundColor="#D2B48C"
                onClick={this.saveStory}
                disabled={!this.state.card.text.length} />
              <RaisedButton key='submit'
                label="PUBLISH CARD & CONTINUE STORY"
                backgroundColor="#D2B48C"
                onClick={this.handleOpen}
                disabled={!this.state.card.text.length} />
              <RaisedButton key='clear'
                label="CLEAR"
                backgroundColor="#B83939"
                onClick={this.clearStory} />

        <Dialog
          title="Submit a New Story"
          actions={actionsDialog}
          modal={false}
          open={this.state.openSubmit}
          onRequestClose={this.handleClose}
          contentStyle={dialogStyle}
          autoScrollBodyContent={true}
        >
          <form onSubmit={this.publishStory} />

{this.state.card.branchTitle}

          { ReactHtmlParser(this.state.card.text) }
        </Dialog>

    )
  }
}

// <TextField
// hintText="Name Your Story Line"
// floatingLabelText="Title"
// name="title"
// fullWidth={true}
// multiLine={true}
// onChange={this.changeTitle}
// />
<|endoftext|>


<commit_before>var assert = require('assert');
var goToUrlAndSetLocalStorage = require('../../shared/specUtils')
    .goToUrlAndSetLocalStorage;
var waitForOncoprint = require('../../shared/specUtils').waitForOncoprint;
var reactSelectOption = require('../../shared/specUtils').reactSelectOption;
var getReactSelectOptions = require('../../shared/specUtils')
    .getReactSelectOptions;
var selectReactSelectOption = require('../../shared/specUtils')
    .selectReactSelectOption;
var useExternalFrontend = require('../../shared/specUtils').useExternalFrontend;
var setResultsPageSettingsMenuOpen = require('../../shared/specUtils')
    .setResultsPageSettingsMenuOpen;

const CBIOPORTAL_URL = process.env.CBIOPORTAL_URL.replace(/\/$/, '');
const oncoprintTabUrl =
    CBIOPORTAL_URL +
    '/results/oncoprint?Action=Submit&RPPA_SCORE_THRESHOLD=2.0&Z_SCORE_THRESHOLD=2.0&cancer_study_list=study_es_0&case_set_id=study_es_0_all&data_priority=0&gene_list=ABLIM1%250ATMEM247&geneset_list=%20&genetic_profile_ids_PROFILE_COPY_NUMBER_ALTERATION=study_es_0_gistic&genetic_profile_ids_PROFILE_MUTATION_EXTENDED=study_es_0_mutations&profileFilter=0&tab_index=tab_visualize';

describe('custom driver annotations feature', function() {
    if (useExternalFrontend) {

        describe('oncoprint tab', () => {

            beforeEach(() => {
                goToUrlAndSetLocalStorage(oncoprintTabUrl);
                waitForOncoprint(100000);
                setResultsPageSettingsMenuOpen(true);
            });

            it('shows custom driver annotation elements in config menu', () => {
                var topCheckBox = $('input[data-test=annotateCustomBinary]');
                assert(topCheckBox.isSelected());

                var tiersCheckboxes = $(
                    'span[data-test=annotateCustomTiers]'
                ).$$('input');
                assert(tiersCheckboxes[0].isSelected());
                assert(tiersCheckboxes[1].isSelected());
            });

            it('allows deselection of Tiers checkboxes', () => {
                var class1Checkbox = $('label*=Class 1').$('input');
                class1Checkbox.click();
                waitForOncoprint();
                assert(!class1Checkbox.isSelected());

                var class2Checkbox = $('label*=Class 2').$('input');
                class2Checkbox.click();
                waitForOncoprint();
                assert(!class2Checkbox.isSelected());
            });

            it('updates selected samples when VUS alterations are excluded', () => {
                // deselected all checkboxes except Custom driver annotation
                $('input[data-test=annotateHotspots]').click();
                $('label*=Class 1')
                    .$('input')
                    .click();
                $('label*=Class 2')
                    .$('input')
                    .click();

                $('input[data-test=HideVUS]').click();
                waitForOncoprint();
                assert($('div.alert-info*=1 mutation').isExisting());

                $('label*=Class 1')
                    .$('input')
                    .click();
                waitForOncoprint();
                assert($('div.alert-info*=1 mutation').isExisting());

                $('label*=Class 2')
                    .$('input')
                    .click();
                waitForOncoprint();
                assert(!$('div.alert-info').isExisting());

            });

            it('(de-)selects custom driver checkboxes with main annotation select option', () => {
                var topCheckBox = $('input[data-test=annotateCustomBinary]');
                var tiersCheckboxes = $(
                    'span[data-test=annotateCustomTiers]'
                ).$$('input');

                $('input[data-test=ColorByDriver]').click();
                assert(!topCheckBox.isSelected());
                assert(!tiersCheckboxes[0].isSelected());
                assert(!tiersCheckboxes[1].isSelected());

                $('input[data-test=ColorByDriver]').click();
                assert(topCheckBox.isSelected());
                assert(tiersCheckboxes[0].isSelected());
                assert(tiersCheckboxes[1].isSelected());
            });
        });
    }
});
<commit_msg>Run Prettier<commit_after>var assert = require('assert');
var goToUrlAndSetLocalStorage = require('../../shared/specUtils')
    .goToUrlAndSetLocalStorage;
var waitForOncoprint = require('../../shared/specUtils').waitForOncoprint;
var reactSelectOption = require('../../shared/specUtils').reactSelectOption;
var getReactSelectOptions = require('../../shared/specUtils')
    .getReactSelectOptions;
var selectReactSelectOption = require('../../shared/specUtils')
    .selectReactSelectOption;
var useExternalFrontend = require('../../shared/specUtils').useExternalFrontend;
var setResultsPageSettingsMenuOpen = require('../../shared/specUtils')
    .setResultsPageSettingsMenuOpen;

const CBIOPORTAL_URL = process.env.CBIOPORTAL_URL.replace(/\/$/, '');
const oncoprintTabUrl =
    CBIOPORTAL_URL +
    '/results/oncoprint?Action=Submit&RPPA_SCORE_THRESHOLD=2.0&Z_SCORE_THRESHOLD=2.0&cancer_study_list=study_es_0&case_set_id=study_es_0_all&data_priority=0&gene_list=ABLIM1%250ATMEM247&geneset_list=%20&genetic_profile_ids_PROFILE_COPY_NUMBER_ALTERATION=study_es_0_gistic&genetic_profile_ids_PROFILE_MUTATION_EXTENDED=study_es_0_mutations&profileFilter=0&tab_index=tab_visualize';

describe('custom driver annotations feature', function() {
    if (useExternalFrontend) {
        describe('oncoprint tab', () => {
            beforeEach(() => {
                goToUrlAndSetLocalStorage(oncoprintTabUrl);
                waitForOncoprint(100000);
                setResultsPageSettingsMenuOpen(true);
            });

            it('shows custom driver annotation elements in config menu', () => {
                var topCheckBox = $('input[data-test=annotateCustomBinary]');
                assert(topCheckBox.isSelected());

                var tiersCheckboxes = $(
                    'span[data-test=annotateCustomTiers]'
                ).$$('input');
                assert(tiersCheckboxes[0].isSelected());
                assert(tiersCheckboxes[1].isSelected());
            });

            it('allows deselection of Tiers checkboxes', () => {
                var class1Checkbox = $('label*=Class 1').$('input');
                class1Checkbox.click();
                waitForOncoprint();
                assert(!class1Checkbox.isSelected());

                var class2Checkbox = $('label*=Class 2').$('input');
                class2Checkbox.click();
                waitForOncoprint();
                assert(!class2Checkbox.isSelected());
            });

            it('updates selected samples when VUS alterations are excluded', () => {
                // deselected all checkboxes except Custom driver annotation
                $('input[data-test=annotateHotspots]').click();
                $('label*=Class 1')
                    .$('input')
                    .click();
                $('label*=Class 2')
                    .$('input')
                    .click();

                $('input[data-test=HideVUS]').click();
                waitForOncoprint();
                assert($('div.alert-info*=1 mutation').isExisting());

                $('label*=Class 1')
                    .$('input')
                    .click();
                waitForOncoprint();
                assert($('div.alert-info*=1 mutation').isExisting());

                $('label*=Class 2')
                    .$('input')
                    .click();
                waitForOncoprint();
                assert(!$('div.alert-info').isExisting());
            });

            it('(de-)selects custom driver checkboxes with main annotation select option', () => {
                var topCheckBox = $('input[data-test=annotateCustomBinary]');
                var tiersCheckboxes = $(
                    'span[data-test=annotateCustomTiers]'
                ).$$('input');

                $('input[data-test=ColorByDriver]').click();
                assert(!topCheckBox.isSelected());
                assert(!tiersCheckboxes[0].isSelected());
                assert(!tiersCheckboxes[1].isSelected());

                $('input[data-test=ColorByDriver]').click();
                assert(topCheckBox.isSelected());
                assert(tiersCheckboxes[0].isSelected());
                assert(tiersCheckboxes[1].isSelected());
            });
        });
    }
});
<|endoftext|>


<commit_before>function Routes(){
    $("#home").click(function(){
        var name = "home.html";
        addNewPage(name);
    });
    $("#case_studies").click(function(){
        $( "div#jumbo"  ).empty()
        var total = ""
        var div_end = "
";
        $.getJSON("/landlordslovecreatives/casestudies.json", function(data){
            console.log("getJSON running");
            $.each(data, function(i, item){
                total = total + "
";
                total = total + "
" + item[i].title + "
";
                total = total + "
" + item[i].description  + "
";
                total = total + "
" + item[i].city + "
";
                total = total + "
" + item[i].country + "
";
                total = total + "";
                total = total + "Source";
                total = total + item[i].video;
                var benefits = item[i].benefits;
                console.log(total);
                total = total + "
Benefits:
"
                $.each(benefits, function(i, val){
                    total = total + "
   " + val[i] + "
"
                });
                total = total + div_end;
                console.log("Generate html = " + total + " \n");
            });
        });
        $( "div#jumbo"  ).append(total);
    });
    $("#template").click(function(){
        var name = "template.html";
        addNewPage(name);
    });
    $("#guide").click(function(){
        var name = "guide.html";
        addNewPage(name);
    });
    $("#faq").click(function(){
        var name = "FAQs.html";
        addNewPage(name);
    });
    function addNewPage(name){
        $( "div#jumbo"  ).empty();
        var url = "/landlordslovecreatives/";
        $( "div#jumbo"  ).load(url.concat(name));
    }
}

$(document).ready(function(){
    $("div#jumbo").load("/landlordslovecreatives/home.html")
    routes = new Routes();
});
<commit_msg>Insert console log inside .each loop<commit_after>function Routes(){
    $("#home").click(function(){
        var name = "home.html";
        addNewPage(name);
    });
    $("#case_studies").click(function(){
        $( "div#jumbo"  ).empty()
        var total = ""
        var div_end = "
";
        $.getJSON("/landlordslovecreatives/casestudies.json", function(data){
            console.log("getJSON running data = \n" + data);
            $.each(data, function(i, item){
                console.log("i = " + i + " item = " + item);
                total = total + "
";
                total = total + "
" + item[i].title + "
";
                total = total + "
" + item[i].description  + "
";
                total = total + "
" + item[i].city + "
";
                total = total + "
" + item[i].country + "
";
                total = total + "";
                total = total + "Source";
                total = total + item[i].video;
                var benefits = item[i].benefits;
                console.log(total);
                total = total + "
Benefits:
"
                $.each(benefits, function(i, val){
                    total = total + "
   " + val[i] + "
"
                });
                total = total + div_end;
                console.log("Generate html = " + total + " \n");
            });
        });
        $( "div#jumbo"  ).append(total);
    });
    $("#template").click(function(){
        var name = "template.html";
        addNewPage(name);
    });
    $("#guide").click(function(){
        var name = "guide.html";
        addNewPage(name);
    });
    $("#faq").click(function(){
        var name = "FAQs.html";
        addNewPage(name);
    });
    function addNewPage(name){
        $( "div#jumbo"  ).empty();
        var url = "/landlordslovecreatives/";
        $( "div#jumbo"  ).load(url.concat(name));
    }
}

$(document).ready(function(){
    $("div#jumbo").load("/landlordslovecreatives/home.html")
    routes = new Routes();
});
<|endoftext|>


<commit_before>(function ($) {
    var methods = {
        init: function(options) {
            return this.each(function() {
                show($(this), false);
                $(this).change(function() {
                    show($(this), true);
                });

                function show(element, replace) {
                    var id = element.attr('id');
                    var selectedValue = element.val();
                    var prototypeElement = $('#' + id + '_' + selectedValue);
                    var container = $(prototypeElement.data('container'));

                    if (replace) {
                        container.html('
' + prototypeElement.data('prototype'));
                    } else if (!container.html().trim()) {
                        container.html('
' + prototypeElement.data('prototype'));
                    }
                };
            });
        }
    };

    $.fn.handlePrototypes = function(method) {
        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        } else {
            $.error( 'Method ' +  method + ' does not exist on jQuery.handlePrototypes' );
        }
    };
})(jQuery);
<commit_msg>Add some options for prototype handler.<commit_after>(function ($) {
    var methods = {
        init: function(options) {
            var settings = $.extend({
              'prototypePrefix': false,
              'prototypeElementPrefix': '
',
              'containerSelector': false,
            }, options);

            return this.each(function() {
                show($(this), false);
                $(this).change(function() {
                    show($(this), true);
                });

                function show(element, replace) {
                    var id = element.attr('id');
                    var selectedValue = element.val();
                    var prototypePrefix = id;
                    if (false != settings.prototypePrefix) {
                        prototypePrefix = settings.prototypePrefix;
                    }

                    var prototypeElement = $('#' + prototypePrefix + '_' + selectedValue);
                    var container;
                    if (settings.containerSelector) {
                        container = $(settings.containerSelector);
                    } else {
                        container = $(prototypeElement.data('container'));
                    }

                    if (replace) {
                        container.html(settings.prototypeElementPrefix + prototypeElement.data('prototype'));
                    } else if (!container.html().trim()) {
                        container.html(settings.prototypeElementPrefix + prototypeElement.data('prototype'));
                    }
                };
            });
        }
    };

    $.fn.handlePrototypes = function(method) {
        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        } else {
            $.error( 'Method ' +  method + ' does not exist on jQuery.handlePrototypes' );
        }
    };
})(jQuery);
<|endoftext|>


<commit_before>/*
 * Copyright 2018, Emanuel Rabina (http://www.ultraq.net.nz/)
 *
 * 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 ExpressionProcessor from '../expressions/ExpressionProcessor';
import AttributeProcessor  from '../../processors/AttributeProcessor';

/**
 * Configurable attribute processor that sets or empties an attribute value on
 * an element if the result of its expression is truthy or falsey respectively.
 *
 * @author Emanuel Rabina
 */
export default class EmptyableAttributeProcessor extends AttributeProcessor {

	/**
	 * Constructor, set the name of the attribute this processor will operate on.
	 *
	 * @param {String} prefix
	 * @param {String} name
	 */
	constructor(prefix, name) {

		super(prefix, name);
	}

	/**
	 * Processes an element that contains the configured attribute to be worked
	 * on, setting it if the expression resolves to a truthy value, or removing it
	 * if it resolves to a falsey value.
	 *
	 * @param {Element} element
	 *   Element being processed.
	 * @param {String} attribute
	 *   The attribute that was encountered to invoke this processor.
	 * @param {String} attributeValue
	 *   The value given by the attribute.
	 * @param {Object} context
	 */
	process(element, attribute, attributeValue, context) {

		let value = new ExpressionProcessor(context).process(attributeValue);
		element.setAttribute(this.name, value ? value.toString() : '');
		element.removeAttribute(attribute);
	}
}

export const EMPTYABLE_ATTRIBUTE_NAMES = [
	'href',
	'src',
	'value'
];
<commit_msg>Allow processing of th:style<commit_after>/*
 * Copyright 2018, Emanuel Rabina (http://www.ultraq.net.nz/)
 *
 * 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 ExpressionProcessor from '../expressions/ExpressionProcessor';
import AttributeProcessor  from '../../processors/AttributeProcessor';

/**
 * Configurable attribute processor that sets or empties an attribute value on
 * an element if the result of its expression is truthy or falsey respectively.
 *
 * @author Emanuel Rabina
 */
export default class EmptyableAttributeProcessor extends AttributeProcessor {

	/**
	 * Constructor, set the name of the attribute this processor will operate on.
	 *
	 * @param {String} prefix
	 * @param {String} name
	 */
	constructor(prefix, name) {

		super(prefix, name);
	}

	/**
	 * Processes an element that contains the configured attribute to be worked
	 * on, setting it if the expression resolves to a truthy value, or removing it
	 * if it resolves to a falsey value.
	 *
	 * @param {Element} element
	 *   Element being processed.
	 * @param {String} attribute
	 *   The attribute that was encountered to invoke this processor.
	 * @param {String} attributeValue
	 *   The value given by the attribute.
	 * @param {Object} context
	 */
	process(element, attribute, attributeValue, context) {

		let value = new ExpressionProcessor(context).process(attributeValue);
		element.setAttribute(this.name, value ? value.toString() : '');
		element.removeAttribute(attribute);
	}
}

export const EMPTYABLE_ATTRIBUTE_NAMES = [
	'href',
	'src',
	'style',
	'value'
];
<|endoftext|>


<commit_before>var core_services = [
    {
        "name": "example01",
        "extKeyRequired": false,
        "port": 4010,
        "apis": [
            {
                "l": "Test Get",
                'v': "/testGet"
            },
            {
                "l": "Test Delete",
                'v': "/testDel"
            },
            {
                'l': 'Build Name',
                'v': '/buildName'
            },
            {
                'l': 'Test Post',
                'v': '/testPost'
            },
            {
                'l': 'Test Put',
                'v': '/testPut'
            }
        ]
    },
    {
        "name": "example02",
        "extKeyRequired": true,
        "port": 4011,
        "apis": [
            {
                'l': 'Build Name',
                'v': '/buildName'
            }
        ]
    },
    {
        "name": "example03",
        "extKeyRequired": true,
        "port": 4012,
        "apis": [
            {
                "l": "Test Get Api",
                'v': "/testGet"
            },
            {
                'l': 'Build Name Api',
                'v': '/buildName'
            }
        ]
    },
    {
        "name": "example04",
        "extKeyRequired": true,
        "port": 4013,
        "apis": [
            {
                'l': 'Build Name',
                'v': '/buildName'
            },
            {
                "l": "Build Name Gold",
                'v': "/buildNameGold"
            },
            {
                "l": "Test Get",
                'v': "/testGet"
            }
        ]
    }
];

var core_hosts = [
    {
        "env": "dev",
        "name": "controller",
        "ip": "127.0.0.1"
    },
    {
        "env": "dev",
        "name": "example01",
        "ip": "127.0.0.1"
    },
    {
        "env": "dev",
        "name": "example02",
        "ip": "127.0.0.1"
    },
    {
        "env": "dev",
        "name": "example03",
        "ip": "127.0.0.1"
    },
    {
        "env": "dev",
        "name": "example04",
        "ip": "127.0.0.1"
    }
];<commit_msg>added entries for hello world example<commit_after>var core_services = [
    {
        "name": "example01",
        "extKeyRequired": false,
        "port": 4010,
        "apis": [
            {
                "l": "Test Get",
                'v': "/testGet"
            },
            {
                "l": "Test Delete",
                'v': "/testDel"
            },
            {
                'l': 'Build Name',
                'v': '/buildName'
            },
            {
                'l': 'Test Post',
                'v': '/testPost'
            },
            {
                'l': 'Test Put',
                'v': '/testPut'
            }
        ]
    },
    {
        "name": "example02",
        "extKeyRequired": true,
        "port": 4011,
        "apis": [
            {
                'l': 'Build Name',
                'v': '/buildName'
            }
        ]
    },
    {
        "name": "example03",
        "extKeyRequired": true,
        "port": 4012,
        "apis": [
            {
                "l": "Test Get Api",
                'v': "/testGet"
            },
            {
                'l': 'Build Name Api',
                'v': '/buildName'
            }
        ]
    },
    {
        "name": "example04",
        "extKeyRequired": true,
        "port": 4013,
        "apis": [
            {
                'l': 'Build Name',
                'v': '/buildName'
            },
            {
                "l": "Build Name Gold",
                'v': "/buildNameGold"
            },
            {
                "l": "Test Get",
                'v': "/testGet"
            }
        ]
    },
    {
        "name": "helloworld",
        "extKeyRequired": true,
        "port": 4020,
        "apis": [
            {
                'l': 'hello world',
                'v': '/hello'
            }
        ]
    }
];

var core_hosts = [
    {
        "env": "dev",
        "name": "controller",
        "ip": "127.0.0.1"
    },
    {
        "env": "dev",
        "name": "example01",
        "ip": "127.0.0.1"
    },
    {
        "env": "dev",
        "name": "example02",
        "ip": "127.0.0.1"
    },
    {
        "env": "dev",
        "name": "example03",
        "ip": "127.0.0.1"
    },
    {
        "env": "dev",
        "name": "example04",
        "ip": "127.0.0.1"
    },
    {
        "env": "dev",
        "name": "helloworld",
        "ip": "127.0.0.1"
    }
];<|endoftext|>


<commit_before>'use strict';

module.exports = function(config) {
  config.set({
    browsers: ['PhantomJS'],
    preprocessors: {
      'test/fixtures/**/*.json': ['json_fixtures']
    },
    files : [
      'bower_components/angular-mocks/angular-mocks.js',
      'app/scripts/**/*.js',
      'app/translations/*.js',
      'test/fixtures/**/*.json',
      'test/mocks/**/*.js',
      'test/specs/**/*.js'
    ],
    logLevel: 'info',
    basePath: '../',
    frameworks: ['mocha', 'chai', 'wiredep', 'angular-filesort'],
    reporters: ['spec'],
    colors: true,
    plugins : [
      'karma-wiredep',
      'karma-mocha',
      'karma-chai',
      'karma-angular-filesort',
      'karma-phantomjs-launcher',
      'karma-mocha-reporter',
      'karma-spec-reporter',
      'karma-json-fixtures-preprocessor'
    ],

    specReporter: {
      maxLogLines: 3
    },
    jsonFixturesPreprocessor: {
      stripPrefix: 'test/unit/fixtures/',
      camelizeFilenames: true
    },
    wiredep: {},
    angularFilesort: {
      whitelist: [
        'app/scripts/**/*.js'
      ]
    }
  });
};
<commit_msg>Fixtures path fixed<commit_after>'use strict';

module.exports = function(config) {
  config.set({
    browsers: ['PhantomJS'],
    preprocessors: {
      'test/fixtures/**/*.json': ['json_fixtures']
    },
    files : [
      'bower_components/angular-mocks/angular-mocks.js',
      'app/scripts/**/*.js',
      'app/translations/*.js',
      'test/fixtures/**/*.json',
      'test/mocks/**/*.js',
      'test/specs/**/*.js'
    ],
    logLevel: 'info',
    basePath: '../',
    frameworks: ['mocha', 'chai', 'wiredep', 'angular-filesort'],
    reporters: ['spec'],
    colors: true,
    plugins : [
      'karma-wiredep',
      'karma-mocha',
      'karma-chai',
      'karma-angular-filesort',
      'karma-phantomjs-launcher',
      'karma-mocha-reporter',
      'karma-spec-reporter',
      'karma-json-fixtures-preprocessor'
    ],

    specReporter: {
      maxLogLines: 3
    },
    jsonFixturesPreprocessor: {
      stripPrefix: 'test/fixtures/',
      camelizeFilenames: true
    },
    wiredep: {},
    angularFilesort: {
      whitelist: [
        'app/scripts/**/*.js'
      ]
    }
  });
};
<|endoftext|>


<commit_before>var sys = require('sys'),
    Layer = require('./Layer').Layer,
    Director = require('./Director').Director,
    MenuItem = require('./MenuItem').MenuItem,
    TouchDispatcher = require('./TouchDispatcher').TouchDispatcher,
    geom = require('geometry'), ccp = geom.ccp;

/** @private
 * @constant */
var kMenuStateWaiting = 0;

/** @private
 * @constant */
var kMenuStateTrackingTouch = 1;

/** @member cocos
 * @class
 *
 * @extends cocos.Layer
 */
var Menu = Layer.extend(/** @scope cocos.Menu# */{
	state: kMenuStateWaiting,
	selectedItem: null,
	opacuty: 255,
	color: null,

	init: function(opts) {
		@super;

		var items = opts['items'];

		this.set('isTouchEnabled', true);

        var s = Director.get('sharedDirector.winSize');

		this.set('isRelativeAnchorPoint', false);
		this.anchorPoint = ccp(0.5, 0.5);
		this.set('contentSize', s);

		this.set('position', ccp(s.width /2, s.height /2));

		if (items) {
			var z = 0;
			sys.each(items, sys.callback(this, function(item) {
				this.addChild({child: item, z:z++});
			}));
		}

	},

	addChild: function(opts) {
		if (!opts['child'] instanceof MenuItem) {
			throw "Menu only supports MenuItem objects as children";
		}

		return @super;
    },

    registerWithTouchDispatcher: function() {
        TouchDispatcher.get('sharedDispatcher').addTargetedDelegate({delegate: this, priority: INT_MIN+1, swallowsTouches: true});
    },

    itemForTouch: function(touch) {
        var children = this.get('children');
        for (var i = 0, len = children.length; i < len; i++) {
            var item = children[i];

            if (item.get('visible') && item.get('isEnabled')) {
                var local = item.convertToNodeSpace(touch.location);

                var r = item.get('rect');
                r.origin = ccp(0, 0);

                if (geom.rectContainsPoint(r, local)) {
                    return item;
                }

            }
        }

        return null;
    },

    touchBegan: function(opts) {
        var touch = opts['touch'],
            event = opts['event'];

        if (this.state != kMenuStateWaiting || !this.visible) {
            return false;
        }

        var selectedItem = this.set('selectedItem', this.itemForTouch(touch));
        if (selectedItem) {
            selectedItem.set('isSelected', true);
            this.set('state', kMenuStateTrackingTouch);

            return true;
        }

        return false;
    },
    touchMoved: function(opts) {
        var touch = opts['touch'],
            event = opts['event'];

            var currentItem = this.itemForTouch(touch);

            if (currentItem != this.selectedItem) {
                if (this.selectedItem) {
                    this.selectedItem.set('isSelected', false);
                }
                this.set('selectedItem', currentItem);
                if (this.selectedItem) {
                    this.selectedItem.set('isSelected', true);
                }
            }

    },
    touchEnded: function(opts) {
        var touch = opts['touch'],
            event = opts['event'];

        if (this.selectedItem) {
            this.selectedItem.set('isSelected', false);
            this.selectedItem.activate();
        }

        this.set('state', kMenuStateWaiting);
    }

});

exports.Menu = Menu;
<commit_msg>Fixed MIN_INT reference in Menu<commit_after>var sys = require('sys'),
    Layer = require('./Layer').Layer,
    Director = require('./Director').Director,
    MenuItem = require('./MenuItem').MenuItem,
    TouchDispatcher = require('./TouchDispatcher').TouchDispatcher,
    geom = require('geometry'), ccp = geom.ccp;

/** @private
 * @constant */
var kMenuStateWaiting = 0;

/** @private
 * @constant */
var kMenuStateTrackingTouch = 1;

/** @member cocos
 * @class
 *
 * @extends cocos.Layer
 */
var Menu = Layer.extend(/** @scope cocos.Menu# */{
	state: kMenuStateWaiting,
	selectedItem: null,
	opacuty: 255,
	color: null,

	init: function(opts) {
		@super;

		var items = opts['items'];

		this.set('isTouchEnabled', true);

        var s = Director.get('sharedDirector.winSize');

		this.set('isRelativeAnchorPoint', false);
		this.anchorPoint = ccp(0.5, 0.5);
		this.set('contentSize', s);

		this.set('position', ccp(s.width /2, s.height /2));

		if (items) {
			var z = 0;
			sys.each(items, sys.callback(this, function(item) {
				this.addChild({child: item, z:z++});
			}));
		}

	},

	addChild: function(opts) {
		if (!opts['child'] instanceof MenuItem) {
			throw "Menu only supports MenuItem objects as children";
		}

		return @super;
    },

    registerWithTouchDispatcher: function() {
        TouchDispatcher.get('sharedDispatcher').addTargetedDelegate({delegate: this, priority: Number.MIN_INT+1, swallowsTouches: true});
    },

    itemForTouch: function(touch) {
        var children = this.get('children');
        for (var i = 0, len = children.length; i < len; i++) {
            var item = children[i];

            if (item.get('visible') && item.get('isEnabled')) {
                var local = item.convertToNodeSpace(touch.location);

                var r = item.get('rect');
                r.origin = ccp(0, 0);

                if (geom.rectContainsPoint(r, local)) {
                    return item;
                }

            }
        }

        return null;
    },

    touchBegan: function(opts) {
        var touch = opts['touch'],
            event = opts['event'];

        if (this.state != kMenuStateWaiting || !this.visible) {
            return false;
        }

        var selectedItem = this.set('selectedItem', this.itemForTouch(touch));
        if (selectedItem) {
            selectedItem.set('isSelected', true);
            this.set('state', kMenuStateTrackingTouch);

            return true;
        }

        return false;
    },
    touchMoved: function(opts) {
        var touch = opts['touch'],
            event = opts['event'];

            var currentItem = this.itemForTouch(touch);

            if (currentItem != this.selectedItem) {
                if (this.selectedItem) {
                    this.selectedItem.set('isSelected', false);
                }
                this.set('selectedItem', currentItem);
                if (this.selectedItem) {
                    this.selectedItem.set('isSelected', true);
                }
            }

    },
    touchEnded: function(opts) {
        var touch = opts['touch'],
            event = opts['event'];

        if (this.selectedItem) {
            this.selectedItem.set('isSelected', false);
            this.selectedItem.activate();
        }

        this.set('state', kMenuStateWaiting);
    }

});

exports.Menu = Menu;
<|endoftext|>


<commit_before>/**
    Licensed to the Apache Software Foundation (ASF) under one
    or more contributor license agreements.  See the NOTICE file
    distributed with this work for additional information
    regarding copyright ownership.  The ASF licenses this file
    to you 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.
*/
var fs            = require('fs'),
    path          = require('path'),
    et            = require('elementtree'),
    xml           = require('../xml-helpers'),
    util          = require('../util'),
    events        = require('../events'),
    shell         = require('shelljs'),
    child_process = require('child_process'),
    Q             = require('q'),
    config_parser = require('../config_parser'),
    config        = require('../config'),
    hooker        = require('../hooker');

module.exports = function wp7_parser(project) {
    try {
        // TODO : Check that it's not a wp7 project?
        var csproj_file   = fs.readdirSync(project).filter(function(e) { return e.match(/\.csproj$/i); })[0];
        if (!csproj_file) throw new Error('No .csproj file.');
        this.wp7_proj_dir = project;
        this.csproj_path  = path.join(this.wp7_proj_dir, csproj_file);
        this.sln_path     = path.join(this.wp7_proj_dir, csproj_file.replace(/\.csproj/, '.sln'));
    } catch(e) {
        throw new Error('The provided path "' + project + '" is not a Windows Phone 7 project. ' + e);
    }
    this.manifest_path  = path.join(this.wp7_proj_dir, 'Properties', 'WMAppManifest.xml');
    this.config_path = path.join(this.wp7_proj_dir, 'config.xml');
    this.config = new util.config_parser(this.config_path);
};

// Returns a promise.
module.exports.check_requirements = function(project_root) {
    events.emit('log', 'Checking wp7 requirements...');
    var lib_path = path.join(util.libDirectory, 'wp', 'cordova', require('../../platforms').wp7.version, 'wp7');
    var custom_path = config.has_custom_path(project_root, 'wp7');
    if (custom_path) {
        lib_path = path.join(custom_path, 'wp7');
    }
    var command = '"' + path.join(lib_path, 'bin', 'check_reqs') + '"';
    events.emit('verbose', 'Running "' + command + '" (output to follow)');
    var d = Q.defer();
    child_process.exec(command, function(err, output, stderr) {
        events.emit('verbose', output+stderr);
        if (err) {
            d.reject(new Error('Error while checking requirements: ' + output + stderr));
        } else {
            d.resolve();
        }
    });
    return d.promise;
};

module.exports.prototype = {
    update_from_config:function(config) {
        //check config parser
        if (config instanceof config_parser) {
        } else throw new Error('update_from_config requires a config_parser object');

        //Get manifest file
        var manifest = xml.parseElementtreeSync(this.manifest_path);

        //Update app version
        var version = config.version();
        manifest.find('.//App').attrib.Version = version;

        // Update app name by editing app title in Properties\WMAppManifest.xml
        var name = config.name();
        var prev_name = manifest.find('.//App[@Title]')['attrib']['Title'];
        if(prev_name != name) {
            events.emit('verbose', "Updating app name from " + prev_name + " to " + name);
            manifest.find('.//App').attrib.Title = name;
            manifest.find('.//App').attrib.Publisher = name + " Publisher";
            manifest.find('.//App').attrib.Author = name + " Author";
            manifest.find('.//PrimaryToken').attrib.TokenID = name;
            //update name of sln and csproj.
            name = name.replace(/(\.\s|\s\.|\s+|\.+)/g, '_'); //make it a ligitamate name
            prev_name = prev_name.replace(/(\.\s|\s\.|\s+|\.+)/g, '_');
            var sln_name = fs.readdirSync(this.wp7_proj_dir).filter(function(e) { return e.match(/\.sln$/i); })[0];
            var sln_path = path.join(this.wp7_proj_dir, sln_name);
            var sln_file = fs.readFileSync(sln_path, 'utf-8');
            var name_regex = new RegExp(prev_name, "g");
            fs.writeFileSync(sln_path, sln_file.replace(name_regex, name), 'utf-8');
            shell.mv('-f', this.csproj_path, path.join(this.wp7_proj_dir, name + '.csproj'));
            this.csproj_path = path.join(this.wp7_proj_dir, name + '.csproj');
            shell.mv('-f', sln_path, path.join(this.wp7_proj_dir, name + '.sln'));
            this.sln_path    = path.join(this.wp7_proj_dir, name + '.sln');
        }

        // Update package name by changing:
        /*  - CordovaAppProj.csproj
         *  - MainPage.xaml
         *  - MainPage.xaml.cs
         *  - App.xaml
         *  - App.xaml.cs
         */
         var pkg = config.packageName();
         var csproj = xml.parseElementtreeSync(this.csproj_path);
         prev_name = csproj.find('.//RootNamespace').text;
         if(prev_name != pkg) {
            events.emit('verbose', "Updating package name from " + prev_name + " to " + pkg);
            //CordovaAppProj.csproj
            csproj.find('.//RootNamespace').text = pkg;
            csproj.find('.//AssemblyName').text = pkg;
            csproj.find('.//XapFilename').text = pkg + '.xap';
            csproj.find('.//SilverlightAppEntry').text = pkg + '.App';
            fs.writeFileSync(this.csproj_path, csproj.write({indent: 4}), 'utf-8');
            //MainPage.xaml
            var mainPageXAML = xml.parseElementtreeSync(path.join(this.wp7_proj_dir, 'MainPage.xaml'));
            mainPageXAML.getroot().attrib['x:Class'] = pkg + '.MainPage';
            fs.writeFileSync(path.join(this.wp7_proj_dir, 'MainPage.xaml'), mainPageXAML.write({indent: 4}), 'utf-8');
            //MainPage.xaml.cs
            var mainPageCS = fs.readFileSync(path.join(this.wp7_proj_dir, 'MainPage.xaml.cs'), 'utf-8');
            var namespaceRegEx = new RegExp('namespace ' + prev_name);
            fs.writeFileSync(path.join(this.wp7_proj_dir, 'MainPage.xaml.cs'), mainPageCS.replace(namespaceRegEx, 'namespace ' + pkg), 'utf-8');
            //App.xaml
            var appXAML = xml.parseElementtreeSync(path.join(this.wp7_proj_dir, 'App.xaml'));
            appXAML.getroot().attrib['x:Class'] = pkg + '.App';
            fs.writeFileSync(path.join(this.wp7_proj_dir, 'App.xaml'), appXAML.write({indent: 4}), 'utf-8');
            //App.xaml.cs
            var appCS = fs.readFileSync(path.join(this.wp7_proj_dir, 'App.xaml.cs'), 'utf-8');
            fs.writeFileSync(path.join(this.wp7_proj_dir, 'App.xaml.cs'), appCS.replace(namespaceRegEx, 'namespace ' + pkg), 'utf-8');
         }

         //Write out manifest
         fs.writeFileSync(this.manifest_path, manifest.write({indent: 4}), 'utf-8');
    },
    // Returns the platform-specific www directory.
    www_dir:function() {
        return path.join(this.wp7_proj_dir, 'www');
    },
    // copy files from merges directory to actual www dir
    copy_merges:function(merges_sub_path) {
        var merges_path = path.join(util.appDir(util.isCordova(this.wp7_proj_dir)), 'merges', merges_sub_path);
        if (fs.existsSync(merges_path)) {
            var overrides = path.join(merges_path, '*');
            shell.cp('-rf', overrides, this.www_dir());
        }
    },

    // Used for creating platform_www in projects created by older versions.
    cordovajs_path:function(libDir) {
        var jsPath = path.join(libDir, 'common', 'www', 'cordova.js');
        return path.resolve(jsPath);
    },

    // Replace the www dir with contents of platform_www and app www and updates the csproj file.
    update_www:function() {
        var projectRoot = util.isCordova(this.wp7_proj_dir);
        var app_www = util.projectWww(projectRoot);
        var platform_www = path.join(this.wp7_proj_dir, 'platform_www');

        // Clear the www dir
        shell.rm('-rf', this.www_dir());
        shell.mkdir(this.www_dir());
        // Copy over all app www assets
        shell.cp('-rf', path.join(app_www, '*'), this.www_dir());

        // Copy all files from merges directories - wp generic first, then wp7 specific.
        this.copy_merges('wp');
        this.copy_merges('wp7');
        // Copy over stock platform www assets (cordova.js)
        shell.cp('-rf', path.join(platform_www, '*'), this.www_dir());
    },

    // updates the csproj file to explicitly list all www content.
    update_csproj:function() {
        var csproj_xml = xml.parseElementtreeSync(this.csproj_path);
        // remove any previous references to the www files
        var item_groups = csproj_xml.findall('ItemGroup');
        for (var i = 0, l = item_groups.length; i < l; i++) {
            var group = item_groups[i];
            var files = group.findall('Content');
            for (var j = 0, k = files.length; j < k; j++) {
                var file = files[j];
                if (file.attrib.Include.substr(0, 3) == 'www') {
                    // remove file reference
                    group.remove(0, file);
                    // remove ItemGroup if empty
                    var new_group = group.findall('Content');
                    if(new_group.length < 1) {
                        csproj_xml.getroot().remove(0, group);
                    }
                }
            }
        }

        // now add all www references back in from the wp www folder
        var www_files = this.folder_contents('www', this.www_dir());
        for(file in www_files) {
            var item = new et.Element('ItemGroup');
            var content = new et.Element('Content');
            content.attrib.Include = www_files[file];
            item.append(content);
            csproj_xml.getroot().append(item);
        }
        // save file
        fs.writeFileSync(this.csproj_path, csproj_xml.write({indent:4}), 'utf-8');
    },
    // Returns an array of all the files in the given directory with reletive paths
    // - name     : the name of the top level directory (i.e all files will start with this in their path)
    // - path     : the directory whos contents will be listed under 'name' directory
    folder_contents:function(name, dir) {
        var results = [];
        var folder_dir = fs.readdirSync(dir);
        for(item in folder_dir) {
            var stat = fs.statSync(path.join(dir, folder_dir[item]));
            // means its a folder?
            if(stat.size == 0) {
                var sub_dir = this.folder_contents(path.join(name, folder_dir[item]), path.join(dir, folder_dir[item]));
                //Add all subfolder item paths
                for(sub_item in sub_dir) {
                    results.push(sub_dir[sub_item]);
                }
            }
            else {
                results.push(path.join(name, folder_dir[item]));
            }
        }
        return results;
    },
    staging_dir: function() {
        return path.join(this.wp7_proj_dir, '.staging', 'www');
    },

    update_staging: function() {
        var projectRoot = util.isCordova(this.wp7_proj_dir);
        if (fs.existsSync(this.staging_dir())) {
            var staging = path.join(this.staging_dir(), '*');
            shell.cp('-rf', staging, this.www_dir());
        }
    },

    // calls the nessesary functions to update the wp7 project
    // Returns a promise.
    update_project:function(cfg) {
        try {
            this.update_from_config(cfg);
        } catch(e) {
            return Q.reject(e);
        }
        // trigger an event in case anyone needs to modify the contents of the www folder before we package it.
        var that = this;
        var projectRoot = util.isCordova(process.cwd());
        var hooks = new hooker(projectRoot);

        return hooks.fire('pre_package', { wwwPath:this.www_dir() })
        .then(function() {
            that.update_csproj();
            // TODO: Add overrides support? Why is this missing?
            that.update_staging();
            util.deleteSvnFolders(that.www_dir());
        });
    }
};
<commit_msg>Update wp7_parser.js<commit_after>/**
    Licensed to the Apache Software Foundation (ASF) under one
    or more contributor license agreements.  See the NOTICE file
    distributed with this work for additional information
    regarding copyright ownership.  The ASF licenses this file
    to you 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.
*/
var fs            = require('fs'),
    path          = require('path'),
    et            = require('elementtree'),
    xml           = require('../xml-helpers'),
    util          = require('../util'),
    events        = require('../events'),
    shell         = require('shelljs'),
    child_process = require('child_process'),
    Q             = require('q'),
    config_parser = require('../config_parser'),
    config        = require('../config'),
    hooker        = require('../hooker');

module.exports = function wp7_parser(project) {
    try {
        // TODO : Check that it's not a wp7 project?
        var csproj_file   = fs.readdirSync(project).filter(function(e) { return e.match(/\.csproj$/i); })[0];
        if (!csproj_file) throw new Error('No .csproj file.');
        this.wp7_proj_dir = project;
        this.csproj_path  = path.join(this.wp7_proj_dir, csproj_file);
        this.sln_path     = path.join(this.wp7_proj_dir, csproj_file.replace(/\.csproj/, '.sln'));
    } catch(e) {
        throw new Error('The provided path "' + project + '" is not a Windows Phone 7 project. ' + e);
    }
    this.manifest_path  = path.join(this.wp7_proj_dir, 'Properties', 'WMAppManifest.xml');
    this.config_path = path.join(this.wp7_proj_dir, 'config.xml');
    this.config = new util.config_parser(this.config_path);
};

// Returns a promise.
module.exports.check_requirements = function(project_root) {
    events.emit('log', 'Checking wp7 requirements...');
    var lib_path = path.join(util.libDirectory, 'wp', 'cordova', require('../../platforms').wp7.version, 'wp7');
    var custom_path = config.has_custom_path(project_root, 'wp7');
    if (custom_path) {
        lib_path = path.join(custom_path, 'wp7');
    }
    var command = '"' + path.join(lib_path, 'bin', 'check_reqs') + '"';
    events.emit('verbose', 'Running "' + command + '" (output to follow)');
    var d = Q.defer();
    child_process.exec(command, function(err, output, stderr) {
        events.emit('verbose', output+stderr);
        if (err) {
            d.reject(new Error('Error while checking requirements: ' + output + stderr));
        } else {
            d.resolve();
        }
    });
    return d.promise;
};

module.exports.prototype = {
    update_from_config:function(config) {
        //check config parser
        if (config instanceof config_parser) {
        } else throw new Error('update_from_config requires a config_parser object');

        //Get manifest file
        var manifest = xml.parseElementtreeSync(this.manifest_path);

        //Update app version
        var version = config.version();
        manifest.find('.//App').attrib.Version = version;

        // Update app name by editing app title in Properties\WMAppManifest.xml
        var name = config.name();
        var prev_name = manifest.find('.//App[@Title]')['attrib']['Title'];
        if(prev_name != name) {
            events.emit('verbose', "Updating app name from " + prev_name + " to " + name);
            manifest.find('.//App').attrib.Title = name;
            manifest.find('.//App').attrib.Publisher = name + " Publisher";
            manifest.find('.//App').attrib.Author = name + " Author";
            manifest.find('.//PrimaryToken').attrib.TokenID = name;
            //update name of sln and csproj.
            name = name.replace(/(\.\s|\s\.|\s+|\.+)/g, '_'); //make it a ligitamate name
            prev_name = prev_name.replace(/(\.\s|\s\.|\s+|\.+)/g, '_');
            var sln_name = fs.readdirSync(this.wp7_proj_dir).filter(function(e) { return e.match(/\.sln$/i); })[0];
            var sln_path = path.join(this.wp7_proj_dir, sln_name);
            var sln_file = fs.readFileSync(sln_path, 'utf-8');
            var name_regex = new RegExp(prev_name, "g");
            fs.writeFileSync(sln_path, sln_file.replace(name_regex, name), 'utf-8');
            shell.mv('-f', this.csproj_path, path.join(this.wp7_proj_dir, name + '.csproj'));
            this.csproj_path = path.join(this.wp7_proj_dir, name + '.csproj');
            shell.mv('-f', sln_path, path.join(this.wp7_proj_dir, name + '.sln'));
            this.sln_path    = path.join(this.wp7_proj_dir, name + '.sln');
        }

        // Update package name by changing:
        /*  - CordovaAppProj.csproj
         *  - MainPage.xaml
         *  - MainPage.xaml.cs
         *  - App.xaml
         *  - App.xaml.cs
         */
         var pkg = config.packageName();
         var csproj = xml.parseElementtreeSync(this.csproj_path);
         prev_name = csproj.find('.//RootNamespace').text;
         if(prev_name != pkg) {
            events.emit('verbose', "Updating package name from " + prev_name + " to " + pkg);
            //CordovaAppProj.csproj
            csproj.find('.//RootNamespace').text = pkg;
            csproj.find('.//AssemblyName').text = pkg;
            csproj.find('.//XapFilename').text = pkg + '.xap';
            csproj.find('.//SilverlightAppEntry').text = pkg + '.App';
            fs.writeFileSync(this.csproj_path, csproj.write({indent: 4}), 'utf-8');
            //MainPage.xaml
            var mainPageXAML = xml.parseElementtreeSync(path.join(this.wp7_proj_dir, 'MainPage.xaml'));
            mainPageXAML.getroot().attrib['x:Class'] = pkg + '.MainPage';
            fs.writeFileSync(path.join(this.wp7_proj_dir, 'MainPage.xaml'), mainPageXAML.write({indent: 4}), 'utf-8');
            //MainPage.xaml.cs
            var mainPageCS = fs.readFileSync(path.join(this.wp7_proj_dir, 'MainPage.xaml.cs'), 'utf-8');
            var namespaceRegEx = new RegExp('namespace ' + prev_name);
            fs.writeFileSync(path.join(this.wp7_proj_dir, 'MainPage.xaml.cs'), mainPageCS.replace(namespaceRegEx, 'namespace ' + pkg), 'utf-8');
            //App.xaml
            var appXAML = xml.parseElementtreeSync(path.join(this.wp7_proj_dir, 'App.xaml'));
            appXAML.getroot().attrib['x:Class'] = pkg + '.App';
            fs.writeFileSync(path.join(this.wp7_proj_dir, 'App.xaml'), appXAML.write({indent: 4}), 'utf-8');
            //App.xaml.cs
            var appCS = fs.readFileSync(path.join(this.wp7_proj_dir, 'App.xaml.cs'), 'utf-8');
            fs.writeFileSync(path.join(this.wp7_proj_dir, 'App.xaml.cs'), appCS.replace(namespaceRegEx, 'namespace ' + pkg), 'utf-8');
         }

         //Write out manifest
         fs.writeFileSync(this.manifest_path, manifest.write({indent: 4}), 'utf-8');
    },
    // Returns the platform-specific www directory.
    www_dir:function() {
        return path.join(this.wp7_proj_dir, 'www');
    },
    // copy files from merges directory to actual www dir
    copy_merges:function(merges_sub_path) {
        var merges_path = path.join(util.appDir(util.isCordova(this.wp7_proj_dir)), 'merges', merges_sub_path);
        if (fs.existsSync(merges_path)) {
            var overrides = path.join(merges_path, '*');
            shell.cp('-rf', overrides, this.www_dir());
        }
    },

    // Used for creating platform_www in projects created by older versions.
    cordovajs_path:function(libDir) {
        var jsPath = path.join(libDir, 'common', 'www', 'cordova.js');
        return path.resolve(jsPath);
    },

    // Replace the www dir with contents of platform_www and app www and updates the csproj file.
    update_www:function() {
        var projectRoot = util.isCordova(this.wp7_proj_dir);
        var app_www = util.projectWww(projectRoot);
        var platform_www = path.join(this.wp7_proj_dir, 'platform_www');

        // Clear the www dir
        shell.rm('-rf', this.www_dir());
        shell.mkdir(this.www_dir());
        // Copy over all app www assets
        shell.cp('-rf', path.join(app_www, '*'), this.www_dir());

        // Copy all files from merges directories - wp generic first, then wp7 specific.
        this.copy_merges('wp');
        this.copy_merges('wp7');
        // Copy over stock platform www assets (cordova.js)
        shell.cp('-rf', path.join(platform_www, '*'), this.www_dir());
    },

    // updates the csproj file to explicitly list all www content.
    update_csproj:function() {
        var csproj_xml = xml.parseElementtreeSync(this.csproj_path);
        // remove any previous references to the www files
        var item_groups = csproj_xml.findall('ItemGroup');
        for (var i = 0, l = item_groups.length; i < l; i++) {
            var group = item_groups[i];
            var files = group.findall('Content');
            for (var j = 0, k = files.length; j < k; j++) {
                var file = files[j];
                if (file.attrib.Include.substr(0, 3) == 'www') {
                    // remove file reference
                    group.remove(0, file);
                    // remove ItemGroup if empty
                    var new_group = group.findall('Content');
                    if(new_group.length < 1) {
                        csproj_xml.getroot().remove(0, group);
                    }
                }
            }
        }

        // now add all www references back in from the wp www folder
        var www_files = this.folder_contents('www', this.www_dir());
        for(file in www_files) {
            var item = new et.Element('ItemGroup');
            var content = new et.Element('Content');
            content.attrib.Include = www_files[file];
            item.append(content);
            csproj_xml.getroot().append(item);
        }
        // save file
        fs.writeFileSync(this.csproj_path, csproj_xml.write({indent:4}), 'utf-8');
    },
    // Returns an array of all the files in the given directory with reletive paths
    // - name     : the name of the top level directory (i.e all files will start with this in their path)
    // - path     : the directory whos contents will be listed under 'name' directory
    folder_contents:function(name, dir) {
        var results = [];
        var folder_dir = fs.readdirSync(dir);
        for(item in folder_dir) {
            var stat = fs.statSync(path.join(dir, folder_dir[item]));
            // means its a folder?
            if(stat.isDirectory()) {
                var sub_dir = this.folder_contents(path.join(name, folder_dir[item]), path.join(dir, folder_dir[item]));
                //Add all subfolder item paths
                for(sub_item in sub_dir) {
                    results.push(sub_dir[sub_item]);
                }
            }
            else {
                results.push(path.join(name, folder_dir[item]));
            }
        }
        return results;
    },
    staging_dir: function() {
        return path.join(this.wp7_proj_dir, '.staging', 'www');
    },

    update_staging: function() {
        var projectRoot = util.isCordova(this.wp7_proj_dir);
        if (fs.existsSync(this.staging_dir())) {
            var staging = path.join(this.staging_dir(), '*');
            shell.cp('-rf', staging, this.www_dir());
        }
    },

    // calls the nessesary functions to update the wp7 project
    // Returns a promise.
    update_project:function(cfg) {
        try {
            this.update_from_config(cfg);
        } catch(e) {
            return Q.reject(e);
        }
        // trigger an event in case anyone needs to modify the contents of the www folder before we package it.
        var that = this;
        var projectRoot = util.isCordova(process.cwd());
        var hooks = new hooker(projectRoot);

        return hooks.fire('pre_package', { wwwPath:this.www_dir() })
        .then(function() {
            that.update_csproj();
            // TODO: Add overrides support? Why is this missing?
            that.update_staging();
            util.deleteSvnFolders(that.www_dir());
        });
    }
};
<|endoftext|>


<commit_before>(function (Q, $) {
	/**
	 * @module Q-tools
	 */

	/**
	 * This tool show round process bar.
	 * @class Q pie
	 * @constructor
	 * @param {Object}   [options] Override various options for this tool
	 *  @param {Number}  [options.fraction] Value process
	 *  @param {Number}  [options.size] Circle size
	 *  @param {Object}  [options.bgImage] URL to image to put in background
	 *  @param {Object}  [options.color] Arc color
	 *  @param {Object}  [options.borderSize] Arc border size. The progress line width.
	 * @return {Q.Tool}
	 */
	Q.Tool.define("Q/pie", function (options) {
			var tool = this;
			var $toolElement = $(tool.element);
			var state = tool.state;
			options = options || {};

			Q.addStylesheet('{{Q}}/css/pie.css');

			// positioning tool box
			tool.positionParent();

			// rotate arcs according to fraction
			tool.Q.onStateChanged('fraction').set(function () {
				var angle = 360/(100/parseFloat(state.fraction));

				var arcLeftAngle = angle > 180 ? angle - 180 + 45 : 45;
				arcLeftAngle = angle > 360 ? 225 : arcLeftAngle;
				var arcLeftDisplay = arcLeftAngle > 45 ? "block" : "none"; // only for Chrome

				var arcRightAngle = angle < 180 ? angle + 45 : 180 + 45;
				arcRightAngle = angle < 0 ? 45 : arcRightAngle;

				$(".Q_pie_arc.Q_pie_arcLeft", $toolElement).css({transform: "rotate(" + arcLeftAngle + "deg)", display: arcLeftDisplay}); // Chrome incorrect calculate positions
				$(".Q_pie_arc.Q_pie_arcRight", $toolElement).css("transform", "rotate(" + arcRightAngle + "deg)");
			}, "Q/pie");

			// set new size
			tool.Q.onStateChanged('size').set(function () {
				var size = state.size;

				$(".Q_pie_box", $toolElement).css({width: size, height: size});
			}, "Q/pie");

			// set new Arc color
			tool.Q.onStateChanged('color').set(function () {
				var color = state.color;

				$(".Q_pie_arc.Q_pie_arcLeft", $toolElement).css("border-color", color + " " + color + " transparent transparent");
				$(".Q_pie_arc.Q_pie_arcRight", $toolElement).css("border-color", "transparent transparent " + color + " " + color);
			}, "Q/pie");

			// set new Arc borderSize
			tool.Q.onStateChanged('borderSize').set(function () {
				var borderSize = state.borderSize;

				$(".Q_pie_arc, .Q_pie_shield", $toolElement).css("border-width", borderSize);
			}, "Q/pie");

			tool.refresh();
		},

		{
			fraction: 0,
			size: 80,
			bgImage: "",
			color: 'red',
			borderSize: 5, // in px
			clickPos: {
				angle: 0,
				anglePercent: 0
			} // service param contain info about click event inside tool element
		},

		{
			refresh: function () {
				var tool = this;
				var state = tool.state;
				var $toolElement = $(tool.element);

				var bgImage = state.bgImage ? "background-image: url("+state.bgImage+")" : "";

				var fields = {
					bgImage: bgImage
				};

				Q.Template.render(
					'Q/pie/main',
					fields,
					function (err, html) {
						if (err) return;

						$toolElement.html(html);

						// set arcs rotate
						tool.stateChanged('fraction');

						// set pie size
						tool.stateChanged('size');

						// set Arc color
						tool.stateChanged('color');

						// set Arc borderSize
						tool.stateChanged('borderSize');

						// set toolElement click event
						$toolElement.on(Q.Pointer.click, function (event) {
							var x = event.pageX - $toolElement.offset().left;
							var y = event.pageY - $toolElement.offset().top;
							var toolWidth = $toolElement.width();
							var insideR = (toolWidth - state.borderSize * 2)/2; // radius of circle inside arcs
							var outsideR = toolWidth/2; // radius of circle
							var angle = Math.atan2(y - outsideR, x - outsideR)*180/Math.PI + 90;
							angle = angle > 0 ? angle : 360 + angle;
							var anglePercent = angle/360*100;

							state.clickPos.angle = angle;
							state.clickPos.anglePercent = anglePercent;

							if(Math.sqrt((x - outsideR) * (x - outsideR) + (y - outsideR) * (y - outsideR)) < insideR){
								state.clickPos.inside = true;
							}else{
								state.clickPos.inside = false;

								//state.fraction = anglePercent;
								//tool.stateChanged('fraction');
							}
						});
					}
				)
			},
			/**
			 * Positioning tool box in parent box
			 * @method positionParent
			 */
			positionParent: function(){
				var tool = this;

				// if size already set in params - exit
				if(tool.state.size) return;

				var parent = $(tool.element).parent();
				var parentW = parent.width();
				var parentH = parent.height();

				tool.state.size = parentW > parentH ? parentH : parentW;
			},
			/**
			 * Set pie to initial position
			 * @method initPos
			 */
			initPos: function(){
				var tool = this;

				tool.state.fraction = 0;
				tool.stateChanged('fraction');
			}
		}
	);

	Q.Template.set('Q/pie/main',
		'
'
		+ '

'
		+ '

'
		+ '

'
		+ '
'
	);

})(Q, jQuery);
<commit_msg>Fixed Q/pie tool.<commit_after>(function (Q, $) {
	/**
	 * @module Q-tools
	 */

	/**
	 * This tool show round process bar.
	 * @class Q pie
	 * @constructor
	 * @param {Object}   [options] Override various options for this tool
	 *  @param {Number}  [options.fraction] Value process
	 *  @param {Number}  [options.size] Circle size
	 *  @param {Object}  [options.bgImage] URL to image to put in background
	 *  @param {Object}  [options.color] Arc color
	 *  @param {Object}  [options.borderSize] Arc border size. The progress line width.
	 * @return {Q.Tool}
	 */
	Q.Tool.define("Q/pie", function (options) {
			var tool = this;
			var $toolElement = $(tool.element);
			var state = tool.state;
			options = options || {};

			Q.addStylesheet('{{Q}}/css/pie.css');

			// positioning tool box
			tool.positionParent();

			// rotate arcs according to fraction
			tool.Q.onStateChanged('fraction').set(function () {
				var angle = 360/(100/parseFloat(state.fraction));

				var arcLeftAngle = angle > 180 ? angle - 180 + 45 : 45;
				arcLeftAngle = angle > 360 ? 225 : arcLeftAngle;
				var arcLeftDisplay = arcLeftAngle > 45 ? "block" : "none"; // only for Chrome

				var arcRightAngle = angle < 180 ? angle + 45 : 180 + 45;
				arcRightAngle = angle < 0 ? 45 : arcRightAngle;

				$(".Q_pie_arc.Q_pie_arcLeft", $toolElement).css({transform: "rotate(" + arcLeftAngle + "deg)", display: arcLeftDisplay}); // Chrome incorrect calculate positions
				$(".Q_pie_arc.Q_pie_arcRight", $toolElement).css("transform", "rotate(" + arcRightAngle + "deg)");
			}, "Q/pie");

			// set new size
			tool.Q.onStateChanged('size').set(function () {
				var size = state.size;

				$(".Q_pie_box", $toolElement).css({width: size, height: size});
			}, "Q/pie");

			// set new Arc color
			tool.Q.onStateChanged('color').set(function () {
				var color = state.color;

				$(".Q_pie_arc.Q_pie_arcLeft", $toolElement).css("border-color", color + " " + color + " transparent transparent");
				$(".Q_pie_arc.Q_pie_arcRight", $toolElement).css("border-color", "transparent transparent " + color + " " + color);
			}, "Q/pie");

			// set new Arc borderSize
			tool.Q.onStateChanged('borderSize').set(function () {
				var borderSize = state.borderSize;

				$(".Q_pie_arc, .Q_pie_shield", $toolElement).css("border-width", borderSize);
			}, "Q/pie");

			tool.refresh();
		},

		{
			fraction: 0,
			size: 80,
			bgImage: "",
			color: 'red',
			borderSize: 5, // in px
			clickPos: {
				angle: 0,
				anglePercent: 0
			} // service param contain info about click event inside tool element
		},

		{
			refresh: function () {
				var tool = this;
				var state = tool.state;
				var $toolElement = $(tool.element);

				var bgImage = state.bgImage ? "background-image: url("+state.bgImage+")" : "";

				var fields = {
					bgImage: bgImage
				};

				Q.Template.render(
					'Q/pie/main',
					fields,
					function (err, html) {
						if (err) return;

						$toolElement.html(html);

						// set arcs rotate
						tool.stateChanged('fraction');

						// set pie size
						tool.stateChanged('size');

						// set Arc color
						tool.stateChanged('color');

						// set Arc borderSize
						tool.stateChanged('borderSize');

						var lastEvent = {};
						$toolElement.on('touchstart touchmove', function (event) {
							lastEvent = event;
						});

						// set toolElement click event
						$toolElement.on(Q.Pointer.fastclick, function (event) {
							var x = (Q.getObject(["originalEvent", "touches", 0, "pageX"], lastEvent) || event.pageX) - $toolElement.offset().left;
							var y = (Q.getObject(["originalEvent", "touches", 0, "pageY"], lastEvent) || event.pageY) - $toolElement.offset().top;
							var toolWidth = $toolElement.width();
							var insideR = (toolWidth - state.borderSize * 2)/2; // radius of circle inside arcs
							var outsideR = toolWidth/2; // radius of circle
							var angle = Math.atan2(y - outsideR, x - outsideR)*180/Math.PI + 90;
							angle = angle > 0 ? angle : 360 + angle;
							var anglePercent = angle/360*100;

							state.clickPos.angle = angle;
							state.clickPos.anglePercent = anglePercent;

							if(Math.sqrt((x - outsideR) * (x - outsideR) + (y - outsideR) * (y - outsideR)) < insideR){
								state.clickPos.inside = true;
							}else{
								state.clickPos.inside = false;

								//state.fraction = anglePercent;
								//tool.stateChanged('fraction');
							}
						});
					}
				)
			},
			/**
			 * Positioning tool box in parent box
			 * @method positionParent
			 */
			positionParent: function(){
				var tool = this;

				// if size already set in params - exit
				if(tool.state.size) return;

				var parent = $(tool.element).parent();
				var parentW = parent.width();
				var parentH = parent.height();

				tool.state.size = parentW > parentH ? parentH : parentW;
			},
			/**
			 * Set pie to initial position
			 * @method initPos
			 */
			initPos: function(){
				var tool = this;

				tool.state.fraction = 0;
				tool.stateChanged('fraction');
			}
		}
	);

	Q.Template.set('Q/pie/main',
		'
'
		+ '

'
		+ '

'
		+ '

'
		+ '
'
	);

})(Q, jQuery);
<|endoftext|>