first commit

This commit is contained in:
J62 2025-03-12 17:57:28 -07:00
commit 8421f7056b
1096 changed files with 329210 additions and 0 deletions

10
.gitattributes vendored Normal file
View File

@ -0,0 +1,10 @@
# Auto detect text files and perform LF normalization
* text=auto
#
# The above will handle all files NOT found below
#
# These files are text and should be normalized (Convert crlf => lf)
*.bat text eol=crlf
*.java text diff=java
*.sh text eol=lf

23
.github/ISSUE_TEMPLATE/bug_report.md vendored Normal file
View File

@ -0,0 +1,23 @@
---
name: Bug report
about: Create a report to help us improve
---
**Describe the bug**
A clear and concise description of what the bug is.
**To Reproduce**
Steps to reproduce the behavior:
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error
**Desktop (please complete the following information):**
- OS: [e.g. Windows, Mac, Linux]
- Ctbrec Version [e.g. 1.12.1 JRE]
- Standalone or Client / Server mode
**Log**
If there are any errors in the ctbrec.log, please add them here. You can find the ctbrec.log next to the ctbrec.exe.

View File

@ -0,0 +1,17 @@
---
name: Feature request
about: Suggest an idea for this project
---
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
**Describe the solution you'd like**
A clear and concise description of what you want to happen.
**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.
**Additional context**
Add any other context or screenshots about the feature request here.

7
.github/ISSUE_TEMPLATE/other.md vendored Normal file
View File

@ -0,0 +1,7 @@
---
name: Other
about: Anything else
---

9
.gitignore vendored Normal file
View File

@ -0,0 +1,9 @@
.idea
**.log
.debug-config
.vscode
.settings/
.classpath
.project
*/.factorypath
**/.antlr/

1257
CHANGELOG.md Normal file

File diff suppressed because it is too large Load Diff

674
LICENSE.txt Normal file
View File

@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.

17
README.md Normal file
View File

