This commit is contained in:
xkeyC 2023-10-09 01:32:07 +00:00
parent 3fba73ca4b
commit 23fed0b7a7
72 changed files with 7447 additions and 89 deletions

45
.gitignore vendored Normal file
View File

@ -0,0 +1,45 @@
# Miscellaneous
*.class
*.log
*.pyc
*.swp
.DS_Store
.atom/
.buildlog/
.history
.svn/
migrate_working_dir/
# IntelliJ related
*.iml
*.ipr
*.iws
.idea/
# The .vscode folder contains launch configuration and tasks you configure in
# VS Code which you may wish to be included in version control, so this line
# is commented out by default.
#.vscode/
# Flutter/Dart/Pub related
**/doc/api/
**/ios/Flutter/.last_build_id
.dart_tool/
.flutter-plugins
.flutter-plugins-dependencies
.packages
.pub-cache/
.pub/
/build/
# Symbolication related
app.*.symbols
# Obfuscation related
app.*.map.json
# Android Studio will place build artifacts here
/android/app/debug
/android/app/profile
/android/app/release
/pubspec.lock

30
.metadata Normal file
View File

@ -0,0 +1,30 @@
# This file tracks properties of this Flutter project.
# Used by Flutter tool to assess capabilities and perform upgrades etc.
#
# This file should be version controlled.
version:
revision: 4d9e56e694b656610ab87fcf2efbcd226e0ed8cf
channel: stable
project_type: app
# Tracks metadata for the flutter migrate command
migration:
platforms:
- platform: root
create_revision: 4d9e56e694b656610ab87fcf2efbcd226e0ed8cf
base_revision: 4d9e56e694b656610ab87fcf2efbcd226e0ed8cf
- platform: windows
create_revision: 4d9e56e694b656610ab87fcf2efbcd226e0ed8cf
base_revision: 4d9e56e694b656610ab87fcf2efbcd226e0ed8cf
# User provided section
# List of Local paths (relative to this file) that should be
# ignored by the migrate tool.
#
# Files that are not part of the templates will be ignored by default.
unmanaged_files:
- 'lib/main.dart'
- 'ios/Runner.xcodeproj/project.pbxproj'

674
LICENSE 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>.

100
README.md
View File

