codecombat/app/views/play/level/LevelPlaybackView.coffee

402 lines
14 KiB
CoffeeScript
Raw Normal View History

2014-07-17 20:20:11 -04:00
CocoView = require 'views/kinds/CocoView'
2014-01-03 13:32:13 -05:00
template = require 'templates/play/level/playback'
{me} = require 'lib/auth'
EditorConfigModal = require './modal/EditorConfigModal'
KeyboardShortcutsModal = require './modal/KeyboardShortcutsModal'
module.exports = class LevelPlaybackView extends CocoView
2014-06-30 22:16:26 -04:00
id: 'playback-view'
2014-01-03 13:32:13 -05:00
template: template
subscriptions:
'level:disable-controls': 'onDisableControls'
'level:enable-controls': 'onEnableControls'
'level:set-playing': 'onSetPlaying'
'level:toggle-playing': 'onTogglePlay'
'level:scrub-forward': 'onScrubForward'
'level:scrub-back': 'onScrubBack'
'level:set-volume': 'onSetVolume'
'level:set-debug': 'onSetDebug'
2014-01-03 13:32:13 -05:00
'surface:frame-changed': 'onFrameChanged'
'god:new-world-created': 'onNewWorld'
'god:streaming-world-updated': 'onNewWorld'
'level:set-letterbox': 'onSetLetterbox'
'tome:cast-spells': 'onTomeCast'
'playback:real-time-playback-ended': 'onRealTimePlaybackEnded'
'playback:stop-real-time-playback': 'onStopRealTimePlayback'
'real-time-multiplayer:manual-cast': 'onRealTimeMultiplayerCast'
2014-01-03 13:32:13 -05:00
events:
'click #debug-toggle': 'onToggleDebug'
'click #edit-wizard-settings': 'onEditWizardSettings'
'click #edit-editor-config': 'onEditEditorConfig'
'click #view-keyboard-shortcuts': 'onViewKeyboardShortcuts'
'click #music-button': 'onToggleMusic'
'click #zoom-in-button': -> Backbone.Mediator.publish 'camera:zoom-in', {} unless @shouldIgnore()
'click #zoom-out-button': -> Backbone.Mediator.publish 'camera:zoom-out', {} unless @shouldIgnore()
2014-01-03 13:32:13 -05:00
'click #volume-button': 'onToggleVolume'
'click #play-button': 'onTogglePlay'
'click': -> Backbone.Mediator.publish 'tome:focus-editor', {} unless @realTime
'mouseenter #timeProgress': 'onProgressEnter'
'mouseleave #timeProgress': 'onProgressLeave'
'mousemove #timeProgress': 'onProgressHover'
2014-01-03 13:32:13 -05:00
shortcuts:
'⌘+p, p, ctrl+p': 'onTogglePlay'
'⌘+[, ctrl+[': 'onScrubBack'
'⌘+⇧+[, ctrl+⇧+[': 'onSingleScrubBack'
'⌘+], ctrl+]': 'onScrubForward'
'⌘+⇧+], ctrl+⇧+]': 'onSingleScrubForward'
# popover that shows at the current mouse position on the progressbar, using the bootstrap popover.
# Could make this into a jQuery plugins itself theoretically.
class HoverPopup extends $.fn.popover.Constructor
constructor: () ->
@enabled = true
@shown = false
2014-06-30 22:16:26 -04:00
@type = 'HoverPopup'
@options =
placement: 'top'
container: 'body'
animation: true
html: true
delay:
show: 400
@$element = $('#timeProgress')
@$tip = $('#timePopover')
2014-06-30 22:16:26 -04:00
@content = ''
getContent: -> @content
show: ->
unless @shown
super()
@shown = true
updateContent: (@content) ->
@setContent()
@$tip.addClass('fade top in')
onHover: (@e) ->
pos = @getPosition()
actualWidth = @$tip[0].offsetWidth
actualHeight = @$tip[0].offsetHeight
calculatedOffset =
top: pos.top - actualHeight
left: pos.left + pos.width / 2 - actualWidth / 2
this.applyPlacement(calculatedOffset, 'top')
getPosition: ->
top: @$element.offset().top
left: if @e? then @e.pageX else @$element.offset().left
height: 0
width: 0
hide: ->
super()
@shown = false
disable: ->
super()
@hide()
2014-01-03 13:32:13 -05:00
constructor: ->
super(arguments...)
me.on('change:music', @updateMusicButton, @)
2014-01-03 13:32:13 -05:00
2014-02-11 17:24:06 -05:00
afterRender: ->
2014-01-03 13:32:13 -05:00
super()
@$progressScrubber = $('.scrubber .progress', @$el)
2014-01-03 13:32:13 -05:00
@hookUpScrubber()
@updateMusicButton()
2014-03-24 12:07:09 -04:00
$(window).on('resize', @onWindowResize)
ua = navigator.userAgent.toLowerCase()
if /safari/.test(ua) and not /chrome/.test(ua)
@$el.find('.toggle-fullscreen').hide()
@timePopup ?= new HoverPopup
t = $.i18n.t
@second = t 'units.second'
@seconds = t 'units.seconds'
@minute = t 'units.minute'
@minutes = t 'units.minutes'
@goto = t 'play_level.time_goto'
@current = t 'play_level.time_current'
@total = t 'play_level.time_total'
@$el.find('#play-button').css('visibility', 'hidden') if @options.levelID in ['dungeons-of-kithgard', 'gems-in-the-deep', 'shadow-guard', 'true-names'] # Don't show for first few levels, confuses new players.
2014-01-03 13:32:13 -05:00
updatePopupContent: ->
@timePopup?.updateContent "<h2>#{@timeToString @newTime}</h2>#{@formatTime(@current, @currentTime)}<br/>#{@formatTime(@total, @totalTime)}"
# These functions could go to some helper class
pad2: (num) ->
2014-06-30 22:16:26 -04:00
if not num? or num is 0 then '00' else ((if num < 10 then '0' else '') + num)
formatTime: (text, time) =>
"#{text}\t#{@timeToString time}"
timeToString: (time=0, withUnits=false) ->
mins = Math.floor(time / 60)
2014-03-29 20:30:12 -04:00
secs = (time - mins * 60).toFixed(1)
if withUnits
2014-06-30 22:16:26 -04:00
ret = ''
ret = (mins + ' ' + (if mins is 1 then @minute else @minutes)) if (mins > 0)
ret = (ret + ' ' + secs + ' ' + (if secs is 1 then @second else @seconds)) if (secs > 0 or mins is 0)
else
2014-03-29 20:30:12 -04:00
"#{mins}:#{@pad2 secs}"
2014-01-03 13:32:13 -05:00
# callbacks
updateMusicButton: ->
@$el.find('#music-button').toggleClass('music-on', me.get('music'))
onSetLetterbox: (e) ->
return if @realTime
@togglePlaybackControls !e.on
2014-01-03 13:32:13 -05:00
@disabled = e.on
togglePlaybackControls: (to) ->
buttons = @$el.find '#play-button, .scrubber-handle'
buttons.css 'visibility', if to then 'visible' else 'hidden'
onTomeCast: (e) ->
return unless e.realTime
2014-08-30 00:46:26 -04:00
@realTime = true
@togglePlaybackControls false
Backbone.Mediator.publish 'playback:real-time-playback-started', {}
Backbone.Mediator.publish 'audio-player:play-sound', trigger: 'real-time-playback-start', volume: 1
Backbone.Mediator.publish 'level:set-letterbox', on: true
onRealTimeMultiplayerCast: (e) ->
@realTime = true
@togglePlaybackControls false
2014-08-30 00:46:26 -04:00
Backbone.Mediator.publish 'playback:real-time-playback-waiting', {}
2014-01-03 13:32:13 -05:00
onWindowResize: (s...) =>
@barWidth = $('.progress', @$el).width()
2014-02-11 17:24:06 -05:00
onNewWorld: (e) ->
@updateBarWidth e.world.frames.length, e.world.maxTotalFrames, e.world.dt
updateBarWidth: (loadedFrameCount, maxTotalFrames, dt) ->
@totalTime = (loadedFrameCount - 1) * dt
pct = parseInt(100 * loadedFrameCount / (maxTotalFrames - 1)) + '%'
@barWidth = $('.progress', @$el).css('width', pct).show().width()
$('.scrubber .progress', @$el).slider('enable', true)
@newTime = 0
@currentTime = 0
@lastLoadedFrameCount = loadedFrameCount
2014-01-03 13:32:13 -05:00
onToggleDebug: ->
return if @shouldIgnore()
flag = $('#debug-toggle i.icon-ok')
Backbone.Mediator.publish('level:set-debug', {debug: flag.hasClass('invisible')})
2014-01-03 13:32:13 -05:00
onEditWizardSettings: ->
Backbone.Mediator.publish 'level:edit-wizard-settings', {}
2014-01-03 13:32:13 -05:00
onEditEditorConfig: ->
@openModalView new EditorConfigModal session: @options.session
onViewKeyboardShortcuts: ->
@openModalView new KeyboardShortcutsModal()
2014-02-11 17:24:06 -05:00
onDisableControls: (e) ->
2014-01-03 13:32:13 -05:00
if not e.controls or 'playback' in e.controls
@disabled = true
$('button', @$el).addClass('disabled')
try
@$progressScrubber.slider('disable', true)
catch error
console.warn('error disabling scrubber', error)
@timePopup?.disable()
2014-01-03 13:32:13 -05:00
$('#volume-button', @$el).removeClass('disabled')
2014-02-11 17:24:06 -05:00
onEnableControls: (e) ->
return if @realTime
2014-01-03 13:32:13 -05:00
if not e.controls or 'playback' in e.controls
@disabled = false
$('button', @$el).removeClass('disabled')
try
@$progressScrubber.slider('enable', true)
catch error
console.warn('error enabling scrubber', error)
@timePopup?.enable()
2014-01-03 13:32:13 -05:00
2014-02-11 17:24:06 -05:00
onSetPlaying: (e) ->
2014-01-03 13:32:13 -05:00
@playing = (e ? {}).playing ? true
button = @$el.find '#play-button'
ended = button.hasClass 'ended'
changed = button.hasClass('playing') isnt @playing
2014-01-03 13:32:13 -05:00
button.toggleClass('playing', @playing and not ended).toggleClass('paused', not @playing and not ended)
Backbone.Mediator.publish 'audio-player:play-sound', trigger: (if @playing then 'playback-play' else 'playback-pause'), volume: 1
2014-01-03 13:32:13 -05:00
return # don't stripe the bar
bar = @$el.find '.scrubber .progress'
bar.toggleClass('progress-striped', @playing and not ended).toggleClass('active', @playing and not ended)
onSetVolume: (e) ->
classes = ['vol-off', 'vol-down', 'vol-up']
button = $('#volume-button', @$el)
button.removeClass(c) for c in classes
button.addClass(classes[0]) if e.volume <= 0.0
button.addClass(classes[1]) if e.volume > 0.0 and e.volume < 1.0
button.addClass(classes[2]) if e.volume >= 1.0
onScrub: (e, options) ->
2014-08-28 20:08:05 -04:00
e?.preventDefault?()
options.scrubDuration = 500
Backbone.Mediator.publish('level:set-time', options)
onScrubForward: (e) ->
@onScrub e, ratioOffset: 0.05
onSingleScrubForward: (e) ->
@onScrub e, frameOffset: 1
2014-01-03 13:32:13 -05:00
onScrubBack: (e) ->
@onScrub e, ratioOffset: -0.05
onSingleScrubBack: (e) ->
@onScrub e, frameOffset: -1
2014-01-03 13:32:13 -05:00
onFrameChanged: (e) ->
if e.progress isnt @lastProgress
@currentTime = e.frame / e.world.frameRate
@updatePopupContent() if @timePopup?.shown
@updateProgress(e.progress, e.world)
2014-01-03 13:32:13 -05:00
@updatePlayButton(e.progress)
@lastProgress = e.progress
onProgressEnter: (e) ->
# Why it needs itself as parameter you ask? Ask Twitter instead.
@timePopup?.enter @timePopup
onProgressLeave: (e) ->
@timePopup?.leave @timePopup
onProgressHover: (e) ->
timeRatio = @$progressScrubber.width() / @totalTime
2014-07-15 12:35:14 -04:00
offsetX = e.offsetX or e.clientX - $(e.target).offset().left
@newTime = offsetX / timeRatio
@updatePopupContent()
@timePopup?.onHover e
# Show it instantaneously if close enough to current time.
if @timePopup and Math.abs(@currentTime - @newTime) < 1 and not @timePopup.shown
@timePopup.show()
updateProgress: (progress, world) ->
if world.frames.length isnt @lastLoadedFrameCount
@updateBarWidth world.frames.length, world.maxTotalFrames, world.dt
wasLoaded = @worldCompletelyLoaded
@worldCompletelyLoaded = world.frames.length is world.totalFrames
if @realTime and @worldCompletelyLoaded and not wasLoaded
Backbone.Mediator.publish 'playback:real-time-playback-ended', {}
Backbone.Mediator.publish 'level:set-letterbox', on: false
2014-08-22 17:59:32 -04:00
$('.scrubber .progress-bar', @$el).css('width', "#{progress * 100}%")
2014-01-03 13:32:13 -05:00
updatePlayButton: (progress) ->
if @worldCompletelyLoaded and progress >= 0.99 and @lastProgress < 0.99
2014-01-03 13:32:13 -05:00
$('#play-button').removeClass('playing').removeClass('paused').addClass('ended')
Backbone.Mediator.publish 'level:set-letterbox', on: false if @realTime
Backbone.Mediator.publish 'playback:real-time-playback-ended', {} if @realTime
if progress < 0.99 and @lastProgress >= 0.99
2014-01-03 13:32:13 -05:00
b = $('#play-button').removeClass('ended')
if @playing then b.addClass('playing') else b.addClass('paused')
onRealTimePlaybackEnded: (e) ->
return unless @realTime
@realTime = false
@togglePlaybackControls true
Backbone.Mediator.publish 'audio-player:play-sound', trigger: 'real-time-playback-end', volume: 1
onStopRealTimePlayback: (e) ->
Backbone.Mediator.publish 'level:set-letterbox', on: false
Backbone.Mediator.publish 'playback:real-time-playback-ended', {}
2014-01-03 13:32:13 -05:00
onSetDebug: (e) ->
flag = $('#debug-toggle i.icon-ok')
flag.toggleClass 'invisible', not e.debug
2014-01-03 13:32:13 -05:00
# to refactor
hookUpScrubber: ->
@sliderIncrements = 500 # max slider width before we skip pixels
@$progressScrubber.slider(
2014-01-03 13:32:13 -05:00
max: @sliderIncrements
2014-06-30 22:16:26 -04:00
animate: 'slow'
slide: (event, ui) =>
return if @shouldIgnore()
++@slideCount
oldRatio = @getScrubRatio()
@scrubTo ui.value / @sliderIncrements
if ratioChange = @getScrubRatio() - oldRatio
sound = "playback-scrub-slide-#{if ratioChange > 0 then 'forward' else 'back'}-#{@slideCount % 3}"
Backbone.Mediator.publish 'audio-player:play-sound', trigger: sound, volume: Math.min 1, Math.abs ratioChange * 50
start: (event, ui) =>
return if @shouldIgnore()
@slideCount = 0
@wasPlaying = @playing and not $('#play-button').hasClass('ended')
Backbone.Mediator.publish 'level:set-playing', {playing: false}
Backbone.Mediator.publish 'audio-player:play-sound', trigger: 'playback-scrub-start', volume: 0.5
2014-09-11 14:08:25 -04:00
2014-01-03 13:32:13 -05:00
stop: (event, ui) =>
return if @shouldIgnore()
2014-01-03 13:32:13 -05:00
@actualProgress = ui.value / @sliderIncrements
Backbone.Mediator.publish 'playback:manually-scrubbed', ratio: @actualProgress # For scripts
Backbone.Mediator.publish 'level:set-playing', {playing: @wasPlaying}
if @slideCount < 3
2014-01-03 13:32:13 -05:00
@wasPlaying = false
Backbone.Mediator.publish 'level:set-playing', {playing: false}
2014-01-03 13:32:13 -05:00
@$el.find('.scrubber-handle').effect('bounce', {times: 2})
else
Backbone.Mediator.publish 'audio-player:play-sound', trigger: 'playback-scrub-end', volume: 0.5
2014-09-11 14:08:25 -04:00
2014-01-03 13:32:13 -05:00
)
getScrubRatio: ->
@$progressScrubber.find('.progress-bar').width() / @$progressScrubber.width()
2014-01-03 13:32:13 -05:00
scrubTo: (ratio, duration=0) ->
return if @shouldIgnore()
Backbone.Mediator.publish 'level:set-time', ratio: ratio, scrubDuration: duration
2014-01-03 13:32:13 -05:00
shouldIgnore: -> return @disabled or @realTime
2014-01-03 13:32:13 -05:00
onTogglePlay: (e) ->
2014-08-28 20:08:05 -04:00
e?.preventDefault?()
2014-01-03 13:32:13 -05:00
return if @shouldIgnore()
button = $('#play-button')
willPlay = button.hasClass('paused') or button.hasClass('ended')
Backbone.Mediator.publish 'level:set-playing', playing: willPlay
2014-01-03 13:32:13 -05:00
$(document.activeElement).blur()
onToggleVolume: (e) ->
button = $(e.target).closest('#volume-button')
classes = ['vol-off', 'vol-down', 'vol-up']
volumes = [0, 0.4, 1.0]
for oldClass, i in classes
if button.hasClass oldClass
newI = (i + 1) % classes.length
break
else if i is classes.length - 1 # no oldClass
newI = 2
Backbone.Mediator.publish 'level:set-volume', volume: volumes[newI]
2014-01-03 13:32:13 -05:00
$(document.activeElement).blur()
onToggleMusic: (e) ->
e?.preventDefault()
me.set('music', not me.get('music', true))
me.patch()
$(document.activeElement).blur()
destroy: ->
me.off('change:music', @updateMusicButton, @)
$(window).off('resize', @onWindowResize)
@onWindowResize = null
super()