@ -0,0 +1,17 @@
# CTB Recorder
A free recording software for different camsites. Currently supported: BongaCams, Cam4, CamSoda, Chaturbate, FC2Live, LiveJasmin, MyFreeCams, Streamate
![Screenshot](https://raw.githubusercontent.com/0xboobface/ctbrec/master/docs/img/featured-s.jpg)
If you ever wanted to record a cam girl show to watch it later or if your favorite model lives in another timezone and is never online when you are, CTB Recorder is the solution for you.
CTB Recorder allows you to record any public show on different cam sites. It is very easy to use and set up in minutes. You can even run the recorder on a server and control it with the graphical user interface, so that you never miss a show again.
For more visit the [homepage](https://0xboobface.github.io/ctbrec)
## Installation
[Download](https://github.com/0xboobface/ctbrec/releases) the bundle ending in -jre for your platform and follow the instructions in the README.md contained in the zip.
## License
CTB Recorder is licensed under the GPLv3. See [LICENSE.txt](https://raw.githubusercontent.com/0xboobface/ctbrec/master/LICENSE.txt).

6
build-all.sh Normal file
View File

@ -0,0 +1,6 @@
#!/bin/sh
mvn clean -f ./master
mvn verify -am -f ./master -pl :client -Djavafx.platform=win
mvn verify -am -f ./master -pl :client -Djavafx.platform=linux
mvn verify -am -f ./master -pl :client -Djavafx.platform=mac
mvn verify -am -f ./master -pl :server

16
client/.gitignore vendored Normal file
View File

@ -0,0 +1,16 @@
/bin/
/target/
*~
*.bak
/*.log
/ctbrec-tunnel.sh
/jre/
/server-local.sh
/browser/
/ffmpeg/
/client.iml
/.idea/
.settings/
.classpath
.project

674
client/LICENSE.txt Normal file
View File

@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.

19
client/README.md Normal file
View File

@ -0,0 +1,19 @@
# CTB Recorder
A free recording software for Chaturbate, MyFreeCams, CamSoda, Cam4 and BongaCams.
## Requirements
* Java 64-bit version >= 10 (already included in the bundles, which end in -jre)
## Installation
* Download the ctbrec bundle ending in -jre for your platform.
* Unzip it
* Open the new ctbrec directory and start ctbrec by executing ctbrec.exe or ctbrec.sh
* If you want to use features like follow/unfollow or tipping, set up your credentials
in the settings tab. **!!Caution!!** The credentials are stored unencrypted on your hard drive.
Alternatively you can [download](https://www.oracle.com/technetwork/java/javase/downloads/index.html) and install Java
yourself and use the smaller bundles without JRE. Make sure to add the java binary to your PATH environment variable.
## License
CTB Recorder is licensed under the GPLv3. See [LICENSE.txt](https://raw.githubusercontent.com/0xboobface/ctbrec/master/LICENSE.txt).

5
client/build.sh Normal file
View File

@ -0,0 +1,5 @@
#!/bin/bash
mvn clean
mvn -Djavafx.platform=win verify
mvn -Djavafx.platform=linux verify
mvn -Djavafx.platform=mac verify

279
client/pom.xml Normal file
View File

@ -0,0 +1,279 @@
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>client</artifactId>
<parent>
<groupId>ctbrec</groupId>
<artifactId>master</artifactId>
<version>5.3.2</version>
<relativePath>../master</relativePath>
</parent>
<properties>
<name.final>${project.groupId}-${project.version}</name.final>
</properties>
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/java</directory>
<filtering>false</filtering>
<includes>
<include>**/*.css</include>
</includes>
</resource>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
<includes>
<include>version</include>
</includes>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<archive>
<manifestFile>src/main/resources/META-INF/MANIFEST.MF</manifestFile>
<manifest>
<addClasspath>true</addClasspath>
<classpathPrefix>lib/</classpathPrefix>
</manifest>
</archive>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>ctbrec</groupId>
<artifactId>common</artifactId>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-controls</artifactId>
</dependency>
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-media</artifactId>
</dependency>
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-swing</artifactId>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-servlet</artifactId>
</dependency>
<dependency>
<groupId>com.github.usefulness</groupId>
<artifactId>webp-imageio</artifactId>
<version>0.9.0</version>
</dependency>
</dependencies>
<profiles>
<profile>
<id>win</id>
<activation>
<property>
<name>javafx.platform</name>
<value>win</value>
</property>
</activation>
<properties>
<javafx.platform>win</javafx.platform>
</properties>
<build>
<plugins>
<plugin>
<groupId>com.akathist.maven.plugins.launch4j</groupId>
<artifactId>launch4j-maven-plugin</artifactId>
<version>2.4.1</version>
<configuration>
<headerType>gui</headerType>
<jar>${name.final}.jar</jar>
<dontWrapJar>true</dontWrapJar>
<icon>src/main/resources/icon.ico</icon>
<errTitle>ctbrec</errTitle>
<classPath>
<mainClass>ctbrec.ui.Launcher</mainClass>
<addDependencies>true</addDependencies>
<jarLocation>lib/</jarLocation>
<preCp>.</preCp>
</classPath>
<downloadUrl>https://jdk.java.net/</downloadUrl>
<jre>
<path>jre</path>
<bundledJre64Bit>true</bundledJre64Bit>
<minVersion>15</minVersion>
<maxHeapSize>1024</maxHeapSize>
<opts>
<opt>-Dfile.encoding=utf-8</opt>
</opts>
</jre>
<versionInfo>
<fileVersion>${project.version}.0</fileVersion>
<txtFileVersion>${project.version}.0</txtFileVersion>
<fileDescription>Software to record live streams</fileDescription>
<copyright>2023 0xb00bface</copyright>
<productVersion>${project.version}.0</productVersion>
<txtProductVersion>${project.version}.0</txtProductVersion>
<productName>CTB Recorder</productName>
<internalName>ctbrec</internalName>
<originalFilename>ctbrec.exe</originalFilename>
</versionInfo>
</configuration>
<executions>
<execution>
<id>l4j-win</id>
<phase>package</phase>
<goals>
<goal>launch4j</goal>
</goals>
<configuration>
<outfile>target/ctbrec.exe</outfile>
<splash>
<file>src/main/resources/splash.bmp</file>
<waitForWindow>true</waitForWindow>
<timeout>60</timeout>
<timeoutErr>true</timeoutErr>
</splash>
</configuration>
</execution>
<execution>
<id>l4j-win-no-splash</id>
<phase>package</phase>
<goals>
<goal>launch4j</goal>
</goals>
<configuration>
<outfile>target/ctbrec-no-splash.exe</outfile>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<version>3.1.0</version>
<executions>
<execution>
<id>zip</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
<configuration>
<finalName>ctbrec-${project.version}</finalName>
<descriptors>
<descriptor>src/assembly/win64-jre.xml</descriptor>
</descriptors>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>linux</id>
<activation>
<property>
<name>javafx.platform</name>
<value>linux</value>
</property>
</activation>
<properties>
<javafx.platform>linux</javafx.platform>
</properties>
<build>
<plugins>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<version>3.1.0</version>
<executions>
<execution>
<id>zip</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
<configuration>
<finalName>ctbrec-${project.version}</finalName>
<descriptors>
<descriptor>src/assembly/linux-jre.xml</descriptor>
</descriptors>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>macos</id>
<activation>
<property>
<name>javafx.platform</name>
<value>mac</value>
</property>
</activation>
<properties>
<javafx.platform>mac</javafx.platform>
</properties>
<build>
<plugins>
<!-- <plugin> <groupId>de.perdian.maven.plugins</groupId> <artifactId>macosappbundler-maven-plugin</artifactId>
<version>1.10.1</version> <configuration> <plist> <CFBundleIconFile>src/main/resources/icon.icns</CFBundleIconFile>
<CFBundleDisplayName>CTB Recorder</CFBundleDisplayName> <CFBundleDevelopmentRegion>English</CFBundleDevelopmentRegion>
<CFBundleName>ctbrec</CFBundleName> <CFBundleURLTypes> <string>msa</string>
</CFBundleURLTypes> <JVMMainClassName>ctbrec.ui.Launcher</JVMMainClassName>
<JVMVersion>11+</JVMVersion> <JVMOptions> <string>-Dfile.encoding=utf-8</string>
</JVMOptions> <JVMRuntimePath>Contents/Java/jdk/Contents/Home</JVMRuntimePath>
</plist> <jdk> <include>true</include> <location>jre/jdk_macos</location>
</jdk> </configuration> <executions> <execution> <phase>package</phase> <goals>
<goal>bundle</goal> </goals> </execution> </executions> </plugin> <plugin>
<artifactId>maven-assembly-plugin</artifactId> <version>3.1.0</version> <executions>
<execution> <id>zip</id> <phase>verify</phase> <goals> <goal>single</goal>
</goals> <configuration> <finalName>ctbrec-${project.version}</finalName>
<descriptors> <descriptor>src/assembly/macos-bundle.xml</descriptor> </descriptors>
</configuration> </execution> </executions> </plugin> -->
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<version>3.1.0</version>
<executions>
<execution>
<id>zip</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
<configuration>
<finalName>ctbrec-${project.version}</finalName>
<descriptors>
<descriptor>src/assembly/macos-jre.xml</descriptor>
</descriptors>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
</project>

View File

@ -0,0 +1,8 @@
#!/bin/bash
DIR="$(dirname "$0")"
pushd "${DIR}"
JAVA=./jre/bin/java
$JAVA -version
$JAVA -Xmx1g -Djdk.gtk.version=3 -Dfile.encoding=utf-8 -jar ${name.final}.jar
popd

View File

@ -0,0 +1,8 @@
#!/bin/bash
DIR="$(dirname "$0")"
pushd "${DIR}"
JAVA=./jre/bin/java
$JAVA -version
$JAVA -splash:splash.png -Xmx1g -Djdk.gtk.version=3 -Dfile.encoding=utf-8 -jar ${name.final}.jar
popd

View File

@ -0,0 +1,9 @@
#!/bin/bash
DIR=$(dirname $0)
pushd "$DIR"
JAVA_HOME="$DIR/jre/Contents/Home"
JAVA="$JAVA_HOME/bin/java"
$JAVA -version
$JAVA -Xmx1g -Dfile.encoding=utf-8 -jar ${name.final}.jar
popd

View File

@ -0,0 +1,9 @@
#!/bin/bash
DIR=$(dirname $0)
pushd "$DIR"
JAVA_HOME="$DIR/jre/Contents/Home"
JAVA="$JAVA_HOME/bin/java"
$JAVA -version
$JAVA -splash:splash.png -Xmx1g -Dfile.encoding=utf-8 -jar ${name.final}.jar
popd

View File

@ -0,0 +1 @@
jre\bin\java -Xmx1g -Dfile.encoding=utf-8 -jar ${name.final}.jar

View File

@ -0,0 +1,70 @@
<?xml version="1.0" encoding="UTF-8"?>
<assembly>
<id>linux-jre</id>
<formats>
<format>zip</format>
</formats>
<includeBaseDirectory>false</includeBaseDirectory>
<dependencySets>
<dependencySet>
<outputDirectory>ctbrec/lib</outputDirectory>
<useProjectArtifact>false</useProjectArtifact>
<unpack>false</unpack>
<scope>runtime</scope>
</dependencySet>
</dependencySets>
<files>
<file>
<source>${project.basedir}/src/assembly/ctbrec-linux-jre.sh</source>
<outputDirectory>ctbrec</outputDirectory>
<filtered>true</filtered>
<destName>ctbrec.sh</destName>
</file>
<file>
<source>${project.basedir}/src/assembly/ctbrec-linux-jre-no-splash.sh</source>
<outputDirectory>ctbrec</outputDirectory>
<filtered>true</filtered>
<destName>ctbrec-no-splash.sh</destName>
</file>
<file>
<source>${project.build.directory}/${project.artifactId}-${project.version}.jar</source>
<outputDirectory>ctbrec</outputDirectory>
<destName>${name.final}.jar</destName>
</file>
<file>
<source>${project.basedir}/LICENSE.txt</source>
<outputDirectory>ctbrec</outputDirectory>
</file>
<file>
<source>${project.basedir}/README.md</source>
<outputDirectory>ctbrec</outputDirectory>
</file>
<file>
<source>${project.basedir}/src/main/resources/splash.png</source>
<outputDirectory>ctbrec</outputDirectory>
</file>
<file>
<source>${project.basedir}/ffmpeg/ffmpeg-linux64</source>
<outputDirectory>ctbrec/lib/ffmpeg</outputDirectory>
<destName>ffmpeg</destName>
</file>
</files>
<fileSets>
<fileSet>
<directory>jre/jdk_linux</directory>
<includes>
<include>**/*</include>
</includes>
<outputDirectory>ctbrec/jre</outputDirectory>
<filtered>false</filtered>
</fileSet>
<fileSet>
<directory>browser/ctbrec-minimal-browser-linux-x64</directory>
<includes>
<include>**/*</include>
</includes>
<outputDirectory>ctbrec/lib/browser</outputDirectory>
<filtered>false</filtered>
</fileSet>
</fileSets>
</assembly>

View File

@ -0,0 +1,71 @@
<?xml version="1.0" encoding="UTF-8"?>
<assembly>
<id>macos-jre</id>
<formats>
<format>zip</format>
</formats>
<includeBaseDirectory>false</includeBaseDirectory>
<dependencySets>
<dependencySet>
<outputDirectory>ctbrec/lib</outputDirectory>
<useProjectArtifact>false</useProjectArtifact>
<unpack>false</unpack>
<scope>runtime</scope>
</dependencySet>
</dependencySets>
<files>
<file>
<source>${project.basedir}/src/assembly/ctbrec-macos-jre.sh</source>
<outputDirectory>ctbrec</outputDirectory>
<filtered>true</filtered>
<destName>ctbrec.sh</destName>
</file>
<file>
<source>${project.basedir}/src/assembly/ctbrec-macos-jre-no-splash.sh</source>
<outputDirectory>ctbrec</outputDirectory>
<filtered>true</filtered>
<destName>ctbrec-no-splash.sh</destName>
</file>
<file>
<source>${project.build.directory}/${project.artifactId}-${project.version}.jar
</source>
<outputDirectory>ctbrec</outputDirectory>
<destName>${name.final}.jar</destName>
</file>
<file>
<source>${project.basedir}/LICENSE.txt</source>
<outputDirectory>ctbrec</outputDirectory>
</file>
<file>
<source>${project.basedir}/README.md</source>
<outputDirectory>ctbrec</outputDirectory>
</file>
<file>
<source>${project.basedir}/src/main/resources/splash.png</source>
<outputDirectory>ctbrec</outputDirectory>
</file>
<file>
<source>${project.basedir}/ffmpeg/ffmpeg-macos64</source>
<outputDirectory>ctbrec/lib/ffmpeg</outputDirectory>
<destName>ffmpeg</destName>
</file>
</files>
<fileSets>
<fileSet>
<directory>jre/jdk_macos</directory>
<includes>
<include>**/*</include>
</includes>
<outputDirectory>ctbrec/jre</outputDirectory>
<filtered>false</filtered>
</fileSet>
<fileSet>
<directory>browser/ctbrec-minimal-browser-darwin-x64</directory>
<includes>
<include>**/*</include>
</includes>
<outputDirectory>ctbrec/lib/browser</outputDirectory>
<filtered>false</filtered>
</fileSet>
</fileSets>
</assembly>

View File

@ -0,0 +1,67 @@
<?xml version="1.0" encoding="UTF-8"?>
<assembly>
<id>win64-jre</id>
<formats>
<format>zip</format>
</formats>
<includeBaseDirectory>false</includeBaseDirectory>
<dependencySets>
<dependencySet>
<outputDirectory>ctbrec/lib</outputDirectory>
<useProjectArtifact>false</useProjectArtifact>
<unpack>false</unpack>
<scope>runtime</scope>
</dependencySet>
</dependencySets>
<files>
<file>
<source>${project.build.directory}/ctbrec.exe</source>
<outputDirectory>ctbrec</outputDirectory>
</file>
<file>
<source>${project.build.directory}/ctbrec-no-splash.exe</source>
<outputDirectory>ctbrec</outputDirectory>
</file>
<file>
<source>${project.build.directory}/${project.artifactId}-${project.version}.jar</source>
<outputDirectory>ctbrec</outputDirectory>
<destName>${name.final}.jar</destName>
</file>
<file>
<source>${project.basedir}/LICENSE.txt</source>
<outputDirectory>ctbrec</outputDirectory>
</file>
<file>
<source>${project.basedir}/README.md</source>
<outputDirectory>ctbrec</outputDirectory>
</file>
<file>
<source>${project.basedir}/src/assembly/ctbrec.bat</source>
<outputDirectory>ctbrec</outputDirectory>
<filtered>true</filtered>
</file>
<file>
<source>${project.basedir}/ffmpeg/ffmpeg-win64.exe</source>
<outputDirectory>ctbrec/lib/ffmpeg</outputDirectory>
<destName>ffmpeg.exe</destName>
</file>
</files>
<fileSets>
<fileSet>
<directory>jre/jdk_windows</directory>
<includes>
<include>**/*</include>
</includes>
<outputDirectory>ctbrec/jre</outputDirectory>
<filtered>false</filtered>
</fileSet>
<fileSet>
<directory>browser/ctbrec-minimal-browser-win32-x64</directory>
<includes>
<include>**/*</include>
</includes>
<outputDirectory>ctbrec/lib/browser</outputDirectory>
<filtered>false</filtered>
</fileSet>
</fileSets>
</assembly>

View File

@ -0,0 +1,89 @@
package ctbrec;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.time.Instant;
import java.util.concurrent.ExecutorService;
import com.iheartradio.m3u8.ParseException;
import com.iheartradio.m3u8.PlaylistException;
import ctbrec.io.HttpClient;
import ctbrec.io.HttpException;
import ctbrec.recorder.ProgressListener;
import ctbrec.recorder.download.hls.MergedFfmpegHlsDownload;
import ctbrec.recorder.download.hls.SegmentPlaylist;
import ctbrec.recorder.download.hls.SegmentPlaylist.Segment;
import okhttp3.Request;
import okhttp3.Response;
public class RecordingDownload extends MergedFfmpegHlsDownload {
public RecordingDownload(HttpClient client) {
super(client);
}
@Override
public void init(Config config, Model model, Instant startTime, ExecutorService executorService) throws IOException {
this.config = config;
this.model = model;
this.startTime = startTime;
this.downloadExecutor = executorService;
splittingStrategy = initSplittingStrategy(config.getSettings());
}
public void downloadFinishedRecording(String segmentPlaylistUri, File target, ProgressListener progressListener, long sizeInBytes)
throws InvalidKeyException, NoSuchAlgorithmException, IllegalStateException, InterruptedException, IOException, ParseException, PlaylistException {
running = true;
if (Config.getInstance().getSettings().requireAuthentication) {
URL u = new URL(segmentPlaylistUri);
String path = u.getPath();
byte[] key = Config.getInstance().getSettings().key;
if (!Config.getInstance().getContextPath().isEmpty()) {
path = path.substring(Config.getInstance().getContextPath().length());
}
String hmac = Hmac.calculate(path, key);
segmentPlaylistUri = segmentPlaylistUri + "?hmac=" + hmac;
}
startFfmpegProcess(target);
for (int i = 0; i < 10 && ffmpegStdIn == null; i++) {
Thread.sleep(100);
}
SegmentPlaylist segmentPlaylist = getNextSegments(segmentPlaylistUri);
long loadedBytes = 0;
for (Segment segment : segmentPlaylist.segments) {
loadedBytes += downloadFile(segment.url, loadedBytes, sizeInBytes, progressListener);
int progress = (int) (loadedBytes / (double) sizeInBytes * 100);
progressListener.update(progress);
}
internalStop();
}
private long downloadFile(String fileUri, long loadedBytes, long totalBytes, ProgressListener progressListener) throws IOException {
long fileLoadedBytes = 0;
Request request = new Request.Builder().url(fileUri).addHeader("connection", "keep-alive").build();
try (Response response = client.execute(request)) {
if (response.isSuccessful()) {
InputStream in = response.body().byteStream();
byte[] b = new byte[1024 * 100];
int length = -1;
while ((length = in.read(b)) >= 0) {
ffmpegStdIn.write(b, 0, length);
fileLoadedBytes += length;
int progress = (int) ((loadedBytes + fileLoadedBytes) / (double) totalBytes * 100);
progressListener.update(progress);
}
} else {
throw new HttpException(response.code(), response.message());
}
}
return fileLoadedBytes;
}
}

View File

@ -0,0 +1,78 @@
package ctbrec.docs;
import ctbrec.servlet.AbstractDocServlet;
import ctbrec.servlet.MarkdownServlet;
import ctbrec.servlet.SearchServlet;
import ctbrec.servlet.StaticFileServlet;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.jetty.server.*;
import org.eclipse.jetty.server.handler.HandlerList;
import org.eclipse.jetty.servlet.ServletHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.util.component.LifeCycle;
import java.net.BindException;
@Slf4j
public class DocServer {
private static volatile boolean started = false;
private DocServer() {
}
public static synchronized void start() throws Exception {
start(() -> {
});
}
public static synchronized void start(Runnable callback) throws Exception {
log.info("DocServer.start");
if (started) {
log.info("if started");
callback.run();
return;
}
started = true;
var server = new Server();
var config = new HttpConfiguration();
config.setSendServerVersion(false);
var http = new ServerConnector(server, new HttpConnectionFactory(config));
http.setPort(5689);
server.addConnector(http);
var handler = new ServletHandler();
server.setHandler(handler);
var handlers = new HandlerList();
handlers.setHandlers(new Handler[]{handler});
server.setHandler(handlers);
var markdownServlet = new MarkdownServlet();
var holder = new ServletHolder(markdownServlet);
handler.addServletWithMapping(holder, "/docs/*");
AbstractDocServlet searchServlet = new SearchServlet();
holder = new ServletHolder(searchServlet);
handler.addServletWithMapping(holder, "/search/*");
var staticFileServlet = new StaticFileServlet("/html", false);
holder = new ServletHolder(staticFileServlet);
handler.addServletWithMapping(holder, "/static/*");
server.addLifeCycleListener(new LifeCycle.Listener() {
@Override
public void lifeCycleStarted(LifeCycle event) {
callback.run();
}
});
try {
server.start();
server.join();
} catch (BindException e) {
log.error("Port {} is already in use", http.getPort(), e);
}
}
}

View File

@ -0,0 +1,43 @@
package ctbrec.ui;
import java.io.InputStream;
import ctbrec.ui.controls.Dialogs;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.ButtonType;
import javafx.scene.image.Image;
import javafx.scene.layout.Region;
import javafx.stage.Stage;
public class AutosizeAlert extends Alert {
private Scene parent;
public AutosizeAlert(AlertType type) {
super(type, null);
}
public AutosizeAlert(AlertType type, Scene parent) {
super(type);
this.parent = parent;
init();
}
public AutosizeAlert(AlertType type, String text, Scene parent, ButtonType... buttons) {
super(type, text, buttons);
this.parent = parent;
init();
}
private void init() {
setResizable(true);
getDialogPane().setMinHeight(Region.USE_PREF_SIZE);
if(parent != null) {
var stage = (Stage) getDialogPane().getScene().getWindow();
stage.getScene().getStylesheets().addAll(parent.getStylesheets());
InputStream icon = Dialogs.class.getResourceAsStream("/icon.png");
stage.getIcons().add(new Image(icon));
}
}
}

View File

@ -0,0 +1,653 @@
package ctbrec.ui;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.type.TypeReference;
import com.google.common.eventbus.Subscribe;
import ctbrec.Config;
import ctbrec.Model;
import ctbrec.StringUtil;
import ctbrec.Version;
import ctbrec.event.Event;
import ctbrec.event.EventBusHolder;
import ctbrec.event.EventHandler;
import ctbrec.event.EventHandlerConfiguration;
import ctbrec.image.LocalPortraitStore;
import ctbrec.image.PortraitStore;
import ctbrec.image.RemotePortraitStore;
import ctbrec.io.*;
import ctbrec.io.json.ObjectMapperFactory;
import ctbrec.notes.LocalModelNotesService;
import ctbrec.notes.ModelNotesService;
import ctbrec.notes.RemoteModelNotesService;
import ctbrec.recorder.OnlineMonitor;
import ctbrec.recorder.Recorder;
import ctbrec.recorder.RemoteRecorder;
import ctbrec.recorder.SimplifiedLocalRecorder;
import ctbrec.sites.Site;
import ctbrec.sites.amateurtv.AmateurTv;
import ctbrec.sites.bonga.BongaCams;
import ctbrec.sites.cam4.Cam4;
import ctbrec.sites.camsoda.Camsoda;
import ctbrec.sites.chaturbate.Chaturbate;
import ctbrec.sites.cherrytv.CherryTv;
import ctbrec.sites.dreamcam.Dreamcam;
import ctbrec.sites.fc2live.Fc2Live;
import ctbrec.sites.flirt4free.Flirt4Free;
import ctbrec.sites.jasmin.LiveJasmin;
import ctbrec.sites.manyvids.MVLive;
import ctbrec.sites.mfc.MyFreeCams;
import ctbrec.sites.secretfriends.SecretFriends;
import ctbrec.sites.showup.Showup;
import ctbrec.sites.streamate.Streamate;
import ctbrec.sites.streamray.Streamray;
import ctbrec.sites.stripchat.Stripchat;
import ctbrec.sites.winktv.WinkTv;
import ctbrec.sites.xlovecam.XloveCam;
import ctbrec.ui.controls.Dialogs;
import ctbrec.ui.news.NewsTab;
import ctbrec.ui.settings.SettingsTab;
import ctbrec.ui.tabs.*;
import ctbrec.ui.tabs.logging.LoggingTab;
import ctbrec.ui.tabs.recorded.RecordedTab;
import javafx.application.Application;
import javafx.application.HostServices;
import javafx.application.Platform;
import javafx.beans.value.ObservableValue;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;
import lombok.Data;
import okhttp3.Request;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.awt.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.*;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import static ctbrec.event.Event.Type.*;
import static javafx.scene.control.TabPane.TabDragPolicy.FIXED;
import static javafx.scene.control.TabPane.TabDragPolicy.REORDER;
public class CamrecApplication extends Application {
static final Logger LOG = LoggerFactory.getLogger(CamrecApplication.class);
private Config config;
private Recorder recorder;
private OnlineMonitor onlineMonitor;
static HostServices hostServices;
private final BorderPane rootPane = new BorderPane();
private final HBox statusBar = new HBox();
private final Label statusLabel = new Label();
private final TabPane tabPane = new TabPane();
private final List<Site> sites = new ArrayList<>();
public static HttpClient httpClient;
public static PortraitStore portraitStore;
public static ModelNotesService modelNotesService;
public static String title;
private Stage primaryStage;
private RecordingsTab recordingsTab;
private ScheduledExecutorService scheduler;
private int activeRecordings = 0;
private double bytesPerSecond = 0;
@Override
public void start(Stage primaryStage) throws Exception {
this.primaryStage = primaryStage;
scheduler = Executors.newScheduledThreadPool(1, r -> {
var t = new Thread(r);
t.setDaemon(true);
t.setName("Scheduler");
return t;
});
logEnvironment();
createSites();
loadConfig();
registerAlertSystem();
registerActiveRecordingsCounter();
registerBandwidthMeterListener();
createHttpClient();
hostServices = getHostServices();
createRecorder();
initSites();
startOnlineMonitor();
createPortraitStore();
createModelNotesService();
createGui(primaryStage);
if (config.getSettings().checkForUpdates) {
checkForUpdates();
}
registerClipboardListener();
registerTrayIconListener();
}
private void createPortraitStore() {
if (config.getSettings().localRecording) {
portraitStore = new LocalPortraitStore(config);
} else {
portraitStore = new RemotePortraitStore(httpClient, config);
}
}
private void createModelNotesService() {
if (config.getSettings().localRecording) {
modelNotesService = new LocalModelNotesService(config);
} else {
modelNotesService = new RemoteModelNotesService(httpClient, config);
}
}
private void registerTrayIconListener() {
EventBusHolder.BUS.register(new Object() {
@Subscribe
public void trayActionRequest(Map<String, Object> evt) {
if (Objects.equals("shutdown", evt.get("event"))) {
LOG.debug("Shutdown request from tray icon");
try {
Platform.runLater(() -> {
primaryStage.show();
shutdown();
});
} catch (Exception ex) {
LOG.error(ex.getMessage(), ex);
}
}
if (Objects.equals("stage_restored", evt.get("event"))) {
LOG.debug("Main stage restored");
Platform.runLater(() -> {
if (tabPane.getSelectionModel().getSelectedItem() instanceof TabSelectionListener listener) {
listener.selected();
}
});
}
}
});
}
private void createSites() {
sites.add(new AmateurTv());
sites.add(new BongaCams());
sites.add(new Cam4());
sites.add(new Camsoda());
sites.add(new Chaturbate());
sites.add(new CherryTv());
sites.add(new Dreamcam());
sites.add(new Fc2Live());
sites.add(new Flirt4Free());
sites.add(new LiveJasmin());
sites.add(new MVLive());
sites.add(new MyFreeCams());
sites.add(new SecretFriends());
sites.add(new Showup());
sites.add(new Streamate());
sites.add(new Stripchat());
sites.add(new Streamray());
sites.add(new WinkTv());
sites.add(new XloveCam());
}
private void registerClipboardListener() {
if (config.getSettings().monitorClipboard) {
var clipboardListener = new ClipboardListener(recorder, sites);
scheduler.scheduleAtFixedRate(clipboardListener, 0, 1, TimeUnit.SECONDS);
}
}
private void initSites() {
sites.forEach(site -> {
try {
site.setRecorder(recorder);
site.setConfig(config);
if (site.isEnabled()) {
site.init();
}
} catch (Exception e) {
LOG.error("Error while initializing site {}", site.getName(), e);
}
});
}
private void startOnlineMonitor() {
onlineMonitor = new OnlineMonitor(recorder, config);
onlineMonitor.start();
}
private void logEnvironment() {
LOG.debug("OS:\t{} {}", System.getProperty("os.name"), System.getProperty("os.version"));
LOG.debug("Java:\t{} {} {}", System.getProperty("java.vendor"), System.getProperty("java.vm.name"), System.getProperty("java.version"));
LOG.debug("JavaFX:\t{} ({})", System.getProperty("javafx.version"), System.getProperty("javafx.runtime.version"));
}
private void createGui(Stage primaryStage) throws IOException {
LOG.debug("Creating GUI");
DesktopIntegration.setRecorder(recorder);
DesktopIntegration.setPrimaryStage(primaryStage);
CamrecApplication.title = "CTB Recorder " + Version.getVersion();
primaryStage.setTitle(title);
InputStream icon = getClass().getResourceAsStream("/icon.png");
primaryStage.getIcons().add(new Image(icon));
int windowWidth = Config.getInstance().getSettings().windowWidth;
int windowHeight = Config.getInstance().getSettings().windowHeight;
var scene = new Scene(rootPane, windowWidth, windowHeight);
primaryStage.setScene(scene);
Dialogs.setScene(scene);
rootPane.setCenter(tabPane);
rootPane.setBottom(statusBar);
for (Site site : sites) {
if (site.isEnabled()) {
var siteTab = new SiteTab(site, scene);
tabPane.getTabs().add(siteTab);
}
}
var modelsTab = new RecordedTab(recorder, sites);
tabPane.getTabs().add(modelsTab);
recordingsTab = new RecordingsTab("Recordings", recorder, config, modelNotesService);
tabPane.getTabs().add(recordingsTab);
if (config.getSettings().recentlyWatched) {
tabPane.getTabs().add(new RecentlyWatchedTab(recorder, sites));
}
tabPane.getTabs().add(new SettingsTab(sites, recorder));
tabPane.getTabs().add(new NewsTab(config));
tabPane.getTabs().add(new DonateTabFx());
tabPane.getTabs().add(new HelpTab());
tabPane.getTabs().add(new LoggingTab());
tabPane.setTabDragPolicy(config.getSettings().tabsSortable ? REORDER : FIXED);
restoreTabOrder();
switchToStartTab();
writeColorSchemeStyleSheet();
var base = Color.web(Config.getInstance().getSettings().colorBase);
if (!base.equals(Color.WHITE)) {
loadStyleSheet(primaryStage, "color.css");
}
loadStyleSheet(primaryStage, "style.css");
loadStyleSheet(primaryStage, "font.css");
primaryStage.getScene().getStylesheets().add("/ctbrec/ui/settings/ColorSettingsPane.css");
primaryStage.getScene().getStylesheets().add("/ctbrec/ui/controls/SearchBox.css");
primaryStage.getScene().getStylesheets().add("/ctbrec/ui/controls/Popover.css");
primaryStage.getScene().getStylesheets().add("/ctbrec/ui/settings/api/Preferences.css");
primaryStage.getScene().getStylesheets().add("/ctbrec/ui/tabs/ThumbCell.css");
primaryStage.getScene().widthProperty().addListener((observable, oldVal, newVal) -> Config.getInstance().getSettings().windowWidth = newVal.intValue());
primaryStage.getScene().heightProperty()
.addListener((observable, oldVal, newVal) -> Config.getInstance().getSettings().windowHeight = newVal.intValue());
primaryStage.setMaximized(Config.getInstance().getSettings().windowMaximized);
primaryStage.maximizedProperty().addListener((observable, oldVal, newVal) -> Config.getInstance().getSettings().windowMaximized = newVal);
Player.setScene(primaryStage.getScene());
primaryStage.setX(Config.getInstance().getSettings().windowX);
primaryStage.setY(Config.getInstance().getSettings().windowY);
primaryStage.xProperty().addListener((observable, oldVal, newVal) -> {
if (newVal.doubleValue() + primaryStage.getWidth() > 0) {
Config.getInstance().getSettings().windowX = newVal.intValue();
}
});
primaryStage.yProperty().addListener((observable, oldVal, newVal) -> {
if (newVal.doubleValue() + primaryStage.getHeight() > 0) {
Config.getInstance().getSettings().windowY = newVal.intValue();
}
});
if (config.getSettings().startMinimized) {
LOG.info("Minimize to tray on start");
DesktopIntegration.minimizeToTray(primaryStage);
} else {
LOG.info("Showing primary stage");
primaryStage.show();
}
primaryStage.setOnCloseRequest(createShutdownHandler());
Runtime.getRuntime().addShutdownHook(new Thread(() -> Platform.runLater(this::shutdown)));
setWindowMinimizeListener(primaryStage);
// register changelistener to activate / deactivate tabs, when the user switches between them
tabPane.getSelectionModel().selectedItemProperty().addListener(this::tabChanged);
statusBar.getChildren().add(statusLabel);
HBox.setMargin(statusLabel, new Insets(10, 10, 10, 10));
Optional.ofNullable(SplashScreen.getSplashScreen()).ifPresent(SplashScreen::close);
}
private void setWindowMinimizeListener(Stage primaryStage) {
primaryStage.iconifiedProperty().addListener((obs, oldV, newV) -> {
if (Boolean.TRUE.equals(newV) && Config.getInstance().getSettings().minimizeToTray && primaryStage.isShowing()) {
DesktopIntegration.minimizeToTray(primaryStage);
suspendTabUpdates();
}
});
}
private void tabChanged(ObservableValue<?> ov, Tab from, Tab to) {
try {
if (from instanceof TabSelectionListener l) {
l.deselected();
}
if (to instanceof TabSelectionListener l) {
l.selected();
}
} catch (Exception e) {
LOG.error("Error switching tabs", e);
}
}
private void suspendTabUpdates() {
tabPane.getTabs().stream()
.filter(TabSelectionListener.class::isInstance)
.forEach(t -> ((TabSelectionListener) t).deselected());
}
private javafx.event.EventHandler<WindowEvent> createShutdownHandler() {
return e -> {
e.consume();
shutdown();
};
}
private void shutdown() {
// check for active downloads
if (recordingsTab.isDownloadRunning()) {
boolean exitAnyway = Dialogs.showConfirmDialog("Shutdown", "Do you want to exit anyway?", "There are downloads running", primaryStage.getScene());
if (!exitAnyway) {
return;
}
}
// check for active recordings
var shutdownNow = false;
if (config.getSettings().localRecording) {
try {
if (!recorder.getCurrentlyRecording().isEmpty()) {
ButtonType result = Dialogs.showShutdownDialog(primaryStage.getScene());
if (result == ButtonType.NO) {
return;
} else if (result == ButtonType.YES) {
shutdownNow = true;
}
}
} catch (InvalidKeyException | NoSuchAlgorithmException | IOException ex) {
LOG.warn("Couldn't check, if recordings are running");
}
}
Alert shutdownInfo = new AutosizeAlert(Alert.AlertType.INFORMATION, primaryStage.getScene());
shutdownInfo.setTitle("Shutdown");
shutdownInfo.setContentText("Shutting down. Please wait while recordings are finished...");
shutdownInfo.show();
final boolean immediately = shutdownNow;
new Thread(() -> {
List<String> tabOrder = Config.getInstance().getSettings().tabOrder;
tabOrder.clear();
for (Tab tab : tabPane.getTabs()) {
tabOrder.add(tab.getText());
if (tab instanceof ShutdownListener l) {
l.onShutdown();
}
}
onlineMonitor.shutdown();
recorder.shutdown(immediately);
scheduler.shutdownNow();
for (Site site : sites) {
if (site.isEnabled()) {
site.shutdown();
}
}
try {
Config.getInstance().save();
clearHttpCache();
LOG.info("Shutdown complete. Goodbye!");
Platform.runLater(() -> {
primaryStage.close();
shutdownInfo.close();
Platform.exit();
// This is needed, because OkHttp?! seems to block the shutdown with its writer threads. They are not daemon threads :(
System.exit(0);
});
} catch (IOException e1) {
Platform.runLater(() -> {
Alert alert = new AutosizeAlert(Alert.AlertType.ERROR, primaryStage.getScene());
alert.setTitle("Error saving settings");
alert.setContentText("Couldn't save settings: " + e1.getLocalizedMessage());
alert.showAndWait();
System.exit(1);
});
}
try {
ExternalBrowser.getInstance().close();
} catch (IOException e12) {
// noop
}
}).start();
}
private void clearHttpCache() throws IOException {
try {
File httpCacheDir = new File(config.getConfigDir(), "cache");
LOG.debug("Deleting http cache {}", httpCacheDir);
HttpClientCacheProvider.getCache(config).evictAll();
HttpClientCacheProvider.getCache(config).close();
IoUtils.deleteDirectory(httpCacheDir);
LOG.debug("Cache has been deleted");
} catch (Exception e) {
LOG.info("The HTTP cache was not completely deleted: {}", e.getLocalizedMessage());
}
}
private void registerAlertSystem() {
for (EventHandlerConfiguration eventHandlerConfig : Config.getInstance().getSettings().eventHandlers) {
var handler = new EventHandler(eventHandlerConfig);
EventBusHolder.register(handler);
LOG.debug("Registered event handler for {} {}", eventHandlerConfig.getEvent(), eventHandlerConfig.getName());
}
LOG.debug("Alert System registered");
}
private void registerActiveRecordingsCounter() {
EventBusHolder.BUS.register(new Object() {
@Subscribe
public void handleEvent(Event evt) {
if (evt.getType() == MODEL_ONLINE || evt.getType() == MODEL_STATUS_CHANGED || evt.getType() == RECORDING_STATUS_CHANGED) {
try {
int modelCount = recorder.getModelCount();
List<Model> currentlyRecording = recorder.getCurrentlyRecording();
activeRecordings = currentlyRecording.size();
DesktopIntegration.updateTrayIcon(activeRecordings);
String windowTitle = getActiveRecordings(activeRecordings, modelCount) + title;
Platform.runLater(() -> primaryStage.setTitle(windowTitle));
updateStatus();
} catch (Exception e) {
LOG.warn("Couldn't update window title", e);
}
}
}
private String getActiveRecordings(int activeRecordings, int modelCount) {
if (activeRecordings > 0) {
StringBuilder s = new StringBuilder("(").append(activeRecordings);
if (config.getSettings().totalModelCountInTitle) {
s.append("/").append(modelCount);
}
s.append(") ");
return s.toString();
} else {
return "";
}
}
});
}
private void registerBandwidthMeterListener() {
BandwidthMeter.addListener((bytes, dur) -> {
long millis = dur.toMillis();
double bytesPerMilli = bytes / (double) millis;
bytesPerSecond = bytesPerMilli * 1000;
updateStatus();
});
}
private void updateStatus() {
if (activeRecordings == 0) {
bytesPerSecond = 0;
}
String humanReadable = ByteUnitFormatter.format(bytesPerSecond);
var status = String.format("Recording %s / %s models (%s grouped) @ %s/s", activeRecordings, recorder.getModelCount(), recorder.getGroupedModelCount(), humanReadable);
Platform.runLater(() -> statusLabel.setText(status));
}
private void writeColorSchemeStyleSheet() {
var colorCss = new File(Config.getInstance().getConfigDir(), "color.css");
try (var fos = new FileOutputStream(colorCss)) {
String content = ".root {\n" + " -fx-base: " + Config.getInstance().getSettings().colorBase + ";\n" + " -fx-accent: "
+ Config.getInstance().getSettings().colorAccent + ";\n" + " -fx-default-button: -fx-accent;\n" + " -fx-focus-color: -fx-accent;\n"
+ " -fx-control-inner-background-alt: derive(-fx-base, 95%);\n" + "}";
fos.write(content.getBytes(StandardCharsets.UTF_8));
} catch (Exception e) {
LOG.error("Couldn't write stylesheet for user defined color theme");
}
}
public static void loadStyleSheet(Stage primaryStage, String filename) {
var css = new File(Config.getInstance().getConfigDir(), filename);
if (css.exists() && css.isFile()) {
primaryStage.getScene().getStylesheets().add(css.toURI().toString());
}
}
private void restoreTabOrder() {
List<String> tabOrder = Config.getInstance().getSettings().tabOrder;
for (int i = 0; i < tabOrder.size(); i++) {
Tab matched = null;
for (Tab tab : tabPane.getTabs()) {
if (Objects.equals(tabOrder.get(i), tab.getText())) {
matched = tab;
}
}
if (matched != null) {
tabPane.getTabs().remove(matched);
int max = tabPane.getTabs().size();
tabPane.getTabs().add(Math.min(i, max), matched);
}
}
}
private void switchToStartTab() {
String startTab = Config.getInstance().getSettings().startTab;
if (StringUtil.isNotBlank(startTab)) {
for (Tab tab : tabPane.getTabs()) {
if (Objects.equals(startTab, tab.getText())) {
tabPane.getSelectionModel().select(tab);
break;
}
}
}
if (tabPane.getSelectionModel().getSelectedItem() instanceof TabSelectionListener l) {
l.selected();
}
}
private void createRecorder() {
if (config.getSettings().localRecording) {
try {
recorder = new SimplifiedLocalRecorder(config, sites);
} catch (IOException e) {
LOG.error("Couldn't initialize recorder", e);
Alert alert = new AutosizeAlert(Alert.AlertType.ERROR, primaryStage.getScene());
alert.setTitle("Whoopsie");
alert.setContentText("Couldn't initialize recorder: " + e.getLocalizedMessage());
alert.showAndWait();
}
} else {
recorder = new RemoteRecorder(config, httpClient, sites);
}
}
private void loadConfig() {
try {
Config.init(sites);
} catch (Exception e) {
LOG.error("Couldn't load settings", e);
Alert alert = new AutosizeAlert(Alert.AlertType.ERROR, primaryStage.getScene());
alert.setTitle("Whoopsie");
alert.setContentText("Couldn't load settings. Falling back to defaults. A backup of your settings has been created.");
alert.showAndWait();
}
config = Config.getInstance();
}
private void createHttpClient() {
httpClient = new HttpClient("camrec", config) {
@Override
public boolean login() {
return false;
}
};
}
public static void main(String[] args) {
launch(args);
}
private void checkForUpdates() {
var updateCheck = new Thread(() -> {
var url = "https://pastebin.com/raw/mUxtKzyB";
var request = new Request.Builder().url(url).build();
try (var response = httpClient.execute(request)) {
var body = response.body().string();
LOG.trace("Version check respone: {}", body);
if (response.isSuccessful()) {
List<Release> releases = ObjectMapperFactory.getMapper().readValue(body, new TypeReference<>() {
});
var latest = releases.get(0);
var latestVersion = latest.getVersion();
var ctbrecVersion = Version.getVersion();
if (latestVersion.compareTo(ctbrecVersion) > 0) {
LOG.debug("Update available {} < {}", ctbrecVersion, latestVersion);
Platform.runLater(() -> tabPane.getTabs().add(new UpdateTab(latest)));
} else {
LOG.debug("ctbrec is up-to-date {}", ctbrecVersion);
}
} else {
throw new HttpException(response.code(), response.message());
}
} catch (Exception e) {
LOG.warn("Update check failed: {}", e.getMessage());
}
});
updateCheck.setName("Update Check");
updateCheck.setDaemon(true);
updateCheck.start();
}
@Data
public static class Release {
private String name;
@JsonProperty("tag_name")
private String tagName;
@JsonProperty("html_url")
private String htmlUrl;
public Version getVersion() {
return Version.of(tagName);
}
}
}

View File

@ -0,0 +1,65 @@
package ctbrec.ui;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.Objects;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ctbrec.recorder.Recorder;
import ctbrec.sites.Site;
import javafx.application.Platform;
import javafx.scene.input.Clipboard;
public class ClipboardListener implements Runnable {
private static final Logger LOG = LoggerFactory.getLogger(ClipboardListener.class);
private Recorder recorder;
private List<Site> sites;
private Clipboard systemClipboard;
private String lastUrl = null;
public ClipboardListener(Recorder recorder, List<Site> sites) {
this.recorder = recorder;
this.sites = sites;
systemClipboard = Clipboard.getSystemClipboard();
}
@Override
public void run() {
Platform.runLater(() -> {
try {
String url = null;
if (systemClipboard.hasUrl()) {
url = systemClipboard.getUrl();
} else if (systemClipboard.hasString()) {
url = systemClipboard.getString();
}
if (url != null && !Objects.equals(url, lastUrl)) {
lastUrl = url;
addModelIfUrlMatches(url);
}
} catch (Exception e) {
LOG.error("Error in clipboard polling loop", e);
}
});
}
private void addModelIfUrlMatches(String url) {
for (Site site : sites) {
var m = site.createModelFromUrl(url);
if (m != null) {
try {
recorder.addModel(m);
DesktopIntegration.notification("Add from clipboard", "Model added", "Model " + m.getDisplayName() + " added");
} catch (InvalidKeyException | NoSuchAlgorithmException | IOException e) {
DesktopIntegration.notification("Add from clipboard", "Error", "Couldn't add URL from clipboard: " + e.getLocalizedMessage());
}
break;
}
}
}
}

View File

@ -0,0 +1,229 @@
package ctbrec.ui;
import ctbrec.Config;
import ctbrec.OS;
import ctbrec.StringUtil;
import ctbrec.io.StreamRedirector;
import ctbrec.recorder.Recorder;
import javafx.application.Platform;
import javafx.geometry.Insets;
import javafx.scene.control.Alert;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.awt.*;
import java.awt.TrayIcon.MessageType;
import java.io.File;
import java.io.IOException;
import java.net.URI;
public class DesktopIntegration {
private DesktopIntegration() {
}
private static final Logger LOG = LoggerFactory.getLogger(DesktopIntegration.class);
private static Recorder recorder;
private static Stage primaryStage;
private static TrayIcon trayIcon;
public static void open(String uri) {
Config cfg = Config.getInstance();
Runtime rt = Runtime.getRuntime();
String[] cmdline = createCmdline(uri);
if (!cfg.getSettings().browserOverride.isEmpty()) {
try {
rt.exec(cmdline);
return;
} catch (Exception e) {
LOG.debug("Couldn't open URL with user-defined {} {}", cmdline, uri);
}
}
if (!cfg.getSettings().forceBrowserOverride) {
try {
CamrecApplication.hostServices.showDocument(uri);
return;
} catch (Exception e) {
LOG.debug("Couldn't open URL with host services {}", uri);
}
// opening with HostServices failed, now try Desktop
try {
Desktop.getDesktop().browse(new URI(uri));
return;
} catch (Exception e) {
LOG.debug("Couldn't open URL with Desktop {}", uri);
}
// try external helpers
var externalHelpers = new String[]{"kde-open5", "kde-open", "gnome-open", "xdg-open"};
for (String helper : externalHelpers) {
try {
rt.exec(helper + " " + uri);
return;
} catch (IOException e) {
LOG.debug("Couldn't open URL with {} {}", helper, uri);
}
}
}
// all attempts failed, show a dialog with URL at least
Alert info = new AutosizeAlert(Alert.AlertType.ERROR);
info.setTitle("Open URL");
info.setContentText("Couldn't open URL");
var pane = new BorderPane();
pane.setTop(new Label());
var urlField = new TextField(uri);
urlField.setPadding(new Insets(10));
urlField.setEditable(false);
pane.setCenter(urlField);
info.getDialogPane().setExpandableContent(pane);
info.getDialogPane().setExpanded(true);
info.show();
}
private static String[] createCmdline(String streamUrl) {
Config cfg = Config.getInstance();
String params = cfg.getSettings().browserParams.trim();
String[] cmdline;
if (params.isEmpty()) {
cmdline = new String[2];
} else {
String[] playerArgs = StringUtil.splitParams(params);
cmdline = new String[playerArgs.length + 2];
System.arraycopy(playerArgs, 0, cmdline, 1, playerArgs.length);
}
cmdline[0] = cfg.getSettings().browserOverride;
cmdline[cmdline.length - 1] = streamUrl;
return cmdline;
}
public static void open(File f) {
try {
Desktop.getDesktop().open(f);
return;
} catch (Exception e) {
LOG.debug("Couldn't open file with Desktop {}", f);
}
// try external helpers
var externalHelpers = new String[]{"kde-open5", "kde-open", "gnome-open", "xdg-open"};
var rt = Runtime.getRuntime();
for (String helper : externalHelpers) {
try {
rt.exec(helper + " " + f.getAbsolutePath());
return;
} catch (IOException e) {
LOG.debug("Couldn't open file with {} {}", helper, f);
}
}
// all attempts failed, show a dialog with path at least
Alert info = new AutosizeAlert(Alert.AlertType.ERROR);
info.setTitle("Open file");
info.setContentText("Couldn't open file");
var pane = new BorderPane();
pane.setTop(new Label());
var urlField = new TextField(f.toString());
urlField.setPadding(new Insets(10));
urlField.setEditable(false);
pane.setCenter(urlField);
info.getDialogPane().setExpandableContent(pane);
info.getDialogPane().setExpanded(true);
info.show();
}
public static void notification(String title, String header, String msg) {
if (OS.getOsType() == OS.TYPE.LINUX) {
notifyLinux(title, header, msg);
} else if (OS.getOsType() == OS.TYPE.WINDOWS) {
notifyWindows(title, header, msg);
} else if (OS.getOsType() == OS.TYPE.MAC) {
notifyMac(title, header, msg);
} else {
// unknown system, try systemtray notification anyways
notifySystemTray(title, header, msg);
}
}
private static void notifyLinux(String title, String header, String msg) {
try {
Process p = Runtime.getRuntime().exec(new String[]{
"notify-send",
"-u", "normal",
"-t", "5000",
"-a", title,
header,
msg.replace("-", "\\\\-").replace("\\s", "\\\\ "),
"--icon=dialog-information"
});
new Thread(new StreamRedirector(p.getInputStream(), System.out)).start(); // NOSONAR
new Thread(new StreamRedirector(p.getErrorStream(), System.err)).start(); // NOSONAR
} catch (NullPointerException e) {
// can happen at start, ignore
} catch (IOException e1) {
LOG.error("Notification failed", e1);
}
}
private static void notifyWindows(String title, String header, String msg) {
notifySystemTray(title, header, msg);
}
private static void notifyMac(String title, String header, String msg) {
notifySystemTray(title, header, msg);
}
private static synchronized void notifySystemTray(String title, String header, String msg) {
if (SystemTray.isSupported()) {
createTrayIcon(primaryStage);
trayIcon.displayMessage(header, msg, MessageType.INFO);
} else {
LOG.error("SystemTray notifications not supported by this OS");
}
}
public static void minimizeToTray(Stage primaryStage) {
Platform.setImplicitExit(false);
boolean supported = createTrayIcon(primaryStage);
if (supported) {
primaryStage.hide();
}
}
private static boolean createTrayIcon(Stage stage) {
if (SystemTray.isSupported()) {
boolean created = true;
if (trayIcon == null) {
trayIcon = new ctbrec.ui.TrayIcon(stage, recorder);
created = trayIcon.createTrayIcon();
}
return created;
} else {
LOG.error("SystemTray notifications not supported by this OS");
return false;
}
}
public static void setRecorder(Recorder recorder) {
DesktopIntegration.recorder = recorder;
}
public static void setPrimaryStage(Stage primaryStage) {
DesktopIntegration.primaryStage = primaryStage;
}
public static void updateTrayIcon(int activeRecordings) {
if (trayIcon != null) {
trayIcon.updateActiveRecordings(activeRecordings);
}
}
}

View File

@ -0,0 +1,238 @@
package ctbrec.ui;
import ctbrec.Config;
import ctbrec.OS;
import ctbrec.io.ProcessOutputLogger;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONObject;
import java.io.*;
import java.net.Socket;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Consumer;
import static java.nio.charset.StandardCharsets.UTF_8;
@Slf4j
public class ExternalBrowser implements AutoCloseable { // NOSONAR singleton is wanted
private static final ExternalBrowser INSTANCE = new ExternalBrowser();
private static final String MSGID = "msgid";
private final Lock lock = new ReentrantLock();
private Socket socket;
private Consumer<String> messageListener;
private InputStream in;
private OutputStream out;
private Thread reader;
private volatile boolean stopped = true;
private volatile boolean browserReady = false;
private final Object browserReadyLock = new Object();
private final Map<String, CompletableFuture<Object>> responseFutures = new HashMap<>();
private Runnable onReadyCallback;
public static ExternalBrowser getInstance() {
return INSTANCE;
}
public void run(JSONObject jsonConfig, Consumer<String> messageListener) throws InterruptedException, IOException {
log.debug("Running browser with config {}", jsonConfig);
lock.lock();
try {
stopped = false;
this.messageListener = messageListener;
addProxyConfig(jsonConfig.getJSONObject("config"));
var configDir = new File(Config.getInstance().getConfigDir(), "ctbrec-minimal-browser");
String[] cmdline = OS.getBrowserCommand(configDir.getCanonicalPath());
Process p = new ProcessBuilder(cmdline).start();
new Thread(new ProcessOutputLogger(p.getInputStream(), "ExternalBrowser stdout")).start();
new Thread(new ProcessOutputLogger(p.getErrorStream(), "ExternalBrowser stderr")).start();
log.debug("Browser started: {}", Arrays.toString(cmdline));
connectToRemoteControlSocket();
while (!browserReady) {
synchronized (browserReadyLock) {
browserReadyLock.wait(100);
}
}
if (log.isTraceEnabled()) {
log.debug("Connected to remote control server. Sending config {}", jsonConfig);
} else {
log.debug("Connected to remote control server. Sending config");
}
out.write(jsonConfig.toString().getBytes(UTF_8));
out.write('\n');
out.flush();
Optional.ofNullable(onReadyCallback).ifPresent(Runnable::run);
log.debug("Waiting for browser to terminate");
p.waitFor();
int exitValue = p.exitValue();
reader = null;
in = null;
out = null;
this.messageListener = null;
log.debug("Browser Process terminated with {}", exitValue);
} finally {
lock.unlock();
}
}
private void connectToRemoteControlSocket() throws IOException {
for (var i = 0; i < 20; i++) {
try {
socket = new Socket("localhost", 3202);
in = socket.getInputStream();
out = socket.getOutputStream();
reader = new Thread(this::readBrowserOutput);
reader.start();
log.debug("Connected to control socket");
return;
} catch (IOException e) {
if (i == 19) {
log.error("Connection to remote control socket failed", e);
throw e;
}
}
// wait a bit, so that the remote server socket can be opened by electron
try {
Thread.sleep(100);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
public CompletableFuture<Object> executeJavaScript(String javaScript) throws IOException {
String id = UUID.randomUUID().toString();
var future = new CompletableFuture<>();
var script = new JSONObject();
script.put(MSGID, id);
script.put("execute", javaScript);
if (out != null) {
out.write(script.toString().getBytes(UTF_8));
out.write('\n');
out.flush();
responseFutures.put(id, future);
}
if (javaScript.equals("quit")) {
stopped = true;
}
return future;
}
@Override
public void close() throws IOException {
if (stopped) {
return;
}
stopped = true;
executeJavaScript("quit");
}
private void readBrowserOutput() {
log.debug("Browser output reader started");
try (var br = new BufferedReader(new InputStreamReader(in))) {
String line;
synchronized (browserReadyLock) {
browserReady = true;
browserReadyLock.notifyAll();
}
while (!Thread.interrupted() && (line = br.readLine()) != null) {
log.debug("Browser output: {}", line);
if (line.startsWith("{")) {
JSONObject json = new JSONObject(line);
if (json.has(MSGID)) {
handleExecuteScriptResponse(json);
} else {
if (messageListener != null) {
messageListener.accept(line);
}
}
}
}
} catch (IOException e) {
if (!stopped) {
log.error("Couldn't read browser output", e);
}
} finally {
stopped = true;
synchronized (browserReadyLock) {
browserReady = true;
browserReadyLock.notifyAll();
}
}
}
private void handleExecuteScriptResponse(JSONObject json) {
var msgid = json.getString(MSGID);
log.debug("Future {}", msgid);
CompletableFuture<Object> future = responseFutures.get(msgid);
if (future != null) {
responseFutures.remove(msgid);
final String RESULT = "result";
if (json.has(RESULT)) {
log.debug("Future {} done. Result: {}", msgid, json.get(RESULT));
future.complete(json.get(RESULT));
} else if (json.has("error")) {
log.debug("Future {} failed", msgid);
future.completeExceptionally(new Exception(json.getJSONObject("error").toString()));
}
} else {
log.warn("No future for previous request {}", msgid);
}
}
private void addProxyConfig(JSONObject jsonConfig) {
var proxyType = Config.getInstance().getSettings().proxyType;
var proxy = new JSONObject();
final String KEY_ADDRESS = "address";
final String KEY_PROXY = "proxy";
switch (proxyType) {
case HTTP:
proxy.put(KEY_ADDRESS,
"http=" + Config.getInstance().getSettings().proxyHost + ':' + Config.getInstance().getSettings().proxyPort
+ ";https=" + Config.getInstance().getSettings().proxyHost + ':' + Config.getInstance().getSettings().proxyPort);
if (Config.getInstance().getSettings().proxyUser != null && !Config.getInstance().getSettings().proxyUser.isEmpty()) {
String username = Config.getInstance().getSettings().proxyUser;
String password = Config.getInstance().getSettings().proxyPassword;
proxy.put("user", username);
proxy.put("password", password);
}
jsonConfig.put(KEY_PROXY, proxy);
break;
case SOCKS4:
proxy = new JSONObject();
proxy.put(KEY_ADDRESS, "socks4://" + Config.getInstance().getSettings().proxyHost + ':' + Config.getInstance().getSettings().proxyPort);
jsonConfig.put(KEY_PROXY, proxy);
break;
case SOCKS5:
proxy = new JSONObject();
proxy.put(KEY_ADDRESS, "socks5://" + Config.getInstance().getSettings().proxyHost + ':' + Config.getInstance().getSettings().proxyPort);
if (Config.getInstance().getSettings().proxyUser != null && !Config.getInstance().getSettings().proxyUser.isEmpty()) {
String username = Config.getInstance().getSettings().proxyUser;
String password = Config.getInstance().getSettings().proxyPassword;
proxy.put("user", username);
proxy.put("password", password);
}
jsonConfig.put(KEY_PROXY, proxy);
break;
case DIRECT:
default:
// nothing to do here
break;
}
}
public ExternalBrowser onReady(Runnable onReadyCallback) {
this.onReadyCallback = onReadyCallback;
return this;
}
}

View File

@ -0,0 +1,53 @@
package ctbrec.ui;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ctbrec.io.HttpClient;
import ctbrec.recorder.ProgressListener;
import okhttp3.Request;
public class FileDownload {
private static final Logger LOG = LoggerFactory.getLogger(FileDownload.class);
private HttpClient httpClient;
private ProgressListener downloadListener;
public FileDownload(HttpClient httpClient, ProgressListener downloadListener) {
this.httpClient = httpClient;
this.downloadListener = downloadListener;
}
public void start(URL url, File target) throws IOException {
LOG.trace("Downloading file {} to {}", url, target);
var request = new Request.Builder().url(url).addHeader("connection", "keep-alive").build();
var response = httpClient.execute(request);
var fileSize = Long.parseLong(response.header("Content-Length", String.valueOf(Long.MAX_VALUE)));
InputStream in = null;
try (var fos = new FileOutputStream(target)) {
in = response.body().byteStream();
var b = new byte[1024 * 100];
long totalBytesRead = 0;
int length = -1;
while ((length = in.read(b)) >= 0) {
fos.write(b, 0, length);
totalBytesRead += length;
int progress = (int)(totalBytesRead * 100d / fileSize);
downloadListener.update(progress);
}
} finally {
if (in != null) {
in.close();
}
response.close();
}
}
}

View File

@ -0,0 +1,23 @@
package ctbrec.ui;
public enum Icon {
BLANK_16(Icon.class.getResource("/16/blank.png").toExternalForm()),
BOOKMARK_16(Icon.class.getResource("/16/bookmark-new.png").toExternalForm()),
CHECK_16(Icon.class.getResource("/16/check-small.png").toExternalForm()),
CLOCK_16(Icon.class.getResource("/16/clock.png").toExternalForm()),
GROUP_16(Icon.class.getResource("/16/users.png").toExternalForm()),
MEDIA_PLAYBACK_PAUSE_16(Icon.class.getResource("/16/media-playback-pause.png").toExternalForm()),
MEDIA_RECORD_16(Icon.class.getResource("/16/media-record.png").toExternalForm()),
MEDIA_FORCE_RECORD_16(Icon.class.getResource("/16/media-force-record.png").toExternalForm());
private String url;
private Icon(String url) {
this.url = url;
}
public String url() {
return url;
}
}

View File

@ -0,0 +1,18 @@
package ctbrec.ui;
import java.time.Instant;
import javafx.beans.property.ObjectPropertyBase;
public class InstantProperty extends ObjectPropertyBase<Instant> {
@Override
public Object getBean() {
return get();
}
@Override
public String getName() {
return "Instant";
}
}

View File

@ -0,0 +1,396 @@
package ctbrec.ui;
import com.iheartradio.m3u8.ParseException;
import com.iheartradio.m3u8.PlaylistException;
import ctbrec.Model;
import ctbrec.SubsequentAction;
import ctbrec.recorder.download.HttpHeaderFactory;
import ctbrec.recorder.download.RecordingProcess;
import ctbrec.recorder.download.StreamSource;
import ctbrec.sites.Site;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleObjectProperty;
import javax.xml.bind.JAXBException;
import java.io.IOException;
import java.time.Instant;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
/**
* Just a wrapper for Model, which augments it with JavaFX value binding properties, so that UI widgets get updated proeprly
*/
public class JavaFxModel implements Model {
private final transient BooleanProperty onlineProperty = new SimpleBooleanProperty();
private final transient BooleanProperty recordingProperty = new SimpleBooleanProperty();
private final transient BooleanProperty pausedProperty = new SimpleBooleanProperty();
private final transient BooleanProperty forcePriorityProperty = new SimpleBooleanProperty();
private final transient SimpleIntegerProperty priorityProperty = new SimpleIntegerProperty();
private final transient SimpleObjectProperty<Instant> lastSeenProperty = new SimpleObjectProperty<>();
private final transient SimpleObjectProperty<Instant> lastRecordedProperty = new SimpleObjectProperty<>();
private final transient SimpleObjectProperty<State> onlineStateProperty = new SimpleObjectProperty<>();
private final Model delegate;
public JavaFxModel(Model delegate) {
this.delegate = delegate;
setPriority(delegate.getPriority());
setLastSeen(delegate.getLastSeen());
setLastRecorded(delegate.getLastRecorded());
try { // TODO: split online state updates and reading from cache, so that we don't need try-catch
onlineStateProperty.setValue(delegate.getOnlineState(true));
} catch (Exception e) {}
}
public void updateFrom(JavaFxModel other) {
this.setSuspended(other.isSuspended());
this.setForcePriority(other.isForcePriority());
this.getOnlineProperty().set(other.getOnlineProperty().get());
this.getRecordingProperty().set(other.getRecordingProperty().get());
this.lastRecordedProperty().set(other.lastRecordedProperty().get());
this.lastSeenProperty().set(other.lastSeenProperty().get());
this.setRecordUntil(other.getRecordUntil());
this.setRecordUntilSubsequentAction(other.getRecordUntilSubsequentAction());
this.onlineStateProperty().set(other.onlineStateProperty().get());
}
@Override
public String getUrl() {
return delegate.getUrl();
}
@Override
public void setUrl(String url) {
delegate.setUrl(url);
}
@Override
public String getName() {
return delegate.getName();
}
@Override
public void setName(String name) {
delegate.setName(name);
}
@Override
public String getSanitizedNamed() {
return delegate.getSanitizedNamed();
}
@Override
public String getPreview() {
return delegate.getPreview();
}
@Override
public void setPreview(String preview) {
delegate.setPreview(preview);
}
@Override
public List<String> getTags() {
return delegate.getTags();
}
@Override
public void setTags(List<String> tags) {
delegate.setTags(tags);
}
@Override
public int hashCode() {
return delegate.hashCode();
}
@Override
public boolean equals(Object obj) {
return delegate.equals(obj);
}
@Override
public String toString() {
return delegate.toString();
}
public BooleanProperty getOnlineProperty() {
return onlineProperty;
}
public void setOnlineProperty(boolean online) {
this.onlineProperty.set(online);
}
public BooleanProperty getRecordingProperty() {
return recordingProperty;
}
public void setRecordingProperty(boolean recording) {
this.recordingProperty.setValue(recording);
}
public BooleanProperty getPausedProperty() {
return pausedProperty;
}
public BooleanProperty getForcePriorityProperty() {
return forcePriorityProperty;
}
public SimpleIntegerProperty getPriorityProperty() {
return priorityProperty;
}
public Model getDelegate() {
return delegate;
}
@Override
public boolean isOnline() throws IOException, ExecutionException, InterruptedException {
return delegate.isOnline();
}
@Override
public boolean isOnline(boolean ignoreCache) throws IOException, ExecutionException, InterruptedException {
return delegate.isOnline(ignoreCache);
}
public void setOnlineStateProperty(State state) throws IOException, ExecutionException {
onlineStateProperty.set(state);
}
@Override
public State getOnlineState(boolean failFast) throws IOException, ExecutionException {
return delegate.getOnlineState(failFast);
}
@Override
public List<StreamSource> getStreamSources() throws IOException, ExecutionException, ParseException, PlaylistException, JAXBException {
return delegate.getStreamSources();
}
@Override
public void invalidateCacheEntries() {
delegate.invalidateCacheEntries();
}
@Override
public void receiveTip(Double tokens) throws IOException {
SiteUiFactory.getUi(getSite()).login();
delegate.receiveTip(tokens);
}
@Override
public int[] getStreamResolution(boolean b) throws ExecutionException {
return delegate.getStreamResolution(b);
}
@Override
public boolean follow() throws IOException {
SiteUiFactory.getUi(getSite()).login();
return delegate.follow();
}
@Override
public boolean unfollow() throws IOException {
SiteUiFactory.getUi(getSite()).login();
return delegate.unfollow();
}
@Override
public void setSite(Site site) {
delegate.setSite(site);
}
@Override
public Site getSite() {
return delegate.getSite();
}
@Override
public void readSiteSpecificData(Map<String, String> data) {
delegate.readSiteSpecificData(data);
}
@Override
public void writeSiteSpecificData(Map<String, String> data) {
delegate.writeSiteSpecificData(data);
}
@Override
public String getDescription() {
return delegate.getDescription();
}
@Override
public void setDescription(String description) {
delegate.setDescription(description);
}
@Override
public int getStreamUrlIndex() {
return delegate.getStreamUrlIndex();
}
@Override
public void setStreamUrlIndex(int streamUrlIndex) {
delegate.setStreamUrlIndex(streamUrlIndex);
}
@Override
public boolean isSuspended() {
return delegate.isSuspended();
}
@Override
public void setSuspended(boolean suspended) {
delegate.setSuspended(suspended);
pausedProperty.set(suspended);
}
@Override
public void delay() {
delegate.delay();
}
@Override
public boolean isDelayed() {
return delegate.isDelayed();
}
@Override
public String getDisplayName() {
return delegate.getDisplayName();
}
@Override
public void setDisplayName(String name) {
delegate.setDisplayName(name);
}
@Override
public void setPriority(int priority) {
delegate.setPriority(priority);
priorityProperty.set(priority);
}
@Override
public int getPriority() {
return delegate.getPriority();
}
@Override
public boolean isForcePriority() {
return delegate.isForcePriority();
}
@Override
public void setForcePriority(boolean forcePriority) {
delegate.setForcePriority(forcePriority);
forcePriorityProperty.set(forcePriority);
}
public SimpleObjectProperty<Instant> lastSeenProperty() {
return lastSeenProperty;
}
@Override
public void setLastSeen(Instant timestamp) {
delegate.setLastSeen(timestamp);
lastSeenProperty.set(timestamp);
}
@Override
public Instant getLastSeen() {
return delegate.getLastSeen();
}
public SimpleObjectProperty<Instant> lastRecordedProperty() {
return lastRecordedProperty;
}
public SimpleObjectProperty<State> onlineStateProperty() {
return onlineStateProperty;
}
@Override
public void setLastRecorded(Instant timestamp) {
delegate.setLastRecorded(timestamp);
lastRecordedProperty.set(timestamp);
}
@Override
public Instant getLastRecorded() {
return delegate.getLastRecorded();
}
@Override
public Instant getAddedTimestamp() {
return delegate.getAddedTimestamp();
}
@Override
public void setAddedTimestamp(Instant timestamp) {
delegate.setAddedTimestamp(timestamp);
}
@Override
public int compareTo(Model o) {
return delegate.compareTo(o);
}
@Override
public RecordingProcess createDownload() {
return delegate.createDownload();
}
@Override
public HttpHeaderFactory getHttpHeaderFactory() {
return delegate.getHttpHeaderFactory();
}
@Override
public Instant getRecordUntil() {
return delegate.getRecordUntil();
}
@Override
public void setRecordUntil(Instant instant) {
delegate.setRecordUntil(instant);
}
@Override
public SubsequentAction getRecordUntilSubsequentAction() {
return delegate.getRecordUntilSubsequentAction();
}
@Override
public void setRecordUntilSubsequentAction(SubsequentAction action) {
delegate.setRecordUntilSubsequentAction(action);
}
@Override
public boolean exists() throws IOException {
return delegate.exists();
}
@Override
public boolean isRecordingTimeLimited() {
return delegate.isRecordingTimeLimited();
}
@Override
public boolean isMarkedForLaterRecording() {
return delegate.isMarkedForLaterRecording();
}
@Override
public void setMarkedForLaterRecording(boolean marked) {
delegate.setMarkedForLaterRecording(marked);
}
}

View File

@ -0,0 +1,310 @@
package ctbrec.ui;
import ctbrec.Config;
import ctbrec.Model;
import ctbrec.Recording;
import ctbrec.recorder.download.RecordingProcess;
import javafx.beans.property.LongProperty;
import javafx.beans.property.SimpleLongProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import java.io.File;
import java.time.Duration;
import java.time.Instant;
import java.util.Optional;
import java.util.Set;
public class JavaFxRecording extends Recording {
private final transient StringProperty statusProperty = new SimpleStringProperty();
private final transient StringProperty progressProperty = new SimpleStringProperty();
private final transient StringProperty notesProperty = new SimpleStringProperty();
private final transient LongProperty sizeProperty = new SimpleLongProperty();
private final Recording delegate;
private long lastValue = 0;
public JavaFxRecording(Recording recording) {
this.delegate = recording;
setStatus(recording.getStatus());
setSizeInByte(recording.getSizeInByte());
setProgress(recording.getProgress());
setNote(recording.getNote());
notesProperty.addListener((obs, oldV, newV) -> delegate.setNote(newV));
}
public Recording getDelegate() {
return delegate;
}
@Override
public Model getModel() {
return delegate.getModel();
}
@Override
public void setModel(Model model) {
delegate.setModel(model);
}
@Override
public Instant getStartDate() {
return delegate.getStartDate();
}
@Override
public void setStartDate(Instant startDate) {
delegate.setStartDate(startDate);
}
@Override
public State getStatus() {
return delegate.getStatus();
}
public StringProperty getStatusProperty() {
return statusProperty;
}
@Override
public void setStatus(State status) {
delegate.setStatus(status);
switch (status) {
case RECORDING:
statusProperty.set("recording");
break;
case GENERATING_PLAYLIST:
statusProperty.set("generating playlist");
break;
case FINISHED:
statusProperty.set("finished");
break;
case DOWNLOADING:
statusProperty.set("downloading");
break;
case POST_PROCESSING:
statusProperty.set("post-processing");
break;
case DELETED:
statusProperty.set("deleted");
break;
case DELETING:
statusProperty.set("deleting");
break;
case FAILED:
statusProperty.set("failed");
break;
case WAITING:
statusProperty.set("waiting");
break;
case UNKNOWN:
default:
statusProperty.set("unknown");
break;
}
if (isPinned()) {
statusProperty.set(statusProperty.get() + " 🔒");
}
}
@Override
public int getProgress() {
return delegate.getProgress();
}
@Override
public void setProgress(int progress) {
delegate.setProgress(progress);
if (progress >= 0) {
progressProperty.set(progress + "%");
} else {
progressProperty.set("");
}
}
@Override
public void setSizeInByte(long sizeInByte) {
delegate.setSizeInByte(sizeInByte);
sizeProperty.set(sizeInByte);
}
public StringProperty getProgressProperty() {
return progressProperty;
}
@Override
public int hashCode() {
return delegate.hashCode();
}
@Override
public boolean equals(Object obj) {
return delegate.equals(obj);
}
@Override
public String toString() {
return delegate.toString();
}
public void update(Recording updated) {
if (!Config.getInstance().getSettings().localRecording) {
if (getStatus() == State.DOWNLOADING && updated.getStatus() != State.DOWNLOADING) {
// ignore, because the the status coming from the server is FINISHED and we are
// overriding it with DOWNLOADING
return;
}
}
setStatus(updated.getStatus());
setProgress(updated.getProgress());
setSizeInByte(updated.getSizeInByte());
setSingleFile(updated.isSingleFile());
setAssociatedFiles(updated.getAssociatedFiles());
}
@Override
public void setPath(String path) {
delegate.setPath(path);
}
@Override
public long getSizeInByte() {
return delegate.getSizeInByte();
}
public LongProperty getSizeProperty() {
return sizeProperty;
}
@Override
public void setMetaDataFile(String metaDataFile) {
delegate.setMetaDataFile(metaDataFile);
}
@Override
public String getMetaDataFile() {
return delegate.getMetaDataFile();
}
@Override
public boolean isSingleFile() {
return delegate.isSingleFile();
}
@Override
public void setSingleFile(boolean singleFile) {
delegate.setSingleFile(singleFile);
}
@Override
public boolean isPinned() {
return delegate.isPinned();
}
@Override
public void setPinned(boolean pinned) {
delegate.setPinned(pinned);
setStatus(getStatus());
}
public boolean valueChanged() {
boolean changed = getSizeInByte() != lastValue;
lastValue = getSizeInByte();
return changed;
}
@Override
public String getNote() {
return delegate.getNote();
}
@Override
public void setNote(String note) {
delegate.setNote(note);
notesProperty.set(note);
}
public StringProperty getNoteProperty() {
return notesProperty;
}
@Override
public File getAbsoluteFile() {
return delegate.getAbsoluteFile();
}
@Override
public void setAbsoluteFile(File absoluteFile) {
delegate.setAbsoluteFile(absoluteFile);
}
@Override
public String getId() {
return delegate.getId();
}
@Override
public void setId(String id) {
delegate.setId(id);
}
@Override
public void setStatusWithEvent(State status) {
delegate.setStatusWithEvent(status);
}
@Override
public File getPostProcessedFile() {
return delegate.getPostProcessedFile();
}
@Override
public void setPostProcessedFile(File postProcessedFile) {
delegate.setPostProcessedFile(postProcessedFile);
}
@Override
public RecordingProcess getRecordingProcess() {
return delegate.getRecordingProcess();
}
@Override
public void setRecordingProcess(RecordingProcess recordingProcess) {
delegate.setRecordingProcess(recordingProcess);
}
@Override
public Duration getLength() {
return delegate.getLength();
}
@Override
public void refresh() {
delegate.refresh();
}
@Override
public boolean canBePostProcessed() {
return delegate.canBePostProcessed();
}
@Override
public Set<String> getAssociatedFiles() {
return delegate.getAssociatedFiles();
}
@Override
public void setAssociatedFiles(Set<String> associatedFiles) {
delegate.setAssociatedFiles(associatedFiles);
}
@Override
public Optional<File> getContactSheet() {
return delegate.getContactSheet();
}
@Override
public int getSelectedResolution() {
return delegate.getSelectedResolution();
}
}

View File

@ -0,0 +1,23 @@
package ctbrec.ui;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ctbrec.Java;
public class Launcher {
private static final Logger LOG = LoggerFactory.getLogger(Launcher.class);
public static void main(String[] args) {
int javaVersion = Java.version();
if(javaVersion == 0) {
LOG.warn("Unknown Java version {}. App might not work as expected", javaVersion);
} else if (javaVersion < 10) {
LOG.error("Your Java version ({}) is too old. Please update to Java 10 or newer", javaVersion);
System.exit(1);
}
System.setProperty("awt.useSystemAAFontSettings","lcd");
CamrecApplication.main(args);
}
}

View File

@ -0,0 +1,22 @@
package ctbrec.ui;
import javafx.scene.paint.Color;
import javafx.scene.shape.Polygon;
public class PauseIcon extends Polygon {
public PauseIcon(Color color, int size) {
super(
0, size,
0, 0,
(size * 2.0 / 5.0), 0,
(size * 2.0 / 5.0), size,
(size * 3.0 / 5.0), size,
(size * 3.0 / 5.0), 0,
size, 0,
size, size
);
setFill(color);
}
}

View File

@ -0,0 +1,240 @@
package ctbrec.ui;
import com.iheartradio.m3u8.ParseException;
import com.iheartradio.m3u8.PlaylistException;
import ctbrec.*;
import ctbrec.event.EventBusHolder;
import ctbrec.io.StreamRedirector;
import ctbrec.io.UrlUtil;
import ctbrec.recorder.download.StreamSource;
import ctbrec.recorder.download.hls.NoStreamFoundException;
import ctbrec.ui.controls.Dialogs;
import ctbrec.ui.event.PlayerStartedEvent;
import ctbrec.variableexpansion.ModelVariableExpander;
import javafx.scene.Scene;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import javax.xml.bind.JAXBException;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ExecutionException;
@Slf4j
public class Player {
private static PlayerThread playerThread;
private static Scene scene;
private Player() {
}
public static boolean play(Recording rec) {
boolean singlePlayer = Config.getInstance().getSettings().singlePlayer;
try {
if (singlePlayer && playerThread != null && playerThread.isRunning()) {
playerThread.stopThread();
}
playerThread = new PlayerThread(rec);
return true;
} catch (Exception e1) {
log.error("Couldn't start player", e1);
return false;
}
}
public static boolean play(Model model) {
return play(model, true);
}
public static boolean play(Model model, boolean async) {
try {
if (model.isOnline(true)) {
boolean singlePlayer = Config.getInstance().getSettings().singlePlayer;
if (singlePlayer && playerThread != null && playerThread.isRunning()) {
playerThread.stopThread();
}
EventBusHolder.BUS.post(new PlayerStartedEvent(model));
if (singlePlayer && playerThread != null && playerThread.isRunning()) {
playerThread.stopThread();
}
playerThread = new PlayerThread(model);
if (!async) {
playerThread.join();
}
return true;
} else {
Dialogs.showError(scene, "Room not public", "Room is currently not public", null);
return false;
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
log.error("Couldn't get stream information for model {}", model, e);
Dialogs.showError(scene, "Couldn't determine stream URL", e.getLocalizedMessage(), e);
return false;
} catch (Exception e) {
log.error("Couldn't get stream information for model {}", model, e);
Dialogs.showError(scene, "Couldn't determine stream URL", e.getLocalizedMessage(), e);
return false;
}
}
public static void stop() {
if (playerThread != null) {
playerThread.stopThread();
}
}
private static class PlayerThread extends Thread {
@Getter
private boolean running = false;
private Process playerProcess;
private Recording rec;
private Model model;
PlayerThread(Model model) {
this.model = model;
setName(getClass().getName());
start();
}
PlayerThread(Recording rec) {
this.rec = rec;
this.model = rec.getModel();
setName(getClass().getName());
start();
}
@Override
public void run() {
running = true;
Runtime rt = Runtime.getRuntime();
Config cfg = Config.getInstance();
try {
if (cfg.getSettings().localRecording && rec != null) {
File file = rec.getAbsoluteFile();
String[] cmdline = createCmdline(file.getAbsolutePath(), model);
playerProcess = rt.exec(cmdline, OS.getEnvironment(), file.getParentFile());
} else {
String url = null;
if (rec != null) {
url = getRemoteRecordingUrl(rec, cfg);
model = rec.getModel();
} else if (model != null) {
url = getPlaylistUrl(model);
}
log.debug("Playing {}", url);
String[] cmdline = createCmdline(url, model);
log.debug("Player command line: {}", Arrays.toString(cmdline));
playerProcess = rt.exec(cmdline);
}
// create threads, which read stdout and stderr of the player process. these are needed,
// because otherwise the internal buffer for these streams fill up and block the process
Thread std = new Thread(new StreamRedirector(playerProcess.getInputStream(), OutputStream.nullOutputStream()));
std.setName("Player stdout pipe");
std.setDaemon(true);
std.start();
Thread err = new Thread(new StreamRedirector(playerProcess.getErrorStream(), OutputStream.nullOutputStream()));
err.setName("Player stderr pipe");
err.setDaemon(true);
err.start();
playerProcess.waitFor();
log.debug("Media player finished.");
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
log.error("Error in player thread", e);
Dialogs.showError(scene, "Playback failed", "Couldn't start playback", e);
} catch (Exception e) {
log.error("Error in player thread", e);
Dialogs.showError(scene, "Playback failed", "Couldn't start playback", e);
}
running = false;
}
private static String getPlaylistUrl(Model model) throws IOException, ExecutionException, ParseException, PlaylistException, JAXBException {
List<StreamSource> sources = model.getStreamSources();
Collections.sort(sources);
StreamSource best;
int maxRes = Config.getInstance().getSettings().maximumResolutionPlayer;
if (maxRes > 0 && !sources.isEmpty()) {
for (Iterator<StreamSource> iterator = sources.iterator(); iterator.hasNext(); ) {
StreamSource streamSource = iterator.next();
if (streamSource.getHeight() > 0 && maxRes < streamSource.getHeight()) {
log.trace("Res too high {} > {}", streamSource.getHeight(), maxRes);
iterator.remove();
}
}
}
if (sources.isEmpty()) {
throw new NoStreamFoundException("No stream left in playlist, because player resolution is set to " + maxRes);
} else {
log.debug("{} selected {}", model.getName(), sources.get(sources.size() - 1));
best = sources.get(sources.size() - 1);
}
return best.getMediaPlaylistUrl();
}
private void expandPlaceHolders(String[] cmdline) {
ModelVariableExpander expander = new ModelVariableExpander(model, CamrecApplication.modelNotesService, null, null);
for (int i = 1; i < cmdline.length; i++) {
var param = cmdline[i];
param = expander.expand(param);
cmdline[i] = param;
}
}
private String[] createCmdline(String mediaSource, Model model) {
Config cfg = Config.getInstance();
String params = cfg.getSettings().mediaPlayerParams.trim();
String[] cmdline;
if (params.isEmpty()) {
cmdline = new String[2];
} else {
String[] playerArgs = StringUtil.splitParams(params);
cmdline = new String[playerArgs.length + 2];
System.arraycopy(playerArgs, 0, cmdline, 1, playerArgs.length);
}
cmdline[0] = cfg.getSettings().mediaPlayer;
cmdline[cmdline.length - 1] = mediaSource;
if (model != null) {
expandPlaceHolders(cmdline);
}
return cmdline;
}
private String getRemoteRecordingUrl(Recording rec, Config cfg)
throws MalformedURLException, InvalidKeyException, NoSuchAlgorithmException, UnsupportedEncodingException {
String hlsBase = Config.getInstance().getServerUrl() + "/hls";
String recUrl = hlsBase + '/' + rec.getId() + (rec.isSingleFile() ? "" : "/playlist.m3u8");
if (cfg.getSettings().requireAuthentication) {
recUrl = UrlUtil.addHmac(recUrl, cfg);
}
return recUrl;
}
public void stopThread() {
if (playerProcess != null) {
playerProcess.destroy();
}
}
}
public static void setScene(Scene scene) {
Player.scene = scene;
}
}

View File

@ -0,0 +1,190 @@
package ctbrec.ui;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ctbrec.Config;
import ctbrec.ui.controls.StreamPreview;
import javafx.application.Platform;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Point2D;
import javafx.scene.Node;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableRow;
import javafx.scene.control.TableView;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.StackPane;
import javafx.stage.Popup;
public class PreviewPopupHandler implements EventHandler<MouseEvent> {
private static final Logger LOG = LoggerFactory.getLogger(PreviewPopupHandler.class);
private static final int offset = 10;
private long timeForPopupOpen = TimeUnit.SECONDS.toMillis(1);
private long timeForPopupClose = 400;
private Popup popup = new Popup();
private Node parent;
private StreamPreview streamPreview;
private JavaFxModel model;
private volatile long openCountdown = -1;
private volatile long closeCountdown = -1;
private volatile long lastModelChange = -1;
private volatile boolean changeModel = false;
public PreviewPopupHandler(Node parent) {
this.parent = parent;
streamPreview = new StreamPreview();
streamPreview.setStyle("-fx-background-color: -fx-outer-border, -fx-inner-border, -fx-base;"+
"-fx-background-insets: 0 0 -1 0, 0, 1, 2;" +
"-fx-background-radius: 10px, 10px, 10px, 10px;" +
"-fx-padding: 1;" +
"-fx-effect: dropshadow(gaussian, rgba(0, 0, 0, 0.8), 20, 0, 0, 0);");
popup.getContent().add(streamPreview);
StackPane.setMargin(streamPreview, new Insets(5));
createTimerThread();
}
@Override
public void handle(MouseEvent event) {
if(!isInPreviewColumn(event) || !Config.getInstance().getSettings().livePreviews) {
closeCountdown = timeForPopupClose;
return;
}
if(event.getEventType() == MouseEvent.MOUSE_CLICKED && event.getButton() == MouseButton.PRIMARY) {
model = getModel(event);
popup.setX(event.getScreenX()+ offset);
popup.setY(event.getScreenY()+ offset);
showPopup();
openCountdown = -1;
} else if(event.getEventType() == MouseEvent.MOUSE_ENTERED) {
popup.setX(event.getScreenX()+ offset);
popup.setY(event.getScreenY()+ offset);
JavaFxModel newModel = getModel(event);
if(newModel != null) {
closeCountdown = -1;
boolean modelChanged = newModel != this.model;
this.model = newModel;
if(popup.isShowing()) {
openCountdown = -1;
if(modelChanged) {
lastModelChange = System.currentTimeMillis();
changeModel = true;
streamPreview.stop();
}
} else {
openCountdown = timeForPopupOpen;
}
}
} else if(event.getEventType() == MouseEvent.MOUSE_EXITED) {
openCountdown = -1;
closeCountdown = timeForPopupClose;
model = null;
} else if(event.getEventType() == MouseEvent.MOUSE_MOVED) {
popup.setX(event.getScreenX() + offset);
popup.setY(event.getScreenY() + offset);
}
}
private boolean isInPreviewColumn(MouseEvent event) {
@SuppressWarnings("unchecked")
TableRow<JavaFxModel> row = (TableRow<JavaFxModel>) event.getSource();
TableView<JavaFxModel> table = row.getTableView();
double columnOffset = 0;
double width = 0;
for (TableColumn<JavaFxModel, ?> col : table.getColumns()) {
columnOffset += width;
width = col.getWidth();
if(Objects.equals(col.getId(), "preview")) {
Point2D screenToLocal = table.screenToLocal(event.getScreenX(), event.getScreenY());
double x = screenToLocal.getX();
return x >= columnOffset && x <= columnOffset + width;
}
}
return false;
}
private JavaFxModel getModel(MouseEvent event) {
@SuppressWarnings("unchecked")
TableRow<JavaFxModel> row = (TableRow<JavaFxModel>) event.getSource();
TableView<JavaFxModel> table = row.getTableView();
int rowIndex = row.getIndex();
if(rowIndex < table.getItems().size()) {
return table.getItems().get(rowIndex);
} else {
return null;
}
}
private void showPopup() {
startStream(model);
}
private void startStream(JavaFxModel model) {
Platform.runLater(() -> {
streamPreview.startStream(model);
popup.show(parent.getScene().getWindow());
});
}
private void hidePopup() {
Platform.runLater(() -> {
popup.setX(-1000);
popup.setY(-1000);
popup.hide();
streamPreview.stop();
});
}
private void createTimerThread() {
Thread timerThread = new Thread(() -> {
while(true) {
openCountdown--;
if(openCountdown == 0) {
openCountdown = -1;
if(model != null) {
showPopup();
}
}
closeCountdown--;
if(closeCountdown == 0) {
hidePopup();
closeCountdown = -1;
}
openCountdown = Math.max(openCountdown, -1);
closeCountdown = Math.max(closeCountdown, -1);
long now = System.currentTimeMillis();
long diff = (now - lastModelChange);
if(changeModel && diff > 400) {
changeModel = false;
if(model != null) {
startStream(model);
}
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
LOG.error("PreviewPopupTimer interrupted");
break;
}
}
});
timerThread.setDaemon(true);
timerThread.setPriority(Thread.MIN_PRIORITY);
timerThread.setName("PreviewPopupTimer");
timerThread.start();
}
}

View File

@ -0,0 +1,105 @@
package ctbrec.ui;
import static ctbrec.SubsequentAction.*;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import ctbrec.Config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ctbrec.Model;
import ctbrec.SubsequentAction;
import ctbrec.ui.controls.DateTimePicker;
import ctbrec.ui.controls.Dialogs;
import javafx.geometry.Insets;
import javafx.geometry.VPos;
import javafx.scene.Cursor;
import javafx.scene.Node;
import javafx.scene.control.Label;
import javafx.scene.control.RadioButton;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.VBox;
public class RecordUntilDialog {
private static final Logger LOG = LoggerFactory.getLogger(RecordUntilDialog.class);
private final Node source;
private final Model model;
private final GridPane gridPane = new GridPane();
private RadioButton pauseButton;
private RadioButton removeButton;
private DateTimePicker datePicker;
private Config config = Config.getInstance();
public RecordUntilDialog(Node source, Model model) {
this.source = source;
this.model = model;
createGui();
}
private void createGui() {
source.setCursor(Cursor.WAIT);
datePicker = new DateTimePicker();
gridPane.setHgap(10);
gridPane.setVgap(10);
gridPane.setPadding(new Insets(20, 150, 10, 10));
gridPane.add(new Label("Stop at"), 0, 0);
gridPane.add(datePicker, 1, 0);
Label l = new Label("And then");
l.setPadding(new Insets(5, 0, 0, 0));
gridPane.add(l, 0, 1);
GridPane.setValignment(l, VPos.TOP);
var toggleGroup = new ToggleGroup();
pauseButton = new RadioButton("pause recording");
pauseButton.setSelected(model.getRecordUntilSubsequentAction() == PAUSE);
pauseButton.setToggleGroup(toggleGroup);
removeButton = new RadioButton("remove model");
removeButton.setSelected(model.getRecordUntilSubsequentAction() == REMOVE);
removeButton.setToggleGroup(toggleGroup);
RadioButton recordLaterButton = new RadioButton("mark for later");
recordLaterButton.setSelected(model.getRecordUntilSubsequentAction() == RECORD_LATER);
recordLaterButton.setToggleGroup(toggleGroup);
var row = new VBox();
row.getChildren().addAll(pauseButton, removeButton, recordLaterButton);
VBox.setMargin(pauseButton, new Insets(5));
VBox.setMargin(removeButton, new Insets(5));
VBox.setMargin(recordLaterButton, new Insets(5));
gridPane.add(row, 1, 1);
if (model.isRecordingTimeLimited()) {
var localDate = LocalDateTime.ofInstant(model.getRecordUntil(), ZoneId.systemDefault());
datePicker.setDateTimeValue(localDate);
} else {
var localDate = LocalDateTime.now().plusMinutes(config.getSettings().recordUntilDefaultDurationInMinutes);
datePicker.setDateTimeValue(localDate);
}
}
public boolean showAndWait() {
boolean confirmed = Dialogs.showCustomInput(source.getScene(), "Stop Recording of " + model.getDisplayName() + " at", gridPane);
if (confirmed) {
SubsequentAction action = getSubsequentAction();
LOG.info("Stop at {} and {}", datePicker.getDateTimeValue(), action);
var stopAt = Instant.from(datePicker.getDateTimeValue().atZone(ZoneId.systemDefault()));
model.setRecordUntil(stopAt);
model.setRecordUntilSubsequentAction(action);
}
return confirmed;
}
private SubsequentAction getSubsequentAction() {
if (pauseButton.isSelected()) {
return PAUSE;
} else if (removeButton.isSelected()) {
return REMOVE;
} else {
return RECORD_LATER;
}
}
}

View File

@ -0,0 +1,5 @@
package ctbrec.ui;
public interface ShutdownListener {
void onShutdown();
}

View File

@ -0,0 +1,18 @@
package ctbrec.ui;
import ctbrec.Model;
import ctbrec.ui.sites.ConfigUI;
import ctbrec.ui.tabs.TabProvider;
import java.io.IOException;
public interface SiteUI {
TabProvider getTabProvider();
ConfigUI getConfigUI();
boolean login() throws IOException;
boolean play(Model model);
}

View File

@ -0,0 +1,168 @@
package ctbrec.ui;
import ctbrec.sites.Site;
import ctbrec.sites.amateurtv.AmateurTv;
import ctbrec.sites.bonga.BongaCams;
import ctbrec.sites.cam4.Cam4;
import ctbrec.sites.camsoda.Camsoda;
import ctbrec.sites.chaturbate.Chaturbate;
import ctbrec.sites.cherrytv.CherryTv;
import ctbrec.sites.dreamcam.Dreamcam;
import ctbrec.sites.fc2live.Fc2Live;
import ctbrec.sites.flirt4free.Flirt4Free;
import ctbrec.sites.jasmin.LiveJasmin;
import ctbrec.sites.manyvids.MVLive;
import ctbrec.sites.mfc.MyFreeCams;
import ctbrec.sites.secretfriends.SecretFriends;
import ctbrec.sites.showup.Showup;
import ctbrec.sites.streamate.Streamate;
import ctbrec.sites.streamray.Streamray;
import ctbrec.sites.stripchat.Stripchat;
import ctbrec.sites.winktv.WinkTv;
import ctbrec.sites.xlovecam.XloveCam;
import ctbrec.ui.sites.amateurtv.AmateurTvSiteUi;
import ctbrec.ui.sites.bonga.BongaCamsSiteUi;
import ctbrec.ui.sites.cam4.Cam4SiteUi;
import ctbrec.ui.sites.camsoda.CamsodaSiteUi;
import ctbrec.ui.sites.chaturbate.ChaturbateSiteUi;
import ctbrec.ui.sites.cherrytv.CherryTvSiteUi;
import ctbrec.ui.sites.dreamcam.DreamcamSiteUi;
import ctbrec.ui.sites.fc2live.Fc2LiveSiteUi;
import ctbrec.ui.sites.flirt4free.Flirt4FreeSiteUi;
import ctbrec.ui.sites.jasmin.LiveJasminSiteUi;
import ctbrec.ui.sites.manyvids.MVLiveSiteUi;
import ctbrec.ui.sites.myfreecams.MyFreeCamsSiteUi;
import ctbrec.ui.sites.secretfriends.SecretFriendsSiteUi;
import ctbrec.ui.sites.showup.ShowupSiteUi;
import ctbrec.ui.sites.streamate.StreamateSiteUi;
import ctbrec.ui.sites.streamray.StreamraySiteUi;
import ctbrec.ui.sites.stripchat.StripchatSiteUi;
import ctbrec.ui.sites.winktv.WinkTvSiteUi;
import ctbrec.ui.sites.xlovecam.XloveCamSiteUi;
public class SiteUiFactory {
private static AmateurTvSiteUi amateurTvUi;
private static BongaCamsSiteUi bongaSiteUi;
private static Cam4SiteUi cam4SiteUi;
private static CamsodaSiteUi camsodaSiteUi;
private static ChaturbateSiteUi ctbSiteUi;
private static CherryTvSiteUi cherryTvSiteUi;
private static Fc2LiveSiteUi fc2SiteUi;
private static Flirt4FreeSiteUi flirt4FreeSiteUi;
private static LiveJasminSiteUi jasminSiteUi;
private static MVLiveSiteUi mvLiveSiteUi;
private static MyFreeCamsSiteUi mfcSiteUi;
private static SecretFriendsSiteUi secretFriendsSiteUi;
private static ShowupSiteUi showupSiteUi;
private static StreamateSiteUi streamateSiteUi;
private static StripchatSiteUi stripchatSiteUi;
private static XloveCamSiteUi xloveCamSiteUi;
private static StreamraySiteUi streamraySiteUi;
private static WinkTvSiteUi winkTvSiteUi;
private static DreamcamSiteUi dreamcamSiteUi;
private SiteUiFactory() {
}
public static synchronized SiteUI getUi(Site site) { // NOSONAR
if (site instanceof AmateurTv) {
if (amateurTvUi == null) {
amateurTvUi = new AmateurTvSiteUi((AmateurTv) site);
}
return amateurTvUi;
} else if (site instanceof BongaCams) {
if (bongaSiteUi == null) {
bongaSiteUi = new BongaCamsSiteUi((BongaCams) site);
}
return bongaSiteUi;
} else if (site instanceof Cam4) {
if (cam4SiteUi == null) {
cam4SiteUi = new Cam4SiteUi((Cam4) site);
}
return cam4SiteUi;
} else if (site instanceof Camsoda) {
if (camsodaSiteUi == null) {
camsodaSiteUi = new CamsodaSiteUi((Camsoda) site);
}
return camsodaSiteUi;
} else if (site instanceof Chaturbate) {
if (ctbSiteUi == null) {
ctbSiteUi = new ChaturbateSiteUi((Chaturbate) site);
}
return ctbSiteUi;
} else if (site instanceof CherryTv) {
if (cherryTvSiteUi == null) {
cherryTvSiteUi = new CherryTvSiteUi((CherryTv) site);
}
return cherryTvSiteUi;
} else if (site instanceof Dreamcam) {
if (dreamcamSiteUi == null) {
dreamcamSiteUi = new DreamcamSiteUi((Dreamcam) site);
}
return dreamcamSiteUi;
} else if (site instanceof Fc2Live) {
if (fc2SiteUi == null) {
fc2SiteUi = new Fc2LiveSiteUi((Fc2Live) site);
}
return fc2SiteUi;
} else if (site instanceof Flirt4Free) {
if (flirt4FreeSiteUi == null) {
flirt4FreeSiteUi = new Flirt4FreeSiteUi((Flirt4Free) site);
}
return flirt4FreeSiteUi;
} else if (site instanceof MVLive) {
if (mvLiveSiteUi == null) {
mvLiveSiteUi = new MVLiveSiteUi((MVLive) site);
}
return mvLiveSiteUi;
} else if (site instanceof MyFreeCams) {
if (mfcSiteUi == null) {
mfcSiteUi = new MyFreeCamsSiteUi((MyFreeCams) site);
}
return mfcSiteUi;
} else if (site instanceof SecretFriends) {
if (secretFriendsSiteUi == null) {
secretFriendsSiteUi = new SecretFriendsSiteUi((SecretFriends) site);
}
return secretFriendsSiteUi;
} else if (site instanceof Showup) {
if (showupSiteUi == null) {
showupSiteUi = new ShowupSiteUi((Showup) site);
}
return showupSiteUi;
} else if (site instanceof Streamate) {
if (streamateSiteUi == null) {
streamateSiteUi = new StreamateSiteUi((Streamate) site);
}
return streamateSiteUi;
} else if (site instanceof LiveJasmin) {
if (jasminSiteUi == null) {
jasminSiteUi = new LiveJasminSiteUi((LiveJasmin) site);
}
return jasminSiteUi;
} else if (site instanceof Stripchat) {
if (stripchatSiteUi == null) {
stripchatSiteUi = new StripchatSiteUi((Stripchat) site);
}
return stripchatSiteUi;
} else if (site instanceof Streamray) {
if (streamraySiteUi == null) {
streamraySiteUi = new StreamraySiteUi((Streamray) site);
}
return streamraySiteUi;
} else if (site instanceof WinkTv) {
if (winkTvSiteUi == null) {
winkTvSiteUi = new WinkTvSiteUi((WinkTv) site);
}
return winkTvSiteUi;
} else if (site instanceof XloveCam) {
if (xloveCamSiteUi == null) {
xloveCamSiteUi = new XloveCamSiteUi((XloveCam) site);
}
return xloveCamSiteUi;
}
throw new RuntimeException("Unknown site " + site.getName());
}
}

View File

@ -0,0 +1,131 @@
package ctbrec.ui;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ctbrec.GlobalThreadPool;
import ctbrec.Model;
import ctbrec.recorder.download.StreamSource;
import ctbrec.ui.controls.Dialogs;
import javafx.concurrent.Task;
import javafx.concurrent.WorkerStateEvent;
import javafx.scene.Cursor;
import javafx.scene.Scene;
import javafx.scene.control.ButtonType;
import javafx.scene.control.ChoiceDialog;
import javafx.scene.image.Image;
import javafx.stage.Stage;
public class StreamSourceSelectionDialog extends ChoiceDialog<StreamSource> {
private static final Logger LOG = LoggerFactory.getLogger(StreamSourceSelectionDialog.class);
public static final StreamSource BEST = new BestStreamSource();
public static final StreamSource LOADING = new LoadingStreamSource();
private Scene parent;
private Model model;
private Task<List<StreamSource>> loadStreamSources;
public StreamSourceSelectionDialog(Scene parent, Model model) {
this.parent = parent;
this.model = model;
if (parent != null) {
getDialogPane().getScene().getStylesheets().addAll(parent.getStylesheets());
}
changeCursorTo(Cursor.WAIT);
getItems().add(LOADING);
setSelectedItem(LOADING);
setTitle("Stream Quality");
setHeaderText("Select your preferred stream quality for " + model.getDisplayName());
var icon = Dialogs.class.getResourceAsStream("/icon.png");
var stage = (Stage) getDialogPane().getScene().getWindow();
stage.getIcons().add(new Image(icon));
setResultConverter(bt -> (bt == ButtonType.OK) ? getSelectedItem() : null);
loadStreamSources = new Task<List<StreamSource>>() {
@Override
protected List<StreamSource> call() throws Exception {
List<StreamSource> sources = model.getStreamSources();
Collections.sort(sources);
sources.add(BEST);
return sources;
}
};
loadStreamSources.setOnFailed(this::onFailed);
loadStreamSources.setOnSucceeded(this::onSucceeded);
GlobalThreadPool.submit(loadStreamSources);
}
private void onFailed(WorkerStateEvent evt) {
changeCursorTo(Cursor.DEFAULT);
try {
loadStreamSources.get();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
LOG.error("Couldn't fetch available stream sources", e);
} catch (ExecutionException e) {
LOG.error("Couldn't fetch available stream sources", e);
}
boolean confirmed = Dialogs.showConfirmDialog("Error loading stream resolutions", "Do you want to add the model anyway?", "Stream resolutions unknown", parent);
if (confirmed) {
getItems().clear();
getItems().add(BEST);
setSelectedItem(BEST);
} else {
close();
}
}
private void onSucceeded(WorkerStateEvent evt) {
changeCursorTo(Cursor.DEFAULT);
List<StreamSource> sources;
try {
sources = loadStreamSources.get();
getItems().remove(LOADING);
getItems().addAll(sources);
var selectedIndex = model.getStreamUrlIndex() > -1 ? Math.min(model.getStreamUrlIndex(), sources.size() - 1) : sources.size() - 1;
setSelectedItem(getItems().get(selectedIndex));
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
showError(e);
} catch (ExecutionException e) {
showError(e);
}
}
void changeCursorTo(Cursor cursor) {
parent.setCursor(cursor);
getDialogPane().setCursor(cursor);
}
private void showError(Exception e) {
Dialogs.showError(parent, getHeaderText(), getContentText(), e);
}
private static class BestStreamSource extends StreamSource {
@Override
public String toString() {
return "Best";
}
}
private static class LoadingStreamSource extends StreamSource {
@Override
public String toString() {
return "Loading...";
}
}
public int indexOf(StreamSource selectedSource) {
int index = -1;
if (selectedSource != LOADING && selectedSource != BEST) {
index = getItems().indexOf(selectedSource);
}
return index;
}
}

View File

@ -0,0 +1,258 @@
package ctbrec.ui;
import java.util.regex.Pattern;
import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.beans.binding.IntegerBinding;
import javafx.beans.property.ReadOnlyIntegerProperty;
import javafx.beans.property.ReadOnlyIntegerWrapper;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.IndexRange;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class TimeTextFieldTest extends Application {
@Override
public void start(Stage primaryStage) {
VBox root = new VBox(5);
root.setPadding(new Insets(5));
Label hrLabel = new Label();
Label minLabel = new Label();
Label secLabel = new Label();
TimeTextField timeTextField = new TimeTextField();
hrLabel.textProperty().bind(Bindings.format("Hours: %d", timeTextField.hoursProperty()));
minLabel.textProperty().bind(Bindings.format("Minutes: %d", timeTextField.minutesProperty()));
secLabel.textProperty().bind(Bindings.format("Seconds: %d", timeTextField.secondsProperty()));
root.getChildren().addAll(timeTextField, hrLabel, minLabel, secLabel);
Scene scene = new Scene(root);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
public static class TimeTextField extends TextField {
enum Unit {
HOURS, MINUTES, SECONDS
};
private final Pattern timePattern;
private final ReadOnlyIntegerWrapper hours;
private final ReadOnlyIntegerWrapper minutes;
private final ReadOnlyIntegerWrapper seconds;
public TimeTextField() {
this("00:00:00");
}
public TimeTextField(String time) {
super(time);
timePattern = Pattern.compile("\\d\\d:\\d\\d:\\d\\d");
if (!validate(time)) {
throw new IllegalArgumentException("Invalid time: " + time);
}
hours = new ReadOnlyIntegerWrapper(this, "hours");
minutes = new ReadOnlyIntegerWrapper(this, "minutes");
seconds = new ReadOnlyIntegerWrapper(this, "seconds");
hours.bind(new TimeTextField.TimeUnitBinding(Unit.HOURS));
minutes.bind(new TimeTextField.TimeUnitBinding(Unit.MINUTES));
seconds.bind(new TimeTextField.TimeUnitBinding(Unit.SECONDS));
}
public ReadOnlyIntegerProperty hoursProperty() {
return hours.getReadOnlyProperty();
}
public int getHours() {
return hours.get();
}
public ReadOnlyIntegerProperty minutesProperty() {
return minutes.getReadOnlyProperty();
}
public int getMinutes() {
return minutes.get();
}
public ReadOnlyIntegerProperty secondsProperty() {
return seconds.getReadOnlyProperty();
}
public int getSeconds() {
return seconds.get();
}
@Override
public void appendText(String text) {
// Ignore this. Our text is always 8 characters long, we cannot append anything
}
@Override
public boolean deleteNextChar() {
boolean success = false;
// If there's a selection, delete it:
final IndexRange selection = getSelection();
if (selection.getLength() > 0) {
int selectionEnd = selection.getEnd();
this.deleteText(selection);
this.positionCaret(selectionEnd);
success = true;
} else {
// If the caret preceeds a digit, replace that digit with a zero and move the caret forward. Else just move the caret forward.
int caret = this.getCaretPosition();
if (caret % 3 != 2) { // not preceeding a colon
String currentText = this.getText();
setText(currentText.substring(0, caret) + "0" + currentText.substring(caret + 1));
success = true;
}
this.positionCaret(Math.min(caret + 1, this.getText().length()));
}
return success;
}
@Override
public boolean deletePreviousChar() {
boolean success = false;
// If there's a selection, delete it:
final IndexRange selection = getSelection();
if (selection.getLength() > 0) {
int selectionStart = selection.getStart();
this.deleteText(selection);
this.positionCaret(selectionStart);
success = true;
} else {
// If the caret is after a digit, replace that digit with a zero and move the caret backward. Else just move the caret back.
int caret = this.getCaretPosition();
if (caret % 3 != 0) { // not following a colon
String currentText = this.getText();
setText(currentText.substring(0, caret - 1) + "0" + currentText.substring(caret));
success = true;
}
this.positionCaret(Math.max(caret - 1, 0));
}
return success;
}
@Override
public void deleteText(IndexRange range) {
this.deleteText(range.getStart(), range.getEnd());
}
@Override
public void deleteText(int begin, int end) {
// Replace all digits in the given range with zero:
StringBuilder builder = new StringBuilder(this.getText());
for (int c = begin; c < end; c++) {
if (c % 3 != 2) { // Not at a colon:
builder.replace(c, c + 1, "0");
}
}
this.setText(builder.toString());
}
@Override
public void insertText(int index, String text) {
// Handle an insert by replacing the range from index to index+text.length() with text, if that results in a valid string:
StringBuilder builder = new StringBuilder(this.getText());
builder.replace(index, index + text.length(), text);
final String testText = builder.toString();
if (validate(testText)) {
this.setText(testText);
}
this.positionCaret(index + text.length());
}
@Override
public void replaceSelection(String replacement) {
final IndexRange selection = this.getSelection();
if (selection.getLength() == 0) {
this.insertText(selection.getStart(), replacement);
} else {
this.replaceText(selection.getStart(), selection.getEnd(), replacement);
}
}
@Override
public void replaceText(IndexRange range, String text) {
this.replaceText(range.getStart(), range.getEnd(), text);
}
@Override
public void replaceText(int begin, int end, String text) {
if (begin == end) {
this.insertText(begin, text);
} else {
// only handle this if text.length() is equal to the number of characters being replaced, and if the replacement results in a valid string:
if (text.length() == end - begin) {
StringBuilder builder = new StringBuilder(this.getText());
builder.replace(begin, end, text);
String testText = builder.toString();
if (validate(testText)) {
this.setText(testText);
}
this.positionCaret(end);
}
}
}
private boolean validate(String time) {
if (!timePattern.matcher(time).matches()) {
return false;
}
String[] tokens = time.split(":");
assert tokens.length == 3;
try {
int hours = Integer.parseInt(tokens[0]);
int mins = Integer.parseInt(tokens[1]);
int secs = Integer.parseInt(tokens[2]);
if (hours < 0 || hours > 23) {
return false;
}
if (mins < 0 || mins > 59) {
return false;
}
if (secs < 0 || secs > 59) {
return false;
}
return true;
} catch (NumberFormatException nfe) {
// regex matching should assure we never reach this catch block
assert false;
return false;
}
}
private final class TimeUnitBinding extends IntegerBinding {
final Unit unit;
TimeUnitBinding(Unit unit) {
this.bind(textProperty());
this.unit = unit;
}
@Override
protected int computeValue() {
// Crazy enum magic
String token = getText().split(":")[unit.ordinal()];
return Integer.parseInt(token);
}
}
}
}

View File

@ -0,0 +1,102 @@
package ctbrec.ui;
import java.text.DecimalFormat;
import java.util.Objects;
import java.util.concurrent.ExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ctbrec.GlobalThreadPool;
import ctbrec.sites.Site;
import javafx.application.Platform;
import javafx.concurrent.Task;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.ButtonType;
import javafx.scene.control.TextInputDialog;
import javafx.stage.Stage;
public class TipDialog extends TextInputDialog {
private static final Logger LOG = LoggerFactory.getLogger(TipDialog.class);
private Site site;
private Scene parent;
public TipDialog(Scene parent, Site site) {
this.parent = parent;
this.site = site;
setTitle("Send Tip");
loadTokenBalance();
setHeaderText("Loading token balance…");
setContentText("Amount of tokens to tip:");
setResizable(true);
getEditor().setDisable(true);
if (parent != null) {
Stage stage = (Stage) getDialogPane().getScene().getWindow();
stage.getScene().getStylesheets().addAll(parent.getStylesheets());
}
}
private void loadTokenBalance() {
Task<Double> task = new Task<Double>() {
@Override
protected Double call() throws Exception {
if (!Objects.equals(System.getenv("CTBREC_DEV"), "1")) {
SiteUiFactory.getUi(site).login();
return site.getTokenBalance();
} else {
return 1_000_000d;
}
}
@Override
protected void done() {
try {
double tokens = get();
Platform.runLater(() -> {
if (tokens <= 0) {
String msg = "Do you want to buy tokens now?\n\nIf you agree, " + site.getName() + " will open in a browser. "
+ "The used address is an affiliate link, which supports me, but doesn't cost you anything more.";
Alert buyTokens = new AutosizeAlert(Alert.AlertType.CONFIRMATION, msg, parent, ButtonType.NO, ButtonType.YES);
buyTokens.setTitle("No tokens");
buyTokens.setHeaderText("You don't have any tokens");
buyTokens.showAndWait();
TipDialog.this.close();
if (buyTokens.getResult() == ButtonType.YES) {
DesktopIntegration.open(site.getAffiliateLink());
}
} else {
getEditor().setDisable(false);
DecimalFormat df = new DecimalFormat("0.##");
setHeaderText("Current token balance: " + df.format(tokens));
}
});
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
handleExcetion(e);
} catch (ExecutionException e) {
handleExcetion(e);
}
}
};
GlobalThreadPool.submit(task);
}
private void handleExcetion(Exception e) {
LOG.error("Couldn't retrieve account balance", e);
showErrorDialog(e);
}
private void showErrorDialog(Throwable throwable) {
Platform.runLater(() -> {
Alert alert = new AutosizeAlert(Alert.AlertType.ERROR, parent);
alert.setTitle("Error");
alert.setHeaderText("Couldn't retrieve token balance");
alert.setContentText("Error while loading your token balance: " + throwable.getLocalizedMessage());
alert.showAndWait();
TipDialog.this.close();
});
}
}

View File

@ -0,0 +1,97 @@
package ctbrec.ui;
import com.google.common.eventbus.Subscribe;
import ctbrec.GlobalThreadPool;
import ctbrec.event.EventBusHolder;
import ctbrec.sites.Site;
import javafx.application.Platform;
import javafx.concurrent.Task;
import javafx.scene.control.Label;
import javafx.scene.control.Tooltip;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.text.DecimalFormat;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ExecutionException;
public class TokenLabel extends Label {
private static final Logger LOG = LoggerFactory.getLogger(TokenLabel.class);
private double tokens = -1;
private final Site site;
public TokenLabel(Site site) {
this.site = site;
setText("Tokens: loading…");
EventBusHolder.BUS.register(new Object() {
@Subscribe
public void tokensUpdates(Map<String, Object> e) {
if (Objects.equals("tokens", e.get("event"))) {
tokens = (double) e.get("amount");
updateText();
} else if (Objects.equals("tokens.sent", e.get("event"))) {
tokens -= (double) e.get("amount");
updateText();
}
}
});
}
public void decrease(int tokens) {
this.tokens -= tokens;
updateText();
}
public void update(double tokens) {
this.tokens = tokens;
updateText();
}
private void updateText() {
Platform.runLater(() -> {
DecimalFormat df = new DecimalFormat("0.##");
setText("Tokens: " + df.format(tokens));
});
}
public void loadBalance() {
if (tokens != -1) {
return;
}
Task<Double> task = new Task<>() {
@Override
protected Double call() throws Exception {
if (!Objects.equals(System.getenv("CTBREC_DEV"), "1")) {
SiteUiFactory.getUi(site).login();
return site.getTokenBalance();
} else {
return 1_000_000d;
}
}
@Override
protected void done() {
try {
tokens = get();
update(tokens);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
handleException(e);
} catch (ExecutionException e) {
handleException(e);
}
}
private void handleException(Exception e) {
LOG.error("Couldn't retrieve account balance", e);
Platform.runLater(() -> {
setText("Tokens: error");
setTooltip(new Tooltip(e.getMessage()));
});
}
};
GlobalThreadPool.submit(task);
}
}

View File

@ -0,0 +1,182 @@
package ctbrec.ui;
import ctbrec.Config;
import ctbrec.event.EventBusHolder;
import ctbrec.recorder.Recorder;
import ctbrec.ui.controls.Dialogs;
import javafx.application.Platform;
import javafx.stage.Stage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.font.LineMetrics;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Map;
import static java.awt.Font.BOLD;
import static java.awt.RenderingHints.KEY_ANTIALIASING;
import static java.awt.RenderingHints.VALUE_ANTIALIAS_ON;
public class TrayIcon {
private static final Logger LOG = LoggerFactory.getLogger(TrayIcon.class);
private final Stage stage;
private final Recorder recorder;
private SystemTray tray;
private java.awt.TrayIcon awtTrayIcon;
private BufferedImage background;
public TrayIcon(Stage stage, Recorder recorder) {
this.stage = stage;
this.recorder = recorder;
}
boolean createTrayIcon() {
if (SystemTray.isSupported()) {
if (tray == null) {
String title = CamrecApplication.title;
tray = SystemTray.getSystemTray();
BufferedImage image = null;
try {
image = createImage(recorder.getCurrentlyRecording().size());
} catch (Exception e) {
// fail silently
}
PopupMenu menu = createTrayContextMenu(stage);
awtTrayIcon = new java.awt.TrayIcon(image, title, menu);
awtTrayIcon.setImageAutoSize(true);
awtTrayIcon.setToolTip(title);
try {
tray.add(awtTrayIcon);
} catch (AWTException e) {
LOG.error("Couldn't add tray icon", e);
}
awtTrayIcon.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
if (SwingUtilities.isLeftMouseButton(e)) {
toggleVisibility(stage);
}
}
});
}
return true;
} else {
LOG.error("SystemTray notifications not supported by this OS");
return false;
}
}
private PopupMenu createTrayContextMenu(Stage stage) {
var menu = new PopupMenu();
var show = new MenuItem("Show");
show.addActionListener(evt -> restoreStage(stage));
menu.add(show);
menu.addSeparator();
var pauseRecording = new MenuItem("Pause recording");
pauseRecording.addActionListener(evt -> {
try {
recorder.pause();
} catch (InvalidKeyException | NoSuchAlgorithmException | IOException e) {
Dialogs.showError(stage.getScene(), "Pausing recording", "Pausing of the recorder failed", e);
}
});
menu.add(pauseRecording);
var resumeRecording = new MenuItem("Resume recording");
resumeRecording.addActionListener(evt -> {
try {
recorder.resume();
} catch (InvalidKeyException | NoSuchAlgorithmException | IOException e) {
Dialogs.showError(stage.getScene(), "Resuming recording", "Resuming of the recorder failed", e);
}
});
menu.add(resumeRecording);
menu.addSeparator();
var exit = new MenuItem("Exit");
exit.addActionListener(evt -> exit());
menu.add(exit);
return menu;
}
private void restoreStage(Stage stage) {
Platform.runLater(() -> {
stage.setX(Config.getInstance().getSettings().windowX);
stage.setY(Config.getInstance().getSettings().windowY);
LOG.debug("Restoring window location {},{}", stage.getX(), stage.getY());
stage.setIconified(false);
stage.show();
stage.toFront();
EventBusHolder.BUS.post(Map.of("event", "stage_restored"));
});
}
private void toggleVisibility(Stage stage) {
if (stage.isShowing()) {
Platform.setImplicitExit(false);
Platform.runLater(stage::hide);
} else {
restoreStage(stage);
}
}
private void exit() {
EventBusHolder.BUS.post(Map.of("event", "shutdown"));
}
public void displayMessage(String header, String msg, java.awt.TrayIcon.MessageType info) {
createTrayIcon();
awtTrayIcon.displayMessage(header, msg, info);
}
public void updateActiveRecordings(int activeRecordings) {
try {
createTrayIcon();
if (awtTrayIcon != null) {
awtTrayIcon.setImage(createImage(activeRecordings));
}
} catch (IOException e) {
LOG.error("Couldn't update tray icon image", e);
}
}
private BufferedImage createImage(int number) throws IOException {
if (this.background == null) {
this.background = ImageIO.read(TrayIcon.class.getResource("/icon64.png"));
}
BufferedImage image = new BufferedImage(64, 64, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = (Graphics2D) image.getGraphics();
g2.drawImage(background, 0, 0, (img, infoflags, x, y, width, height) -> false);
if (number > 0 && Config.getInstance().getSettings().showActiveRecordingsInTray) {
g2.setColor(Color.decode("#dc4444"));
g2.fillOval(0, 0, 64, 64);
String text = String.valueOf(number);
String fontFamily = Config.getInstance().getSettings().showActiveRecordingsInTrayFont;
int fontSize = Config.getInstance().getSettings().showActiveRecordingsInTrayFontSize;
g2.setRenderingHint(KEY_ANTIALIASING, VALUE_ANTIALIAS_ON);
Font font = new Font(fontFamily, BOLD, fontSize);
g2.setFont(font);
FontMetrics fontMetrics = g2.getFontMetrics(font);
LineMetrics lineMetrics = fontMetrics.getLineMetrics(text, g2);
Rectangle2D stringBounds = fontMetrics.getStringBounds(text, g2);
g2.setColor(Color.decode(Config.getInstance().getSettings().showActiveRecordingsInTrayColor));
int x = (int) (image.getWidth() - stringBounds.getWidth()) / 2;
int y = (int) (((image.getHeight() - lineMetrics.getAscent()) / 2) - 8 - stringBounds.getY());
g2.drawString(text, x, y);
g2.dispose();
}
return image;
}
}

View File

@ -0,0 +1,33 @@
package ctbrec.ui;
import javafx.geometry.Bounds;
import javafx.scene.Node;
import javafx.scene.control.ContextMenu;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
public class UiUtils {
private UiUtils() {}
public static void disableRightClickFor(ContextMenu menu) {
menu.addEventFilter(MouseEvent.MOUSE_RELEASED, event -> {
if (event.getButton() == MouseButton.SECONDARY) {
event.consume();
}
});
}
public static void ignoreMouseReleasedIfMouseExited(ContextMenu menu) {
menu.addEventFilter(MouseEvent.MOUSE_RELEASED, evt -> {
if (evt.getTarget() instanceof Node) {
Node target = (Node) evt.getTarget();
Bounds screenBounds = target.localToScreen(target.getBoundsInLocal());
boolean releasedOnOriginalMouseItem = screenBounds.contains(evt.getScreenX(), evt.getScreenY());
if (!releasedOnOriginalMouseItem) {
evt.consume();
}
}
});
}
}

View File

@ -0,0 +1,8 @@
package ctbrec.ui;
public class UnicodeEmoji {
public static final String HEAVY_CHECK_MARK = "";
public static final String CLOCK = "🕒";
}

View File

@ -0,0 +1,56 @@
package ctbrec.ui.action;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import ctbrec.ui.tasks.TaskExecutionException;
import javafx.application.Platform;
public abstract class AbstractAction<P, R> {
private R result;
public CompletableFuture<Optional<R>> execute(P param) {
try {
result = doExecute(param);
Platform.runLater(() -> onSuccess(Optional.ofNullable(result)));
return CompletableFuture.completedFuture(Optional.of(result));
} catch (Exception e) {
Platform.runLater(() -> onError(e));
return CompletableFuture.failedFuture(e);
} finally {
Platform.runLater(() -> done(Optional.ofNullable(result)));
}
}
protected abstract R doExecute(P param) throws InvalidKeyException, NoSuchAlgorithmException, IOException;
public CompletableFuture<Optional<R>> executeAsync(P param) {
return CompletableFuture.supplyAsync(() -> {
try {
result = doExecute(param);
Platform.runLater(() -> onSuccess(Optional.ofNullable(result)));
return Optional.of(result);
} catch (Exception e) {
Platform.runLater(() -> onError(e));
throw new TaskExecutionException(e);
} finally {
Platform.runLater(() -> done(Optional.ofNullable(result)));
}
});
}
@SuppressWarnings("unchecked")
public <T extends AbstractAction<P, R>> T beforeOnGuiThread(Runnable r) {
return (T) this;
}
protected void onSuccess(Optional<R> result) {}
protected void onError(Exception e) {}
protected void done(Optional<R> result) {}
}

View File

@ -0,0 +1,91 @@
package ctbrec.ui.action;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
import ctbrec.GlobalThreadPool;
import ctbrec.Model;
import ctbrec.recorder.Recorder;
import ctbrec.ui.controls.Dialogs;
import ctbrec.ui.tasks.AbstractModelTask;
import javafx.application.Platform;
import javafx.scene.Cursor;
import javafx.scene.Node;
public abstract class AbstractModelAction {
protected Node source;
protected List<? extends Model> models;
protected Recorder recorder;
private AbstractModelTask task;
protected AbstractModelAction(Node source, List<? extends Model> models, Recorder recorder, AbstractModelTask task) {
this.source = source;
this.models = models;
this.recorder = recorder;
this.task = task;
}
protected CompletableFuture<List<Result>> execute(String errorHeader, String errorMsg) {
source.setCursor(Cursor.WAIT);
return CompletableFuture.supplyAsync(() -> internalExecute(errorHeader, errorMsg), GlobalThreadPool.get());
}
protected CompletableFuture<List<Result>> executeSync(String errorHeader, String errorMsg) {
source.setCursor(Cursor.WAIT);
return CompletableFuture.completedFuture(internalExecute(errorHeader, errorMsg));
}
protected List<Result> internalExecute(String errorHeader, String errorMsg) {
final List<Result> result = new ArrayList<>(models.size());
final List<CompletableFuture<Model>> futures = new ArrayList<>(models.size());
for (Model model : models) {
futures.add(task
.executeSync(model)
.whenComplete((mdl, ex) ->
result.add(new Result(model, ex))));
}
Platform.runLater(() -> source.setCursor(Cursor.DEFAULT));
checkResultForErrors(errorHeader, errorMsg, result);
return result;
}
protected void checkResultForErrors(String errorHeader, String errorMsg, List<Result> result) {
List<Result> failed = result.stream().filter(Result::failed).collect(Collectors.toList());
if (!failed.isEmpty()) {
Throwable t = failed.get(0).getThrowable();
String failedModelList = failed.stream().map(Result::getModel).map(Model::getDisplayName).collect(Collectors.joining(", "));
String msg = MessageFormat.format(errorMsg, failedModelList);
Dialogs.showError(source.getScene(), errorHeader, msg, t);
}
}
public static class Result {
private Model model;
private Throwable throwable;
public Result(Model model, Throwable t) {
this.model = model;
this.throwable = t;
}
public boolean successful() {
return throwable == null;
}
public boolean failed() {
return throwable != null;
}
public Model getModel() {
return model;
}
public Throwable getThrowable() {
return throwable;
}
}
}

View File

@ -0,0 +1,80 @@
package ctbrec.ui.action;
import ctbrec.Config;
import ctbrec.Model;
import ctbrec.event.EventBusHolder;
import ctbrec.ui.CamrecApplication;
import javafx.scene.Node;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
public abstract class AbstractPortraitAction {
public static final String FORMAT = "jpg";
protected Node source;
protected Model model;
protected BufferedImage convertToScaledJpg(BufferedImage original) {
java.awt.Image scaledPortrait = original.getScaledInstance(-1, 256, java.awt.Image.SCALE_SMOOTH);
BufferedImage bimage = new BufferedImage(scaledPortrait.getWidth(null), scaledPortrait.getHeight(null), BufferedImage.TYPE_INT_RGB);
Graphics2D bGr = bimage.createGraphics();
bGr.drawImage(scaledPortrait, 0, 0, null);
bGr.dispose();
return bimage;
}
protected boolean store(String modelUrl, BufferedImage portrait) throws IOException {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
ImageIO.write(portrait, FORMAT, bytes);
CamrecApplication.portraitStore.writePortrait(modelUrl, bytes.toByteArray());
return true;
}
protected File getPortraitFile(String portraitId) {
File configDir = Config.getInstance().getConfigDir();
File portraitDir = new File(configDir, "portraits");
File output = new File(portraitDir, portraitId + '.' + FORMAT);
return output;
}
protected BufferedImage cropImage(BufferedImage img) {
int w = img.getWidth();
int h = img.getHeight();
if (w > h) {
return cropSides(img);
} else {
return cropTopAndBottom(img);
}
}
protected BufferedImage cropSides(BufferedImage img) {
int overlap = img.getWidth() - img.getHeight();
return img.getSubimage(overlap / 2, 0, img.getHeight(), img.getHeight());
}
protected BufferedImage cropTopAndBottom(BufferedImage img) {
int overlap = img.getHeight() - img.getWidth();
return img.getSubimage(0, overlap / 2, img.getWidth(), img.getWidth());
}
protected void firePortraitChanged() {
EventBusHolder.BUS.post(new PortraitChangedEvent(model));
}
public static class PortraitChangedEvent {
private final Model mdl;
public PortraitChangedEvent(Model model) {
this.mdl = model;
}
public Model getModel() {
return mdl;
}
}
}

View File

@ -0,0 +1,206 @@
package ctbrec.ui.action;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;
import ctbrec.Model;
import ctbrec.ModelGroup;
import ctbrec.StringUtil;
import ctbrec.recorder.Recorder;
import ctbrec.ui.controls.Dialogs;
import ctbrec.ui.controls.autocomplete.ObservableListSuggester;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Cursor;
import javafx.scene.Node;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Region;
public class AddToGroupAction {
private Node source;
private List<Model> models;
private Recorder recorder;
public AddToGroupAction(Node source, Recorder recorder, List<Model> models) {
this.source = source;
this.recorder = recorder;
this.models = models;
}
public void execute() {
execute(() -> {});
}
public void execute(Runnable callback) {
source.setCursor(Cursor.WAIT);
try {
var dialog = new AddModelGroupDialog();
boolean ok = Dialogs.showCustomInput(source.getScene(), "Add model to group", dialog.getMainPane(), (obs, ov, nv) -> dialog.requestFocus());
if (ok) {
String text = dialog.getText();
if (StringUtil.isBlank(text)) {
return;
}
Set<ModelGroup> modelGroups = recorder.getModelGroups();
Optional<ModelGroup> existingGroup = modelGroups.stream().filter(mg -> mg.getName().equalsIgnoreCase(text)).findFirst();
if (existingGroup.isPresent()) {
for (Model model : models) {
existingGroup.get().add(model);
}
recorder.saveModelGroup(existingGroup.get());
} else {
var group = new ModelGroup();
group.setId(UUID.randomUUID());
group.setName(text);
for (Model model : models) {
group.add(model);
}
modelGroups.add(group);
recorder.saveModelGroup(group);
}
}
} catch (IOException | InvalidKeyException | NoSuchAlgorithmException e) {
Dialogs.showError(source.getScene(), "Add model to group", "Saving model group failed", e);
} finally {
callback.run();
source.setCursor(Cursor.DEFAULT);
}
}
private class AddModelGroupDialog {
private ComboBox<ModelGroupListItem> comboBox;
private TextField editor;
private ObservableListSuggester suggester;
public String getText() {
return comboBox.getEditor().getText();
}
void requestFocus() {
editor.requestFocus();
editor.positionCaret(0);
editor.selectAll();
}
Region getMainPane() {
var dialogPane = new GridPane();
Set<ModelGroup> modelGroups;
modelGroups = recorder.getModelGroups();
List<ModelGroupListItem> comboBoxItems = modelGroups.stream().map(ModelGroupListItem::new).sorted().collect(Collectors.toList());
ObservableList<ModelGroupListItem> comboBoxModel = FXCollections.observableArrayList(comboBoxItems);
comboBox = new ComboBox<>(comboBoxModel);
comboBox.setEditable(true);
editor = comboBox.getEditor();
comboBox.getEditor().addEventHandler(KeyEvent.KEY_RELEASED, evt -> {
if (evt.getCode().isLetterKey() || evt.getCode().isDigitKey()) {
autocomplete(false);
} else if (evt.getCode() == KeyCode.ENTER) {
if (editor.getSelection().getLength() > 0) {
editor.selectRange(0, 0);
editor.insertText(editor.lengthProperty().get(), ":");
editor.positionCaret(editor.lengthProperty().get());
evt.consume();
}
} else if (evt.getCode() == KeyCode.SPACE && evt.isControlDown()) {
autocomplete(true);
}
});
comboBox.setPlaceholder(new Label(" type in a name to a add a new group "));
dialogPane.add(new Label("Model group "), 0, 0);
dialogPane.add(comboBox, 1, 0);
suggestInitialName(modelGroups);
suggester = new ObservableListSuggester(comboBoxModel);
return dialogPane;
}
private void suggestInitialName(Set<ModelGroup> modelGroups) {
String bestName = models.get(0).getDisplayName();
for (ModelGroup modelGroup : modelGroups) {
if (StringUtil.percentageOfEquality(bestName, modelGroup.getName()) > 70) {
bestName = modelGroup.getName();
break;
}
}
editor.setText(bestName);
}
private void autocomplete(boolean fulltextSearch) {
String oldtext = getOldText();
if(oldtext.isEmpty()) {
return;
}
Optional<String> match;
if (fulltextSearch) {
match = suggester.fulltext(oldtext);
} else {
match = suggester.startsWith(oldtext);
}
if (match.isPresent()) {
editor.setText(match.get());
int pos = oldtext.length();
editor.positionCaret(pos);
editor.selectRange(pos, match.get().length());
}
}
private String getOldText() {
if(editor.getSelection().getLength() > 0) {
return editor.getText().substring(0, editor.getSelection().getStart());
} else {
return editor.getText();
}
}
}
private static class ModelGroupListItem implements Comparable<ModelGroupListItem> {
private ModelGroup modelGroup;
public ModelGroupListItem(ModelGroup modelGroup) {
this.modelGroup = modelGroup;
}
@Override
public String toString() {
return this.modelGroup.getName();
}
@Override
public int hashCode() {
return java.util.Objects.hash(modelGroup);
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
ModelGroupListItem other = (ModelGroupListItem) obj;
return java.util.Objects.equals(modelGroup, other.modelGroup);
}
@Override
public int compareTo(ModelGroupListItem o) {
return this.modelGroup.getName().compareTo(o.modelGroup.getName());
}
}
}

View File

@ -0,0 +1,85 @@
package ctbrec.ui.action;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ctbrec.GlobalThreadPool;
import ctbrec.Model;
import ctbrec.recorder.Recorder;
import ctbrec.ui.controls.Dialogs;
import javafx.application.Platform;
import javafx.scene.control.Button;
public class CheckModelAccountAction {
private static final Logger LOG = LoggerFactory.getLogger(CheckModelAccountAction.class);
private Button b;
private Recorder recorder;
private String buttonText;
public CheckModelAccountAction(Button b, Recorder recorder) {
this.b = b;
this.recorder = recorder;
buttonText = b.getText();
}
public void execute(Predicate<Model> filter) {
b.setDisable(true);
Runnable checker = (() -> {
List<Model> deletedAccounts = new ArrayList<>();
try {
checkModelAccounts(filter, deletedAccounts);
} finally {
showResult(deletedAccounts);
}
});
GlobalThreadPool.submit(checker);
}
private void showResult(List<Model> deletedAccounts) {
Platform.runLater(() -> {
b.setDisable(false);
b.setText(buttonText);
if (!deletedAccounts.isEmpty()) {
var sb = new StringBuilder();
for (Model deletedModel : deletedAccounts) {
String name = deletedModel.getDisplayName() + " ".repeat(30);
name = name.substring(0, 30);
sb.append(name).append(' ').append('(').append(deletedModel.getUrl()).append(')').append('\n');
}
boolean remove = Dialogs.showConfirmDialog("Deleted Accounts", sb.toString(),
"The following accounts seem to have been deleted. Do you want to remove them?", b.getScene());
if (remove) {
new StopRecordingAction(b, deletedAccounts, recorder).execute();
}
}
});
}
private void checkModelAccounts(Predicate<Model> filter, List<Model> deletedAccounts) {
List<Model> models = recorder.getModels().stream() //
.filter(filter) //
.collect(Collectors.toList());
int total = models.size();
for (var i = 0; i < total; i++) {
final int counter = i+1;
Platform.runLater(() -> b.setText(buttonText + ' ' + counter + '/' + total));
var modelToCheck = models.get(i);
try {
if (!modelToCheck.exists()) {
deletedAccounts.add(modelToCheck);
}
} catch (IOException e) {
LOG.warn("Couldn't check, if model account still exists", e);
}
}
}
}

View File

@ -0,0 +1,179 @@
package ctbrec.ui.action;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.function.Consumer;
import ctbrec.Model;
import ctbrec.ModelGroup;
import ctbrec.recorder.Recorder;
import ctbrec.ui.controls.Dialogs;
import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import javafx.scene.Cursor;
import javafx.scene.Node;
import javafx.scene.control.Button;
import javafx.scene.control.ListView;
import javafx.scene.control.TextField;
import javafx.scene.control.Tooltip;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
public class EditGroupAction {
private static final String DIALOG_TITLE = "Edit model group";
private Node source;
private Model model;
private Recorder recorder;
public EditGroupAction(Node source, Recorder recorder, Model model) {
this.source = source;
this.recorder = recorder;
this.model = model;
}
public void execute() {
execute(m -> {});
}
public void execute(Consumer<Model> callback) {
source.setCursor(Cursor.WAIT);
try {
var dialog = new EditModelGroupDialog(model);
boolean ok = Dialogs.showCustomInput(source.getScene(), DIALOG_TITLE, dialog);
if (ok) {
var group = dialog.getModelGroup();
group.setName(dialog.getGroupName());
group.getModelUrls().clear();
group.getModelUrls().addAll(dialog.getUrls());
recorder.saveModelGroup(group);
if (dialog.getUrls().isEmpty()) {
boolean delete = Dialogs.showConfirmDialog(DIALOG_TITLE, "Do you want to delete the group?", "Group is empty", source.getScene());
if (delete) {
recorder.deleteModelGroup(group);
}
}
}
} catch (Exception e) {
Dialogs.showError(source.getScene(), DIALOG_TITLE, "Editing model group failed", e);
} finally {
Optional.ofNullable(callback).ifPresent(c -> c.accept(model));
source.setCursor(Cursor.DEFAULT);
}
}
private class EditModelGroupDialog extends GridPane {
private TextField groupName;
private ListView<String> urlListView;
private ObservableList<String> urlList;
private ModelGroup modelGroup;
private List<String> urls;
public EditModelGroupDialog(Model model) {
Optional<ModelGroup> optionalModelGroup = recorder.getModelGroup(model);
if (optionalModelGroup.isPresent()) {
modelGroup = optionalModelGroup.get();
urls = new ArrayList<>(modelGroup.getModelUrls());
createGui(modelGroup);
} else {
Dialogs.showError(getScene(), DIALOG_TITLE, "No group found for model", null);
}
}
public ModelGroup getModelGroup() {
return modelGroup;
}
public List<String> getUrls() {
return urls;
}
public String getGroupName() {
return groupName.getText();
}
void createGui(ModelGroup modelGroup) {
setHgap(5);
vgapProperty().bind(hgapProperty());
groupName = new TextField(modelGroup.getName());
var up = createUpButton();
var down = createDownButton();
var add = createAddButton();
var remove = createRemoveButton();
var buttons = new VBox(3, up, down, add, remove);
urlList = FXCollections.observableList(urls);
urlList.addListener((ListChangeListener<String>) change -> urls = new ArrayList<>(urlList));
urlListView = new ListView<>(urlList);
urlListView.setPrefWidth(600);
GridPane.setHgrow(urlListView, Priority.ALWAYS);
var row = 0;
add(groupName, 0, row++);
add(urlListView, 0, row);
add(buttons, 1, row);
urlListView.getSelectionModel().selectedIndexProperty().addListener((obs, oldV, newV) -> {
var idx = newV.intValue();
boolean noSelection = idx == -1;
up.setDisable(noSelection || idx == 0);
down.setDisable(noSelection || idx == urlList.size() - 1);
remove.setDisable(noSelection);
});
}
private Button createUpButton() {
var button = createButton("\u25B4", "Move up");
button.setOnAction(evt -> {
int idx = urlListView.getSelectionModel().getSelectedIndex();
String selectedItem = urlListView.getSelectionModel().getSelectedItem();
urlList.remove(idx);
urlList.add(idx - 1, selectedItem);
urlListView.getSelectionModel().select(idx - 1);
});
return button;
}
private Button createDownButton() {
var button = createButton("\u25BE", "Move down");
button.setOnAction(evt -> {
int idx = urlListView.getSelectionModel().getSelectedIndex();
String selectedItem = urlListView.getSelectionModel().getSelectedItem();
urlList.remove(idx);
urlList.add(idx + 1, selectedItem);
urlListView.getSelectionModel().select(idx + 1);
});
return button;
}
private Button createAddButton() {
var button = createButton("+", "Add selected URL");
button.setDisable(false);
button.setOnAction(evt -> Dialogs.showTextInput(getScene(), "Add URL", "Add new model URL", "").ifPresent(urlList::add));
return button;
}
private Button createRemoveButton() {
var button = createButton("-", "Remove selected URL");
button.setOnAction(evt -> {
String selectedItem = urlListView.getSelectionModel().getSelectedItem();
if (selectedItem != null) {
urlList.remove(selectedItem);
}
});
return button;
}
private Button createButton(String text, String tooltip) {
var b = new Button(text);
b.setTooltip(new Tooltip(tooltip));
b.setDisable(true);
b.setPrefSize(32, 32);
return b;
}
}
}

View File

@ -0,0 +1,57 @@
package ctbrec.ui.action;
import ctbrec.Model;
import ctbrec.notes.ModelNotesService;
import ctbrec.ui.CamrecApplication;
import ctbrec.ui.controls.Dialogs;
import javafx.scene.Cursor;
import javafx.scene.Node;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.Optional;
public class EditNotesAction {
private static final Logger LOG = LoggerFactory.getLogger(EditNotesAction.class);
private final Node source;
private final Model model;
private final Runnable callback;
public EditNotesAction(Node source, Model selectedModel, Runnable callback) {
this.source = source;
this.model = selectedModel;
this.callback = callback;
}
public void execute() {
source.setCursor(Cursor.WAIT);
ModelNotesService notesService = CamrecApplication.modelNotesService;
try {
String notes = notesService.loadModelNotes(model.getUrl()).orElse("");
Optional<String> newNotes = Dialogs.showTextInput(source.getScene(), "Model Notes", "Notes for " + model.getName(), notes);
newNotes.ifPresent(n -> {
try {
if (!n.trim().isEmpty()) {
notesService.writeModelNotes(model.getUrl(), n);
} else {
notesService.removeModelNotes(model.getUrl());
}
} catch (IOException e) {
LOG.warn("Couldn't save config", e);
}
});
if (callback != null) {
try {
callback.run();
} catch (Exception e) {
LOG.error("Error while executing callback", e);
}
}
} catch (Exception e) {
Dialogs.showError(source.getScene(), "Model Notes", "Could not change model notes", e);
}
source.setCursor(Cursor.DEFAULT);
}
}

View File

@ -0,0 +1,20 @@
package ctbrec.ui.action;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import ctbrec.Model;
import ctbrec.recorder.Recorder;
import ctbrec.ui.tasks.FollowTask;
import javafx.scene.Node;
public class FollowAction extends AbstractModelAction {
public FollowAction(Node source, List<? extends Model> models, Recorder recorder) {
super(source, models, recorder, new FollowTask(recorder));
}
public CompletableFuture<List<Result>> execute() {
return super.execute("Couldn't follow model", "Following of {0} failed:");
}
}

View File

@ -0,0 +1,20 @@
package ctbrec.ui.action;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import ctbrec.Model;
import ctbrec.recorder.Recorder;
import ctbrec.ui.tasks.ForcePriorityTask;
import javafx.scene.Node;
public class ForcePriorityAction extends AbstractModelAction {
public ForcePriorityAction(Node source, List<Model> models, Recorder recorder) {
super(source, models, recorder, new ForcePriorityTask(recorder));
}
public CompletableFuture<List<Result>> execute() {
return super.execute("Couldn't force ignoring priority", "Force priority of {0} failed:");
}
}

View File

@ -0,0 +1,66 @@
package ctbrec.ui.action;
import java.util.List;
import java.util.function.Consumer;
import ctbrec.Config;
import ctbrec.Model;
import ctbrec.recorder.Recorder;
import ctbrec.ui.JavaFxModel;
import ctbrec.ui.action.AbstractModelAction.Result;
import ctbrec.ui.controls.Dialogs;
import javafx.scene.Node;
public class IgnoreModelsAction {
private Node source;
private List<? extends Model> selectedModels;
private Recorder recorder;
private boolean withRemoveDialog;
public IgnoreModelsAction(Node source, List<? extends Model> selectedModels, Recorder recorder, boolean withRemoveDialog) {
this.source = source;
this.selectedModels = selectedModels;
this.recorder = recorder;
this.withRemoveDialog = withRemoveDialog;
}
public void execute() {
execute(model -> {});
}
public void execute(Consumer<Model> callback) {
var settings = Config.getInstance().getSettings();
var confirmed = true;
if (settings.confirmationForDangerousActions) {
int n = selectedModels.size();
String plural = n > 1 ? "s" : "";
String header = "This will add " + n + " model" + plural + " to the ignore list";
confirmed = Dialogs.showConfirmDialog("Ignore Models", "Continue?", header, source.getScene());
}
if (confirmed) {
for (Model model : selectedModels) {
var modelToIgnore = unwrap(model);
settings.ignoredModels.add(modelToIgnore.getUrl());
}
if (withRemoveDialog) {
boolean removeAsWell = Dialogs.showConfirmDialog("Ignore Model", null, "Remove as well?", source.getScene());
if (removeAsWell) {
new StopRecordingAction(source, selectedModels, recorder).execute()
.whenComplete((r, ex) -> r.stream().map(Result::getModel).forEach(callback::accept));
}
} else {
for (Model model : selectedModels) {
callback.accept(model);
}
}
}
}
private Model unwrap(Model model) {
if (model instanceof JavaFxModel) {
return ((JavaFxModel) model).getDelegate();
} else {
return model;
}
}
}

View File

@ -0,0 +1,51 @@
package ctbrec.ui.action;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import ctbrec.Model;
import ctbrec.ModelGroup;
import ctbrec.recorder.Recorder;
import ctbrec.ui.controls.Dialogs;
import javafx.application.Platform;
import javafx.scene.Node;
public class LaterGroupAction extends ModelMassEditAction {
private Recorder recorder;
private Model model;
public LaterGroupAction(Node source, Recorder recorder, Model model) {
super.source = source;
this.recorder = recorder;
this.model = model;
action = m -> {
try {
if (recorder.isMarkedForLaterRecording(m) == false) {
recorder.markForLaterRecording(m, true);
}
} catch (InvalidKeyException | NoSuchAlgorithmException | IOException e) {
Platform.runLater(() -> Dialogs.showError(source.getScene(), "Couldn't change model state", "Mark for later recording of " + m.getName() + " failed", e));
}
};
}
@Override
protected List<Model> getModels() {
Optional<ModelGroup> optionalGroup = recorder.getModelGroup(model);
if (optionalGroup.isPresent()) {
ModelGroup group = optionalGroup.get();
return recorder.getModels().stream() //
.filter(m -> group.getModelUrls().contains(m.getUrl())) //
.collect(Collectors.toList());
} else {
return Collections.emptyList();
}
}
}

View File

@ -0,0 +1,24 @@
package ctbrec.ui.action;
import java.util.List;
import ctbrec.Model;
import ctbrec.recorder.Recorder;
import ctbrec.ui.controls.Dialogs;
import javafx.application.Platform;
import javafx.scene.Node;
public class MarkForLaterRecordingAction extends ModelMassEditAction {
public MarkForLaterRecordingAction(Node source, List<? extends Model> models, boolean recordLater, Recorder recorder) {
super(source, models);
action = m -> {
try {
recorder.markForLaterRecording(m, recordLater);
} catch (Exception e) {
Platform.runLater(() -> Dialogs.showError(source.getScene(), "Couldn't model mark model for later recording",
"Marking for later recording of " + m.getName() + " failed", e));
}
};
}
}

View File

@ -0,0 +1,81 @@
package ctbrec.ui.action;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.function.Consumer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ctbrec.GlobalThreadPool;
import ctbrec.Model;
import ctbrec.ui.controls.Dialogs;
import javafx.application.Platform;
import javafx.scene.Cursor;
import javafx.scene.Node;
public class ModelMassEditAction {
private static final Logger LOG = LoggerFactory.getLogger(ModelMassEditAction.class);
protected List<? extends Model> models;
protected Consumer<Model> action;
protected Node source;
protected ModelMassEditAction() {
}
protected ModelMassEditAction(Node source, List<? extends Model> models) {
this.source = source;
this.models = models;
}
public ModelMassEditAction(Node source, List<? extends Model> models, Consumer<Model> action) {
this.source = source;
this.models = models;
this.action = action;
}
public void execute() {
execute(m -> {});
}
public void executeSync(Consumer<Model> callback) {
Platform.runLater(() -> source.setCursor(Cursor.WAIT));
Consumer<Model> cb = Objects.requireNonNull(callback, "Callback is null, call execute() instead");
List<Future<?>> futures = new LinkedList<>();
for (Model model : getModels()) {
futures.add(GlobalThreadPool.submit(() -> {
action.accept(model);
cb.accept(model);
}));
}
Exception ex = null;
for (Future<?> future : futures) {
try {
future.get();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} catch (ExecutionException e) {
ex = e;
}
}
if (ex != null) {
LOG.error("Error while executing model mass edit", ex);
Dialogs.showError(source.getScene(), "Error", "Error while execution action", ex);
}
Platform.runLater(() -> source.setCursor(Cursor.DEFAULT));
}
public void execute(Consumer<Model> callback) {
GlobalThreadPool.submit(() -> executeSync(callback));
}
@SuppressWarnings("unchecked")
protected List<Model> getModels() {
return (List<Model>) models;
}
}

View File

@ -0,0 +1,50 @@
package ctbrec.ui.action;
import ctbrec.Config;
import ctbrec.GlobalThreadPool;
import ctbrec.Model;
import ctbrec.ui.DesktopIntegration;
import ctbrec.ui.controls.Dialogs;
import javafx.scene.Cursor;
import javafx.scene.Node;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import java.io.File;
import java.time.Instant;
@Slf4j
@RequiredArgsConstructor
public class OpenRecordingsDir {
private final Node source;
private final Model selectedModel;
public void execute() {
source.setCursor(Cursor.WAIT);
var dir = Config.getInstance().getFileForRecording(selectedModel, ".mp4", Instant.now());
dir = findDeepestExistingDir(dir);
log.info("Directory for model is {}", dir.getAbsolutePath());
if (dir.exists()) {
final File directory = dir;
GlobalThreadPool.submit(() -> DesktopIntegration.open(directory));
} else {
Dialogs.showError(source.getScene(), "Directory does not exist", "There are no recordings for this model", null);
}
source.setCursor(Cursor.DEFAULT);
}
private File findDeepestExistingDir(File dir) {
while (!dir.exists()) {
if (dir.getParentFile() == null) {
return dir;
} else {
dir = dir.getParentFile();
if (dir.exists()) {
break;
}
}
}
return dir;
}
}

View File

@ -0,0 +1,15 @@
package ctbrec.ui.action;
import java.util.List;
import ctbrec.Model;
import ctbrec.ui.DesktopIntegration;
import javafx.scene.Node;
public class OpenUrlAction extends ModelMassEditAction {
public OpenUrlAction(Node source, List<? extends Model> models) {
super(source, models);
action = m -> DesktopIntegration.open(m.getUrl());
}
}

View File

@ -0,0 +1,20 @@
package ctbrec.ui.action;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import ctbrec.Model;
import ctbrec.recorder.Recorder;
import ctbrec.ui.tasks.PauseRecordingTask;
import javafx.scene.Node;
public class PauseAction extends AbstractModelAction {
public PauseAction(Node source, List<Model> models, Recorder recorder) {
super(source, models, recorder, new PauseRecordingTask(recorder));
}
public CompletableFuture<List<Result>> execute() {
return super.execute("Couldn't pause recording", "Pausing recording of {0} failed:");
}
}

View File

@ -0,0 +1,49 @@
package ctbrec.ui.action;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import ctbrec.Model;
import ctbrec.ModelGroup;
import ctbrec.recorder.Recorder;
import ctbrec.ui.controls.Dialogs;
import javafx.application.Platform;
import javafx.scene.Node;
public class PauseGroupAction extends ModelMassEditAction {
private Recorder recorder;
private Model model;
public PauseGroupAction(Node source, Recorder recorder, Model model) {
super.source = source;
this.recorder = recorder;
this.model = model;
action = m -> {
try {
recorder.suspendRecording(m);
} catch (InvalidKeyException | NoSuchAlgorithmException | IOException e) {
Platform.runLater(() -> Dialogs.showError(source.getScene(), "Couldn't pause model", "Pausing recording of " + m.getName() + " failed", e));
}
};
}
@Override
protected List<Model> getModels() {
Optional<ModelGroup> optionalGroup = recorder.getModelGroup(model);
if (optionalGroup.isPresent()) {
ModelGroup group = optionalGroup.get();
return recorder.getModels().stream() //
.filter(m -> group.getModelUrls().contains(m.getUrl())) //
.collect(Collectors.toList());
} else {
return Collections.emptyList();
}
}
}

View File

@ -0,0 +1,37 @@
package ctbrec.ui.action;
import ctbrec.Config;
import ctbrec.Model;
import ctbrec.ui.SiteUiFactory;
import ctbrec.ui.controls.Toast;
import javafx.application.Platform;
import javafx.scene.Cursor;
import javafx.scene.Node;
public class PlayAction {
private Model selectedModel;
private Node source;
public PlayAction(Node source, Model selectedModel) {
this.source = source;
this.selectedModel = selectedModel;
}
public void execute() {
source.setCursor(Cursor.WAIT);
var t = new Thread(() -> {
var siteUI = SiteUiFactory.getUi(selectedModel.getSite());
boolean started = siteUI.play(selectedModel);
Platform.runLater(() -> {
if (started && Config.getInstance().getSettings().showPlayerStarting) {
Toast.makeText(source.getScene(), "Starting Player", 2000, 500, 500);
}
source.setCursor(Cursor.DEFAULT);
});
});
t.setName("Player " + selectedModel);
t.setDaemon(true);
t.start();
}
}

View File

@ -0,0 +1,42 @@
package ctbrec.ui.action;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.time.Instant;
import java.util.concurrent.CompletableFuture;
import ctbrec.GlobalThreadPool;
import ctbrec.Model;
import ctbrec.recorder.Recorder;
import ctbrec.ui.controls.Dialogs;
import javafx.scene.Cursor;
import javafx.scene.Node;
public class RemoveTimeLimitAction {
private Model selectedModel;
private Node source;
private Recorder recorder;
public RemoveTimeLimitAction(Node source, Model selectedModel, Recorder recorder) {
this.source = source;
this.selectedModel = selectedModel;
this.recorder = recorder;
}
public CompletableFuture<Boolean> execute() {
source.setCursor(Cursor.WAIT);
var unlimited = Instant.ofEpochMilli(Model.RECORD_INDEFINITELY);
return CompletableFuture.supplyAsync(() -> {
try {
selectedModel.setRecordUntil(unlimited);
recorder.stopRecordingAt(selectedModel);
return true;
} catch (InvalidKeyException | NoSuchAlgorithmException | IOException e) {
Dialogs.showError(source.getScene(), "Error", "Couln't remove stop date", e);
return false;
}
}, GlobalThreadPool.get()).whenComplete((r,e) -> source.setCursor(Cursor.DEFAULT));
}
}

View File

@ -0,0 +1,20 @@
package ctbrec.ui.action;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import ctbrec.Model;
import ctbrec.recorder.Recorder;
import ctbrec.ui.tasks.ResumeRecordingTask;
import javafx.scene.Node;
public class ResumeAction extends AbstractModelAction {
public ResumeAction(Node source, List<Model> models, Recorder recorder) {
super(source, models, recorder, new ResumeRecordingTask(recorder));
}
public CompletableFuture<List<Result>> execute() {
return super.execute("Couldn't resume recording", "Resuming recording of {0} failed:");
}
}

View File

@ -0,0 +1,49 @@
package ctbrec.ui.action;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import ctbrec.Model;
import ctbrec.ModelGroup;
import ctbrec.recorder.Recorder;
import ctbrec.ui.controls.Dialogs;
import javafx.application.Platform;
import javafx.scene.Node;
public class ResumeGroupAction extends ModelMassEditAction {
private Recorder recorder;
private Model model;
public ResumeGroupAction(Node source, Recorder recorder, Model model) {
super.source = source;
this.recorder = recorder;
this.model = model;
action = m -> {
try {
recorder.resumeRecording(m);
} catch (InvalidKeyException | NoSuchAlgorithmException | IOException e) {
Platform.runLater(() -> Dialogs.showError(source.getScene(), "Couldn't resume model", "Resuming recording of " + m.getName() + " failed", e));
}
};
}
@Override
protected List<Model> getModels() {
Optional<ModelGroup> optionalGroup = recorder.getModelGroup(model);
if (optionalGroup.isPresent()) {
ModelGroup group = optionalGroup.get();
return recorder.getModels().stream() //
.filter(m -> group.getModelUrls().contains(m.getUrl())) //
.collect(Collectors.toList());
} else {
return Collections.emptyList();
}
}
}

View File

@ -0,0 +1,20 @@
package ctbrec.ui.action;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import ctbrec.Model;
import ctbrec.recorder.Recorder;
import ctbrec.ui.tasks.ResumePriorityTask;
import javafx.scene.Node;
public class ResumePriorityAction extends AbstractModelAction {
public ResumePriorityAction(Node source, List<Model> models, Recorder recorder) {
super(source, models, recorder, new ResumePriorityTask(recorder));
}
public CompletableFuture<List<Result>> execute() {
return super.execute("Couldn't resume respecting priority", "Resuming priority of {0} failed:");
}
}

View File

@ -0,0 +1,104 @@
package ctbrec.ui.action;
import ctbrec.Model;
import ctbrec.StringUtil;
import ctbrec.ui.CamrecApplication;
import ctbrec.ui.controls.Dialogs;
import ctbrec.ui.controls.FileSelectionBox;
import javafx.geometry.Insets;
import javafx.scene.Cursor;
import javafx.scene.Node;
import javafx.scene.control.Label;
import javafx.scene.layout.GridPane;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.function.Consumer;
public class SetPortraitAction extends AbstractPortraitAction {
private static final Logger LOG = LoggerFactory.getLogger(SetPortraitAction.class);
private final Consumer<Model> callback;
public SetPortraitAction(Node source, Model selectedModel, Consumer<Model> callback) {
this.source = source;
this.model = selectedModel;
this.callback = callback;
}
public void execute() {
source.setCursor(Cursor.WAIT);
GridPane pane = new GridPane();
Label l = new Label("Select a portrait image. Leave empty to remove a portrait again.");
pane.add(l, 0, 0);
FileSelectionBox portraitSelectionBox = new FileSelectionBox();
pane.add(portraitSelectionBox, 0, 1);
GridPane.setMargin(l, new Insets(5));
GridPane.setMargin(portraitSelectionBox, new Insets(5));
boolean accepted = Dialogs.showCustomInput(source.getScene(), "Select a portrait image", pane);
if (!accepted) {
source.setCursor(Cursor.DEFAULT);
return;
}
String selectedFile = portraitSelectionBox.fileProperty().getValue();
if (StringUtil.isBlank(selectedFile)) {
removePortrait(model.getUrl());
} else {
LOG.debug("User selected {}", selectedFile);
boolean success = processImageFile(selectedFile);
if (success) {
try {
firePortraitChanged();
runCallback();
} catch (Exception e) {
Dialogs.showError("Set Portrait", "Couldn't change portrait image: ", e);
}
}
}
source.setCursor(Cursor.DEFAULT);
}
private void removePortrait(String modelUrl) {
try {
CamrecApplication.portraitStore.removePortrait(modelUrl);
firePortraitChanged();
runCallback();
} catch (IOException e) {
Dialogs.showError("Remove Portrait", "Couldn't remove portrait image: ", e);
}
}
private void runCallback() {
if (callback != null) {
try {
callback.accept(model);
} catch (Exception e) {
LOG.error("Error while executing callback", e);
}
}
}
private boolean processImageFile(String selectedFile) {
try {
BufferedImage original = ImageIO.read(new File(selectedFile));
BufferedImage croppedImage = cropImage(original);
BufferedImage portrait = convertToScaledJpg(croppedImage);
boolean success = store(model.getUrl(), portrait);
if (!success) {
LOG.debug("Available formats: {}", Arrays.toString(ImageIO.getWriterFormatNames()));
throw new IOException("No suitable writer found for image format " + FORMAT);
}
return success;
} catch (IOException e) {
LOG.error("Error while changing portrait image", e);
Dialogs.showError("Set Portrait", "Couldn't change portrait image: ", e);
return false;
}
}
}

View File

@ -0,0 +1,83 @@
package ctbrec.ui.action;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.CompletableFuture;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ctbrec.GlobalThreadPool;
import ctbrec.Model;
import ctbrec.recorder.Recorder;
import ctbrec.ui.RecordUntilDialog;
import ctbrec.ui.controls.Dialogs;
import ctbrec.ui.tasks.StartRecordingTask;
import javafx.application.Platform;
import javafx.scene.Cursor;
import javafx.scene.Node;
public class SetStopDateAction {
private static final Logger LOG = LoggerFactory.getLogger(SetStopDateAction.class);
private Node source;
private Model model;
private Recorder recorder;
public SetStopDateAction(Node source, Model model, Recorder recorder) {
this.source = source;
this.model = model;
this.recorder = recorder;
}
public CompletableFuture<Boolean> execute() {
source.setCursor(Cursor.WAIT);
RecordUntilDialog dialog = new RecordUntilDialog(source, model);
boolean userClickedOk = dialog.showAndWait();
return createAsyncTask(userClickedOk);
}
private CompletableFuture<Boolean> createAsyncTask(boolean userClickedOk) {
return CompletableFuture.supplyAsync(() -> {
if (userClickedOk) {
setRecordingTimeLimit();
}
return true;
}, GlobalThreadPool.get()).whenComplete((r, e) -> {
Platform.runLater(() -> source.setCursor(Cursor.DEFAULT));
if (e != null) {
LOG.error("Error", e);
}
});
}
private void setRecordingTimeLimit() {
try {
if (!recorder.isTracked(model) || model.isMarkedForLaterRecording()) {
new StartRecordingTask(recorder).executeSync(model)
.thenAccept(m -> {
try {
recorder.stopRecordingAt(m);
} catch (InvalidKeyException | NoSuchAlgorithmException | IOException e1) {
showError(e1);
}
}).exceptionally(ex -> {
showError(ex);
return null;
});
} else {
recorder.stopRecordingAt(model);
}
} catch (InvalidKeyException | NoSuchAlgorithmException | IOException e) {
showError(e);
}
}
private void showError(Throwable t) {
Platform.runLater(() -> Dialogs.showError(source.getScene(), "Error", "Couln't set stop date", t));
}
}

View File

@ -0,0 +1,49 @@
package ctbrec.ui.action;
import ctbrec.GlobalThreadPool;
import ctbrec.Model;
import ctbrec.ui.controls.Dialogs;
import javafx.application.Platform;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.Cursor;
import javafx.scene.Node;
import javafx.scene.image.Image;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.awt.image.BufferedImage;
public class SetThumbAsPortraitAction extends AbstractPortraitAction {
private static final Logger LOG = LoggerFactory.getLogger(SetThumbAsPortraitAction.class);
private final Image image;
public SetThumbAsPortraitAction(Node source, Model model, Image image) {
this.source = source;
this.model = model;
this.image = image;
}
public void execute() {
source.setCursor(Cursor.WAIT);
GlobalThreadPool.submit(() -> {
try {
BufferedImage bufferedImage = convertFxImageToAwt(image);
BufferedImage croppedImage = cropImage(bufferedImage);
BufferedImage portrait = convertToScaledJpg(croppedImage);
store(model.getUrl(), portrait);
firePortraitChanged();
} catch (Exception e) {
LOG.error("Error while changing portrait image", e);
Platform.runLater(() -> Dialogs.showError("Set Portrait", "Couldn't change portrait image: ", e));
} finally {
Platform.runLater(() -> source.setCursor(Cursor.DEFAULT));
}
});
}
private BufferedImage convertFxImageToAwt(Image img) {
return SwingFXUtils.fromFXImage(img, null);
}
}

View File

@ -0,0 +1,81 @@
package ctbrec.ui.action;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import ctbrec.Config;
import ctbrec.Model;
import ctbrec.recorder.Recorder;
import ctbrec.recorder.download.StreamSource;
import ctbrec.ui.RecordUntilDialog;
import ctbrec.ui.StreamSourceSelectionDialog;
import ctbrec.ui.tasks.StartRecordingTask;
import javafx.application.Platform;
import javafx.scene.Cursor;
import javafx.scene.Node;
public class StartRecordingAction extends AbstractModelAction {
private static final String ERROR_HEADER = "Couldn't start recording";
private static final String ERROR_MSG = "Starting recording of {0} failed:";
private boolean showRecordUntilDialog = false;
public StartRecordingAction(Node source, List<Model> models, Recorder recorder) {
super(source, models, recorder, new StartRecordingTask(recorder));
}
public StartRecordingAction showRecordUntilDialog() {
showRecordUntilDialog = true;
return this;
}
public CompletableFuture<List<Result>> execute() {
boolean selectSource = Config.getInstance().getSettings().chooseStreamQuality;
if (selectSource || showRecordUntilDialog) {
var future = executeSync();
Platform.runLater(() -> source.setCursor(Cursor.DEFAULT));
return future;
} else {
return super.execute(ERROR_HEADER, ERROR_MSG);
}
}
private CompletableFuture<List<Result>> executeSync() {
var result = new ArrayList<Result>(models.size());
for (final Model model : models) {
if (showRecordUntilDialog) {
RecordUntilDialog dialog = new RecordUntilDialog(source, model);
var confirmed = dialog.showAndWait();
if (!confirmed) {
continue;
}
}
boolean selectSource = Config.getInstance().getSettings().chooseStreamQuality;
if (selectSource) {
var dialog = new StreamSourceSelectionDialog(source.getScene(), model);
Optional<StreamSource> selection = dialog.showAndWait();
if (selection.isPresent()) {
StreamSource src = selection.get();
if (src != StreamSourceSelectionDialog.LOADING) {
int index = dialog.indexOf(src);
model.setStreamUrlIndex(index);
}
} else {
continue;
}
}
if (showRecordUntilDialog) {
model.setSuspended(false);
}
new StartRecordingTask(recorder).executeSync(model)
.whenComplete((mdl, ex) -> result.add(new Result(mdl, ex)));
}
checkResultForErrors(ERROR_HEADER, ERROR_MSG, result);
return CompletableFuture.completedFuture(result);
}
}

View File

@ -0,0 +1,49 @@
package ctbrec.ui.action;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import ctbrec.Model;
import ctbrec.ModelGroup;
import ctbrec.recorder.Recorder;
import ctbrec.ui.controls.Dialogs;
import javafx.application.Platform;
import javafx.scene.Node;
public class StopGroupAction extends ModelMassEditAction {
private Recorder recorder;
private Model model;
public StopGroupAction(Node source, Recorder recorder, Model model) {
super.source = source;
this.recorder = recorder;
this.model = model;
action = m -> {
try {
recorder.stopRecording(m);
} catch (InvalidKeyException | NoSuchAlgorithmException | IOException e) {
Platform.runLater(() -> Dialogs.showError(source.getScene(), "Couldn't stop model", "Stopping recording of " + m.getName() + " failed", e));
}
};
}
@Override
protected List<Model> getModels() {
Optional<ModelGroup> optionalGroup = recorder.getModelGroup(model);
if (optionalGroup.isPresent()) {
ModelGroup group = optionalGroup.get();
return recorder.getModels().stream() //
.filter(m -> group.getModelUrls().contains(m.getUrl())) //
.collect(Collectors.toList());
} else {
return Collections.emptyList();
}
}
}

View File

@ -0,0 +1,20 @@
package ctbrec.ui.action;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import ctbrec.Model;
import ctbrec.recorder.Recorder;
import ctbrec.ui.tasks.StopRecordingTask;
import javafx.scene.Node;
public class StopRecordingAction extends AbstractModelAction {
public StopRecordingAction(Node source, List<? extends Model> models, Recorder recorder) {
super(source, models, recorder, new StopRecordingTask(recorder));
}
public CompletableFuture<List<Result>> execute() {
return super.execute("Couldn't stop recording", "Stopping recording of {0} failed:");
}
}

View File

@ -0,0 +1,83 @@
package ctbrec.ui.action;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import org.eclipse.jetty.io.RuntimeIOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ctbrec.GlobalThreadPool;
import ctbrec.Model;
import ctbrec.recorder.Recorder;
import ctbrec.recorder.download.StreamSource;
import ctbrec.sites.ModelOfflineException;
import ctbrec.ui.StreamSourceSelectionDialog;
import ctbrec.ui.controls.Dialogs;
import javafx.application.Platform;
import javafx.scene.Cursor;
import javafx.scene.Node;
public class SwitchStreamResolutionAction {
private static final Logger LOG = LoggerFactory.getLogger(SwitchStreamResolutionAction.class);
private Node source;
private Model selectedModel;
private Recorder recorder;
public SwitchStreamResolutionAction(Node source, Model selectedModel, Recorder recorder) {
this.source = source;
this.selectedModel = selectedModel;
this.recorder = recorder;
}
public CompletableFuture<Void> execute() {
source.setCursor(Cursor.WAIT);
var couldntSwitchHeaderText = "Couldn't switch stream resolution";
return CompletableFuture.supplyAsync(() -> {
checkOnlineState();
return selectedModel;
}, GlobalThreadPool.get())
.thenAccept(m -> Platform.runLater(() -> {
StreamSourceSelectionDialog dialog = new StreamSourceSelectionDialog(source.getScene(), selectedModel);
Optional<StreamSource> selectedSource = dialog.showAndWait();
if (selectedSource.isPresent()) {
StreamSource src = selectedSource.get();
if (src != StreamSourceSelectionDialog.LOADING) {
int index = dialog.indexOf(selectedSource.get());
selectedModel.setStreamUrlIndex(index);
try {
recorder.switchStreamSource(selectedModel);
} catch (InvalidKeyException | NoSuchAlgorithmException | IllegalStateException | IOException e) {
LOG.error(couldntSwitchHeaderText, e);
Dialogs.showError(source.getScene(), "Couldn't switch stream resolution", "Error while switching stream resolution", e);
}
}
}
source.setCursor(Cursor.DEFAULT);
}))
.exceptionally(ex -> {
Dialogs.showError(source.getScene(), couldntSwitchHeaderText, "The resolution can only be changed when the model is online", null);
Platform.runLater(() -> source.setCursor(Cursor.DEFAULT));
return null;
});
}
private void checkOnlineState() {
try {
if (!selectedModel.isOnline(true)) {
throw new ModelOfflineException(selectedModel);
}
} catch (IOException | ExecutionException e) {
throw new RuntimeIOException(e);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e); // NOSONAR
}
}
}

View File

@ -0,0 +1,60 @@
package ctbrec.ui.action;
import static ctbrec.ui.controls.Dialogs.*;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ctbrec.Model;
import ctbrec.event.EventBusHolder;
import ctbrec.ui.SiteUiFactory;
import ctbrec.ui.TipDialog;
import javafx.scene.Cursor;
import javafx.scene.Node;
public class TipAction {
private static final Logger LOG = LoggerFactory.getLogger(TipAction.class);
private Model model;
private Node source;
public TipAction(Model model, Node source) {
this.model = model;
this.source = source;
}
public void execute() {
source.setCursor(Cursor.WAIT);
try {
var site = model.getSite();
var tipDialog = new TipDialog(source.getScene(), site);
tipDialog.showAndWait();
String tipText = tipDialog.getResult();
if (tipText != null) {
var df = new DecimalFormat("0.##");
try {
Number tokens = df.parse(tipText);
SiteUiFactory.getUi(site).login();
model.receiveTip(tokens.doubleValue());
Map<String, Object> event = new HashMap<>();
event.put("event", "tokens.sent");
event.put("amount", tokens.doubleValue());
EventBusHolder.BUS.post(event);
} catch (IOException ex) {
LOG.error("An error occurred while sending tip", ex);
showError(source.getScene(), "Couldn't send tip", "An error occurred while sending tip:", ex);
} catch (Exception ex) {
showError(source.getScene(), "Couldn't send tip", "You entered an invalid amount of tokens", ex);
}
}
} finally {
source.setCursor(Cursor.DEFAULT);
}
}
}

View File

@ -0,0 +1,41 @@
package ctbrec.ui.action;
import ctbrec.GlobalThreadPool;
import ctbrec.recorder.Recorder;
import ctbrec.ui.controls.Dialogs;
import javafx.application.Platform;
import javafx.scene.Cursor;
import javafx.scene.control.ToggleButton;
public class ToggleRecordingAction {
private ToggleButton toggleButton;
private Recorder recorder;
private boolean pause;
public ToggleRecordingAction(ToggleButton toggleButton, Recorder recorder) {
this.toggleButton = toggleButton;
this.recorder = recorder;
pause = toggleButton.isSelected();
}
public void execute() {
toggleButton.setCursor(Cursor.WAIT);
GlobalThreadPool.submit(() -> {
try {
if (pause) {
recorder.pause();
Platform.runLater(() -> toggleButton.setText("Resume Recorder"));
} else {
recorder.resume();
Platform.runLater(() -> toggleButton.setText("Pause Recorder"));
}
} catch (Exception e) {
Dialogs.showError(toggleButton.getScene(), "Toggle Recorder", "An error ocurred while toggling the recorder", e);
Platform.runLater(() -> toggleButton.setSelected(!toggleButton.isSelected()));
} finally {
Platform.runLater(() -> toggleButton.setCursor(Cursor.DEFAULT));
}
});
}
}

View File

@ -0,0 +1,7 @@
package ctbrec.ui.action;
@FunctionalInterface
public interface TriConsumer<T, U, V> {
void accept(T t, U u, V v);
}

View File

@ -0,0 +1,20 @@
package ctbrec.ui.action;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import ctbrec.Model;
import ctbrec.recorder.Recorder;
import ctbrec.ui.tasks.UnfollowTask;
import javafx.scene.Node;
public class UnfollowAction extends AbstractModelAction {
public UnfollowAction(Node source, List<? extends Model> models, Recorder recorder) {
super(source, models, recorder, new UnfollowTask(recorder));
}
public CompletableFuture<List<Result>> execute() {
return super.execute("Couldn't unfollow model", "Unfollowing of {0} failed:");
}
}

View File

@ -0,0 +1,167 @@
package ctbrec.ui.controls;
import java.io.File;
import java.io.IOException;
import java.util.Objects;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ctbrec.StringUtil;
import ctbrec.ui.AutosizeAlert;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.beans.value.ChangeListener;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.control.Tooltip;
import javafx.scene.layout.Border;
import javafx.scene.layout.BorderStroke;
import javafx.scene.layout.BorderStrokeStyle;
import javafx.scene.layout.BorderWidths;
import javafx.scene.layout.CornerRadii;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.paint.Color;
import javafx.stage.FileChooser;
public abstract class AbstractFileSelectionBox extends HBox {
private static final Logger LOG = LoggerFactory.getLogger(AbstractFileSelectionBox.class);
private final StringProperty fileProperty = new SimpleStringProperty();
private final Tooltip validationError = new Tooltip();
protected TextField fileInput;
protected boolean allowEmptyValue = false;
protected boolean saveDialog = false;
protected boolean validationDisabled = false;
protected AbstractFileSelectionBox() {
super(5);
fileInput = new TextField();
fileInput.textProperty().addListener(textListener());
fileInput.focusedProperty().addListener((obs, o, n) -> {
if (Objects.equals(Boolean.FALSE, n)) {
validationError.hide();
}
});
var browse = createBrowseButton();
browse.disableProperty().bind(disableProperty());
browse.prefHeightProperty().bind(fileInput.prefWidthProperty());
fileInput.disableProperty().bind(disableProperty());
fileInput.textProperty().bindBidirectional(fileProperty);
getChildren().addAll(fileInput, browse);
HBox.setHgrow(fileInput, Priority.ALWAYS);
disabledProperty().addListener((obs, oldV, newV) -> {
if (Objects.equals(Boolean.TRUE, newV)) {
hideValidationHints();
} else {
if (StringUtil.isNotBlank(fileInput.getText())) {
setFile(new File(fileInput.getText()));
}
}
});
}
protected AbstractFileSelectionBox(String initialValue) {
this();
fileInput.setText(initialValue);
}
protected ChangeListener<String> textListener() {
return (obs, o, n) -> {
var input = fileInput.getText();
if (StringUtil.isBlank(input)) {
if (allowEmptyValue) {
fileProperty.set("");
hideValidationHints();
}
} else {
var program = new File(input);
setFile(program);
}
};
}
protected void setFile(File file) {
var msg = validate(file);
if (msg != null) {
fileInput.setBorder(new Border(new BorderStroke(Color.RED, BorderStrokeStyle.DASHED, new CornerRadii(2), new BorderWidths(2))));
validationError.setText(msg);
fileInput.setTooltip(validationError);
var p = fileInput.localToScreen(fileInput.getTranslateY(), fileInput.getTranslateY());
if (!validationError.isShowing() && getScene() != null) {
validationError.show(getScene().getWindow(), p.getX(), p.getY() + fileInput.getHeight() + 4);
}
} else {
fileProperty.set(file.getAbsolutePath());
hideValidationHints();
}
}
private void hideValidationHints() {
fileInput.setBorder(Border.EMPTY);
fileInput.setTooltip(null);
validationError.hide();
}
protected String validate(File file) {
if (isDisabled() || validationDisabled) {
return null;
}
if (file == null || !file.exists()) {
return "File does not exist";
} else {
return null;
}
}
public void allowEmptyValue() {
this.allowEmptyValue = true;
}
public void useSaveDialog() {
this.saveDialog = true;
}
public void disableValidation() {
validationDisabled = true;
}
private Button createBrowseButton() {
var button = new Button("Select");
button.setOnAction(e -> choose());
button.prefHeightProperty().bind(this.heightProperty());
button.prefWidthProperty().set(70);
return button;
}
protected void choose() {
var chooser = new FileChooser();
File program;
if (saveDialog) {
program = chooser.showSaveDialog(null);
} else {
program = chooser.showOpenDialog(null);
}
if (program != null) {
try {
fileInput.setText(program.getCanonicalPath());
} catch (IOException e1) {
LOG.error("Couldn't determine path", e1);
var alert = new AutosizeAlert(Alert.AlertType.ERROR, getScene());
alert.setTitle("Whoopsie");
alert.setContentText("Couldn't determine path");
alert.showAndWait();
}
setFile(program);
}
}
public StringProperty fileProperty() {
return fileProperty;
}
}

View File

@ -0,0 +1,17 @@
package ctbrec.ui.controls;
import ctbrec.ui.UiUtils;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.MenuItem;
public class CustomMouseBehaviorContextMenu extends ContextMenu {
public CustomMouseBehaviorContextMenu(MenuItem...items) {
super(items);
UiUtils.disableRightClickFor(this);
UiUtils.ignoreMouseReleasedIfMouseExited(this);
setAutoHide(true);
setHideOnEscape(true);
setAutoFix(true);
}
}

View File

@ -0,0 +1,35 @@
package ctbrec.ui.controls;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.util.Callback;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
public class DateTimeCellFactory<T> implements Callback<TableColumn<T, Instant>, TableCell<T, Instant>> {
private final DateTimeFormatter formatter;
public DateTimeCellFactory (DateTimeFormatter formatter) {
this.formatter = formatter;
}
@Override
public TableCell<T, Instant> call(TableColumn<T, Instant> param) {
return new TableCell<T, Instant>() {
@Override
protected void updateItem(Instant item, boolean empty) {
if (empty || item == null) {
setText("");
} else {
var dateTime = LocalDateTime.ofInstant(item, ZoneId.systemDefault());
String formattedDateTime = formatter.format(dateTime);
setText(item.equals(Instant.EPOCH) ? "" : formattedDateTime);
}
}
};
}
}

View File

@ -0,0 +1,115 @@
package ctbrec.ui.controls;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.scene.control.DatePicker;
import javafx.util.StringConverter;
/**
* A DateTimePicker with configurable datetime format where both date and time can be changed
* via the text field and the date can additionally be changed via the JavaFX default date picker.
*
* @author Edvin Syse
* @author Rene Fischer
*
* copyright TornadoFX
* license Apache 2.0
*
*/
public class DateTimePicker extends DatePicker {
private static final Logger LOG = LoggerFactory.getLogger(DateTimePicker.class);
public static final String DefaultFormat = "yyyy-MM-dd HH:mm";
private DateTimeFormatter formatter;
private ObjectProperty<LocalDateTime> dateTimeValue = new SimpleObjectProperty<>(LocalDateTime.now());
private ObjectProperty<String> format = new SimpleObjectProperty<String>() {
@Override
public void set(String newValue) {
super.set(newValue);
formatter = DateTimeFormatter.ofPattern(newValue);
}
};
public DateTimePicker() {
getStyleClass().add("datetime-picker");
setFormat(DefaultFormat);
setConverter(new InternalConverter());
// Syncronize changes to the underlying date value back to the dateTimeValue
valueProperty().addListener((observable, oldValue, newValue) -> {
if (newValue == null) {
dateTimeValue.set(null);
} else {
if (dateTimeValue.get() == null) {
dateTimeValue.set(LocalDateTime.of(newValue, LocalTime.now()));
} else {
var time = dateTimeValue.get().toLocalTime();
dateTimeValue.set(LocalDateTime.of(newValue, time));
}
}
LOG.debug("{} {}", newValue, dateTimeValue);
});
editorProperty().get().textProperty().addListener((obs, ov, nv) -> {
try {
getConverter().fromString(nv);
} catch (Exception e) {
}
});
// Syncronize changes to dateTimeValue back to the underlying date value
dateTimeValue.addListener((observable, oldValue, newValue) -> setValue(newValue == null ? null : newValue.toLocalDate()));
}
public LocalDateTime getDateTimeValue() {
return dateTimeValue.get();
}
public void setDateTimeValue(LocalDateTime dateTimeValue) {
this.dateTimeValue.set(dateTimeValue);
}
public ObjectProperty<LocalDateTime> dateTimeValueProperty() {
return dateTimeValue;
}
public String getFormat() {
return format.get();
}
public ObjectProperty<String> formatProperty() {
return format;
}
public void setFormat(String format) {
this.format.set(format);
}
class InternalConverter extends StringConverter<LocalDate> {
@Override
public String toString(LocalDate object) {
LocalDateTime value = getDateTimeValue();
return (value != null) ? value.format(formatter) : "";
}
@Override
public LocalDate fromString(String value) {
if (value == null) {
dateTimeValue.set(null);
return null;
}
dateTimeValue.set(LocalDateTime.parse(value, formatter));
return dateTimeValue.get().toLocalDate();
}
}
}

View File

@ -0,0 +1,138 @@
package ctbrec.ui.controls;
import ctbrec.ui.AutosizeAlert;
import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.image.Image;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Region;
import javafx.stage.Modality;
import javafx.stage.Stage;
import java.io.InputStream;
import java.util.Optional;
import static javafx.scene.control.ButtonType.*;
public class Dialogs {
private Dialogs() {}
private static Scene scene;
public static void setScene(Scene scene) {
Dialogs.scene = scene;
}
public static void showError(String header, String text, Throwable t) {
showError(scene, header, text, t);
}
public static void showError(Scene parent, String header, String text, Throwable t) {
Runnable r = () -> {
Alert alert = new AutosizeAlert(Alert.AlertType.ERROR, parent);
alert.setTitle("Error");
alert.setHeaderText(header);
String content = text;
if (t != null) {
content += " " + t.getLocalizedMessage();
}
alert.setContentText(content);
if (parent != null) {
var stage = (Stage) alert.getDialogPane().getScene().getWindow();
stage.getScene().getStylesheets().addAll(parent.getStylesheets());
}
alert.showAndWait();
};
if (Platform.isFxApplicationThread()) {
r.run();
} else {
Platform.runLater(r);
}
}
public static Optional<String> showTextInput(Scene parent, String title, String header, String text) {
Dialog<String> dialog = new Dialog<>();
dialog.setTitle(title);
dialog.setHeaderText(header);
dialog.getDialogPane().getButtonTypes().addAll(OK, CANCEL);
dialog.initModality(Modality.APPLICATION_MODAL);
dialog.setResizable(true);
InputStream icon = Dialogs.class.getResourceAsStream("/icon.png");
var stage = (Stage) dialog.getDialogPane().getScene().getWindow();
stage.getIcons().add(new Image(icon));
if (parent != null) {
stage.getScene().getStylesheets().addAll(parent.getStylesheets());
}
var grid = new GridPane();
grid.setHgap(10);
grid.setVgap(10);
grid.setPadding(new Insets(20, 150, 10, 10));
var notes = new TextArea(text);
notes.setPrefRowCount(3);
grid.add(notes, 0, 0);
dialog.getDialogPane().setContent(grid);
Platform.runLater(notes::requestFocus);
dialog.setResultConverter(dialogButton -> {
if (dialogButton == OK) {
return notes.getText();
}
return null;
});
return dialog.showAndWait();
}
@SafeVarargs
public static Boolean showCustomInput(Scene parent, String title, Region region, ChangeListener<Boolean> ...showingListener) {
Dialog<?> dialog = new Dialog<>();
dialog.setTitle(title);
dialog.getDialogPane().getButtonTypes().addAll(OK, CANCEL);
dialog.initModality(Modality.APPLICATION_MODAL);
dialog.setResizable(true);
InputStream icon = Dialogs.class.getResourceAsStream("/icon.png");
var stage = (Stage) dialog.getDialogPane().getScene().getWindow();
stage.getIcons().add(new Image(icon));
if (parent != null) {
stage.getScene().getStylesheets().addAll(parent.getStylesheets());
}
dialog.getDialogPane().setContent(region);
for (ChangeListener<Boolean> changeListener : showingListener) {
dialog.showingProperty().addListener(changeListener);
}
dialog.showAndWait();
return dialog.getResult() == OK;
}
public static boolean showConfirmDialog(String title, String message, String header, Scene parent) {
var confirm = new AutosizeAlert(AlertType.CONFIRMATION, message, parent, YES, NO);
confirm.setTitle(title);
confirm.setHeaderText(header);
confirm.showAndWait();
return confirm.getResult() == YES;
}
public static ButtonType showShutdownDialog(Scene parent) {
var message = "There are recordings in progress";
var confirm = new AutosizeAlert(AlertType.CONFIRMATION, "", parent, YES, FINISH, NO);
confirm.setTitle("Shutdown");
confirm.setHeaderText(message);
((Button) confirm.getDialogPane().lookupButton(ButtonType.YES)).setText("Shutdown Now");
((Button) confirm.getDialogPane().lookupButton(ButtonType.YES)).setDefaultButton(false);
((Button) confirm.getDialogPane().lookupButton(ButtonType.FINISH)).setText("Shutdown Gracefully");
((Button) confirm.getDialogPane().lookupButton(ButtonType.FINISH)).setDefaultButton(true);
((Button) confirm.getDialogPane().lookupButton(ButtonType.NO)).setText("Keep Running");
((Button) confirm.getDialogPane().lookupButton(ButtonType.NO)).setDefaultButton(false);
confirm.showAndWait();
return confirm.getResult();
}
}

View File

@ -0,0 +1,43 @@
package ctbrec.ui.controls;
import java.io.File;
import java.util.Optional;
import javafx.stage.DirectoryChooser;
public class DirectorySelectionBox extends AbstractFileSelectionBox {
public DirectorySelectionBox(String dir) {
super(dir);
}
@Override
protected void choose() {
var chooser = new DirectoryChooser();
var preselection = Optional.ofNullable(fileProperty().get()).orElse(".");
var currentDir = new File(preselection);
if (currentDir.exists() && currentDir.isDirectory()) {
chooser.setInitialDirectory(currentDir);
}
File selectedDir = chooser.showDialog(null);
if (selectedDir != null) {
fileInput.setText(selectedDir.getAbsolutePath());
setFile(selectedDir);
}
}
@Override
protected String validate(File file) {
if (isDisabled()) {
return null;
}
String msg = super.validate(file);
if (msg != null) {
return msg;
} else if (!file.isDirectory()) {
return "This is not a directory";
} else {
return null;
}
}
}

View File

@ -0,0 +1,31 @@
package ctbrec.ui.controls;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.skin.ScrollPaneSkin;
import javafx.scene.input.ScrollEvent;
public class FasterVerticalScrollPaneSkin extends ScrollPaneSkin {
public FasterVerticalScrollPaneSkin(final ScrollPane scrollPane) {
super(scrollPane);
getSkinnable().addEventFilter(ScrollEvent.SCROLL, event -> {
var ratio = scrollPane.getViewportBounds().getHeight() / scrollPane.getContent().getBoundsInLocal().getHeight();
var baseUnitIncrement = 0.15;
var unitIncrement = baseUnitIncrement * ratio * 1.25;
getVerticalScrollBar().setUnitIncrement(unitIncrement);
if (event.getDeltaX() < 0) {
getHorizontalScrollBar().increment();
} else if (event.getDeltaX() > 0) {
getHorizontalScrollBar().decrement();
}
if (event.getDeltaY() < 0) {
getVerticalScrollBar().increment();
} else if (event.getDeltaY() > 0) {
getVerticalScrollBar().decrement();
}
event.consume();
});
}
}

View File

@ -0,0 +1,28 @@
package ctbrec.ui.controls;
import java.io.File;
public class FileSelectionBox extends AbstractFileSelectionBox {
public FileSelectionBox() {
}
public FileSelectionBox(String initialValue) {
super(initialValue);
}
@Override
protected String validate(File file) {
if (isDisabled() || validationDisabled) {
return null;
}
String msg = super.validate(file);
if (msg != null) {
return msg;
} else if (!file.isFile()) {
return "This is not a regular file";
} else {
return null;
}
}
}

View File

@ -0,0 +1,28 @@
.popover {
-fx-padding: 43 7 7 7;
}
.popover-frame {
-fx-background-color: -fx-outer-border, -fx-inner-border, -fx-base;
-fx-background-insets: 0 0 -1 0, 0, 1, 2;
-fx-background-radius: 10px, 10px, 10px, 10px;
-fx-padding: 1;
-fx-effect: dropshadow(gaussian, rgba(0, 0, 0, 0.8), 20, 0, 0, 0);
}
.popover.left-tooth .popover-frame {
-fx-shape: "m 33.34215,51.52967 4.782653,4.746482 4.333068,4.299995 h 94.637639 c 1.108,0 1.99987,0.891879 1.99987,1.999877 V 164.22046 c 0,1.10801 -0.89187,1.99988 -1.99987,1.99988 H 12.205971 c -1.107998,0 -2.000392,-0.89187 -2.000392,-1.99988 V 62.576024 c 0,-1.107998 0.892394,-1.999877 2.000392,-1.999877 h 12.020455 l 4.333071,-4.299995 z";
}
.popover.right-tooth .popover-frame {
-fx-shape: "M 438.26953 194.75781 L 420.19336 212.69727 L 403.81641 228.94922 L 46.130859 228.94922 C 41.943143 228.94922 38.572266 232.3201 38.572266 236.50781 L 38.572266 620.67578 C 38.572266 624.8635 41.943143 628.23438 46.130859 628.23438 L 518.1543 628.23438 C 522.34201 628.23438 525.71484 624.8635 525.71484 620.67578 L 525.71484 236.50781 C 525.71484 232.3201 522.34201 228.94922 518.1543 228.94922 L 472.72266 228.94922 L 456.3457 212.69727 L 438.26953 194.75781 z";
}
.popover-title {
-fx-font-size: 20px;
-fx-text-fill: -fx-text-background-color;
}
.popover .button {
-fx-font-size: 12px;
}

View File

@ -0,0 +1,456 @@
/*
* Copyright (c) 2008, 2014, Oracle and/or its affiliates.
* All rights reserved. Use is subject to license terms.
*
* This file is available and licensed under the following license:
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the distribution.
* - Neither the name of Oracle Corporation nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package ctbrec.ui.controls;
import java.util.LinkedList;
import javafx.animation.Animation;
import javafx.animation.FadeTransition;
import javafx.animation.Interpolator;
import javafx.animation.KeyFrame;
import javafx.animation.KeyValue;
import javafx.animation.ParallelTransition;
import javafx.animation.ScaleTransition;
import javafx.animation.Timeline;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.event.ActionEvent;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.geometry.Point2D;
import javafx.scene.Node;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.Pane;
import javafx.scene.layout.Region;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.TextAlignment;
import javafx.util.Duration;
/**
* A Popover is a mini-window that pops up and contains some application specific content.
* It's width is defined by the application, but defaults to a hard-coded pref width.
* The height will always be between a minimum height (determined by the application, but
* pre-set with a minimum value) and a maximum height (specified by the application, or
* based on the height of the scene). The value for the pref height is determined by
* inspecting the pref height of the current displayed page. At time this value is animated
* (when switching from page to page).
*/
public class Popover extends Region implements EventHandler<Event>{
private static final int PAGE_GAP = 15;
/**
* The visual frame of the popover is defined as an addition region, rather than simply styling
* the popover itself as one might expect. The reason for this is that our frame is styled via
* a border image, and it has an inner shadow associated with it, and we want to be able to ensure
* that the shadow is on top of whatever content is drawn within the popover. In addition, the inner
* edge of the frame is rounded, and we want the content to slide under it, only to be clipped beneath
* the frame. So it works best for the frame to be overlaid on top, even though it is not intuitive.
*/
private final Region frameBorder = new Region();
private final Button leftButton = new Button("Left");
private final Button rightButton = new Button("Right");
private final LinkedList<Page> pages = new LinkedList<>();
private final Pane pagesPane = new Pane();
private final Rectangle pagesClipRect = new Rectangle();
private final Pane titlesPane = new Pane();
private Label title; // the current title
private final EventHandler<MouseEvent> popoverHideHandler;
private Runnable onHideCallback = null;
private int maxPopupHeight = -1;
private DoubleProperty popoverHeight = new SimpleDoubleProperty(400) {
@Override protected void invalidated() {
requestLayout();
}
};
public Popover() {
getStyleClass().setAll("popover");
frameBorder.getStyleClass().setAll("popover-frame");
frameBorder.setMouseTransparent(true);
// setup buttons
leftButton.setOnMouseClicked(this);
leftButton.getStyleClass().add("popover-left-button");
leftButton.setMinWidth(USE_PREF_SIZE);
rightButton.setOnMouseClicked(this);
rightButton.getStyleClass().add("popover-right-button");
rightButton.setMinWidth(USE_PREF_SIZE);
pagesClipRect.setSmooth(false);
pagesClipRect.setArcHeight(10);
pagesClipRect.arcWidthProperty().bind(pagesClipRect.arcHeightProperty());
pagesPane.setClip(pagesClipRect);
getChildren().addAll(frameBorder, titlesPane, leftButton, rightButton, pagesPane);
// always hide to start with
setVisible(false);
setOpacity(0);
setScaleX(.8);
setScaleY(.8);
// create handlers for auto hiding
popoverHideHandler = (MouseEvent t) -> {
// check if event is outside popup
Point2D mouseInFilterPane = sceneToLocal(t.getX(), t.getY());
if (mouseInFilterPane.getX() < 0 || mouseInFilterPane.getX() > (getWidth()) ||
mouseInFilterPane.getY() < 0 || mouseInFilterPane.getY() > (getHeight())) {
hide();
t.consume();
}
};
}
/**
* Handle mouse clicks on the left and right buttons.
*/
@Override public void handle(Event event) {
if (event.getSource() == leftButton) {
pages.getFirst().handleLeftButton();
} else if (event.getSource() == rightButton) {
pages.getFirst().handleRightButton();
}
}
@Override protected double computeMinWidth(double height) {
Page page = pages.isEmpty() ? null : pages.getFirst();
if (page != null) {
var n = page.getPageNode();
if (n != null) {
var insets = getInsets();
return insets.getLeft() + n.minWidth(-1) + insets.getRight();
}
}
return 200;
}
@Override protected double computeMinHeight(double width) {
var insets = getInsets();
return insets.getLeft() + 100 + insets.getRight();
}
@Override protected double computePrefWidth(double height) {
Page page = pages.isEmpty() ? null : pages.getFirst();
if (page != null) {
var n = page.getPageNode();
if (n != null) {
var insets = getInsets();
return insets.getLeft() + n.prefWidth(-1) + insets.getRight();
}
}
return 400;
}
@Override protected double computePrefHeight(double width) {
double minHeight = minHeight(-1);
double maxHeight = maxHeight(-1);
double prefHeight = popoverHeight.get();
if (prefHeight == -1) {
var page = pages.getFirst();
if (page != null) {
var inset = getInsets();
if (width == -1) {
width = prefWidth(-1);
}
double contentWidth = width - inset.getLeft() - inset.getRight();
double contentHeight = page.getPageNode().prefHeight(contentWidth);
prefHeight = inset.getTop() + contentHeight + inset.getBottom();
popoverHeight.set(prefHeight);
} else {
prefHeight = minHeight;
}
}
return boundedSize(minHeight, prefHeight, maxHeight);
}
static double boundedSize(double min, double pref, double max) {
double a = pref >= min ? pref : min;
double b = min >= max ? min : max;
return a <= b ? a : b;
}
@Override protected double computeMaxWidth(double height) {
return Double.MAX_VALUE;
}
@Override protected double computeMaxHeight(double width) {
var scene = getScene();
if (scene != null) {
return scene.getHeight() - 100;
} else {
return Double.MAX_VALUE;
}
}
@Override protected void layoutChildren() {
if (maxPopupHeight == -1) {
maxPopupHeight = (int)getScene().getHeight()-100;
}
final var insets = getInsets();
final int width = (int)getWidth();
final int height = (int)getHeight();
final int top = (int)insets.getTop() + 40;
final int right = (int)insets.getRight();
final int bottom = (int)insets.getBottom();
final int left = (int)insets.getLeft();
final var offset = 18;
int pageWidth = width - left - right;
int pageHeight = height - top - bottom;
frameBorder.resize(width, height);
pagesPane.resizeRelocate(left, top, pageWidth, pageHeight);
pagesClipRect.setWidth(pageWidth);
pagesClipRect.setHeight(pageHeight);
var pageX = 0;
for (Node page : pagesPane.getChildren()) {
page.resizeRelocate(pageX, 0, pageWidth, pageHeight);
pageX += pageWidth + PAGE_GAP;
}
int buttonHeight = Math.min(30, (int) (leftButton.prefHeight(-1)));
final int buttonTop = (int) ((top - buttonHeight) / 2d);
final int leftButtonWidth = (int) snapSizeX(leftButton.prefWidth(-1));
leftButton.resizeRelocate(left, (double)buttonTop + offset, leftButtonWidth, buttonHeight);
final int rightButtonWidth = (int) snapSizeX(rightButton.prefWidth(-1));
rightButton.resizeRelocate(width - (double)right - rightButtonWidth, (double)buttonTop + offset, rightButtonWidth, buttonHeight);
if (title != null) {
double tw = title.getWidth();
double th = title.getHeight();
title.setTranslateX((width - tw) / 2);
title.setTranslateY((top - th) / 2 + offset);
}
}
public final void clearPages() {
while (!pages.isEmpty()) {
pages.pop().handleHidden();
}
pagesPane.getChildren().clear();
titlesPane.getChildren().clear();
pagesClipRect.setX(0);
pagesClipRect.setWidth(400);
pagesClipRect.setHeight(400);
popoverHeight.set(400);
pagesPane.setTranslateX(0);
titlesPane.setTranslateX(0);
}
public final void popPage() {
var oldPage = pages.pop();
oldPage.handleHidden();
oldPage.setPopover(null);
var page = pages.getFirst();
leftButton.setVisible(page.leftButtonText() != null);
leftButton.setText(page.leftButtonText());
rightButton.setVisible(page.rightButtonText() != null);
rightButton.setText(page.rightButtonText());
if (!pages.isEmpty()) {
final var insets = getInsets();
final int width = (int)prefWidth(-1);
final int right = (int)insets.getRight();
final int left = (int)insets.getLeft();
int pageWidth = width - left - right;
final int newPageX = (pageWidth+PAGE_GAP) * (pages.size()-1);
new Timeline(
new KeyFrame(Duration.millis(350), (ActionEvent t) -> {
pagesPane.setCache(false);
pagesPane.getChildren().remove(pagesPane.getChildren().size()-1);
titlesPane.getChildren().remove(titlesPane.getChildren().size()-1);
resizePopoverToNewPage(pages.getFirst().getPageNode());
},
new KeyValue(pagesPane.translateXProperty(), -newPageX, Interpolator.EASE_BOTH),
new KeyValue(titlesPane.translateXProperty(), -newPageX, Interpolator.EASE_BOTH),
new KeyValue(pagesClipRect.xProperty(), newPageX, Interpolator.EASE_BOTH)
)
).play();
} else {
hide();
}
}
public final void pushPage(final Page page) {
final var pageNode = page.getPageNode();
pageNode.setManaged(false);
pagesPane.getChildren().add(pageNode);
final var insets = getInsets();
final int pageWidth = (int)(prefWidth(-1) - insets.getLeft() - insets.getRight());
final int newPageX = (pageWidth + PAGE_GAP) * pages.size();
leftButton.setVisible(page.leftButtonText() != null);
leftButton.setText(page.leftButtonText());
rightButton.setVisible(page.rightButtonText() != null);
rightButton.setText(page.rightButtonText());
title = new Label(page.getPageTitle());
title.getStyleClass().add("popover-title");
title.setTextAlignment(TextAlignment.CENTER);
title.setTranslateX(newPageX + (pageWidth - title.getLayoutBounds().getWidth()) / 2d);
titlesPane.getChildren().add(title);
if (!pages.isEmpty() && isVisible()) {
final var timeline = new Timeline(
new KeyFrame(Duration.millis(350), (ActionEvent t) -> {
pagesPane.setCache(false);
resizePopoverToNewPage(pageNode);
},
new KeyValue(pagesPane.translateXProperty(), -newPageX, Interpolator.EASE_BOTH),
new KeyValue(titlesPane.translateXProperty(), -newPageX, Interpolator.EASE_BOTH),
new KeyValue(pagesClipRect.xProperty(), newPageX, Interpolator.EASE_BOTH)
)
);
timeline.play();
}
page.setPopover(this);
page.handleShown();
pages.push(page);
}
private void resizePopoverToNewPage(final Node newPageNode) {
final var insets = getInsets();
final double width = prefWidth(-1);
final double contentWidth = width - insets.getLeft() - insets.getRight();
double h = newPageNode.prefHeight(contentWidth);
h += insets.getTop() + insets.getBottom();
new Timeline(
new KeyFrame(Duration.millis(200),
new KeyValue(popoverHeight, h, Interpolator.EASE_BOTH)
)
).play();
}
public void show(){
show(null);
}
private Animation fadeAnimation = null;
public void show(Runnable onHideCallback){
if (!isVisible() || fadeAnimation != null) {
this.onHideCallback = onHideCallback;
getScene().addEventFilter(MouseEvent.MOUSE_CLICKED, popoverHideHandler);
if (fadeAnimation != null) {
fadeAnimation.stop();
setVisible(true); // for good measure
} else {
popoverHeight.set(-1);
setVisible(true);
}
var fade = new FadeTransition(Duration.seconds(.1), this);
fade.setToValue(1.0);
fade.setOnFinished((ActionEvent event) -> fadeAnimation = null);
var scale = new ScaleTransition(Duration.seconds(.1), this);
scale.setToX(1);
scale.setToY(1);
var tx = new ParallelTransition(fade, scale);
fadeAnimation = tx;
tx.play();
}
}
public void hide(){
if (isVisible() || fadeAnimation != null) {
getScene().removeEventFilter(MouseEvent.MOUSE_CLICKED, popoverHideHandler);
if (fadeAnimation != null) {
fadeAnimation.stop();
}
var fade = new FadeTransition(Duration.seconds(.1), this);
fade.setToValue(0);
fade.setOnFinished((ActionEvent event) -> {
fadeAnimation = null;
setVisible(false);
if (onHideCallback != null) onHideCallback.run();
});
var scale = new ScaleTransition(Duration.seconds(.1), this);
scale.setToX(.8);
scale.setToY(.8);
var tx = new ParallelTransition(fade, scale);
fadeAnimation = tx;
tx.play();
}
}
/**
* Represents a page in a popover.
*/
public static interface Page {
public void setPopover(Popover popover);
public Popover getPopover();
/**
* Get the node that represents the page.
*
* @return the page node.
*/
public Node getPageNode();
/**
* Get the title to display for this page.
*
* @return The page title
*/
public String getPageTitle();
/**
* The text for left button, if null then button will be hidden.
* @return The button text
*/
public String leftButtonText();
/**
* Called on a click of the left button of the popover.
*/
public void handleLeftButton();
/**
* The text for right button, if null then button will be hidden.
* @return The button text
*/
public String rightButtonText();
/**
* Called on a click of the right button of the popover.
*/
public void handleRightButton();
public void handleShown();
public void handleHidden();
}
}

View File

@ -0,0 +1,91 @@
/*
* Copyright (c) 2008, 2014, Oracle and/or its affiliates.
* All rights reserved. Use is subject to license terms.
*
* This file is available and licensed under the following license:
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the distribution.
* - Neither the name of Oracle Corporation nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package ctbrec.ui.controls;
import javafx.event.EventHandler;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.input.MouseEvent;
import javafx.util.Callback;
/**
* Special ListView designed to look like "Text... &gt;" tree list. Perhaps we ought to have customized
* a TreeView instead of a ListView (as the TreeView already has the data model all defined).
*
* This implementation minimizes classes by just having the PopoverTreeList implementing everything
* (it is the Control, the Skin, and the CellFactory all in one).
*/
public class PopoverTreeList<T> extends ListView<T> implements Callback<ListView<T>, ListCell<T>> {
public PopoverTreeList(){
getStyleClass().clear();
setCellFactory(this);
}
@Override public ListCell<T> call(ListView<T> p) {
return new TreeItemListCell();
}
protected void itemClicked(T item) { /* nothing to do */ }
private class TreeItemListCell extends ListCell<T> implements EventHandler<MouseEvent> {
private TreeItemListCell() {
super();
getStyleClass().setAll("popover-tree-list-cell");
setOnMouseClicked(this);
}
@Override public void handle(MouseEvent t) {
itemClicked(getItem());
}
@Override protected double computePrefWidth(double height) {
return 100;
}
@Override protected double computePrefHeight(double width) {
return 44;
}
// CELL METHODS
@Override protected void updateItem(T item, boolean empty) {
// let super do its work
super.updateItem(item,empty);
// update our state
if (item == null) { // empty item
setText(null);
} else {
setText(item.toString());
}
}
}
}

View File

@ -0,0 +1,28 @@
package ctbrec.ui.controls;
import java.io.File;
public class ProgramSelectionBox extends FileSelectionBox {
public ProgramSelectionBox() {
}
public ProgramSelectionBox(String initialValue) {
super(initialValue);
}
@Override
protected String validate(File file) {
if (isDisabled()) {
return null;
}
String msg = super.validate(file);
if (msg != null) {
return msg;
} else if (!file.canExecute()) {
return "This is not an executable application";
} else {
return null;
}
}
}

View File

@ -0,0 +1,36 @@
package ctbrec.ui.controls;
import javafx.scene.Cursor;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Paint;
import javafx.scene.shape.Rectangle;
public class RecordingIndicator extends StackPane {
private ImageView icon;
private Rectangle clickPanel;
public RecordingIndicator(int size) {
setMaxSize(size, size);
icon = new ImageView();
icon.setVisible(false);
icon.prefHeight(size);
icon.prefWidth(size);
icon.maxHeight(size);
icon.maxWidth(size);
clickPanel = new Rectangle(size, size);
clickPanel.setCursor(Cursor.HAND);
clickPanel.setFill(Paint.valueOf("#00000000"));
getChildren().add(icon);
getChildren().add(clickPanel);
icon.visibleProperty().bindBidirectional(visibleProperty());
}
public void setImage(Image img) {
icon.setImage(img);
}
}

View File

@ -0,0 +1,28 @@
package ctbrec.ui.controls;
import javafx.beans.value.ChangeListener;
import java.io.File;
public class SaveFileSelectionBox extends FileSelectionBox {
public SaveFileSelectionBox() {
disableValidation();
useSaveDialog();
}
@Override
protected void setFile(File file) {
// nothing to do
}
@Override
protected ChangeListener<String> textListener() {
return (obs, o, n) -> {};
}
@Override
protected String validate(File file) {
return null;
}
}

View File

@ -0,0 +1,34 @@
.search-box-icon {
-fx-shape: "M10.728,9.893c0.889-1.081,1.375-2.435,1.375-3.842C12.103,2.714,9.388,0,6.051,0C2.715,0,0,2.714,0,6.051c0,3.338,2.715,6.052,6.051,6.052c0.954,0,1.898-0.227,2.744-0.656l3.479,3.478l1.743-1.742L10.728,9.893z M6.051,2.484c1.966,0,3.566,1.602,3.566,3.566c0,1.968-1.6,3.567-3.566,3.567c-1.967,0-3.566-1.6-3.566-3.567C2.485,4.086,4.084,2.484,6.051,2.484z";
-fx-scale-shape: false;
-fx-background-color: -fx-mark-color;
}
.search-box {
/*-fx-font-size: 16px;*/
/*-fx-text-fill: #363636;*/
/*-fx-background-radius: 15, 14;*/
-fx-padding: 0 0 0 30;
}
.search-box:focused {
/*-fx-background-radius: 15,14,16,14;*/
}
.search-clear-button {
-fx-shape: "M9.521,0.083c-5.212,0-9.438,4.244-9.438,9.479c0,5.234,4.225,9.479,9.438,9.479c5.212,0,9.437-4.244,9.437-9.479C18.958,4.327,14.733,0.083,9.521,0.083z M13.91,13.981c-0.367,0.369-0.963,0.369-1.329,0l-3.019-3.03l-3.019,3.03c-0.367,0.369-0.962,0.369-1.329,0c-0.367-0.368-0.366-0.965,0.001-1.334l3.018-3.031L5.216,6.585C4.849,6.217,4.849,5.618,5.217,5.25c0.366-0.369,0.961-0.368,1.328,0l3.018,3.031l3.019-3.031c0.366-0.368,0.961-0.369,1.328,0c0.366,0.368,0.366,0.967,0,1.335l-3.019,3.031l3.02,3.031C14.276,13.017,14.276,13.613,13.91,13.981z";
-fx-scale-shape: false;
-fx-background-color: -fx-mark-color;
-fx-padding: 9.5px;
}
.search-tree-list-cell {
-fx-background-color: -fx-background;
-fx-border-color: transparent transparent -fx-base transparent;
-fx-padding: 0 30 0 20;
-fx-font-size: 15px;
-fx-text-fill: -fx-mid-text-color;
-fx-graphic-text-gap: 20px;
}
.highlight {
-fx-background-color: -fx-focus-color;
-fx-text-fill: -fx-light-text-color;
}

View File

@ -0,0 +1,103 @@
/*
* Copyright (c) 2008, 2014, Oracle and/or its affiliates.
* All rights reserved. Use is subject to license terms.
*
* This file is available and licensed under the following license:
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the distribution.
* - Neither the name of Oracle Corporation nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package ctbrec.ui.controls;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.scene.Cursor;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyCode;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.Region;
/**
* Search field with styling and a clear button
*/
public class SearchBox extends TextField implements ChangeListener<String>{
private static final int PREF_HEIGHT = 26;
private final Button clearButton = new Button();
private final Region innerBackground = new Region();
private final Region icon = new Region();
public SearchBox() {
getStyleClass().addAll("search-box");
icon.getStyleClass().setAll("search-box-icon");
innerBackground.getStyleClass().setAll("search-box-inner");
setPromptText("Search");
textProperty().addListener(this);
setPrefHeight(PREF_HEIGHT);
clearButton.getStyleClass().setAll("search-clear-button");
clearButton.setCursor(Cursor.DEFAULT);
clearButton.setOnMouseClicked((MouseEvent t) -> {
setText("");
requestFocus();
});
clearButton.setVisible(false);
clearButton.setManaged(false);
innerBackground.setManaged(false);
icon.setManaged(false);
setOnKeyPressed(evt -> {
if(evt.getCode() == KeyCode.ESCAPE) {
setText("");
}
});
}
public SearchBox(boolean icon) {
this();
this.icon.setVisible(false);
this.icon.getStyleClass().remove("search-box-icon");
this.setStyle("-fx-padding: 5");
}
@Override protected void layoutChildren() {
super.layoutChildren();
if (clearButton.getParent() != this) getChildren().add(clearButton);
if (innerBackground.getParent() != this) getChildren().add(0,innerBackground);
if (icon.getParent() != this) getChildren().add(icon);
innerBackground.setLayoutX(0);
innerBackground.setLayoutY(0);
innerBackground.resize(getWidth(), getHeight());
icon.setLayoutX(0);
icon.setLayoutY(0);
icon.resize(35,PREF_HEIGHT);
clearButton.setLayoutX(getWidth() - PREF_HEIGHT);
clearButton.setLayoutY(0);
clearButton.resize(PREF_HEIGHT, PREF_HEIGHT);
}
@Override public void changed(ObservableValue<? extends String> ov, String oldValue, String newValue) {
clearButton.setVisible(newValue.length() > 0);
}
}

View File

@ -0,0 +1,9 @@
package ctbrec.ui.controls;
public class SearchPopover extends Popover {
public SearchPopover() {
getStyleClass().add("right-tooth");
}
}

View File

@ -0,0 +1,346 @@
/*
* Copyright (c) 2008, 2014, Oracle and/or its affiliates.
* All rights reserved. Use is subject to license terms.
*
* This file is available and licensed under the following license:
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the distribution.
* - Neither the name of Oracle Corporation nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package ctbrec.ui.controls;
import ctbrec.Config;
import ctbrec.GlobalThreadPool;
import ctbrec.Model;
import ctbrec.StringUtil;
import ctbrec.recorder.Recorder;
import ctbrec.ui.action.PlayAction;
import ctbrec.ui.action.SetThumbAsPortraitAction;
import ctbrec.ui.menu.ModelMenuContributor;
import javafx.application.Platform;
import javafx.concurrent.Task;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.Cursor;
import javafx.scene.Node;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.ContextMenuEvent;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.scene.shape.Rectangle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.URL;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
/**
* Popover page that displays a list of samples and sample categories for a given SampleCategory.
*/
public class SearchPopoverTreeList extends PopoverTreeList<Model> implements Popover.Page {
private static final Logger LOG = LoggerFactory.getLogger(SearchPopoverTreeList.class);
private Popover popover;
private Recorder recorder;
ContextMenu popup;
@Override
public ListCell<Model> call(ListView<Model> p) {
return new SearchItemListCell();
}
@Override
protected void itemClicked(Model model) {
if (model == null) {
return;
}
new PlayAction(this, model).execute();
}
@Override
public void setPopover(Popover popover) {
this.popover = popover;
}
@Override
public Popover getPopover() {
return popover;
}
@Override
public Node getPageNode() {
return this;
}
@Override
public String getPageTitle() {
return "Search Results";
}
@Override
public String leftButtonText() {
return null;
}
@Override
public void handleLeftButton() {
// not used
}
@Override
public String rightButtonText() {
return "Done";
}
@Override
public void handleRightButton() {
popover.hide();
}
@Override
public void handleShown() {
// not used
}
@Override
public void handleHidden() {
// not used
}
private class SearchItemListCell extends ListCell<Model> implements Skin<SearchItemListCell>, EventHandler<MouseEvent> {
private Label title = new Label();
private Button follow;
private Button startRecording;
private Model model;
private ImageView thumb = new ImageView();
private int thumbSize = 64;
private Node tallest = thumb;
private SearchItemListCell() {
super();
String highlightClass = "highlight";
setSkin(this);
getStyleClass().setAll("search-tree-list-cell");
setOnMouseClicked(this);
setOnMouseEntered(evt -> getStyleClass().add(highlightClass));
setOnMouseExited(evt -> getStyleClass().remove(highlightClass));
addEventHandler(ContextMenuEvent.CONTEXT_MENU_REQUESTED, event -> {
popup = new CustomMouseBehaviorContextMenu();
ModelMenuContributor.newContributor(this, Config.getInstance(), recorder) //
.withStartStopCallback(m -> setCursor(Cursor.DEFAULT)) //
.contributeToMenu(List.of(model), popup);
var useImageAsPortrait = new MenuItem("Use As Portrait");
useImageAsPortrait.setOnAction(e -> new SetThumbAsPortraitAction(this, model, thumb.getImage()).execute());
popup.getItems().add(useImageAsPortrait);
popup.show(this, event.getScreenX(), event.getScreenY());
event.consume();
});
addEventHandler(MouseEvent.MOUSE_PRESSED, event -> {
if (popup != null) {
popup.hide();
}
});
Rectangle clip = new Rectangle(thumbSize, thumbSize);
clip.setArcWidth(20);
clip.arcHeightProperty().bind(clip.arcWidthProperty());
thumb.setFitWidth(thumbSize);
thumb.setFitHeight(thumbSize);
thumb.setClip(clip);
thumb.setSmooth(true);
follow = new Button("Follow");
follow.setOnAction(evt -> {
setCursor(Cursor.WAIT);
GlobalThreadPool.submit(new Task<Boolean>() {
@Override
protected Boolean call() throws Exception {
model.getSite().login();
return model.follow();
}
@Override
protected void done() {
try {
get();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
LOG.warn("Search failed: {}", e.getMessage());
} catch (Exception e) {
LOG.warn("Search failed: {}", e.getMessage());
}
Platform.runLater(() -> setCursor(Cursor.DEFAULT));
}
});
});
startRecording = new Button("Record");
startRecording.setOnAction(evt -> {
setCursor(Cursor.WAIT);
GlobalThreadPool.submit(new Task<Void>() {
@Override
protected Void call() throws Exception {
recorder.addModel(model);
return null;
}
@Override
protected void done() {
Platform.runLater(() -> setCursor(Cursor.DEFAULT));
}
});
});
getChildren().addAll(thumb, title, follow, startRecording);
startRecording.visibleProperty().bind(title.visibleProperty());
thumb.visibleProperty().bind(title.visibleProperty());
}
@Override
public void handle(MouseEvent t) {
if (t.getButton() == MouseButton.PRIMARY && t.getClickCount() == 2) {
itemClicked(getItem());
}
}
@Override
protected void updateItem(Model model, boolean empty) {
super.updateItem(model, empty);
if (empty) {
follow.setVisible(false);
title.setVisible(false);
this.model = null;
} else {
follow.setVisible(model.getSite().supportsFollow());
follow.setDisable(!model.getSite().credentialsAvailable());
title.setVisible(true);
title.setText(model.getDisplayName());
this.model = model;
URL anonymousPng = getClass().getResource("/anonymous.png");
String previewUrl = Optional.ofNullable(model.getPreview()).orElse(anonymousPng.toString());
if (!Objects.equals(System.getenv("CTBREC_DEV"), "1") && StringUtil.isNotBlank(previewUrl)) {
Image img = new Image(previewUrl, true);
thumb.setImage(img);
} else {
Image img = new Image(anonymousPng.toString(), true);
thumb.setImage(img);
}
}
}
@Override
protected void layoutChildren() {
super.layoutChildren();
final Insets insets = getInsets();
final double left = insets.getLeft();
final double top = insets.getTop();
final double w = getWidth() - left - insets.getRight();
final double h = getHeight() - top - insets.getBottom();
thumb.setLayoutX(left);
thumb.setLayoutY((h - thumbSize) / 2);
final double titleHeight = title.prefHeight(w);
title.setLayoutX(left + thumbSize + 10);
title.setLayoutY((h - titleHeight) / 2);
title.resize(w, titleHeight);
int buttonW = 50;
int buttonH = 24;
follow.setStyle("-fx-font-size: 10px;");
follow.setLayoutX(w - buttonW - 20);
follow.setLayoutY((h - buttonH) / 2);
follow.resize(buttonW, buttonH);
startRecording.setStyle("-fx-font-size: 10px;");
startRecording.setLayoutX(w - 10);
startRecording.setLayoutY((h - buttonH) / 2);
startRecording.resize(buttonW, buttonH);
}
@Override
protected double computeMinWidth(double height) {
final Insets insets = getInsets();
final double h = insets.getBottom() - insets.getTop();
return (int) ((insets.getLeft() + tallest.minWidth(h) + tallest.minWidth(h) + insets.getRight()) + 0.5d);
}
@Override
protected double computePrefWidth(double height) {
final Insets insets = getInsets();
final double h = insets.getBottom() - insets.getTop();
return (int) ((insets.getLeft() + tallest.prefWidth(h) + tallest.prefWidth(h) + insets.getRight()) + 0.5d);
}
@Override
protected double computeMaxWidth(double height) {
final Insets insets = getInsets();
final double h = insets.getBottom() - insets.getTop();
return (int) ((insets.getLeft() + tallest.maxWidth(h) + tallest.maxWidth(h) + insets.getRight()) + 0.5d);
}
@Override
protected double computeMinHeight(double width) {
return thumbSize;
}
@Override
protected double computePrefHeight(double width) {
return thumbSize + 20.0;
}
@Override
protected double computeMaxHeight(double width) {
return thumbSize + 20.0;
}
@Override
public SearchItemListCell getSkinnable() {
return this;
}
@Override
public Node getNode() {
return null;
}
@Override
public void dispose() {
// nothing to do
}
}
public void setRecorder(Recorder recorder) {
this.recorder = recorder;
}
}

Some files were not shown because too many files have changed in this diff Show More