@ -1,92 +1,14 @@
# StarCitizenDoctor # 星际公民诊断工具
该工具为 星际公民玩家 提供 一键诊断,官网及工具网站汉化,游戏汉化,游戏性能优化 等功能,让你的游戏体验更愉快。
### 安装
1. 前往 [Release](https://jihulab.com/StarCitizenCN_Community/StarCitizenDoctor/-/releases) 页面,下载最新安装包 Setup.exe
2. 双击安装,建议使用默认安装位置 点击安装即可。
## Getting started ### 📸 屏幕截图
![image.png](https://s2.loli.net/2023/10/05/ng3ECSaQqs6LxHm.png)
To make it easy for you to get started with GitLab, here's a list of recommended next steps. ![image.png](https://s2.loli.net/2023/10/05/kARF27iDs86f3Kn.png)
![image.png](https://s2.loli.net/2023/10/05/LwaiZflD1NFq8Xj.png)
Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)! ![image.png](https://s2.loli.net/2023/10/05/eGl7ISPEVZM5Cvq.png)
![image.png](https://s2.loli.net/2023/10/05/XEHunP3yWDK7RT1.png)
## Add your files
- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files
- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command:
```
cd existing_repo
git remote add origin https://jihulab.com/StarCitizenCN_Community/StarCitizenDoctor.git
git branch -M main
git push -uf origin main
```
## Integrate with your tools
- [ ] [Set up project integrations](https://jihulab.com/StarCitizenCN_Community/StarCitizenDoctor/-/settings/integrations)
## Collaborate with your team
- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
- [ ] [Set auto-merge](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html)
## Test and Deploy
Use the built-in continuous integration in GitLab.
- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html)
- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing(SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
***
# Editing this README
When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thank you to [makeareadme.com](https://www.makeareadme.com/) for this template.
## Suggestions for a good README
Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
## Name
Choose a self-explaining name for your project.
## Description
Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
## Badges
On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
## Visuals
Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
## Installation
Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
## Usage
Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
## Support
Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
## Roadmap
If you have ideas for releases in the future, it is a good idea to list them in the README.
## Contributing
State if you are open to contributions and what your requirements are for accepting them.
For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
## Authors and acknowledgment
Show your appreciation to those who have contributed to the project.
## License
For open source projects, say how it is licensed.
## Project status
If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.

29
analysis_options.yaml Normal file
View File

@ -0,0 +1,29 @@
# This file configures the analyzer, which statically analyzes Dart code to
# check for errors, warnings, and lints.
#
# The issues identified by the analyzer are surfaced in the UI of Dart-enabled
# IDEs (https://dart.dev/tools#ides-and-editors). The analyzer can also be
# invoked from the command line by running `flutter analyze`.
# The following line activates a set of recommended lints for Flutter apps,
# packages, and plugins designed to encourage good coding practices.
include: package:flutter_lints/flutter.yaml
linter:
# The lint rules applied to this project can be customized in the
# section below to disable rules from the `package:flutter_lints/flutter.yaml`
# included above or to enable additional rules. A list of all available lints
# and their documentation is published at
# https://dart-lang.github.io/linter/lints/index.html.
#
# Instead of disabling a lint rule for the entire project in the
# section below, it can also be suppressed for a single line of code
# or a specific dart file by using the `// ignore: name_of_lint` and
# `// ignore_for_file: name_of_lint` syntax on the line or in the file
# producing the lint.
rules:
# avoid_print: false # Uncomment to disable the `avoid_print` rule
# prefer_single_quotes: true # Uncomment to enable the `prefer_single_quotes` rule
# Additional information about this file can be found at
# https://dart.dev/guides/language/analysis-options

Binary file not shown.

BIN
assets/app_logo.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 187 KiB

View File

@ -0,0 +1,171 @@
/// https://github.com/CxJuice/Uex_Chinese_Translate
let replaceLocalesMap = {"k": "v"};
let enable_webview_localization_capture = false;
function InitWebLocalization() {
let scriptTimeAgo = document.createElement('script');
scriptTimeAgo.src = 'https://cdn.bootcdn.net/ajax/libs/timeago.js/4.0.2/timeago.full.min.js';
document.head.appendChild(scriptTimeAgo);
if (typeof $ === 'undefined') {
let scriptJquery = document.createElement('script');
scriptJquery.src = 'https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js';
document.head.appendChild(scriptJquery);
}
LocalizationWatchUpdate();
}
function LocalizationWatchUpdate() {
const m = window.MutationObserver || window.WebKitMutationObserver;
const observer = new m(function (mutations, observer) {
for (let mutationRecord of mutations) {
for (let node of mutationRecord.addedNodes) {
traverseElement(node);
}
}
});
observer.observe(document.body, {
subtree: true,
characterData: true,
childList: true,
});
if (window.location.hostname.includes("www.erkul.games") || window.location.hostname.includes("ccugame.app")) {
document.body.addEventListener("click", function (event) {
setTimeout(function () {
allTranslate().then(_ => {
})
}, 200);
});
}
}
function WebLocalizationUpdateReplaceWords(w, b) {
enable_webview_localization_capture = b;
let replaceWords = w.sort(function (a, b) {
return b.word.length - a.word.length;
});
replaceWords.forEach(({word, replacement}) => {
replaceLocalesMap[word] = replacement;
});
allTranslate().then(_ => {
})
// console.log("WebLocalizationUpdateReplaceWords ==" + w)
}
async function allTranslate() {
async function replaceTextNode(node1) {
if (node1.nodeType === Node.TEXT_NODE) {
let nodeValue = node1.nodeValue;
const key = nodeValue.trim().toLowerCase()
.replace(/\xa0/g, ' ') // replace '&nbsp;'
.replace(/\s{2,}/g, ' ');
if (replaceLocalesMap[key]) {
nodeValue = replaceLocalesMap[key]
} else {
ReportUnTranslate(key, node1.nodeValue);
}
node1.nodeValue = nodeValue;
} else {
for (let i = 0; i < node1.childNodes.length; i++) {
await replaceTextNode(node1.childNodes[i]);
}
}
}
await replaceTextNode(document.body);
}
function traverseElement(el) {
if (!shouldTranslateEl(el)) {
return
}
for (const child of el.childNodes) {
if (["RELATIVE-TIME", "TIME-AGO"].includes(el.tagName)) {
translateRelativeTimeEl(el);
return;
}
if (child.nodeType === Node.TEXT_NODE) {
translateElement(child);
} else if (child.nodeType === Node.ELEMENT_NODE) {
if (child.tagName === "INPUT") {
translateElement(child);
} else {
traverseElement(child);
}
} else {
// pass
}
}
}
function translateElement(el) {
// Get the text field name
let k;
if (el.tagName === "INPUT") {
if (el.type === 'button' || el.type === 'submit') {
k = 'value';
} else {
k = 'placeholder';
}
} else {
k = 'data';
}
const txtSrc = el[k].trim();
const key = txtSrc.toLowerCase()
.replace(/\xa0/g, ' ') // replace '&nbsp;'
.replace(/\s{2,}/g, ' ');
if (replaceLocalesMap[key]) {
el[k] = el[k].replace(txtSrc, replaceLocalesMap[key])
} else {
ReportUnTranslate(key, txtSrc);
}
}
function translateRelativeTimeEl(el) {
const lang = (navigator.language || navigator.userLanguage);
const datetime = $(el).attr('datetime');
$(el).text(timeago.format(datetime, lang.replace('-', '_')));
}
function shouldTranslateEl(el) {
const blockIds = [];
const blockClass = [
"css-truncate" // 过滤文件目录
];
const blockTags = ["IMG", "svg", "mat-icon"];
if (blockTags.includes(el.tagName)) {
return false;
}
if (el.id && blockIds.includes(el.id)) {
return false;
}
if (el.classList) {
for (let clazz of blockClass) {
if (el.classList.contains(clazz)) {
return false;
}
}
}
return true;
}
function ReportUnTranslate(k, v) {
const cnPattern = /[\u4e00-\u9fa5]/;
const enPattern = /[a-zA-Z]/;
const htmlPattern = /<[^>]*>/;
const cssRegex = /(?:^|[^<])<style[^>]*>[\s\S]*?<\/style>(?:[^>]|$)/i;
const jsRegex = /(?:^|[^<])<script[^>]*>[\s\S]*?<\/script>(?:[^>]|$)/i;
if (enable_webview_localization_capture) {
if (k.trim() !== "" && !cnPattern.test(k) && !htmlPattern.test(k) && !cssRegex.test(k) && !jsRegex.test(k)
&& enPattern.test(k) && !k.startsWith("http://") && !k.startsWith("https://")) {
window.chrome.webview.postMessage({action: 'webview_localization_capture', key: k, value: v});
}
}
}
InitWebLocalization();

312
assets/performance.json Normal file
View File

@ -0,0 +1,312 @@
[
{
"key": "r_ssdo",
"name": "屏幕光线后处理",
"info": "调整光线后处理等级",
"type": "int",
"max": 2,
"min": 0,
"value": 1,
"group": "图形(修改后建议清理着色器)"
},
{
"key": "r_AntialiasingMode",
"name": "抗锯齿",
"info": "0 关闭1 SMAA2 时间过滤+SMAA3 时间滤波和投影矩阵抖动的 SMAA",
"type": "int",
"max": 3,
"min": 0,
"value": 2,
"group": "图形(修改后建议清理着色器)"
},
{
"key": "sys_spec_gameeffects",
"name": "特效等级",
"info": "游戏特效等级",
"type": "int",
"max": 4,
"min": 1,
"value": 2,
"group": "图形(修改后建议清理着色器)"
},
{
"key": "sys_spec_texture",
"name": "纹理等级",
"info": "模型纹理细节",
"type": "int",
"max": 3,
"min": 1,
"value": 2,
"group": "图形(修改后建议清理着色器)"
},
{
"key": "sys_spec_volumetriceffects",
"name": "体积效果",
"info": "体积云、体积光照等",
"type": "int",
"max": 4,
"min": 1,
"value": 2,
"group": "图形(修改后建议清理着色器)"
},
{
"key": "sys_spec_water",
"name": "水体效果",
"info": "各种水的等级",
"type": "int",
"max": 4,
"min": 1,
"value": 2,
"group": "图形(修改后建议清理着色器)"
},
{
"key": "sys_spec_objectdetail",
"name": "对象细节",
"info": "模型对象细节影响LOD等..",
"type": "int",
"max": 4,
"min": 1,
"value": 2,
"group": "图形(修改后建议清理着色器)"
},
{
"key": "sys_spec_particles",
"name": "粒子细节",
"info": "",
"type": "int",
"max": 4,
"min": 1,
"value": 2,
"group": "图形(修改后建议清理着色器)"
},
{
"key": "sys_spec_physics",
"name": "物理细节",
"info": "物理效果范围",
"type": "int",
"max": 4,
"min": 1,
"value": 2,
"group": "图形(修改后建议清理着色器)"
},
{
"key": "sys_spec_shading",
"name": "着色器细节",
"info": "着色器相关",
"type": "int",
"max": 4,
"min": 1,
"value": 2,
"group": "图形(修改后建议清理着色器)"
},
{
"key": "sys_spec_shadows",
"name": "阴影细节",
"info": "阴影效果",
"type": "int",
"max": 4,
"min": 1,
"value": 2,
"group": "图形(修改后建议清理着色器)"
},
{
"key": "sys_spec_postprocessing",
"name": "后处理细节",
"info": "后处理着色器,动态模糊效果 等",
"type": "int",
"max": 4,
"min": 1,
"value": 2,
"group": "图形(修改后建议清理着色器)"
},
{
"key": "q_Renderer",
"name": "渲染器质量",
"info": "cryengine 渲染器质量",
"type": "int",
"max": 3,
"min": 0,
"value": 2,
"group": "图形(修改后建议清理着色器)"
},
{
"key": "q_ShaderDecal",
"name": "贴花质量",
"info": "LOGO、标志等",
"type": "int",
"max": 3,
"min": 0,
"value": 2,
"group": "图形(修改后建议清理着色器)"
},
{
"key": "q_ShaderFX",
"name": "FX 质量",
"info": "",
"type": "int",
"max": 3,
"min": 0,
"value": 2,
"group": "图形(修改后建议清理着色器)"
},
{
"key": "q_ShaderGeneral",
"name": "常规质量",
"info": "整体模型质量",
"type": "int",
"max": 3,
"min": 0,
"value": 2,
"group": "图形(修改后建议清理着色器)"
},
{
"key": "q_ShaderGlass",
"name": "玻璃质量",
"info": "窗、镜子等",
"type": "int",
"max": 3,
"min": 0,
"value": 2,
"group": "图形(修改后建议清理着色器)"
},
{
"key": "q_ShaderHDR",
"name": "HDR质量",
"info": "HDR色差亮度层级 处理 等",
"type": "int",
"max": 3,
"min": 0,
"value": 2,
"group": "图形(修改后建议清理着色器)"
},
{
"key": "q_ShaderParticle",
"name": "粒子质量",
"info": "粒子效果质量",
"type": "int",
"max": 3,
"min": 0,
"value": 2,
"group": "图形(修改后建议清理着色器)"
},
{
"key": "q_ShaderTerrain",
"name": "地面质量",
"info": "",
"type": "int",
"max": 3,
"min": 0,
"value": 2,
"group": "图形(修改后建议清理着色器)"
},
{
"key": "q_ShaderShadow",
"name": "阴影质量",
"info": "",
"type": "int",
"max": 3,
"min": 0,
"value": 2,
"group": "图形(修改后建议清理着色器)"
},
{
"key": "q_ShaderSky",
"name": "天空质量",
"info": "",
"type": "int",
"max": 3,
"min": 0,
"value": 2,
"group": "图形(修改后建议清理着色器)"
},
{
"key": "e_ParticlesObjectCollisions",
"name": "粒子碰撞",
"info": "1 仅静态粒子 2 包括动态粒子",
"type": "int",
"max": 2,
"min": 1,
"value": 1,
"group": "图形(修改后建议清理着色器)"
},
{
"key": "r_HDRDisplayMaxNits",
"name": "HDR 最高亮度",
"info": "推荐设置为您显示器的最高亮度",
"type": "int",
"max": 2000,
"min": 300,
"value": 1000,
"group": "HDR设置 在游戏设置启用HDR "
},
{
"key": "r_HDRDisplayRefWhite",
"name": "HDR 白点亮度",
"info": "调整画面明暗细节对比度",
"type": "int",
"max": 2000,
"min": 1,
"value": 150,
"group": "HDR设置 在游戏设置启用HDR "
},
{
"key": "r_displayinfo",
"name": "屏幕信息(展示帧率)",
"info": "在屏幕右上角展示帧率,服务器信息等",
"type": "int",
"max": 4,
"min": 0,
"value": 1,
"group": "设置"
},
{
"key": "r_DisplaySessionInfo",
"name": "显示会话信息",
"info": "开启后在屏幕上显示一个二维码,用于反馈时让 CIG 快速定位相关信息",
"type": "bool",
"max": 1,
"min": 0,
"value": 0,
"group": "设置"
},
{
"key": "r_VSync",
"name": "垂直同步",
"info": "开启以防止撕裂,关闭以提高帧率",
"type": "bool",
"max": 1,
"min": 0,
"value": 0,
"group": "设置"
},
{
"key": "r_MotionBlur",
"name": "动态模糊",
"info": "开启以提高运动感,关闭提升观感",
"type": "bool",
"max": 1,
"min": 0,
"value": 0,
"group": "设置"
},
{
"key": "cl_fov",
"name": "FOV",
"info": "设置视角FOV",
"type": "int",
"max": 160,
"min": 25,
"value": 90,
"group": "设置"
},
{
"key": "ui_disableScreenFade",
"name": "UI 淡入淡出动画",
"info": "",
"type": "bool",
"max": 1,
"min": 0,
"value": 1,
"group": "设置"
}
]

1
assets/rsi.svg Normal file
View File

@ -0,0 +1 @@
<svg viewBox="0 0 56 16" fill="none" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" clip-rule="evenodd" d="M16.0716 0C17.111 0 17.7697 0.734004 17.5824 1.65153L17.5516 1.77773L16.4646 5.68023C16.2499 6.48564 15.6763 7.15995 14.9845 7.52983L14.8228 7.6097L11.6546 9.08403L12.3485 11.8374C12.4102 12.0494 12.6179 12.227 12.8583 12.2638L12.9497 12.2708H15.0308L14.0135 16H10.7299C9.96799 16 9.22678 15.4621 8.98803 14.8024L8.94926 14.6774L7.95482 10.8185L5.17986 12.1191L4.11629 16H0L4.34743 0H16.0716ZM30.028 0L30.0255 0.00849999L29.0084 3.71374L29.0048 3.72704H29.0004L22.8229 3.71374C22.4538 3.71374 22.1768 3.84407 22.0843 4.19052C22.0024 4.49868 22.1027 4.73832 22.3854 4.94011L22.4999 5.01406L29.1008 9.10927C29.7285 9.49516 30.0921 10.3574 29.9828 11.0527L29.9546 11.1894L29.0084 14.6781C28.8348 15.3511 28.0883 15.9282 27.3084 15.9938L27.1619 16H18.8519L19.8686 12.2728H24.8772C25.2464 12.2728 25.5232 12.0346 25.5925 11.8178C25.6756 11.5644 25.6278 11.3636 25.3483 11.1522L25.2464 11.0812L18.5995 6.92095C17.9719 6.53476 17.6081 5.67281 17.7173 4.97743L17.7455 4.84076L18.6914 1.33023C18.8654 0.657352 19.5912 0.0802618 20.3495 0.0146972L20.492 0.00849999L30.0218 0H30.028ZM34.8758 0L39.0028 0.00849999L34.6207 16H30.4473L34.8566 0.00849999H34.8735L34.8758 0ZM17.698 12.2956L16.6916 16H16.0205L17.0206 12.2956H17.698ZM16.356 12.2956L15.313 16H14.5946L15.6471 12.3028L15.6493 12.2956H16.356ZM19.124 12.2956L18.0887 16H17.3625L18.398 12.2956H19.124ZM12.2017 3.70443H7.46927L6.45853 7.48768L12.0409 4.81988C12.5006 4.60106 12.6614 4.33872 12.7304 4.12006C12.8222 3.83596 12.5694 3.70443 12.2017 3.70443ZM34.1379 0L33.1305 3.70443H32.4604L33.474 0H34.1379ZM32.712 0L31.7062 3.70443H31.0345L32.0511 0H32.712ZM31.3537 0L31.3515 0.00844828H31.37L30.3313 3.69121L30.3277 3.70443H29.6086L29.6121 3.69121L30.6322 0.00844828L30.6346 0H31.3537Z" fill="currentColor"></path><path fill-rule="evenodd" clip-rule="evenodd" d="M44.0993 0.5C45.1052 0.5 45.71 0.718656 46.0714 1.07635C46.4317 1.43287 46.6502 2.02678 46.6502 3.01365C46.6502 4.00008 46.4317 4.58521 46.0739 4.93447C45.7133 5.28641 45.1085 5.5 44.0993 5.5C43.0905 5.5 42.4701 5.28657 42.0962 4.9303C41.7277 4.57908 41.5 3.99382 41.5 3.01365C41.5 2.03297 41.7277 1.43898 42.0987 1.08055C42.4734 0.718531 43.0938 0.5 44.0993 0.5ZM47.1502 3.01365C47.1502 0.918004 46.2283 0 44.0993 0C41.9703 0 41 0.918004 41 3.01365C41 5.10816 41.9703 6 44.0993 6C46.2283 6 47.1502 5.10816 47.1502 3.01365ZM42.7675 1.363C43.2445 1.318 43.717 1.3 44.194 1.3C45.157 1.3 45.4855 1.633 45.4855 2.5105C45.4855 3.154 45.319 3.4555 44.842 3.577L45.607 4.7965C45.643 4.846 45.6205 4.8865 45.553 4.8865H44.725C44.6215 4.8865 44.59 4.855 44.545 4.7875L43.816 3.6355H43.645V4.8145C43.645 4.873 43.6315 4.8865 43.5775 4.8865H42.7675C42.7135 4.8865 42.7 4.873 42.7 4.8145V1.4215C42.7 1.381 42.7135 1.3675 42.7675 1.363ZM44.527 2.542C44.527 2.2495 44.428 2.1235 44.0905 2.1235H43.645V2.9425H44.0905C44.428 2.9425 44.527 2.839 44.527 2.542Z" fill="currentColor"></path></svg>

After

Width:  |  Height:  |  Size: 2.9 KiB

BIN
assets/sc_logo.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 39 KiB

1
assets/uex.svg Normal file
View File

@ -0,0 +1 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"><svg width="100%" height="100%" viewBox="0 0 2763 1189" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xml:space="preserve" xmlns:serif="http://www.serif.com/" style="fill-rule:evenodd;clip-rule:evenodd;stroke-linejoin:round;stroke-miterlimit:2;"><g><g><path d="M2437.31,593.737c-171.792,-136.673 -343.584,-135.941 -515.375,0c-74.996,70.738 -117.478,169.272 -117.41,272.369l-0,321.369l205.305,-0l0,-321.369c0.764,-93.231 76.561,-168.4 169.792,-168.4c93.231,-0 169.028,75.169 169.792,168.4l0,321.369l205.306,-0l-0,-321.369c0.068,-103.097 -42.414,-201.631 -117.41,-272.369Z" style="fill:#ffc843;fill-rule:nonzero;"/><path d="M1921.94,593.737c171.791,136.674 343.583,135.942 515.375,0c74.996,-70.737 117.478,-169.271 117.41,-272.368l-0,-321.369l-205.306,0l0,321.369c-0.764,93.231 -76.561,168.4 -169.792,168.4c-93.231,0 -169.028,-75.169 -169.792,-168.4l0,-321.369l-205.305,0l-0,321.369c-0.068,103.097 42.414,201.631 117.41,272.368Z" style="fill:#05ce7c;fill-rule:nonzero;"/><path d="M1921.94,593.737c171.791,-135.941 343.583,-136.673 515.375,0c-171.792,135.942 -343.584,136.674 -515.375,0Z" style="fill:#05a221;fill-rule:nonzero;"/></g><path d="M750.195,982.17l0,-982.17l-205.305,0l-0,812.394c-0.764,93.232 -76.561,168.4 -169.792,168.4c-93.232,0 -169.029,-75.168 -169.792,-168.4l-0,-812.394l-205.306,0l0,812.394c-0.068,139.898 77.783,268.201 201.893,332.777c124.111,64.559 273.854,54.662 388.39,-25.684c36.362,43.135 89.921,68.005 146.348,67.988l102.653,-0l0,-205.305l-89.089,-0Z" style="fill:#b3b3b3;fill-rule:nonzero;"/><path d="M1288.65,206.647c-0,-0 379.681,-0 379.681,-0l-0,-205.306l-379.681,0c-192.2,0.221 -347.953,155.974 -348.174,348.191l-0,491.093c0.204,192.217 155.957,347.97 348.174,348.191l379.681,0l-0,-205.305l-379.681,-0c-78.87,-0.102 -142.784,-64.016 -142.869,-142.886l0,-173.577c44.901,20.286 93.622,30.743 142.886,30.692l379.664,-0l-0,-205.306l-379.681,0c-78.904,0 -142.886,-63.982 -142.886,-142.902c0,-78.904 63.982,-142.885 142.886,-142.885Z" style="fill:#b3b3b3;fill-rule:nonzero;"/><path d="M940.477,349.532c0.221,-192.217 155.974,-347.97 348.174,-348.191l379.681,0l-0,205.306l-379.681,-0l-0,-0c-78.904,-0 -142.886,63.981 -142.886,142.885l0,0.017c0,78.904 63.982,142.885 142.886,142.885l-0,0l379.681,0l-0,205.306l-379.681,-0c-192.2,-0.221 -347.953,-155.974 -348.174,-348.191l-0,-0.017Z" style="fill:#999;fill-rule:nonzero;"/><path d="M749.438,778.335l0,-778.335l-205.305,0l-0,981.92c-0,49.546 15.053,101.855 46.15,137.567c41.02,47.107 93.032,69.39 155.531,67.988l93.47,-0l0,-205.305l-89.089,-0l-0.757,-203.835Z" style="fill:#999;fill-rule:nonzero;"/></g><g><path d="M2656.77,10.991c-1.051,-3.536 -1.911,-7.263 -2.294,-10.322l-22.365,0c1.625,3.728 2.581,6.117 4.492,11.661l20.358,57.537c1.625,4.588 2.581,7.838 3.059,10.323l24.85,-0c0.478,-2.39 1.434,-5.639 3.059,-10.323l20.262,-57.537c2.39,-6.595 3.25,-8.794 4.588,-11.661l-22.461,0c-0.287,3.25 -0.956,5.926 -2.198,10.322l-13.859,45.973c-0.478,1.816 -0.669,2.39 -1.816,6.595c-1.051,-4.014 -1.051,-4.014 -1.816,-6.595l-13.859,-45.973Z" style="fill:#808080;fill-rule:nonzero;"/><path d="M2727.11,17.682c4.205,-0.478 7.933,-0.669 11.66,-0.669l3.823,-0l0,48.745c0,5.543 -0.191,10.035 -0.764,14.432l20.836,-0c-0.574,-4.683 -0.765,-8.698 -0.765,-14.432l0,-50.083c0,-6.308 0.191,-10.323 0.669,-15.388c-3.823,0.382 -5.066,0.382 -11.852,0.382l-12.138,0c-5.544,0 -8.029,-0.096 -11.469,-0.669l-0,17.682Z" style="fill:#808080;fill-rule:nonzero;"/></g></svg>

After

Width:  |  Height:  |  Size: 3.5 KiB

BIN
favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 66 KiB

52
lib/api/api.dart Normal file
View File

@ -0,0 +1,52 @@
import 'dart:convert';
import 'package:dio/dio.dart';
import 'package:starcitizen_doctor/common/conf.dart';
import 'package:starcitizen_doctor/data/app_placard_data.dart';
import 'package:starcitizen_doctor/data/app_version_data.dart';
import 'package:starcitizen_doctor/data/sc_localization_data.dart';
class Api {
static final dio =
Dio(BaseOptions(connectTimeout: const Duration(seconds: 10)));
static Future<AppVersionData> getAppVersion() async {
return AppVersionData.fromJson(
await getRepoJson("sc_doctor", "version.json"));
}
static Future<AppPlacardData> getAppPlacard() async {
return AppPlacardData.fromJson(
await getRepoJson("sc_doctor", "placard.json"));
}
static Future<Map<String, dynamic>> getAppReleaseDataByVersionName(
String version) async {
final r = await dio
.get("${AppConf.gitlabApiPath}/projects/152243/releases/$version");
return r.data;
}
static Future<List<ScLocalizationData>> getScLocalizationData(
String lang) async {
final data = json.decode(await getRepoData("localizations", "$lang.json"));
List<ScLocalizationData> l = [];
if (data is List) {
for (var element in data) {
l.add(ScLocalizationData.fromJson(element));
}
}
return l;
}
static Future<Map<String, dynamic>> getRepoJson(
String dir, String name) async {
final data = await getRepoData(dir, name);
return json.decode(data);
}
static Future getRepoData(String dir, String name) async {
final r = await dio.get("${AppConf.apiRepoPath}/$dir/$name");
return r.data;
}
}

212
lib/base/ui.dart Normal file
View File

@ -0,0 +1,212 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:starcitizen_doctor/main.dart';
import 'package:starcitizen_doctor/widgets/my_page_route.dart';
import 'package:window_manager/window_manager.dart';
import 'dart:ui' as ui;
import 'ui_model.dart';
export '../common/utils/base_utils.dart';
export '../widgets/widgets.dart';
export 'package:fluent_ui/fluent_ui.dart';
class BaseUIContainer extends ConsumerStatefulWidget {
final ConsumerState<BaseUIContainer> Function() uiCreate;
final dynamic Function() modelCreate;
const BaseUIContainer(
{Key? key, required this.uiCreate, required this.modelCreate})
: super(key: key);
@override
// ignore: no_logic_in_create_state
ConsumerState<BaseUIContainer> createState() => uiCreate();
Future push(BuildContext context) {
return Navigator.push(context, makeRoute(context, this));
}
// Future pushShowModalBottomSheet(BuildContext context) {
// return showModalBottomSheet(
// context: context,
// isScrollControlled: true,
// builder: (BuildContext context) {
// return this;
// },
// );
// }
///
FluentPageRoute makeRoute(
BuildContext context, BaseUIContainer baseUIContainer) {
return MyPageRoute(
builder: (BuildContext context) {
return baseUIContainer;
},
);
}
// Future pushAndRemoveUntil(BuildContext context) {
// return Navigator.pushAndRemoveUntil(context,
// MaterialPageRoute(builder: (BuildContext context) {
// return this;
// }), (_) => false);
// }
}
abstract class BaseUI<T extends BaseUIModel>
extends ConsumerState<BaseUIContainer> {
BaseUIModel? _needDisposeModel;
late final ChangeNotifierProvider<T> provider = bindUIModel();
// final GlobalKey<ScaffoldState> scaffoldState = GlobalKey();
// RefreshController? refreshController;
@override
Widget build(BuildContext context) {
// get model
final model = ref.watch(provider);
return buildBody(context, model)!;
}
String getUITitle(BuildContext context, T model);
Widget? buildBody(
BuildContext context,
T model,
);
Widget? getBottomNavigationBar(BuildContext context, T model) => null;
Color? getBackgroundColor(BuildContext context, T model) => null;
Widget? getFloatingActionButton(BuildContext context, T model) => null;
FloatingActionButtonLocation? getFloatingActionButtonLocation(
BuildContext context, T model) =>
null;
bool getDrawerEnableOpenDragGesture(BuildContext context, T model) => true;
Widget? getDrawer(BuildContext context, T model) => null;
Widget makeDefaultPage(BuildContext context, T model,
{Widget? titleRow,
List<Widget>? actions,
Widget? content,
bool automaticallyImplyLeading = true}) {
return NavigationView(
pane: NavigationPane(
size: const NavigationPaneSize(openWidth: 0),
),
appBar: NavigationAppBar(
automaticallyImplyLeading: automaticallyImplyLeading,
title: DragToMoveArea(
child: titleRow ??
Row(
children: [
Text(getUITitle(context, model)),
],
),
),
actions: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [...?actions, const WindowButtons()],
)),
paneBodyBuilder: (
PaneItem? item,
Widget? body,
) {
return SizedBox(
height: MediaQuery.of(context).size.height,
child: content ?? makeLoading(context),
);
},
);
}
@mustCallSuper
@override
void initState() {
dPrint("[base] <$runtimeType> UI Init");
super.initState();
}
@mustCallSuper
@override
void dispose() {
dPrint("[base] <$runtimeType> UI Disposed");
_needDisposeModel?.dispose();
_needDisposeModel = null;
super.dispose();
}
///
dismissKeyBoard() {
FocusManager.instance.primaryFocus?.unfocus();
}
Widget errorBody(BuildContext context, Widget? child, T model) {
if (model.uiErrorMsg.isNotEmpty) {
//
return InkWell(
child: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(
"Error",
style: Theme.of(context).textTheme.bodyLarge,
),
const SizedBox(
height: 6,
),
Text(model.uiErrorMsg),
],
)),
onTap: () async {
await model.onErrorReloadData();
},
);
}
if (child == null) return makeLoading(context);
return child;
}
// void updateStatusBarIconColor(BuildContext context) {
// SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle(
// statusBarBrightness: Theme.of(context).brightness,
// statusBarIconBrightness: getAndroidIconBrightness(context),
// ));
// }
ChangeNotifierProvider<T> bindUIModel() {
final createdModel = widget.modelCreate();
if (createdModel is T) {
_needDisposeModel = createdModel;
return ChangeNotifierProvider<T>((ref) {
return createdModel..context = context;
});
}
return createdModel;
}
// Widget pullToRefreshBody(
// {required BaseUIModel model, required Widget child}) {
// refreshController ??= RefreshController();
// return AppSmartRefresher(
// enablePullUp: false,
// controller: refreshController,
// onRefresh: () async {
// await model.reloadData();
// refreshController?.refreshCompleted();
// },
// child: child,
// );
// }
makeSvgColor(Color color, {BlendMode blendMode = BlendMode.color}) {
return ui.ColorFilter.mode(color, blendMode);
}
}

125
lib/base/ui_model.dart Normal file
View File

@ -0,0 +1,125 @@
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'ui.dart';
export '../common/utils/base_utils.dart';
export 'ui.dart';
class BaseUIModel extends ChangeNotifier {
String uiErrorMsg = "";
bool _isDisposed = false;
bool get mounted => !_isDisposed;
BuildContext? context;
BaseUIModel() {
initModel();
}
@mustCallSuper
void initModel() {
dPrint("[base] <$runtimeType> Model Init");
loadData();
}
@mustCallSuper
@override
void dispose() {
_isDisposed = true;
_childUIModels?.forEach((k, value) {
(value as BaseUIModel).dispose();
_childUIModels?[k] = null;
});
dPrint("[base] <$runtimeType> Model Disposed");
super.dispose();
}
Future loadData() async {}
Future reloadData() async {
return loadData();
}
Future onErrorReloadData() async {
return loadData();
}
@override
void notifyListeners() {
if (!mounted) return;
super.notifyListeners();
}
Future<T?> handleError<T>(Future<T> Function() requestFunc,
{bool showFullScreenError = false, String? errorOverride}) async {
uiErrorMsg = "";
if (mounted) notifyListeners();
try {
return await requestFunc();
} catch (e) {
dPrint("$runtimeType.handleError Error:$e");
String errorMsg = "Unknown Error";
// if (e is AppHttpResultData && stringIsNotEmpty(e.msg)) {
// errorMsg = e.msg!;
// return null;
// } else {
// errorMsg = e.toString();
// }
errorMsg = e.toString();
if (showFullScreenError) {
uiErrorMsg = errorMsg;
notifyListeners();
return null;
}
showToast(context!, errorOverride ?? errorMsg);
}
return null;
}
Map<dynamic, dynamic>? _childUIModels;
Map<dynamic, dynamic>? _childUIProviders;
BaseUIModel? onCreateChildUIModel(modelKey) => null;
dynamic _getChildUIModel(modelKey) {
_childUIModels ??= {};
final cachedModel = _childUIModels![modelKey];
if (cachedModel != null) {
return (cachedModel);
}
final newModel = onCreateChildUIModel(modelKey);
_childUIModels![modelKey] = newModel!;
return newModel;
}
ChangeNotifierProvider<M> getChildUIModelProviders<M extends BaseUIModel>(
modelKey) {
_childUIProviders ??= {};
if (_childUIProviders![modelKey] == null) {
_childUIProviders![modelKey] = ChangeNotifierProvider<M>((ref) {
final c = (_getChildUIModel(modelKey) as M);
return c..context = context;
});
}
return _childUIProviders![modelKey]!;
}
T? getCreatedChildUIModel<T extends BaseUIModel>(String modelKey) {
return _childUIModels?[modelKey] as T?;
}
Future<void> reloadAllChildModels() async {
if (_childUIModels == null) return;
final futureList = <Future>[];
for (var value in _childUIModels!.entries) {
futureList.add(value.value.reloadData());
}
await Future.wait(futureList);
notifyListeners();
}
dismissKeyBoard() {
FocusManager.instance.primaryFocus?.unfocus();
}
}

93
lib/common/conf.dart Normal file
View File

@ -0,0 +1,93 @@
import 'dart:io';
import 'package:device_info_plus/device_info_plus.dart';
import 'package:flutter_acrylic/flutter_acrylic.dart';
import 'package:hive/hive.dart';
import 'package:path_provider/path_provider.dart';
import 'package:starcitizen_doctor/api/api.dart';
import 'package:starcitizen_doctor/data/app_version_data.dart';
import 'package:window_manager/window_manager.dart';
import '../base/ui.dart';
class AppConf {
static const String appVersion = "2.9 Beta";
static const int appVersionCode = 12;
static const String appVersionDate = "2023-10-06";
static const String gitlabHomeUrl =
"https://jihulab.com/StarCitizenCN_Community/StarCitizenDoctor";
static const String gitlabLocalizationUrl =
"https://jihulab.com/StarCitizenCN_Community/LocalizationData";
static const String apiRepoPath =
"https://jihulab.com/StarCitizenCN_Community/api/-/raw/main/";
static const String gitlabApiPath = "https://jihulab.com/api/v4/";
static late final String applicationSupportDir;
static AppVersionData? networkVersionData;
static bool offlineMode = false;
static late final WindowsDeviceInfo windowsDeviceInfo;
static init() async {
WidgetsFlutterBinding.ensureInitialized();
/// init device info
DeviceInfoPlugin deviceInfo = DeviceInfoPlugin();
windowsDeviceInfo = await deviceInfo.windowsInfo;
/// init Data
applicationSupportDir =
(await getApplicationSupportDirectory()).absolute.path;
dPrint("applicationSupportDir == $applicationSupportDir");
try {
Hive.init("$applicationSupportDir/db");
await Hive.openBox("app_conf");
} catch (e) {
exit(1);
}
/// init windows
await windowManager.ensureInitialized();
windowManager.waitUntilReadyToShow().then((_) async {
await windowManager.setSize(const Size(1280, 820));
await windowManager.setMinimumSize(const Size(1280, 820));
await windowManager.center(animate: true);
await windowManager.setSkipTaskbar(false);
await windowManager.setTitleBarStyle(
TitleBarStyle.hidden,
windowButtonVisibility: false,
);
await windowManager.show();
await Window.initialize();
if (windowsDeviceInfo.productName.contains("Windows 11")) {
await Window.setEffect(
effect: WindowEffect.acrylic,
);
}
await Window.hideWindowControls();
});
await _checkUpdate();
}
static String getUpgradePath() {
return "${AppConf.applicationSupportDir}/._upgrade";
}
static Future<void> _checkUpdate() async {
// clean path
final dir = Directory(getUpgradePath());
if (await dir.exists()) {
dir.delete(recursive: true);
}
try {
networkVersionData = await Api.getAppVersion();
dPrint(
"lastVersion=${networkVersionData?.lastVersion} ${networkVersionData?.lastVersionCode}");
} catch (e) {
dPrint("_checkUpdate Error:$e");
}
}
}

View File

@ -0,0 +1,81 @@
import 'dart:convert';
import 'dart:io';
import '../utils/base_utils.dart';
class SCLoggerHelper {
static Future<String?> getLogFilePath() async {
Map<String, String> envVars = Platform.environment;
final appDataPath = envVars["appdata"];
if (appDataPath == null) {
return null;
}
final rsiLauncherPath = "$appDataPath\\rsilauncher";
dPrint("rsiLauncherPath:$rsiLauncherPath");
final jsonLogPath = "$rsiLauncherPath\\logs\\log.log";
return jsonLogPath;
}
static Future<String?> getShaderCachePath() async {
Map<String, String> envVars = Platform.environment;
final appDataPath = envVars["LOCALAPPDATA"];
if (appDataPath == null) {
return null;
}
final scCachePath = "$appDataPath\\Star Citizen";
dPrint("getShaderCachePath === $scCachePath");
return scCachePath;
}
static Future<List?> getLauncherLogList() async {
final jsonLogPath = await getLogFilePath();
if (jsonLogPath == null) return null;
var jsonString = utf8.decode(await File(jsonLogPath).readAsBytes());
if (jsonString.endsWith("\n")) {
jsonString = jsonString.substring(0, jsonString.length - 3);
}
if (jsonString.endsWith(" ")) {
jsonString = jsonString.substring(0, jsonString.length - 3);
}
if (jsonString.endsWith(",")) {
jsonString = jsonString.substring(0, jsonString.length - 3);
}
return json.decode("[$jsonString]");
}
static Future<List<String>> getGameInstallPath(List listData,
{bool checkExists = true,
List<String> withVersion = const ["LIVE"]}) async {
List<String> scInstallPaths = [];
for (var v in withVersion) {
for (var i = listData.length - 1; i > 0; i--) {
final m = listData[i];
final info = m["[browser][info] "];
if (info is String) {
String installPath = "";
if (info.contains("Installing Star Citizen $v")) {
installPath = "${info.split(" at ")[1]}\\$v";
}
if (info.contains("Launching Star Citizen $v from")) {
installPath = info
.replaceAll("Launching Star Citizen $v from (", "")
.replaceAll(")", "");
}
if (installPath.isNotEmpty && !scInstallPaths.contains(installPath)) {
if (!checkExists) {
dPrint("find installPath == $installPath");
scInstallPaths.add(installPath);
} else if (await File("$installPath/Bin64/StarCitizen.exe")
.exists()) {
dPrint("find installPath == $installPath");
scInstallPaths.add(installPath);
}
}
}
}
}
return scInstallPaths;
}
}

View File

@ -0,0 +1,173 @@
import 'dart:io';
import 'package:starcitizen_doctor/common/utils/base_utils.dart';
class SystemHelper {
static Future<bool> checkNvmePatchStatus() async {
try {
var result = await Process.run('powershell.exe', [
"Get-ItemProperty",
"-Path",
"\"HKLM:\\SYSTEM\\CurrentControlSet\\Services\\stornvme\\Parameters\\Device\"",
"-Name",
"\"ForcedPhysicalSectorSizeInBytes\""
]);
dPrint("checkNvmePatchStatus result ==== ${result.stdout}");
if (result.stderr == "" &&
result.stdout.toString().contains("{* 4095}")) {
return true;
} else {
return false;
}
} catch (e) {
return false;
}
}
static Future<String> addNvmePatch() async {
var result = await Process.run('powershell.exe', [
'New-ItemProperty',
"-Path",
"\"HKLM:\\SYSTEM\\CurrentControlSet\\Services\\stornvme\\Parameters\\Device\"",
"-Name",
"ForcedPhysicalSectorSizeInBytes",
"-PropertyType MultiString",
"-Force -Value",
"\"* 4095\""
]);
dPrint("nvme_PhysicalBytes result == ${result.stdout}");
return result.stderr;
}
static doRemoveNvmePath() async {
try {
var result = await Process.run('powershell.exe', [
"Clear-ItemProperty",
"-Path",
"\"HKLM:\\SYSTEM\\CurrentControlSet\\Services\\stornvme\\Parameters\\Device\"",
"-Name",
"\"ForcedPhysicalSectorSizeInBytes\""
]);
dPrint("doRemoveNvmePath result ==== ${result.stdout}");
if (result.stderr == "") {
return true;
} else {
return false;
}
} catch (e) {
return false;
}
}
/// RSI
static Future<String> getRSILauncherPath() async {
Map<String, String> envVars = Platform.environment;
final programDataPath = envVars["programdata"];
final rsiFilePath =
"$programDataPath\\Microsoft\\Windows\\Start Menu\\Programs\\Roberts Space Industries\\RSI Launcher.lnk";
final rsiLinkFile = File(rsiFilePath);
if (await rsiLinkFile.exists()) {
final r = await Process.run("powershell.exe", [
"(New-Object -ComObject WScript.Shell).CreateShortcut(\"$rsiFilePath\").targetpath"
]);
if (r.stdout.toString().contains("RSI Launcher.exe")) {
final start = r.stdout.toString().split("RSI Launcher.exe");
return "${start[0]}RSI Launcher.exe";
}
}
return "";
}
static killRSILauncher() async {
var psr = await Process.run(
"powershell", ["ps", "\"RSI Launcher\"", "|select -expand id"]);
if (psr.stderr == "") {
for (var value in (psr.stdout ?? "").toString().split("\n")) {
dPrint(value);
if (value != "") {
Process.killPid(int.parse(value));
}
}
}
}
static Future<List<String>> getPID(String name) async {
final r = await Process.run("powershell", ["(ps $name).Id"]);
return r.stdout.toString().trim().split("\n");
}
static checkAndLaunchRSILauncher(String path) async {
// check running and kill
await killRSILauncher();
// launch
final r = await Process.run("powershell", ["start", "\"$path\""]);
dPrint(path);
dPrint(r.stdout);
dPrint(r.stderr);
}
static Future<int> getSystemMemorySizeGB() async {
final r = await Process.run("powershell", [
"(Get-CimInstance Win32_PhysicalMemory | Measure-Object -Property capacity -Sum).sum /1gb"
]);
return int.tryParse(r.stdout.toString().trim()) ?? 0;
}
static Future<String> getSystemCimInstance(String win32InstanceName,
{pathName = "Name"}) async {
final r = await Process.run(
"powershell", ["(Get-CimInstance $win32InstanceName).$pathName"]);
return r.stdout.toString().trim();
}
static Future<String> getSystemName() async {
final r = await Process.run(
"powershell", ["(Get-ComputerInfo | Select-Object -expand OsName)"]);
return r.stdout.toString().trim();
}
static Future<String> getGpuInfo() async {
const cmd = r"""
$adapterMemory = (Get-ItemProperty -Path "HKLM:\SYSTEM\ControlSet001\Control\Class\{4d36e968-e325-11ce-bfc1-08002be10318}\0*" -Name "HardwareInformation.AdapterString", "HardwareInformation.qwMemorySize" -Exclude PSPath -ErrorAction SilentlyContinue)
foreach ($adapter in $adapterMemory) {
[PSCustomObject] @{
Model=$adapter."HardwareInformation.AdapterString"
"VRAM (GB)"=[math]::round($adapter."HardwareInformation.qwMemorySize"/1GB)
}
}
""";
final r = await Process.run("powershell", [cmd]);
return r.stdout.toString().trim();
}
static Future<String> getDiskInfo() async {
return (await Process.run("powershell",
["Get-PhysicalDisk | format-table BusType,FriendlyName,Size"]))
.stdout
.toString()
.trim();
}
static Future<int> getDirLen(String path, {List<String>? skipPath}) async {
if (path == "") return 0;
int totalSize = 0;
try {
final l = await Directory(path).list(recursive: true).toList();
for (var element in l) {
if (element is File) {
bool skip = false;
if (skipPath != null) {
for (var value in skipPath) {
if (element.absolute.path.startsWith(value)) {
skip = true;
break;
}
}
}
if (!skip) totalSize += await element.length();
}
}
} catch (_) {}
return totalSize;
}
}

View File

@ -0,0 +1,95 @@
import 'package:fluent_ui/fluent_ui.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/rendering.dart';
import 'dart:ui' as ui;
void dPrint(src) {
if (kDebugMode) {
print(src);
}
}
Future showToast(BuildContext context, String msg,
{BoxConstraints? constraints}) async {
return showBaseDialog(context,
title: "提示",
content: Text(msg),
actions: [
FilledButton(
child: const Padding(
padding: EdgeInsets.only(top: 2, bottom: 2, left: 8, right: 8),
child: Text('关闭'),
),
onPressed: () => Navigator.pop(context),
),
],
constraints: constraints);
}
Future<bool> showConfirmDialogs(
BuildContext context, String title, Widget content,
{String confirm = "确认",
String cancel = "取消",
BoxConstraints? constraints}) async {
final r = await showBaseDialog(context,
title: title,
content: content,
actions: [
if (confirm.isNotEmpty)
FilledButton(
child: Padding(
padding:
const EdgeInsets.only(top: 2, bottom: 2, left: 8, right: 8),
child: Text(confirm),
),
onPressed: () => Navigator.pop(context, true),
),
if (cancel.isNotEmpty)
Button(
child: Padding(
padding:
const EdgeInsets.only(top: 2, bottom: 2, left: 8, right: 8),
child: Text(cancel),
),
onPressed: () => Navigator.pop(context, false),
),
],
constraints: constraints);
return r == true;
}
Future showBaseDialog(BuildContext context,
{required String title,
required Widget content,
List<Widget>? actions,
BoxConstraints? constraints}) async {
return await showDialog(
context: context,
builder: (context) => ContentDialog(
title: Text(title),
content: content,
constraints: constraints ?? kDefaultContentDialogConstraints,
actions: actions,
),
);
}
bool stringIsNotEmpty(String? s) {
return s != null && (s.isNotEmpty);
}
Future<Uint8List?> widgetToPngImage(GlobalKey repaintBoundaryKey,
{double pixelRatio = 3.0}) async {
RenderRepaintBoundary? boundary = repaintBoundaryKey.currentContext
?.findRenderObject() as RenderRepaintBoundary?;
if (boundary == null) return null;
ui.Image image = await boundary.toImage(pixelRatio: pixelRatio);
ByteData? byteData = await image.toByteData(format: ui.ImageByteFormat.png);
if (byteData == null) return null;
var pngBytes = byteData.buffer.asUint8List();
return pngBytes;
}
double roundDoubleTo(double value, double precision) =>
(value * precision).round() / precision;

View File

@ -0,0 +1,48 @@
/// version : "255c1fd9-c49c-4031-8733-b38e5363d666"
/// title : "测试公告"
/// content : "星际公民诊断工具 V3 正在开发中..."
/// link : null
/// link_type : "external"
/// always_show : false
/// enable : true
class AppPlacardData {
AppPlacardData({
this.version,
this.title,
this.content,
this.link,
this.linkType,
this.alwaysShow,
this.enable,});
AppPlacardData.fromJson(dynamic json) {
version = json['version'];
title = json['title'];
content = json['content'];
link = json['link'];
linkType = json['link_type'];
alwaysShow = json['always_show'];
enable = json['enable'];
}
String? version;
String? title;
String? content;
dynamic link;
String? linkType;
bool? alwaysShow;
bool? enable;
Map<String, dynamic> toJson() {
final map = <String, dynamic>{};
map['version'] = version;
map['title'] = title;
map['content'] = content;
map['link'] = link;
map['link_type'] = linkType;
map['always_show'] = alwaysShow;
map['enable'] = enable;
return map;
}
}

View File

@ -0,0 +1,43 @@
/// lastVersion : "V2.5"
/// lastVersionCode : 8
/// lastBetaVersion : "V2.5"
/// lastBetaVersionCode : 8
/// minVersionCode : 7
/// minBetaVersionCode : 7
class AppVersionData {
AppVersionData({
this.lastVersion,
this.lastVersionCode,
this.lastBetaVersion,
this.lastBetaVersionCode,
this.minVersionCode,
this.minBetaVersionCode,});
AppVersionData.fromJson(dynamic json) {
lastVersion = json['lastVersion'];
lastVersionCode = json['lastVersionCode'];
lastBetaVersion = json['lastBetaVersion'];
lastBetaVersionCode = json['lastBetaVersionCode'];
minVersionCode = json['minVersionCode'];
minBetaVersionCode = json['minBetaVersionCode'];
}
String? lastVersion;
num? lastVersionCode;
String? lastBetaVersion;
num? lastBetaVersionCode;
num? minVersionCode;
num? minBetaVersionCode;
Map<String, dynamic> toJson() {
final map = <String, dynamic>{};
map['lastVersion'] = lastVersion;
map['lastVersionCode'] = lastVersionCode;
map['lastBetaVersion'] = lastBetaVersion;
map['lastBetaVersionCode'] = lastBetaVersionCode;
map['minVersionCode'] = minVersionCode;
map['minBetaVersionCode'] = minBetaVersionCode;
return map;
}
}

View File

@ -0,0 +1,43 @@
/// rsi : "0.2.11"
/// uex : "2.2"
/// addresses : "1.0"
/// concierge : "1.1"
/// hangar : "1.2"
/// orgs : "1.3"
class AppWebLocalizationVersionsData {
AppWebLocalizationVersionsData({
this.rsi,
this.uex,
this.addresses,
this.concierge,
this.hangar,
this.orgs,});
AppWebLocalizationVersionsData.fromJson(dynamic json) {
rsi = json['rsi'];
uex = json['uex'];
addresses = json['addresses'];
concierge = json['concierge'];
hangar = json['hangar'];
orgs = json['orgs'];
}
String? rsi;
String? uex;
String? addresses;
String? concierge;
String? hangar;
String? orgs;
Map<String, dynamic> toJson() {
final map = <String, dynamic>{};
map['rsi'] = rsi;
map['uex'] = uex;
map['addresses'] = addresses;
map['concierge'] = concierge;
map['hangar'] = hangar;
map['orgs'] = orgs;
return map;
}
}

View File

@ -0,0 +1,53 @@
/// key : "r_displayinfo"
/// name : "屏幕信息(展示帧率)"
/// info : "在屏幕右上角展示帧率,服务器信息等"
/// type : "int"
/// max : 4
/// min : 0
/// value : 0
/// group : "设置"
class GamePerformanceData {
GamePerformanceData({
this.key,
this.name,
this.info,
this.type,
this.max,
this.min,
this.value,
this.group,});
GamePerformanceData.fromJson(dynamic json) {
key = json['key'];
name = json['name'];
info = json['info'];
type = json['type'];
max = json['max'];
min = json['min'];
value = json['value'];
group = json['group'];
}
String? key;
String? name;
String? info;
String? type;
num? max;
num? min;
num? value;
String? group;
Map<String, dynamic> toJson() {
final map = <String, dynamic>{};
map['key'] = key;
map['name'] = name;
map['info'] = info;
map['type'] = type;
map['max'] = max;
map['min'] = min;
map['value'] = value;
map['group'] = group;
return map;
}
}

View File

@ -0,0 +1,38 @@
/// enable : false
/// versionName : "3.21.0(PU)_CN_V0"
/// updateAt : "2023-10-5: 10:15:00"
/// info : "简体中文汉化"
/// channel : "PTU"
class ScLocalizationData {
ScLocalizationData({
this.enable,
this.versionName,
this.updateAt,
this.info,
this.channel,});
ScLocalizationData.fromJson(dynamic json) {
enable = json['enable'];
versionName = json['versionName'];
updateAt = json['updateAt'];
info = json['info'];
channel = json['channel'];
}
bool? enable;
String? versionName;
String? updateAt;
String? info;
String? channel;
Map<String, dynamic> toJson() {
final map = <String, dynamic>{};
map['enable'] = enable;
map['versionName'] = versionName;
map['updateAt'] = updateAt;
map['info'] = info;
map['channel'] = channel;
return map;
}
}

44
lib/global_ui_model.dart Normal file
View File

@ -0,0 +1,44 @@
// ignore_for_file: use_build_context_synchronously
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'api/api.dart';
import 'base/ui_model.dart';
import 'common/conf.dart';
import 'ui/settings/upgrade_dialog_ui.dart';
import 'ui/settings/upgrade_dialog_ui_model.dart';
final globalUIModel = AppGlobalUIModel();
final globalUIModelProvider = ChangeNotifierProvider((ref) => globalUIModel);
class AppGlobalUIModel extends BaseUIModel {
Future<bool> checkUpdate(BuildContext context, {bool init = true}) async {
if (!init) {
try {
AppConf.networkVersionData = await Api.getAppVersion();
} catch (_) {}
}
await Future.delayed(const Duration(milliseconds: 100));
if (AppConf.networkVersionData == null) {
showToast(context,
"检查更新失败!请检查网络连接... \n进入离线模式.. \n\n请谨慎在离线模式中使用。 \n当前版本构建日期:${AppConf.appVersionDate}\n QQ群940696487");
return false;
}
if (((AppConf.networkVersionData?.lastVersionCode) ?? 0) >
AppConf.appVersionCode) {
// need update
final r = await showDialog(
dismissWithEsc: false,
context: context,
builder: (context) => BaseUIContainer(
uiCreate: () => UpgradeDialogUI(),
modelCreate: () => UpgradeDialogUIModel()));
if (r != true) {
showToast(context, "获取更新信息失败,请稍后重试。");
return false;
}
return true;
}
return false;
}
}

112
lib/main.dart Normal file
View File

@ -0,0 +1,112 @@
import 'package:desktop_webview_window/desktop_webview_window.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:starcitizen_doctor/base/ui_model.dart';
import 'package:starcitizen_doctor/common/conf.dart';
import 'package:starcitizen_doctor/ui/index_ui_model.dart';
import 'package:window_manager/window_manager.dart';
import 'global_ui_model.dart';
import 'ui/index_ui.dart';
void main(List<String> args) async {
if (runWebViewTitleBarWidget(args,
backgroundColor: const Color.fromRGBO(19, 36, 49, 1),
builder: _defaultWebviewTitleBar)) {
return;
}
await AppConf.init();
runApp(ProviderScope(
child: BaseUIContainer(
uiCreate: () => AppUI(),
modelCreate: () => globalUIModelProvider,
),
));
}
class AppUI extends BaseUI {
@override
Widget? buildBody(BuildContext context, BaseUIModel model) {
return FluentApp(
title: "StarCitizen Doctor",
restorationScopeId: "Doctor",
themeMode: ThemeMode.dark,
// theme: FluentThemeData(brightness: Brightness.light),
darkTheme: FluentThemeData(
brightness: Brightness.dark,
fontFamily: "SourceHanSansCN-Regular",
navigationPaneTheme: const NavigationPaneThemeData(
backgroundColor: Color.fromRGBO(19, 36, 49, .75),
),
menuColor: const Color.fromRGBO(18, 45, 66, .95),
micaBackgroundColor: const Color.fromRGBO(10, 49, 66, 1.0),
),
debugShowCheckedModeBanner: false,
home: BaseUIContainer(
uiCreate: () => IndexUI(), modelCreate: () => IndexUIModel()),
);
}
@override
String getUITitle(BuildContext context, BaseUIModel model) => "";
}
class WindowButtons extends StatelessWidget {
const WindowButtons({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
final FluentThemeData theme = FluentTheme.of(context);
return SizedBox(
width: 138,
height: 50,
child: WindowCaption(
brightness: theme.brightness,
backgroundColor: Colors.transparent,
),
);
}
}
Widget _defaultWebviewTitleBar(BuildContext context) {
final state = TitleBarWebViewState.of(context);
final controller = TitleBarWebViewController.of(context);
return FluentTheme(
data: FluentThemeData.dark(),
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
IconButton(
onPressed: !state.canGoBack ? null : controller.back,
icon: const Icon(FluentIcons.chevron_left),
),
const SizedBox(width: 12),
IconButton(
onPressed: !state.canGoForward ? null : controller.forward,
icon: const Icon(FluentIcons.chevron_right),
),
const SizedBox(width: 12),
if (state.isLoading)
IconButton(
onPressed: controller.stop,
icon: const Icon(FluentIcons.chrome_close),
)
else
IconButton(
onPressed: controller.reload,
icon: const Icon(FluentIcons.refresh),
),
const SizedBox(width: 12),
(state.isLoading)
? const SizedBox(
width: 24,
height: 24,
child: ProgressRing(),
)
: const SizedBox(width: 24),
const SizedBox(width: 12),
SelectableText("${state.url}"),
const Spacer()
],
));
}

152
lib/ui/about/about_ui.dart Normal file
View File

@ -0,0 +1,152 @@
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:starcitizen_doctor/base/ui.dart';
import 'package:starcitizen_doctor/common/conf.dart';
import 'package:starcitizen_doctor/global_ui_model.dart';
import 'package:url_launcher/url_launcher_string.dart';
import 'about_ui_model.dart';
class AboutUI extends BaseUI<AboutUIModel> {
bool isTipTextCn = false;
@override
Widget? buildBody(BuildContext context, AboutUIModel model) {
return Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const Spacer(),
const SizedBox(height: 64),
Image.asset("assets/app_logo.png", width: 64, height: 64),
const SizedBox(height: 6),
const Text(
"星际公民盒子 V${AppConf.appVersion}",
style: TextStyle(fontSize: 21),
),
const SizedBox(height: 12),
Button(
child: const Padding(
padding: EdgeInsets.all(4),
child: Text("检查更新"),
),
onPressed: () async {
final hasUpdate = await globalUIModel.checkUpdate(context);
if (!hasUpdate) {
if (mounted) showToast(context, "已是最新版本");
}
}),
const SizedBox(height: 32),
Container(
decoration: BoxDecoration(
color: FluentTheme.of(context).cardColor,
borderRadius: BorderRadius.circular(12)),
child: Padding(
padding: const EdgeInsets.all(24),
child: Text(
"不仅不仅是汉化!\n\n星际公民盒子是你探索宇宙的好帮手,我们致力于为各位公民解决游戏中的常见问题,并为社区汉化、性能调优、常用网站汉化 等操作提供便利。",
style: TextStyle(
fontSize: 14, color: Colors.white.withOpacity(.9)),
),
),
),
const SizedBox(height: 24),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
IconButton(
icon: Row(
children: [
const Icon(FontAwesomeIcons.qq),
const SizedBox(width: 6),
Text(
"反馈QQ群: 940696487",
style: TextStyle(
fontSize: 14, color: Colors.white.withOpacity(.6)),
),
],
),
onPressed: () {
launchUrlString(
"https://qm.qq.com/cgi-bin/qm/qr?k=TdyR3QU-x77OeD0NQ5w--F0uiNxPq-Tn&jump_from=webapi&authKey=m8s5GhF/7bRCvm5vI4aNl7RQEx5KOViwkzzIl54K+u9w2hzFpr9N/3avG4W/HaVS");
},
),
const SizedBox(width: 24),
IconButton(
icon: Row(
children: [
const Icon(FontAwesomeIcons.envelope),
const SizedBox(width: 6),
Text(
"邮箱: scbox@xkeyc.com",
style: TextStyle(
fontSize: 14, color: Colors.white.withOpacity(.6)),
),
],
),
onPressed: () {
launchUrlString("mailto:scbox@xkeyc.com");
},
),
const SizedBox(width: 24),
IconButton(
icon: Row(
children: [
const Icon(FontAwesomeIcons.gitlab),
const SizedBox(width: 6),
Text(
"开源",
style: TextStyle(
fontSize: 14, color: Colors.white.withOpacity(.6)),
),
],
),
onPressed: () {
launchUrlString(
"https://jihulab.com/StarCitizenCN_Community/StarCitizenDoctor");
},
),
],
),
const Spacer(),
Row(
children: [
const Spacer(),
Container(
width: MediaQuery.of(context).size.width * .35,
decoration: BoxDecoration(
color: FluentTheme.of(context).cardColor.withOpacity(.03),
borderRadius: BorderRadius.circular(12)),
child: IconButton(
icon: Padding(
padding: const EdgeInsets.all(3),
child: Text(
isTipTextCn ? tipTextCN : tipTextEN,
textAlign: TextAlign.start,
style: TextStyle(
fontSize: 12, color: Colors.white.withOpacity(.9)),
),
),
onPressed: () {
isTipTextCn = !isTipTextCn;
setState(() {});
},
),
),
const SizedBox(width: 12),
],
),
const SizedBox(height: 12),
],
),
);
}
static const tipTextEN =
"This is an unofficial Star Citizen fan-made tools, not affiliated with the Cloud Imperium group of companies. All content on this Software not authored by its host or users are property of their respective owners. \nStar Citizen®, Roberts Space Industries® and Cloud Imperium® are registered trademarks of Cloud Imperium Rights LLC.";
static const tipTextCN =
"这是一个非官方的星际公民工具,不隶属于 Cloud Imperium 公司集团。 本软件中非由其主机或用户创作的所有内容均为其各自所有者的财产。 \nStar Citizen®、Roberts Space Industries® 和 Cloud Imperium® 是 Cloud Imperium Rights LLC 的注册商标。";
@override
String getUITitle(BuildContext context, AboutUIModel model) => "";
}

