├── .gitignore
├── .travis.yml
├── CONTRIBUTING.md
├── LICENSE
├── README.md
├── build.gradle
├── gradle.properties
├── gradle
├── buildViaTravis.sh
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── settings.gradle
└── src
├── main
└── java
│ └── rx
│ ├── observables
│ └── SwingObservable.java
│ ├── schedulers
│ └── SwingScheduler.java
│ ├── subscriptions
│ └── SwingSubscriptions.java
│ └── swing
│ └── sources
│ ├── AbstractButtonSource.java
│ ├── ChangeEventSource.java
│ ├── ComponentEventSource.java
│ ├── ContainerEventSource.java
│ ├── DocumentEventSource.java
│ ├── FocusEventSource.java
│ ├── HierarchyEventSource.java
│ ├── ItemEventSource.java
│ ├── KeyEventSource.java
│ ├── ListSelectionEventSource.java
│ ├── MouseEventSource.java
│ ├── PropertyChangeEventSource.java
│ ├── SwingTestHelper.java
│ └── WindowEventSource.java
└── test
└── java
└── rx
├── schedulers
└── SwingSchedulerTest.java
└── swing
└── sources
├── AbstractButtonSourceTest.java
├── ChangeEventSourceTest.java
├── ContainerEventSourceTest.java
├── DocumentEventSourceTest.java
├── FocusEventSourceTest.java
├── HierarchyBoundsEventSourceTest.java
├── HierarchyEventSourceTest.java
├── ItemEventSourceTest.java
├── KeyEventSourceTest.java
├── ListSelectionEventSourceTest.java
├── MouseEventSourceTest.java
├── PropertyChangeEventSourceTest.java
└── WindowEventSourceTest.java
/.gitignore:
--------------------------------------------------------------------------------
1 | # Compiled source #
2 | ###################
3 | *.com
4 | *.class
5 | *.dll
6 | *.exe
7 | *.o
8 | *.so
9 |
10 | # Packages #
11 | ############
12 | # it's better to unpack these files and commit the raw source
13 | # git has its own built in compression methods
14 | *.7z
15 | *.dmg
16 | *.gz
17 | *.iso
18 | *.jar
19 | *.rar
20 | *.tar
21 | *.zip
22 |
23 | # Logs and databases #
24 | ######################
25 | *.log
26 |
27 | # OS generated files #
28 | ######################
29 | .DS_Store*
30 | ehthumbs.db
31 | Icon?
32 | Thumbs.db
33 |
34 | # Editor Files #
35 | ################
36 | *~
37 | *.swp
38 |
39 | # Gradle Files #
40 | ################
41 | .gradle
42 | .gradletasknamecache
43 | .m2
44 |
45 | # Build output directies
46 | target/
47 | build/
48 |
49 | # IntelliJ specific files/directories
50 | out
51 | .idea
52 | *.ipr
53 | *.iws
54 | *.iml
55 | atlassian-ide-plugin.xml
56 |
57 | # Eclipse specific files/directories
58 | .classpath
59 | .project
60 | .settings
61 | .metadata
62 | bin/
63 |
64 | # NetBeans specific files/directories
65 | .nbattrs
66 | /.nb-gradle/profiles/private/
67 | .nb-gradle-properties
68 |
69 | # Scala build
70 | *.cache
71 | /.nb-gradle/private/
72 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: java
2 | jdk:
3 | - oraclejdk7
4 | sudo: false
5 | script: gradle/buildViaTravis.sh
6 | cache:
7 | directories:
8 | - "$HOME/.m2"
9 | - "$HOME/.gradle"
10 | env:
11 | global:
12 | - secure: i92CdoDDqeIiCGbhVc4AM4nQ4RORRZy1s9dEKMl6yQtXeD6Y5kZXg+SzRJSlAM9TNM7O24VmFHJn0o34jD8AJx4irk6JuFJQ23yGipGIsVUUetqpckF9hcsJl5/9D+0B6DpxQR4wiy2W4mSZeYSryXKWLbx4YC84ICEmiMIF0tc=
13 | - secure: Q4TcIw8otYdvhPUgVcKMsoUm4ab277+bA9CMvcQSopSl9PRZgQBXG8GTI41LrPnlWHoocAqA8lhj4dS1ACHb7ulPBNVGOTbJwgSAP62WZ7Ka7T07idef2i8/s/HOKAYGJO2tC7OCX5Ynfd9seVm4zXbyLJkR5FqGhFDPhF5zDxc=
14 | - secure: fx61a7A8lZNqGAArBcigjPtsxfj7wJOT2Tq+vbfdZouiPBZ68yUHKMmebssWDun62hrwJoFO3rSM6Qeg/t592AsRn/y+MF1l/IWG5VXkggaC0mYAYVH3cBjbVnWeAmPILva9YHeCsLHPyq8v8Z7bIhRz2f2tWwAPbUeezQUtxk4=
15 | - secure: bIv6R9czUONhAOIpw/ustrmea5AMnLaUqLN93ASXzX1jqH8enx0uNj7HI5rRnmRSliKlh3klWofiMnuQnQQeREGlOYHJnkXx2Dy5RAQ2ps7gZDB/LCeBoyi6LajS5gEvNOvK7p2FuPtXZSGGDE9iEyLP/zswWeNJkjDY/Gi3WNo=
16 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # Contributing to RxJava
2 |
3 | If you would like to contribute code you can do so through GitHub by forking the repository and sending a pull request (on a branch other than `master` or `gh-pages`).
4 |
5 | When submitting code, please make every effort to follow existing conventions and style in order to keep the code as readable as possible.
6 |
7 | ## License
8 |
9 | By contributing your code, you agree to license your contribution under the terms of the APLv2: https://github.com/ReactiveX/RxJava/blob/master/LICENSE
10 |
11 | All files are released with the Apache 2.0 license.
12 |
13 | If you are adding a new file it should have a header like this:
14 |
15 | ```
16 | /**
17 | * Copyright 2014 Netflix, Inc.
18 | *
19 | * Licensed under the Apache License, Version 2.0 (the "License");
20 | * you may not use this file except in compliance with the License.
21 | * You may obtain a copy of the License at
22 | *
23 | * http://www.apache.org/licenses/LICENSE-2.0
24 | *
25 | * Unless required by applicable law or agreed to in writing, software
26 | * distributed under the License is distributed on an "AS IS" BASIS,
27 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
28 | * See the License for the specific language governing permissions and
29 | * limitations under the License.
30 | */
31 | ```
32 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 |
2 | Apache License
3 | Version 2.0, January 2004
4 | http://www.apache.org/licenses/
5 |
6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7 |
8 | 1. Definitions.
9 |
10 | "License" shall mean the terms and conditions for use, reproduction,
11 | and distribution as defined by Sections 1 through 9 of this document.
12 |
13 | "Licensor" shall mean the copyright owner or entity authorized by
14 | the copyright owner that is granting the License.
15 |
16 | "Legal Entity" shall mean the union of the acting entity and all
17 | other entities that control, are controlled by, or are under common
18 | control with that entity. For the purposes of this definition,
19 | "control" means (i) the power, direct or indirect, to cause the
20 | direction or management of such entity, whether by contract or
21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
22 | outstanding shares, or (iii) beneficial ownership of such entity.
23 |
24 | "You" (or "Your") shall mean an individual or Legal Entity
25 | exercising permissions granted by this License.
26 |
27 | "Source" form shall mean the preferred form for making modifications,
28 | including but not limited to software source code, documentation
29 | source, and configuration files.
30 |
31 | "Object" form shall mean any form resulting from mechanical
32 | transformation or translation of a Source form, including but
33 | not limited to compiled object code, generated documentation,
34 | and conversions to other media types.
35 |
36 | "Work" shall mean the work of authorship, whether in Source or
37 | Object form, made available under the License, as indicated by a
38 | copyright notice that is included in or attached to the work
39 | (an example is provided in the Appendix below).
40 |
41 | "Derivative Works" shall mean any work, whether in Source or Object
42 | form, that is based on (or derived from) the Work and for which the
43 | editorial revisions, annotations, elaborations, or other modifications
44 | represent, as a whole, an original work of authorship. For the purposes
45 | of this License, Derivative Works shall not include works that remain
46 | separable from, or merely link (or bind by name) to the interfaces of,
47 | the Work and Derivative Works thereof.
48 |
49 | "Contribution" shall mean any work of authorship, including
50 | the original version of the Work and any modifications or additions
51 | to that Work or Derivative Works thereof, that is intentionally
52 | submitted to Licensor for inclusion in the Work by the copyright owner
53 | or by an individual or Legal Entity authorized to submit on behalf of
54 | the copyright owner. For the purposes of this definition, "submitted"
55 | means any form of electronic, verbal, or written communication sent
56 | to the Licensor or its representatives, including but not limited to
57 | communication on electronic mailing lists, source code control systems,
58 | and issue tracking systems that are managed by, or on behalf of, the
59 | Licensor for the purpose of discussing and improving the Work, but
60 | excluding communication that is conspicuously marked or otherwise
61 | designated in writing by the copyright owner as "Not a Contribution."
62 |
63 | "Contributor" shall mean Licensor and any individual or Legal Entity
64 | on behalf of whom a Contribution has been received by Licensor and
65 | subsequently incorporated within the Work.
66 |
67 | 2. Grant of Copyright License. Subject to the terms and conditions of
68 | this License, each Contributor hereby grants to You a perpetual,
69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70 | copyright license to reproduce, prepare Derivative Works of,
71 | publicly display, publicly perform, sublicense, and distribute the
72 | Work and such Derivative Works in Source or Object form.
73 |
74 | 3. Grant of Patent License. Subject to the terms and conditions of
75 | this License, each Contributor hereby grants to You a perpetual,
76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77 | (except as stated in this section) patent license to make, have made,
78 | use, offer to sell, sell, import, and otherwise transfer the Work,
79 | where such license applies only to those patent claims licensable
80 | by such Contributor that are necessarily infringed by their
81 | Contribution(s) alone or by combination of their Contribution(s)
82 | with the Work to which such Contribution(s) was submitted. If You
83 | institute patent litigation against any entity (including a
84 | cross-claim or counterclaim in a lawsuit) alleging that the Work
85 | or a Contribution incorporated within the Work constitutes direct
86 | or contributory patent infringement, then any patent licenses
87 | granted to You under this License for that Work shall terminate
88 | as of the date such litigation is filed.
89 |
90 | 4. Redistribution. You may reproduce and distribute copies of the
91 | Work or Derivative Works thereof in any medium, with or without
92 | modifications, and in Source or Object form, provided that You
93 | meet the following conditions:
94 |
95 | (a) You must give any other recipients of the Work or
96 | Derivative Works a copy of this License; and
97 |
98 | (b) You must cause any modified files to carry prominent notices
99 | stating that You changed the files; and
100 |
101 | (c) You must retain, in the Source form of any Derivative Works
102 | that You distribute, all copyright, patent, trademark, and
103 | attribution notices from the Source form of the Work,
104 | excluding those notices that do not pertain to any part of
105 | the Derivative Works; and
106 |
107 | (d) If the Work includes a "NOTICE" text file as part of its
108 | distribution, then any Derivative Works that You distribute must
109 | include a readable copy of the attribution notices contained
110 | within such NOTICE file, excluding those notices that do not
111 | pertain to any part of the Derivative Works, in at least one
112 | of the following places: within a NOTICE text file distributed
113 | as part of the Derivative Works; within the Source form or
114 | documentation, if provided along with the Derivative Works; or,
115 | within a display generated by the Derivative Works, if and
116 | wherever such third-party notices normally appear. The contents
117 | of the NOTICE file are for informational purposes only and
118 | do not modify the License. You may add Your own attribution
119 | notices within Derivative Works that You distribute, alongside
120 | or as an addendum to the NOTICE text from the Work, provided
121 | that such additional attribution notices cannot be construed
122 | as modifying the License.
123 |
124 | You may add Your own copyright statement to Your modifications and
125 | may provide additional or different license terms and conditions
126 | for use, reproduction, or distribution of Your modifications, or
127 | for any such Derivative Works as a whole, provided Your use,
128 | reproduction, and distribution of the Work otherwise complies with
129 | the conditions stated in this License.
130 |
131 | 5. Submission of Contributions. Unless You explicitly state otherwise,
132 | any Contribution intentionally submitted for inclusion in the Work
133 | by You to the Licensor shall be under the terms and conditions of
134 | this License, without any additional terms or conditions.
135 | Notwithstanding the above, nothing herein shall supersede or modify
136 | the terms of any separate license agreement you may have executed
137 | with Licensor regarding such Contributions.
138 |
139 | 6. Trademarks. This License does not grant permission to use the trade
140 | names, trademarks, service marks, or product names of the Licensor,
141 | except as required for reasonable and customary use in describing the
142 | origin of the Work and reproducing the content of the NOTICE file.
143 |
144 | 7. Disclaimer of Warranty. Unless required by applicable law or
145 | agreed to in writing, Licensor provides the Work (and each
146 | Contributor provides its Contributions) on an "AS IS" BASIS,
147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148 | implied, including, without limitation, any warranties or conditions
149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150 | PARTICULAR PURPOSE. You are solely responsible for determining the
151 | appropriateness of using or redistributing the Work and assume any
152 | risks associated with Your exercise of permissions under this License.
153 |
154 | 8. Limitation of Liability. In no event and under no legal theory,
155 | whether in tort (including negligence), contract, or otherwise,
156 | unless required by applicable law (such as deliberate and grossly
157 | negligent acts) or agreed to in writing, shall any Contributor be
158 | liable to You for damages, including any direct, indirect, special,
159 | incidental, or consequential damages of any character arising as a
160 | result of this License or out of the use or inability to use the
161 | Work (including but not limited to damages for loss of goodwill,
162 | work stoppage, computer failure or malfunction, or any and all
163 | other commercial damages or losses), even if such Contributor
164 | has been advised of the possibility of such damages.
165 |
166 | 9. Accepting Warranty or Additional Liability. While redistributing
167 | the Work or Derivative Works thereof, You may choose to offer,
168 | and charge a fee for, acceptance of support, warranty, indemnity,
169 | or other liability obligations and/or rights consistent with this
170 | License. However, in accepting such obligations, You may act only
171 | on Your own behalf and on Your sole responsibility, not on behalf
172 | of any other Contributor, and only if You agree to indemnify,
173 | defend, and hold each Contributor harmless for any liability
174 | incurred by, or claims asserted against, such Contributor by reason
175 | of your accepting any such warranty or additional liability.
176 |
177 | END OF TERMS AND CONDITIONS
178 |
179 | APPENDIX: How to apply the Apache License to your work.
180 |
181 | To apply the Apache License to your work, attach the following
182 | boilerplate notice, with the fields enclosed by brackets "[]"
183 | replaced with your own identifying information. (Don't include
184 | the brackets!) The text should be enclosed in the appropriate
185 | comment syntax for the file format. We also recommend that a
186 | file or class name and description of purpose be included on the
187 | same "printed page" as the copyright notice for easier
188 | identification within third-party archives.
189 |
190 | Copyright 2012 Netflix, Inc.
191 |
192 | Licensed under the Apache License, Version 2.0 (the "License");
193 | you may not use this file except in compliance with the License.
194 | You may obtain a copy of the License at
195 |
196 | http://www.apache.org/licenses/LICENSE-2.0
197 |
198 | Unless required by applicable law or agreed to in writing, software
199 | distributed under the License is distributed on an "AS IS" BASIS,
200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201 | See the License for the specific language governing permissions and
202 | limitations under the License.
203 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # RxSwing: Swing bindings for RxJava
2 |
3 | Learn more about RxJava on the Wiki Home and the Netflix TechBlog post where RxJava was introduced.
4 |
5 | ## Master Build Status
6 |
7 |
8 |
9 | ## Communication
10 | RxSwing:
11 | - [GitHub Issues](https://github.com/ReactiveX/RxSwing/issues)
12 |
13 | General RxJava:
14 | - Google Group: [RxJava](http://groups.google.com/d/forum/rxjava)
15 | - Twitter: [@RxJava](http://twitter.com/RxJava)
16 |
17 | ## Binaries
18 |
19 | Binaries and dependency information for Maven, Ivy, Gradle and others can be found at [http://search.maven.org](http://search.maven.org/#search%7Cga%7C1%7C%22rxswing%22%20AND%20g%3A%22io.reactivex%22).
20 |
21 | Example for Maven:
22 |
23 | ```xml
24 |
25 | io.reactivex
26 | rxswing
27 | 0.24.0
28 |
29 | ```
30 | and for Ivy:
31 |
32 | ```xml
33 |
34 | ```
35 |
36 | ## Build
37 |
38 | To build:
39 |
40 | ```
41 | $ git clone git@github.com:ReactiveX/RxSwing.git
42 | $ cd RxSwing/
43 | $ ./gradlew build
44 | ```
45 |
46 | ## Bugs and Feedback
47 |
48 | For bugs, questions and discussions please use the [Github Issues](https://github.com/ReactiveX/RxSwing/issues).
49 |
50 | ## Learning Resources:
51 |
52 | Architecture tutorial and examples from @Petikoch: https://github.com/Petikoch/Java_MVVM_with_Swing_and_RxJava_Examples
53 |
54 |
55 | ## LICENSE
56 |
57 | Licensed under the Apache License, Version 2.0 (the "License");
58 | you may not use this file except in compliance with the License.
59 | You may obtain a copy of the License at
60 |
61 |
62 |
63 | Unless required by applicable law or agreed to in writing, software
64 | distributed under the License is distributed on an "AS IS" BASIS,
65 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
66 | See the License for the specific language governing permissions and
67 | limitations under the License.
68 |
--------------------------------------------------------------------------------
/build.gradle:
--------------------------------------------------------------------------------
1 | buildscript {
2 | repositories { jcenter() }
3 | dependencies { classpath 'com.netflix.nebula:gradle-rxjava-project-plugin:4.0.0' }
4 | }
5 |
6 | apply plugin: 'nebula.rxjava-project'
7 | apply plugin: 'java'
8 |
9 | dependencies {
10 | compile 'io.reactivex:rxjava:1.1.8'
11 | testCompile 'junit:junit:4.12'
12 | testCompile 'org.mockito:mockito-core:1.10.19'
13 | }
14 |
15 | // support for snapshot/final releases with the various branches RxJava uses
16 | nebulaRelease {
17 | addReleaseBranchPattern(/\d+\.\d+\.\d+/)
18 | addReleaseBranchPattern('HEAD')
19 | }
20 |
21 | if (project.hasProperty('release.useLastTag')) {
22 | tasks.prepare.enabled = false
23 | }
24 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | version=1.0.0-RC1-SNAPSHOT
2 |
--------------------------------------------------------------------------------
/gradle/buildViaTravis.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | # This script will build the project.
3 |
4 | if [ "$TRAVIS_PULL_REQUEST" != "false" ]; then
5 | echo -e "Build Pull Request #$TRAVIS_PULL_REQUEST => Branch [$TRAVIS_BRANCH]"
6 | ./gradlew -Prelease.useLastTag=true build
7 | elif [ "$TRAVIS_PULL_REQUEST" == "false" ] && [ "$TRAVIS_TAG" == "" ]; then
8 | echo -e 'Build Branch with Snapshot => Branch ['$TRAVIS_BRANCH']'
9 | ./gradlew -Prelease.travisci=true -PbintrayUser="${bintrayUser}" -PbintrayKey="${bintrayKey}" -PsonatypeUsername="${sonatypeUsername}" -PsonatypePassword="${sonatypePassword}" build snapshot --stacktrace
10 | elif [ "$TRAVIS_PULL_REQUEST" == "false" ] && [ "$TRAVIS_TAG" != "" ]; then
11 | echo -e 'Build Branch for Release => Branch ['$TRAVIS_BRANCH'] Tag ['$TRAVIS_TAG']'
12 | ./gradlew -Prelease.travisci=true -Prelease.useLastTag=true -PbintrayUser="${bintrayUser}" -PbintrayKey="${bintrayKey}" -PsonatypeUsername="${sonatypeUsername}" -PsonatypePassword="${sonatypePassword}" final --stacktrace
13 | else
14 | echo -e 'WARN: Should not be here => Branch ['$TRAVIS_BRANCH'] Tag ['$TRAVIS_TAG'] Pull Request ['$TRAVIS_PULL_REQUEST']'
15 | ./gradlew -Prelease.useLastTag=true build
16 | fi
17 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ReactiveX/RxSwing/281ddb9500bea4ce8b44fccde907963712647ab4/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Tue Aug 09 15:44:13 CEST 2016
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=https\://services.gradle.org/distributions/gradle-2.14-bin.zip
7 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Attempt to set APP_HOME
10 | # Resolve links: $0 may be a link
11 | PRG="$0"
12 | # Need this for relative symlinks.
13 | while [ -h "$PRG" ] ; do
14 | ls=`ls -ld "$PRG"`
15 | link=`expr "$ls" : '.*-> \(.*\)$'`
16 | if expr "$link" : '/.*' > /dev/null; then
17 | PRG="$link"
18 | else
19 | PRG=`dirname "$PRG"`"/$link"
20 | fi
21 | done
22 | SAVED="`pwd`"
23 | cd "`dirname \"$PRG\"`/" >/dev/null
24 | APP_HOME="`pwd -P`"
25 | cd "$SAVED" >/dev/null
26 |
27 | APP_NAME="Gradle"
28 | APP_BASE_NAME=`basename "$0"`
29 |
30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
31 | DEFAULT_JVM_OPTS=""
32 |
33 | # Use the maximum available, or set MAX_FD != -1 to use that value.
34 | MAX_FD="maximum"
35 |
36 | warn ( ) {
37 | echo "$*"
38 | }
39 |
40 | die ( ) {
41 | echo
42 | echo "$*"
43 | echo
44 | exit 1
45 | }
46 |
47 | # OS specific support (must be 'true' or 'false').
48 | cygwin=false
49 | msys=false
50 | darwin=false
51 | nonstop=false
52 | case "`uname`" in
53 | CYGWIN* )
54 | cygwin=true
55 | ;;
56 | Darwin* )
57 | darwin=true
58 | ;;
59 | MINGW* )
60 | msys=true
61 | ;;
62 | NONSTOP* )
63 | nonstop=true
64 | ;;
65 | esac
66 |
67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
68 |
69 | # Determine the Java command to use to start the JVM.
70 | if [ -n "$JAVA_HOME" ] ; then
71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
72 | # IBM's JDK on AIX uses strange locations for the executables
73 | JAVACMD="$JAVA_HOME/jre/sh/java"
74 | else
75 | JAVACMD="$JAVA_HOME/bin/java"
76 | fi
77 | if [ ! -x "$JAVACMD" ] ; then
78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
79 |
80 | Please set the JAVA_HOME variable in your environment to match the
81 | location of your Java installation."
82 | fi
83 | else
84 | JAVACMD="java"
85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
86 |
87 | Please set the JAVA_HOME variable in your environment to match the
88 | location of your Java installation."
89 | fi
90 |
91 | # Increase the maximum file descriptors if we can.
92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
93 | MAX_FD_LIMIT=`ulimit -H -n`
94 | if [ $? -eq 0 ] ; then
95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
96 | MAX_FD="$MAX_FD_LIMIT"
97 | fi
98 | ulimit -n $MAX_FD
99 | if [ $? -ne 0 ] ; then
100 | warn "Could not set maximum file descriptor limit: $MAX_FD"
101 | fi
102 | else
103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
104 | fi
105 | fi
106 |
107 | # For Darwin, add options to specify how the application appears in the dock
108 | if $darwin; then
109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
110 | fi
111 |
112 | # For Cygwin, switch paths to Windows format before running java
113 | if $cygwin ; then
114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
116 | JAVACMD=`cygpath --unix "$JAVACMD"`
117 |
118 | # We build the pattern for arguments to be converted via cygpath
119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
120 | SEP=""
121 | for dir in $ROOTDIRSRAW ; do
122 | ROOTDIRS="$ROOTDIRS$SEP$dir"
123 | SEP="|"
124 | done
125 | OURCYGPATTERN="(^($ROOTDIRS))"
126 | # Add a user-defined pattern to the cygpath arguments
127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
129 | fi
130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
131 | i=0
132 | for arg in "$@" ; do
133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
135 |
136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
138 | else
139 | eval `echo args$i`="\"$arg\""
140 | fi
141 | i=$((i+1))
142 | done
143 | case $i in
144 | (0) set -- ;;
145 | (1) set -- "$args0" ;;
146 | (2) set -- "$args0" "$args1" ;;
147 | (3) set -- "$args0" "$args1" "$args2" ;;
148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
154 | esac
155 | fi
156 |
157 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
158 | function splitJvmOpts() {
159 | JVM_OPTS=("$@")
160 | }
161 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
162 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
163 |
164 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
165 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | set DIRNAME=%~dp0
12 | if "%DIRNAME%" == "" set DIRNAME=.
13 | set APP_BASE_NAME=%~n0
14 | set APP_HOME=%DIRNAME%
15 |
16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
17 | set DEFAULT_JVM_OPTS=
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windows variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 | if "%@eval[2+2]" == "4" goto 4NT_args
53 |
54 | :win9xME_args
55 | @rem Slurp the command line arguments.
56 | set CMD_LINE_ARGS=
57 | set _SKIP=2
58 |
59 | :win9xME_args_slurp
60 | if "x%~1" == "x" goto execute
61 |
62 | set CMD_LINE_ARGS=%*
63 | goto execute
64 |
65 | :4NT_args
66 | @rem Get arguments from the 4NT Shell from JP Software
67 | set CMD_LINE_ARGS=%$
68 |
69 | :execute
70 | @rem Setup the command line
71 |
72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
73 |
74 | @rem Execute Gradle
75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
76 |
77 | :end
78 | @rem End local scope for the variables with windows NT shell
79 | if "%ERRORLEVEL%"=="0" goto mainEnd
80 |
81 | :fail
82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
83 | rem the _cmd.exe /c_ return code!
84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
85 | exit /b 1
86 |
87 | :mainEnd
88 | if "%OS%"=="Windows_NT" endlocal
89 |
90 | :omega
91 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | rootProject.name='rxswing'
2 |
--------------------------------------------------------------------------------
/src/main/java/rx/observables/SwingObservable.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright 2014 Netflix, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package rx.observables;
17 |
18 | import java.awt.*;
19 | import java.awt.event.*;
20 | import java.beans.PropertyChangeEvent;
21 | import java.util.Set;
22 |
23 | import javax.swing.*;
24 | import javax.swing.colorchooser.ColorSelectionModel;
25 | import javax.swing.event.ChangeEvent;
26 | import javax.swing.event.DocumentEvent;
27 | import javax.swing.event.ListSelectionEvent;
28 | import javax.swing.text.Document;
29 |
30 | import rx.Observable;
31 | import rx.functions.Func1;
32 | import rx.swing.sources.*;
33 |
34 | /**
35 | * Allows creating observables from various sources specific to Swing.
36 | */
37 | public enum SwingObservable { ; // no instances
38 |
39 | /**
40 | * Creates an observable corresponding to a Swing button action.
41 | *
42 | * @param button
43 | * The button to register the observable for.
44 | * @return Observable of action events.
45 | */
46 | public static Observable fromButtonAction(AbstractButton button) {
47 | return AbstractButtonSource.fromActionOf(button);
48 | }
49 |
50 | /**
51 | * Creates an observable corresponding to raw key events.
52 | *
53 | * @param component
54 | * The component to register the observable for.
55 | * @return Observable of key events.
56 | */
57 | public static Observable fromKeyEvents(Component component) {
58 | return KeyEventSource.fromKeyEventsOf(component);
59 | }
60 |
61 | /**
62 | * Creates an observable corresponding to raw key events, restricted a set of given key codes.
63 | *
64 | * @param component
65 | * The component to register the observable for.
66 | * @return Observable of key events.
67 | */
68 | public static Observable fromKeyEvents(Component component, final Set keyCodes) {
69 | return fromKeyEvents(component).filter(new Func1() {
70 | @Override
71 | public Boolean call(KeyEvent event) {
72 | return keyCodes.contains(event.getKeyCode());
73 | }
74 | });
75 | }
76 |
77 | /**
78 | * Creates an observable that emits the set of all currently pressed keys each time
79 | * this set changes.
80 | * @param component
81 | * The component to register the observable for.
82 | * @return Observable of currently pressed keys.
83 | */
84 | public static Observable> fromPressedKeys(Component component) {
85 | return KeyEventSource.currentlyPressedKeysOf(component);
86 | }
87 |
88 | /**
89 | * Creates an observable corresponding to raw mouse events (excluding mouse motion events).
90 | *
91 | * @param component
92 | * The component to register the observable for.
93 | * @return Observable of mouse events.
94 | */
95 | public static Observable fromMouseEvents(Component component) {
96 | return MouseEventSource.fromMouseEventsOf(component);
97 | }
98 |
99 | /**
100 | * Creates an observable corresponding to raw mouse motion events.
101 | *
102 | * @param component
103 | * The component to register the observable for.
104 | * @return Observable of mouse motion events.
105 | */
106 | public static Observable fromMouseMotionEvents(Component component) {
107 | return MouseEventSource.fromMouseMotionEventsOf(component);
108 | }
109 |
110 | /**
111 | * Creates an observable corresponding to relative mouse motion.
112 | * @param component
113 | * The component to register the observable for.
114 | * @return A point whose x and y coordinate represent the relative horizontal and vertical mouse motion.
115 | */
116 | public static Observable fromRelativeMouseMotion(Component component) {
117 | return MouseEventSource.fromRelativeMouseMotion(component);
118 | }
119 |
120 | /**
121 | * Creates an observable corresponding to raw mouse wheel events.
122 | *
123 | * @param component
124 | * The component to register the observable for.
125 | * @return The component to register the observable for.
126 | */
127 | public static Observable fromMouseWheelEvents(Component component) {
128 | return MouseEventSource.fromMouseWheelEvents(component);
129 | }
130 |
131 | /**
132 | * Creates an observable corresponding to raw component events.
133 | *
134 | * @param component
135 | * The component to register the observable for.
136 | * @return Observable of component events.
137 | */
138 | public static Observable fromComponentEvents(Component component) {
139 | return ComponentEventSource.fromComponentEventsOf(component);
140 | }
141 |
142 | /**
143 | * Creates an observable corresponding to focus events.
144 | *
145 | * @param component
146 | * The component to register the observable for.
147 | * @return Observable of focus events.
148 | */
149 | public static Observable fromFocusEvents(Component component) {
150 | return FocusEventSource.fromFocusEventsOf(component);
151 | }
152 |
153 | /**
154 | * Creates an observable corresponding to component resize events.
155 | *
156 | * @param component
157 | * The component to register the observable for.
158 | * @return Observable emitting the current size of the given component after each resize event.
159 | */
160 | public static Observable fromResizing(Component component) {
161 | return ComponentEventSource.fromResizing(component);
162 | }
163 |
164 | /**
165 | * Creates an observable corresponding to item events.
166 | *
167 | * @param itemSelectable
168 | * The ItemSelectable to register the observable for.
169 | * @return Observable emitting the item events for the given itemSelectable.
170 | */
171 | public static Observable fromItemEvents(ItemSelectable itemSelectable) {
172 | return ItemEventSource.fromItemEventsOf(itemSelectable);
173 | }
174 |
175 | /**
176 | * Creates an observable corresponding to item selection events.
177 | *
178 | * @param itemSelectable
179 | * The ItemSelectable to register the observable for.
180 | * @return Observable emitting the an item event whenever the given itemSelectable is selected.
181 | */
182 | public static Observable fromItemSelectionEvents(ItemSelectable itemSelectable) {
183 | return ItemEventSource.fromItemEventsOf(itemSelectable).filter(new Func1() {
184 | @Override
185 | public Boolean call(ItemEvent event) {
186 | return event.getStateChange() == ItemEvent.SELECTED;
187 | }
188 | });
189 | }
190 |
191 | /**
192 | * Creates an observable corresponding to item deselection events.
193 | *
194 | * @param itemSelectable
195 | * The ItemSelectable to register the observable for.
196 | * @return Observable emitting the an item event whenever the given itemSelectable is deselected.
197 | */
198 | public static Observable fromItemDeselectionEvents(ItemSelectable itemSelectable) {
199 | return ItemEventSource.fromItemEventsOf(itemSelectable).filter(new Func1() {
200 | @Override
201 | public Boolean call(ItemEvent event) {
202 | return event.getStateChange() == ItemEvent.DESELECTED;
203 | }
204 | });
205 | }
206 |
207 | /**
208 | * Creates an observable corresponding to list selection events (e.g. from a JList or a JTable row / column selection).
209 | *
210 | * For more info to swing list selection see
211 | * How to Write a List Selection Listener.
212 | *
213 | * @param listSelectionModel
214 | * The ListSelectionModel to register the observable for.
215 | * @return Observable emitting the list selection events.
216 | */
217 | public static Observable fromListSelectionEvents(ListSelectionModel listSelectionModel) {
218 | return ListSelectionEventSource.fromListSelectionEventsOf(listSelectionModel);
219 | }
220 |
221 | /**
222 | * Creates an observable corresponding to property change events.
223 | *
224 | * @param component
225 | * The component to register the observable for.
226 | * @return Observable of property change events for the given component
227 | */
228 | public static Observable fromPropertyChangeEvents(Component component) {
229 | return PropertyChangeEventSource.fromPropertyChangeEventsOf(component);
230 | }
231 |
232 | /**
233 | * Creates an observable corresponding to property change events filtered by property name.
234 | *
235 | * @param component
236 | * The component to register the observable for.
237 | * @param propertyName
238 | * A property name to filter the property events on.
239 | * @return Observable of property change events for the given component, filtered by the provided property name
240 | */
241 | public static Observable fromPropertyChangeEvents(Component component, final String propertyName) {
242 | return fromPropertyChangeEvents(component).filter(new Func1() {
243 | @Override
244 | public Boolean call(PropertyChangeEvent event) {
245 | return event.getPropertyName().equals(propertyName);
246 | }
247 | });
248 | }
249 |
250 | /**
251 | * @param window
252 | * The window to register the observable for
253 | * @return Observable of window events for the given window
254 | */
255 | public static Observable fromWindowEventsOf(Window window) {
256 | return WindowEventSource.fromWindowEventsOf(window);
257 | }
258 |
259 | /**
260 | * Creates an observable corresponding to document events.
261 | *
262 | * @param document The document to register the observable for.
263 | * @return Observable of document events.
264 | */
265 | public static Observable fromDocumentEvents(Document document) {
266 | return DocumentEventSource.fromDocumentEventsOf(document);
267 | }
268 |
269 | /**
270 | * Creates an observable corresponding to document events restricted to a
271 | * set of given event types.
272 | *
273 | * @param document The document to register the observable for.
274 | * @param eventTypes The set of event types for which the observable should
275 | * emit document events.
276 | * @return Observable of document events.
277 | */
278 | public static Observable fromDocumentEvents(Document document, final Set eventTypes) {
279 | return fromDocumentEvents(document).filter(new Func1() {
280 | @Override
281 | public Boolean call(DocumentEvent event) {
282 | return eventTypes.contains(event.getType());
283 | }
284 | });
285 | }
286 |
287 | /**
288 | * Creates an observable corresponding to change events (e.g. tab selection).
289 | *
290 | * For more info to change listeners and events see
291 | * How to Write a Change Listener.
292 | *
293 | * @param component
294 | * The component to register the observable for.
295 | * @return Observable emitting the change events.
296 | */
297 | public static Observable fromChangeEvents(JTabbedPane component) {
298 | return ChangeEventSource.fromChangeEventsOf(component);
299 | }
300 |
301 | /**
302 | * Creates an observable corresponding to change events (e.g. value changes).
303 | *
304 | * For more info to change listeners and events see
305 | * How to Write a Change Listener.
306 | *
307 | * @param component
308 | * The component to register the observable for.
309 | * @return Observable emitting the change events.
310 | */
311 | public static Observable fromChangeEvents(JSlider component) {
312 | return ChangeEventSource.fromChangeEventsOf(component);
313 | }
314 |
315 | /**
316 | * Creates an observable corresponding to change events (e.g. value changes).
317 | *
318 | * For more info to change listeners and events see
319 | * How to Write a Change Listener and
320 | * How to Use Spinners.
321 | *
322 | * @param component
323 | * The component to register the observable for.
324 | * @return Observable emitting the change events.
325 | */
326 | public static Observable fromChangeEvents(JSpinner component) {
327 | return ChangeEventSource.fromChangeEventsOf(component);
328 | }
329 |
330 | /**
331 | * Creates an observable corresponding to change events (e.g. value changes).
332 | *
333 | * For more info to change listeners and events see
334 | * How to Write a Change Listener and
335 | * How to Use Spinners.
336 | *
337 | * @param spinnerModel
338 | * The spinnerModel to register the observable for.
339 | * @return Observable emitting the change events.
340 | */
341 | public static Observable fromChangeEvents(SpinnerModel spinnerModel) {
342 | return ChangeEventSource.fromChangeEventsOf(spinnerModel);
343 | }
344 |
345 | /**
346 | * Creates an observable corresponding to change events (e.g. button clicks changes).
347 | *
348 | * For more info to change listeners and events see
349 | * How to Write a Change Listener.
350 | *
351 | * @param component
352 | * The component to register the observable for.
353 | * @return Observable emitting the change events.
354 | */
355 | public static Observable fromChangeEvents(AbstractButton component) {
356 | return ChangeEventSource.fromChangeEventsOf(component);
357 | }
358 |
359 | /**
360 | * Creates an observable corresponding to change events (e.g. button clicks changes).
361 | *
362 | * For more info to change listeners and events see
363 | * How to Write a Change Listener.
364 | *
365 | * @param buttonModel
366 | * The buttonModel to register the observable for.
367 | * @return Observable emitting the change events.
368 | */
369 | public static Observable fromChangeEvents(ButtonModel buttonModel) {
370 | return ChangeEventSource.fromChangeEventsOf(buttonModel);
371 | }
372 |
373 | /**
374 | * Creates an observable corresponding to change events (e.g. scrolling).
375 | *
376 | * For more info to change listeners and events see
377 | * How to Write a Change Listener.
378 | *
379 | * @param component
380 | * The component to register the observable for.
381 | * @return Observable emitting the change events.
382 | */
383 | public static Observable fromChangeEvents(JViewport component) {
384 | return ChangeEventSource.fromChangeEventsOf(component);
385 | }
386 |
387 | /**
388 | * Creates an observable corresponding to change events (e.g. from a color chooser).
389 | *
390 | * For more info to change listeners and events see
391 | * How to Write a Change Listener.
392 | *
393 | * @param colorSelectionModel
394 | * The colorSelectionModel to register the observable for.
395 | * @return Observable emitting the change events.
396 | */
397 | public static Observable fromChangeEvents(ColorSelectionModel colorSelectionModel) {
398 | return ChangeEventSource.fromChangeEventsOf(colorSelectionModel);
399 | }
400 |
401 | /**
402 | * Creates an observable corresponding to change events (e.g. progressbar value changes).
403 | *
404 | * For more info to change listeners and events see
405 | * How to Write a Change Listener.
406 | *
407 | * @param component
408 | * The component to register the observable for.
409 | * @return Observable emitting the change events.
410 | */
411 | public static Observable fromChangeEvents(JProgressBar component) {
412 | return ChangeEventSource.fromChangeEventsOf(component);
413 | }
414 |
415 | /**
416 | * Creates an observable corresponding to change events (e.g. progressbar value changes).
417 | *
418 | * For more info to change listeners and events see
419 | * How to Write a Change Listener.
420 | *
421 | * @param boundedRangeModel
422 | * The boundedRangeModel to register the observable for.
423 | * @return Observable emitting the change events.
424 | */
425 | public static Observable fromChangeEvents(BoundedRangeModel boundedRangeModel) {
426 | return ChangeEventSource.fromChangeEventsOf(boundedRangeModel);
427 | }
428 |
429 | /**
430 | * Creates an observable corresponding to container events (e.g. component added).
431 | *
432 | * @param container
433 | * The container to register the observable for.
434 | * @return Observable emitting the container events.
435 | */
436 | public static Observable fromContainerEvents(Container container) {
437 | return ContainerEventSource.fromContainerEventsOf(container);
438 | }
439 |
440 | /**
441 | * Creates an observable corresponding to hierarchy events (e.g. parent added).
442 | *
443 | * @param component
444 | * The {@link Component} to register the observable for.
445 | * @return Observable emitting hierarchy events for the provided component.
446 | */
447 | public static Observable fromHierachyEvents(Component component) {
448 | return HierarchyEventSource.fromHierarchyEventsOf(component);
449 | }
450 |
451 | /**
452 | * Creates an observable corresponding to hierarchy bounds events (e.g. parent resized).
453 | *
454 | * @param component
455 | * The {@link Component} to register the observable for.
456 | * @return Observable emitting hierarchy bounds events for the provided component.
457 | */
458 | public static Observable fromHierachyBoundsEvents(Component component) {
459 | return HierarchyEventSource.fromHierarchyBoundsEventsOf(component);
460 | }
461 |
462 | /**
463 | * Check if the current thead is the event dispatch thread.
464 | *
465 | * @throws IllegalStateException if the current thread is not the event dispatch thread.
466 | */
467 | public static void assertEventDispatchThread() {
468 | if (!SwingUtilities.isEventDispatchThread()) {
469 | throw new IllegalStateException("Need to run in the event dispatch thread, but was " + Thread.currentThread());
470 | }
471 | }
472 | }
473 |
--------------------------------------------------------------------------------
/src/main/java/rx/schedulers/SwingScheduler.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright 2014 Netflix, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package rx.schedulers;
17 |
18 | import java.awt.EventQueue;
19 | import java.awt.event.ActionEvent;
20 | import java.awt.event.ActionListener;
21 | import java.util.concurrent.TimeUnit;
22 |
23 | import javax.swing.*;
24 |
25 | import rx.Scheduler;
26 | import rx.Subscription;
27 | import rx.functions.Action0;
28 | import rx.subscriptions.BooleanSubscription;
29 | import rx.subscriptions.CompositeSubscription;
30 | import rx.subscriptions.Subscriptions;
31 |
32 | /**
33 | * Executes work on the Swing UI thread.
34 | * This scheduler should only be used with actions that execute quickly.
35 | *
36 | * If the calling thread is the Swing UI thread, and no delay parameter is
37 | * provided, the action will run immediately. Otherwise, if the calling
38 | * thread is NOT the Swing UI thread, the action will be deferred until
39 | * all pending UI events have been processed.
40 | */
41 | public final class SwingScheduler extends Scheduler {
42 | private static final SwingScheduler INSTANCE = new SwingScheduler();
43 |
44 | public static SwingScheduler getInstance() {
45 | return INSTANCE;
46 | }
47 |
48 | /* package for unit test */SwingScheduler() {
49 | }
50 |
51 | @Override
52 | public Worker createWorker() {
53 | return new InnerSwingScheduler();
54 | }
55 |
56 | private static class InnerSwingScheduler extends Worker {
57 |
58 | private final CompositeSubscription innerSubscription = new CompositeSubscription();
59 |
60 | @Override
61 | public void unsubscribe() {
62 | innerSubscription.unsubscribe();
63 | }
64 |
65 | @Override
66 | public boolean isUnsubscribed() {
67 | return innerSubscription.isUnsubscribed();
68 | }
69 |
70 | @Override
71 | public Subscription schedule(final Action0 action, long delayTime, TimeUnit unit) {
72 | long delay = Math.max(0, unit.toMillis(delayTime));
73 | assertThatTheDelayIsValidForTheSwingTimer(delay);
74 | final BooleanSubscription s = BooleanSubscription.create();
75 | class ExecuteOnceAction implements ActionListener {
76 | private Timer timer;
77 |
78 | private void setTimer(Timer timer) {
79 | this.timer = timer;
80 | }
81 |
82 | @Override
83 | public void actionPerformed(ActionEvent e) {
84 | timer.stop();
85 | if (innerSubscription.isUnsubscribed() || s.isUnsubscribed()) {
86 | return;
87 | }
88 | action.call();
89 | innerSubscription.remove(s);
90 | }
91 | }
92 |
93 | ExecuteOnceAction executeOnce = new ExecuteOnceAction();
94 | final Timer timer = new Timer((int) delay, executeOnce);
95 | executeOnce.setTimer(timer);
96 | timer.start();
97 |
98 | innerSubscription.add(s);
99 |
100 | // wrap for returning so it also removes it from the 'innerSubscription'
101 | return Subscriptions.create(new Action0() {
102 |
103 | @Override
104 | public void call() {
105 | timer.stop();
106 | s.unsubscribe();
107 | innerSubscription.remove(s);
108 | }
109 |
110 | });
111 | }
112 |
113 | @Override
114 | public Subscription schedule(final Action0 action) {
115 | final BooleanSubscription s = BooleanSubscription.create();
116 |
117 | final Runnable runnable = new Runnable() {
118 | @Override
119 | public void run() {
120 | if (innerSubscription.isUnsubscribed() || s.isUnsubscribed()) {
121 | return;
122 | }
123 | action.call();
124 | innerSubscription.remove(s);
125 | }
126 | };
127 |
128 | if (SwingUtilities.isEventDispatchThread()){
129 | runnable.run();
130 | } else {
131 | EventQueue.invokeLater(runnable);
132 | }
133 |
134 | innerSubscription.add(s);
135 | // wrap for returning so it also removes it from the 'innerSubscription'
136 | return Subscriptions.create(new Action0() {
137 |
138 | @Override
139 | public void call() {
140 | s.unsubscribe();
141 | innerSubscription.remove(s);
142 | }
143 |
144 | });
145 | }
146 |
147 | }
148 |
149 | private static void assertThatTheDelayIsValidForTheSwingTimer(long delay) {
150 | if (delay < 0 || delay > Integer.MAX_VALUE) {
151 | throw new IllegalArgumentException(String.format("The swing timer only accepts non-negative delays up to %d milliseconds.", Integer.MAX_VALUE));
152 | }
153 | }
154 | }
155 |
--------------------------------------------------------------------------------
/src/main/java/rx/subscriptions/SwingSubscriptions.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright 2014 Netflix, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package rx.subscriptions;
17 |
18 | import javax.swing.SwingUtilities;
19 |
20 | import rx.Scheduler.Worker;
21 | import rx.Subscription;
22 | import rx.functions.Action0;
23 | import rx.schedulers.SwingScheduler;
24 |
25 | public final class SwingSubscriptions {
26 |
27 | private SwingSubscriptions() {
28 | // no instance
29 | }
30 |
31 | /**
32 | * @deprecated All RxSwing sources now use subscribeOn to subscribe and unsubscribe on
33 | * the Swing thread.
34 | *
35 | * Create an Subscription that always runs unsubscribe
in the event dispatch thread.
36 | *
37 | * @param unsubscribe
38 | * @return an Subscription that always runs unsubscribe
in the event dispatch thread.
39 | */
40 | @Deprecated
41 | public static Subscription unsubscribeInEventDispatchThread(final Action0 unsubscribe) {
42 | return Subscriptions.create(new Action0() {
43 | @Override
44 | public void call() {
45 | if (SwingUtilities.isEventDispatchThread()) {
46 | unsubscribe.call();
47 | } else {
48 | final Worker inner = SwingScheduler.getInstance().createWorker();
49 | inner.schedule(new Action0() {
50 | @Override
51 | public void call() {
52 | unsubscribe.call();
53 | inner.unsubscribe();
54 | }
55 | });
56 | }
57 | }
58 | });
59 | }
60 | }
61 |
--------------------------------------------------------------------------------
/src/main/java/rx/swing/sources/AbstractButtonSource.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright 2014 Netflix, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package rx.swing.sources;
17 |
18 | import rx.Observable;
19 | import rx.Observable.OnSubscribe;
20 | import rx.Subscriber;
21 | import rx.functions.Action0;
22 | import rx.schedulers.SwingScheduler;
23 | import rx.subscriptions.Subscriptions;
24 |
25 | import javax.swing.*;
26 | import java.awt.event.ActionEvent;
27 | import java.awt.event.ActionListener;
28 |
29 | public enum AbstractButtonSource { ; // no instances
30 |
31 | /**
32 | * @see rx.observables.SwingObservable#fromButtonAction
33 | */
34 | public static Observable fromActionOf(final AbstractButton button) {
35 | return Observable.create(new OnSubscribe() {
36 | @Override
37 | public void call(final Subscriber super ActionEvent> subscriber) {
38 | final ActionListener listener = new ActionListener() {
39 | @Override
40 | public void actionPerformed(ActionEvent e) {
41 | subscriber.onNext(e);
42 | }
43 | };
44 | button.addActionListener(listener);
45 | subscriber.add(Subscriptions.create(new Action0() {
46 | @Override
47 | public void call() {
48 | button.removeActionListener(listener);
49 | }
50 | }));
51 | }
52 | }).subscribeOn(SwingScheduler.getInstance())
53 | .unsubscribeOn(SwingScheduler.getInstance());
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/src/main/java/rx/swing/sources/ChangeEventSource.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright 2015 Netflix, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package rx.swing.sources;
17 |
18 | import rx.Observable;
19 | import rx.Observable.OnSubscribe;
20 | import rx.Subscriber;
21 | import rx.functions.Action0;
22 | import rx.schedulers.SwingScheduler;
23 | import rx.subscriptions.Subscriptions;
24 |
25 | import javax.swing.event.ChangeEvent;
26 | import javax.swing.event.ChangeListener;
27 | import java.lang.reflect.InvocationTargetException;
28 | import java.lang.reflect.Method;
29 | import java.lang.reflect.Modifier;
30 |
31 | public enum ChangeEventSource { ; // no instances
32 |
33 | private static final String ADD_CHANGE_LISTENER_METHOD_NAME = "addChangeListener";
34 | private static final String REMOVE_CHANGE_LISTENER_METHOD_NAME = "removeChangeListener";
35 |
36 | /**
37 | * Creates an observable corresponding to change events (e.g. progressbar value changes).
38 | *
39 | * Due to the lack of a common interface in Java (up to at least version 8), the implementation
40 | * is generic and uses internally reflection to add and remove it's {@link ChangeListener}'s.
41 | * The contract is therefor that the given parameter object MUST have the typical two public methods "addChangeListener"
42 | * (like {@link javax.swing.JProgressBar#addChangeListener(ChangeListener)}) and "removeChangeListener"
43 | * (like {@link javax.swing.JProgressBar#removeChangeListener(ChangeListener)}).
44 | *
45 | * For more info to change listeners and events see
46 | * How to Write a Change Listener.
47 | *
48 | * @param changeEventSource
49 | * The object to register the observable for.
50 | * @return Observable emitting the change events.
51 | * @throws IllegalArgumentException if the given parameter object has not the needed signature
52 | */
53 | public static Observable fromChangeEventsOf(final Object changeEventSource) {
54 | checkHasChangeListenerSupport(changeEventSource);
55 | return Observable.create(new OnSubscribe() {
56 | @Override
57 | public void call(final Subscriber super ChangeEvent> subscriber) {
58 | final ChangeListener listener = new ChangeListener() {
59 | @Override
60 | public void stateChanged(final ChangeEvent event) {
61 | subscriber.onNext(event);
62 | }
63 | };
64 | addChangeListener(changeEventSource, listener);
65 | subscriber.add(Subscriptions.create(new Action0() {
66 | @Override
67 | public void call() {
68 | removeChangeListener(changeEventSource, listener);
69 | }
70 | }));
71 | }
72 | }).subscribeOn(SwingScheduler.getInstance())
73 | .unsubscribeOn(SwingScheduler.getInstance());
74 | }
75 |
76 | private static void checkHasChangeListenerSupport(Object object) {
77 | checkPublicMethodExists(object, ADD_CHANGE_LISTENER_METHOD_NAME, ChangeListener.class);
78 | checkPublicMethodExists(object, REMOVE_CHANGE_LISTENER_METHOD_NAME, ChangeListener.class);
79 | }
80 |
81 | private static void checkPublicMethodExists(Object object, String methodName, Class>... parameterTypes) {
82 | try {
83 | Method method = object.getClass().getMethod(methodName, parameterTypes);
84 | if (!Modifier.isPublic(method.getModifiers())) {
85 | throw new IllegalArgumentException(
86 | "Class '" + object.getClass().getName() + "' has not the expected signature to support change listeners in "
87 | + ChangeEventSource.class.getName() + ". " + methodName + " is not accessible.");
88 | }
89 | } catch (NoSuchMethodException e) {
90 | throw new IllegalArgumentException("Class '" + object.getClass().getName() + "' has not the expected signature to support change listeners in " + ChangeEventSource.class.getName(), e);
91 | }
92 | }
93 |
94 | private static void addChangeListener(Object object, ChangeListener changeListener) {
95 | callChangeListenerMethodViaReflection(object, ADD_CHANGE_LISTENER_METHOD_NAME, changeListener);
96 | }
97 |
98 | private static void removeChangeListener(Object object, ChangeListener changeListener) {
99 | callChangeListenerMethodViaReflection(object, REMOVE_CHANGE_LISTENER_METHOD_NAME, changeListener);
100 | }
101 |
102 | private static void callChangeListenerMethodViaReflection(Object object,
103 | String methodName,
104 | ChangeListener changeListener) {
105 | try {
106 | object.getClass().getMethod(methodName, ChangeListener.class).invoke(object, changeListener);
107 | } catch (IllegalAccessException e) {
108 | throw new IllegalArgumentException("Call of " + methodName + " via reflection failed. Does class " + object.getClass().getName() + " support change listeners?", e);
109 | } catch (InvocationTargetException e) {
110 | throw new IllegalArgumentException("Call of " + methodName + " via reflection failed.", e);
111 | } catch (NoSuchMethodException e) {
112 | throw new IllegalArgumentException("Call of " + methodName + " via reflection failed. Does class " + object.getClass().getName() + " support change listeners?", e);
113 | }
114 | }
115 | }
116 |
--------------------------------------------------------------------------------
/src/main/java/rx/swing/sources/ComponentEventSource.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright 2014 Netflix, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package rx.swing.sources;
17 |
18 | import rx.Observable;
19 | import rx.Observable.OnSubscribe;
20 | import rx.Subscriber;
21 | import rx.functions.Action0;
22 | import rx.functions.Func1;
23 | import rx.observables.SwingObservable;
24 | import rx.schedulers.SwingScheduler;
25 | import rx.subscriptions.Subscriptions;
26 |
27 | import java.awt.*;
28 | import java.awt.event.ComponentEvent;
29 | import java.awt.event.ComponentListener;
30 |
31 | import static rx.swing.sources.ComponentEventSource.Predicate.RESIZED;
32 |
33 | public enum ComponentEventSource { ; // no instances
34 |
35 | /**
36 | * @see rx.observables.SwingObservable#fromComponentEvents
37 | */
38 | public static Observable fromComponentEventsOf(final Component component) {
39 | return Observable.create(new OnSubscribe() {
40 | @Override
41 | public void call(final Subscriber super ComponentEvent> subscriber) {
42 | final ComponentListener listener = new ComponentListener() {
43 | @Override
44 | public void componentHidden(ComponentEvent event) {
45 | subscriber.onNext(event);
46 | }
47 |
48 | @Override
49 | public void componentMoved(ComponentEvent event) {
50 | subscriber.onNext(event);
51 | }
52 |
53 | @Override
54 | public void componentResized(ComponentEvent event) {
55 | subscriber.onNext(event);
56 | }
57 |
58 | @Override
59 | public void componentShown(ComponentEvent event) {
60 | subscriber.onNext(event);
61 | }
62 | };
63 | component.addComponentListener(listener);
64 | subscriber.add(Subscriptions.create(new Action0() {
65 | @Override
66 | public void call() {
67 | component.removeComponentListener(listener);
68 | }
69 | }));
70 | }
71 | }).subscribeOn(SwingScheduler.getInstance())
72 | .unsubscribeOn(SwingScheduler.getInstance());
73 | }
74 |
75 | /**
76 | * @see SwingObservable#fromResizing
77 | */
78 | public static Observable fromResizing(final Component component) {
79 | return fromComponentEventsOf(component).filter(RESIZED).map(new Func1() {
80 | @Override
81 | public Dimension call(ComponentEvent event) {
82 | return event.getComponent().getSize();
83 | }
84 | });
85 | }
86 |
87 | /**
88 | * Predicates that help with filtering observables for specific component events.
89 | */
90 | public enum Predicate implements rx.functions.Func1 {
91 | RESIZED(ComponentEvent.COMPONENT_RESIZED),
92 | HIDDEN(ComponentEvent.COMPONENT_HIDDEN),
93 | MOVED(ComponentEvent.COMPONENT_MOVED),
94 | SHOWN(ComponentEvent.COMPONENT_SHOWN);
95 |
96 | private final int id;
97 |
98 | private Predicate(int id) {
99 | this.id = id;
100 | }
101 |
102 | @Override
103 | public Boolean call(ComponentEvent event) {
104 | return event.getID() == id;
105 | }
106 | }
107 | }
108 |
--------------------------------------------------------------------------------
/src/main/java/rx/swing/sources/ContainerEventSource.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright 2015 Netflix, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package rx.swing.sources;
17 |
18 | import java.awt.Container;
19 | import java.awt.event.ContainerEvent;
20 | import java.awt.event.ContainerListener;
21 |
22 | import rx.Observable;
23 | import rx.Observable.OnSubscribe;
24 | import rx.Subscriber;
25 | import rx.functions.Action0;
26 | import rx.functions.Func1;
27 | import rx.schedulers.SwingScheduler;
28 | import rx.subscriptions.Subscriptions;
29 |
30 | public enum ContainerEventSource { ; // no instances
31 |
32 | /**
33 | * @see rx.observables.SwingObservable#fromContainerEvents
34 | */
35 | public static Observable fromContainerEventsOf(final Container container) {
36 | return Observable.create(new OnSubscribe() {
37 | @Override
38 | public void call(final Subscriber super ContainerEvent> subscriber) {
39 | final ContainerListener listener = new ContainerListener() {
40 | @Override
41 | public void componentRemoved(ContainerEvent event) {
42 | subscriber.onNext(event);
43 | }
44 | @Override
45 | public void componentAdded(ContainerEvent event) {
46 | subscriber.onNext(event);
47 | }
48 | };
49 | container.addContainerListener(listener);
50 | subscriber.add(Subscriptions.create(new Action0() {
51 | @Override
52 | public void call() {
53 | container.removeContainerListener(listener);
54 | }
55 | }));
56 | }
57 | }).subscribeOn(SwingScheduler.getInstance())
58 | .observeOn(SwingScheduler.getInstance());
59 | }
60 |
61 | public static enum Predicate implements Func1 {
62 | COMPONENT_ADDED(ContainerEvent.COMPONENT_ADDED),
63 | COMPONENT_REMOVED(ContainerEvent.COMPONENT_REMOVED);
64 |
65 | private final int id;
66 |
67 | private Predicate(int id) {
68 | this.id = id;
69 | }
70 |
71 | @Override
72 | public Boolean call(ContainerEvent event) {
73 | return event.getID() == id;
74 | }
75 | }
76 | }
77 |
--------------------------------------------------------------------------------
/src/main/java/rx/swing/sources/DocumentEventSource.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright 2015 Netflix, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package rx.swing.sources;
17 |
18 | import javax.swing.event.DocumentEvent;
19 | import javax.swing.event.DocumentListener;
20 | import javax.swing.text.Document;
21 |
22 | import rx.Observable;
23 | import rx.Observable.OnSubscribe;
24 | import rx.Subscriber;
25 | import rx.functions.Action0;
26 | import rx.schedulers.SwingScheduler;
27 | import rx.subscriptions.Subscriptions;
28 |
29 | public enum DocumentEventSource { ; // no instances
30 |
31 | /**
32 | * @see rx.observables.SwingObservable#fromDocumentEvents(Document)
33 | */
34 | public static Observable fromDocumentEventsOf(final Document document) {
35 | return Observable.create(new OnSubscribe() {
36 | @Override
37 | public void call(final Subscriber super DocumentEvent> subscriber) {
38 | final DocumentListener listener = new DocumentListener() {
39 | @Override
40 | public void insertUpdate(DocumentEvent event) {
41 | subscriber.onNext(event);
42 | }
43 |
44 | @Override
45 | public void removeUpdate(DocumentEvent event) {
46 | subscriber.onNext(event);
47 | }
48 |
49 | @Override
50 | public void changedUpdate(DocumentEvent event) {
51 | subscriber.onNext(event);
52 | }
53 | };
54 | document.addDocumentListener(listener);
55 | subscriber.add(Subscriptions.create(new Action0() {
56 | @Override
57 | public void call() {
58 | document.removeDocumentListener(listener);
59 | }
60 | }));
61 | }
62 | }).subscribeOn(SwingScheduler.getInstance())
63 | .unsubscribeOn(SwingScheduler.getInstance());
64 | }
65 | }
66 |
--------------------------------------------------------------------------------
/src/main/java/rx/swing/sources/FocusEventSource.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright 2014 Netflix, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package rx.swing.sources;
17 |
18 | import rx.Observable;
19 | import rx.Observable.OnSubscribe;
20 | import rx.Subscriber;
21 | import rx.functions.Action0;
22 | import rx.functions.Func1;
23 | import rx.schedulers.SwingScheduler;
24 | import rx.subscriptions.Subscriptions;
25 |
26 | import java.awt.*;
27 | import java.awt.event.FocusEvent;
28 | import java.awt.event.FocusListener;
29 |
30 | public enum FocusEventSource { ; // no instances
31 |
32 | /**
33 | * @see rx.observables.SwingObservable#fromFocusEvents
34 | */
35 | public static Observable fromFocusEventsOf(final Component component) {
36 | return Observable.create(new OnSubscribe() {
37 | @Override
38 | public void call(final Subscriber super FocusEvent> subscriber) {
39 | final FocusListener listener = new FocusListener() {
40 |
41 | @Override
42 | public void focusGained(FocusEvent event) {
43 | subscriber.onNext(event);
44 | }
45 |
46 | @Override
47 | public void focusLost(FocusEvent event) {
48 | subscriber.onNext(event);
49 | }
50 | };
51 | component.addFocusListener(listener);
52 | subscriber.add(Subscriptions.create(new Action0() {
53 | @Override
54 | public void call() {
55 | component.removeFocusListener(listener);
56 | }
57 | }));
58 | }
59 | }).subscribeOn(SwingScheduler.getInstance())
60 | .unsubscribeOn(SwingScheduler.getInstance());
61 | }
62 |
63 | /**
64 | * Predicates that help with filtering observables for specific focus events.
65 | */
66 | public enum Predicate implements Func1 {
67 | FOCUS_GAINED(FocusEvent.FOCUS_GAINED),
68 | FOCUS_LOST(FocusEvent.FOCUS_LOST);
69 |
70 | private final int id;
71 |
72 | private Predicate(int id) {
73 | this.id = id;
74 | }
75 |
76 | @Override
77 | public Boolean call(FocusEvent event) {
78 | return event.getID() == id;
79 | }
80 | }
81 | }
82 |
--------------------------------------------------------------------------------
/src/main/java/rx/swing/sources/HierarchyEventSource.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright 2015 Netflix, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package rx.swing.sources;
17 |
18 | import java.awt.Component;
19 | import java.awt.event.HierarchyBoundsListener;
20 | import java.awt.event.HierarchyEvent;
21 | import java.awt.event.HierarchyListener;
22 |
23 | import rx.*;
24 | import rx.Observable.OnSubscribe;
25 | import rx.functions.*;
26 | import rx.schedulers.SwingScheduler;
27 | import rx.subscriptions.Subscriptions;
28 |
29 | public enum HierarchyEventSource { ; // no instances
30 |
31 | /**
32 | * @see rx.observables.SwingObservable#fromHierachyEvents
33 | */
34 | public static Observable fromHierarchyEventsOf(final Component component) {
35 | return Observable.create(new OnSubscribe() {
36 | @Override
37 | public void call(final Subscriber super HierarchyEvent> subscriber) {
38 | final HierarchyListener hiearchyListener = new HierarchyListener() {
39 | @Override
40 | public void hierarchyChanged(HierarchyEvent e) {
41 | subscriber.onNext(e);
42 | }
43 | };
44 | component.addHierarchyListener(hiearchyListener);
45 | subscriber.add(Subscriptions.create(new Action0() {
46 | @Override
47 | public void call() {
48 | component.removeHierarchyListener(hiearchyListener);
49 | }
50 | }));
51 | }
52 | }).subscribeOn(SwingScheduler.getInstance())
53 | .unsubscribeOn(SwingScheduler.getInstance());
54 | }
55 |
56 | /**
57 | * @see rx.observables.SwingObservable#fromHierachyBoundsEvents
58 | */
59 | public static Observable fromHierarchyBoundsEventsOf(final Component component) {
60 | return Observable.create(new OnSubscribe() {
61 | @Override
62 | public void call(final Subscriber super HierarchyEvent> subscriber) {
63 | final HierarchyBoundsListener hiearchyBoundsListener = new HierarchyBoundsListener() {
64 | @Override
65 | public void ancestorMoved(HierarchyEvent e) {
66 | subscriber.onNext(e);
67 | }
68 | @Override
69 | public void ancestorResized(HierarchyEvent e) {
70 | subscriber.onNext(e);
71 | }
72 | };
73 | component.addHierarchyBoundsListener(hiearchyBoundsListener);
74 | subscriber.add(Subscriptions.create(new Action0() {
75 | @Override
76 | public void call() {
77 | component.removeHierarchyBoundsListener(hiearchyBoundsListener);
78 | }
79 | }));
80 | }
81 | }).subscribeOn(SwingScheduler.getInstance())
82 | .unsubscribeOn(SwingScheduler.getInstance());
83 | }
84 |
85 | public static enum Predicate implements Func1
86 | {
87 | ANCESTOR_RESIZED(HierarchyEvent.ANCESTOR_RESIZED),
88 | ANCESTOR_MOVED(HierarchyEvent.ANCESTOR_MOVED);
89 |
90 | private final int id;
91 |
92 | private Predicate(int id)
93 | {
94 | this.id = id;
95 | }
96 |
97 | @Override
98 | public Boolean call(HierarchyEvent event) {
99 | return event.getID() == id;
100 | }
101 | }
102 | }
103 |
--------------------------------------------------------------------------------
/src/main/java/rx/swing/sources/ItemEventSource.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright 2015 Netflix, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package rx.swing.sources;
17 |
18 | import rx.Observable;
19 | import rx.Observable.OnSubscribe;
20 | import rx.Subscriber;
21 | import rx.functions.Action0;
22 | import rx.schedulers.SwingScheduler;
23 | import rx.subscriptions.Subscriptions;
24 |
25 | import java.awt.*;
26 | import java.awt.event.ItemEvent;
27 | import java.awt.event.ItemListener;
28 |
29 | public enum ItemEventSource { ; // no instances
30 |
31 | public static Observable fromItemEventsOf(final ItemSelectable itemSelectable) {
32 | return Observable.create(new OnSubscribe() {
33 | @Override
34 | public void call(final Subscriber super ItemEvent> subscriber) {
35 | final ItemListener listener = new ItemListener() {
36 | @Override
37 | public void itemStateChanged( ItemEvent event ) {
38 | subscriber.onNext(event);
39 | }
40 | };
41 | itemSelectable.addItemListener(listener);
42 | subscriber.add(Subscriptions.create(new Action0() {
43 | @Override
44 | public void call() {
45 | itemSelectable.removeItemListener(listener);
46 | }
47 | }));
48 | }
49 | }).subscribeOn(SwingScheduler.getInstance())
50 | .unsubscribeOn(SwingScheduler.getInstance());
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/src/main/java/rx/swing/sources/KeyEventSource.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright 2014 Netflix, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package rx.swing.sources;
17 |
18 | import rx.Observable;
19 | import rx.Observable.OnSubscribe;
20 | import rx.Subscriber;
21 | import rx.functions.Action0;
22 | import rx.functions.Func1;
23 | import rx.functions.Func2;
24 | import rx.schedulers.SwingScheduler;
25 | import rx.subscriptions.Subscriptions;
26 |
27 | import java.awt.*;
28 | import java.awt.event.KeyEvent;
29 | import java.awt.event.KeyListener;
30 | import java.util.Collections;
31 | import java.util.HashSet;
32 | import java.util.Set;
33 |
34 | public enum KeyEventSource { ; // no instances
35 |
36 | /**
37 | * @see rx.observables.SwingObservable#fromKeyEvents(Component)
38 | */
39 | public static Observable fromKeyEventsOf(final Component component) {
40 | return Observable.create(new OnSubscribe() {
41 | @Override
42 | public void call(final Subscriber super KeyEvent> subscriber) {
43 | final KeyListener listener = new KeyListener() {
44 | @Override
45 | public void keyPressed(KeyEvent event) {
46 | subscriber.onNext(event);
47 | }
48 |
49 | @Override
50 | public void keyReleased(KeyEvent event) {
51 | subscriber.onNext(event);
52 | }
53 |
54 | @Override
55 | public void keyTyped(KeyEvent event) {
56 | subscriber.onNext(event);
57 | }
58 | };
59 | component.addKeyListener(listener);
60 |
61 | subscriber.add(Subscriptions.create(new Action0() {
62 | @Override
63 | public void call() {
64 | component.removeKeyListener(listener);
65 | }
66 | }));
67 | }
68 | }).subscribeOn(SwingScheduler.getInstance())
69 | .unsubscribeOn(SwingScheduler.getInstance());
70 | }
71 |
72 | /**
73 | * @see rx.observables.SwingObservable#fromPressedKeys(Component)
74 | */
75 | public static Observable> currentlyPressedKeysOf(Component component) {
76 | class CollectKeys implements Func2, KeyEvent, Set>{
77 | @Override
78 | public Set call(Set pressedKeys, KeyEvent event) {
79 | Set afterEvent = new HashSet(pressedKeys);
80 | switch (event.getID()) {
81 | case KeyEvent.KEY_PRESSED:
82 | afterEvent.add(event.getKeyCode());
83 | break;
84 |
85 | case KeyEvent.KEY_RELEASED:
86 | afterEvent.remove(event.getKeyCode());
87 | break;
88 |
89 | default: // nothing to do
90 | }
91 | return afterEvent;
92 | }
93 | }
94 |
95 | Observable filteredKeyEvents = fromKeyEventsOf(component).filter(new Func1() {
96 | @Override
97 | public Boolean call(KeyEvent event) {
98 | return event.getID() == KeyEvent.KEY_PRESSED || event.getID() == KeyEvent.KEY_RELEASED;
99 | }
100 | });
101 |
102 | return filteredKeyEvents.scan(Collections.emptySet(), new CollectKeys());
103 | }
104 |
105 | }
106 |
--------------------------------------------------------------------------------
/src/main/java/rx/swing/sources/ListSelectionEventSource.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright 2015 Netflix, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package rx.swing.sources;
17 |
18 | import rx.Observable;
19 | import rx.Observable.OnSubscribe;
20 | import rx.Subscriber;
21 | import rx.functions.Action0;
22 | import rx.schedulers.SwingScheduler;
23 | import rx.subscriptions.Subscriptions;
24 |
25 | import javax.swing.ListSelectionModel;
26 | import javax.swing.event.ListSelectionEvent;
27 | import javax.swing.event.ListSelectionListener;
28 |
29 | public enum ListSelectionEventSource { ; // no instances
30 |
31 | /**
32 | * @see rx.observables.SwingObservable#fromListSelectionEvents(ListSelectionModel)
33 | */
34 | public static Observable fromListSelectionEventsOf(final ListSelectionModel listSelectionModel) {
35 | return Observable.create(new OnSubscribe() {
36 | @Override
37 | public void call(final Subscriber super ListSelectionEvent> subscriber) {
38 | final ListSelectionListener listener = new ListSelectionListener() {
39 | @Override
40 | public void valueChanged(final ListSelectionEvent event) {
41 | subscriber.onNext(event);
42 | }
43 |
44 | };
45 | listSelectionModel.addListSelectionListener(listener);
46 | subscriber.add(Subscriptions.create(new Action0() {
47 | @Override
48 | public void call() {
49 | listSelectionModel.removeListSelectionListener(listener);
50 | }
51 | }));
52 | }
53 | }).subscribeOn(SwingScheduler.getInstance())
54 | .unsubscribeOn(SwingScheduler.getInstance());
55 | }
56 | }
57 |
--------------------------------------------------------------------------------
/src/main/java/rx/swing/sources/MouseEventSource.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright 2014 Netflix, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package rx.swing.sources;
17 |
18 | import rx.Observable;
19 | import rx.Observable.OnSubscribe;
20 | import rx.Subscriber;
21 | import rx.functions.Action0;
22 | import rx.functions.Func2;
23 | import rx.schedulers.SwingScheduler;
24 | import rx.subscriptions.Subscriptions;
25 |
26 | import java.awt.*;
27 | import java.awt.event.*;
28 |
29 | public enum MouseEventSource {
30 | ; // no instances
31 |
32 | /**
33 | * @see rx.observables.SwingObservable#fromMouseEvents
34 | */
35 | public static Observable fromMouseEventsOf(final Component component) {
36 | return Observable.create(new OnSubscribe() {
37 | @Override
38 | public void call(final Subscriber super MouseEvent> subscriber) {
39 | final MouseListener listener = new MouseListener() {
40 | @Override
41 | public void mouseClicked(MouseEvent event) {
42 | subscriber.onNext(event);
43 | }
44 |
45 | @Override
46 | public void mousePressed(MouseEvent event) {
47 | subscriber.onNext(event);
48 | }
49 |
50 | @Override
51 | public void mouseReleased(MouseEvent event) {
52 | subscriber.onNext(event);
53 | }
54 |
55 | @Override
56 | public void mouseEntered(MouseEvent event) {
57 | subscriber.onNext(event);
58 | }
59 |
60 | @Override
61 | public void mouseExited(MouseEvent event) {
62 | subscriber.onNext(event);
63 | }
64 | };
65 | component.addMouseListener(listener);
66 |
67 | subscriber.add(Subscriptions.create(new Action0() {
68 | @Override
69 | public void call() {
70 | component.removeMouseListener(listener);
71 | }
72 | }));
73 | }
74 | }).subscribeOn(SwingScheduler.getInstance())
75 | .unsubscribeOn(SwingScheduler.getInstance());
76 | }
77 |
78 | /**
79 | * @see rx.observables.SwingObservable#fromMouseMotionEvents
80 | */
81 | public static Observable fromMouseMotionEventsOf(final Component component) {
82 | return Observable.create(new OnSubscribe() {
83 | @Override
84 | public void call(final Subscriber super MouseEvent> subscriber) {
85 | final MouseMotionListener listener = new MouseMotionListener() {
86 | @Override
87 | public void mouseDragged(MouseEvent event) {
88 | subscriber.onNext(event);
89 | }
90 |
91 | @Override
92 | public void mouseMoved(MouseEvent event) {
93 | subscriber.onNext(event);
94 | }
95 | };
96 | component.addMouseMotionListener(listener);
97 |
98 | subscriber.add(Subscriptions.create(new Action0() {
99 | @Override
100 | public void call() {
101 | component.removeMouseMotionListener(listener);
102 | }
103 | }));
104 | }
105 | }).subscribeOn(SwingScheduler.getInstance())
106 | .unsubscribeOn(SwingScheduler.getInstance());
107 | }
108 |
109 | public static Observable fromMouseWheelEvents(final Component component){
110 | return Observable.create(new OnSubscribe() {
111 | @Override
112 | public void call(final Subscriber super MouseWheelEvent> subscriber) {
113 | final MouseWheelListener listener = new MouseWheelListener() {
114 | @Override
115 | public void mouseWheelMoved(MouseWheelEvent event) {
116 | subscriber.onNext(event);
117 | }
118 | };
119 | component.addMouseWheelListener(listener);
120 |
121 | subscriber.add(Subscriptions.create(new Action0() {
122 | @Override
123 | public void call() {
124 | component.removeMouseWheelListener(listener);
125 | }
126 | }));
127 | }
128 | }).subscribeOn(SwingScheduler.getInstance())
129 | .unsubscribeOn(SwingScheduler.getInstance());
130 | }
131 |
132 | /**
133 | * @see rx.observables.SwingObservable#fromRelativeMouseMotion
134 | */
135 | public static Observable fromRelativeMouseMotion(final Component component) {
136 | final Observable events = fromMouseMotionEventsOf(component);
137 | return Observable.zip(events, events.skip(1), new Func2() {
138 | @Override
139 | public Point call(MouseEvent ev1, MouseEvent ev2) {
140 | return new Point(ev2.getX() - ev1.getX(), ev2.getY() - ev1.getY());
141 | }
142 | }).subscribeOn(SwingScheduler.getInstance())
143 | .unsubscribeOn(SwingScheduler.getInstance());
144 | }
145 |
146 | }
147 |
--------------------------------------------------------------------------------
/src/main/java/rx/swing/sources/PropertyChangeEventSource.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright 2015 Netflix, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package rx.swing.sources;
17 |
18 | import rx.Observable;
19 | import rx.Observable.OnSubscribe;
20 | import rx.Subscriber;
21 | import rx.functions.Action0;
22 | import rx.schedulers.SwingScheduler;
23 | import rx.subscriptions.Subscriptions;
24 |
25 | import java.awt.*;
26 | import java.beans.PropertyChangeEvent;
27 | import java.beans.PropertyChangeListener;
28 |
29 | public enum PropertyChangeEventSource { ; // no instances
30 |
31 | public static Observable fromPropertyChangeEventsOf(final Component component) {
32 | return Observable.create(new OnSubscribe() {
33 | @Override
34 | public void call(final Subscriber super PropertyChangeEvent> subscriber) {
35 | final PropertyChangeListener listener = new PropertyChangeListener() {
36 | @Override
37 | public void propertyChange(PropertyChangeEvent event) {
38 | subscriber.onNext(event);
39 | }
40 | };
41 | component.addPropertyChangeListener(listener);
42 | subscriber.add(Subscriptions.create(new Action0() {
43 | @Override
44 | public void call() {
45 | component.removePropertyChangeListener(listener);
46 | }
47 | }));
48 | }
49 | }).subscribeOn(SwingScheduler.getInstance())
50 | .unsubscribeOn(SwingScheduler.getInstance());
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/src/main/java/rx/swing/sources/SwingTestHelper.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright 2014 Netflix, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package rx.swing.sources;
17 |
18 | import java.util.concurrent.CountDownLatch;
19 | import java.util.concurrent.TimeUnit;
20 |
21 | import rx.Scheduler.Worker;
22 | import rx.functions.Action0;
23 | import rx.schedulers.SwingScheduler;
24 |
25 | /* package-private */final class SwingTestHelper { // only for test
26 |
27 | private final CountDownLatch latch = new CountDownLatch(1);
28 | private volatile Throwable error;
29 |
30 | private SwingTestHelper() {
31 | }
32 |
33 | public static SwingTestHelper create() {
34 | return new SwingTestHelper();
35 | }
36 |
37 | public SwingTestHelper runInEventDispatchThread(final Action0 action) {
38 | Worker inner = SwingScheduler.getInstance().createWorker();
39 | inner.schedule(new Action0() {
40 |
41 | @Override
42 | public void call() {
43 | try {
44 | action.call();
45 | } catch (Throwable e) {
46 | error = e;
47 | }
48 | latch.countDown();
49 | }
50 | });
51 | return this;
52 | }
53 |
54 | public void awaitTerminal() throws Throwable {
55 | latch.await();
56 | if (error != null) {
57 | throw error;
58 | }
59 | }
60 |
61 | public void awaitTerminal(long timeout, TimeUnit unit) throws Throwable {
62 | latch.await(timeout, unit);
63 | if (error != null) {
64 | throw error;
65 | }
66 | }
67 |
68 | }
69 |
--------------------------------------------------------------------------------
/src/main/java/rx/swing/sources/WindowEventSource.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright 2015 Netflix
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package rx.swing.sources;
17 |
18 | import rx.Observable;
19 | import rx.Observable.OnSubscribe;
20 | import rx.Subscriber;
21 | import rx.functions.Action0;
22 | import rx.schedulers.SwingScheduler;
23 | import rx.subscriptions.Subscriptions;
24 |
25 | import java.awt.*;
26 | import java.awt.event.WindowEvent;
27 | import java.awt.event.WindowListener;
28 |
29 |
30 | public enum WindowEventSource { ; // no instances
31 |
32 | /**
33 | * @see rx.observables.SwingObservable#fromWindowEventsOf(Window)
34 | */
35 | public static Observable fromWindowEventsOf(final Window window) {
36 | return Observable.create(new OnSubscribe() {
37 | @Override
38 | public void call(final Subscriber super WindowEvent> subscriber) {
39 | final WindowListener windowListener = new WindowListener() {
40 | @Override
41 | public void windowOpened(WindowEvent windowEvent) {
42 | subscriber.onNext(windowEvent);
43 | }
44 |
45 | @Override
46 | public void windowClosing(WindowEvent windowEvent) {
47 | subscriber.onNext(windowEvent);
48 | }
49 |
50 | @Override
51 | public void windowClosed(WindowEvent windowEvent) {
52 | subscriber.onNext(windowEvent);
53 | }
54 |
55 | @Override
56 | public void windowIconified(WindowEvent windowEvent) {
57 | subscriber.onNext(windowEvent);
58 | }
59 |
60 | @Override
61 | public void windowDeiconified(WindowEvent windowEvent) {
62 | subscriber.onNext(windowEvent);
63 | }
64 |
65 | @Override
66 | public void windowActivated(WindowEvent windowEvent) {
67 | subscriber.onNext(windowEvent);
68 | }
69 |
70 | @Override
71 | public void windowDeactivated(WindowEvent windowEvent) {
72 | subscriber.onNext(windowEvent);
73 | }
74 | };
75 |
76 | window.addWindowListener(windowListener);
77 |
78 | subscriber.add(Subscriptions.create(new Action0() {
79 | @Override
80 | public void call() {
81 | window.removeWindowListener(windowListener);
82 | }
83 | }));
84 | }
85 | }).subscribeOn(SwingScheduler.getInstance())
86 | .unsubscribeOn(SwingScheduler.getInstance());
87 | }
88 | }
89 |
--------------------------------------------------------------------------------
/src/test/java/rx/schedulers/SwingSchedulerTest.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright 2014 Netflix, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package rx.schedulers;
17 |
18 | import static org.junit.Assert.assertTrue;
19 | import static org.junit.Assert.fail;
20 | import static org.mockito.Mockito.inOrder;
21 | import static org.mockito.Mockito.mock;
22 | import static org.mockito.Mockito.times;
23 | import static org.mockito.Mockito.verify;
24 |
25 | import java.awt.EventQueue;
26 | import java.util.concurrent.CountDownLatch;
27 | import java.util.concurrent.TimeUnit;
28 |
29 | import javax.swing.SwingUtilities;
30 |
31 | import org.junit.Rule;
32 | import org.junit.Test;
33 | import org.junit.rules.ExpectedException;
34 | import org.mockito.InOrder;
35 |
36 | import rx.Scheduler.Worker;
37 | import rx.functions.Action0;
38 |
39 | /**
40 | * Executes work on the Swing UI thread.
41 | * This scheduler should only be used with actions that execute quickly.
42 | */
43 | public final class SwingSchedulerTest {
44 |
45 | @Rule
46 | public ExpectedException exception = ExpectedException.none();
47 |
48 | @Test
49 | public void testInvalidDelayValues() {
50 | final SwingScheduler scheduler = new SwingScheduler();
51 | final Worker inner = scheduler.createWorker();
52 | final Action0 action = mock(Action0.class);
53 |
54 | inner.schedulePeriodically(action, -1L, 100L, TimeUnit.SECONDS);
55 |
56 | inner.schedulePeriodically(action, 100L, -1L, TimeUnit.SECONDS);
57 |
58 | exception.expect(IllegalArgumentException.class);
59 | inner.schedulePeriodically(action, 1L + Integer.MAX_VALUE, 100L, TimeUnit.MILLISECONDS);
60 |
61 | exception.expect(IllegalArgumentException.class);
62 | inner.schedulePeriodically(action, 100L, 1L + Integer.MAX_VALUE / 1000, TimeUnit.SECONDS);
63 | }
64 |
65 | @Test
66 | public void testPeriodicScheduling() throws Exception {
67 | final SwingScheduler scheduler = new SwingScheduler();
68 | final Worker inner = scheduler.createWorker();
69 |
70 | final CountDownLatch latch = new CountDownLatch(4);
71 |
72 | final Action0 innerAction = mock(Action0.class);
73 | final Action0 action = new Action0() {
74 | @Override
75 | public void call() {
76 | try {
77 | innerAction.call();
78 | assertTrue(SwingUtilities.isEventDispatchThread());
79 | } finally {
80 | latch.countDown();
81 | }
82 | }
83 | };
84 |
85 | inner.schedulePeriodically(action, 50, 200, TimeUnit.MILLISECONDS);
86 |
87 | if (!latch.await(5000, TimeUnit.MILLISECONDS)) {
88 | fail("timed out waiting for tasks to execute");
89 | }
90 |
91 | inner.unsubscribe();
92 | waitForEmptyEventQueue();
93 | verify(innerAction, times(4)).call();
94 | }
95 |
96 | @Test
97 | public void testNestedActions() throws Exception {
98 | final SwingScheduler scheduler = new SwingScheduler();
99 | final Worker inner = scheduler.createWorker();
100 |
101 | final Action0 firstStepStart = mock(Action0.class);
102 | final Action0 firstStepEnd = mock(Action0.class);
103 |
104 | final Action0 secondStepStart = mock(Action0.class);
105 | final Action0 secondStepEnd = mock(Action0.class);
106 |
107 | final Action0 thirdStepStart = mock(Action0.class);
108 | final Action0 thirdStepEnd = mock(Action0.class);
109 |
110 | final Action0 firstAction = new Action0() {
111 | @Override
112 | public void call() {
113 | assertTrue(SwingUtilities.isEventDispatchThread());
114 | firstStepStart.call();
115 | firstStepEnd.call();
116 | }
117 | };
118 | final Action0 secondAction = new Action0() {
119 | @Override
120 | public void call() {
121 | assertTrue(SwingUtilities.isEventDispatchThread());
122 | secondStepStart.call();
123 | inner.schedule(firstAction);
124 | secondStepEnd.call();
125 | }
126 | };
127 | final Action0 thirdAction = new Action0() {
128 | @Override
129 | public void call() {
130 | assertTrue(SwingUtilities.isEventDispatchThread());
131 | thirdStepStart.call();
132 | inner.schedule(secondAction);
133 | thirdStepEnd.call();
134 | }
135 | };
136 |
137 | InOrder inOrder = inOrder(firstStepStart, firstStepEnd, secondStepStart, secondStepEnd, thirdStepStart, thirdStepEnd);
138 |
139 | inner.schedule(thirdAction);
140 | waitForEmptyEventQueue();
141 |
142 | inOrder.verify(thirdStepStart, times(1)).call();
143 | inOrder.verify(secondStepStart, times(1)).call();
144 | inOrder.verify(firstStepStart, times(1)).call();
145 | inOrder.verify(firstStepEnd, times(1)).call();
146 | inOrder.verify(secondStepEnd, times(1)).call();
147 | inOrder.verify(thirdStepEnd, times(1)).call();
148 | }
149 |
150 | private static void waitForEmptyEventQueue() throws Exception {
151 | EventQueue.invokeAndWait(new Runnable() {
152 | @Override
153 | public void run() {
154 | // nothing to do, we're just waiting here for the event queue to be emptied
155 | }
156 | });
157 | }
158 |
159 | }
160 |
--------------------------------------------------------------------------------
/src/test/java/rx/swing/sources/AbstractButtonSourceTest.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright 2014 Netflix, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package rx.swing.sources;
17 |
18 | import java.awt.event.ActionEvent;
19 |
20 | import static org.mockito.Mockito.mock;
21 | import static org.mockito.Mockito.never;
22 | import static org.mockito.Mockito.times;
23 | import static org.mockito.Mockito.verify;
24 |
25 | import org.junit.Test;
26 | import org.mockito.Matchers;
27 |
28 | import javax.swing.AbstractButton;
29 |
30 | import rx.Subscription;
31 | import rx.functions.Action0;
32 | import rx.functions.Action1;
33 |
34 | public class AbstractButtonSourceTest {
35 | @Test
36 | public void testObservingActionEvents() throws Throwable {
37 | SwingTestHelper.create().runInEventDispatchThread(new Action0() {
38 |
39 | @Override
40 | public void call() {
41 | @SuppressWarnings("unchecked")
42 | Action1 action = mock(Action1.class);
43 | @SuppressWarnings("unchecked")
44 | Action1 error = mock(Action1.class);
45 | Action0 complete = mock(Action0.class);
46 |
47 | final ActionEvent event = new ActionEvent(this, 1, "command");
48 |
49 | @SuppressWarnings("serial")
50 | class TestButton extends AbstractButton {
51 | void testAction() {
52 | fireActionPerformed(event);
53 | }
54 | }
55 |
56 | TestButton button = new TestButton();
57 | Subscription sub = AbstractButtonSource.fromActionOf(button).subscribe(action,
58 | error, complete);
59 |
60 | verify(action, never()).call(Matchers. any());
61 | verify(error, never()).call(Matchers. any());
62 | verify(complete, never()).call();
63 |
64 | button.testAction();
65 | verify(action, times(1)).call(Matchers. any());
66 |
67 | button.testAction();
68 | verify(action, times(2)).call(Matchers. any());
69 |
70 | sub.unsubscribe();
71 | button.testAction();
72 | verify(action, times(2)).call(Matchers. any());
73 | verify(error, never()).call(Matchers. any());
74 | verify(complete, never()).call();
75 | }
76 |
77 | }).awaitTerminal();
78 | }
79 | }
80 |
--------------------------------------------------------------------------------
/src/test/java/rx/swing/sources/ChangeEventSourceTest.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright 2015 Netflix, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package rx.swing.sources;
17 |
18 | import org.junit.Test;
19 | import rx.Subscription;
20 | import rx.functions.Action0;
21 | import rx.observers.TestSubscriber;
22 |
23 | import javax.swing.*;
24 | import javax.swing.colorchooser.ColorSelectionModel;
25 | import javax.swing.event.ChangeEvent;
26 | import javax.swing.event.ChangeListener;
27 | import java.awt.*;
28 | import java.lang.reflect.InvocationTargetException;
29 | import java.util.Arrays;
30 | import java.util.List;
31 |
32 | import static org.junit.Assert.*;
33 |
34 | public class ChangeEventSourceTest {
35 |
36 | @Test
37 | public void jTabbedPane_observingSelectionEvents() throws Throwable {
38 | SwingTestHelper.create().runInEventDispatchThread(new Action0() {
39 |
40 | @Override
41 | public void call() {
42 | TestSubscriber testSubscriber = TestSubscriber.create();
43 |
44 | JTabbedPane tabbedPane = createTabbedPane();
45 | ChangeEventSource.fromChangeEventsOf(tabbedPane)
46 | .subscribe(testSubscriber);
47 |
48 | testSubscriber.assertNoErrors();
49 | testSubscriber.assertNoValues();
50 |
51 | tabbedPane.setSelectedIndex(2);
52 |
53 | testSubscriber.assertNoErrors();
54 | testSubscriber.assertValueCount(1);
55 |
56 | assertEquals(tabbedPane, testSubscriber.getOnNextEvents().get(0).getSource());
57 |
58 | tabbedPane.setSelectedIndex(0);
59 |
60 | testSubscriber.assertNoErrors();
61 | testSubscriber.assertValueCount(2);
62 |
63 | assertEquals(tabbedPane, testSubscriber.getOnNextEvents().get(1).getSource());
64 | }
65 | }).awaitTerminal();
66 | }
67 |
68 | @Test
69 | public void jSlider_observingValueChangeEvents() throws Throwable {
70 | SwingTestHelper.create().runInEventDispatchThread(new Action0() {
71 |
72 | @Override
73 | public void call() {
74 | TestSubscriber testSubscriber = TestSubscriber.create();
75 |
76 | JSlider slider = new JSlider();
77 | slider.setMinimum(0);
78 | slider.setMaximum(10);
79 | ChangeEventSource.fromChangeEventsOf(slider)
80 | .subscribe(testSubscriber);
81 |
82 | testSubscriber.assertNoErrors();
83 | testSubscriber.assertNoValues();
84 |
85 | slider.setValue(5);
86 |
87 | testSubscriber.assertNoErrors();
88 | testSubscriber.assertValueCount(1);
89 |
90 | assertEquals(slider, testSubscriber.getOnNextEvents().get(0).getSource());
91 |
92 | slider.setValue(8);
93 |
94 | testSubscriber.assertNoErrors();
95 | testSubscriber.assertValueCount(2);
96 |
97 | assertEquals(slider, testSubscriber.getOnNextEvents().get(1).getSource());
98 | }
99 | }).awaitTerminal();
100 | }
101 |
102 | @Test
103 | public void jSpinner_observingValueChangeEvents() throws Throwable {
104 | SwingTestHelper.create().runInEventDispatchThread(new Action0() {
105 |
106 | @Override
107 | public void call() {
108 | TestSubscriber testSubscriber = TestSubscriber.create();
109 |
110 | JSpinner spinner = createSpinner();
111 | ChangeEventSource.fromChangeEventsOf(spinner)
112 | .subscribe(testSubscriber);
113 |
114 | testSubscriber.assertNoErrors();
115 | testSubscriber.assertNoValues();
116 |
117 | spinner.setValue("2015");
118 |
119 | testSubscriber.assertNoErrors();
120 | testSubscriber.assertValueCount(1);
121 |
122 | assertEquals(spinner, testSubscriber.getOnNextEvents().get(0).getSource());
123 |
124 | spinner.setValue("2016");
125 |
126 | testSubscriber.assertNoErrors();
127 | testSubscriber.assertValueCount(2);
128 |
129 | assertEquals(spinner, testSubscriber.getOnNextEvents().get(1).getSource());
130 | }
131 | }).awaitTerminal();
132 | }
133 |
134 | @Test
135 | public void spinnerModel_observingValueChangeEvents() throws Throwable {
136 | SwingTestHelper.create().runInEventDispatchThread(new Action0() {
137 |
138 | @Override
139 | public void call() {
140 | TestSubscriber testSubscriber = TestSubscriber.create();
141 |
142 | JSpinner spinner = createSpinner();
143 | final SpinnerModel spinnerModel = spinner.getModel();
144 | ChangeEventSource.fromChangeEventsOf(spinnerModel)
145 | .subscribe(testSubscriber);
146 |
147 | testSubscriber.assertNoErrors();
148 | testSubscriber.assertNoValues();
149 |
150 | spinner.setValue("2015");
151 |
152 | testSubscriber.assertNoErrors();
153 | testSubscriber.assertValueCount(1);
154 |
155 | assertEquals(spinnerModel, testSubscriber.getOnNextEvents().get(0).getSource());
156 |
157 | spinner.setValue("2016");
158 |
159 | testSubscriber.assertNoErrors();
160 | testSubscriber.assertValueCount(2);
161 |
162 | assertEquals(spinnerModel, testSubscriber.getOnNextEvents().get(1).getSource());
163 | }
164 | }).awaitTerminal();
165 | }
166 |
167 | @Test
168 | public void abstractButton_observingPressedEvents() throws Throwable {
169 | SwingTestHelper.create().runInEventDispatchThread(new Action0() {
170 |
171 | @Override
172 | public void call() {
173 | TestSubscriber testSubscriber = TestSubscriber.create();
174 |
175 | AbstractButton button = new JButton("Click me");
176 | ChangeEventSource.fromChangeEventsOf(button)
177 | .subscribe(testSubscriber);
178 |
179 | testSubscriber.assertNoErrors();
180 | testSubscriber.assertNoValues();
181 |
182 | button.getModel().setPressed(true);
183 |
184 | testSubscriber.assertNoErrors();
185 | testSubscriber.assertValueCount(1);
186 |
187 | assertEquals(button, testSubscriber.getOnNextEvents().get(0).getSource());
188 |
189 | button.getModel().setPressed(false);
190 |
191 | testSubscriber.assertNoErrors();
192 | testSubscriber.assertValueCount(2);
193 |
194 | assertEquals(button, testSubscriber.getOnNextEvents().get(1).getSource());
195 | }
196 | }).awaitTerminal();
197 | }
198 |
199 | @Test
200 | public void buttonModel_observingPressedEvents() throws Throwable {
201 | SwingTestHelper.create().runInEventDispatchThread(new Action0() {
202 |
203 | @Override
204 | public void call() {
205 | TestSubscriber testSubscriber = TestSubscriber.create();
206 |
207 | AbstractButton button = new JButton("Click me");
208 | final ButtonModel buttonModel = button.getModel();
209 | ChangeEventSource.fromChangeEventsOf(buttonModel)
210 | .subscribe(testSubscriber);
211 |
212 | testSubscriber.assertNoErrors();
213 | testSubscriber.assertNoValues();
214 |
215 | buttonModel.setPressed(true);
216 |
217 | testSubscriber.assertNoErrors();
218 | testSubscriber.assertValueCount(1);
219 |
220 | assertEquals(buttonModel, testSubscriber.getOnNextEvents().get(0).getSource());
221 |
222 | buttonModel.setPressed(false);
223 |
224 | testSubscriber.assertNoErrors();
225 | testSubscriber.assertValueCount(2);
226 |
227 | assertEquals(buttonModel, testSubscriber.getOnNextEvents().get(1).getSource());
228 | }
229 | }).awaitTerminal();
230 | }
231 |
232 | @Test
233 | public void jViewPort_observingScrollEvents() throws Throwable {
234 | SwingTestHelper.create().runInEventDispatchThread(new Action0() {
235 |
236 | @Override
237 | public void call() {
238 | TestSubscriber testSubscriber = TestSubscriber.create();
239 |
240 | JTable table = new JTable(1000, 5);
241 | JScrollPane scrollPane = new JScrollPane(table);
242 | final JViewport viewPort = scrollPane.getViewport();
243 | ChangeEventSource.fromChangeEventsOf(viewPort)
244 | .subscribe(testSubscriber);
245 |
246 | testSubscriber.assertNoErrors();
247 | testSubscriber.assertNoValues();
248 |
249 | // scoll down
250 | table.scrollRectToVisible(table.getCellRect(table.getModel().getRowCount() - 1, 0, false));
251 |
252 | testSubscriber.assertNoErrors();
253 | testSubscriber.assertValueCount(1);
254 |
255 | assertEquals(viewPort, testSubscriber.getOnNextEvents().get(0).getSource());
256 |
257 | // scoll up
258 | table.scrollRectToVisible(table.getCellRect(0, 0, false));
259 |
260 | testSubscriber.assertNoErrors();
261 | testSubscriber.assertValueCount(2);
262 |
263 | assertEquals(viewPort, testSubscriber.getOnNextEvents().get(1).getSource());
264 | }
265 | }).awaitTerminal();
266 | }
267 |
268 | @Test
269 | public void colorSelectionModel_observingColorChooserEvents() throws Throwable {
270 | SwingTestHelper.create().runInEventDispatchThread(new Action0() {
271 |
272 | @Override
273 | public void call() {
274 | TestSubscriber testSubscriber = TestSubscriber.create();
275 |
276 | JColorChooser colorChooser = new JColorChooser();
277 | final ColorSelectionModel colorSelectionModel = colorChooser.getSelectionModel();
278 | ChangeEventSource.fromChangeEventsOf(colorSelectionModel)
279 | .subscribe(testSubscriber);
280 |
281 | testSubscriber.assertNoErrors();
282 | testSubscriber.assertNoValues();
283 |
284 | colorChooser.setColor(Color.BLUE);
285 |
286 | testSubscriber.assertNoErrors();
287 | testSubscriber.assertValueCount(1);
288 |
289 | assertEquals(colorSelectionModel, testSubscriber.getOnNextEvents().get(0).getSource());
290 |
291 | colorChooser.setColor(Color.GREEN);
292 |
293 | testSubscriber.assertNoErrors();
294 | testSubscriber.assertValueCount(2);
295 |
296 | assertEquals(colorSelectionModel, testSubscriber.getOnNextEvents().get(1).getSource());
297 | }
298 | }).awaitTerminal();
299 | }
300 |
301 | @Test
302 | public void jProgressBar_observingProgressEvents() throws Throwable {
303 | SwingTestHelper.create().runInEventDispatchThread(new Action0() {
304 |
305 | @Override
306 | public void call() {
307 | TestSubscriber testSubscriber = TestSubscriber.create();
308 |
309 | JProgressBar progressBar = new JProgressBar();
310 | progressBar.setMinimum(0);
311 | progressBar.setMaximum(10);
312 | ChangeEventSource.fromChangeEventsOf(progressBar)
313 | .subscribe(testSubscriber);
314 |
315 | testSubscriber.assertNoErrors();
316 | testSubscriber.assertNoValues();
317 |
318 | progressBar.setValue(1);
319 |
320 | testSubscriber.assertNoErrors();
321 | testSubscriber.assertValueCount(1);
322 |
323 | assertEquals(progressBar, testSubscriber.getOnNextEvents().get(0).getSource());
324 |
325 | progressBar.setValue(2);
326 |
327 | testSubscriber.assertNoErrors();
328 | testSubscriber.assertValueCount(2);
329 |
330 | assertEquals(progressBar, testSubscriber.getOnNextEvents().get(1).getSource());
331 | }
332 | }).awaitTerminal();
333 | }
334 |
335 | @Test
336 | public void boundedRangeModel_observingProgressEvents() throws Throwable {
337 | SwingTestHelper.create().runInEventDispatchThread(new Action0() {
338 |
339 | @Override
340 | public void call() {
341 | TestSubscriber testSubscriber = TestSubscriber.create();
342 |
343 | JProgressBar progressBar = new JProgressBar();
344 | progressBar.setMinimum(0);
345 | progressBar.setMaximum(10);
346 | final BoundedRangeModel boundedRangeModel = progressBar.getModel();
347 | ChangeEventSource.fromChangeEventsOf(boundedRangeModel)
348 | .subscribe(testSubscriber);
349 |
350 | testSubscriber.assertNoErrors();
351 | testSubscriber.assertNoValues();
352 |
353 | progressBar.setValue(1);
354 |
355 | testSubscriber.assertNoErrors();
356 | testSubscriber.assertValueCount(1);
357 |
358 | assertEquals(boundedRangeModel, testSubscriber.getOnNextEvents().get(0).getSource());
359 |
360 | progressBar.setValue(2);
361 |
362 | testSubscriber.assertNoErrors();
363 | testSubscriber.assertValueCount(2);
364 |
365 | assertEquals(boundedRangeModel, testSubscriber.getOnNextEvents().get(1).getSource());
366 | }
367 | }).awaitTerminal();
368 | }
369 |
370 | @Test
371 | public void unsubscribeRemovesRowSelectionListener() throws Throwable {
372 | SwingTestHelper.create().runInEventDispatchThread(new Action0() {
373 |
374 | @Override
375 | public void call() {
376 | TestSubscriber testSubscriber = TestSubscriber.create();
377 |
378 | JTabbedPane tabbedPane = createTabbedPane();
379 | int numberOfListenersBefore = tabbedPane.getChangeListeners().length;
380 |
381 | Subscription sub = ChangeEventSource.fromChangeEventsOf(tabbedPane)
382 | .subscribe(testSubscriber);
383 |
384 | testSubscriber.assertNoErrors();
385 | testSubscriber.assertNoValues();
386 |
387 | sub.unsubscribe();
388 |
389 | testSubscriber.assertUnsubscribed();
390 |
391 | tabbedPane.setSelectedIndex(2);
392 |
393 | testSubscriber.assertNoErrors();
394 | testSubscriber.assertNoValues();
395 |
396 | assertEquals(numberOfListenersBefore, tabbedPane.getChangeListeners().length);
397 | }
398 | }).awaitTerminal();
399 | }
400 |
401 | @Test
402 | public void fromChangeEventsOf_usingObjectWithoutExpectedChangeListenerSupport_failsFastWithException() throws Throwable {
403 | SwingTestHelper.create().runInEventDispatchThread(new Action0() {
404 |
405 | @Override
406 | public void call() {
407 | try {
408 | ChangeEventSource.fromChangeEventsOf("doesNotSupportChangeListeners").subscribe(TestSubscriber.create());
409 | fail(IllegalArgumentException.class.getSimpleName() + " expected");
410 | } catch (IllegalArgumentException ex) {
411 | assertEquals("Class 'java.lang.String' has not the expected signature to support change listeners in rx.swing.sources.ChangeEventSource",
412 | ex.getMessage());
413 | }
414 |
415 | Object changeEventSource = null;
416 | try {
417 | changeEventSource = new Object() {
418 | private void addChangeListener(ChangeListener changeListener) {/* no-op */ }
419 |
420 | private void removeChangeListener(ChangeListener changeListener) {/* no-op */ }
421 |
422 | @Override
423 | public String toString() {
424 | return "hasWrongMethodModifiers";
425 | }
426 | };
427 | ChangeEventSource.fromChangeEventsOf(changeEventSource).subscribe(TestSubscriber.create());
428 | fail(IllegalArgumentException.class.getSimpleName() + " expected");
429 | } catch (IllegalArgumentException ex) {
430 | assertEquals("Class '" + changeEventSource.getClass().getName() + "' has not the expected signature to support change listeners in rx.swing.sources.ChangeEventSource",
431 | ex.getMessage());
432 | }
433 | }
434 | }).awaitTerminal();
435 | }
436 |
437 | @Test
438 | public void issuesWithAddingChangeListenerOnSubscriptionArePropagatedAsError() throws Throwable {
439 | SwingTestHelper.create().runInEventDispatchThread(new Action0() {
440 |
441 | @Override
442 | public void call() {
443 | TestSubscriber testSubscriber = TestSubscriber.create();
444 |
445 | JProgressBar brokenProgressBarSubClass = new JProgressBar() {
446 | @Override
447 | public void addChangeListener(ChangeListener listener) {
448 | if (listener.getClass().getName().contains(ChangeEventSource.class.getSimpleName())) {
449 | throw new RuntimeException("Totally broken");
450 | }
451 | }
452 | };
453 | ChangeEventSource.fromChangeEventsOf(brokenProgressBarSubClass)
454 | .subscribe(testSubscriber);
455 |
456 | testSubscriber.assertNoValues();
457 |
458 | List onErrorEvents = testSubscriber.getOnErrorEvents();
459 | assertEquals(1, onErrorEvents.size());
460 | assertTrue(onErrorEvents.get(0) instanceof RuntimeException);
461 | assertEquals("Call of addChangeListener via reflection failed.", onErrorEvents.get(0).getMessage());
462 | assertEquals(InvocationTargetException.class, onErrorEvents.get(0).getCause().getClass());
463 | }
464 | }).awaitTerminal();
465 | }
466 |
467 | private static JTabbedPane createTabbedPane() {
468 | final JTabbedPane tabbedPane = new JTabbedPane();
469 | tabbedPane.addTab("tab1", new JPanel());
470 | tabbedPane.addTab("tab2", new JPanel());
471 | tabbedPane.addTab("tab3", new JPanel());
472 | return tabbedPane;
473 | }
474 |
475 | private static JSpinner createSpinner() {
476 | List yearStrings = Arrays.asList("2014", "2015", "2016");
477 | SpinnerListModel spinnerListModel = new SpinnerListModel(yearStrings);
478 | return new JSpinner(spinnerListModel);
479 | }
480 | }
--------------------------------------------------------------------------------
/src/test/java/rx/swing/sources/ContainerEventSourceTest.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright 2015 Netflix, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package rx.swing.sources;
17 |
18 | import java.awt.Component;
19 | import java.awt.Container;
20 | import java.awt.event.ContainerEvent;
21 | import java.awt.event.ContainerListener;
22 | import java.util.Arrays;
23 | import java.util.Collection;
24 |
25 | import javax.swing.JPanel;
26 |
27 | import org.hamcrest.Matcher;
28 | import org.junit.Assert;
29 | import org.junit.Before;
30 | import org.junit.Test;
31 | import org.junit.runner.RunWith;
32 | import org.junit.runners.Parameterized;
33 | import org.junit.runners.Parameterized.Parameters;
34 | import org.mockito.ArgumentMatcher;
35 | import org.mockito.InOrder;
36 | import org.mockito.Matchers;
37 | import org.mockito.Mockito;
38 |
39 | import rx.Observable;
40 | import rx.Subscription;
41 | import rx.functions.Action0;
42 | import rx.functions.Action1;
43 | import rx.functions.Func1;
44 | import rx.observables.SwingObservable;
45 | import rx.swing.sources.ContainerEventSource.Predicate;
46 |
47 | @RunWith(Parameterized.class)
48 | public class ContainerEventSourceTest {
49 |
50 | private final Func1> observableFactory;
51 |
52 | private JPanel panel;
53 | private Action1 action;
54 | private Action1 error;
55 | private Action0 complete;
56 |
57 | public ContainerEventSourceTest(Func1> observableFactory) {
58 | this.observableFactory = observableFactory;
59 | }
60 |
61 | @Parameters
62 | public static Collection