Files @ 6b535f723a45
Branch filter:

Location: light9/light9/web/timeline/timeline.coffee

drewp@bigasterisk.com
fix effect resources in notes
Ignore-this: 9ad7cbd26bdbaa558206b84b405f2fb3
   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
log = console.log
RDF = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#'
Drawing = window.Drawing
ROW_COUNT = 7

# polymer dom-repeat is happy to shuffle children by swapping their
# attribute values, and it's hard to correctly setup/teardown your
# side effects if your attributes are changing before the detach
# call. This alternative to dom-repeat never reassigns
# attributes. But, it can't set up property bindings.
updateChildren = (parent, newUris, makeChild) ->
  childUris = []
  childByUri = {}
  for e in parent.children
    childUris.push(e.uri)
    childByUri[e.uri] = e

  for uri in _.difference(childUris, newUris)
    childByUri[uri].detached()
    ko.removeNode(childByUri[uri])
  for uri in _.difference(newUris, childUris)
    parent.appendChild(makeChild(uri))


Polymer
  is: 'light9-timeline-editor'
  behaviors: [ Polymer.IronResizableBehavior ]
  properties:
    viewState: { type: Object }
    debug: {type: String}
    graph: {type: Object, notify: true}
    setAdjuster: {type: Function, notify: true}
    playerSong: {type: String, notify: true}
    followPlayerSong: {type: Boolean, notify: true, value: true}
    song: {type: String, notify: true}
    show: {value: 'http://light9.bigasterisk.com/show/dance2017'}
    songTime: {type: Number, notify: true, observer: '_onSongTime'}
    songDuration: {type: Number, notify: true, observer: '_onSongDuration'}
    songPlaying: {type: Boolean, notify: true}
    fullZoomX: {type: Object, notify: true}
    zoomInX: {type: Object, notify: true}
    selection: {type: Object, notify: true}
  width: ko.observable(1)
  listeners:
    'iron-resize': '_onIronResize'
  observers: [
    'setSong(playerSong, followPlayerSong)'
    ]
  _onIronResize: ->
    @width(@offsetWidth)
  _onSongTime: (t) ->
    @viewState.cursor.t(t)
  _onSongDuration: (d) ->
    d = 700 if d < 1 # bug is that asco isn't giving duration, but 0 makes the scale corrupt
    @viewState.zoomSpec.duration(d)
  setSong: (s) ->
    @song = @playerSong if @followPlayerSong

  ready: ->
    ko.options.deferUpdates = true;
    @selection = {hover: ko.observable(null), selected: ko.observable([])}

    window.debug_zoomOrLayoutChangedCount = 0
    window.debug_adjUpdateDisplay = 0
    
    @viewState =
      zoomSpec:
        duration: ko.observable(100) # current song duration
        t1: ko.observable(0) # need validation to stay in bounds and not go too close
        t2: ko.observable(100)
      cursor:
        t: ko.observable(20)
      mouse:
        pos: ko.observable($V([0,0]))
    @fullZoomX = d3.scaleLinear()
    @zoomInX = d3.scaleLinear()
    @setAdjuster = @$.adjustersCanvas.setAdjuster.bind(@$.adjustersCanvas)

    setInterval(@updateDebugSummary.bind(@), 100)

    #if anchor == loadtest
    #  add note and delete it repeatedly
    #  disconnect the graph, make many notes, drag a point over many steps, measure lag somewhere

  updateDebugSummary: ->
    elemCount = (tag) -> document.getElementsByTagName(tag).length
    @debug = "#{window.debug_zoomOrLayoutChangedCount} layout change,
     #{elemCount('light9-timeline-note')} notes,
     #{@selection.selected().length} selected
     #{elemCount('light9-timeline-graph-row')} rows,
     #{window.debug_adjsCount} adjuster items registered,
     #{window.debug_adjUpdateDisplay} adjuster updateDisplay calls,
    "
    
  attached: ->
    @dia = @$.dia
    ko.computed(@zoomOrLayoutChanged.bind(@))
    ko.computed(@songTimeChanged.bind(@))

    @trackMouse()
    @bindKeys()
    @bindWheelZoom(@dia.querySelector('svg'))
    @forwardMouseEventsToAdjustersCanvas()

    @makeZoomAdjs()

    zoomed = @$.zoomed
    setupDrop(@$.dia.querySelector('svg'), zoomed.$.rows, @, zoomed.onDrop.bind(zoomed))


  zoomOrLayoutChanged: ->
    log('zoomOrLayoutChanged')
    # not for cursor updates

    vs = @viewState
    
    if vs.zoomSpec.t1() < 0
      vs.zoomSpec.t1(0)
    if vs.zoomSpec.duration() and vs.zoomSpec.t2() > vs.zoomSpec.duration()
      vs.zoomSpec.t2(vs.zoomSpec.duration())

    window.debug_zoomOrLayoutChangedCount++
    @fullZoomX.domain([0, vs.zoomSpec.duration()])
    @fullZoomX.range([0, @width()])

    # had trouble making notes update when this changes
    zoomInX = d3.scaleLinear()
    zoomInX.domain([vs.zoomSpec.t1(), vs.zoomSpec.t2()])
    zoomInX.range([0, @width()])
    @zoomInX = zoomInX

    # todo: these run a lot of work purely for a time change
    @dia.setTimeAxis(@width(), @$.zoomed.$.audio.offsetTop, @zoomInX)
    @$.adjustersCanvas.updateAllCoords()

    # cursor needs update when layout changes, but I don't want
    # zoom/layout to depend on the playback time
    setTimeout(@songTimeChanged.bind(@), 1)

  songTimeChanged: ->
    @$.cursorCanvas.setCursor(@$.audio.offsetTop, @$.audio.offsetHeight,
                              @$.zoomed.$.time.offsetTop,
                              @$.zoomed.$.time.offsetHeight,
                              @fullZoomX, @zoomInX, @viewState.cursor)
    
  trackMouse: ->
    # not just for show- we use the mouse pos sometimes
    for evName in ['mousemove', 'touchmove']
      @addEventListener evName, (ev) =>
        ev.preventDefault()

        # todo: consolidate with _editorCoordinates version
        if ev.touches?.length
          ev = ev.touches[0]

        @root = @getBoundingClientRect()
        @viewState.mouse.pos($V([ev.pageX - @root.left, ev.pageY - @root.top]))

        @$.cursorCanvas.setMouse(@viewState.mouse.pos())
        # should be controlled by a checkbox next to follow-player-song-choice
        @sendMouseToVidref() unless window.location.hash.match(/novidref/)

  sendMouseToVidref: ->
    now = Date.now()
    if (!@$.vidrefLastSent? || @$.vidrefLastSent < now - 200) && !@songPlaying
      @$.vidrefTime.body = {t: @latestMouseTime(), source: 'timeline'}
      @$.vidrefTime.generateRequest()
      @$.vidrefLastSent = now

  latestMouseTime: ->
    @zoomInX.invert(@viewState.mouse.pos().e(1))

  bindWheelZoom: (elem) ->
    elem.addEventListener 'mousewheel', (ev) =>
      zs = @viewState.zoomSpec

      center = @latestMouseTime()
      left = center - zs.t1()
      right = zs.t2() - center
      scale = Math.pow(1.005, ev.deltaY)

      zs.t1(center - left * scale)
      zs.t2(center + right * scale)

  forwardMouseEventsToAdjustersCanvas: ->
    ac = @$.adjustersCanvas
    @addEventListener('mousedown', ac.onDown.bind(ac))
    @addEventListener('mousemove', ac.onMove.bind(ac))
    @addEventListener('mouseup', ac.onUp.bind(ac))

  animatedZoom: (newT1, newT2, secs) ->
    fps = 30
    oldT1 = @viewState.zoomSpec.t1()
    oldT2 = @viewState.zoomSpec.t2()
    lastTime = 0
    for step in [0..secs * fps]
      frac = step / (secs * fps)
      do (frac) =>
        gotoStep = =>
          @viewState.zoomSpec.t1((1 - frac) * oldT1 + frac * newT1)
          @viewState.zoomSpec.t2((1 - frac) * oldT2 + frac * newT2)
        delay = frac * secs * 1000
        setTimeout(gotoStep, delay)
        lastTime = delay
    setTimeout(=>
        @viewState.zoomSpec.t1(newT1)
        @viewState.zoomSpec.t2(newT2)
      , lastTime + 10)  
    
  bindKeys: ->
    shortcut.add "Ctrl+P", (ev) =>
      @$.music.seekPlayOrPause(@latestMouseTime())

    zoomAnimSec = .1
    shortcut.add "Ctrl+Escape", =>
      @animatedZoom(0, @viewState.zoomSpec.duration(), zoomAnimSec)
    shortcut.add "Shift+Escape", =>
      @animatedZoom(@songTime - 2, @viewState.zoomSpec.duration(), zoomAnimSec)
    shortcut.add "Escape", =>
      zs = @viewState.zoomSpec
      visSeconds = zs.t2() - zs.t1()
      margin = visSeconds * .4
      # buggy: really needs t1/t2 to limit their ranges
      if @songTime < zs.t1() or @songTime > zs.t2() - visSeconds * .6
        newCenter = @songTime + margin
        @animatedZoom(newCenter - visSeconds / 2,
                      newCenter + visSeconds / 2, zoomAnimSec)
    shortcut.add "L", =>
      @$.adjustersCanvas.updateAllCoords()
    shortcut.add 'Delete', =>
      for note in @selection.selected()
        deleteNote(@graph, @song, note, @selection)

  makeZoomAdjs: ->
    yMid = => @$.audio.offsetTop + @$.audio.offsetHeight / 2
    dur = @viewState.zoomSpec.duration
    
    valForPos = (pos) =>
        x = pos.e(1)
        t = @fullZoomX.invert(x)
    @setAdjuster('zoom-left', => new AdjustableFloatObservable({
      observable: @viewState.zoomSpec.t1,
      getTarget: () =>
        $V([@fullZoomX(@viewState.zoomSpec.t1()), yMid()])
      getSuggestedTargetOffset: () => $V([50, 0])
      getValueForPos: valForPos
    }))

    @setAdjuster('zoom-right', => new AdjustableFloatObservable({
      observable: @viewState.zoomSpec.t2,
      getTarget: () =>
        $V([@fullZoomX(@viewState.zoomSpec.t2()), yMid()])
      getSuggestedTargetOffset: () => $V([-50, 0])
      getValueForPos: valForPos
    }))

    panObs = ko.pureComputed({
        read: () =>
          (@viewState.zoomSpec.t1() + @viewState.zoomSpec.t2()) / 2
        write: (value) =>
          zs = @viewState.zoomSpec
          span = zs.t2() - zs.t1()
          zs.t1(value - span / 2)
          zs.t2(value + span / 2)
      })

    @setAdjuster('zoom-pan', => new AdjustableFloatObservable({
      observable: panObs
      emptyBox: true
      # fullzoom is not right- the sides shouldn't be able to go
      # offscreen
      getTarget: () => $V([@fullZoomX(panObs()), yMid()])
      getSuggestedTargetOffset: () => $V([0, 0])
      getValueForPos: valForPos
      }))
      