View File

@ -0,0 +1,5 @@
import 'package:starcitizen_doctor/base/ui_model.dart';
class AboutUIModel extends BaseUIModel {
}

View File

@ -0,0 +1,42 @@
import 'package:flutter/material.dart' show Material;
import 'package:starcitizen_doctor/base/ui.dart';
import 'package:starcitizen_doctor/ui/home/dialogs/md_content_dialog_ui_model.dart';
class MDContentDialogUI extends BaseUI<MDContentDialogUIModel> {
@override
Widget? buildBody(BuildContext context, MDContentDialogUIModel model) {
return Material(
child: ContentDialog(
constraints: BoxConstraints(
maxWidth: MediaQuery.of(context).size.width * .6,
),
title: Text(getUITitle(context, model)),
content: model.data == null
? makeLoading(context)
: SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.only(left: 12, right: 12),
child: Column(
mainAxisSize: MainAxisSize.min,
children: makeMarkdownView(model.data ?? ""),
),
),
),
actions: [
FilledButton(
child: const Padding(
padding: EdgeInsets.only(left: 8, right: 8, top: 2, bottom: 2),
child: Text("关闭"),
),
onPressed: () {
Navigator.pop(context);
})
],
),
);
}
@override
String getUITitle(BuildContext context, MDContentDialogUIModel model) =>
model.title;
}

View File

@ -0,0 +1,19 @@
import 'package:dio/dio.dart';
import 'package:starcitizen_doctor/base/ui_model.dart';
class MDContentDialogUIModel extends BaseUIModel {
String title;
String url;
MDContentDialogUIModel(this.title, this.url);
String? data;
@override
Future loadData() async {
final r = await handleError(() => Dio().get(url));
if (r == null) return;
data = r.data;
notifyListeners();
}
}

513
lib/ui/home/home_ui.dart Normal file
View File

@ -0,0 +1,513 @@
import 'package:extended_image/extended_image.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:starcitizen_doctor/base/ui.dart';
import 'package:url_launcher/url_launcher_string.dart';
import 'home_ui_model.dart';
class HomeUI extends BaseUI<HomeUIModel> {
@override
Widget? buildBody(BuildContext context, HomeUIModel model) {
return Stack(
children: [
Center(
child: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
if (model.appPlacardData != null) ...[
InfoBar(
title: Text("${model.appPlacardData?.title}"),
content: Text("${model.appPlacardData?.content}"),
severity: InfoBarSeverity.info,
action: model.appPlacardData?.link == null
? null
: Button(
child: const Text('查看详情'),
onPressed: () => model.showPlacard(),
),
onClose: model.appPlacardData?.alwaysShow == true
? null
: () => model.closePlacard(),
),
const SizedBox(height: 12),
],
if (!model.isChecking &&
model.checkResult != null &&
model.checkResult!.isNotEmpty)
...makeResult(context, model)
else
...makeIndex(context, model)
],
),
),
),
if (model.isFixing)
Container(
decoration: BoxDecoration(
color: Colors.black.withAlpha(150),
),
child: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const ProgressRing(),
const SizedBox(height: 12),
Text(model.isFixingString.isNotEmpty
? model.isFixingString
: "正在处理..."),
],
),
),
)
],
);
}
List<Widget> makeIndex(BuildContext context, HomeUIModel model) {
final width = MediaQuery.of(context).size.width * .21;
return [
Stack(
children: [
Padding(
padding: const EdgeInsets.only(top: 64, bottom: 64),
child: Image.asset(
"assets/sc_logo.png",
height: 256,
width: MediaQuery.of(context).size.width,
fit: BoxFit.fitHeight,
),
),
Positioned(
top: 0,
right: 24,
child: Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
makeWebViewButton(model,
icon: SvgPicture.asset(
"assets/rsi.svg",
colorFilter: makeSvgColor(Colors.white),
height: 18,
),
name: "星际公民官网汉化",
webTitle: "星际公民官网汉化",
webURL: "https://robertsspaceindustries.com",
info: "罗伯茨航天工业公司,万物的起源",
useLocalization: true,
width: width),
const SizedBox(height: 12),
makeWebViewButton(model,
icon: Row(
children: [
SvgPicture.asset(
"assets/uex.svg",
height: 18,
),
const SizedBox(width: 12),
],
),
name: "UEX 汉化",
webTitle: "UEX 汉化",
webURL: "https://uexcorp.space",
info: "采矿、精炼、贸易计算器、价格、船信息",
useLocalization: true,
width: width),
const SizedBox(height: 12),
makeWebViewButton(model,
icon: Row(
children: [
ExtendedImage.network(
"https://www.erkul.games/assets/icons/icon-512x512.png",
height: 20,
),
const SizedBox(width: 12),
],
),
name: "DPSCalculator 汉化",
webTitle: "DPSCalculatorLIVE 汉化",
webURL: "https://www.erkul.games/live/calculator",
info: "在线改船,查询伤害数值和配件购买地点",
useLocalization: true,
width: width),
const SizedBox(height: 12),
makeWebViewButton(model,
icon: Row(
children: [
ExtendedImage.network(
"https://ccugame.app/assets/images/logo/logo.png",
height: 20,
),
const SizedBox(width: 12),
],
),
name: "CCUGame 网站汉化",
webTitle: "CCUGame 网站汉化",
webURL: "https://ccugame.app",
info: "资产管理和舰队规划,一定要理性消费.jpg",
useLocalization: true,
width: width),
],
),
),
Positioned(
left: 24,
bottom: 0,
child: Column(
children: [
makeADCard(context, model,
bgURl:
"https://i2.hdslb.com/bfs/face/7582c8d46fc03004f4f8032c667c0ea4dbbb1088.jpg",
title: "Anicat",
subtitle: "高质量星际公民资讯UP主",
jumpUrl: "https://space.bilibili.com/27976358/video"),
const SizedBox(height: 12),
makeADCard(context, model,
bgURl:
"https://citizenwiki.cn/images/f/f2/890Jump_beach.jpg.webp",
title: "星际公民中文百科",
subtitle: "探索宇宙的好伙伴",
jumpUrl: "https://citizenwiki.cn"),
],
))
],
),
const SizedBox(height: 24),
Padding(
padding: const EdgeInsets.only(left: 24, right: 24),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
const Text("安装位置:"),
const SizedBox(width: 6),
Expanded(
child: ComboBox<String>(
value: model.scInstalledPath,
items: [
const ComboBoxItem(
value: "not_install",
child: Text("未安装 或 安装失败"),
),
for (final path in model.scInstallPaths)
ComboBoxItem(
value: path,
child: Text(path),
)
],
onChanged: (v) {
model.scInstalledPath = v!;
model.notifyListeners();
},
),
),
const SizedBox(width: 12),
Button(
child: const Padding(
padding: EdgeInsets.all(8.0),
child: Icon(FluentIcons.folder_open),
),
onPressed: () => model.openDir(model.scInstalledPath)),
const SizedBox(width: 12),
Button(
onPressed: model.isChecking ? null : model.reScanPath,
child: const Padding(
padding: EdgeInsets.all(6),
child: Icon(FluentIcons.refresh),
),
),
],
),
),
const SizedBox(height: 8),
Text(model.lastScreenInfo, maxLines: 1),
const SizedBox(height: 32),
makeIndexActionLists(context, model),
const SizedBox(height: 32),
];
}
Widget makeIndexActionLists(BuildContext context, HomeUIModel model) {
final items = [
_HomeItemData("auto_check", "一键诊断", "一键诊断星际公民常见问题",
FluentIcons.auto_deploy_settings),
_HomeItemData(
"localization", "汉化管理", "快捷安装汉化资源", FluentIcons.locale_language),
_HomeItemData("performance", "性能优化", "调整引擎配置文件,优化游戏性能",
FluentIcons.process_meta_task),
];
return Padding(
padding: const EdgeInsets.all(24),
child: AlignedGridView.count(
crossAxisCount: 3,
mainAxisSpacing: 12,
crossAxisSpacing: 12,
itemCount: items.length,
shrinkWrap: true,
itemBuilder: (context, index) {
final item = items.elementAt(index);
return HoverButton(
onPressed: item.key == "auto_check" && model.isChecking
? null
: () => model.onMenuTap(item.key),
builder: (BuildContext context, Set<ButtonStates> states) {
return Container(
width: 300,
height: 120,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(12),
color: states.isHovering
? FluentTheme.of(context).cardColor.withOpacity(.1)
: FluentTheme.of(context).cardColor,
),
child: Padding(
padding: const EdgeInsets.all(12),
child: Row(
children: [
Container(
decoration: BoxDecoration(
color: Colors.white.withOpacity(.2),
borderRadius: BorderRadius.circular(1000)),
child: Padding(
padding: const EdgeInsets.all(8),
child: Icon(
item.icon,
size: 26,
),
),
),
const SizedBox(width: 24),
Expanded(
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
item.name,
style: const TextStyle(fontSize: 18),
),
const SizedBox(height: 4),
Text(item.infoString),
],
)),
const SizedBox(width: 12),
if (item.key == "auto_check" && model.isChecking)
const ProgressRing()
else
const Icon(
FluentIcons.chevron_right,
size: 16,
),
],
),
),
);
},
);
}),
);
}
List<Widget> makeResult(BuildContext context, HomeUIModel model) {
return [
const SizedBox(height: 24),
const Text(
"检测结果",
style: TextStyle(fontSize: 20),
),
const SizedBox(height: 6),
Text(model.lastScreenInfo, maxLines: 1),
const SizedBox(height: 24),
ListView.builder(
itemCount: model.checkResult!.length,
shrinkWrap: true,
itemBuilder: (BuildContext context, int index) {
final item = model.checkResult![index];
return makeResultItem(item, model);
},
),
Text(
"注意:本工具检测结果仅供参考,若您不理解以上操作,请提供截图给有经验的玩家!",
style: TextStyle(color: Colors.red, fontSize: 16),
),
const SizedBox(height: 64),
FilledButton(
onPressed: model.resetCheck,
child: const Padding(
padding: EdgeInsets.only(left: 8, right: 8, top: 4, bottom: 4),
child: Text('返回'),
),
),
const SizedBox(height: 38),
];
}
@override
String getUITitle(BuildContext context, HomeUIModel model) => "HOME";
Widget makeResultItem(MapEntry<String, String> item, HomeUIModel model) {
final errorNames = {
"unSupport_system":
MapEntry("不支持的操作系统,游戏可能无法运行", "请升级您的系统 (${item.value})"),
"no_live_path": MapEntry("安装目录缺少LIVE文件夹可能导致安装失败",
"点击修复为您创建 LIVE 文件夹,完成后重试安装。(${item.value})"),
"nvme_PhysicalBytes": MapEntry("新型 NVME 设备,与 RSI 启动器暂不兼容,可能导致安装失败",
"为注册表项添加 ForcedPhysicalSectorSizeInBytes 值 模拟旧设备。硬盘分区(${item.value})"),
"eac_file_miss": const MapEntry("EasyAntiCheat 文件丢失",
"未在 LIVE 文件夹找到 EasyAntiCheat 文件 或 文件不完整,请使用 RSI 启动器校验文件"),
"eac_not_install": const MapEntry("EasyAntiCheat 未安装",
"EasyAntiCheat 未安装,请点击修复为您一键安装。(在 EAC 完成首次启动前,本条目持续存在)"),
"cn_user_name":
const MapEntry("中文用户名!", "中文用户名可能会导致游戏启动/安装错误! 点击修复按钮查看修改教程!"),
"cn_install_path": MapEntry("中文安装路径!",
"中文安装路径!这可能会导致游戏 启动/安装 错误!(${item.value}请在RSI启动器更换安装路径。"),
"low_ram": MapEntry(
"物理内存过低", "您至少需要 16GB 的物理内存Memory才可运行此游戏。当前大小${item.value}"),
};
return ListTile(
title: Text(errorNames[item.key]?.key ?? item.key),
subtitle: Padding(
padding: const EdgeInsets.only(top: 4, bottom: 4),
child: Text("修复建议: ${errorNames[item.key]?.value ?? "暂无解决方法,请截图反馈"}"),
),
trailing: Button(
onPressed: (errorNames[item.key]?.value == null || model.isFixing)
? null
: () async {
await model.doFix(item);
model.isFixing = false;
model.notifyListeners();
},
child: const Padding(
padding: EdgeInsets.only(left: 8, right: 8),
child: Text("修复"),
),
),
);
}
Widget makeADCard(
BuildContext context,
HomeUIModel model, {
required String bgURl,
required String title,
required String subtitle,
required String jumpUrl,
}) {
final width = MediaQuery.of(context).size.width * .21;
return Container(
width: width,
height: 128,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(12),
color: FluentTheme.of(context).cardColor,
),
child: Stack(
children: [
ClipRRect(
borderRadius: BorderRadius.circular(12),
child: ExtendedImage.network(
bgURl,
fit: BoxFit.cover,
width: width,
),
),
Container(
width: width,
height: 128,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(12),
color: Colors.black.withOpacity(.7),
),
),
Positioned(
top: 0,
bottom: 0,
left: 0,
right: 0,
child: IconButton(
icon: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(
title,
style: const TextStyle(
fontSize: 24,
),
),
const SizedBox(height: 6),
Text(
subtitle,
style: TextStyle(
color: Colors.white.withOpacity(.8), fontSize: 14),
),
],
),
),
onPressed: () {
launchUrlString(jumpUrl);
},
),
)
],
),
);
}
Widget makeWebViewButton(HomeUIModel model,
{required Widget icon,
required String name,
required String webTitle,
required String webURL,
required bool useLocalization,
required double width,
String? info}) {
return Container(
width: width,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(12),
color: FluentTheme.of(context).cardColor,
),
child: Padding(
padding: const EdgeInsets.all(8.0),
child: IconButton(
icon: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
icon,
Text(
name,
style: const TextStyle(fontSize: 14),
),
],
),
if (info != null)
Padding(
padding: const EdgeInsets.only(top: 4),
child: Text(
info,
style: TextStyle(
fontSize: 12, color: Colors.white.withOpacity(.6)),
),
)
],
),
onPressed: () =>
model.goWebView(webTitle, webURL, useLocalization: true)),
),
);
}
}
class _HomeItemData {
String key;
_HomeItemData(this.key, this.name, this.infoString, this.icon);
String name;
String infoString;
IconData icon;
}

