/
CometActor.scala
1543 lines (1285 loc) · 47.2 KB
/
CometActor.scala
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
/*
* Copyright 2007-2011 WorldWide Conferencing, LLC
*
* 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.
*/
package net.liftweb
package http
import net.liftweb.common._
import net.liftweb.actor._
import net.liftweb.util.Helpers._
import net.liftweb.util._
import net.liftweb.json._
import scala.xml.{NodeSeq, Text, Elem, Node, Group, Null, PrefixedAttribute, UnprefixedAttribute}
import scala.collection.mutable.ListBuffer
import net.liftweb.http.js._
import JsCmds._
import JE._
import java.util.Locale
/**
* A case class that contains the information necessary to set up a CometActor
*/
final case class CometCreationInfo(cometType: String,
cometName: Box[String],
cometHtml: NodeSeq,
cometAttributes: Map[String, String],
session: LiftSession)
trait DeltaTrait {
def toJs: JsCmd
}
trait CometState[DeltaType <: DeltaTrait,
MyType <: CometState[DeltaType, MyType]] {
self: MyType =>
def -(other: MyType): Seq[DeltaType]
def render: NodeSeq
}
trait CometStateWithUpdate[UpdateType, DeltaType <: DeltaTrait,
MyType <: CometStateWithUpdate[UpdateType,
DeltaType, MyType]]
extends CometState[DeltaType, MyType] {
self: MyType =>
def process(in: UpdateType): MyType
}
trait StatefulComet extends CometActor {
type Delta <: DeltaTrait
type State <: CometState[Delta, State]
/**
* Test the parameter to see if it's an updated state object
*/
def testState(in: Any): Box[State]
/**
* Return the empty state object
*/
def emptyState: State
/**
* The current state objects
*/
protected var state: State = emptyState
/**
* If there's some ThreadLocal variable that needs to be set up
* before processing the state deltas, set it up here.
*/
protected def setupLocalState[T](f: => T): T = f
private[http] override val _lowPriority = {
val pf: PartialFunction[Any, Unit] = {
case v if testState(v).isDefined =>
testState(v).foreach {
ns =>
if (ns ne state) {
val diff = ns - state
state = ns
partialUpdate(setupLocalState {
diff.map(_.toJs).foldLeft(Noop)(_ & _)
})
}
}
}
pf orElse super._lowPriority
}
/**
* The Render method
*/
def render = state.render
}
object CurrentCometActor extends ThreadGlobal[LiftCometActor]
object AddAListener {
def apply(who: SimpleActor[Any]) = new AddAListener(who, {
case _ => true
})
}
/**
* This is a message class for use with ListenerManager and CometListener
* instances. The use of the shouldUpdate function is deprecated, and
* should instead be handled by the message processing partial functions
* on the CometListener instances themselves.
*
* @see CometListener
* @see ListenerManager
*/
case class AddAListener(who: SimpleActor[Any], shouldUpdate: PartialFunction[Any, Boolean])
/**
* This is a message class for use with ListenerManager and CometListener
* instances.
*
* @see CometListener
* @see ListenerManager
*/
case class RemoveAListener(who: SimpleActor[Any])
object ListenerManager {
type ActorTest = (SimpleActor[Any], PartialFunction[Any, Boolean])
}
/**
* This trait manages a set of Actors in a publish/subscribe pattern. When you extend your Actor with
* this trait, you automatically get handling for sending messages out to all subscribed Actors. Simply
* override the high-, medium-, or lowPriority handlers to do your message processing. When you want to update
* all subscribers, just call the updateListeners method. The createUpdate method is used to generate
* the message that you want sent to all subscribers.
*
* Note that the AddAListener and RemoveAListener messages (for subscription control) are processed
* after any highPriority or mediumPriority messages are processed, so take care to avoid overly
* broad matches in those handlers that might consume internal messages.
*
* For example, you could write a simple service to provide clock ticks using the following code:
*
* <pre name="code" class="scala">
* case object Tick
*
* object Ticker extends ListenerManager with LiftActor {
* import net.liftweb.util.ActorPing
*
* // Set up the initial tick
* ActorPing.schedule(this, Tick, 1000L)
*
* // This is a placeholder, since we're only interested
* // in Ticks
* def createUpdate = "Registered"
*
* override def mediumPriority = {
* case Tick => {
* sendListenersMessage(Tick)
* ActorPing.schedule(this, Tick, 1000L)
* }
* }
* }
* </pre>
*
* A client CometActor could look like:
*
* <pre name="code" class="scala">
* class CometClock extends CometListener {
* val registerWith = Ticker
*
* ... handling code ...
* }
* </pre>
*
* @see CometListener
*
*/
trait ListenerManager {
self: SimpleActor[Any] =>
import ListenerManager._
/**
* This is the list of all registered actors
*/
private var listeners: List[ActorTest] = Nil
protected def messageHandler: PartialFunction[Any, Unit] =
highPriority orElse mediumPriority orElse
listenerService orElse lowPriority
protected def listenerService: PartialFunction[Any, Unit] = {
case AddAListener(who, wantsMessage) =>
val pair = (who, wantsMessage)
listeners ::= pair
updateListeners(pair :: Nil)
case RemoveAListener(who) =>
listeners = listeners.filter(_._1 ne who)
if (listeners.isEmpty) {
onListenersListEmptied()
}
}
/**
* Called after RemoveAListener-message is processed and no more listeners exist.
* Default does nothing.
*/
protected def onListenersListEmptied() {
}
/**
* Update the listeners with the message generated by createUpdate
*/
protected def updateListeners(listeners: List[ActorTest] = listeners) {
val update = createUpdate
listeners foreach {
case (who, wantsMessage) if wantsMessage.isDefinedAt(update) && wantsMessage(update) =>
who ! update
}
}
/**
* Send a message we create to all of the listeners. Note that with this
* invocation the createUpdate method is not used.
*/
protected def sendListenersMessage(msg: Any) {
listeners foreach (_._1 ! msg)
}
/**
* This method is called when the <pre>updateListeners()</pre> method
* needs a message to send to subscribed Actors. In particular, createUpdate
* is used to create the first message that a newly subscribed CometListener
* will receive.
*/
protected def createUpdate: Any
/**
* Override this method to process high priority messages. Note:
* <b>you must not process messages with a wildcard (match all)</b>, since
* this will intercept the messages used for subscription control.
*/
protected def highPriority: PartialFunction[Any, Unit] = Map.empty
/**
* Override this method to process medium priority messages. See
* the highPriority method for an important note on wildcard
* processing.
*
* @see #highPriority
*/
protected def mediumPriority: PartialFunction[Any, Unit] = Map.empty
/**
* Override this method to process low priority messages.
*/
protected def lowPriority: PartialFunction[Any, Unit] = Map.empty
}
/**
* A LiftActorJ with ListenerManager. Subclass this class
* to get a Java-usable LiftActorJ with ListenerManager
*/
abstract class LiftActorJWithListenerManager extends LiftActorJ with ListenerManager {
protected override def messageHandler: PartialFunction[Any, Unit] =
highPriority orElse mediumPriority orElse
listenerService orElse lowPriority orElse _messageHandler
}
/**
* This trait adds functionality to automatically register with a given
* Actor using AddAListener and RemoveAListener control messages. The most
* typical usage would be to register with an instance of ListenerManager.
* You will need to provide a def/val for the <pre>registerWith</pre> member
* to control which Actor to connect to.
*
* See ListenerManager for a complete example.
*
* @see ListenerManager
*/
trait CometListener extends BaseCometActor {
self: BaseCometActor =>
/**
* This controls which Actor to register with for updates. Typically
* this will be an instance of ListenerActor, although you can provide
* your own subscription handling on top of any SimpleActor.
*/
protected def registerWith: SimpleActor[Any]
abstract override protected def localSetup() {
registerWith ! AddAListener(this, { case _ => true })
super.localSetup()
}
abstract override protected def localShutdown() {
registerWith ! RemoveAListener(this)
super.localShutdown()
}
}
trait LiftCometActor extends TypedActor[Any, Any] with ForwardableActor[Any, Any] with Dependent {
def uniqueId: String
/**
* The last "when" sent from the listener
* @return the last when sent from the listener
*/
def lastListenerTime: Long
def lastRenderTime: Long
private[http] def callInitCometActor(creationInfo: CometCreationInfo) {
initCometActor(creationInfo)
}
/**
* Override in sub-class to customise timeout for the render()-method for the specific comet
*/
def cometRenderTimeout = LiftRules.cometRenderTimeout
/**
* Override in sub-class to customise timeout for AJAX-requests to the comet-component for the specific comet
*/
def cometProcessingTimeout = LiftRules.cometProcessingTimeout
/**
* This is to react to comet-requests timing out.
* When the timeout specified in {@link LiftRules#cometProcessingTimeout} occurs one may override
* this to send a message to the user informing of the timeout.
* <p/><p/>
* Do NOT manipulate actor-state here. If you want to manipulate state, send the actor a new message.
* <p/><p/>
* Typical example would be:
* <pre>
* override def cometTimeoutHandler(): JsCmd = {
* Alert("Timeout processing comet-request, timeout is: " + cometProcessingTimeout + "ms")
* }
* </pre>
*/
def cometProcessingTimeoutHandler(): JsCmd = Noop
/**
* This is to react to comet-actors timing out while initial rendering, calls to render().
* When the timeout specified in {@link LiftRules#cometRenderTimeout} occurs one may override
* this to customise the output.
* <p/><p/>
* Do NOT manipulate actor-state here. If you want to manipulate state, send the actor a new message.
* <p/><p/>
* Typical example would be:
* <pre>
* override def renderTimeoutHandler(): Box[NodeSeq] = {
* Full(<div>Comet {this.getClass} timed out, timeout is {cometRenderTimeout}ms</div>)
* }
* </pre>
*/
def cometRenderTimeoutHandler(): Box[NodeSeq] = Empty
protected def initCometActor(creationInfo: CometCreationInfo): Unit
def theType: Box[String]
def name: Box[String]
def hasOuter: Boolean
def buildSpan(xml: NodeSeq): NodeSeq
def parentTag: Elem
/**
* Poke the CometActor and cause it to do a partial update Noop which
* will have the effect of causing the component to redisplay any
* Wiring elements on the component.
* This method is Actor-safe and may be called from any thread, not
* just the Actor's message handler thread.
*/
def poke(): Unit = {}
/**
* Is this CometActor going to capture the initial Req
* object? If yes, override this method and return true
* and override captureInitialReq to capture the Req. Why
* have to explicitly ask for the Req? In order to send Req
* instances across threads, the Req objects must be snapshotted
* which is the process of reading the POST or PUT body from the
* HTTP request stream. We don't want to do this unless we
* have to, so by default the Req is not snapshotted/sent. But
* if you want it, you can have it.
*/
def sendInitialReq_? : Boolean = false
/**
* If the predicate cell changes, the Dependent will be notified
*/
def predicateChanged(which: Cell[_]): Unit = {
poke()
}
/**
* The locale for the session that created the CometActor
*/
def cometActorLocale: Locale = _myLocale
private var _myLocale = Locale.getDefault()
private[http] def setCometActorLocale(loc: Locale) {
_myLocale = loc
}
}
/**
* Subclass from this class if you're in Java-land
* and want a CometActor
*/
abstract class CometActorJ extends LiftActorJ with CometActor {
override def lowPriority = _messageHandler
}
/**
* Subclass from this class if you want a CometActorJ with
* CometListeners
*/
abstract class CometActorJWithCometListener extends CometActorJ with CometListener {
override def lowPriority = _messageHandler
}
trait CometActor extends BaseCometActor {
override final private[http] def partialUpdateStream_? = false
}
trait MessageCometActor extends BaseCometActor {
override final private[http] def partialUpdateStream_? = true
override final def render = NodeSeq.Empty
protected def pushMessage(cmd: => JsCmd) {
partialUpdate(cmd)
}
}
/**
* Takes care of the plumbing for building Comet-based Web Apps
*/
trait BaseCometActor extends LiftActor with LiftCometActor with CssBindImplicits {
private val logger = Logger(classOf[CometActor])
val uniqueId = Helpers.nextFuncName
private var spanId = uniqueId
@volatile private var _lastRenderTime =
if (partialUpdateStream_?)
0
else
Helpers.nextNum
/**
* If we're going to cache the last rendering, here's the
* private cache
*/
private[this] var _realLastRendering: RenderOut = _
/**
* Get the current render clock for the CometActor
* @return
*/
def renderClock: Long = lastRenderTime
@volatile
private var _lastListenerTime: Long = millis
/**
* The last "when" sent from the listener
* @return the last when sent from the listener
*/
def lastListenerTime: Long = _lastListenerTime
def lastRenderTime: Long = _lastRenderTime
/**
* If this method returns true, this CometActor will be treated as a source
* of continuous partial updates. Usually the basic assumption of a Lift
* Comet Actor is that render will display the current state of the actor.
* Partial updates may modify that display, but it is always possible to
* recreate the complete display by calling render again (in which case
* pending partial updates can be safely discarded). If this method
* returns true, render will not be called, but partial updates are
* guaranteed to always be sent to the client. This is useful as a means to
* push arbitrary JavaScript to the client without a distinct UI for the
* comet actor itself.
*/
private[http] def partialUpdateStream_? : Boolean = false
/**
* The last rendering (cached or not)
*/
private def lastRendering: RenderOut =
if (dontCacheRendering) {
val ret =
if (partialUpdateStream_?)
nsToNsFuncToRenderOut(_ => NodeSeq.Empty)
else
render
theSession.updateFunctionMap(S.functionMap, uniqueId, lastRenderTime)
ret
} else {
_realLastRendering
}
/**
* set the last rendering... ignore if we're not caching
*/
private def lastRendering_=(last: RenderOut) {
if (!dontCacheRendering) {
_realLastRendering = last
}
}
private var receivedDelta = false
private var wasLastFullRender = false
@transient
private var listeners: List[(ListenerId, AnswerRender => Unit)] = Nil
private var askingWho: Box[LiftCometActor] = Empty
private var whosAsking: Box[LiftCometActor] = Empty
private var answerWith: Box[Any => Any] = Empty
private var deltas: List[Delta] = Nil
private var jsonHandlerChain: PartialFunction[Any, JsCmd] = Map.empty
private val notices = new ListBuffer[(NoticeType.Value, NodeSeq, Box[String])]
private var _deltaPruner: (BaseCometActor, List[Delta]) => List[Delta] =
(actor, d) => {
val m = Helpers.millis
d.filter(d => (m - d.timestamp) < 120000L)
}
private var _theSession: LiftSession = _
def theSession = _theSession
@volatile private var _defaultHtml: NodeSeq = _
/**
* The template that was passed to this component during comet
* initializations
*/
def defaultHtml: NodeSeq = _defaultHtml
private var _name: Box[String] = Empty
/**
* The optional name of this CometActors
*/
def name: Box[String] = _name
private var _theType: Box[String] = Empty
/**
* The optional type of this CometActor
*/
def theType: Box[String] = _theType
private var _attributes: Map[String, String] = Map.empty
def attributes = _attributes
/**
* The lifespan of this component. By default CometActors
* will last for the entire session that they were created in,
* even if the CometActor is not currently visible. You can
* set the lifespan of the CometActor. If the CometActor
* isn't visible on any page for some period after its lifespan
* the CometActor will be shut down.
*/
def lifespan: Box[TimeSpan] = Empty
private var _running = true
private var _shutDownAt = millis
/**
* Is the CometActor running?
*/
protected def running = _running
/**
* It's seriously suboptimal to override this method. Instead
* use localSetup()
*/
protected def initCometActor(creationInfo: CometCreationInfo) {
if (!dontCacheRendering) {
lastRendering = RenderOut(Full(defaultHtml),
Empty, Empty, Empty, false)
}
_theType = Full(creationInfo.cometType)
_name = creationInfo.cometName
_defaultHtml = creationInfo.cometHtml
_attributes = creationInfo.cometAttributes
_theSession = creationInfo.session
}
def defaultPrefix: Box[String] = Empty
private lazy val _defaultPrefix: String = (defaultPrefix or _name) openOr "comet"
/**
* Set to 'true' if we should run "render" on every page load
*/
protected def alwaysReRenderOnPageLoad = false
def hasOuter = true
def parentTag = <div style="display: inline"/>
/**
* Return the list of ListenerIds of all long poll agents that
* are waiting for this CometActor to change its state. This method
* is useful for detecting presence.
*/
protected def cometListeners: List[ListenerId] = listeners.map(_._1)
/**
* This method will be called when there's a change in the long poll
* listeners. The method does nothing, but allows you to get a granular
* sense of how many browsers care about this CometActor. Note that
* this method should not block for any material time and if there's
* any processing to do, use Scheduler.schedule or send a message to this
* CometActor. Do not change the Actor's state from this method.
*/
protected def listenerTransition(): Unit = {}
/**
* Prepends the handler to the Json Handlers. Should only be used
* during instantiation
*
* @param h -- the PartialFunction that can handle a JSON request
*/
def appendJsonHandler(h: PartialFunction[Any, JsCmd]) {
jsonHandlerChain = h orElse jsonHandlerChain
}
/**
* If there's actor-specific JSON behavior on failure to make the JSON
* call, include the JavaScript here.
*/
def onJsonError: Box[JsCmd] = Empty
/**
* Override this method to deal with JSON sent from the browser via the sendJson function. This
* is based on the Lift JSON package rather than the handleJson stuff based on the older util.JsonParser. This
* is the preferred mechanism. If you use the jsonSend call, you will get a JObject(JField("command", cmd), JField("param", params))
*/
def receiveJson: PartialFunction[JsonAST.JValue, JsCmd] = Map()
/**
* The JavaScript call that you use to send the data to the server. For example:
* <button onclick={jsonSend("Hello", JsRaw("Dude".encJs))}>Click</button>
*/
def jsonSend: JsonCall = _sendJson
/**
* The call that packages up the JSON and tosses it to the server. If you set autoIncludeJsonCode to true,
* then this will be included in the stuff sent to the server.
*/
def jsonToIncludeInCode: JsCmd = _jsonToIncludeCode
private lazy val (_sendJson, _jsonToIncludeCode) = S.createJsonFunc(Full(_defaultPrefix), onJsonError, receiveJson _)
/**
* Set this method to true to have the Json call code included in the Comet output
*/
def autoIncludeJsonCode: Boolean = false
/**
* Creates the span element acting as the real estate for comet rendering.
*/
def buildSpan(xml: NodeSeq): Elem = {
parentTag.copy(child = xml) % ("id" -> spanId)
}
/**
* How to report an error that occurs during message dispatch
*/
protected def reportError(msg: String, exception: Exception) {
logger.error(msg, exception)
}
protected override def messageHandler = {
val what = composeFunction
val myPf: PartialFunction[Any, Unit] = new PartialFunction[Any, Unit] {
def apply(in: Any): Unit =
CurrentCometActor.doWith(BaseCometActor.this) {
S.initIfUninitted(theSession) {
RenderVersion.doWith(uniqueId) {
S.functionLifespan(true) {
try {
what.apply(in)
} catch {
case e if exceptionHandler.isDefinedAt(e) => exceptionHandler(e)
case e: Exception => reportError("Message dispatch for " + in, e)
}
val updatedJs = S.jsToAppend(clearAfterReading = true)
if (updatedJs.nonEmpty) {
partialUpdate(updatedJs)
}
if (S.functionMap.size > 0) {
theSession.updateFunctionMap(S.functionMap,
uniqueId, lastRenderTime)
S.clearFunctionMap
}
}
}
}
}
def isDefinedAt(in: Any): Boolean =
CurrentCometActor.doWith(BaseCometActor.this) {
S.initIfUninitted(theSession) {
RenderVersion.doWith(uniqueId) {
S.functionLifespan(true) {
try {
what.isDefinedAt(in)
} catch {
case e if exceptionHandler.isDefinedAt(e) => exceptionHandler(e); false
case e: Exception => reportError("Message test for " + in, e); false
}
}
}
}
}
}
myPf
}
/**
* A part of the CometActor's screen real estate that is not
* updated by default with reRender(). This block of HTML is
* useful for the editor part of a Comet-based control where
* the data is JSON and updated with partialUpdates.
*/
def fixedRender: Box[NodeSeq] = Empty
/**
* Calculate fixedRender and capture the postpage javascript
*/
protected def calcFixedRender: Box[NodeSeq] =
fixedRender.map(ns => theSession.postPageJavaScript() match {
case Nil => ns
case xs => {
ns ++ Script(xs)
}
})
/**
* We have to cache fixedRender and only change it if
* the template changes or we get a reRender(true)
*/
private def internalFixedRender: Box[NodeSeq] =
if (!cacheFixedRender) {
calcFixedRender
} else {
cachedFixedRender.get
}
private val cachedFixedRender: FatLazy[Box[NodeSeq]] = FatLazy(calcFixedRender)
/**
* By default, we do not cache the value of fixedRender. If it's
* expensive to recompute it each time there's a conversion
* of something to a RenderOut, override this method if you
* want to cache fixedRender.
*/
protected def cacheFixedRender = false
/**
* A helpful implicit conversion that takes a NodeSeq => NodeSeq
* (for example a CssSel) and converts it to a Box[NodeSeq] by
* applying the function to defaultHtml
*/
protected implicit def nodeSeqFuncToBoxNodeSeq(f: NodeSeq => NodeSeq):
Box[NodeSeq] = Full(f(defaultHtml))
/**
* By default, `CometActor` handles `RedirectShortcutException`, which is
* used to handle many types of redirects in Lift. If you override this
* `PartialFunction` to do your own exception handling and want redirects
* from e.g. `S.redirectTo` to continue working correctly, make sure you
* chain back to this implementation.
*/
override def exceptionHandler : PartialFunction[Throwable, Unit] = {
case ResponseShortcutException(_, Full(redirectUri), _) =>
partialUpdate(RedirectTo(redirectUri))
case other if super.exceptionHandler.isDefinedAt(other) =>
super.exceptionHandler(other)
}
/**
* Handle messages sent to this Actor before the
*/
def highPriority: PartialFunction[Any, Unit] = Map.empty
def lowPriority: PartialFunction[Any, Unit] = Map.empty
def mediumPriority: PartialFunction[Any, Unit] = Map.empty
private[http] def _lowPriority: PartialFunction[Any, Unit] = {
case s => logger.debug("CometActor " + this + " got unexpected message " + s)
}
private lazy val _mediumPriority: PartialFunction[Any, Unit] = {
case l@Unlisten(seq) => {
_lastListenerTime = millis
askingWho match {
case Full(who) => forwardMessageTo(l, who) // forward l
case _ => listeners = listeners.filter(_._1 != seq)
}
listenerTransition()
}
case l@Listen(when, seqId, toDo) => {
_lastListenerTime = millis
askingWho match {
case Full(who) => forwardMessageTo(l, who) // who forward l
case _ =>
if (when < lastRenderTime && ! partialUpdateStream_?) {
toDo(AnswerRender(new XmlOrJsCmd(spanId, lastRendering,
buildSpan _, notices.toList),
whosAsking openOr this, lastRenderTime, wasLastFullRender))
clearNotices
} else {
_lastRenderTime = when
deltas.filter(_.when > when) match {
case Nil => listeners = (seqId, toDo) :: listeners
case all@(hd :: xs) => {
toDo(AnswerRender(new XmlOrJsCmd(spanId, Empty, Empty,
Full(all.reverse.foldLeft(Noop)(_ & _.js)), Empty, buildSpan, false, notices.toList),
whosAsking openOr this, hd.when, false))
clearNotices
}
}
deltas = _deltaPruner(this, deltas)
}
}
listenerTransition()
}
case PerformSetupComet2(initialReq) => {
localSetup()
captureInitialReq(initialReq)
performReRender(true)
}
/**
* Update the defaultHtml... sent in dev mode
*/
case UpdateDefaultHtml(html) => {
val redo = html != _defaultHtml
_defaultHtml = html
if (redo) {
performReRender(false)
}
}
case AskRender =>
askingWho match {
case Full(who) => forwardMessageTo(AskRender, who) // forward AskRender
case _ => {
val out =
if (receivedDelta || alwaysReRenderOnPageLoad) {
try {
Full(performReRender(false))
} catch {
case e if exceptionHandler.isDefinedAt(e) => {
exceptionHandler(e)
Empty
}
case e: Exception => {
reportError("Failed performReRender", e)
Empty
}
}
} else {
Empty
}
reply(AnswerRender(new XmlOrJsCmd(spanId, out.openOr(lastRendering),
buildSpan _, notices.toList),
whosAsking openOr this, lastRenderTime, true))
clearNotices
}
}
case ActionMessageSet(msgs, req) =>
S.doCometParams(req.params) {
val computed: List[Any] =
msgs.flatMap {
f => try {
List(f())
} catch {
case e if exceptionHandler.isDefinedAt(e) => exceptionHandler(e); Nil
case e: Exception => reportError("Ajax function dispatch", e); Nil
}
}
reply(computed ::: List(S.noticesToJsCmd))
}
case AskQuestion(what, who, otherlisteners) => {
this.spanId = who.uniqueId
this.listeners = otherlisteners ::: this.listeners
startQuestion(what)
whosAsking = Full(who)
this.reRender(true)
listenerTransition()
}
case AnswerQuestion(what, otherListeners) =>
askingWho.foreach {
ah => {
reply("A null message to release the actor from its send and await reply... do not delete this message")
// askingWho.unlink(self)
ah ! ShutDown
this.listeners = this.listeners ::: otherListeners
this.askingWho = Empty
val aw = answerWith
answerWith = Empty
aw.foreach(_(what))
performReRender(true)
listenerTransition()
}
}
case ShutdownIfPastLifespan =>
for {
ls <- lifespan if listeners.isEmpty && (lastListenerTime + ls.millis + 1000l) < millis
} {
this ! ShutDown
}
case ReRender(all) => performReRender(all)
case SetDeltaPruner(f) =>
_deltaPruner = f
deltas = f(this, deltas)
case Error(id, node) => notices += ((NoticeType.Error, node, id))
case Warning(id, node) => notices += ((NoticeType.Warning, node, id))
case Notice(id, node) => notices += ((NoticeType.Notice, node, id))
case ClearNotices => clearNotices
case ShutDown =>
logger.info("The CometActor " + this + " Received Shutdown")
askingWho.foreach(_ ! ShutDown)
theSession.removeCometActor(this)
_localShutdown()
case PartialUpdateMsg(cmdF) => {
val cmd: JsCmd = cmdF.apply
val time = Helpers.nextNum
val delta = JsDelta(time, cmd)
receivedDelta = true
theSession.updateFunctionMap(S.functionMap, uniqueId, time)
S.clearFunctionMap
deltas = _deltaPruner(this, (delta :: deltas))
if (!listeners.isEmpty) {
val postPage = theSession.postPageJavaScript()
val rendered =
AnswerRender(new XmlOrJsCmd(spanId, Empty, Empty,