-
Notifications
You must be signed in to change notification settings - Fork 108
/
fxml.scala
1517 lines (1341 loc) · 63 KB
/
fxml.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
package com.thoughtworks
package binding
import java.beans.{BeanInfo, Introspector, PropertyDescriptor}
import javafx.beans.DefaultProperty
import javafx.beans.value.{ChangeListener, ObservableValue}
import javafx.event._
import javafx.collections._
import javafx.fxml.JavaFXBuilderFactory
import javafx.scene.Scene
import javafx.stage.{PopupWindow, Stage, Window, WindowEvent}
import javax.swing.SwingUtilities
import com.thoughtworks.binding.Binding.{BindingSeq, Constants, MultiMountPoint, SingleMountPoint, SingletonBindingSeq}
import com.thoughtworks.binding.XmlExtractor._
import com.thoughtworks.Extractor._
import com.thoughtworks.sde.core.Preprocessor
import macrocompat.bundle
import scala.annotation.{StaticAnnotation, compileTimeOnly, implicitNotFound, tailrec}
import scala.collection.{GenSeq, mutable}
import scala.collection.immutable.Queue
import scala.collection.JavaConverters._
import scala.language.experimental.macros
import scala.language.implicitConversions
import scalaz.Semigroup
import scalaz.syntax.all._
import scala.language.dynamics
import scala.language.existentials
/** An annotation to convert FXML literals to JavaFX GUI.
*
* @note The FXML support is still experimental.
* API or behavior of this annotation may change without bumping a majoy version number.
* @see [[https://github.com/ThoughtWorksInc/Binding.scala/wiki/FXML]] for usage
* @author 杨博 (Yang Bo) <pop.atry@gmail.com>
*/
@compileTimeOnly("enable macro paradise to expand macro annotations")
class fxml extends StaticAnnotation {
def macroTransform(annottees: Any*): Any = macro fxml.Macros.macroTransform
}
object fxml {
@enableIf(c => !c.compilerSettings.exists(_.matches("""^-Xplugin:.*scalajs-compiler_[0-9\.\-]*\.jar$""")))
private def screenMountPoint[W <: Window](windowBinding: Binding[W])(show: W => Unit) = {
var shownWindow: Option[W] = None
lazy val unwatchHandler: EventHandler[WindowEvent] = new EventHandler[WindowEvent] {
override def handle(event: WindowEvent): Unit = {
event.getSource.asInstanceOf[W].removeEventHandler(WindowEvent.WINDOW_HIDDEN, this)
mountPoint.unwatch()
}
}
lazy val mountPoint: Binding[Unit] = Binding {
val currentWindow = windowBinding.bind
shownWindow match {
case None =>
case Some(originalWindow) =>
originalWindow.removeEventHandler(WindowEvent.WINDOW_HIDDEN, unwatchHandler)
originalWindow.hide()
}
shownWindow = Some(currentWindow)
currentWindow.addEventHandler(WindowEvent.WINDOW_HIDDEN, unwatchHandler)
show(currentWindow)
}
mountPoint
}
/**
* [[com.thoughtworks.binding.Binding#watch Watch]]es the value of `sceneBinding`, renders it into `parent` and shows `parent`.
*
* @note `sceneBinding` will be automatically [[com.thoughtworks.binding.Binding#unwatch unwatch]]ed when `parent` is closed or hidden.
*/
@enableIf(c => !c.compilerSettings.exists(_.matches("""^-Xplugin:.*scalajs-compiler_[0-9\.\-]*\.jar$""")))
def show(parent: Stage, sceneBinding: Binding[Scene]): Unit = {
lazy val handler = new EventHandler[WindowEvent] with ChangeListener[Scene] {
private def cleanUp() = {
parent.removeEventHandler(WindowEvent.WINDOW_HIDDEN, this)
parent.sceneProperty.removeListener(this)
mountPoint.unwatch()
}
override def handle(event: WindowEvent): Unit = {
cleanUp()
}
override def changed(observable: ObservableValue[_ <: Scene], oldValue: Scene, newValue: Scene): Unit = {
cleanUp()
}
}
lazy val mountPoint: Binding[Unit] = Binding {
val scene = sceneBinding.bind
parent.sceneProperty.removeListener(handler)
parent.removeEventHandler(WindowEvent.WINDOW_HIDDEN, handler)
parent.setScene(scene)
parent.sceneProperty.addListener(handler)
parent.addEventHandler(WindowEvent.WINDOW_HIDDEN, handler)
parent.show()
}
mountPoint.watch()
}
/**
* [[com.thoughtworks.binding.Binding#watch Watch]]es the value of `popupWindowBinding` and shows it as a pop-up window onto `parent`.
*
* @note `popupWindowBinding` will be automatically [[com.thoughtworks.binding.Binding#unwatch unwatch]]ed when being closed or hidden.
*/
@enableIf(c => !c.compilerSettings.exists(_.matches("""^-Xplugin:.*scalajs-compiler_[0-9\.\-]*\.jar$""")))
def show(parent: Window, popupWindowBinding: Binding[PopupWindow]): Unit = {
screenMountPoint(popupWindowBinding)(_.show(parent)).watch()
}
/**
* [[com.thoughtworks.binding.Binding#watch Watch]]es the value of `stageBinding` and shows it on the screen.
*
* @note `stageBinding` will be automatically [[com.thoughtworks.binding.Binding#unwatch unwatch]]ed when being closed or hidden.
*/
@enableIf(c => !c.compilerSettings.exists(_.matches("""^-Xplugin:.*scalajs-compiler_[0-9\.\-]*\.jar$""")))
def show(stageBinding: Binding[Stage]): Unit = {
screenMountPoint(stageBinding)(_.show()).watch()
}
object AutoImports {
implicit final class FunctionEventHandler[E <: Event](f: E => Unit) extends EventHandler[E] {
override def handle(event: E): Unit = f(event)
}
implicit final def functionBindingToEventHandlerBinding[E <: Event](
binding: Binding[E => Unit]): Binding[FunctionEventHandler[E]] = {
binding.map(new FunctionEventHandler[E](_))
}
implicit final class FunctionChangeListener[E](f: (ObservableValue[_ <: E], E, E) => Unit)
extends ChangeListener[E] {
override def changed(c: ObservableValue[_ <: E], oldValue: E, newValue: E): Unit = f(c, oldValue, newValue)
}
implicit final def functionBindingToListListenerBinding[E](
binding: Binding[(ObservableValue[_ <: E], E, E) => Unit]): Binding[FunctionChangeListener[E]] = {
binding.map(new FunctionChangeListener[E](_))
}
implicit final class FunctionListChangeListener[E](f: ListChangeListener.Change[_ <: E] => Unit)
extends ListChangeListener[E] {
override def onChanged(c: ListChangeListener.Change[_ <: E]): Unit = f(c)
}
implicit final def functionBindingToListChangeListenerBinding[E](
binding: Binding[ListChangeListener.Change[_ <: E] => Unit]): Binding[FunctionListChangeListener[E]] = {
binding.map(new FunctionListChangeListener[E](_))
}
implicit final class FunctionArrayChangeListener[T <: ObservableArray[T]](f: (T, Boolean, Int, Int) => Unit)
extends ArrayChangeListener[T] {
override def onChanged(observableArray: T, sizeChanged: Boolean, from: Int, to: Int): Unit =
f(observableArray, sizeChanged, from, to)
}
implicit final def functionBindingToArrayChangeListenerBinding[T <: ObservableArray[T]](
binding: Binding[(T, Boolean, Int, Int) => Unit]): Binding[FunctionArrayChangeListener[T]] = {
binding.map(new FunctionArrayChangeListener[T](_))
}
implicit final class FunctionSetChangeListener[E](f: SetChangeListener.Change[_ <: E] => Unit)
extends SetChangeListener[E] {
override def onChanged(c: SetChangeListener.Change[_ <: E]): Unit = f(c)
}
implicit final def functionBindingToSetChangeListenerBinding[E](
binding: Binding[SetChangeListener.Change[_ <: E] => Unit]): Binding[FunctionSetChangeListener[E]] = {
binding.map(new FunctionSetChangeListener[E](_))
}
implicit final class FunctionMapChangeListener[K, V](f: MapChangeListener.Change[_ <: K, _ <: V] => Unit)
extends MapChangeListener[K, V] {
override def onChanged(c: MapChangeListener.Change[_ <: K, _ <: V]): Unit = f(c)
}
implicit final def functionBindingToMapChangeListenerBinding[K, V](
binding: Binding[MapChangeListener.Change[_ <: K, _ <: V] => Unit])
: Binding[FunctionMapChangeListener[K, V]] = {
binding.map(new FunctionMapChangeListener[K, V](_))
}
}
object Runtime {
trait Listen[-Source] {
type Listener
def addListener(source: Source, listener: Listener): Unit
def removeListener(source: Source, listener: Listener): Unit
}
object Listen {
type Aux[-Source, -Listener0] = Listen[Source] {
type Listener >: Listener0
}
implicit def ValueListen[Value]: Listen.Aux[ObservableValue[_ <: Value], ChangeListener[_ >: Value]] = {
new Listen[ObservableValue[_ <: Value]] {
override type Listener = ChangeListener[_ >: Value]
override def addListener(source: ObservableValue[_ <: Value], listener: ChangeListener[_ >: Value]): Unit = {
source.addListener(listener)
}
override def removeListener(source: ObservableValue[_ <: Value],
listener: ChangeListener[_ >: Value]): Unit = {
source.removeListener(listener)
}
}
}
implicit def MapListen[Key, Value]
: Listen.Aux[ObservableMap[_ <: Key, _ <: Value], MapChangeListener[_ >: Key, _ >: Value]] = {
new Listen[ObservableMap[_ <: Key, _ <: Value]] {
override type Listener = MapChangeListener[_ >: Key, _ >: Value]
override def addListener(source: ObservableMap[_ <: Key, _ <: Value],
listener: MapChangeListener[_ >: Key, _ >: Value]): Unit = {
source.addListener(listener)
}
override def removeListener(source: ObservableMap[_ <: Key, _ <: Value],
listener: MapChangeListener[_ >: Key, _ >: Value]): Unit = {
source.removeListener(listener)
}
}
}
implicit def SetListen[Element]: Listen.Aux[ObservableSet[_ <: Element], SetChangeListener[_ >: Element]] = {
new Listen[ObservableSet[_ <: Element]] {
override type Listener = SetChangeListener[_ >: Element]
override def addListener(source: ObservableSet[_ <: Element],
listener: SetChangeListener[_ >: Element]): Unit = {
source.addListener(listener)
}
override def removeListener(source: ObservableSet[_ <: Element],
listener: SetChangeListener[_ >: Element]): Unit = {
source.removeListener(listener)
}
}
}
implicit def ArrayListen[T <: ObservableArray[T]]: Listen.Aux[ObservableArray[T], ArrayChangeListener[T]] = {
new Listen[ObservableArray[T]] {
override type Listener = ArrayChangeListener[T]
override def addListener(source: ObservableArray[T], listener: Listener): Unit = {
source.addListener(listener)
}
override def removeListener(source: ObservableArray[T], listener: Listener): Unit = {
source.removeListener(listener)
}
}
}
implicit def ListListen[Element]: Listen.Aux[ObservableList[_ <: Element], ListChangeListener[_ >: Element]] = {
new Listen[ObservableList[_ <: Element]] {
override type Listener = ListChangeListener[_ >: Element]
override def addListener(source: ObservableList[_ <: Element],
listener: ListChangeListener[_ >: Element]): Unit = {
source.addListener(listener)
}
override def removeListener(source: ObservableList[_ <: Element],
listener: ListChangeListener[_ >: Element]): Unit = {
source.removeListener(listener)
}
}
}
}
def listenMountPoint[Source](source: Source)(
implicit listen: Listen[Source]): Binding[listen.Listener] => ListenMountPoint[Source, listen.Listener] = {
ListenMountPoint[Source, listen.Listener](source, _)(listen)
}
final case class ListenMountPoint[Source, Listener](source: Source, binding: Binding[Listener])(
implicit listen: Listen.Aux[Source, Listener])
extends SingleMountPoint[Listener](binding) {
var lastListenerOption: Option[Listener] = None
override protected def set(value: Listener): Unit = {
lastListenerOption.foreach(listen.removeListener(source, _))
lastListenerOption = Some(value)
listen.addListener(source, value)
}
override protected def unmount(): Unit = {
lastListenerOption.foreach(listen.removeListener(source, _))
lastListenerOption = None
super.unmount()
}
}
def mountPoint(parent: AnyRef, propertyName: String with Singleton)(
implicit mountPointFactory: MountPointFactory[parent.type, propertyName.type]): mountPointFactory.Out =
mountPointFactory(parent, propertyName)
@implicitNotFound(msg = "${PropertyName} is not a valid property")
trait MountPointFactory[Parent, PropertyName <: String with Singleton] {
type Out
def apply(parent: Parent, propertyName: PropertyName): Out
}
object MountPointFactory {
import scala.language.dynamics
type Aux[Parent, PropertyName <: String with Singleton, Out0] = MountPointFactory[Parent, PropertyName] {
type Out = Out0
}
implicit final class FunctionMountPointFactory[Parent, PropertyName <: String with Singleton, Out0](
underlying: (Parent, PropertyName) => Out0)
extends MountPointFactory[Parent, PropertyName] { this: MountPointFactory.Aux[Parent, PropertyName, Out0] =>
type Out = Out0
override def apply(parent: Parent, propertyName: PropertyName) = underlying(parent, propertyName)
}
implicit def onChangeMountPointFactory[Parent, PropertyName <: String with Singleton]: MountPointFactory[
Parent,
PropertyName] = macro Macros.onChangeMountPointFactory[Parent, PropertyName]
}
val bindingUnitSemigroup: Semigroup[Binding[Unit]] = {
implicit val unitSemigroup: Semigroup[Unit] = Semigroup.instance((_, _) => ())
Semigroup.liftSemigroup
}
val bindingAnySemigroup: Semigroup[Binding[Any]] = {
implicit val unitSemigroup: Semigroup[Any] = Semigroup.instance((_, _) => ())
Semigroup.liftSemigroup
}
val bindingStringSemigroup: Semigroup[Binding[String]] = {
import scalaz.std.string._
Semigroup.liftSemigroup
}
trait ToBindingSeq[OneOrMany] { outer =>
type Element
def toBindingSeq(binding: Binding[OneOrMany]): BindingSeq[Element]
def toBindingSeqBinding(binding: Binding[OneOrMany]): Binding[BindingSeq[Element]] = {
Binding.Constant(toBindingSeq(binding))
}
final def compose[A](f: Binding[A] => Binding[OneOrMany]): ToBindingSeq.Aux[A, Element] = new ToBindingSeq[A] {
override type Element = outer.Element
override final def toBindingSeq(binding: Binding[A]) = outer.toBindingSeq(f(binding))
override final def toBindingSeqBinding(binding: Binding[A]) = outer.toBindingSeqBinding(f(binding))
}
}
trait ToBindingSeqId[Element0] extends ToBindingSeq[Element0]
object ToBindingSeqId {
type Aux[OneOrMany, Element0] = ToBindingSeqId[OneOrMany] {
type Element = Element0
}
implicit final def fromSingleElement[Element0, Element2 >: Element0]: ToBindingSeqId.Aux[Element0, Element2] =
new ToBindingSeqId[Element0] {
override type Element = Element2
override final def toBindingSeq(binding: Binding[Element0]): SingletonBindingSeq[Element2] = {
SingletonBindingSeq[Element2](binding)
}
}
}
private[Runtime] trait LowPriorityToBindingSeq1 {
implicit final def fromSingleElement[From, Element0](
implicit toBindingSeqId: ToBindingSeqId.Aux[From, Element0]): ToBindingSeq.Aux[From, Element0] =
toBindingSeqId
}
private[Runtime] trait LowPriorityToBindingSeq0 extends LowPriorityToBindingSeq1 {
private[Runtime] type InvariantBindingBindingSeq[E] = Binding[BindingSeq[E]]
implicit def fromBindingSeq[From, Element0](
implicit constraint: Binding[From] <:< InvariantBindingBindingSeq[Element0]
): ToBindingSeq.Aux[From, Element0] = {
new ToBindingSeq[From] {
override type Element = Element0
override def toBindingSeq(from: Binding[From]): BindingSeq[Element] = {
(from: Binding[BindingSeq[Element0]]) match {
case Binding.Constant(bindingSeq) => bindingSeq
case binding => Constants(binding).flatMapBinding(identity)
}
}
override def toBindingSeqBinding(binding: Binding[From]) = binding
}
}
}
object ToBindingSeq extends LowPriorityToBindingSeq0 {
type Aux[OneOrMany, Element0] = ToBindingSeq[OneOrMany] {
type Element = Element0
}
def apply[OneOrMany](implicit toBindingSeq: ToBindingSeq[OneOrMany]): toBindingSeq.type = toBindingSeq
private[Runtime] type InvariantBindingBindingSeqBinding[E] = Binding[BindingSeq[Binding[E]]]
implicit def fromBindingBindingSeq[From, Element0](
implicit constraint: Binding[From] <:< InvariantBindingBindingSeqBinding[Element0]
): ToBindingSeq.Aux[From, Element0] = {
import scalaz.syntax.all._
new ToBindingSeq[From] {
override type Element = Element0
override def toBindingSeq(from: Binding[From]): BindingSeq[Element] = {
(from: Binding[BindingSeq[Binding[Element]]]) match {
case Binding.Constant(bindingSeq) =>
bindingSeq.mapBinding(identity)
case binding =>
Constants(binding).flatMapBinding(_.map(_.mapBinding(identity)))
}
}
override def toBindingSeqBinding(from: Binding[From]) = {
(from: Binding[BindingSeq[Binding[Element]]]).map(_.mapBinding(identity))
}
}
}
private[Runtime] type InvariantSeq[E] = Seq[E]
implicit def fromSeq[From, Element](
implicit constraint: From <:< InvariantSeq[Element]
): ToBindingSeq.Aux[From, Element] = {
import scalaz.syntax.all._
fromBindingSeq[BindingSeq[Element], Element].compose[From](_.map { seq =>
Constants(seq: _*)
})
}
implicit def fromJavaList[From, Element](
implicit constraint: From <:< java.util.List[Element]
): ToBindingSeq.Aux[From, Element] = {
import scalaz.syntax.all._
fromBindingSeq[BindingSeq[Element], Element].compose[From](_.map { list =>
Constants(constraint(list).asScala: _*)
})
}
private[Runtime] type InvariantBinding[E] = Binding[E]
implicit def fromBindingBinding[From, Element](
implicit constraint: From <:< InvariantBinding[Element]
): ToBindingSeq.Aux[From, Element] = {
import scalaz.syntax.all._
fromSingleElement[Element, Element].compose(_.flatMap(constraint))
}
}
final def toBindingSeq[OneOrMany](binding: Binding[OneOrMany])(
implicit typeClass: ToBindingSeq[OneOrMany]): BindingSeq[typeClass.Element] = {
typeClass.toBindingSeq(binding)
}
final def toBindingSeqBinding[OneOrMany](binding: Binding[OneOrMany])(
implicit typeClass: ToBindingSeq[OneOrMany]): Binding[BindingSeq[typeClass.Element]] = {
typeClass.toBindingSeqBinding(binding)
}
// This macro does not work if it uses a whitebox Context.
// I have to use deprecated `scala.reflect.macros.Context` instead.
def autoBind(c: scala.reflect.macros.Context): c.Expr[Any] = {
import c.universe._
c.Expr[Any](
c.macroApplication match {
case q"$parent.$macroName" =>
q"$parent.${newTermName(s"${macroName.decodedName}$$binding")}.bind"
case Ident(macroName) =>
q"${newTermName(s"${macroName.decodedName}$$binding")}.bind"
}
)
}
object EmptyConstructor {
def apply[A](a: => A) = new EmptyConstructor(a _)
implicit def emptyConstructor[A]: EmptyConstructor[A] = macro Macros.emptyConstructor[A]
}
final class EmptyConstructor[A](val f: () => A) extends AnyVal {
def apply() = f()
}
final class JavaBeanPropertyTyper[A](implicit val constructor: EmptyConstructor[A]) extends PropertyTyper[A] {
def resolveProperties(initializer: A => Seq[(Seq[String], Seq[Binding[_]])]): Binding[A] =
macro Macros.resolvePropertiesForJavaBean[A]
}
object JavaFXPropertyTyper {
final class CurrentJavaFXBuilderFactory(val underlying: JavaFXBuilderFactory)
object CurrentJavaFXBuilderFactory {
implicit val defaultJavaFXBuilderFactory = new CurrentJavaFXBuilderFactory(new JavaFXBuilderFactory())
}
}
import JavaFXPropertyTyper._
final class JavaFXPropertyTyper[A, B](val constructor: () => B) extends PropertyTyper[A] {
def resolveProperties(initializer: A => Seq[(Seq[String], Seq[Binding[_]])]): Binding[A] =
macro Macros.resolvePropertiesFromJavaFXBuilder[A, B]
}
private[Runtime] sealed trait LowPriorityBuilder {
implicit final def javaBeanTyper[A](implicit constructor: EmptyConstructor[A]): JavaBeanPropertyTyper[A] = {
new JavaBeanPropertyTyper
}
}
object PropertyTyper extends LowPriorityBuilder {
@enableIf(c => !c.compilerSettings.exists(_.matches("""^-Xplugin:.*scalajs-compiler_[0-9\.\-]*\.jar$""")))
implicit def javafxTyper[A]: PropertyTyper[A] = macro Macros.javafxTyper[A]
def apply[Value](implicit typer: PropertyTyper[Value]): typer.type = typer
}
@implicitNotFound(msg = "${Value} is not a Java Bean nor a type built from JavaFXBuilderFactory")
trait PropertyTyper[Value]
final class JavaListMountPoint[A](javaList: java.util.List[A])(bindingSeq: BindingSeq[A])
extends MultiMountPoint[A](bindingSeq) {
override protected def set(children: Seq[A]): Unit = {
javaList.clear()
javaList.addAll(children.asJava)
}
override protected def splice(from: Int, that: GenSeq[A], replaced: Int): Unit = {
val i = javaList.listIterator(from)
for (_ <- 0 until replaced) {
i.next()
i.remove()
}
javaList.addAll(from, that.seq.asJava)
}
}
}
private object Macros {
@enableIf(c => !c.compilerSettings.exists(_.matches("""^-Xplugin:.*scalajs-compiler_[0-9\.\-]*\.jar$""")))
private[Macros] val javafxBuilderFactory = {
if (!SwingUtilities.isEventDispatchThread) {
val panelVar = new scala.concurrent.SyncVar[javafx.embed.swing.JFXPanel]()
SwingUtilities.invokeLater(new Runnable {
override def run(): Unit = {
panelVar.put(new javafx.embed.swing.JFXPanel)
}
})
panelVar.get
} else {
new javafx.embed.swing.JFXPanel
}
new JavaFXBuilderFactory()
}
private[Macros] val Spaces = """\s*""".r
private[Macros] val ExpressionBinding = """(?s)\$\{(.*)\}\s*""".r
private[Macros] val VariableResolution = """(?s)\$(.*)""".r
private[Macros] val EscapeSequences = """(?s)\\(.*)""".r
private[Macros] val ResourceResolution = """(?s)%(.*)""".r
private[Macros] val LocationResolution = """(?s)@(.*)""".r
private[Macros] val ClassName = """[A-Z][^\.]+""".r
private[Macros] val StaticProperty = """([^\.]+)\.([^\.]+)""".r
private[Macros] val OnXxxChange = """on(\w*)Change""".r
}
import scala.reflect.macros.whitebox
@bundle
private[binding] final class Macros(context: whitebox.Context) extends Preprocessor(context) with XmlExtractor {
import Macros._
import c.internal.decorators._
import c.universe._
def onChangeMountPointFactory[Parent: WeakTypeTag, PropertyName <: String with Singleton: WeakTypeTag]: Tree = {
val parentType = weakTypeOf[Parent]
val propertyNameType = weakTypeOf[PropertyName]
val ConstantType(Constant(OnXxxChange(propertyPrefix))) = propertyNameType
val parentName = TermName(c.freshName("parent"))
if (propertyPrefix == "") {
q"""new _root_.com.thoughtworks.binding.fxml.Runtime.MountPointFactory.FunctionMountPointFactory({ ($parentName: $parentType, _: $propertyNameType) =>
_root_.com.thoughtworks.binding.fxml.Runtime.listenMountPoint($parentName)
})"""
} else {
val propertyName = TermName(s"${Introspector.decapitalize(propertyPrefix)}Property")
q"""new _root_.com.thoughtworks.binding.fxml.Runtime.MountPointFactory.FunctionMountPointFactory({ ($parentName: $parentType, _: $propertyNameType) =>
_root_.com.thoughtworks.binding.fxml.Runtime.listenMountPoint($parentName.$propertyName)
})"""
}
}
private implicit def constantLiftable[A: Liftable]: Liftable[Binding.Constant[A]] =
new Liftable[Binding.Constant[A]] {
override def apply(value: Binding.Constant[A]): Tree = {
q"_root_.com.thoughtworks.binding.Binding.Constant(..${value.value})"
}
}
private implicit def seqLiftable[A: Liftable]: Liftable[Seq[A]] = new Liftable[Seq[A]] {
override def apply(value: Seq[A]): Tree = {
q"_root_.scala.Seq(..$value)"
}
}
private implicit def queueLiftable[A: Liftable]: Liftable[Queue[A]] = new Liftable[Queue[A]] {
override def apply(value: Queue[A]): Tree = {
q"_root_.scala.collection.immutable.Queue(..$value)"
}
}
private implicit def treeLiftable: Liftable[Tree] = new Liftable[Tree] {
override def apply(value: Tree): Tree = value
}
// Workaround for Scala 2.10
private def lift[A](a: A)(implicit liftable: Liftable[A]) = liftable(a)
def emptyConstructor[A](implicit weakTypeTag: c.WeakTypeTag[A]): Tree = {
q"_root_.com.thoughtworks.binding.fxml.Runtime.EmptyConstructor(new ${weakTypeTag.tpe}())"
}
private object EmptyBinding {
private val ConstantSymbol = typeOf[Binding.Constant.type].termSymbol
def unapply(tree: Tree): Boolean = {
tree match {
case q"$c.apply[$stringType](${Literal(Constant(Macros.Spaces()))})"
if stringType.tpe <:< typeOf[String] && c.symbol == ConstantSymbol =>
true
case _ =>
false
}
}
}
private def map(binding: Tree)(f: Tree => Tree) = {
atPos(binding.pos) {
val valueName = TermName(c.freshName("value"))
q"""_root_.com.thoughtworks.binding.Binding.typeClass.map($binding)({ $valueName: ${TypeTree()} =>
${f(atPos(binding.pos)(q"$valueName"))}
})"""
}
}
private def buildFromDescriptor(parentBean: Tree,
descriptor: PropertyDescriptor,
bindings: Seq[Tree]): (Tree, TermName, Tree) = {
val name = TermName(c.freshName(descriptor.getName))
if (descriptor.getReadMethod != null && classOf[java.util.List[_]].isAssignableFrom(descriptor.getPropertyType)) {
val nonEmptyBindings = bindings.filterNot(EmptyBinding.unapply)
def list = q"$parentBean.${TermName(descriptor.getReadMethod.getName)}"
val bindingSeq = nonEmptyBindings match {
case Seq() =>
q"_root_.com.thoughtworks.binding.Binding.Constants(())"
case Seq(binding) =>
q"_root_.com.thoughtworks.binding.fxml.Runtime.toBindingSeq($binding)"
case _ =>
val valueBindings = for (binding <- nonEmptyBindings) yield {
q"_root_.com.thoughtworks.binding.fxml.Runtime.toBindingSeqBinding($binding)"
}
q"_root_.com.thoughtworks.binding.Binding.Constants(..$valueBindings).flatMapBinding(_root_.scala.Predef.locally _)"
}
(
q"$bindingSeq.all",
name,
q"""
import _root_.scala.collection.JavaConverters._
$list.addAll($name.asJava)
"""
)
} else if (descriptor.getWriteMethod != null) {
def setterName = TermName(descriptor.getWriteMethod.getName)
if (classOf[String].isAssignableFrom(descriptor.getPropertyType)) {
bindings match {
case Seq() =>
(q"""_root_.com.thoughtworks.binding.Binding.Constant(())""", name, q"()")
case Seq(value) =>
(value, name, q"$parentBean.$setterName($name)")
case nonEmptyBindings =>
val value = nonEmptyBindings.reduce { (left, right) =>
q"_root_.com.thoughtworks.binding.fxml.Runtime.bindingStringSemigroup.append($left, $right)"
}
(value, name, q"$parentBean.$setterName($name)")
}
} else {
bindings match {
case Seq() =>
c.error(parentBean.pos, s"expect a value for ${descriptor.getName}")
(q"???", TermName("<error>"), q"???")
case Seq(value) =>
(value, name, q"$parentBean.$setterName($name)")
case _ =>
c.error(parentBean.pos, s"expect only one value for ${descriptor.getName}")
(q"???", TermName("<error>"), q"???")
}
}
} else {
c.error(parentBean.pos, s"${descriptor.getName} is not writeable")
(q"???", TermName("<error>"), q"???")
}
}
private def bindPropertyFromDescriptor(parentBean: Tree,
descriptor: PropertyDescriptor,
bindings: Seq[Tree]): Tree = {
if (descriptor.getReadMethod != null && classOf[java.util.List[_]].isAssignableFrom(descriptor.getPropertyType)) {
val nonEmptyBindings = bindings.filterNot(EmptyBinding.unapply)
def list = q"$parentBean.${TermName(descriptor.getReadMethod.getName)}"
nonEmptyBindings match {
case Seq() =>
q"_root_.com.thoughtworks.binding.Binding.Constant(())"
case Seq(binding) =>
q"""
new _root_.com.thoughtworks.binding.fxml.Runtime.JavaListMountPoint(
$list
)(
_root_.com.thoughtworks.binding.fxml.Runtime.toBindingSeq($binding)
)
"""
case _ =>
val valueBindings = for (binding <- nonEmptyBindings) yield {
q"_root_.com.thoughtworks.binding.fxml.Runtime.toBindingSeqBinding($binding)"
}
q"""
new _root_.com.thoughtworks.binding.fxml.Runtime.JavaListMountPoint(
$list
)(
_root_.com.thoughtworks.binding.Binding.Constants(..$valueBindings).flatMapBinding(_root_.scala.Predef.locally _)
)
"""
}
} else if (descriptor.getWriteMethod != null) {
def mapSetter(binding: Tree) = {
map(binding) { value =>
q"$parentBean.${TermName(descriptor.getWriteMethod.getName)}($value)"
}
}
if (classOf[String].isAssignableFrom(descriptor.getPropertyType)) {
bindings match {
case Seq() =>
q"""_root_.com.thoughtworks.binding.Binding.Constant(())"""
case Seq(value) =>
mapSetter(value)
case nonEmptyBindings =>
val value = nonEmptyBindings.reduce { (left, right) =>
q"_root_.com.thoughtworks.binding.fxml.Runtime.bindingStringSemigroup.append($left, $right)"
}
mapSetter(value)
}
} else {
bindings match {
case Seq() =>
c.error(parentBean.pos, s"expect a value for ${descriptor.getName}")
q"???"
case Seq(value) =>
mapSetter(value)
}
}
} else {
c.error(parentBean.pos, s"${descriptor.getName} is not writeable")
q"???"
}
}
private def arguments: PartialFunction[Tree, Seq[Tree]] = {
case q"new $t(..$arguments)" => arguments
case q"new $t()" => Nil
}
private def findDefaultProperty(beanClass: Class[_], beanInfo: BeanInfo): Option[PropertyDescriptor] = {
beanInfo.getDefaultPropertyIndex match {
case -1 =>
beanClass.getAnnotation(classOf[DefaultProperty]) match {
case null =>
None
case defaultProperty =>
beanInfo.getPropertyDescriptors.find(_.getName == defaultProperty.value)
}
case i =>
Some(beanInfo.getPropertyDescriptors.apply(i))
}
}
@tailrec
private def resolveGetters(beanClass: Class[_],
beanInfo: BeanInfo,
bean: Tree,
getters: Seq[Tree]): (Class[_], BeanInfo, Tree) = {
getters match {
case Seq() =>
(beanClass, beanInfo, bean)
case (head @ Literal(Constant(name: String))) +: tail =>
beanInfo.getPropertyDescriptors.find(_.getName == name) match {
case None =>
c.error(head.pos, s"$name is not a property of ${beanInfo.getBeanDescriptor.getName}")
(beanClass, beanInfo, bean)
case Some(propertyDescriptor) =>
val nestedClass = propertyDescriptor.getPropertyType
val nestedInfo = Introspector.getBeanInfo(nestedClass)
val nestedBean = atPos(head.pos)(q"$bean.${TermName(propertyDescriptor.getReadMethod.getName)}")
resolveGetters(nestedClass, nestedInfo, nestedBean, tail)
}
}
}
private def mapMethodName(numberOfParamters: Int) = {
numberOfParamters match {
case 1 => TermName("map")
case _ => TermName(s"apply$numberOfParamters")
}
}
// FIXME: Use the same logic as JavaBean
def resolvePropertiesFromJavaFXBuilder[Out: WeakTypeTag, Builder: WeakTypeTag](initializer: Tree): Tree = {
val outType = weakTypeOf[Out]
val q"{ $valDef => $seq(..$properties) }" = initializer
val builderName = TermName(c.freshName("builder"))
val beanId = q"$builderName"
val beanType = weakTypeOf[Builder]
val beanClass = Class.forName(beanType.typeSymbol.fullName)
val beanInfo = Introspector.getBeanInfo(beanClass)
val tripleSeq: Seq[(Tree, TermName, Tree)] = for {
property @ q"($keySeq(..$keyPath), $valueSeq(..$values))" <- properties
} yield {
def defaultResult = (q"???", TermName("<error>"), q"???")
keyPath match {
case Seq() =>
// Default properties
findDefaultProperty(beanClass, beanInfo) match {
case None =>
c.error(property.pos, s"No default property found in ${beanInfo.getBeanDescriptor.getName}")
defaultResult
case Some(descriptor) =>
buildFromDescriptor(beanId, descriptor, values)
}
case prefix :+ (lastProperty @ Literal(Constant(lastPropertyName: String))) =>
val valueName = TermName(c.freshName(lastPropertyName))
def defaultResult = (q"???", valueName, q"???")
val (resolvedClass, resolvedInfo, resolvedBean) = resolveGetters(beanClass, beanInfo, beanId, prefix)
lastPropertyName match {
case StaticProperty(classPrefix, propertyName) =>
val setterName = TermName(s"set${propertyName.capitalize}")
val className = TermName(classPrefix)
values match {
case Seq() =>
c.error(resolvedBean.pos, s"Expect a value for $lastPropertyName")
(q"???", TermName("<error>"), q"???")
case Seq(value) =>
(value, valueName, q"$className.$setterName($resolvedBean, $valueName)")
case _ =>
c.error(resolvedBean.pos, s"Expect only one value for $lastPropertyName")
(q"???", TermName("<error>"), q"???")
}
case _ =>
if (classOf[java.util.Map[_, _]].isAssignableFrom(resolvedClass)) {
values match {
case Seq(value) =>
(value, valueName, q"$resolvedBean.put($lastPropertyName, $valueName)")
case _ =>
values.filterNot(EmptyBinding.unapply) match {
case Seq(value) =>
(value, valueName, q"$resolvedBean.put($lastPropertyName, $valueName)")
case _ =>
c.error(lastProperty.pos, "An attribute for java.util.Map must have extractly one value.")
defaultResult
}
}
} else {
resolvedInfo.getPropertyDescriptors.find(_.getName == lastPropertyName) match {
case Some(descriptor) =>
buildFromDescriptor(resolvedBean, descriptor, values)
case None =>
c.error(lastProperty.pos,
s"$lastPropertyName is not a property of ${resolvedInfo.getBeanDescriptor.getName}")
defaultResult
}
}
}
}
}
val (bindings, names, setters) = tripleSeq.unzip3
val result = if (bindings.isEmpty) {
q"_root_.com.thoughtworks.binding.Binding.Constant(${c.prefix}.constructor().build().asInstanceOf[$outType])"
} else {
val applyN = mapMethodName(bindings.length)
val argumentDefinitions = for (name <- names) yield {
q"val $name = $EmptyTree"
}
q"""
_root_.com.thoughtworks.binding.Binding.typeClass.$applyN(..$bindings)({ ..$argumentDefinitions =>
val $builderName: $beanType = ${c.prefix}.constructor()
..$setters
$builderName.build().asInstanceOf[$outType]
})
"""
}
c.untypecheck(result)
}
def resolvePropertiesForJavaBean[Bean: WeakTypeTag](initializer: Tree): Tree = {
val q"{ ${valDef: ValDef} => $seq(..$properties) }" = initializer
val beanId = Ident(valDef.name)
val beanType = weakTypeOf[Bean]
val beanClass = Class.forName(beanType.typeSymbol.fullName)
val beanInfo = Introspector.getBeanInfo(beanClass)
val attributeBindings: Seq[Tree] = for {
property @ q"($keySeq(..$keyPath), $valueSeq(..$values))" <- properties
} yield {
keyPath match {
case Seq() =>
// Default properties
findDefaultProperty(beanClass, beanInfo) match {
case None =>
c.error(property.pos, s"No default property found in ${beanInfo.getBeanDescriptor.getName}")
q"???"
case Some(descriptor) =>
bindPropertyFromDescriptor(beanId, descriptor, values)
}
case prefix :+ (lastProperty @ Literal(Constant(lastPropertyName: String))) =>
val (resolvedClass, resolvedInfo, resolvedBean) = resolveGetters(beanClass, beanInfo, beanId, prefix)
lastPropertyName match {
case StaticProperty(classPrefix, propertyName) =>
val setterName = TermName(s"set${propertyName.capitalize}")
val className = TermName(classPrefix)
values match {
case Seq() =>
c.error(resolvedBean.pos, s"Expect a value for $lastPropertyName")
q"???"
case Seq(binding) =>
map(binding) { value =>
q"$className.$setterName($resolvedBean, $value)"
}
case _ =>
c.error(resolvedBean.pos, s"Expect only one value for $lastPropertyName")
q"???"
}
case _ =>
if (classOf[java.util.Map[_, _]].isAssignableFrom(resolvedClass)) {
def put(binding: Tree) = {
map(binding) { value =>
q"$resolvedBean.put($lastPropertyName, $value)"
}
}
values match {
case Seq(value) =>
put(value)
case _ =>
values.filterNot(EmptyBinding.unapply) match {
case Seq(value) =>
put(value)
case _ =>
c.error(lastProperty.pos, "An attribute for java.util.Map must have extractly one value.")
q"???"
}
}
} else {