View File

@ -0,0 +1,410 @@
import 'dart:convert';
import 'dart:io';
import 'package:desktop_webview_window/desktop_webview_window.dart';
import 'package:hive/hive.dart';
import 'package:starcitizen_doctor/api/api.dart';
import 'package:starcitizen_doctor/base/ui_model.dart';
import 'package:starcitizen_doctor/common/conf.dart';
import 'package:starcitizen_doctor/common/helper/log_helper.dart';
import 'package:starcitizen_doctor/common/helper/system_helper.dart';
import 'package:starcitizen_doctor/data/app_placard_data.dart';
import 'package:starcitizen_doctor/ui/home/dialogs/md_content_dialog_ui.dart';
import 'package:starcitizen_doctor/ui/home/dialogs/md_content_dialog_ui_model.dart';
import 'package:starcitizen_doctor/ui/home/localization/localization_ui_model.dart';
import 'package:starcitizen_doctor/ui/home/performance/performance_ui_model.dart';
import 'package:starcitizen_doctor/ui/home/webview/webview.dart';
import 'package:starcitizen_doctor/ui/home/webview/webview_localization_capture_ui_model.dart';
import 'package:url_launcher/url_launcher_string.dart';
import 'localization/localization_ui.dart';
import 'performance/performance_ui.dart';
import 'webview/webview_localization_capture_ui.dart';
class HomeUIModel extends BaseUIModel {
var scInstalledPath = "not_install";
List<String> scInstallPaths = [];
String _lastScreenInfo = "";
String get lastScreenInfo => _lastScreenInfo;
bool isChecking = false;
bool isFixing = false;
String isFixingString = "";
set lastScreenInfo(String info) {
_lastScreenInfo = info;
notifyListeners();
}
List<MapEntry<String, String>>? checkResult;
final cnExp = RegExp(r"[^\x00-\xff]");
AppPlacardData? appPlacardData;
@override
Future loadData() async {
if (AppConf.networkVersionData == null) return;
try {
final r = await Api.getAppPlacard();
final box = await Hive.openBox("app_conf");
final version = box.get("close_placard", defaultValue: "");
if (r.enable != true) return;
if (r.alwaysShow != true && version == r.version) return;
appPlacardData = r;
notifyListeners();
} catch (e) {
dPrint(e);
}
}
@override
void initModel() {
reScanPath();
super.initModel();
}
Future<void> reScanPath() async {
scInstallPaths.clear();
scInstalledPath = "not_install";
lastScreenInfo = "正在扫描 ...";
try {
final listData = await SCLoggerHelper.getLauncherLogList();
if (listData == null) {
lastScreenInfo = "获取log失败";
return;
}
scInstallPaths = await SCLoggerHelper.getGameInstallPath(listData,
withVersion: ["LIVE", "PTU", "EPTU"], checkExists: true);
if (scInstallPaths.isNotEmpty) {
scInstalledPath = scInstallPaths.first;
}
lastScreenInfo = "扫描完毕,共找到 ${scInstallPaths.length} 个有效安装目录";
} catch (e) {
lastScreenInfo = "解析 log 文件失败!";
showToast(context!,
"解析 log 文件失败! \n请关闭游戏退出RSI启动器后重试若仍有问题请使用工具箱中的 RSI Launcher log 修复。");
}
}
VoidCallback? doCheck() {
if (isChecking) return null;
return () async {
isChecking = true;
lastScreenInfo = "正在分析...";
await _statCheck();
isChecking = false;
notifyListeners();
};
}
Future _statCheck() async {
checkResult = [];
await _checkPreInstall();
await _checkEAC();
// TODO for debug
// checkResult?.add(const MapEntry("unSupport_system", "android"));
// checkResult?.add(const MapEntry("nvme_PhysicalBytes", "c"));
// checkResult?.add(const MapEntry("no_live_path", ""));
if (checkResult!.isEmpty) {
checkResult = null;
lastScreenInfo = "分析完毕,没有发现问题";
} else {
lastScreenInfo = "分析完毕,发现 ${checkResult!.length} 个问题";
}
if (scInstalledPath == "not_install" && (checkResult?.isEmpty ?? true)) {
showToast(context!, "扫描完毕,没有发现问题,若仍然安装失败,请尝试使用工具箱中的 RSI启动器管理员模式。");
}
}
Future _checkEAC() async {
if (scInstalledPath == "not_install") return;
lastScreenInfo = "正在检查EAC";
final eacPath = "$scInstalledPath\\EasyAntiCheat";
final eacJsonPath = "$eacPath\\Settings.json";
if (!await Directory(eacPath).exists() ||
!await File(eacJsonPath).exists()) {
checkResult?.add(const MapEntry("eac_file_miss", ""));
return;
}
final eacJsonData = await File(eacJsonPath).readAsBytes();
final Map eacJson = json.decode(utf8.decode(eacJsonData));
final eacID = eacJson["productid"];
final eacDeploymentId = eacJson["deploymentid"];
if (eacID == null || eacDeploymentId == null) {
checkResult?.add(const MapEntry("eac_file_miss", ""));
return;
}
final eacFilePath =
"${Platform.environment["appdata"]}\\EasyAntiCheat\\$eacID\\$eacDeploymentId\\easyanticheat_wow64_x64.eac";
if (!await File(eacFilePath).exists()) {
checkResult?.add(MapEntry("eac_not_install", eacPath));
return;
}
}
Future _checkPreInstall() async {
lastScreenInfo = "正在检查:运行环境";
if (!(Platform.operatingSystemVersion.contains("Windows 10") ||
Platform.operatingSystemVersion.contains("Windows 11"))) {
checkResult
?.add(MapEntry("unSupport_system", Platform.operatingSystemVersion));
lastScreenInfo = "不支持的操作系统:${Platform.operatingSystemVersion}";
await showToast(context!, lastScreenInfo);
}
if (cnExp.hasMatch(await SCLoggerHelper.getLogFilePath() ?? "")) {
checkResult?.add(const MapEntry("cn_user_name", ""));
}
// RAM
final ramSize = await SystemHelper.getSystemMemorySizeGB();
if (ramSize < 16) {
checkResult?.add(MapEntry("low_ram", "$ramSize"));
}
lastScreenInfo = "正在检查:安装信息";
//
try {
final listData = await SCLoggerHelper.getGameInstallPath(
await SCLoggerHelper.getLauncherLogList() ?? []);
final p = [];
final checkedPath = [];
for (var installPath in listData) {
if (!checkedPath.contains(installPath)) {
if (cnExp.hasMatch(installPath)) {
checkResult?.add(MapEntry("cn_install_path", installPath));
}
if (scInstalledPath == "not_install") {
checkedPath.add(installPath);
if (!await Directory(installPath).exists()) {
checkResult?.add(MapEntry("no_live_path", installPath));
}
}
final tp = installPath.split(":")[0];
if (!p.contains(tp)) {
p.add(tp);
}
}
}
// call check
for (var element in p) {
var result = await Process.run('powershell', [
"(fsutil fsinfo sectorinfo $element: | Select-String 'PhysicalBytesPerSectorForPerformance').ToString().Split(':')[1].Trim()"
]);
dPrint(result.stdout);
if (result.stderr == "") {
final rs = result.stdout.toString();
final physicalBytesPerSectorForPerformance = (int.tryParse(rs) ?? 0);
if (physicalBytesPerSectorForPerformance > 4096) {
checkResult?.add(MapEntry("nvme_PhysicalBytes", element));
}
}
}
} catch (e) {
dPrint(e);
}
}
void resetCheck() {
checkResult = null;
reScanPath();
notifyListeners();
}
Future<void> doFix(MapEntry<String, String> item) async {
isFixing = true;
notifyListeners();
switch (item.key) {
case "unSupport_system":
showToast(context!, "若您的硬件达标,请尝试安装最新的 Windows 系统。");
return;
case "no_live_path":
try {
await Directory(item.value).create(recursive: true);
showToast(context!, "创建文件夹成功,请尝试继续下载游戏!");
checkResult?.remove(item);
notifyListeners();
} catch (e) {
showToast(context!, "创建文件夹失败,请尝试手动创建。\n目录:${item.value} \n错误:$e");
}
return;
case "nvme_PhysicalBytes":
final r = await SystemHelper.addNvmePatch();
if (r == "") {
showToast(context!,
"修复成功,请尝试重启后继续安装游戏! 若注册表修改操作导致其他软件出现兼容问题,请使用 工具 中的 NVME 注册表清理。");
checkResult?.remove(item);
notifyListeners();
} else {
showToast(context!, "修复失败,$r");
}
return;
case "eac_file_miss":
showToast(
context!, "未在 LIVE 文件夹找到 EasyAntiCheat 文件 或 文件不完整,请使用 RSI 启动器校验文件");
return;
case "eac_not_install":
final eacJsonPath = "${item.value}\\Settings.json";
final eacJsonData = await File(eacJsonPath).readAsBytes();
final Map eacJson = json.decode(utf8.decode(eacJsonData));
final eacID = eacJson["productid"];
try {
var result = await Process.run(
"${item.value}\\EasyAntiCheat_EOS_Setup.exe", ["install", eacID]);
dPrint("${item.value}\\EasyAntiCheat_EOS_Setup.exe install $eacID");
if (result.stderr == "") {
showToast(context!, "修复成功,请尝试启动游戏。(若问题无法解决,请使用工具箱的 《重装 EAC》");
checkResult?.remove(item);
notifyListeners();
} else {
showToast(context!, "修复失败,${result.stderr}");
}
} catch (e) {
showToast(context!, "修复失败,$e");
}
return;
case "cn_user_name":
showToast(context!, "即将跳转,教程来自互联网,请谨慎操作...");
await Future.delayed(const Duration(milliseconds: 300));
launchUrlString(
"https://btfy.eu.org/?q=5L+u5pS5d2luZG93c+eUqOaIt+WQjeS7juS4reaWh+WIsOiLseaWhw==");
return;
default:
showToast(context!, "该问题暂不支持自动处理,请提供截图寻求帮助");
return;
}
}
openDir(rsiLauncherInstalledPath) async {
await Process.run("powershell.exe",
["explorer.exe", "/select,\"$rsiLauncherInstalledPath\""]);
}
onMenuTap(String key) {
switch (key) {
case "auto_check":
doCheck()?.call();
return;
case "localization":
if (scInstalledPath == "not_install") {
showToast(context!, "该功能需要一个有效的安装位置");
return;
}
showDialog(
context: context!,
dismissWithEsc: false,
builder: (BuildContext context) {
return BaseUIContainer(
uiCreate: () => LocalizationUI(),
modelCreate: () => LocalizationUIModel(scInstalledPath));
});
return;
case "performance":
if (scInstalledPath == "not_install") {
showToast(context!, "该功能需要一个有效的安装位置");
return;
}
BaseUIContainer(
uiCreate: () => PerformanceUI(),
modelCreate: () => PerformanceUIModel(scInstalledPath))
.push(context!);
return;
}
}
showPlacard() {
switch (appPlacardData?.linkType) {
case "external":
launchUrlString(appPlacardData?.link);
return;
case "doc":
showDialog(
context: context!,
builder: (context) {
return BaseUIContainer(
uiCreate: () => MDContentDialogUI(),
modelCreate: () => MDContentDialogUIModel(
appPlacardData?.title ?? "公告详情", appPlacardData?.link));
});
return;
}
}
closePlacard() async {
final box = await Hive.openBox("app_conf");
await box.put("close_placard", appPlacardData?.version);
appPlacardData = null;
notifyListeners();
}
goWebView(String title, String url, {bool useLocalization = false}) async {
if (useLocalization) {
const tipVersion = 1;
final box = await Hive.openBox("app_conf");
final skip =
await box.get("skip_web_localization_tip_version", defaultValue: 0);
if (skip != tipVersion) {
final ok = await showConfirmDialogs(
context!,
"星际公民官网汉化",
const Text(
"该汉化功能移植自星际公民汉化组的 Tampermonkey 浏览器插件https://greasyfork.org/zh-CN/scripts/459084文本内容由星际公民汉化组进行更新。"
"\n\n移植后的脚本源代码随 StarCitizenDoctor 项目一起分发https://jihulab.com/StarCitizenCN_Community/StarCitizenDoctor"
"\n\n\n本插功能件仅供大致浏览使用,不对任何有关本功能产生的问题负责!在涉及账号操作前请注意确认网站的原本内容!"
"\n\n\n使用此功能登录账号时请确保您的 StarCitizenDoctor 是从可信任的来源下载。",
style: TextStyle(fontSize: 16),
),
constraints: BoxConstraints(
maxWidth: MediaQuery.of(context!).size.width * .6));
if (!ok) return;
await box.put("skip_web_localization_tip_version", tipVersion);
}
}
if (!await WebviewWindow.isWebviewAvailable()) {
showToast(context!, "需要安装 WebView2 Runtime");
launchUrlString(
"https://developer.microsoft.com/en-us/microsoft-edge/webview2/");
return;
}
final webViewModel = WebViewModel(context!);
if (useLocalization) {
isFixingString = "正在初始化汉化资源...";
isFixing = true;
notifyListeners();
try {
await webViewModel.initLocalization();
} catch (e) {
showToast(context!, "初始化网页汉化资源失败!$e");
}
isFixingString = "";
isFixing = false;
}
await webViewModel.initWebView(title: title);
if (await File(
"${AppConf.applicationSupportDir}\\webview_data\\enable_webview_localization_capture")
.exists()) {
webViewModel.enableCapture = true;
BaseUIContainer(
uiCreate: () => WebviewLocalizationCaptureUI(),
modelCreate: () =>
WebviewLocalizationCaptureUIModel(webViewModel))
.push(context!)
.then((_) {
webViewModel.enableCapture = false;
});
}
await webViewModel.launch(url);
notifyListeners();
}
}

View File

@ -0,0 +1,310 @@
import 'package:starcitizen_doctor/base/ui.dart';
import 'package:starcitizen_doctor/data/sc_localization_data.dart';
import 'localization_ui_model.dart';
class LocalizationUI extends BaseUI<LocalizationUIModel> {
@override
Widget? buildBody(BuildContext context, LocalizationUIModel model) {
return ContentDialog(
title: makeTitle(context, model),
constraints: BoxConstraints(
maxWidth: MediaQuery.of(context).size.width * .7,
minHeight: MediaQuery.of(context).size.height * .9),
content: Padding(
padding: const EdgeInsets.only(left: 12, right: 12, top: 12),
child: SingleChildScrollView(
child: Column(
children: [
AnimatedSize(
duration: const Duration(milliseconds: 130),
child: model.patchStatus?.key == true &&
model.patchStatus?.value == "游戏内置"
? Padding(
padding: const EdgeInsets.only(bottom: 12),
child: InfoBar(
title: const Text("警告"),
content: const Text(
"您正在使用游戏内置文本官方文本目前为机器翻译截至3.21.0),建议您在下方 [最新版本] 安装社区汉化。"),
severity: InfoBarSeverity.info,
style: InfoBarThemeData(decoration: (severity) {
return const BoxDecoration(
color: Color.fromRGBO(155, 7, 7, 1.0));
}, iconColor: (severity) {
return Colors.white;
}),
),
)
: SizedBox(
width: MediaQuery.of(context).size.width,
),
),
makeListContainer("汉化状态", [
if (model.patchStatus == null)
makeLoading(context)
else ...[
const SizedBox(height: 6),
Row(
children: [
Center(
child: Text(
"启用(${LocalizationUIModel.languageSupport[model.selectedLanguage]}"),
),
const Spacer(),
ToggleSwitch(
checked: model.patchStatus?.key == true,
onChanged: model.updateLangCfg,
)
],
),
const SizedBox(height: 12),
Row(
children: [
Text("已安装版本:${model.patchStatus?.value}"),
const Spacer(),
if (model.patchStatus?.value != "游戏内置")
Button(
onPressed: model.doDelIniFile(),
child: const Padding(
padding: EdgeInsets.all(4),
child: Icon(FluentIcons.delete),
)),
],
),
],
]),
makeListContainer("最新版本", [
if (model.apiLocalizationData == null)
makeLoading(context)
else if (model.apiLocalizationData!.isEmpty)
Center(
child: Text(
"该语言/版本 暂无可用汉化,敬请期待!",
style: TextStyle(
fontSize: 13, color: Colors.white.withOpacity(.8)),
),
)
else
for (final item in model.apiLocalizationData!.entries)
makeRemoteList(context, model, item),
]),
makeListContainer("自定义", [
if (model.customizeList == null)
makeLoading(context)
else if (model.customizeList!.isEmpty)
Center(
child: Text(
"请将 任意名称.ini 文件放入 Customize_ini 文件夹,即可使用此工具快捷安装 / 切换。",
style: TextStyle(
fontSize: 13, color: Colors.white.withOpacity(.8)),
),
)
else ...[
for (final file in model.customizeList!)
Row(
children: [
Text(
model.getCustomizeFileName(file),
),
const Spacer(),
if (model.workingVersion == file)
const Padding(
padding: EdgeInsets.only(right: 12),
child: ProgressRing(),
)
else
Button(
onPressed: model.doLocalInstall(file),
child: const Padding(
padding: EdgeInsets.only(
left: 8, right: 8, top: 4, bottom: 4),
child: Text("安装"),
))
],
)
],
], actions: [
Button(
onPressed: () => model.openDir(),
child: const Padding(
padding: EdgeInsets.all(4),
child: Icon(FluentIcons.folder_open),
)),
]),
const SizedBox(height: 12),
],
),
),
),
);
}
Widget makeRemoteList(BuildContext context, LocalizationUIModel model,
MapEntry<String, ScLocalizationData> item) {
final isWorking = model.workingVersion.isNotEmpty;
final isMineWorking = model.workingVersion == item.key;
final isInstalled = model.patchStatus?.value == item.key;
return Padding(
padding: const EdgeInsets.only(bottom: 12),
child: Column(
children: [
Row(
children: [
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
"${item.value.info}",
style: const TextStyle(fontSize: 19),
),
const SizedBox(height: 4),
Text(
"版本号:${item.value.versionName}",
style: TextStyle(color: Colors.white.withOpacity(.6)),
),
const SizedBox(height: 4),
Text(
"通道:${item.value.channel}",
style: TextStyle(color: Colors.white.withOpacity(.6)),
),
const SizedBox(height: 4),
Text(
"更新时间:${item.value.updateAt}",
style: TextStyle(color: Colors.white.withOpacity(.6)),
),
],
),
const Spacer(),
if (isMineWorking)
const Padding(
padding: EdgeInsets.only(right: 12),
child: ProgressRing(),
)
else
Button(
onPressed: ((item.value.enable == true &&
!isWorking &&
!isInstalled)
? model.doRemoteInstall(item.value)
: null),
child: Padding(
padding: const EdgeInsets.only(
left: 8, right: 8, top: 4, bottom: 4),
child: Text(isInstalled
? "已安装"
: ((item.value.enable ?? false) ? "安装" : "不可用")),
)),
],
),
const SizedBox(height: 6),
Container(
color: Colors.white.withOpacity(.05),
height: 1,
),
],
),
);
}
Widget makeListContainer(String title, List<Widget> children,
{List<Widget> actions = const []}) {
return Padding(
padding: const EdgeInsets.only(bottom: 12),
child: AnimatedSize(
duration: const Duration(milliseconds: 130),
child: Container(
decoration: BoxDecoration(
color: FluentTheme.of(context).cardColor,
borderRadius: BorderRadius.circular(7)),
child: Padding(
padding:
const EdgeInsets.only(top: 12, bottom: 12, left: 24, right: 24),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Text(
title,
style: const TextStyle(fontSize: 22),
),
const Spacer(),
if (actions.isNotEmpty) ...actions,
],
),
const SizedBox(
height: 6,
),
Container(
color: Colors.white.withOpacity(.1),
height: 1,
),
const SizedBox(height: 12),
...children
],
),
),
),
),
);
}
Widget makeTitle(BuildContext context, LocalizationUIModel model) {
return Row(
children: [
IconButton(
icon: const Icon(
FluentIcons.back,
size: 22,
),
onPressed: model.onBack()),
const SizedBox(width: 12),
Text(getUITitle(context, model)),
const SizedBox(width: 24),
Text(
model.scInstallPath,
style: const TextStyle(fontSize: 13),
),
const Spacer(),
SizedBox(
height: 36,
child: Row(
children: [
const Text(
"语言: ",
style: TextStyle(fontSize: 16),
),
ComboBox<String>(
value: model.selectedLanguage,
items: [
for (final lang
in LocalizationUIModel.languageSupport.entries)
ComboBoxItem(
value: lang.key,
child: Text(lang.value),
)
],
onChanged: model.workingVersion.isNotEmpty
? null
: (v) {
if (v == null) return;
model.selectLang(v);
},
)
],
),
),
const SizedBox(width: 12),
Button(
onPressed: model.doRefresh(),
child: const Padding(
padding: EdgeInsets.all(6),
child: Icon(FluentIcons.refresh),
)),
],
);
}
@override
String getUITitle(BuildContext context, LocalizationUIModel model) => "汉化管理";
}

View File