# plan: in here, turn all the notes into simple js objects with all
# their timing data and whatever's needed for adjusters. From that, do
# the brick layout. update only changing adjusters.
Polymer
  is: 'light9-timeline-time-zoomed'
  behaviors: [ Polymer.IronResizableBehavior ]
  properties:
    graph: { type: Object, notify: true }
    selection: { type: Object, notify: true }
    dia: { type: Object, notify: true }
    song: { type: String, notify: true }
    zoomInX: { type: Object, notify: true }
    rows: { value: [0...ROW_COUNT] }
    zoom: { type: Object, notify: true, observer: 'onZoom' } # viewState.zoomSpec
    zoomFlattened: { type: Object, notify: true }
  onZoom: ->
    updateZoomFlattened = ->
      log('updateZoomFlattened')
      @zoomFlattened = ko.toJS(@zoom)
    ko.computed(updateZoomFlattened.bind(@))
  ready: ->

  attached: ->
    root = @closest('light9-timeline-editor')

  onDrop: (effect, pos) ->
    U = (x) => @graph.Uri(x)

    # we could probably accept some initial overrides right on the
    # effect uri, maybe as query params

    if not @graph.contains(effect, RDF + 'type', U(':Effect'))
      if @graph.contains(effect, RDF + 'type', U(':LightSample'))
        effect = @makeEffect(effect)
      else
        log("drop #{effect} is not an effect")
        return

    dropTime = @zoomInX.invert(pos.e(1))
    @makeNewNote(effect, dropTime)

  makeEffect: (uri) ->
    U = (x) => @graph.Uri(x)
    effect = U(uri + '/effect')
    quad = (s, p, o) => {subject: s, predicate: p, object: o, graph: effect}
    
    quads = [
      quad(effect, U('rdf:type'), U(':Effect')),
      quad(effect, U(':copiedFrom'), uri),
      quad(effect, U('rdfs:label'), @graph.Literal(uri.replace(/.*capture\//, ''))),
      quad(effect, U(':publishAttr'), U(':strength')),
      ]

    fromSettings = @graph.objects(uri, U(':setting'))

    toSettings = @graph.nextNumberedResources(effect + '_set', fromSettings.length)
      
    for fs in fromSettings
      ts = toSettings.pop()
      # full copies of these since I may have to delete captures
      quads.push(quad(effect, U(':setting'), ts))
      quads.push(quad(ts, U(':device'), @graph.uriValue(fs, U(':device'))))
      quads.push(quad(ts, U(':deviceAttr'), @graph.uriValue(fs, U(':deviceAttr'))))
      try
        quads.push(quad(ts, U(':value'), @graph.uriValue(fs, U(':value'))))
      catch
        quads.push(quad(ts, U(':scaledValue'), @graph.uriValue(fs, U(':scaledValue'))))

    @graph.applyAndSendPatch({delQuads: [], addQuads: quads})
    return effect
        
  makeNewNote: (effect, dropTime) ->
    U = (x) => @graph.Uri(x)
    quad = (s, p, o) => {subject: s, predicate: p, object: o, graph: @song}
      
    newNote = @graph.nextNumberedResource("#{@song}/n")
    newCurve = @graph.nextNumberedResource("#{newNote}c")
    points = @graph.nextNumberedResources("#{newCurve}p", 4)

    curveQuads = [
        quad(@song, U(':note'), newNote)
        quad(newNote, RDF + 'type', U(':Note'))
        quad(newNote, U(':originTime'), @graph.LiteralRoundedFloat(dropTime))
        quad(newNote, U(':effectClass'), effect)
        quad(newNote, U(':curve'), newCurve)
        quad(newCurve, RDF + 'type', U(':Curve'))
        quad(newCurve, U(':attr'), U(':strength'))
      ]        
    pointQuads = []

    desiredWidthX = @offsetWidth * .3
    desiredWidthT = @zoomInX.invert(desiredWidthX) - @zoomInX.invert(0)
    desiredWidthT = Math.min(desiredWidthT, @zoom.duration() - dropTime)
    
    for i in [0...4]
      pt = points[i]
      pointQuads.push(quad(newCurve, U(':point'), pt))
      pointQuads.push(quad(pt, U(':time'), @graph.LiteralRoundedFloat(i/3 * desiredWidthT)))
      pointQuads.push(quad(pt, U(':value'), @graph.LiteralRoundedFloat(i == 1 or i == 2)))

    patch = {
      delQuads: []
      addQuads: curveQuads.concat(pointQuads)
      }
    @graph.applyAndSendPatch(patch)

Polymer
  is: "light9-timeline-time-axis",
  # for now since it's just one line calling dia,
  # light9-timeline-editor does our drawing work.


Polymer
  is: 'light9-timeline-graph-row'
  behaviors: [ Polymer.IronResizableBehavior ]
  properties:
    graph: { type: Object, notify: true }
    dia: { type: Object, notify: true }
    song:  { type: String, notify: true }
    zoomInX: { type: Object, notify: true }
    noteUris: { type: Array, notify: true }
    rowIndex: { type: Object, notify: true }
    selection: { type: Object, notify: true }
  observers: [
    'onGraph(graph, dia, setAdjuster, song, zoomInX)'
    'observedUpdate(graph, song, rowIndex)'
    'onZoom(zoomInX)'
    ]
  onGraph: ->
    @graph.runHandler(@update.bind(@), "row notes #{@rowIndex}")

  observedUpdate: (graph, song, rowIndex) ->
    @update() # old behavior
    #@graph.runHandler(@update.bind(@), "row notes #{@rowIndex}")

  update: (patch) ->
    U = (x) => @graph.Uri(x)

    notesForThisRow = []
    i = 0
    for n in _.sortBy(@graph.objects(@song, U(':note')), 'uri')
      if (i % ROW_COUNT) == @rowIndex
        notesForThisRow.push(n)
      i++

    updateChildren @, notesForThisRow, (newUri) =>
      child = document.createElement('light9-timeline-note')
      child.graph = @graph
      child.selection = @selection
      child.dia = @dia
      child.uri = newUri
      child.setAdjuster = @setAdjuster
      child.song = @song # could change, but all the notes will be rebuilt
      child.zoomInX = @zoomInX # missing binding; see onZoom
      return child      

  onZoom: ->
    for e in @children
      e.zoomInX = @zoomInX


Polymer
  is: 'light9-timeline-note'
  behaviors: [ Polymer.IronResizableBehavior ]
  listeners: 'iron-resize': 'update'
  properties:
    graph: { type: Object, notify: true }
    selection: { type: Object, notify: true }
    dia: { type: Object, notify: true }
    uri: { type: String, notify: true }
    zoomInX: { type: Object, notify: true }
    setAdjuster: {type: Function, notify: true }
    inlineRect: { type: Object, notify: true }
    song: { type: String, notify: true }
  observers: [
    'onUri(graph, dia, uri, zoomInX, setAdjuster, song)'
    'update(graph, dia, uri, zoomInX, setAdjuster, song)'
    ]
  ready: ->
    @adjusterIds = {} # id : true

  detached: ->
    log('detatch', @uri)
    @dia.clearNote(@uri)
    @isDetached = true
    @clearAdjusters()

  clearAdjusters: ->
    for i in Object.keys(@adjusterIds)
      @setAdjuster(i, null)

  onUri: ->
    @graph.runHandler(@update.bind(@), "note updates #{@uri}")

  patchCouldAffectMe: (patch) ->
    if patch and patch.addQuads # sometimes patch is a polymer-sent value. @update is used as a listener too
      if patch.addQuads.length == patch.delQuads.length == 1
        add = patch.addQuads[0]
        del = patch.delQuads[0]
        if (add.predicate == del.predicate == @graph.Uri(':time') and
            add.subject == del.subject)
          timeEditFor = add.subject
          if @worldPts and timeEditFor not in @pointUris
            return false
    return true
            
  update: (patch) ->
    # update our note DOM and SVG elements based on the graph
    if not @patchCouldAffectMe(patch)
      # as autodep still fires all handlers on all patches, we just
      # need any single dep to cause another callback. (without this,
      # we would no longer be registered at all)
      @graph.subjects(@uri, @uri, @uri)
      return
    if @isDetached?
      return

    @_updateDisplay()

  _updateDisplay: ->
    U = (x) => @graph.Uri(x)

    # @offsetTop causes some CSS layout to run!
    yForV = (v) => @offsetTop + (1 - v) * @offsetHeight

    originTime = @graph.floatValue(@uri, U(':originTime'))
    effect = @graph.uriValue(@uri, U(':effectClass'))
    for curve in @graph.objects(@uri, U(':curve'))
      if @graph.uriValue(curve, U(':attr')) == U(':strength')

        [@pointUris, @worldPts] = @_getCurvePoints(curve, originTime)
        curveWidthCalc = () => @_curveWidth(@worldPts)
    
        screenPts = ($V([@zoomInX(pt.e(1)), @offsetTop + (1 - pt.e(2)) * @offsetHeight]) for pt in @worldPts)
    
        @dia.setNote(@uri, screenPts, effect)
        @_updateAdjusters(screenPts, curveWidthCalc, yForV, U(@song))
        @_updateInlineAttrs(screenPts)
        
  _updateAdjusters: (screenPts, curveWidthCalc, yForV, ctx) ->   
    if screenPts[screenPts.length - 1].e(1) - screenPts[0].e(1) < 100
      @clearAdjusters()
    else
      @_makeOffsetAdjuster(yForV, curveWidthCalc, ctx)
      @_makeCurvePointAdjusters(yForV, @worldPts, ctx)
      @_makeFadeAdjusters(yForV, ctx)

  _updateInlineAttrs: (screenPts) ->
    leftX = Math.max(2, screenPts[Math.min(1, screenPts.length - 1)].e(1) + 5)
    rightX = screenPts[Math.min(2, screenPts.length - 1)].e(1) - 5
    if screenPts.length < 3
      rightX = leftX + 120
    w = 250
    h = 110
    wasHidden = @inlineRect?.display == 'none'
    @inlineRect = {
      left: leftX,
      top: @offsetTop + @offsetHeight - h - 5,
      width: w,
      height: h,
      display: if rightX - leftX > w then 'block' else 'none'
      }
    if wasHidden and @inlineRect.display != 'none'
      @async =>
        @querySelector('light9-timeline-note-inline-attrs')?.displayed()
    
  _getCurvePoints: (curve, xOffset) ->
    worldPts = []
    uris = @graph.objects(curve, @graph.Uri(':point'))
    for pt in uris
      v = $V([xOffset + @graph.floatValue(pt, @graph.Uri(':time')),
              @graph.floatValue(pt, @graph.Uri(':value'))])
      v.uri = pt
      worldPts.push(v)
    worldPts.sort((a,b) -> a.e(1) > b.e(1))
    return [uris, worldPts]

  _curveWidth: (worldPts) ->
    tMin = @graph.floatValue(worldPts[0].uri, @graph.Uri(':time'))
    tMax = @graph.floatValue(worldPts[3].uri, @graph.Uri(':time'))
    tMax - tMin
    
  _makeCurvePointAdjusters: (yForV, worldPts, ctx) ->
    for pointNum in [0...worldPts.length]
      @_makePointAdjuster(yForV, worldPts, pointNum, ctx)

  _makePointAdjuster: (yForV, worldPts, pointNum, ctx) ->
    U = (x) => @graph.Uri(x)

    adjId = @uri + '/p' + pointNum
    @adjusterIds[adjId] = true
    @setAdjuster adjId, =>
      adj = new AdjustableFloatObject({
        graph: @graph
        subj: worldPts[pointNum].uri
        pred: U(':time')
        ctx: ctx
        getTargetPosForValue: (value) =>
          $V([@zoomInX(value), yForV(worldPts[pointNum].e(2))])
        getValueForPos: (pos) =>
          origin = @graph.floatValue(@uri, U(':originTime'))
          (@zoomInX.invert(pos.e(1)) - origin)
        getSuggestedTargetOffset: () => @_suggestedOffset(worldPts[pointNum]),
      })
      adj._getValue = (=>
        # note: don't use originTime from the closure- we need the
        # graph dependency
        adj._currentValue + @graph.floatValue(@uri, U(':originTime'))
        )
      adj

  _makeOffsetAdjuster: (yForV, curveWidthCalc, ctx) ->
    U = (x) => @graph.Uri(x)

    adjId = @uri + '/offset'
    @adjusterIds[adjId] = true
    @setAdjuster adjId, => 
      adj = new AdjustableFloatObject({
        graph: @graph
        subj: @uri
        pred: U(':originTime')
        ctx: ctx
        getDisplayValue: (v, dv) => "o=#{dv}"
        getTargetPosForValue: (value) =>
          # display bug: should be working from pt[0].t, not from origin
          $V([@zoomInX(value + curveWidthCalc() / 2), yForV(.5)])
        getValueForPos: (pos) =>
          @zoomInX.invert(pos.e(1)) - curveWidthCalc() / 2
        getSuggestedTargetOffset: () => $V([-10, 0])
      })
      adj

  _makeFadeAdjusters: (yForV, ctx) ->
    @_makeFadeAdjuster(yForV, ctx, @uri + '/fadeIn', 0, 1, $V([-50, -10]))
    n = @worldPts.length
    @_makeFadeAdjuster(yForV, ctx, @uri + '/fadeOut', n - 2, n - 1, $V([50, -10]))

  _makeFadeAdjuster: (yForV, ctx, adjId, i0, i1, offset) ->
    @adjusterIds[adjId] = true
    @setAdjuster adjId, => new AdjustableFade(yForV, i0, i1, @, offset, ctx)
    
  _suggestedOffset: (pt) ->
    if pt.e(2) > .5
      $V([0, 30])
    else
      $V([0, -30])
    
    

Polymer
  is: "light9-timeline-note-inline-attrs"
  properties:
    graph: { type: Object, notify: true }
    song: { type: String, notify: true }
    uri: { type: String, notify: true }  # the Note
    rect: { type: Object, notify: true }
    effect: { type: String, notify: true }
    colorScale: { type: String, notify: true }
    noteLabel: { type: String, notify: true }
    selection: { type: Object, notify: true }
  observers: [
    'addHandler(graph, uri)'
    'onColorScale(graph, uri, colorScale)'
    ]
  displayed: ->
    @querySelector('light9-color-picker').displayed()
  onColorScale: ->
    U = (x) => @graph.Uri(x)
    if @colorScale == @colorScaleFromGraph
      return
    @editAttr(@song, @uri, U(':colorScale'), @graph.Literal(@colorScale))

  editAttr: (song, note, attr, value) ->
    U = (x) => @graph.Uri(x)
    if not song?
      log("can't edit inline attr yet, no song")
      return
    quad = (s, p, o) => {subject: s, predicate: p, object: o, graph: song}

    existingColorScaleSetting = null
    for setting in @graph.objects(note, U(':setting'))
      ea = @graph.uriValue(setting, U(':effectAttr'))
      if ea == attr
        existingColorScaleSetting = setting
        
    if existingColorScaleSetting
      @graph.patchObject(existingColorScaleSetting, U(':value'), value, song)
    else
      setting = @graph.nextNumberedResource(note + 'set')
      patch = {delQuads: [], addQuads: [
        quad(note, U(':setting'), setting)
        quad(setting, U(':effectAttr'), attr)
        quad(setting, U(':value'), value)
        ]}
      @graph.applyAndSendPatch(patch)
    
  addHandler: ->
    @graph.runHandler(@update.bind(@), "update inline attrs #{@uri}")
    
  update: ->
    #console.time('attrs update')
    U = (x) => @graph.Uri(x)
    @effect = @graph.uriValue(@uri, U(':effectClass'))
    @noteLabel = @uri.replace(/.*\//, '')

    existingColorScaleSetting = null
    for setting in @graph.objects(@uri, U(':setting'))
      ea = @graph.uriValue(setting, U(':effectAttr'))
      value = @graph.stringValue(setting, U(':value'))
      if ea == U(':colorScale')
        @colorScaleFromGraph = value
        @colorScale = value
        existingColorScaleSetting = setting
    if existingColorScaleSetting == null
      @colorScaleFromGraph = '#ffffff'
      @colorScale = '#ffffff'
    #console.timeEnd('attrs update')


  onDel: ->
    deleteNote(@graph, @song, @uri, @selection)


deleteNote = (graph, song, note, selection) ->
  patch = {delQuads: [{subject: song, predicate: graph.Uri(':note'), object: note, graph: song}], addQuads: []}
  graph.applyAndSendPatch(patch)
  if note in selection.selected()
    selection.selected(_.without(selection.selected(), note))
  

Polymer
  is: 'light9-cursor-canvas'
  behaviors: [ Polymer.IronResizableBehavior ]
  listeners: 'iron-resize': 'update'

  ready: ->
    @mouseX = 0
    @mouseY = 0
    @cursorPath = null
    @ctx = @$.canvas.getContext('2d')

  update: (ev) ->
    @$.canvas.width = ev.target.offsetWidth
    @$.canvas.height = ev.target.offsetHeight
    @redraw()

  setMouse: (pos) ->
    @mouseX = pos.e(1)
    @mouseY = pos.e(2)
    @redraw()

  setCursor: (y1, h1, y2, h2, fullZoomX, zoomInX, cursor) ->
    
    xZoomedOut = fullZoomX(cursor.t())
    xZoomedIn = zoomInX(cursor.t())

    @cursorPath = {
      top0: $V([xZoomedOut, y1])
      top1: $V([xZoomedOut, y1 + h1])
      mid0: $V([xZoomedIn + 2, y2 + h2])
      mid1: $V([xZoomedIn - 2, y2 + h2])
      mid2: $V([xZoomedOut - 1, y1 + h1])
      mid3: $V([xZoomedOut + 1, y1 + h1])
      bot0: $V([xZoomedIn, y2 + h2])
      bot1: $V([xZoomedIn, @offsetParent.offsetHeight])
    }
    @redraw()

  redraw: ->
    @ctx.clearRect(0, 0, @$.canvas.width, @$.canvas.height)

    @ctx.strokeStyle = '#fff'
    @ctx.lineWidth = 0.5
    @ctx.beginPath()
    Drawing.line(@ctx, $V([0, @mouseY]), $V([@$.canvas.width, @mouseY]))
    Drawing.line(@ctx, $V([@mouseX, 0]), $V([@mouseX, @$.canvas.height]))
    @ctx.stroke()

    if @cursorPath
      @ctx.strokeStyle = '#ff0303'
      @ctx.lineWidth = 1.5
      @ctx.beginPath()
      Drawing.line(@ctx, @cursorPath.top0, @cursorPath.top1)
      @ctx.stroke()

      @ctx.fillStyle = '#9c0303'
      @ctx.beginPath()
      @ctx.moveTo(@cursorPath.mid0.e(1), @cursorPath.mid0.e(2))
      @ctx.lineTo(p.e(1), p.e(2)) for p in [
        @cursorPath.mid1, @cursorPath.mid2, @cursorPath.mid3]
      @ctx.fill()
      
      @ctx.strokeStyle = '#ff0303'
      @ctx.lineWidth = 3
      @ctx.beginPath()
      Drawing.line(@ctx, @cursorPath.bot0, @cursorPath.bot1, '#ff0303', '3px')
      @ctx.stroke()
    
Polymer
  is: 'light9-adjusters-canvas'
  behaviors: [ Polymer.IronResizableBehavior ]
  properties:
    adjs: { type: Object, notify: true }, # adjId: Adjustable
  observers: [
    'updateAllCoords(adjs)'
  ]
  listeners:
    'iron-resize': 'resizeUpdate'
  ready: ->
    @adjs = {}
    @ctx = @$.canvas.getContext('2d')

    @redraw()
   
  onDown: (ev) ->
    if ev.buttons == 1
      ev.stopPropagation()
      start = $V([ev.x, ev.y])
      adj = @_adjAtPoint(start)
      if adj
        @currentDrag = {start: start, adj: adj}
        adj.startDrag()

  onMove: (ev) ->
    pos = $V([ev.x, ev.y])
    if @currentDrag
      @currentDrag.cur = pos
      @currentDrag.adj.continueDrag(@currentDrag.cur.subtract(@currentDrag.start))

  onUp: (ev) ->
    return unless @currentDrag
    @currentDrag.adj.endDrag()
    @currentDrag = null
    
  setAdjuster: (adjId, makeAdjustable) ->
    # callers register/unregister the Adjustables they want us to make
    # adjuster elements for. Caller invents adjId.  makeAdjustable is
    # a function returning the Adjustable or it is null to clear any
    # adjusters with this id.
    if not @adjs[adjId] or not makeAdjustable?
      if not makeAdjustable?
        delete @adjs[adjId]
      else
        adj = makeAdjustable()
        @adjs[adjId] = adj
        adj.id = adjId

    @debounce('adj redraw', @redraw.bind(@))

    window.debug_adjsCount = Object.keys(@adjs).length

  updateAllCoords: ->
    @redraw()

  _adjAtPoint: (pt) ->
    nearest = @qt.find(pt.e(1), pt.e(2))
    if not nearest? or nearest.distanceFrom(pt) > 50
      return null
    return nearest?.adj

  resizeUpdate: (ev) ->
    @$.canvas.width = ev.target.offsetWidth
    @$.canvas.height = ev.target.offsetHeight
    @redraw()

  redraw: (adjs) ->
    @debounce('redraw', @_throttledRedraw.bind(@))

  _throttledRedraw: () ->
    console.time('adjs redraw')
    @_layoutCenters()
    
    @ctx.clearRect(0, 0, @$.canvas.width, @$.canvas.height)

    for adjId, adj of @adjs
      ctr = adj.getCenter()
      target = adj.getTarget()
      @_drawConnector(ctr, target)
      
      @_drawAdjuster(adj.getDisplayValue(),
                     Math.floor(ctr.e(1)) - 20, Math.floor(ctr.e(2)) - 10,
                     Math.floor(ctr.e(1)) + 20, Math.floor(ctr.e(2)) + 10)
    console.timeEnd('adjs redraw')

  _layoutCenters: ->
    # push Adjustable centers around to avoid overlaps
    # Todo: also don't overlap inlineattr boxes
    # Todo: don't let their connector lines cross each other
    @qt = d3.quadtree([], ((d)->d.e(1)), ((d)->d.e(2)))
    @qt.extent([[0,0], [8000,8000]])
    for _, adj of @adjs
      desired = adj.getSuggestedCenter()
      output = desired
      for tries in [0...4]
        nearest = @qt.find(output.e(1), output.e(2))
        if nearest
          dist = output.distanceFrom(nearest)
          if dist < 60
            away = output.subtract(nearest).toUnitVector()
            toScreenCenter = $V([500,200]).subtract(output).toUnitVector()
            output = output.add(away.x(60).add(toScreenCenter.x(10)))

      if -50 < output.e(1) < 20 # mostly for zoom-left
        output.setElements([
          Math.max(20, output.e(1)),
          output.e(2)])
        
      adj.centerOffset = output.subtract(adj.getTarget())
      output.adj = adj
      @qt.add(output)

  _drawConnector: (ctr, target) ->
    @ctx.strokeStyle = '#aaa'
    @ctx.lineWidth = 2
    @ctx.beginPath()
    Drawing.line(@ctx, ctr, target)
    @ctx.stroke()
    
  _drawAdjuster: (label, x1, y1, x2, y2) ->
    radius = 8

    @ctx.shadowColor = 'black'
    @ctx.shadowBlur = 15
    @ctx.shadowOffsetX = 5
    @ctx.shadowOffsetY = 9
    
    @ctx.fillStyle = 'rgba(255, 255, 0, 0.5)'
    @ctx.beginPath()
    Drawing.roundRect(@ctx, x1, y1, x2, y2, radius)
    @ctx.fill()

    @ctx.shadowColor = 'rgba(0,0,0,0)'
        
    @ctx.strokeStyle = 'yellow'
    @ctx.lineWidth = 2
    @ctx.setLineDash([3, 3])
    @ctx.beginPath()
    Drawing.roundRect(@ctx, x1, y1, x2, y2, radius)
    @ctx.stroke()
    @ctx.setLineDash([])

    @ctx.font = "12px sans"
    @ctx.fillStyle = '#000'
    @ctx.fillText(label, x1 + 5, y2 - 5, x2 - x1 - 10)

    # coords from a center that's passed in
    # # special layout for the thaeter ones with middinh 
    # l/r arrows
    # mouse arrow cursor upon hover, and accent the hovered adjuster
    # connector

  
Polymer
  # note boxes. 
  is: 'light9-timeline-diagram-layer'
  properties: {
    selection: {type: Object, notify: true}
  }
  ready: ->
    @elemById = {}

  attached: ->
    

  setTimeAxis: (width, yTop, scale) ->
    pxPerTick = 50
    axis = d3.axisTop(scale).ticks(width / pxPerTick)
    d3.select(@$.timeAxis).attr('transform', 'translate(0,'+yTop+')').call(axis)

  getOrCreateElem: (uri, groupId, tag, attrs, moreBuild) ->
    elem = @elemById[uri]
    if !elem
      elem = @elemById[uri] = document.createElementNS("http://www.w3.org/2000/svg", tag)
      @$[groupId].appendChild(elem)
      elem.setAttribute('id', uri)
      for k,v of attrs
        elem.setAttribute(k, v)
      if moreBuild
        moreBuild(elem)
    return elem

  _clearElem: (uri, suffixes) ->
    for suff in suffixes
      elem = @elemById[uri+suff]
      if elem
        ko.removeNode(elem)
        delete @elemById[uri+suff]

  _anyPointsInView: (pts) ->
    for pt in pts
      # wrong:
      if pt.e(1) > -100 && pt.e(1) < 2500
        return true
    return false
    
  setNote: (uri, curvePts, effect) ->
    @debounce("setNote #{uri}", () => @_setNoteThrottle(uri, curvePts, effect))
    
  _setNoteThrottle: (uri, curvePts, effect) ->
    areaId = uri + '/area'
    if not @_anyPointsInView(curvePts)
      @clearNote(uri)
      return

    attrs = @_noteAttrs(effect)
    elem = @getOrCreateElem areaId, 'notes', 'path', attrs, (elem) =>
      @_addNoteListeners(elem, uri)
    elem.setAttribute('d', Drawing.svgPathFromPoints(curvePts))
    @_updateNotePathClasses(uri, elem)

  _addNoteListeners: (elem, uri) ->
    elem.addEventListener 'mouseenter', =>
      @selection.hover(uri)
    elem.addEventListener 'mousedown', (ev) =>
      sel = @selection.selected()
      if ev.getModifierState('Control')
        if uri in sel
          sel = _.without(sel, uri)
        else
          sel.push(uri)
      else
        sel = [uri]
      @selection.selected(sel)
    elem.addEventListener 'mouseleave', =>
      @selection.hover(null)

  _noteAttrs: (effect) ->
    if effect in ['http://light9.bigasterisk.com/effect/blacklight',
      'http://light9.bigasterisk.com/effect/strobewarm']
      hue = 0
      sat = 100
    else        
      hash = 0
      for i in [(effect.length-10)...effect.length]
        hash += effect.charCodeAt(i)
      hue = (hash * 8) % 360
      sat = 40 + (hash % 20) # don't conceal colorscale too much

    {style: "fill:hsla(#{hue}, #{sat}%, 58%, 0.313);"}

  clearNote: (uri) ->
    @_clearElem(uri, ['/area'])

  _noteInDiagram: (uri) ->
    return !!@elemById[uri + '/area']

  _updateNotePathClasses: (uri, elem) ->
    ko.computed =>
      return if not @_noteInDiagram(uri)
      classes = 'light9-timeline-diagram-layer ' + (if @selection.hover() == uri then 'hover' else '') + ' '  + (if uri in @selection.selected() then 'selected' else '')
      elem.setAttribute('class', classes)
    
    #elem = @getOrCreateElem(uri+'/label', 'noteLabels', 'text', {style: "font-size:13px;line-height:125%;font-family:'Verana Sans';text-align:start;text-anchor:start;fill:#000000;"})
    #elem.setAttribute('x', curvePts[0].e(1)+20)
    #elem.setAttribute('y', curvePts[0].e(2)-10)
    #elem.innerHTML = effectLabel;