@ -0,0 +1,303 @@
import 'dart:async';
import 'dart:io';
import 'package:archive/archive_io.dart';
import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:starcitizen_doctor/api/api.dart';
import 'package:starcitizen_doctor/base/ui_model.dart';
import 'package:starcitizen_doctor/common/conf.dart';
import 'package:starcitizen_doctor/data/sc_localization_data.dart';
class LocalizationUIModel extends BaseUIModel {
final String scInstallPath;
static const languageSupport = {
"chinese_(simplified)": "简体中文",
"chinese_(traditional)": "繁體中文",
};
late String selectedLanguage;
Map<String, ScLocalizationData>? apiLocalizationData;
LocalizationUIModel(this.scInstallPath);
String workingVersion = "";
final downloadDir =
Directory("${AppConf.applicationSupportDir}\\Localizations");
late final customizeDir =
Directory("${downloadDir.absolute.path}\\Customize_ini");
late final scDataDir = Directory("$scInstallPath\\data");
late final cfgFile = File("${scDataDir.absolute.path}\\system.cfg");
MapEntry<bool, String>? patchStatus;
List<String>? customizeList;
StreamSubscription? customizeDirListenSub;
@override
void initModel() {
selectedLanguage = languageSupport.entries.first.key;
if (!customizeDir.existsSync()) {
customizeDir.createSync(recursive: true);
}
customizeDirListenSub = customizeDir.watch().listen((event) {
_scanCustomizeDir();
});
super.initModel();
}
@override
Future loadData() async {
await _updateStatus();
_scanCustomizeDir();
final l =
await handleError(() => Api.getScLocalizationData(selectedLanguage));
if (l != null) {
apiLocalizationData = {};
for (var element in l) {
final isPTU = !scInstallPath.contains("LIVE");
if (isPTU && element.channel == "PTU") {
apiLocalizationData![element.versionName ?? ""] = element;
} else if (!isPTU && element.channel == "PU") {
apiLocalizationData![element.versionName ?? ""] = element;
}
}
}
notifyListeners();
}
@override
dispose() {
customizeDirListenSub?.cancel();
super.dispose();
}
_scanCustomizeDir() {
final fileList = customizeDir.listSync();
customizeList = [];
for (var value in fileList) {
if (value is File && value.path.endsWith(".ini")) {
customizeList?.add(value.absolute.path);
}
}
notifyListeners();
}
String getCustomizeFileName(String path) {
return path.split("\\").last;
}
_updateStatus() async {
patchStatus = MapEntry(await getLangCfgEnableLang(lang: selectedLanguage),
await getInstalledIniVersion());
notifyListeners();
}
VoidCallback? onBack() {
if (workingVersion.isNotEmpty) return null;
return () {
Navigator.pop(context!);
};
}
void selectLang(String v) {
selectedLanguage = v;
apiLocalizationData = null;
notifyListeners();
reloadData();
}
VoidCallback? doRefresh() {
if (workingVersion.isNotEmpty) return null;
return () {
apiLocalizationData = null;
notifyListeners();
reloadData();
};
}
VoidCallback? doRemoteInstall(ScLocalizationData value) {
return () async {
final downloadUrl =
"${AppConf.gitlabLocalizationUrl}/-/archive/${value.versionName}/LocalizationData-${value.versionName}.tar.bz2";
final savePath =
File("${downloadDir.absolute.path}\\${value.versionName}.sclang");
try {
workingVersion = value.versionName!;
notifyListeners();
if (!await savePath.exists()) {
// download
dPrint("downloading file to $savePath");
await Dio().download(downloadUrl, savePath.absolute.path);
} else {
dPrint("use cache $savePath");
}
await Future.delayed(const Duration(milliseconds: 300));
// check file
final globalIni = await compute(_readArchive, savePath.absolute.path);
if (globalIni.isEmpty) {
throw "文件受损,请重新下载";
}
await _installFormString(globalIni, value.versionName ?? "");
} catch (e) {
await showToast(context!, "安装出错!\n\n $e");
if (await savePath.exists()) await savePath.delete();
}
workingVersion = "";
notifyListeners();
};
}
Future<bool> getLangCfgEnableLang({String lang = ""}) async {
if (!await cfgFile.exists()) return false;
final str = (await cfgFile.readAsString()).replaceAll(" ", "");
return str.contains("sys_languages=$lang") &&
str.contains("g_language=$lang");
}
Future<String> getInstalledIniVersion() async {
final iniFile = File(
"${scDataDir.absolute.path}\\Localization\\$selectedLanguage\\global.ini");
if (!await iniFile.exists()) return "游戏内置";
final iniStringSplit = (await iniFile.readAsString()).split("\n");
for (var i = iniStringSplit.length - 1; i > 0; i--) {
if (iniStringSplit[i]
.contains("_starcitizen_doctor_localization_version=")) {
final v = iniStringSplit[i]
.trim()
.split("_starcitizen_doctor_localization_version=")[1];
return v;
}
}
return "自定义文件";
}
_installFormString(StringBuffer globalIni, String versionName) async {
final iniFile = File(
"${scDataDir.absolute.path}\\Localization\\$selectedLanguage\\global.ini");
if (versionName.isNotEmpty) {
if (!globalIni.toString().endsWith("\n")) {
globalIni.write("\n");
}
globalIni.write("_starcitizen_doctor_localization_version=$versionName");
}
/// write cfg
if (await cfgFile.exists()) {}
/// write ini
if (await iniFile.exists()) {
await iniFile.delete();
}
await iniFile.create(recursive: true);
await iniFile.writeAsString("\uFEFF${globalIni.toString().trim()}",
flush: true);
await updateLangCfg(true);
await _updateStatus();
}
openDir() async {
showToast(context!,
"即将打开本地化文件夹,请将自定义的 任意名称.ini 文件放入 Customize_ini 文件夹。\n\n添加新文件后未显示请使用右上角刷新按钮。\n\n安装时请确保选择了正确的语言。");
await Process.run("powershell.exe",
["explorer.exe", "/select,\"${customizeDir.absolute.path}\"\\"]);
}
updateLangCfg(bool enable) async {
final status = await getLangCfgEnableLang(lang: selectedLanguage);
final exists = await cfgFile.exists();
if (status == enable) {
await _updateStatus();
return;
}
StringBuffer newStr = StringBuffer();
var str = <String>[];
if (exists) {
str = (await cfgFile.readAsString()).replaceAll(" ", "").split("\n");
}
if (enable) {
if (exists) {
for (var value in str) {
if (value.contains("sys_languages=")) {
value = "sys_languages=$selectedLanguage";
} else if (value.contains("g_language")) {
value = "g_language=$selectedLanguage";
}
if (value.trim().isNotEmpty) newStr.writeln(value);
}
}
if (!newStr.toString().contains("sys_languages=$selectedLanguage")) {
newStr.writeln("sys_languages=$selectedLanguage");
}
if (!newStr.toString().contains("g_language=$selectedLanguage")) {
newStr.writeln("g_language=$selectedLanguage");
}
} else {
if (exists) {
for (var value in str) {
if (value.contains("sys_languages=")) {
continue;
} else if (value.contains("g_language")) {
continue;
}
newStr.writeln(value);
}
}
}
if (exists) await cfgFile.delete(recursive: true);
await cfgFile.create(recursive: true);
await cfgFile.writeAsString(newStr.toString());
await _updateStatus();
notifyListeners();
}
VoidCallback? doDelIniFile() {
final iniFile = File(
"${scDataDir.absolute.path}\\Localization\\$selectedLanguage\\global.ini");
return () async {
if (await iniFile.exists()) await iniFile.delete();
await _updateStatus();
};
}
/// read locale active
static StringBuffer _readArchive(String savePath) {
final inputStream = InputFileStream(savePath);
final archive =
TarDecoder().decodeBytes(BZip2Decoder().decodeBuffer(inputStream));
StringBuffer globalIni = StringBuffer("");
for (var element in archive.files) {
if (element.name.contains("global.ini")) {
for (var value
in (element.rawContent?.readString() ?? "").split("\n")) {
final tv = value.trim();
if (tv.isNotEmpty) globalIni.writeln(tv);
}
}
}
archive.clear();
return globalIni;
}
VoidCallback? doLocalInstall(String filePath) {
if (workingVersion.isNotEmpty) return null;
return () async {
final f = File(filePath);
if (!await f.exists()) return;
workingVersion = filePath;
notifyListeners();
final str = await f.readAsString();
await _installFormString(
StringBuffer(str), "自定义_${getCustomizeFileName(filePath)}");
workingVersion = "";
notifyListeners();
};
}
}

View File

@ -0,0 +1,259 @@
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:starcitizen_doctor/base/ui.dart';
import 'package:starcitizen_doctor/data/game_performance_data.dart';
import 'performance_ui_model.dart';
class PerformanceUI extends BaseUI<PerformanceUIModel> {
@override
Widget? buildBody(BuildContext context, PerformanceUIModel model) {
var content = makeLoading(context);
if (model.performanceMap != null) {
content = Stack(
children: [
Padding(
padding: const EdgeInsets.only(top: 12, left: 12, right: 12),
child: Column(
children: [
Padding(
padding: const EdgeInsets.only(left: 24, right: 24),
child: Column(
children: [
if (model.showGraphicsPerformanceTip)
InfoBar(
title: const Text("图形优化提示"),
content: const Text(
"该功能对优化显卡瓶颈有很大帮助,但对 CPU 瓶颈可能起返效果,如果您显卡性能强劲,可以尝试使用更好的画质来获得更高的显卡利用率。",
),
onClose: () => model.closeTip(),
),
const SizedBox(height: 16),
Row(
children: [
Text(
"当前状态:${model.enabled ? "已应用" : "未应用"}",
style: const TextStyle(fontSize: 18),
),
const SizedBox(width: 32),
const Text(
"预设:",
style: TextStyle(fontSize: 18),
),
for (final item in const {
"low": "",
"medium": "",
"high": "",
"ultra": "超级"
}.entries)
Padding(
padding: const EdgeInsets.only(left: 6, right: 6),
child: Button(
child: Padding(
padding: const EdgeInsets.only(
top: 2, bottom: 2, left: 4, right: 4),
child: Text(item.value),
),
onPressed: () =>
model.onChangePreProfile(item.key)),
),
const Text("(预设只修改图形设置)"),
const Spacer(),
Button(
onPressed: () => model.refresh(),
child: const Padding(
padding: EdgeInsets.all(6),
child: Icon(FluentIcons.refresh),
),
),
const SizedBox(width: 12),
Button(
child: const Text(
" 恢复默认 ",
style: TextStyle(fontSize: 16),
),
onPressed: () => model.clean()),
const SizedBox(width: 24),
Button(
child: const Text(
"应用",
style: TextStyle(fontSize: 16),
),
onPressed: () => model.applyProfile(false)),
const SizedBox(width: 6),
Button(
child: const Text(
"应用并清理着色器(推荐)",
style: TextStyle(fontSize: 16),
),
onPressed: () => model.applyProfile(true)),
],
),
const SizedBox(height: 16),
],
),
),
Expanded(
child: MasonryGridView.count(
crossAxisCount: 2,
mainAxisSpacing: 1,
crossAxisSpacing: 1,
itemCount: model.performanceMap!.length,
itemBuilder: (context, index) {
return makeItemGroup(
model.performanceMap!.entries.elementAt(index));
},
)),
],
),
),
if (model.workingString.isNotEmpty)
Container(
decoration: BoxDecoration(
color: Colors.black.withAlpha(150),
),
child: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const ProgressRing(),
const SizedBox(height: 12),
Text(model.workingString),
],
),
),
)
],
);
}
return makeDefaultPage(context, model, content: content);
}
Widget makeItemGroup(MapEntry<String?, List<GamePerformanceData>> group) {
return Padding(
padding: const EdgeInsets.all(12),
child: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(12),
color: FluentTheme.of(context).cardColor,
),
child: Padding(
padding: const EdgeInsets.all(24),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
"${group.key}",
style: const TextStyle(fontSize: 20),
),
const SizedBox(height: 6),
Container(
color: FluentTheme.of(context).cardColor.withOpacity(.2),
height: 1),
const SizedBox(height: 6),
for (final item in group.value) makeItem(item)
],
),
),
),
);
}
Widget makeItem(GamePerformanceData item) {
return Padding(
padding: const EdgeInsets.only(top: 8, bottom: 8),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
"${item.name}",
style: const TextStyle(fontSize: 16),
),
const SizedBox(height: 12),
if (item.type == "int")
Column(
children: [
Row(
children: [
SizedBox(
width: 72,
child: TextFormBox(
key: UniqueKey(),
initialValue: "${item.value}",
onFieldSubmitted: (str) {
dPrint(str);
if (str.isEmpty) return;
final v = int.tryParse(str);
if (v != null &&
v < (item.max ?? 0) &&
v >= (item.min ?? 0)) {
item.value = v;
}
setState(() {});
},
onTapOutside: (e) {
setState(() {});
},
),
),
const SizedBox(width: 32),
SizedBox(
width: MediaQuery.of(context).size.width / 4,
child: Slider(
value: item.value?.toDouble() ?? 0,
min: item.min?.toDouble() ?? 0,
max: item.max?.toDouble() ?? 0,
onChanged: (double value) {
item.value = value.toInt();
setState(() {});
},
),
)
],
)
],
)
else if (item.type == "bool")
Column(
children: [
ToggleSwitch(
checked: item.value == 1,
onChanged: (bool value) {
item.value = value ? 1 : 0;
setState(() {});
},
)
],
),
if (item.info != null && item.info!.isNotEmpty) ...[
const SizedBox(height: 12),
Text(
"${item.info}",
style:
TextStyle(fontSize: 14, color: Colors.white.withOpacity(.6)),
),
],
const SizedBox(height: 12),
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
Text(
"${item.key} 最小值: ${item.min} / 最大值: ${item.max}",
style: TextStyle(color: Colors.white.withOpacity(.6)),
)
],
),
const SizedBox(height: 6),
Container(
color: FluentTheme.of(context).cardColor.withOpacity(.1),
height: 1),
],
),
);
}
@override
String getUITitle(BuildContext context, PerformanceUIModel model) =>
"性能优化 ${model.scPath}";
}

View File

@ -0,0 +1,184 @@
import 'dart:convert';
import 'dart:io';
import 'package:flutter/services.dart';
import 'package:hive/hive.dart';
import 'package:starcitizen_doctor/base/ui_model.dart';
import 'package:starcitizen_doctor/common/helper/log_helper.dart';
import 'package:starcitizen_doctor/data/game_performance_data.dart';
class PerformanceUIModel extends BaseUIModel {
String scPath;
PerformanceUIModel(this.scPath);
Map<String?, List<GamePerformanceData>>? performanceMap;
String workingString = "";
late final confFile = File("$scPath\\USER.cfg");
bool enabled = false;
bool showGraphicsPerformanceTip = false;
static const _graphicsPerformanceTipVersion = 1;
@override
Future loadData() async {
final String jsonString =
await rootBundle.loadString('assets/performance.json');
final list = json.decode(jsonString);
if (list is List) {
performanceMap = {};
for (var element in list) {
final item = GamePerformanceData.fromJson(element);
performanceMap?[item.group] ??= [];
performanceMap?[item.group]?.add(item);
}
}
if (await confFile.exists()) {
await _readConf();
} else {
enabled = false;
}
final box = await Hive.openBox("app_conf");
final v = box.get("close_graphics_performance_tip", defaultValue: -1);
showGraphicsPerformanceTip = v != _graphicsPerformanceTipVersion;
notifyListeners();
}
onChangePreProfile(String key) {
switch (key) {
case "low":
performanceMap?.forEach((key, v) {
if (key?.contains("图形") ?? false) {
for (var element in v) {
element.value = element.min;
}
}
});
break;
case "medium":
performanceMap?.forEach((key, v) {
if (key?.contains("图形") ?? false) {
for (var element in v) {
element.value = ((element.max ?? 0) ~/ 2);
}
}
});
break;
case "high":
performanceMap?.forEach((key, v) {
if (key?.contains("图形") ?? false) {
for (var element in v) {
element.value = ((element.max ?? 0) / 1.5).ceil();
}
}
});
break;
case "ultra":
performanceMap?.forEach((key, v) {
if (key?.contains("图形") ?? false) {
for (var element in v) {
element.value = element.max;
}
}
});
break;
}
notifyListeners();
}
applyProfile(bool cleanShader) async {
if (performanceMap == null) return;
workingString = "生成配置文件";
notifyListeners();
String conf = "";
for (var v in performanceMap!.entries) {
for (var c in v.value) {
conf = "$conf${c.key} = ${c.value}\n";
}
}
workingString = "写出配置文件";
notifyListeners();
if (await confFile.exists()) {
await confFile.delete();
}
await confFile.create();
await confFile.writeAsString(conf);
if (cleanShader) {
workingString = "清理着色器";
notifyListeners();
await _cleanShaderCache();
}
workingString = "完成...";
notifyListeners();
await await Future.delayed(const Duration(milliseconds: 300));
await reloadData();
workingString = "";
notifyListeners();
}
Future<void> _cleanShaderCache() async {
final gameShaderCachePath = await SCLoggerHelper.getShaderCachePath();
final l =
await Directory(gameShaderCachePath!).list(recursive: false).toList();
for (var value in l) {
if (value is Directory) {
if (!value.absolute.path.contains("Crashes")) {
await value.delete(recursive: true);
}
}
}
await Future.delayed(const Duration(milliseconds: 300));
showToast(context!, "清理着色器后首次进入游戏可能会出现卡顿,请耐心等待游戏初始化完毕。");
}
_readConf() async {
if (performanceMap == null) return;
enabled = true;
final confString = await confFile.readAsString();
for (var value in confString.split("\n")) {
final kv = value.split("=");
for (var m in performanceMap!.entries) {
for (var value in m.value) {
if (value.key == kv[0].trim()) {
final v = int.tryParse(kv[1].trim());
if (v != null) value.value = v;
}
}
}
}
notifyListeners();
}
clean() async {
workingString = "删除配置文件...";
notifyListeners();
if (await confFile.exists()) {
await confFile.delete(recursive: true);
}
workingString = "清理着色器";
notifyListeners();
await _cleanShaderCache();
workingString = "完成...";
await await Future.delayed(const Duration(milliseconds: 300));
await reloadData();
workingString = "";
notifyListeners();
}
refresh() async {
await reloadData();
}
closeTip() async {
final box = await Hive.openBox("app_conf");
await box.put(
"close_graphics_performance_tip", _graphicsPerformanceTipVersion);
loadData();
}
}

View File

@ -0,0 +1,204 @@
// ignore_for_file: use_build_context_synchronously
import 'dart:convert';
import 'package:desktop_webview_window/desktop_webview_window.dart';
import 'package:dio/dio.dart';
import 'package:flutter/services.dart';
import 'package:hive/hive.dart';
import 'package:starcitizen_doctor/common/conf.dart';
import 'package:starcitizen_doctor/data/app_web_localization_versions_data.dart';
import '../../../api/api.dart';
import '../../../base/ui.dart';
class WebViewModel {
late Webview webview;
final BuildContext context;
bool _isClosed = false;
bool get isClosed => _isClosed;
WebViewModel(this.context);
String url = "";
bool canGoBack = false;
final localizationResource = <String, dynamic>{};
var localizationScript = "";
bool enableCapture = false;
initWebView({String title = ""}) async {
try {
webview = await WebviewWindow.create(
configuration: CreateConfiguration(
windowWidth: 1920,
windowHeight: 1080,
userDataFolderWindows:
"${AppConf.applicationSupportDir}/webview_data",
title: title));
// webview.openDevToolsWindow();
webview.isNavigating.addListener(() async {
if (!webview.isNavigating.value && localizationResource.isNotEmpty) {
final uri = Uri.parse(url);
if (uri.host.contains("robertsspaceindustries.com")) {
// SC
dPrint("load script");
await Future.delayed(const Duration(milliseconds: 100));
await webview.evaluateJavaScript(localizationScript);
dPrint("update replaceWords");
final replaceWords = _getLocalizationResource("zh-CN");
const org = "https://robertsspaceindustries.com/orgs";
const citizens = "https://robertsspaceindustries.com/citizens";
const organization =
"https://robertsspaceindustries.com/account/organization";
const concierge =
"https://robertsspaceindustries.com/account/concierge";
const referral =
"https://robertsspaceindustries.com/account/referral-program";
const address =
"https://robertsspaceindustries.com/account/addresses";
const hangar = "https://robertsspaceindustries.com/account/pledges";
if (url.startsWith(org) ||
url.startsWith(citizens) ||
url.startsWith(organization)) {
replaceWords.add({"word": 'members', "replacement": '名成员'});
replaceWords.addAll(_getLocalizationResource("orgs"));
}
if (address.startsWith(address)) {
replaceWords.addAll(_getLocalizationResource("address"));
}
if (url.startsWith(referral)) {
replaceWords.addAll([
{"word": 'Total recruits: ', "replacement": '总邀请数:'},
{"word": 'Prospects ', "replacement": '未完成的邀请'},
{"word": 'Recruits', "replacement": '已完成的邀请'},
]);
}
if (url.startsWith(concierge)) {
replaceWords.addAll(_getLocalizationResource("concierge"));
}
if (url.startsWith(hangar)) {
replaceWords.addAll(_getLocalizationResource("hangar"));
}
await Future.delayed(const Duration(milliseconds: 100));
await webview.evaluateJavaScript(
"WebLocalizationUpdateReplaceWords(${json.encode(replaceWords)},$enableCapture)");
} else if (uri.host.contains("www.erkul.games") ||
uri.host.contains("uexcorp.space") ||
uri.host.contains("ccugame.app")) {
//
dPrint("load script");
await Future.delayed(const Duration(milliseconds: 100));
await webview.evaluateJavaScript(localizationScript);
dPrint("update replaceWords");
final replaceWords = _getLocalizationResource("UEX");
await webview.evaluateJavaScript(
"WebLocalizationUpdateReplaceWords(${json.encode(replaceWords)},$enableCapture)");
}
}
});
webview.addOnUrlRequestCallback((url) {
dPrint("OnUrlRequestCallback === $url");
this.url = url;
});
webview.onClose.whenComplete(() {
_isClosed = true;
});
} catch (e) {
showToast(context, "初始化失败:$e");
}
}
launch(String url) async {
webview.launch(url);
}
initLocalization() async {
localizationScript =
await rootBundle.loadString('assets/localization_web_script.js');
/// https://github.com/CxJuice/Uex_Chinese_Translate
// get versions
const hostUrl = "https://ch.citizenwiki.cn/json-files";
final v = AppWebLocalizationVersionsData.fromJson(
await _getJson("$hostUrl/versions.json"));
dPrint("AppWebLocalizationVersionsData === ${v.toJson()}");
localizationResource["zh-CN"] = await _getJson("$hostUrl/zh-CN-rsi.json",
cacheKey: "rsi", version: v.rsi);
localizationResource["concierge"] = await _getJson(
"$hostUrl/concierge.json",
cacheKey: "concierge",
version: v.concierge);
localizationResource["orgs"] =
await _getJson("$hostUrl/orgs.json", cacheKey: "orgs", version: v.orgs);
localizationResource["address"] = await _getJson("$hostUrl/addresses.json",
cacheKey: "addresses", version: v.addresses);
localizationResource["hangar"] = await _getJson("$hostUrl/hangar.json",
cacheKey: "hangar", version: v.hangar);
localizationResource["UEX"] = await _getJson("$hostUrl/zh-CN-uex.json",
cacheKey: "uex", version: v.uex);
}
List<Map<String, String>> _getLocalizationResource(String key) {
final List<Map<String, String>> localizations = [];
final dict = localizationResource[key]?["dict"];
if (dict is Map) {
for (var element in dict.entries) {
final k = element.key
.toString()
.trim()
.toLowerCase()
.replaceAll(RegExp("/\xa0/g"), ' ')
.replaceAll(RegExp("/s{2,}/g"), ' ');
localizations
.add({"word": k, "replacement": element.value.toString().trim()});
}
}
return localizations;
}
Future<Map> _getJson(String url,
{String cacheKey = "", String? version}) async {
final box = await Hive.openBox("web_localization_cache_data");
if (cacheKey.isNotEmpty) {
final localVersion = box.get("${cacheKey}_version}", defaultValue: "");
var data = box.get(cacheKey, defaultValue: {});
if (data is Map && data.isNotEmpty && localVersion == version) {
return data;
}
}
final startTime = DateTime.now();
final r = await Api.dio
.get(url, options: Options(responseType: ResponseType.plain));
final endTime = DateTime.now();
final data = json.decode(r.data);
if (cacheKey.isNotEmpty) {
dPrint(
"update $cacheKey v == $version time == ${(endTime.microsecondsSinceEpoch - startTime.microsecondsSinceEpoch) / 1000 / 1000}s");
await box.put(cacheKey, data);
await box.put("${cacheKey}_version}", version);
}
return data;
}
void addOnWebMessageReceivedCallback(OnWebMessageReceivedCallback callback) {
webview.addOnWebMessageReceivedCallback(callback);
}
void removeOnWebMessageReceivedCallback(
OnWebMessageReceivedCallback callback) {
webview.removeOnWebMessageReceivedCallback(callback);
}
}

View File

@ -0,0 +1,43 @@
import 'package:markdown_widget/config/all.dart';
import 'package:markdown_widget/widget/blocks/leaf/code_block.dart';
import 'package:markdown_widget/widget/markdown.dart';
import 'package:starcitizen_doctor/base/ui.dart';
import 'webview_localization_capture_ui_model.dart';
class WebviewLocalizationCaptureUI
extends BaseUI<WebviewLocalizationCaptureUIModel> {
@override
Widget? buildBody(
BuildContext context, WebviewLocalizationCaptureUIModel model) {
return makeDefaultPage(context, model,
content: model.data.isEmpty
? const Center(
child: Text("等待数据"),
)
: Column(
children: [
Expanded(
child: MarkdownWidget(
data: model.renderString,
config: MarkdownConfig(configs: [
const PreConfig(
decoration: BoxDecoration(
color: Color.fromRGBO(0, 0, 0, .4),
borderRadius: BorderRadius.all(Radius.circular(8.0)),
)),
]),
))
],
),
actions: [
IconButton(
icon: const Icon(FluentIcons.refresh), onPressed: model.doClean)
]);
}
@override
String getUITitle(
BuildContext context, WebviewLocalizationCaptureUIModel model) =>
"Webview 翻译捕获工具";
}

View File

@ -0,0 +1,53 @@
import 'dart:convert';
import 'package:starcitizen_doctor/base/ui_model.dart';
import 'package:starcitizen_doctor/ui/home/webview/webview.dart';
class WebviewLocalizationCaptureUIModel extends BaseUIModel {
final WebViewModel webViewModel;
WebviewLocalizationCaptureUIModel(this.webViewModel);
Map<String, dynamic> data = {};
Map<String, dynamic> oldData = {};
String renderString = "";
final jsonEncoder = const JsonEncoder.withIndent(' ');
@override
void initModel() {
webViewModel.addOnWebMessageReceivedCallback(_onMessage);
super.initModel();
}
@override
void dispose() {
webViewModel.removeOnWebMessageReceivedCallback(_onMessage);
super.dispose();
}
void _onMessage(String message) {
final map = json.decode(message);
if (map["action"] == "webview_localization_capture") {
dPrint(
"<WebviewLocalizationCaptureUIModel> webview_localization_capture message == $map");
if (!oldData.containsKey(map["key"])) {
data[map["key"].toString().trim().toLowerCase().replaceAll(" ", "_")] =
map["value"];
}
_updateRenderString();
}
}
_updateRenderString() {
renderString = "```json\n${jsonEncoder.convert(data)}\n```";
notifyListeners();
}
doClean() {
oldData.addAll(data);
data.clear();
_updateRenderString();
}
}

104
lib/ui/index_ui.dart Normal file
View File

@ -0,0 +1,104 @@
import 'package:starcitizen_doctor/base/ui_model.dart';
import 'package:starcitizen_doctor/common/conf.dart';
import 'package:starcitizen_doctor/main.dart';
import 'package:starcitizen_doctor/ui/about/about_ui.dart';
import 'package:starcitizen_doctor/ui/about/about_ui_model.dart';
import 'package:starcitizen_doctor/ui/home/home_ui.dart';
import 'package:starcitizen_doctor/ui/settings/settings_ui.dart';
import 'package:starcitizen_doctor/ui/settings/settings_ui_model.dart';
import 'package:starcitizen_doctor/ui/tools/tools_ui.dart';
import 'package:starcitizen_doctor/ui/tools/tools_ui_model.dart';
import 'package:window_manager/window_manager.dart';
import 'home/home_ui_model.dart';
import 'index_ui_model.dart';
class IndexUI extends BaseUI<IndexUIModel> {
@override
Widget? buildBody(BuildContext context, IndexUIModel model) {
return NavigationView(
appBar: NavigationAppBar(
automaticallyImplyLeading: false,
title: () {
return DragToMoveArea(
child: Align(
alignment: AlignmentDirectional.centerStart,
child: Row(
children: [
Image.asset("assets/app_logo.png", width: 24, height: 24),
const SizedBox(width: 12),
const Text("星际公民盒子 V${AppConf.appVersion}"),
],
),
),
);
}(),
actions: const Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [WindowButtons()],
)),
pane: NavigationPane(
selected: model.curIndex,
items: getNavigationPaneItems(model),
size: const NavigationPaneSize(openWidth: 160),
),
paneBodyBuilder: (item, child) {
// final name =
// item?.key is ValueKey ? (item!.key as ValueKey).value : null;
return FocusTraversalGroup(
key: ValueKey('body_${model.curIndex}'),
child: getPage(model),
);
},
);
}
Widget getPage(IndexUIModel model) {
switch (model.curIndex) {
case 0:
return BaseUIContainer(
uiCreate: () => HomeUI(),
modelCreate: () =>
model.getChildUIModelProviders<HomeUIModel>("home"));
case 1:
return BaseUIContainer(
uiCreate: () => ToolsUI(),
modelCreate: () =>
model.getChildUIModelProviders<ToolsUIModel>("tools"));
case 2:
return BaseUIContainer(
uiCreate: () => SettingUI(),
modelCreate: () =>
model.getChildUIModelProviders<SettingUIModel>("settings"));
case 3:
return BaseUIContainer(
uiCreate: () => AboutUI(),
modelCreate: () =>
model.getChildUIModelProviders<AboutUIModel>("about"));
}
return const SizedBox();
}
List<NavigationPaneItem> getNavigationPaneItems(IndexUIModel model) {
final menus = {
FluentIcons.home: "首页",
FluentIcons.toolbox: "工具",
FluentIcons.settings: "设置",
FluentIcons.info: "关于",
};
return [
for (final kv in menus.entries)
PaneItem(
icon: Icon(kv.key),
title: Text(kv.value),
body: const SizedBox.shrink(),
onTap: () {
model.onIndexMenuTap(kv.value);
},
),
];
}
@override
String getUITitle(BuildContext context, IndexUIModel model) => "";
}

View File

@ -0,0 +1,75 @@
import 'dart:io';
import 'package:starcitizen_doctor/base/ui_model.dart';
import 'package:starcitizen_doctor/global_ui_model.dart';
import 'package:starcitizen_doctor/ui/about/about_ui_model.dart';
import 'package:starcitizen_doctor/ui/home/home_ui_model.dart';
import 'package:starcitizen_doctor/ui/settings/settings_ui_model.dart';
import 'package:starcitizen_doctor/ui/tools/tools_ui_model.dart';
import 'package:url_launcher/url_launcher_string.dart';
class IndexUIModel extends BaseUIModel {
int curIndex = 0;
@override
void initModel() {
_checkRunTime();
Future.delayed(const Duration(milliseconds: 300))
.then((value) => globalUIModel.checkUpdate(context!));
super.initModel();
}
@override
BaseUIModel? onCreateChildUIModel(modelKey) {
switch (modelKey) {
case "home":
return HomeUIModel();
case "tools":
return ToolsUIModel();
case "settings":
return SettingUIModel();
case "about":
return AboutUIModel();
}
return null;
}
void onIndexMenuTap(String value) {
final index = {
"首页": 0,
"工具": 1,
"设置": 2,
"关于": 3,
};
curIndex = index[value] ?? 0;
switch (curIndex) {
case 0:
getCreatedChildUIModel("home")?.reloadData();
break;
case 1:
getCreatedChildUIModel("tools")?.reloadData();
break;
}
notifyListeners();
}
Future<void> _checkRunTime() async {
Future<void> onError() async {
await showToast(context!, "运行环境出错,请检查系统环境变量 PATH");
await launchUrlString(
"https://answers.microsoft.com/zh-hans/windows/forum/all/%E7%B3%BB%E7%BB%9F%E7%8E%AF%E5%A2%83%E5%8F%98/b88369e6-2620-4a77-b07a-d0af50894a07");
exit(0);
}
try {
var result = await Process.run('powershell.exe', ["echo", "ping"]);
if (result.stdout.toString().startsWith("ping")) {
dPrint("powershell check pass");
} else {
onError();
}
} catch (e) {
onError();
}
}
}

View File

@ -0,0 +1,14 @@
import 'package:starcitizen_doctor/base/ui.dart';
import 'package:starcitizen_doctor/ui/settings/settings_ui_model.dart';
class SettingUI extends BaseUI<SettingUIModel> {
@override
Widget? buildBody(BuildContext context, SettingUIModel model) {
return const Center(
child: Text("暂时没啥好设置的。"),
);
}
@override
String getUITitle(BuildContext context, SettingUIModel model) => "SettingUI";
}

View File

@ -0,0 +1,5 @@
import 'package:starcitizen_doctor/base/ui_model.dart';
class SettingUIModel extends BaseUIModel {
}

View File

@ -0,0 +1,85 @@
import 'package:flutter/material.dart' show Material;
import 'package:starcitizen_doctor/base/ui_model.dart';
import 'package:starcitizen_doctor/common/conf.dart';
import 'upgrade_dialog_ui_model.dart';
class UpgradeDialogUI extends BaseUI<UpgradeDialogUIModel> {
@override
Widget? buildBody(BuildContext context, UpgradeDialogUIModel model) {
return Material(
child: ContentDialog(
title: const Text("发现新版本"),
constraints:
BoxConstraints(maxWidth: MediaQuery.of(context).size.width * .55),
content: Column(
mainAxisSize: MainAxisSize.min,
children: [
Expanded(
child: SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.only(left: 24, right: 24),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
if (model.description == null) ...[
const Center(
child: Column(
children: [
ProgressRing(),
SizedBox(height: 16),
Text("正在获取新版本详情...")
],
),
)
] else
...makeMarkdownView(model.description!),
],
),
),
)),
if (model.isUpgrading) ...[
const SizedBox(height: 24),
Row(
children: [
Text(model.progress == 100
? "正在安装: "
: "正在下载: ${model.progress?.toStringAsFixed(2) ?? 0}% "),
Expanded(
child: ProgressBar(
value: model.progress == 100 ? null : model.progress,
)),
],
),
],
],
),
actions: model.isUpgrading
? null
: [
if (model.downloadUrl.isNotEmpty)
FilledButton(
onPressed: model.doUpgrade,
child: const Padding(
padding: EdgeInsets.only(
top: 4, bottom: 4, left: 8, right: 8),
child: Text("立即更新"),
)),
if (AppConf.appVersionCode <=
(AppConf.networkVersionData?.minVersionCode ?? 0))
Button(
onPressed: model.doCancel,
child: const Padding(
padding: EdgeInsets.only(
top: 4, bottom: 4, left: 8, right: 8),
child: Text("下次吧"),
)),
],
),
);
}
@override
String getUITitle(BuildContext context, UpgradeDialogUIModel model) => "";
}

View File

@ -0,0 +1,72 @@
import 'dart:io';
import 'package:dio/dio.dart';
import 'package:starcitizen_doctor/api/api.dart';
import 'package:starcitizen_doctor/base/ui_model.dart';
import 'package:starcitizen_doctor/common/conf.dart';
class UpgradeDialogUIModel extends BaseUIModel {
String? description;
String downloadUrl = "";
bool isUpgrading = false;
double? progress;
@override
Future loadData() async {
// get download url for gitlab release
try {
final r = await Api.getAppReleaseDataByVersionName(
AppConf.networkVersionData!.lastVersion!);
description = r["description"];
final assetsLinks = List.of(r["assets"]?["links"] ?? []);
for (var link in assetsLinks) {
if (link["name"].toString().contains("SETUP.exe")) {
downloadUrl = link["direct_asset_url"];
break;
}
}
notifyListeners();
} catch (e) {
Navigator.pop(context!, false);
}
}
doUpgrade() async {
isUpgrading = true;
notifyListeners();
final fileName = "${AppConf.getUpgradePath()}/next_SETUP.exe";
try {
await Dio().download(downloadUrl, fileName,
onReceiveProgress: (int count, int total) {
progress = (count / total) * 100;
notifyListeners();
});
} catch (_) {
isUpgrading = false;
progress = null;
showToast(context!, "下载失败,请尝试手动安装!");
notifyListeners();
}
try {
final r =
await (Process.run("powershell", ["start", fileName, "/SILENT"]));
if (r.stderr.toString().isNotEmpty) {
throw r.stderr;
}
exit(0);
} catch (_) {
isUpgrading = false;
progress = null;
showToast(context!, "运行失败,请尝试手动安装!");
Process.run("powershell.exe", ["explorer.exe", "/select,\"$fileName\""]);
notifyListeners();
}
}
void doCancel() {
Navigator.pop(context!, true);
}
}

View File

@ -0,0 +1,60 @@
import 'package:file_sizes/file_sizes.dart';
import 'package:starcitizen_doctor/base/ui.dart';
import 'downloader_dialog_ui_model.dart';
class DownloaderDialogUI extends BaseUI<DownloaderDialogUIModel> {
@override
Widget? buildBody(BuildContext context, DownloaderDialogUIModel model) {
return ContentDialog(
constraints:
BoxConstraints(maxWidth: MediaQuery.of(context).size.width * .54),
title: const Text("文件下载..."),
content: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Text("文件名:${model.fileName}"),
const SizedBox(height: 6),
Text("保存位置:${model.savePath}"),
const SizedBox(height: 6),
Text("线程数:${model.threadCount}"),
const SizedBox(height: 6),
Text(
"文件大小: ${FileSize.getSize(model.count ?? 0)} / ${FileSize.getSize(model.total ?? 0)}"),
const SizedBox(height: 6),
Text("下载速度: ${FileSize.getSize(model.speed?.toInt() ?? 0)}/s"),
const SizedBox(height: 12),
Row(
children: [
Text(getStatus(model)),
const SizedBox(width: 24),
Expanded(
child: ProgressBar(
value: model.progress == 100 ? null : model.progress,
)),
const SizedBox(width: 24),
],
),
],
),
actions: [
FilledButton(
child: const Padding(
padding: EdgeInsets.only(left: 8, right: 8, top: 2, bottom: 2),
child: Text("取消下载"),
),
onPressed: () => model.doCancel()),
],
);
}
@override
String getUITitle(BuildContext context, DownloaderDialogUIModel model) => "";
String getStatus(DownloaderDialogUIModel model) {
if (model.progress == null && !model.isInMerging) return "准备中...";
if (model.isInMerging) return "正在合并文件...";
return "${model.progress?.toStringAsFixed(2) ?? "0"}% ";
}
}

View File

@ -0,0 +1,100 @@
import 'dart:io';
import 'package:file_picker/file_picker.dart';
import 'package:hyper_thread_downloader/hyper_thread_downloader.dart';
import 'package:starcitizen_doctor/base/ui_model.dart';
class DownloaderDialogUIModel extends BaseUIModel {
final String fileName;
String savePath;
final String downloadUrl;
final bool showChangeSavePathDialog;
final int threadCount;
DownloaderDialogUIModel(this.fileName, this.savePath, this.downloadUrl,
{this.showChangeSavePathDialog = false, this.threadCount = 1});
final downloader = HyperDownload();
int? downloadTaskId;
bool isInMerging = false;
double? progress;
double? speed;
double? remainTime;
int? count;
int? total;
@override
void initModel() {
super.initModel();
_initDownload();
}
_initDownload() async {
if (showChangeSavePathDialog) {
final userSelect = await FilePicker.platform.saveFile(
initialDirectory: savePath,
fileName: fileName,
lockParentWindow: true);
if (userSelect == null) {
Navigator.pop(context!);
return;
}
final f = File(userSelect);
if (await f.exists()) {
await f.delete();
}
savePath = userSelect;
dPrint(savePath);
notifyListeners();
} else {
savePath = "$savePath/$fileName";
}
// start download
downloader.startDownload(
url: downloadUrl,
savePath: savePath,
threadCount: threadCount,
prepareWorking: (bool done) {},
workingMerge: (bool done) {
isInMerging = true;
progress = null;
notifyListeners();
},
downloadProgress: ({
required double progress,
required double speed,
required double remainTime,
required int count,
required int total,
}) {
this.progress = ((progress) * 100);
this.speed = speed;
this.remainTime = remainTime;
this.count = count;
this.total = total;
notifyListeners();
},
downloadComplete: () {
notifyListeners();
Navigator.pop(context!, savePath);
},
downloadFailed: (String reason) {
notifyListeners();
showToast(context!, "下载失败! $reason");
},
downloadTaskId: (int id) {
downloadTaskId = id;
},
downloadingLog: (String log) {});
}
doCancel() {
if (downloadTaskId != null) {
downloader.stopDownload(id: downloadTaskId!);
}
Navigator.pop(context!, "cancel");
}
}

235
lib/ui/tools/tools_ui.dart Normal file
View File

@ -0,0 +1,235 @@
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:starcitizen_doctor/base/ui.dart';
import 'tools_ui_model.dart';
class ToolsUI extends BaseUI<ToolsUIModel> {
@override
Widget? buildBody(BuildContext context, ToolsUIModel model) {
return Stack(
children: [
Column(
children: [
const SizedBox(height: 12),
Padding(
padding: const EdgeInsets.only(left: 22, right: 22),
child: Row(
children: [
Expanded(
child: Column(
children: [
makeGameLauncherPathSelect(context, model),
const SizedBox(height: 12),
makeGamePathSelect(context, model),
],
),
),
const SizedBox(width: 12),
Button(
onPressed: model.working ? null : model.loadData,
child: const Padding(
padding: EdgeInsets.only(
top: 32, bottom: 32, left: 12, right: 12),
child: Icon(FluentIcons.refresh),
),
),
],
),
),
const SizedBox(height: 12),
if (model.items.isEmpty)
const Expanded(
child: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
ProgressRing(),
SizedBox(height: 12),
Text("正在扫描..."),
],
),
),
)
else
Expanded(
child: SingleChildScrollView(
padding: const EdgeInsets.all(16),
child: AlignedGridView.count(
crossAxisCount: 3,
mainAxisSpacing: 12,
crossAxisSpacing: 12,
itemCount: model.items.length,
shrinkWrap: true,
itemBuilder: (context, index) {
final item = model.items[index];
return Container(
width: 300,
height: 200,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(12),
color: FluentTheme.of(context).cardColor,
),
child: Padding(
padding: const EdgeInsets.all(12),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Container(
decoration: BoxDecoration(
color: Colors.white.withOpacity(.2),
borderRadius:
BorderRadius.circular(1000)),
child: Padding(
padding: const EdgeInsets.all(8),
child: item.icon,
),
),
const SizedBox(width: 12),
Expanded(
child: Text(
item.name,
style: const TextStyle(fontSize: 16),
)),
const SizedBox(width: 12),
],
),
const SizedBox(height: 12),
Expanded(
child: Text(
item.infoString,
style: TextStyle(
fontSize: 14,
color: Colors.white.withOpacity(.6)),
)),
Row(
children: [
const Spacer(),
Button(
onPressed: model.working
? null
: item.onTap == null
? null
: () {
try {
item.onTap?.call();
} catch (e) {
showToast(
context, "处理失败!:$e");
}
},
child: const Padding(
padding: EdgeInsets.all(6),
child: Icon(FluentIcons.play),
),
),
],
)
],
),
),
);
},
),
),
)
],
),
if (model.working)
Container(
decoration: BoxDecoration(
color: Colors.black.withAlpha(150),
),
child: const Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
ProgressRing(),
SizedBox(height: 12),
Text("正在处理..."),
],
),
),
)
],
);
}
Widget makeGamePathSelect(BuildContext context, ToolsUIModel model) {
return Row(
mainAxisSize: MainAxisSize.min,
children: [
const Text("游戏安装位置: "),
const SizedBox(width: 6),
Expanded(
child: SizedBox(
height: 36,
child: ComboBox<String>(
value: model.scInstalledPath,
items: [
for (final path in model.scInstallPaths)
ComboBoxItem(
value: path,
child: Text(path),
)
],
onChanged: (v) {
model.loadData(skipPathScan: true);
model.scInstalledPath = v!;
model.notifyListeners();
},
),
),
),
const SizedBox(width: 8),
Button(
child: const Padding(
padding: EdgeInsets.all(8.0),
child: Icon(FluentIcons.folder_open),
),
onPressed: () => model.openDir(model.scInstalledPath))
],
);
}
Widget makeGameLauncherPathSelect(BuildContext context, ToolsUIModel model) {
return Row(
mainAxisSize: MainAxisSize.min,
children: [
const Text("RSI启动器位置"),
const SizedBox(width: 6),
Expanded(
child: SizedBox(
height: 36,
child: ComboBox<String>(
value: model.rsiLauncherInstalledPath,
items: [
for (final path in model.rsiLauncherInstallPaths)
ComboBoxItem(
value: path,
child: Text(path),
)
],
onChanged: (v) {
model.loadData(skipPathScan: true);
model.rsiLauncherInstalledPath = v!;
model.notifyListeners();
},
),
),
),
const SizedBox(width: 8),
Button(
child: const Padding(
padding: EdgeInsets.all(8.0),
child: Icon(FluentIcons.folder_open),
),
onPressed: () => model.openDir(model.rsiLauncherInstalledPath))
],
);
}
@override
String getUITitle(BuildContext context, ToolsUIModel model) => "ToolsUI";
}

View File

@ -0,0 +1,334 @@
import 'dart:convert';
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:starcitizen_doctor/base/ui_model.dart';
import 'package:starcitizen_doctor/common/helper/log_helper.dart';
import 'package:starcitizen_doctor/common/helper/system_helper.dart';
import 'package:starcitizen_doctor/ui/tools/downloader/downloader_dialog_ui_model.dart';
import 'downloader/downloader_dialog_ui.dart';
class ToolsUIModel extends BaseUIModel {
bool _working = false;
String scInstalledPath = "";
String rsiLauncherInstalledPath = "";
List<String> scInstallPaths = [];
List<String> rsiLauncherInstallPaths = [];
set working(bool b) {
_working = b;
notifyListeners();
}
bool get working => _working;
var items = <_ToolsItemData>[];
@override
Future loadData({bool skipPathScan = false}) async {
items.clear();
notifyListeners();
if (!skipPathScan) {
await reScanPath();
}
try {
final nvmePatchStatus = await SystemHelper.checkNvmePatchStatus();
final gameShaderCachePath = await SCLoggerHelper.getShaderCachePath();
double logPathLen = 0;
try {
logPathLen =
(await File(await SCLoggerHelper.getLogFilePath() ?? "").length()) /
1024 /
1024;
} catch (_) {}
items = [
_ToolsItemData(
"systeminfo",
"查看系统信息",
"查看系统关键信息,用于快速问诊 \n\n耗时操作,请耐心等待。",
const Icon(FluentIcons.system, size: 28),
onTap: _showSystemInfo,
),
_ToolsItemData(
"p4k_downloader",
"P4K 分流下载",
"使用星际公民中文百科提供的分流下载服务。 \n\n资源有限,请勿滥用。请确保您的硬盘拥有至少大于 200G 的可用空间。",
const Icon(FontAwesomeIcons.download, size: 28),
onTap: _downloadP4k,
),
_ToolsItemData(
"reinstall_eac",
"重装 EasyAntiCheat 反作弊",
"若您遇到 EAC 错误,且自动修复无效,请尝试使用此功能重装 EAC。",
const Icon(FluentIcons.game, size: 28),
onTap: _reinstallEAC,
),
_ToolsItemData(
"rsilauncher_admin_mode",
"RSI Launcher 管理员模式",
"在某些情况下 RSI启动器 无法正确获得管理员权限,您可尝试使用该功能以管理员模式运行启动器。",
const Icon(FluentIcons.admin, size: 28),
onTap: _adminRSILauncher,
),
_ToolsItemData(
"clean_shaders",
"清理着色器缓存",
"若游戏画面出现异常或版本更新后可使用本工具清理过期的着色器当大于500M时建议清理 \n\n缓存大小:${((await SystemHelper.getDirLen(gameShaderCachePath ?? "", skipPath: [
"$gameShaderCachePath\\Crashes"
])) / 1024 / 1024).toStringAsFixed(4)} MB",
const Icon(FontAwesomeIcons.shapes, size: 28),
onTap: _cleanShaderCache,
),
_ToolsItemData(
"rsilauncher_log_fix",
"RSI Launcher Log 修复",
"在某些情况下 RSI启动器 的 log 文件会损坏,导致无法完成问题扫描,使用此工具清理损坏的 log 文件。\n\n当前日志文件大小:${(logPathLen.toStringAsFixed(4))} MB",
const Icon(FontAwesomeIcons.bookBible, size: 28),
onTap: _rsiLogFix,
),
_ToolsItemData(
"rsilauncher_log_select",
"RSI Launcher Log 查看",
"打开 RSI启动器 Log文件 所在文件夹",
const Icon(FontAwesomeIcons.bookBible, size: 28),
onTap: _selectLog,
),
_ToolsItemData(
"remove_nvme_settings",
"移除 nvme 注册表补丁",
"若您使用 nvme 补丁出现问题,请运行此工具。(可能导致游戏 安装/更新 不可用。)\n\n当前补丁状态:${(nvmePatchStatus) ? "已安装" : "未安装"}",
const Icon(FluentIcons.hard_drive, size: 28),
onTap: nvmePatchStatus
? () async {
working = true;
await SystemHelper.doRemoveNvmePath();
working = false;
showToast(context!, "已移除,重启生效!");
loadData(skipPathScan: true);
}
: null,
),
_ToolsItemData(
"add_nvme_settings",
"写入 nvme 注册表补丁",
"手动写入NVM补丁该功能仅在您知道自己在作什么的情况下使用",
const Icon(FontAwesomeIcons.cashRegister, size: 28),
onTap: () async {
working = true;
final r = await SystemHelper.addNvmePatch();
if (r == "") {
showToast(context!,
"修复成功,请尝试重启后继续安装游戏! 若注册表修改操作导致其他软件出现兼容问题,请使用 工具 中的 NVME 注册表清理。");
notifyListeners();
} else {
showToast(context!, "修复失败,$r");
}
working = false;
loadData(skipPathScan: true);
},
),
];
} catch (e) {
showToast(context!, "初始化失败,请截图报告给开发者。$e");
}
notifyListeners();
}
Future<void> reScanPath() async {
scInstallPaths.clear();
rsiLauncherInstallPaths.clear();
scInstalledPath = "";
rsiLauncherInstalledPath = "";
try {
rsiLauncherInstalledPath = await SystemHelper.getRSILauncherPath();
rsiLauncherInstallPaths.add(rsiLauncherInstalledPath);
final listData = await SCLoggerHelper.getLauncherLogList();
if (listData == null) {
return;
}
scInstallPaths = await SCLoggerHelper.getGameInstallPath(listData,
checkExists: false, withVersion: ["LIVE", "PTU", "EPTU"]);
if (scInstallPaths.isNotEmpty) {
scInstalledPath = scInstallPaths.first;
}
} catch (e) {
showToast(context!, "解析 log 文件失败!\n请尝试使用 RSI Launcher log 修复 工具!");
}
notifyListeners();
if (rsiLauncherInstalledPath == "") {
showToast(context!,
"未找到 RSI 启动器,请尝试重新安装。 \n\n下载链接https://robertsspaceindustries.com/download");
}
if (scInstalledPath == "") {
showToast(context!, "未找到星际公民游戏安装位置,请至少完成一次游戏启动操作。");
}
}
/// EAC
Future<void> _reinstallEAC() async {
if (scInstalledPath.isEmpty) {
showToast(context!, "该功能需要一个有效的游戏安装目录");
return;
}
working = true;
try {
final eacPath = "$scInstalledPath\\EasyAntiCheat";
final eacJsonPath = "$eacPath\\Settings.json";
if (await File(eacJsonPath).exists()) {
Map<String, String> envVars = Platform.environment;
final eacJsonData = await File(eacJsonPath).readAsString();
final Map eacJson = json.decode(eacJsonData);
final eacID = eacJson["productid"];
if (eacID != null) {
final eacCacheDir =
Directory("${envVars["appdata"]}\\EasyAntiCheat\\$eacID");
if (await eacCacheDir.exists()) {
await eacCacheDir.delete(recursive: true);
}
}
}
final dir = Directory(eacPath);
if (await dir.exists()) {
await dir.delete(recursive: true);
}
final eacLauncher = File("$scInstalledPath\\StarCitizen_Launcher.exe");
if (await eacLauncher.exists()) {
await eacLauncher.delete(recursive: true);
}
showToast(context!,
"已为您移除 EAC 文件,接下来将为您打开 RSI 启动器,请您前往 SETTINGS -> VERIFY 重装 EAC。");
_adminRSILauncher();
} catch (e) {
showToast(context!, "出现错误:$e");
}
working = false;
loadData(skipPathScan: true);
}
Future<String> getSystemInfo() async {
return "系统:${await SystemHelper.getSystemName()}\n\n"
"处理器:${await SystemHelper.getSystemCimInstance("Win32_Processor")}\n\n"
"内存大小:${await SystemHelper.getSystemMemorySizeGB()}GB\n\n"
"显卡信息:\n${await SystemHelper.getGpuInfo()}\n\n"
"硬盘信息:\n${await SystemHelper.getDiskInfo()}\n\n";
}
/// RSI
Future _adminRSILauncher() async {
if (rsiLauncherInstalledPath == "") {
showToast(context!, "未找到 RSI 启动器目录,请您尝试手动操作。");
}
handleError(
() => SystemHelper.checkAndLaunchRSILauncher(rsiLauncherInstalledPath));
}
Future<void> _rsiLogFix() async {
working = true;
final path = await SCLoggerHelper.getLogFilePath();
if (!await File(path!).exists()) {
showToast(
context!, "日志文件不存在,请尝试进行一次游戏启动或游戏安装,并退出启动器,若无法解决问题,请尝试将启动器更新至最新版本!");
return;
}
try {
SystemHelper.killRSILauncher();
await File(path).delete(recursive: true);
showToast(context!, "清理完毕,请完成一次安装 / 游戏启动 操作。");
SystemHelper.checkAndLaunchRSILauncher(rsiLauncherInstalledPath);
} catch (_) {
showToast(context!, "清理失败,请手动移除,文件位置:$path");
}
working = false;
}
Future<void> _selectLog() async {
final path = await SCLoggerHelper.getLogFilePath();
if (path == null) return;
openDir(path);
}
openDir(path) async {
await Process.run("powershell.exe", ["explorer.exe", "/select,\"$path\""]);
}
Future _showSystemInfo() async {
working = true;
final systemInfo = await getSystemInfo();
showDialog<String>(
context: context!,
builder: (context) => ContentDialog(
title: const Text('系统信息'),
content: Text(systemInfo),
constraints: BoxConstraints(
maxWidth: MediaQuery.of(context).size.width * .65,
),
actions: [
FilledButton(
child: const Padding(
padding: EdgeInsets.only(top: 2, bottom: 2, left: 8, right: 8),
child: Text('关闭'),
),
onPressed: () => Navigator.pop(context),
),
],
),
);
working = false;
}
Future<void> _cleanShaderCache() async {
working = true;
final gameShaderCachePath = await SCLoggerHelper.getShaderCachePath();
final l =
await Directory(gameShaderCachePath!).list(recursive: false).toList();
for (var value in l) {
if (value is Directory) {
if (!value.absolute.path.contains("Crashes")) {
await value.delete(recursive: true);
}
}
}
loadData(skipPathScan: true);
working = false;
}
Future<void> _downloadP4k() async {
const downloadUrl = "https://r2test.citizenwiki.cn/Data.p4k";
final r = await showDialog(
context: context!,
dismissWithEsc: false,
builder: (context) {
return BaseUIContainer(
uiCreate: () => DownloaderDialogUI(),
modelCreate: () => DownloaderDialogUIModel(
"Data.p4k", scInstalledPath, downloadUrl,
showChangeSavePathDialog: true, threadCount: 10));
});
if (r != null) {
if (r == "cancel") {
return showToast(context!, "下载已取消,下载进度已保留,如果您无需恢复下载,请手动删除下载临时文件。");
}
showToast(context!, "下载完毕,文件已保存到:$r");
}
}
}
class _ToolsItemData {
String key;
_ToolsItemData(this.key, this.name, this.infoString, this.icon, {this.onTap});
String name;
String infoString;
Widget icon;
AsyncCallback? onTap;
}

View File

@ -0,0 +1,25 @@
import 'package:fluent_ui/fluent_ui.dart';
class MyPageRoute extends FluentPageRoute {
late final WidgetBuilder _builder;
MyPageRoute({required super.builder}) : _builder = builder;
@override
Widget buildPage(BuildContext context, Animation<double> animation,
Animation<double> secondaryAnimation) {
assert(debugCheckHasFluentTheme(context));
final result = _builder(context);
return Semantics(
scopesRoute: true,
explicitChildNodes: true,
child: EntrancePageTransition(
animation: CurvedAnimation(
parent: animation,
curve: FluentTheme.of(context).animationCurve,
),
child: result,
),
);
}
}

110
lib/widgets/widgets.dart Normal file
View File

@ -0,0 +1,110 @@
import 'package:extended_image/extended_image.dart';
import 'dart:ui' as ui;
import 'package:markdown_widget/config/all.dart';
import 'package:markdown_widget/widget/all.dart';
import 'package:starcitizen_doctor/common/conf.dart';
import 'package:url_launcher/url_launcher_string.dart';
import '../base/ui.dart';
Widget makeLoading(
BuildContext context, {
double? width,
}) {
width ??= 30;
return Center(
child: SizedBox(
width: width,
height: width,
// child: Lottie.asset("images/lottie/loading.zip", width: width),
child: const ProgressRing(),
),
);
}
Widget makeSafeAre(BuildContext context, {bool withKeyboard = true}) {
return SafeArea(
child: Column(
children: [
const SizedBox(height: 4),
if (withKeyboard)
SizedBox(
height: MediaQuery.of(context).viewInsets.bottom,
),
],
));
}
makeSvgColor(Color color) {
return ui.ColorFilter.mode(color, ui.BlendMode.srcIn);
}
bool isPadUI(BuildContext context) {
final size = MediaQuery.of(context).size;
return size.width >= size.height;
}
fastPadding(
{required double? all,
required Widget child,
double left = 0.0,
double top = 0.0,
double right = 0.0,
double bottom = 0.0}) {
return Padding(
padding: all != null
? EdgeInsets.all(all)
: EdgeInsets.only(left: left, top: top, right: right, bottom: bottom),
child: child);
}
List<Widget> makeMarkdownView(String description) {
return MarkdownGenerator(
config: MarkdownConfig(configs: [
LinkConfig(onTap: (url) {
if (url.startsWith("/")) {
url = "${AppConf.gitlabHomeUrl}/$url";
}
launchUrlString(url);
}),
ImgConfig(builder: (String url, Map<String, String> attributes) {
return ExtendedImage.network(
url,
loadStateChanged: (ExtendedImageState state) {
switch (state.extendedImageLoadState) {
case LoadState.loading:
return const Center(
child: Padding(
padding: EdgeInsets.all(8.0),
child: Column(
children: [
ProgressRing(),
SizedBox(
height: 12,
),
Text("加载图片...")
],
),
),
);
case LoadState.completed:
return ExtendedRawImage(
image: state.extendedImageInfo?.image,
);
case LoadState.failed:
return const Text("Loading Image error");
}
},
);
})
])).buildWidgets(description);
}
class NoScrollBehavior extends ScrollBehavior {
@override
Widget buildOverscrollIndicator(
BuildContext context, Widget child, ScrollableDetails details) {
return child;
}
}

106
pubspec.yaml Normal file
View File

@ -0,0 +1,106 @@
name: starcitizen_doctor
description: A new Flutter project.
# The following line prevents the package from being accidentally published to
# pub.dev using `flutter pub publish`. This is preferred for private packages.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev
# The following defines the version and build number for your application.
# A version number is three numbers separated by dots, like 1.2.43
# followed by an optional build number separated by a +.
# Both the version and the builder number may be overridden in flutter
# build by specifying --build-name and --build-number, respectively.
# In Android, build-name is used as versionName while build-number used as versionCode.
# Read more about Android versioning at https://developer.android.com/studio/publish/versioning
# In iOS, build-name is used as CFBundleShortVersionString while build-number is used as CFBundleVersion.
# Read more about iOS versioning at
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
# In Windows, build-name is used as the major, minor, and patch parts
# of the product and file versions while build-number is used as the build suffix.
version: 1.0.0+1
environment:
sdk: '>=3.0.0 <4.0.0'
# Dependencies specify other packages that your package needs in order to work.
# To automatically upgrade your package dependencies to the latest versions
# consider running `flutter pub upgrade --major-versions`. Alternatively,
# dependencies can be manually updated by changing the version numbers below to
# the latest version available on pub.dev. To see which dependencies have newer
# versions available, run `flutter pub outdated`.
dependencies:
flutter:
sdk: flutter
flutter_riverpod: ^2.3.6
window_manager: ^0.3.2
fluent_ui: ^4.7.4
flutter_staggered_grid_view: ^0.7.0
flutter_acrylic: ^1.1.0
url_launcher: ^6.1.10
font_awesome_flutter: ^10.5.0
cupertino_icons: ^1.0.2
hive: ^2.2.3
path_provider: ^2.1.1
dio: ^5.3.3
markdown_widget: ^2.2.0
extended_image: ^8.1.1
hyper_thread_downloader: ^1.0.5
device_info_plus: ^9.0.3
file_picker: ^5.5.0
file_sizes: ^1.0.6
desktop_webview_window: ^0.2.3
flutter_svg: ^2.0.7
archive: ^3.4.4
dev_dependencies:
flutter_test:
sdk: flutter
# The "flutter_lints" package below contains a set of recommended lints to
# encourage good coding practices. The lint set provided by the package is
# activated in the `analysis_options.yaml` file located at the root of your
# package. See that file for information about deactivating specific lint
# rules and activating additional ones.
flutter_lints: ^2.0.0
# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec
# The following section is specific to Flutter packages.
flutter:
# The following line ensures that the Material Icons font is
# included with your application, so that you can use the icons in
# the material Icons class.
uses-material-design: true
assets:
- assets/
# To add assets to your application, add an assets section, like this:
# assets:
# - images/a_dot_burr.jpeg
# - images/a_dot_ham.jpeg
# An image asset can refer to one or more resolution-specific "variants", see
# https://flutter.dev/assets-and-images/#resolution-aware
# For details regarding adding assets from package dependencies, see
# https://flutter.dev/assets-and-images/#from-packages
# To add custom fonts to your application, add a fonts section here,
# in this "flutter" section. Each entry in this list should have a
# "family" key with the font family name, and a "fonts" key with a
# list giving the asset and other descriptors for the font. For
# example:
fonts:
- family: SourceHanSansCN-Regular
fonts:
- asset: assets/SourceHanSansCN-Regular.otf
# style: italic
# - family: Trajan Pro
# fonts:
# - asset: fonts/TrajanPro.ttf
# - asset: fonts/TrajanPro_Bold.ttf
# weight: 700
#
# For details regarding fonts from package dependencies,
# see https://flutter.dev/custom-fonts/#from-packages

27
test/widget_test.dart Normal file
View File

@ -0,0 +1,27 @@
// This is a basic Flutter widget test.
//
// To perform an interaction with a widget in your test, use the WidgetTester
// utility in the flutter_test package. For example, you can send tap and scroll
// gestures. You can also use WidgetTester to find child widgets in the widget
// tree, read text, and verify that the values of widget properties are correct.
void main() {
// testWidgets('Counter increments smoke test', (WidgetTester tester) async {
// // Build our app and trigger a frame.
// await tester.pumpWidget(const MyApp());
//
// // Verify that our counter starts at 0.
// expect(find.text('0'), findsOneWidget);
// expect(find.text('1'), findsNothing);
//
// // Tap the '+' icon and trigger a frame.
// await tester.tap(find.byIcon(Icons.add));
// await tester.pump();
//
// // Verify that our counter has incremented.
// expect(find.text('0'), findsNothing);
// expect(find.text('1'), findsOneWidget);
// });
}

17
windows/.gitignore vendored Normal file
View File

@ -0,0 +1,17 @@
flutter/ephemeral/
# Visual Studio user-specific files.
*.suo
*.user
*.userosscache
*.sln.docstates
# Visual Studio build-related files.
x64/
x86/
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!*.[Cc]ache/

102
windows/CMakeLists.txt Normal file
View File

@ -0,0 +1,102 @@
# Project-level configuration.
cmake_minimum_required(VERSION 3.14)
project(starcitizen_doctor LANGUAGES CXX)
# The name of the executable created for the application. Change this to change
# the on-disk name of your application.
set(BINARY_NAME "starcitizen_doctor")
# Explicitly opt in to modern CMake behaviors to avoid warnings with recent
# versions of CMake.
cmake_policy(SET CMP0063 NEW)
# Define build configuration option.
get_property(IS_MULTICONFIG GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG)
if(IS_MULTICONFIG)
set(CMAKE_CONFIGURATION_TYPES "Debug;Profile;Release"
CACHE STRING "" FORCE)
else()
if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES)
set(CMAKE_BUILD_TYPE "Debug" CACHE
STRING "Flutter build mode" FORCE)
set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS
"Debug" "Profile" "Release")
endif()
endif()
# Define settings for the Profile build mode.
set(CMAKE_EXE_LINKER_FLAGS_PROFILE "${CMAKE_EXE_LINKER_FLAGS_RELEASE}")
set(CMAKE_SHARED_LINKER_FLAGS_PROFILE "${CMAKE_SHARED_LINKER_FLAGS_RELEASE}")
set(CMAKE_C_FLAGS_PROFILE "${CMAKE_C_FLAGS_RELEASE}")
set(CMAKE_CXX_FLAGS_PROFILE "${CMAKE_CXX_FLAGS_RELEASE}")
# Use Unicode for all projects.
add_definitions(-DUNICODE -D_UNICODE)
# Compilation settings that should be applied to most targets.
#
# Be cautious about adding new options here, as plugins use this function by
# default. In most cases, you should add new options to specific targets instead
# of modifying this function.
function(APPLY_STANDARD_SETTINGS TARGET)
target_compile_features(${TARGET} PUBLIC cxx_std_17)
target_compile_options(${TARGET} PRIVATE /W4 /WX /wd"4100")
target_compile_options(${TARGET} PRIVATE /EHsc)
target_compile_definitions(${TARGET} PRIVATE "_HAS_EXCEPTIONS=0")
target_compile_definitions(${TARGET} PRIVATE "$<$<CONFIG:Debug>:_DEBUG>")
endfunction()
# Flutter library and tool build rules.
set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter")
add_subdirectory(${FLUTTER_MANAGED_DIR})
# Application build; see runner/CMakeLists.txt.
add_subdirectory("runner")
# Generated plugin build rules, which manage building the plugins and adding
# them to the application.
include(flutter/generated_plugins.cmake)
# === Installation ===
# Support files are copied into place next to the executable, so that it can
# run in place. This is done instead of making a separate bundle (as on Linux)
# so that building and running from within Visual Studio will work.
set(BUILD_BUNDLE_DIR "$<TARGET_FILE_DIR:${BINARY_NAME}>")
# Make the "install" step default, as it's required to run.
set(CMAKE_VS_INCLUDE_INSTALL_TO_DEFAULT_BUILD 1)
if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT)
set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE)
endif()
set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data")
set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}")
install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}"
COMPONENT Runtime)
install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}"
COMPONENT Runtime)
install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}"
COMPONENT Runtime)
if(PLUGIN_BUNDLED_LIBRARIES)
install(FILES "${PLUGIN_BUNDLED_LIBRARIES}"
DESTINATION "${INSTALL_BUNDLE_LIB_DIR}"
COMPONENT Runtime)
endif()
# Fully re-copy the assets directory on each build to avoid having stale files
# from a previous install.
set(FLUTTER_ASSET_DIR_NAME "flutter_assets")
install(CODE "
file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\")
" COMPONENT Runtime)
install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}"
DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime)
# Install the AOT library on non-Debug builds only.
install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}"
CONFIGURATIONS Profile;Release
COMPONENT Runtime)

View File

@ -0,0 +1,104 @@
# This file controls Flutter-level build steps. It should not be edited.
cmake_minimum_required(VERSION 3.14)
set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral")
# Configuration provided via flutter tool.
include(${EPHEMERAL_DIR}/generated_config.cmake)
# TODO: Move the rest of this into files in ephemeral. See
# https://github.com/flutter/flutter/issues/57146.
set(WRAPPER_ROOT "${EPHEMERAL_DIR}/cpp_client_wrapper")
# === Flutter Library ===
set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/flutter_windows.dll")
# Published to parent scope for install step.
set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE)
set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE)
set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE)
set(AOT_LIBRARY "${PROJECT_DIR}/build/windows/app.so" PARENT_SCOPE)
list(APPEND FLUTTER_LIBRARY_HEADERS
"flutter_export.h"
"flutter_windows.h"
"flutter_messenger.h"
"flutter_plugin_registrar.h"
"flutter_texture_registrar.h"
)
list(TRANSFORM FLUTTER_LIBRARY_HEADERS PREPEND "${EPHEMERAL_DIR}/")
add_library(flutter INTERFACE)
target_include_directories(flutter INTERFACE
"${EPHEMERAL_DIR}"
)
target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}.lib")
add_dependencies(flutter flutter_assemble)
# === Wrapper ===
list(APPEND CPP_WRAPPER_SOURCES_CORE
"core_implementations.cc"
"standard_codec.cc"
)
list(TRANSFORM CPP_WRAPPER_SOURCES_CORE PREPEND "${WRAPPER_ROOT}/")
list(APPEND CPP_WRAPPER_SOURCES_PLUGIN
"plugin_registrar.cc"
)
list(TRANSFORM CPP_WRAPPER_SOURCES_PLUGIN PREPEND "${WRAPPER_ROOT}/")
list(APPEND CPP_WRAPPER_SOURCES_APP
"flutter_engine.cc"
"flutter_view_controller.cc"
)
list(TRANSFORM CPP_WRAPPER_SOURCES_APP PREPEND "${WRAPPER_ROOT}/")
# Wrapper sources needed for a plugin.
add_library(flutter_wrapper_plugin STATIC
${CPP_WRAPPER_SOURCES_CORE}
${CPP_WRAPPER_SOURCES_PLUGIN}
)
apply_standard_settings(flutter_wrapper_plugin)
set_target_properties(flutter_wrapper_plugin PROPERTIES
POSITION_INDEPENDENT_CODE ON)
set_target_properties(flutter_wrapper_plugin PROPERTIES
CXX_VISIBILITY_PRESET hidden)
target_link_libraries(flutter_wrapper_plugin PUBLIC flutter)
target_include_directories(flutter_wrapper_plugin PUBLIC
"${WRAPPER_ROOT}/include"
)
add_dependencies(flutter_wrapper_plugin flutter_assemble)
# Wrapper sources needed for the runner.
add_library(flutter_wrapper_app STATIC
${CPP_WRAPPER_SOURCES_CORE}
${CPP_WRAPPER_SOURCES_APP}
)
apply_standard_settings(flutter_wrapper_app)
target_link_libraries(flutter_wrapper_app PUBLIC flutter)
target_include_directories(flutter_wrapper_app PUBLIC
"${WRAPPER_ROOT}/include"
)
add_dependencies(flutter_wrapper_app flutter_assemble)
# === Flutter tool backend ===
# _phony_ is a non-existent file to force this command to run every time,
# since currently there's no way to get a full input/output list from the
# flutter tool.
set(PHONY_OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/_phony_")
set_source_files_properties("${PHONY_OUTPUT}" PROPERTIES SYMBOLIC TRUE)
add_custom_command(
OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS}
${CPP_WRAPPER_SOURCES_CORE} ${CPP_WRAPPER_SOURCES_PLUGIN}
${CPP_WRAPPER_SOURCES_APP}
${PHONY_OUTPUT}
COMMAND ${CMAKE_COMMAND} -E env
${FLUTTER_TOOL_ENVIRONMENT}
"${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.bat"
windows-x64 $<CONFIG>
VERBATIM
)
add_custom_target(flutter_assemble DEPENDS
"${FLUTTER_LIBRARY}"
${FLUTTER_LIBRARY_HEADERS}
${CPP_WRAPPER_SOURCES_CORE}
${CPP_WRAPPER_SOURCES_PLUGIN}
${CPP_WRAPPER_SOURCES_APP}
)

View File

@ -0,0 +1,26 @@
//
// Generated file. Do not edit.
//
// clang-format off
#include "generated_plugin_registrant.h"
#include <desktop_webview_window/desktop_webview_window_plugin.h>
#include <flutter_acrylic/flutter_acrylic_plugin.h>
#include <screen_retriever/screen_retriever_plugin.h>
#include <url_launcher_windows/url_launcher_windows.h>
#include <window_manager/window_manager_plugin.h>
void RegisterPlugins(flutter::PluginRegistry* registry) {
DesktopWebviewWindowPluginRegisterWithRegistrar(
registry->GetRegistrarForPlugin("DesktopWebviewWindowPlugin"));
FlutterAcrylicPluginRegisterWithRegistrar(
registry->GetRegistrarForPlugin("FlutterAcrylicPlugin"));
ScreenRetrieverPluginRegisterWithRegistrar(
registry->GetRegistrarForPlugin("ScreenRetrieverPlugin"));
UrlLauncherWindowsRegisterWithRegistrar(
registry->GetRegistrarForPlugin("UrlLauncherWindows"));
WindowManagerPluginRegisterWithRegistrar(
registry->GetRegistrarForPlugin("WindowManagerPlugin"));
}

View File

@ -0,0 +1,15 @@
//
// Generated file. Do not edit.
//
// clang-format off
#ifndef GENERATED_PLUGIN_REGISTRANT_
#define GENERATED_PLUGIN_REGISTRANT_
#include <flutter/plugin_registry.h>
// Registers Flutter plugins.
void RegisterPlugins(flutter::PluginRegistry* registry);
#endif // GENERATED_PLUGIN_REGISTRANT_

View File

@ -0,0 +1,28 @@
#
# Generated file, do not edit.
#
list(APPEND FLUTTER_PLUGIN_LIST
desktop_webview_window
flutter_acrylic
screen_retriever
url_launcher_windows
window_manager
)
list(APPEND FLUTTER_FFI_PLUGIN_LIST
)
set(PLUGIN_BUNDLED_LIBRARIES)
foreach(plugin ${FLUTTER_PLUGIN_LIST})
add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/windows plugins/${plugin})
target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin)
list(APPEND PLUGIN_BUNDLED_LIBRARIES $<TARGET_FILE:${plugin}_plugin>)
list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries})
endforeach(plugin)
foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST})
add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/windows plugins/${ffi_plugin})
list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries})
endforeach(ffi_plugin)

View File

@ -0,0 +1,43 @@
cmake_minimum_required(VERSION 3.14)
project(runner LANGUAGES CXX)
# Define the application target. To change its name, change BINARY_NAME in the
# top-level CMakeLists.txt, not the value here, or `flutter run` will no longer
# work.
#
# Any new source files that you add to the application should be added here.
add_executable(${BINARY_NAME} WIN32
"flutter_window.cpp"
"main.cpp"
"utils.cpp"
"win32_window.cpp"
"${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc"
"Runner.rc"
"runner.exe.manifest"
)
SET_TARGET_PROPERTIES(${BINARY_NAME} PROPERTIES LINK_FLAGS "/MANIFESTUAC:\"level='requireAdministrator' uiAccess='false'\" /SUBSYSTEM:WINDOWS")
# Apply the standard set of build settings. This can be removed for applications
# that need different build settings.
apply_standard_settings(${BINARY_NAME})
# Add preprocessor definitions for the build version.
target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION=\"${FLUTTER_VERSION}\"")
target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MAJOR=${FLUTTER_VERSION_MAJOR}")
target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MINOR=${FLUTTER_VERSION_MINOR}")
target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_PATCH=${FLUTTER_VERSION_PATCH}")
target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_BUILD=${FLUTTER_VERSION_BUILD}")
# Disable Windows macros that collide with C++ standard library functions.
target_compile_definitions(${BINARY_NAME} PRIVATE "NOMINMAX")
# Add dependency libraries and include directories. Add any application-specific
# dependencies here.
target_link_libraries(${BINARY_NAME} PRIVATE flutter flutter_wrapper_app)
target_link_libraries(${BINARY_NAME} PRIVATE "dwmapi.lib")
target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}")
# Run the Flutter tool portions of the build. This must not be removed.
add_dependencies(${BINARY_NAME} flutter_assemble)

121
windows/runner/Runner.rc Normal file
View File

@ -0,0 +1,121 @@
// Microsoft Visual C++ generated resource script.
//
#pragma code_page(65001)
#include "resource.h"
#define APSTUDIO_READONLY_SYMBOLS
/////////////////////////////////////////////////////////////////////////////
//
// Generated from the TEXTINCLUDE 2 resource.
//
#include "winres.h"
/////////////////////////////////////////////////////////////////////////////
#undef APSTUDIO_READONLY_SYMBOLS
/////////////////////////////////////////////////////////////////////////////
// English (United States) resources
#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)
LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US
#ifdef APSTUDIO_INVOKED
/////////////////////////////////////////////////////////////////////////////
//
// TEXTINCLUDE
//
1 TEXTINCLUDE
BEGIN
"resource.h\0"
END
2 TEXTINCLUDE
BEGIN
"#include ""winres.h""\r\n"
"\0"
END
3 TEXTINCLUDE
BEGIN
"\r\n"
"\0"
END
#endif // APSTUDIO_INVOKED
/////////////////////////////////////////////////////////////////////////////
//
// Icon
//
// Icon with lowest ID value placed first to ensure application icon
// remains consistent on all systems.
IDI_APP_ICON ICON "resources\\app_icon.ico"
/////////////////////////////////////////////////////////////////////////////
//
// Version
//
#if defined(FLUTTER_VERSION_MAJOR) && defined(FLUTTER_VERSION_MINOR) && defined(FLUTTER_VERSION_PATCH) && defined(FLUTTER_VERSION_BUILD)
#define VERSION_AS_NUMBER FLUTTER_VERSION_MAJOR,FLUTTER_VERSION_MINOR,FLUTTER_VERSION_PATCH,FLUTTER_VERSION_BUILD
#else
#define VERSION_AS_NUMBER 1,0,0,0
#endif
#if defined(FLUTTER_VERSION)
#define VERSION_AS_STRING FLUTTER_VERSION
#else
#define VERSION_AS_STRING "1.0.0"
#endif
VS_VERSION_INFO VERSIONINFO
FILEVERSION VERSION_AS_NUMBER
PRODUCTVERSION VERSION_AS_NUMBER
FILEFLAGSMASK VS_FFI_FILEFLAGSMASK
#ifdef _DEBUG
FILEFLAGS VS_FF_DEBUG
#else
FILEFLAGS 0x0L
#endif
FILEOS VOS__WINDOWS32
FILETYPE VFT_APP
FILESUBTYPE 0x0L
BEGIN
BLOCK "StringFileInfo"
BEGIN
BLOCK "040904e4"
BEGIN
VALUE "CompanyName", "com.xkeyc.tools.starcitizen.doctor" "\0"
VALUE "FileDescription", "starcitizen_doctor" "\0"
VALUE "FileVersion", VERSION_AS_STRING "\0"
VALUE "InternalName", "starcitizen_doctor" "\0"
VALUE "LegalCopyright", "Copyright (C) 2023 com.xkeyc.tools.starcitizen.doctor. All rights reserved." "\0"
VALUE "OriginalFilename", "starcitizen_doctor.exe" "\0"
VALUE "ProductName", "starcitizen_doctor" "\0"
VALUE "ProductVersion", VERSION_AS_STRING "\0"
END
END
BLOCK "VarFileInfo"
BEGIN
VALUE "Translation", 0x409, 1252
END
END
#endif // English (United States) resources
/////////////////////////////////////////////////////////////////////////////
#ifndef APSTUDIO_INVOKED
/////////////////////////////////////////////////////////////////////////////
//
// Generated from the TEXTINCLUDE 3 resource.
//
/////////////////////////////////////////////////////////////////////////////
#endif // not APSTUDIO_INVOKED

View File

@ -0,0 +1,71 @@
#include "flutter_window.h"
#include <optional>
#include "flutter/generated_plugin_registrant.h"
FlutterWindow::FlutterWindow(const flutter::DartProject& project)
: project_(project) {}
FlutterWindow::~FlutterWindow() {}
bool FlutterWindow::OnCreate() {
if (!Win32Window::OnCreate()) {
return false;
}
RECT frame = GetClientArea();
// The size here must match the window dimensions to avoid unnecessary surface
// creation / destruction in the startup path.
flutter_controller_ = std::make_unique<flutter::FlutterViewController>(
frame.right - frame.left, frame.bottom - frame.top, project_);
// Ensure that basic setup of the controller was successful.
if (!flutter_controller_->engine() || !flutter_controller_->view()) {
return false;
}
RegisterPlugins(flutter_controller_->engine());
SetChildContent(flutter_controller_->view()->GetNativeWindow());
flutter_controller_->engine()->SetNextFrameCallback([&]() {
this->Show();
});
// Flutter can complete the first frame before the "show window" callback is
// registered. The following call ensures a frame is pending to ensure the
// window is shown. It is a no-op if the first frame hasn't completed yet.
flutter_controller_->ForceRedraw();
return true;
}
void FlutterWindow::OnDestroy() {
if (flutter_controller_) {
flutter_controller_ = nullptr;
}
Win32Window::OnDestroy();
}
LRESULT
FlutterWindow::MessageHandler(HWND hwnd, UINT const message,
WPARAM const wparam,
LPARAM const lparam) noexcept {
// Give Flutter, including plugins, an opportunity to handle window messages.
if (flutter_controller_) {
std::optional<LRESULT> result =
flutter_controller_->HandleTopLevelWindowProc(hwnd, message, wparam,
lparam);
if (result) {
return *result;
}
}
switch (message) {
case WM_FONTCHANGE:
flutter_controller_->engine()->ReloadSystemFonts();
break;
}
return Win32Window::MessageHandler(hwnd, message, wparam, lparam);
}

View File

@ -0,0 +1,33 @@
#ifndef RUNNER_FLUTTER_WINDOW_H_
#define RUNNER_FLUTTER_WINDOW_H_
#include <flutter/dart_project.h>
#include <flutter/flutter_view_controller.h>
#include <memory>
#include "win32_window.h"
// A window that does nothing but host a Flutter view.
class FlutterWindow : public Win32Window {
public:
// Creates a new FlutterWindow hosting a Flutter view running |project|.
explicit FlutterWindow(const flutter::DartProject& project);
virtual ~FlutterWindow();
protected:
// Win32Window:
bool OnCreate() override;
void OnDestroy() override;
LRESULT MessageHandler(HWND window, UINT const message, WPARAM const wparam,
LPARAM const lparam) noexcept override;
private:
// The project to run.
flutter::DartProject project_;
// The Flutter instance hosted by this window.
std::unique_ptr<flutter::FlutterViewController> flutter_controller_;
};
#endif // RUNNER_FLUTTER_WINDOW_H_

43
windows/runner/main.cpp Normal file
View File

@ -0,0 +1,43 @@
#include <flutter/dart_project.h>
#include <flutter/flutter_view_controller.h>
#include <windows.h>
#include "flutter_window.h"
#include "utils.h"
int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev,
_In_ wchar_t *command_line, _In_ int show_command) {
// Attach to console when present (e.g., 'flutter run') or create a
// new console when running with a debugger.
if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) {
CreateAndAttachConsole();
}
// Initialize COM, so that it is available for use in the library and/or
// plugins.
::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);
flutter::DartProject project(L"data");
std::vector<std::string> command_line_arguments =
GetCommandLineArguments();
project.set_dart_entrypoint_arguments(std::move(command_line_arguments));
FlutterWindow window(project);
Win32Window::Point origin(0, 0);
Win32Window::Size size(1280, 720);
if (!window.Create(L"starcitizen_doctor", origin, size)) {
return EXIT_FAILURE;
}
window.SetQuitOnClose(true);
::MSG msg;
while (::GetMessage(&msg, nullptr, 0, 0)) {
::TranslateMessage(&msg);
::DispatchMessage(&msg);
}
::CoUninitialize();
return EXIT_SUCCESS;
}

16
windows/runner/resource.h Normal file
View File

@ -0,0 +1,16 @@
//{{NO_DEPENDENCIES}}
// Microsoft Visual C++ generated include file.
// Used by Runner.rc
//
#define IDI_APP_ICON 101
// Next default values for new objects
//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NEXT_RESOURCE_VALUE 102
#define _APS_NEXT_COMMAND_VALUE 40001
#define _APS_NEXT_CONTROL_VALUE 1001
#define _APS_NEXT_SYMED_VALUE 101
#endif
#endif

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

View File

@ -0,0 +1,20 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
<application xmlns="urn:schemas-microsoft-com:asm.v3">
<windowsSettings>
<dpiAwareness xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">PerMonitorV2</dpiAwareness>
</windowsSettings>
</application>
<compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
<application>
<!-- Windows 10 and Windows 11 -->
<supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}"/>
<!-- Windows 8.1 -->
<supportedOS Id="{1f676c76-80e1-4239-95bb-83d0f6d0da78}"/>
<!-- Windows 8 -->
<supportedOS Id="{4a2f28e3-53b9-4441-ba9c-d69d4a4a6e38}"/>
<!-- Windows 7 -->
<supportedOS Id="{35138b9a-5d96-4fbd-8e2d-a2440225f93a}"/>
</application>
</compatibility>
</assembly>

64
windows/runner/utils.cpp Normal file
View File

@ -0,0 +1,64 @@
#include "utils.h"
#include <flutter_windows.h>
#include <io.h>
#include <stdio.h>
#include <windows.h>
#include <iostream>
void CreateAndAttachConsole() {
if (::AllocConsole()) {
FILE *unused;
if (freopen_s(&unused, "CONOUT$", "w", stdout)) {
_dup2(_fileno(stdout), 1);
}
if (freopen_s(&unused, "CONOUT$", "w", stderr)) {
_dup2(_fileno(stdout), 2);
}
std::ios::sync_with_stdio();
FlutterDesktopResyncOutputStreams();
}
}
std::vector<std::string> GetCommandLineArguments() {
// Convert the UTF-16 command line arguments to UTF-8 for the Engine to use.
int argc;
wchar_t** argv = ::CommandLineToArgvW(::GetCommandLineW(), &argc);
if (argv == nullptr) {
return std::vector<std::string>();
}
std::vector<std::string> command_line_arguments;
// Skip the first argument as it's the binary name.
for (int i = 1; i < argc; i++) {
command_line_arguments.push_back(Utf8FromUtf16(argv[i]));
}
::LocalFree(argv);
return command_line_arguments;
}
std::string Utf8FromUtf16(const wchar_t* utf16_string) {
if (utf16_string == nullptr) {
return std::string();
}
int target_length = ::WideCharToMultiByte(
CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string,
-1, nullptr, 0, nullptr, nullptr);
std::string utf8_string;
if (target_length == 0 || target_length > utf8_string.max_size()) {
return utf8_string;
}
utf8_string.resize(target_length);
int converted_length = ::WideCharToMultiByte(
CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string,
-1, utf8_string.data(),
target_length, nullptr, nullptr);
if (converted_length == 0) {
return std::string();
}
return utf8_string;
}

19
windows/runner/utils.h Normal file
View File

@ -0,0 +1,19 @@
#ifndef RUNNER_UTILS_H_
#define RUNNER_UTILS_H_
#include <string>
#include <vector>
// Creates a console for the process, and redirects stdout and stderr to
// it for both the runner and the Flutter library.
void CreateAndAttachConsole();
// Takes a null-terminated wchar_t* encoded in UTF-16 and returns a std::string
// encoded in UTF-8. Returns an empty std::string on failure.
std::string Utf8FromUtf16(const wchar_t* utf16_string);
// Gets the command line arguments passed in as a std::vector<std::string>,
// encoded in UTF-8. Returns an empty std::vector<std::string> on failure.
std::vector<std::string> GetCommandLineArguments();
#endif // RUNNER_UTILS_H_

View File

@ -0,0 +1,288 @@
#include "win32_window.h"
#include <dwmapi.h>
#include <flutter_windows.h>
#include "resource.h"
namespace {
/// Window attribute that enables dark mode window decorations.
///
/// Redefined in case the developer's machine has a Windows SDK older than
/// version 10.0.22000.0.
/// See: https://docs.microsoft.com/windows/win32/api/dwmapi/ne-dwmapi-dwmwindowattribute
#ifndef DWMWA_USE_IMMERSIVE_DARK_MODE
#define DWMWA_USE_IMMERSIVE_DARK_MODE 20
#endif
constexpr const wchar_t kWindowClassName[] = L"FLUTTER_RUNNER_WIN32_WINDOW";
/// Registry key for app theme preference.
///
/// A value of 0 indicates apps should use dark mode. A non-zero or missing
/// value indicates apps should use light mode.
constexpr const wchar_t kGetPreferredBrightnessRegKey[] =
L"Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize";
constexpr const wchar_t kGetPreferredBrightnessRegValue[] = L"AppsUseLightTheme";
// The number of Win32Window objects that currently exist.
static int g_active_window_count = 0;
using EnableNonClientDpiScaling = BOOL __stdcall(HWND hwnd);
// Scale helper to convert logical scaler values to physical using passed in
// scale factor
int Scale(int source, double scale_factor) {
return static_cast<int>(source * scale_factor);
}
// Dynamically loads the |EnableNonClientDpiScaling| from the User32 module.
// This API is only needed for PerMonitor V1 awareness mode.
void EnableFullDpiSupportIfAvailable(HWND hwnd) {
HMODULE user32_module = LoadLibraryA("User32.dll");
if (!user32_module) {
return;
}
auto enable_non_client_dpi_scaling =
reinterpret_cast<EnableNonClientDpiScaling*>(
GetProcAddress(user32_module, "EnableNonClientDpiScaling"));
if (enable_non_client_dpi_scaling != nullptr) {
enable_non_client_dpi_scaling(hwnd);
}
FreeLibrary(user32_module);
}
} // namespace
// Manages the Win32Window's window class registration.
class WindowClassRegistrar {
public:
~WindowClassRegistrar() = default;
// Returns the singleton registar instance.
static WindowClassRegistrar* GetInstance() {
if (!instance_) {
instance_ = new WindowClassRegistrar();
}
return instance_;
}
// Returns the name of the window class, registering the class if it hasn't
// previously been registered.
const wchar_t* GetWindowClass();
// Unregisters the window class. Should only be called if there are no
// instances of the window.
void UnregisterWindowClass();
private:
WindowClassRegistrar() = default;
static WindowClassRegistrar* instance_;
bool class_registered_ = false;
};
WindowClassRegistrar* WindowClassRegistrar::instance_ = nullptr;
const wchar_t* WindowClassRegistrar::GetWindowClass() {
if (!class_registered_) {
WNDCLASS window_class{};
window_class.hCursor = LoadCursor(nullptr, IDC_ARROW);
window_class.lpszClassName = kWindowClassName;
window_class.style = CS_HREDRAW | CS_VREDRAW;
window_class.cbClsExtra = 0;
window_class.cbWndExtra = 0;
window_class.hInstance = GetModuleHandle(nullptr);
window_class.hIcon =
LoadIcon(window_class.hInstance, MAKEINTRESOURCE(IDI_APP_ICON));
window_class.hbrBackground = 0;
window_class.lpszMenuName = nullptr;
window_class.lpfnWndProc = Win32Window::WndProc;
RegisterClass(&window_class);
class_registered_ = true;
}
return kWindowClassName;
}
void WindowClassRegistrar::UnregisterWindowClass() {
UnregisterClass(kWindowClassName, nullptr);
class_registered_ = false;
}
Win32Window::Win32Window() {
++g_active_window_count;
}
Win32Window::~Win32Window() {
--g_active_window_count;
Destroy();
}
bool Win32Window::Create(const std::wstring& title,
const Point& origin,
const Size& size) {
Destroy();
const wchar_t* window_class =
WindowClassRegistrar::GetInstance()->GetWindowClass();
const POINT target_point = {static_cast<LONG>(origin.x),
static_cast<LONG>(origin.y)};
HMONITOR monitor = MonitorFromPoint(target_point, MONITOR_DEFAULTTONEAREST);
UINT dpi = FlutterDesktopGetDpiForMonitor(monitor);
double scale_factor = dpi / 96.0;
HWND window = CreateWindow(
window_class, title.c_str(), WS_OVERLAPPEDWINDOW,
Scale(origin.x, scale_factor), Scale(origin.y, scale_factor),
Scale(size.width, scale_factor), Scale(size.height, scale_factor),
nullptr, nullptr, GetModuleHandle(nullptr), this);
if (!window) {
return false;
}
UpdateTheme(window);
return OnCreate();
}
bool Win32Window::Show() {
return ShowWindow(window_handle_, SW_SHOWNORMAL);
}
// static
LRESULT CALLBACK Win32Window::WndProc(HWND const window,
UINT const message,
WPARAM const wparam,
LPARAM const lparam) noexcept {
if (message == WM_NCCREATE) {
auto window_struct = reinterpret_cast<CREATESTRUCT*>(lparam);
SetWindowLongPtr(window, GWLP_USERDATA,
reinterpret_cast<LONG_PTR>(window_struct->lpCreateParams));
auto that = static_cast<Win32Window*>(window_struct->lpCreateParams);
EnableFullDpiSupportIfAvailable(window);
that->window_handle_ = window;
} else if (Win32Window* that = GetThisFromHandle(window)) {
return that->MessageHandler(window, message, wparam, lparam);
}
return DefWindowProc(window, message, wparam, lparam);
}
LRESULT
Win32Window::MessageHandler(HWND hwnd,
UINT const message,
WPARAM const wparam,
LPARAM const lparam) noexcept {
switch (message) {
case WM_DESTROY:
window_handle_ = nullptr;
Destroy();
if (quit_on_close_) {
PostQuitMessage(0);
}
return 0;
case WM_DPICHANGED: {
auto newRectSize = reinterpret_cast<RECT*>(lparam);
LONG newWidth = newRectSize->right - newRectSize->left;
LONG newHeight = newRectSize->bottom - newRectSize->top;
SetWindowPos(hwnd, nullptr, newRectSize->left, newRectSize->top, newWidth,
newHeight, SWP_NOZORDER | SWP_NOACTIVATE);
return 0;
}
case WM_SIZE: {
RECT rect = GetClientArea();
if (child_content_ != nullptr) {
// Size and position the child window.
MoveWindow(child_content_, rect.left, rect.top, rect.right - rect.left,
rect.bottom - rect.top, TRUE);
}
return 0;
}
case WM_ACTIVATE:
if (child_content_ != nullptr) {
SetFocus(child_content_);
}
return 0;
case WM_DWMCOLORIZATIONCOLORCHANGED:
UpdateTheme(hwnd);
return 0;
}
return DefWindowProc(window_handle_, message, wparam, lparam);
}
void Win32Window::Destroy() {
OnDestroy();
if (window_handle_) {
DestroyWindow(window_handle_);
window_handle_ = nullptr;
}
if (g_active_window_count == 0) {
WindowClassRegistrar::GetInstance()->UnregisterWindowClass();
}
}
Win32Window* Win32Window::GetThisFromHandle(HWND const window) noexcept {
return reinterpret_cast<Win32Window*>(
GetWindowLongPtr(window, GWLP_USERDATA));
}
void Win32Window::SetChildContent(HWND content) {
child_content_ = content;
SetParent(content, window_handle_);
RECT frame = GetClientArea();
MoveWindow(content, frame.left, frame.top, frame.right - frame.left,
frame.bottom - frame.top, true);
SetFocus(child_content_);
}
RECT Win32Window::GetClientArea() {
RECT frame;
GetClientRect(window_handle_, &frame);
return frame;
}
HWND Win32Window::GetHandle() {
return window_handle_;
}
void Win32Window::SetQuitOnClose(bool quit_on_close) {
quit_on_close_ = quit_on_close;
}
bool Win32Window::OnCreate() {
// No-op; provided for subclasses.
return true;
}
void Win32Window::OnDestroy() {
// No-op; provided for subclasses.
}
void Win32Window::UpdateTheme(HWND const window) {
DWORD light_mode;
DWORD light_mode_size = sizeof(light_mode);
LSTATUS result = RegGetValue(HKEY_CURRENT_USER, kGetPreferredBrightnessRegKey,
kGetPreferredBrightnessRegValue,
RRF_RT_REG_DWORD, nullptr, &light_mode,
&light_mode_size);
if (result == ERROR_SUCCESS) {
BOOL enable_dark_mode = light_mode == 0;
DwmSetWindowAttribute(window, DWMWA_USE_IMMERSIVE_DARK_MODE,
&enable_dark_mode, sizeof(enable_dark_mode));
}
}

View File

@ -0,0 +1,102 @@
#ifndef RUNNER_WIN32_WINDOW_H_
#define RUNNER_WIN32_WINDOW_H_
#include <windows.h>
#include <functional>
#include <memory>
#include <string>
// A class abstraction for a high DPI-aware Win32 Window. Intended to be
// inherited from by classes that wish to specialize with custom
// rendering and input handling
class Win32Window {
public:
struct Point {
unsigned int x;
unsigned int y;
Point(unsigned int x, unsigned int y) : x(x), y(y) {}
};
struct Size {
unsigned int width;
unsigned int height;
Size(unsigned int width, unsigned int height)
: width(width), height(height) {}
};
Win32Window();
virtual ~Win32Window();
// Creates a win32 window with |title| that is positioned and sized using
// |origin| and |size|. New windows are created on the default monitor. Window
// sizes are specified to the OS in physical pixels, hence to ensure a
// consistent size this function will scale the inputted width and height as
// as appropriate for the default monitor. The window is invisible until
// |Show| is called. Returns true if the window was created successfully.
bool Create(const std::wstring& title, const Point& origin, const Size& size);
// Show the current window. Returns true if the window was successfully shown.
bool Show();
// Release OS resources associated with window.
void Destroy();
// Inserts |content| into the window tree.
void SetChildContent(HWND content);
// Returns the backing Window handle to enable clients to set icon and other
// window properties. Returns nullptr if the window has been destroyed.
HWND GetHandle();
// If true, closing this window will quit the application.
void SetQuitOnClose(bool quit_on_close);
// Return a RECT representing the bounds of the current client area.
RECT GetClientArea();
protected:
// Processes and route salient window messages for mouse handling,
// size change and DPI. Delegates handling of these to member overloads that
// inheriting classes can handle.
virtual LRESULT MessageHandler(HWND window,
UINT const message,
WPARAM const wparam,
LPARAM const lparam) noexcept;
// Called when CreateAndShow is called, allowing subclass window-related
// setup. Subclasses should return false if setup fails.
virtual bool OnCreate();
// Called when Destroy is called.
virtual void OnDestroy();
private:
friend class WindowClassRegistrar;
// OS callback called by message pump. Handles the WM_NCCREATE message which
// is passed when the non-client area is being created and enables automatic
// non-client DPI scaling so that the non-client area automatically
// responsponds to changes in DPI. All other messages are handled by
// MessageHandler.
static LRESULT CALLBACK WndProc(HWND const window,
UINT const message,
WPARAM const wparam,
LPARAM const lparam) noexcept;
// Retrieves a class instance pointer for |window|
static Win32Window* GetThisFromHandle(HWND const window) noexcept;
// Update the window frame's theme to match the system theme.
static void UpdateTheme(HWND const window);
bool quit_on_close_ = false;
// window handle for top level window.
HWND window_handle_ = nullptr;
// window handle for hosted content.
HWND child_content_ = nullptr;
};
#endif // RUNNER_WIN32_WINDOW_H_