Showing preview only (298K chars total). Download the full file or copy to clipboard to get everything.
Repository: igoogolx/lux
Branch: main
Commit: 974964271809
Files: 92
Total size: 273.9 KB
Directory structure:
gitextract_n5skmjta/
├── .github/
│ ├── pull_request_template.md
│ └── workflows/
│ ├── build.yml
│ ├── virusTotal.yml
│ └── winget.yml
├── .gitignore
├── .metadata
├── CHANGELOG.md
├── LICENSE
├── README.md
├── analysis_options.yaml
├── assets/
│ └── tray.icns
├── distribute_options.yaml
├── l10n.yaml
├── lib/
│ ├── app.dart
│ ├── const/
│ │ └── const.dart
│ ├── core/
│ │ ├── checksum.dart
│ │ ├── core_config.dart
│ │ └── core_manager.dart
│ ├── dashboard.dart
│ ├── error.dart
│ ├── home.dart
│ ├── l10n/
│ │ ├── app_en.arb
│ │ ├── app_localizations.dart
│ │ ├── app_localizations_en.dart
│ │ ├── app_localizations_zh.dart
│ │ └── app_zh.arb
│ ├── main.dart
│ ├── model/
│ │ └── app.dart
│ ├── theme.dart
│ ├── tr.dart
│ ├── tray.dart
│ ├── util/
│ │ ├── elevate.dart
│ │ ├── notifier.dart
│ │ ├── process_manager.dart
│ │ └── utils.dart
│ └── widget/
│ ├── app_body.dart
│ ├── app_bottom_bar.dart
│ ├── app_header_bar.dart
│ ├── error/
│ │ ├── core_run_error_handler.dart
│ │ └── release_mode_error_widget.dart
│ ├── progress_indicator.dart
│ ├── proxy_item_action_menu.dart
│ ├── proxy_list_card.dart
│ └── proxy_list_item.dart
├── macos/
│ ├── .gitignore
│ ├── Flutter/
│ │ ├── Flutter-Debug.xcconfig
│ │ ├── Flutter-Release.xcconfig
│ │ └── GeneratedPluginRegistrant.swift
│ ├── Podfile
│ ├── Runner/
│ │ ├── AppDelegate.swift
│ │ ├── Assets.xcassets/
│ │ │ └── AppIcon.appiconset/
│ │ │ └── Contents.json
│ │ ├── Base.lproj/
│ │ │ └── MainMenu.xib
│ │ ├── Configs/
│ │ │ ├── AppInfo.xcconfig
│ │ │ ├── Debug.xcconfig
│ │ │ ├── Release.xcconfig
│ │ │ └── Warnings.xcconfig
│ │ ├── DebugProfile.entitlements
│ │ ├── Info.plist
│ │ ├── MainFlutterWindow.swift
│ │ └── Release.entitlements
│ ├── Runner.xcodeproj/
│ │ ├── project.pbxproj
│ │ ├── project.xcworkspace/
│ │ │ └── xcshareddata/
│ │ │ └── IDEWorkspaceChecks.plist
│ │ └── xcshareddata/
│ │ └── xcschemes/
│ │ └── Runner.xcscheme
│ ├── Runner.xcworkspace/
│ │ ├── contents.xcworkspacedata
│ │ └── xcshareddata/
│ │ ├── IDEWorkspaceChecks.plist
│ │ └── swiftpm/
│ │ └── Package.resolved
│ ├── RunnerTests/
│ │ └── RunnerTests.swift
│ └── packaging/
│ └── dmg/
│ └── make_config.yaml
├── pubspec.yaml
├── scripts/
│ ├── constant.dart
│ ├── init.dart
│ └── update_core_sha256.dart
├── test/
│ └── widget_test.dart
└── windows/
├── .gitignore
├── CMakeLists.txt
├── flutter/
│ ├── CMakeLists.txt
│ ├── generated_plugin_registrant.cc
│ ├── generated_plugin_registrant.h
│ └── generated_plugins.cmake
├── packaging/
│ └── exe/
│ ├── make_config.yaml
│ └── setup.iss
└── runner/
├── CMakeLists.txt
├── Runner.rc
├── flutter_window.cpp
├── flutter_window.h
├── main.cpp
├── resource.h
├── runner.exe.manifest
├── utils.cpp
├── utils.h
├── win32_window.cpp
└── win32_window.h
================================================
FILE CONTENTS
================================================
================================================
FILE: .github/pull_request_template.md
================================================
## Checklist before merging
- [ ] Upgrade is ok?
- [ ] First installation is ok?
- [ ] DOH(Dns-Over-Https) is ok?
================================================
FILE: .github/workflows/build.yml
================================================
name: Build
on:
push:
# Sequence of patterns matched against refs/tags
tags:
- v*.*.* # Push events to v1.0, v1.1, and v1.9 tags
jobs:
build:
runs-on: ${{ matrix.os }}
strategy:
matrix:
os: [windows-latest, macos-15, macos-15-intel]
steps:
- uses: actions/checkout@v6
- uses: actions/setup-python@v5
with:
python-version: '3.11'
- uses: subosito/flutter-action@v2
with:
flutter-version: '3.41.5'
channel: 'stable'
- run: dart pub global activate fastforge 0.6.6
- run: flutter pub get
- if: matrix.os == 'macos-15'
name: Build mac arm64 installer
run: |
VERSION=${GITHUB_REF_NAME#v}
echo Version: $VERSION
echo "VERSION=$VERSION" >> $GITHUB_ENV
npm install -g appdmg
dart run scripts/init.dart -a 'arm64' -s ${{ secrets.GITHUB_TOKEN }}
fastforge release --name ${{ matrix.os }}
mv dist/${VERSION}/lux-${VERSION}-macos.dmg dist/${VERSION}/lux-${VERSION}-arm64-macos.dmg
- if: matrix.os == 'macos-15-intel'
name: Build mac amd64 installer
run: |
VERSION=${GITHUB_REF_NAME#v}
echo Version: $VERSION
echo "VERSION=$VERSION" >> $GITHUB_ENV
sed -i '' 's/EXCLUDED_ARCHS = x86_64/EXCLUDED_ARCHS = arm64/g' macos/Runner.xcodeproj/project.pbxproj
npm install -g appdmg
dart run scripts/init.dart -a 'amd64' -s ${{ secrets.GITHUB_TOKEN }}
fastforge release --name ${{ matrix.os }}
mv dist/${VERSION}/lux-${VERSION}-macos.dmg dist/${VERSION}/lux-${VERSION}-amd64-macos.dmg
- if: matrix.os == 'windows-latest'
name: install InnoSetup
shell: cmd
run: choco upgrade innosetup -y --no-progress
- if: matrix.os == 'windows-latest'
name: Build windows x64 installer
run: |
mkdir -p C:\temp\dll
cp -Force C:\Windows\System32\msvcp140.dll C:\temp\dll\msvcp140.dll
cp -Force C:\Windows\System32\vcruntime140.dll C:\temp\dll\vcruntime140.dll
cp -Force C:\Windows\System32\vcruntime140_1.dll C:\temp\dll\vcruntime140_1.dll
dart run scripts/init.dart ${{ secrets.GITHUB_TOKEN }}
fastforge release --name ${{ matrix.os }}
- if: matrix.os == 'windows-latest'
name: Rename windows installer
shell: bash
run: |
VERSION=${GITHUB_REF_NAME#v}
echo Version: $VERSION
echo "VERSION=$VERSION" >> $GITHUB_ENV
mv dist/${VERSION}/lux-${VERSION}-windows-setup.exe dist/${VERSION}/lux-${VERSION}-x64-windows.exe
- uses: actions/upload-artifact@v6
with:
name: ${{ matrix.os }}-artifact
path: dist/*/*
release:
needs: build
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
- uses: actions/download-artifact@v7
- run: |
mkdir artifact
mv windows-latest-artifact/*/* artifact/
mv macos-15-artifact/*/* artifact/
mv macos-15-intel-artifact/*/* artifact/
- name: Generate checksum
uses: jmgilman/actions-generate-checksum@v1
with:
patterns: |
artifact/*
- name: Create a release
run: |
RELEASE_NOTES="Release created by [Lux](https://github.com/${{ github.repository }}) workflow run [#${{ github.run_number }}](https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }}/attempts/${{ github.run_attempt }})<br/>"
echo "$RELEASE_NOTES" >> CHANGELOG.md
- name: GH Release
uses: softprops/action-gh-release@v2
with:
prerelease: ${{ contains(github.ref, '-beat.') }}
draft: ${{ !contains(github.ref, '-beat.') }}
body_path: CHANGELOG.md
files: |
checksum.txt
artifact/*
================================================
FILE: .github/workflows/virusTotal.yml
================================================
name: VirusTotal
on:
release:
types: [published]
jobs:
virustotal:
runs-on: ubuntu-latest
steps:
- if: ${{ !contains(github.ref, '-beat.') }}
name: VirusTotal Scan
uses: crazy-max/ghaction-virustotal@v4
with:
vt_api_key: ${{ secrets.VT_API_KEY }}
update_release_body: true
files: |
.exe$
.dmg$
================================================
FILE: .github/workflows/winget.yml
================================================
name: Publish to WinGet
on:
release:
types: [published]
jobs:
publish:
# Action can only be run on windows
runs-on: windows-latest
steps:
- if: ${{ !contains(github.ref, '-beat.') }}
uses: vedantmgoyal9/winget-releaser@main
with:
identifier: igoogolx.lux
max-versions-to-keep: 5 # keep only latest 5 versions
installers-regex: '.*\.exe$' # Only .exe files
token: ${{ secrets.WINGET_TOKEN }}
================================================
FILE: .gitignore
================================================
# Miscellaneous
*.class
*.log
*.pyc
*.swp
.DS_Store
.atom/
.build/
.buildlog/
.history
.svn/
.swiftpm/
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
/assets/bin
dist
config.json
log.txt
ChineseSimplified.isl
devtools_options.yaml
================================================
FILE: .metadata
================================================
# 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: f468f3366c26a5092eb964a230ce7892fda8f2f8
channel: stable
project_type: app
# Tracks metadata for the flutter migrate command
migration:
platforms:
- platform: root
create_revision: f468f3366c26a5092eb964a230ce7892fda8f2f8
base_revision: f468f3366c26a5092eb964a230ce7892fda8f2f8
- platform: macos
create_revision: f468f3366c26a5092eb964a230ce7892fda8f2f8
base_revision: f468f3366c26a5092eb964a230ce7892fda8f2f8
- platform: windows
create_revision: f468f3366c26a5092eb964a230ce7892fda8f2f8
base_revision: f468f3366c26a5092eb964a230ce7892fda8f2f8
# 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'
================================================
FILE: CHANGELOG.md
================================================
## What's Changed
### Bug fixes 🐛
* fix(windows): [high cpu usage](https://github.com/flutter/flutter/issues/182501) of flutter
### Other changes
* chore: upgrade dependencies
================================================
FILE: LICENSE
================================================
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>.
================================================
FILE: README.md
================================================
<a name="readme-top"></a>
<br />
<div align="center">
<a href="https://github.com/igoogolx/lux">
<img src="assets/logo.png" alt="Logo" width="100" height="100">
</a>
[![Contributors][contributors-shield]][contributors-url]
[![Forks][forks-shield]][forks-url]
[![Stargazers][stars-shield]][stars-url]
[![Issues][issues-shield]][issues-url]
[![MIT License][license-shield]][license-url]
[![Build Status][build-shield]][build-url]
[![Version][version-shield]][version-url]
[![Downloads][downloads-shield]][downloads-url]
[![Winget Version][winget-shield]][winget-url]
<h3 align="center">Lux</h3>
A light desktop proxy app.
<br />
<a href="https://igoogolx.github.io/lux-docs/"><strong>lux-docs »</strong></a>
<br />
<br />
<b>Download for </b>
macOS(require macOS 13+)
·
Windows
<br />
<p align="center">
<a href="https://github.com/igoogolx/lux/issues">Report Bug</a>
·
<a href="https://github.com/igoogolx/lux/issues">Request Feature</a>
</p>
</div>
<div align="center">
<a href="https://igoogolx.github.io/lux-docs/docs/intro">
<img src="https://igoogolx.github.io/lux-docs/img/pages/home_page.png" alt="home page screenshot" width="360" >
</a>
</div>
- [Motivation](#motivation)
- [Getting Started](#getting-started)
- [Architecture](#architecture)
- [Monorepo structure](#monorepo-structure)
- [Roadmap](#roadmap)
- [Built With](#built-with)
- [Acknowledgement](#acknowledgement)
- [License](#license)
- [Contact](#contact)
- [Sponsors](#sponsors)
## Motivation
* A proxy tool should be easy to use
* Open source technology is the only way to ensure we retain absolute control over the data
<p align="right">(<a href="#readme-top">back to top</a>)</p>
<!-- GETTING STARTED -->
## Getting Started
See the [docs](https://igoogolx.github.io/lux-docs/docs/category/getting-started) for more.
## Architecture
This project is using what I'm calling the "FGRT" stack (Flutter, Go, React, TypeScript).
* The lux-core (itun2socks) is written in pure Go.
## Monorepo structure
* [itun2socks](https://github.com/igoogolx/itun2socks): The Go core, referred to internally as lux-core. Contains tun, networking stack and clash logic. Can be deployed in windows and macOS.
* [lux-client](https://github.com/igoogolx/lux-client): A React app using fluent-ui. It's the UI of lux.
* [lux-rules](https://github.com/igoogolx/lux-rules): A Go utility tool used to generate built in proxy rules.
* [lux-docs](https://github.com/igoogolx/lux-docs): The docs build with docusaurus.
## Roadmap
- [x] Add splash screen
- [x] Improve UI of About page
- [x] Improve UI Dark mode
- [x] Support DNS over https
- [x] Support Mac OS
- [x] Support adding rules
- [ ] Support IPV6
See the [open issues](https://github.com/igoogolx/lux/issues) for a full list of proposed features (and known issues).
<p align="right">(<a href="#readme-top">back to top</a>)</p>
## Built With
* [![React][React.js]][React-url]
* [![Flutter][Flutter]][Flutter-url]
* [![Go][Go.dev]][Golang-url]
<p align="right">(<a href="#readme-top">back to top</a>)</p>
<!-- Acknowledgement -->
## Acknowledgement
Lux was based on or inspired by these projects and so on:
* [sing-tun](https://github.com/SagerNet/sing-tun): Simple transparent proxy library.
* [outline-sdk](https://github.com/Jigsaw-Code/outline-sdk): SDK to build network tools based on Outline components.
* [clash-verge-rev](https://github.com/clash-verge-rev/clash-verge-rev): A modern GUI client based on Tauri, designed to run in Windows, macOS and Linux for tailored proxy experience.
<p align="right">(<a href="#readme-top">back to top</a>)</p>
<!-- LICENSE -->
## License
Distributed under the GPL License. See `LICENSE.txt` for more information.
<p align="right">(<a href="#readme-top">back to top</a>)</p>
<!-- CONTACT -->
## Contact
Project Link: [https://github.com/igoogolx/lux](https://github.com/igoogolx/lux)
<p align="right">(<a href="#readme-top">back to top</a>)</p>
<!-- Sponsors -->
## Sponsors
<a href="https://jb.gg/OpenSourceSupport">
<img src="https://resources.jetbrains.com/storage/products/company/brand/logos/jetbrains.png" alt="JetBrains logo.">
</a>
Thanks to Jetbrains provided license!
<p align="right">(<a href="#readme-top">back to top</a>)</p>
[contributors-shield]: https://img.shields.io/github/contributors/igoogolx/lux.svg
[contributors-url]: https://github.com/igoogolx/lux/graphs/contributors
[forks-shield]: https://img.shields.io/github/forks/igoogolx/lux.svg
[forks-url]: https://github.com/igoogolx/lux/network/members
[stars-shield]: https://img.shields.io/github/stars/igoogolx/lux.svg
[stars-url]: https://github.com/igoogolx/lux/stargazers
[issues-shield]: https://img.shields.io/github/issues/igoogolx/lux.svg
[issues-url]: https://github.com/igoogolx/lux/issues
[license-shield]: https://img.shields.io/github/license/igoogolx/lux.svg
[license-url]: https://github.com/igoogolx/lux/blob/master/LICENSE
[build-shield]: https://github.com/igoogolx/lux/actions/workflows/build.yml/badge.svg
[build-url]: https://github.com/igoogolx/lux/actions/workflows/build.yml
[version-shield]: https://img.shields.io/github/v/release/igoogolx/lux
[version-url]: https://github.com/igoogolx/lux/releases
[downloads-shield]: https://img.shields.io/github/downloads/igoogolx/lux/total
[downloads-url]: https://github.com/igoogolx/lux/releases
[React.js]: https://img.shields.io/badge/React-20232A?logo=react&logoColor=61DAFB
[React-url]: https://reactjs.org/
[Flutter]: https://img.shields.io/badge/Flutter-%2302569B.svg?logo=flutter&logoColor=61DAFB
[Flutter-url]: https://flutter.dev/
[Go.dev]: https://img.shields.io/badge/Go-20232A?logo=go&logoColor=61DAFB
[Golang-url]: https://go.dev/
[Node-url]: https://nodejs.org/
[winget-shield]: https://img.shields.io/winget/v/igoogolx.lux
[winget-url]: https://github.com/microsoft/winget-cli
================================================
FILE: analysis_options.yaml
================================================
# 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
================================================
FILE: distribute_options.yaml
================================================
output: dist/
releases:
- name: windows-latest
jobs:
- name: release-dev-windows
package:
platform: windows
target: exe
- name: macos-15
jobs:
- name: release-dev-macos
package:
platform: macos
target: dmg
- name: macos-15-intel
jobs:
- name: release-dev-macos
package:
platform: macos
target: dmg
================================================
FILE: l10n.yaml
================================================
arb-dir: lib/l10n
template-arb-file: app_en.arb
output-localization-file: app_localizations.dart
================================================
FILE: lib/app.dart
================================================
import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:lux/core/core_config.dart';
import 'package:lux/home.dart';
import 'package:lux/model/app.dart';
import 'package:lux/theme.dart';
import 'package:lux/tr.dart';
import 'package:provider/provider.dart';
import 'l10n/app_localizations.dart';
class App extends StatefulWidget {
final ThemeMode theme;
final Locale defaultLocal;
final ClientMode clientMode;
const App(this.theme, this.defaultLocal, this.clientMode, {super.key});
@override
State<App> createState() => _App();
}
class _App extends State<App> {
late AppStateModel appState =
AppStateModel(widget.theme, widget.defaultLocal);
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
return ChangeNotifierProvider(
create: (context) => appState,
child: Consumer<AppStateModel>(
builder: (context, appState, child) => MaterialApp(
themeMode: appState.theme,
theme: AppTheme.light,
darkTheme: AppTheme.dark,
home: Home(widget.clientMode),
onGenerateTitle: (context) {
initTr(context);
return 'Lux';
},
locale: appState.locale,
localizationsDelegates: [
AppLocalizations.delegate,
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
],
supportedLocales: [
Locale('en'),
Locale('zh'),
],
),
),
);
}
}
================================================
FILE: lib/const/const.dart
================================================
import 'dart:io';
import 'package:path/path.dart' as path;
class LuxCoreName {
static String get platform {
if (Platform.isWindows) return 'windows';
if (Platform.isMacOS) return 'darwin';
if (Platform.isLinux) return 'linux';
return 'unknown';
}
static String get arch {
return const String.fromEnvironment('OS_ARCH', defaultValue: 'amd64');
}
static String get ext {
if (Platform.isWindows) return '.exe';
return '';
}
static String get name {
return 'lux_core$ext';
}
}
class Paths {
static Directory get flutterAssets {
File mainFile = File(Platform.resolvedExecutable);
String assetsPath = '../data/flutter_assets';
if (Platform.isMacOS) {
assetsPath = '../../Frameworks/App.framework/Resources/flutter_assets';
}
return Directory(path.normalize(path.join(mainFile.path, assetsPath)));
}
static Directory get assets {
return Directory(path.join(flutterAssets.path, 'assets'));
}
static Directory get assetsBin {
return Directory(path.join(assets.path, 'bin'));
}
static String get appIcon {
return path.join(
assets.path, Platform.isWindows ? 'app_icon.ico' : 'tray.icns');
}
static String get pubspec {
return path.join(flutterAssets.path, "pubspec.yaml");
}
}
const darkBackgroundColor = 0xff292929;
const launchFromStartupArg = 'launch_from_startup';
const localServersGroupKey = 'local_servers';
const latestReleaseUrl = 'https://github.com/igoogolx/lux/releases/latest';
enum ProxyItemAction {
edit,
delete,
qrCode,
}
================================================
FILE: lib/core/checksum.dart
================================================
import 'dart:io';
import 'package:crypto/crypto.dart';
// checksum-start
const darwinAmd64Checksum = "6146982cd80750dff36ccba6b3e1aa117a2d2e2c539c758187acf226442a9a49";
const darwinArm64Checksum = "c4d39d5f3dacc662773385e8dc4cc1a2206e5d5b44f26275d4a713d1639e140f";
const windowsAmd64Checksum = "f684132becac1d9399a566299ba0719183bfdf053d77bce81692cfd211858682";
// checksum-end
Future<void> verifyCoreBinary(String filePath) async {
var input = File(filePath);
if (!input.existsSync()) {
throw "File $filePath does not exist.";
}
var value = await sha256.bind(input.openRead()).first;
var curChecksum = value.toString();
var validChecksums = <String>[];
if (Platform.isWindows) {
validChecksums.add(windowsAmd64Checksum);
} else {
validChecksums.add(darwinAmd64Checksum);
validChecksums.add(darwinArm64Checksum);
}
if (!validChecksums.contains(curChecksum)) {
throw "Checksum of core binary is not matched. Expect $validChecksums, get $curChecksum.";
}
}
================================================
FILE: lib/core/core_config.dart
================================================
import 'package:flutter/material.dart';
import 'package:lux/util/utils.dart';
import 'package:path/path.dart' as path;
import '../const/const.dart';
Future<Map<String, dynamic>> readConfig() async {
try {
var homeDir = await getHomeDir();
var configPath = path.join(homeDir, 'config.json');
return await readJsonFile(configPath);
} catch (e) {
return {};
}
}
Future<Map<String, dynamic>> readSetting() async {
try {
final config = await readConfig();
if (config.containsKey('setting') &&
config['setting'] is Map<String, dynamic>) {
return config['setting'] as Map<String, dynamic>;
}
return {};
} catch (e) {
return {};
}
}
ThemeMode convertTheme(String theme) {
switch (theme) {
case 'dark':
return ThemeMode.dark;
case 'light':
return ThemeMode.light;
default:
return ThemeMode.system;
}
}
Future<ThemeMode> readTheme() async {
var setting = await readSetting();
if (setting.containsKey('theme') && setting['theme'] is String) {
return convertTheme(setting['theme']);
}
return ThemeMode.system;
}
enum ClientMode {
light,
webview,
}
Future<ClientMode> readClientMode() async {
var setting = await readSetting();
if (setting.containsKey('lightClientMode') &&
setting['lightClientMode'] is bool) {
if (setting['lightClientMode']) {
return ClientMode.light;
}
}
return ClientMode.webview;
}
Future<bool> readAutoLaunch() async {
var setting = await readSetting();
if (setting.containsKey('autoLaunch') && setting['autoLaunch'] is bool) {
return setting['autoLaunch'] as bool;
}
return false;
}
Future<bool> readAutoConnect() async {
var setting = await readSetting();
if (setting.containsKey('autoConnect') && setting['autoConnect'] is bool) {
return setting['autoConnect'] as bool;
}
return false;
}
Future<String> readLanguage() async {
var setting = await readSetting();
if (setting.containsKey('language') && setting['language'] is String) {
return setting['language'] as String;
}
return 'system';
}
enum ProxyMode { tun, system, mixed }
Future<ProxyMode> readProxyMode() async {
var setting = await readSetting();
if (setting.containsKey('mode') && setting['mode'] is String) {
var mode = setting['mode'] as String;
switch (mode) {
case 'system':
return ProxyMode.system;
case 'tun':
return ProxyMode.tun;
case 'mixed':
return ProxyMode.mixed;
}
}
return ProxyMode.system;
}
List<ProxyList> sortProxyList(
List<ProxyList> groups, List<SubscriptionItem> subscriptions) {
final sortedIds = <String>[localServersGroupKey];
for (var i = subscriptions.length - 1; i >= 0; i--) {
sortedIds.add(subscriptions[i].id);
}
final newGroups = <ProxyList>[];
for (var sortedId in sortedIds) {
var filteredGroups = groups.where((g) => g.id == sortedId);
var group = filteredGroups.firstOrNull;
if (group != null) {
newGroups.add(group);
}
}
return newGroups;
}
List<ProxyList> convertProxyListToGroup(
List<ProxyItem> items, List<SubscriptionItem> subscriptions) {
Map<String, List<ProxyItem>> groupMap = {};
for (var item in items) {
if (item.subscription is String) {
var groupName = item.subscription as String;
if (!groupMap.containsKey(groupName)) {
groupMap[groupName] = [];
}
groupMap[groupName]!.add(item);
} else {
if (!groupMap.containsKey(localServersGroupKey)) {
groupMap[localServersGroupKey] = [];
}
groupMap[localServersGroupKey]!.add(item);
}
}
List<ProxyList> groups = [];
groupMap.forEach((groupName, proxies) {
groups.add(ProxyList(proxies, groupName));
});
return sortProxyList(groups, subscriptions);
}
class ProxyItem {
final String id;
final String name;
final String type;
final String? server;
final int? port;
final String? subscription;
ProxyItem(
this.id, this.name, this.server, this.port, this.subscription, this.type);
ProxyItem.fromJson(Map<String, dynamic> json)
: id = (json['id'] as String),
name = (json['name'] as String),
type = (json['type'] as String),
server = (json['server'] as String),
subscription = (json['subscription'] is String
? json['subscription'] as String
: null),
port = (json['port'] as int);
Map<String, dynamic> toJson() => {
'id': id,
'name': name,
};
}
class ProxyList {
final List<ProxyItem> proxies;
final String id;
ProxyList(this.proxies, this.id);
ProxyList.fromJson(Map<String, dynamic> json)
: proxies = json['proxies'] != null
? (json['proxies'] as List)
.map((asset) =>
ProxyItem.fromJson(asset as Map<String, dynamic>))
.toList()
: <ProxyItem>[],
id = (json['selectedId'] as String);
Map<String, dynamic> toJson() =>
{'proxies': proxies.map((asset) => asset.toJson()).toList(), id: id};
}
class SubscriptionItem {
final String id;
final String url;
final String name;
final String remark;
SubscriptionItem(
this.id,
this.url,
this.name,
this.remark,
);
SubscriptionItem.fromJson(Map<String, dynamic> json)
: id = (json['id'] as String),
url = (json['url'] as String),
name = (json['name'] as String),
remark = (json['remark'] as String);
Map<String, dynamic> toJson() => {
'id': id,
'name': name,
'url': url,
'remark': remark,
};
}
class SubscriptionList {
late List<SubscriptionItem> value;
SubscriptionList(this.value);
SubscriptionList.fromJson(Map<String, dynamic> json) {
value = json['subscriptions'] != null
? (json['subscriptions'] as List)
.map((asset) =>
SubscriptionItem.fromJson(asset as Map<String, dynamic>))
.toList()
: <SubscriptionItem>[];
}
Map<String, dynamic> toJson() => {'value': value};
}
class ProxyListGroup {
final List<ProxyItem> allProxies;
final List<SubscriptionItem> subscriptions;
late String selectedId;
late List<ProxyList> groups;
ProxyListGroup(
{required this.allProxies,
required this.subscriptions,
required this.selectedId})
: groups = convertProxyListToGroup(allProxies, subscriptions);
}
class RuleList {
final List<String> rules;
String selectedId;
RuleList(this.rules, this.selectedId);
RuleList.fromJson(Map<String, dynamic> json)
: rules = json['rules'] != null
? (json['rules'] as List).map((asset) => asset as String).toList()
: <String>[],
selectedId = (json['selectedId'] as String);
Map<String, dynamic> toJson() => {'rules': rules};
}
// Define the data classes
class Speed {
final Proxy proxy;
final Direct direct;
Speed({required this.proxy, required this.direct});
factory Speed.fromJson(Map<String, dynamic> json) {
return Speed(
proxy: Proxy.fromJson(json['proxy']),
direct: Direct.fromJson(json['direct']),
);
}
}
class Total {
final Proxy proxy;
final Direct direct;
Total({required this.proxy, required this.direct});
factory Total.fromJson(Map<String, dynamic> json) {
return Total(
proxy: Proxy.fromJson(json['proxy']),
direct: Direct.fromJson(json['direct']),
);
}
}
class Proxy {
final int upload;
final int download;
Proxy({required this.upload, required this.download});
factory Proxy.fromJson(Map<String, dynamic> json) {
return Proxy(
upload: json['upload'],
download: json['download'],
);
}
}
class Direct {
final int upload;
final int download;
Direct({required this.upload, required this.download});
factory Direct.fromJson(Map<String, dynamic> json) {
return Direct(
upload: json['upload'],
download: json['download'],
);
}
}
class TrafficData {
final Speed speed;
final Total total;
TrafficData({required this.speed, required this.total});
factory TrafficData.fromJson(Map<String, dynamic> json) {
return TrafficData(
speed: Speed.fromJson(json['speed']),
total: Total.fromJson(json['total']),
);
}
}
class RuntimeStatus {
final String addr;
final String name;
final bool isStarted;
RuntimeStatus(
{required this.addr, required this.name, required this.isStarted});
factory RuntimeStatus.fromJson(Map<String, dynamic> json) {
return RuntimeStatus(
addr: json['addr'] is String ? json['addr'] : '',
name: json['name'] is String ? json['name'] : '',
isStarted: json['isStarted'] is bool ? json['isStarted'] : false,
);
}
}
class Setting {
late final ProxyMode mode;
Setting(this.mode);
Setting.fromJson(Map<String, dynamic> json) {
mode = (json.containsKey('mode') && json['mode'] is String)
? (json['mode'] == 'tun'
? ProxyMode.tun
: (json['mode'] == 'system' ? ProxyMode.system : ProxyMode.mixed))
: ProxyMode.mixed;
}
}
================================================
FILE: lib/core/core_manager.dart
================================================
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:lux/error.dart';
import 'package:lux/util/process_manager.dart';
import 'package:web_socket_channel/web_socket_channel.dart';
import '../tr.dart';
import '../util/notifier.dart';
import 'core_config.dart';
Future<int> findAvailablePort(int startPort, int endPort) async {
for (int port = startPort; port <= endPort; port++) {
try {
final serverSocket = await ServerSocket.bind("127.0.0.1", port);
await serverSocket.close();
return port;
} catch (e) {
// Port is not available
}
}
throw Exception('No available port found in range $startPort-$endPort');
}
/// Must be top-level function
Map<String, dynamic> _parseAndDecode(String response) {
return jsonDecode(response) as Map<String, dynamic>;
}
Future<Map<String, dynamic>> parseJson(String text) {
return compute(_parseAndDecode, text);
}
class CoreManager {
final String token;
final ProcessManager? coreProcess;
final String baseUrl;
final Function onReady;
final dio = Dio();
var needRestart = false;
late String baseHttpUrl;
late String baseWsUrl;
WebSocketChannel? _trafficChannel;
WebSocketChannel? _runtimeStatusChannel;
WebSocketChannel? _eventChannel;
CoreManager(
this.baseUrl,
this.coreProcess,
this.token,
this.onReady,
) {
baseHttpUrl = "http://$baseUrl";
baseWsUrl = "ws://$baseUrl";
dio.transformer = BackgroundTransformer()..jsonDecodeCallback = parseJson;
dio.options.receiveTimeout = const Duration(seconds: 3);
dio.interceptors.add(InterceptorsWrapper(onRequest:
(RequestOptions options, RequestInterceptorHandler handler) async {
final customHeaders = {
HttpHeaders.authorizationHeader: 'Bearer $token',
};
options.headers.addAll(customHeaders);
return handler.next(options);
}));
Connectivity()
.onConnectivityChanged
.listen((List<ConnectivityResult> result) async {
// Received changes in available connectivity types!
if (result.contains(ConnectivityResult.none)) {
await Future.delayed(const Duration(seconds: 2));
final List<ConnectivityResult> connectivityResult =
await (Connectivity().checkConnectivity());
if (!connectivityResult.contains(ConnectivityResult.none)) {
return;
}
var isStarted = await getIsStarted();
if (!isStarted) {
return;
}
var setting = await getSetting();
if (setting.mode == ProxyMode.tun || setting.mode == ProxyMode.mixed) {
await stop();
notifier.show(tr().noConnectionMsg);
debugPrint("no connection, stop core");
}
}
if (kDebugMode) {
print(result);
}
});
}
Future<void> makeRequestUntilSuccess(String url) async {
final stopwatch = Stopwatch();
stopwatch.start(); // Start the stopwatch
while (stopwatch.elapsedMilliseconds < 15000) {
try {
final response = await dio.get(url);
// Check if the request was successful
if (response.statusCode == 200) {
return; // Exit the function if the request succeeds
} else {
await makeRequestUntilSuccess(url);
}
} catch (e) {
await Future.delayed(const Duration(milliseconds: 150));
debugPrint("fail to connect to core, retry...");
}
}
throw Exception('timeout');
}
Future<void> ping() async {
try {
await makeRequestUntilSuccess('$baseHttpUrl/ping');
} catch (e) {
throw CoreRunError("fail to ping core: ${e.toString()}");
}
}
Future<void> stop() async {
await dio.post('$baseHttpUrl/manager/stop',
options: Options(
sendTimeout: const Duration(seconds: 10),
receiveTimeout: const Duration(seconds: 10),
));
}
Future<void> start() async {
await dio.post('$baseHttpUrl/manager/start',
options: Options(
sendTimeout: const Duration(seconds: 10),
receiveTimeout: const Duration(seconds: 10),
));
}
Future<bool> getIsStarted() async {
final managerRes = await dio.get('$baseHttpUrl/manager',
options: Options(
sendTimeout: const Duration(seconds: 10),
receiveTimeout: const Duration(seconds: 10),
));
var isStarted = managerRes.data['isStarted'];
if (isStarted is bool) {
return isStarted;
}
return false;
}
Future<String> getCurProxyInfo() async {
final managerRes = await dio.get('$baseHttpUrl/proxies/cur-proxy');
var name = managerRes.data['name'];
if (name is String && name.isNotEmpty) {
return name;
}
var addr = managerRes.data['addr'];
if (addr is String && addr.isNotEmpty) {
return addr;
}
return "";
}
Future<ProxyList> getProxyList() async {
final proxiesRes = await dio.get('$baseHttpUrl/proxies');
return ProxyList.fromJson(proxiesRes.data);
}
Future<RuleList> getRuleList() async {
final rulesRes = await dio.get('$baseHttpUrl/rules');
return RuleList.fromJson(rulesRes.data);
}
Future<void> selectProxy(String id) async {
await dio.post('$baseHttpUrl/selected/proxy', data: {'id': id});
}
Future<void> selectRule(String id) async {
await dio.post('$baseHttpUrl/selected/rule', data: {'id': id});
}
Future<void> exitCore() async {
if (Platform.isWindows) {
try {
await dio.post('$baseHttpUrl/manager/exit');
} catch (e) {
debugPrint(e.toString());
}
}
try {
coreProcess?.exit();
} catch (e) {
debugPrint(e.toString());
}
}
Future<void> safeExit() async {
try {
await dio.post('$baseHttpUrl/manager/exit');
coreProcess?.exit();
} catch (e) {
debugPrint(e.toString());
}
}
Future<void> restart() async {
coreProcess?.exit();
await coreProcess?.run();
}
Future<void> run() async {
await coreProcess?.run();
await ping();
onReady();
}
Future<WebSocketChannel?> getTrafficChannel() async {
_trafficChannel ??=
WebSocketChannel.connect(Uri.parse('$baseWsUrl/traffic?token=$token'));
return _trafficChannel;
}
Future<WebSocketChannel?> getRuntimeStatusChannel() async {
_runtimeStatusChannel ??= WebSocketChannel.connect(
Uri.parse('$baseWsUrl/heartbeat/runtime-status?token=$token'));
return _runtimeStatusChannel;
}
Future<WebSocketChannel?> getEventChannel() async {
_eventChannel ??=
WebSocketChannel.connect(Uri.parse('$baseWsUrl/event?token=$token'));
return _eventChannel;
}
Future<Setting> getSetting() async {
final res = await dio.get('$baseHttpUrl/setting');
if (!(res.data.containsKey('setting') &&
res.data['setting'] is Map<String, dynamic>)) {
throw Exception('invalid setting data');
}
return Setting.fromJson(res.data["setting"]);
}
Future<void> deleteProxies(List<String> ids) async {
await dio.delete('$baseHttpUrl/proxies', data: {'ids': ids});
}
Future<SubscriptionList> getSubscriptionList() async {
final res = await dio.get('$baseHttpUrl/subscription/all');
return SubscriptionList.fromJson(res.data);
}
}
================================================
FILE: lib/dashboard.dart
================================================
import 'dart:async';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:lux/util/utils.dart';
import 'package:lux/widget/app_body.dart';
import 'package:lux/widget/app_bottom_bar.dart';
import 'package:lux/widget/app_header_bar.dart';
import 'package:window_manager/window_manager.dart';
import 'core/core_manager.dart';
class Dashboard extends StatefulWidget {
final String baseUrl;
final String urlStr;
final String homeDir;
final CoreManager coreManager;
const Dashboard(this.homeDir, this.baseUrl, this.urlStr, this.coreManager,
{super.key});
@override
State<Dashboard> createState() => _DashboardState();
}
class _DashboardState extends State<Dashboard> with WindowListener {
String curProxyInfo = "";
_DashboardState();
@override
void initState() {
super.initState();
windowManager.addListener(this);
checkForUpdate();
}
@override
void dispose() {
windowManager.removeListener(this);
super.dispose();
}
@override
void onWindowClose() async {
if (Platform.isMacOS) {
if (await windowManager.isFullScreen()) {
await windowManager.setFullScreen(false);
await Future.delayed(const Duration(seconds: 1));
}
await windowManager.hide();
} else {
await windowManager.hide();
}
}
void onCurProxyInfoChange(String info) {
setState(() {
curProxyInfo = info;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: PreferredSize(
preferredSize: Size.fromHeight(50),
child: AppHeaderBar(
coreManager: widget.coreManager,
urlStr: widget.urlStr,
curProxyInfo: curProxyInfo,
onCurProxyInfoChange: onCurProxyInfoChange,
)),
body: AppBody(
coreManager: widget.coreManager,
curProxyInfo: curProxyInfo,
onCurProxyInfoChange: onCurProxyInfoChange,
dashboardUrl: widget.urlStr,
),
bottomNavigationBar: AppBottomBar(widget.coreManager),
);
}
}
================================================
FILE: lib/error.dart
================================================
class CoreHttpError {
final String message;
final int code;
CoreHttpError({required this.message, required this.code});
factory CoreHttpError.fromJson(Map<String, dynamic> json) {
return CoreHttpError(
message: json['message'] is String ? json['message'] : '',
code: json['code'] is int ? json['code'] : coreHttpErrorDefaultCode,
);
}
}
const coreHttpErrorDefaultCode = 0;
const coreHttpErrorNotElevatedCode = 10000;
class CoreRunError extends Error {
final String message;
CoreRunError(this.message);
}
================================================
FILE: lib/home.dart
================================================
import 'dart:convert';
import 'dart:io';
import 'dart:ui';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:flutter/material.dart';
import 'package:launch_at_startup/launch_at_startup.dart';
import 'package:lux/const/const.dart';
import 'package:lux/core/core_manager.dart';
import 'package:lux/dashboard.dart';
import 'package:lux/model/app.dart';
import 'package:lux/tr.dart';
import 'package:lux/tray.dart';
import 'package:lux/util/notifier.dart';
import 'package:lux/util/process_manager.dart';
import 'package:lux/util/utils.dart';
import 'package:lux/widget/progress_indicator.dart';
import 'package:path/path.dart' as path;
import 'package:power_monitor/power_monitor.dart';
import 'package:provider/provider.dart';
import 'package:tray_manager/tray_manager.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:uuid/uuid.dart';
import 'package:version/version.dart';
import 'package:web_socket_channel/web_socket_channel.dart';
import 'package:window_manager/window_manager.dart';
import 'core/core_config.dart';
class Home extends StatefulWidget {
final ClientMode clientMode;
const Home(this.clientMode, {super.key});
@override
State<Home> createState() => _HomeState();
}
Future<void> initClient(CoreManager? coreManager) async {
await setAutoConnect(coreManager);
await setAutoLaunch(coreManager);
}
class _HomeState extends State<Home>
with TrayListener, WindowListener, PowerMonitorListener {
String baseUrl = "";
String urlStr = "";
String homeDir = "";
CoreManager? coreManager;
ValueNotifier<bool> isCoreReady = ValueNotifier<bool>(false);
Widget? dashboardWidget;
WebSocketChannel? eventChannel;
late final AppLifecycleListener _listener;
var needRestart = false;
dynamic coreError;
void _init(AppStateModel appState) async {
trayManager.addListener(this);
await windowManager.setPreventClose(true);
var corePath = path.join(Paths.assetsBin.path, LuxCoreName.name);
var curHomeDir = await getHomeDir();
final port = await findAvailablePort(8000, 9000);
var uuid = Uuid();
var secret = uuid.v4();
final Version currentVersion = Version.parse(await getAppVersion());
var needElevate = true;
var homeDirArg = '-home_dir=$curHomeDir';
if (Platform.isWindows) {
homeDirArg = "-home_dir=`\"$curHomeDir`\"";
final proxyMode = await readProxyMode();
needElevate = proxyMode != ProxyMode.system;
}
final process = ProcessManager(
corePath, [homeDirArg, '-port=$port', '-secret=$secret'], needElevate);
var curBaseUrl = '127.0.0.1:$port';
var curHttpUrl = 'http://$curBaseUrl';
var curUrlStr =
'$curHttpUrl/?client_version=$currentVersion&token=$secret&theme=${appState.theme == ThemeMode.dark ? 'dark' : 'light'}';
debugPrint("dashboard url: $curUrlStr");
coreManager = CoreManager(curBaseUrl, process, secret, () {
_onCoreReady(appState);
});
setState(() {
homeDir = curHomeDir;
baseUrl = curHttpUrl;
urlStr = curUrlStr;
});
if (Platform.isWindows) {
initSystemTray();
}
isCoreReady.addListener(() {
if (isCoreReady.value) {
initClient(coreManager);
}
});
coreManager?.run().catchError((e) {
setState(() {
coreError = e;
});
});
}
void _onCoreReady(AppStateModel appState) {
setState(() {
isCoreReady.value = true;
});
if (eventChannel == null) {
coreManager?.getEventChannel().then((channel) {
eventChannel = channel;
eventChannel?.stream.listen((rawData) async {
if (rawData is! String) {
return;
}
final message = json.decode(rawData);
if (message is! Map<String, dynamic>) {
return;
}
if (!(message.containsKey('type') && message['type'] is String)) {
return;
}
switch (message['type']) {
case "set_theme":
{
if (!(message.containsKey('value') &&
message['value'] is String)) {
return;
}
appState.updateTheme(convertTheme(message['value']));
}
case "set_language":
{
if (!(message.containsKey('value') &&
message['value'] is String)) {
return;
}
appState.updateLocale(convertLocale(message['value']));
if (Platform.isWindows) {
initSystemTray();
}
}
case "set_auto_launch":
{
if (!(message.containsKey('value') &&
message['value'] is bool)) {
return;
}
if (message['value']) {
await launchAtStartup.enable();
} else {
await launchAtStartup.disable();
}
}
case 'open_home_dir':
{
launchUrl(Uri.file(homeDir));
}
case 'open_web_dashboard':
{
launchUrl(Uri.parse(urlStr));
}
case 'exit_app':
{
await coreManager?.exitCore();
exitApp();
}
}
});
});
}
}
@override
void initState() {
super.initState();
_listener = AppLifecycleListener(onExitRequested: _handleExitRequest);
windowManager.addListener(this);
powerMonitor.addListener(this);
_init(Provider.of<AppStateModel>(context, listen: false));
}
Future<AppExitResponse> _handleExitRequest() async {
if (Platform.isMacOS) {
await coreManager?.safeExit();
}
return AppExitResponse.exit;
}
@override
void dispose() {
trayManager.removeListener(this);
windowManager.removeListener(this);
powerMonitor.removeListener(this);
_listener.dispose();
super.dispose();
}
@override
void onTrayIconMouseDown() {
windowManager.show();
windowManager.focus();
}
@override
void onTrayIconRightMouseDown() {
trayManager.popUpContextMenu();
}
@override
void onTrayMenuItemClick(MenuItem menuItem) async {
if (menuItem.key == 'open_dashboard') {
final Uri url = Uri.parse(urlStr);
launchUrl(url);
} else if (menuItem.key == 'exit_app') {
await coreManager?.exitCore();
exit(0);
}
}
@override
onPowerMonitorSleep() async {
if (Platform.isMacOS) {
var isFullScreen = await windowManager.isFullScreen();
if (isFullScreen) {
await windowManager.setFullScreen(false);
}
}
if (coreManager == null) {
return;
}
var isStarted = await coreManager!.getIsStarted();
if (!isStarted) {
return;
}
final setting = await coreManager!.getSetting();
if (setting.mode == ProxyMode.tun || setting.mode == ProxyMode.mixed) {
needRestart = true;
await coreManager!.stop();
}
}
@override
onPowerMonitorWokeUp() async {
if (coreManager == null) {
return;
}
if (needRestart) {
needRestart = false;
final List<ConnectivityResult> connectivityResult =
await (Connectivity().checkConnectivity());
if (connectivityResult.contains(ConnectivityResult.none)) {
notifier.show(tr().noConnectionMsg);
return;
}
await Future.delayed(const Duration(seconds: 2));
await coreManager!.start();
notifier.show(tr().reconnectedMsg);
}
}
@override
onPowerMonitorShutdown() {
resetSystemProxy();
}
@override
onPowerMonitorUserChanged() async {
if (coreManager == null) {
return;
}
var isStarted = await coreManager!.getIsStarted();
if (isStarted) {
await coreManager!.stop();
}
}
@override
Widget build(BuildContext context) {
if (coreError != null && !isCoreReady.value) {
throw coreError;
}
if (coreManager == null || !isCoreReady.value) {
return Scaffold(body: AppProgressIndicator());
}
return Dashboard(homeDir, baseUrl, urlStr, coreManager!);
}
}
================================================
FILE: lib/l10n/app_en.arb
================================================
{
"trayDashboardLabel": "Open Dashboard",
"exit": "Exit",
"noConnectionMsg": "No available network. Disconnected",
"reconnectedMsg": "Reconnected",
"connectOnOpenErrMsg": "Fail to connect on open: {msg}",
"setAutoLaunchErrMsg": "Fail to set auto launch: {msg}",
"connectOnOpenMsg": "Connect on open",
"proxyAllRuleLabel": "Proxy All",
"proxyGFWRuleLabel": "Proxy GFW",
"bypassCNRuleLabel": "Bypass CN",
"bypassAllRuleLabel": "Bypass All",
"goWebDashboardTip":"Open web dashboard",
"tunModeLabel": "Tun",
"systemModeLabel": "System",
"mixedModeLabel": "Mixed",
"proxyModeTooltip": "System proxy usually only supports TCP and is not accepted by all applications, but Tun can handle all traffic. Mixed enables Tun and System at the same time",
"newVersionMessage": "New available version! Click to Go.",
"uploadLabel": "upload",
"downloadLabel": "download",
"proxyLabel": "Proxy",
"bypassLabel": "Direct",
"launchAtStartUpMessage": "Running in background",
"notElevated": "Not running with elevated permissions.",
"localServer": "Local Servers",
"coreRunError": "Encounter an error when starting lux_core",
"somethingWrong":"Something wrong",
"howToFix": "How to fix",
"elevateCoreStep":"Lux_core is not elevated successfully. Please try to do it manually: \n 1. Copy the following command and run in terminal \n 2. Restart Lux",
"bottomBarTip": "Hover speed and mode text to see more info",
"edit": "Edit",
"delete": "Delete",
"qrCode": "QR Code",
"addProxyTip": "Add new proxy"
}
================================================
FILE: lib/l10n/app_localizations.dart
================================================
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:intl/intl.dart' as intl;
import 'app_localizations_en.dart';
import 'app_localizations_zh.dart';
// ignore_for_file: type=lint
/// Callers can lookup localized strings with an instance of AppLocalizations
/// returned by `AppLocalizations.of(context)`.
///
/// Applications need to include `AppLocalizations.delegate()` in their app's
/// `localizationDelegates` list, and the locales they support in the app's
/// `supportedLocales` list. For example:
///
/// ```dart
/// import 'l10n/app_localizations.dart';
///
/// return MaterialApp(
/// localizationsDelegates: AppLocalizations.localizationsDelegates,
/// supportedLocales: AppLocalizations.supportedLocales,
/// home: MyApplicationHome(),
/// );
/// ```
///
/// ## Update pubspec.yaml
///
/// Please make sure to update your pubspec.yaml to include the following
/// packages:
///
/// ```yaml
/// dependencies:
/// # Internationalization support.
/// flutter_localizations:
/// sdk: flutter
/// intl: any # Use the pinned version from flutter_localizations
///
/// # Rest of dependencies
/// ```
///
/// ## iOS Applications
///
/// iOS applications define key application metadata, including supported
/// locales, in an Info.plist file that is built into the application bundle.
/// To configure the locales supported by your app, you’ll need to edit this
/// file.
///
/// First, open your project’s ios/Runner.xcworkspace Xcode workspace file.
/// Then, in the Project Navigator, open the Info.plist file under the Runner
/// project’s Runner folder.
///
/// Next, select the Information Property List item, select Add Item from the
/// Editor menu, then select Localizations from the pop-up menu.
///
/// Select and expand the newly-created Localizations item then, for each
/// locale your application supports, add a new item and select the locale
/// you wish to add from the pop-up menu in the Value field. This list should
/// be consistent with the languages listed in the AppLocalizations.supportedLocales
/// property.
abstract class AppLocalizations {
AppLocalizations(String locale)
: localeName = intl.Intl.canonicalizedLocale(locale.toString());
final String localeName;
static AppLocalizations? of(BuildContext context) {
return Localizations.of<AppLocalizations>(context, AppLocalizations);
}
static const LocalizationsDelegate<AppLocalizations> delegate =
_AppLocalizationsDelegate();
/// A list of this localizations delegate along with the default localizations
/// delegates.
///
/// Returns a list of localizations delegates containing this delegate along with
/// GlobalMaterialLocalizations.delegate, GlobalCupertinoLocalizations.delegate,
/// and GlobalWidgetsLocalizations.delegate.
///
/// Additional delegates can be added by appending to this list in
/// MaterialApp. This list does not have to be used at all if a custom list
/// of delegates is preferred or required.
static const List<LocalizationsDelegate<dynamic>> localizationsDelegates =
<LocalizationsDelegate<dynamic>>[
delegate,
GlobalMaterialLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
];
/// A list of this localizations delegate's supported locales.
static const List<Locale> supportedLocales = <Locale>[
Locale('en'),
Locale('zh')
];
/// No description provided for @trayDashboardLabel.
///
/// In en, this message translates to:
/// **'Open Dashboard'**
String get trayDashboardLabel;
/// No description provided for @exit.
///
/// In en, this message translates to:
/// **'Exit'**
String get exit;
/// No description provided for @noConnectionMsg.
///
/// In en, this message translates to:
/// **'No available network. Disconnected'**
String get noConnectionMsg;
/// No description provided for @reconnectedMsg.
///
/// In en, this message translates to:
/// **'Reconnected'**
String get reconnectedMsg;
/// No description provided for @connectOnOpenErrMsg.
///
/// In en, this message translates to:
/// **'Fail to connect on open: {msg}'**
String connectOnOpenErrMsg(Object msg);
/// No description provided for @setAutoLaunchErrMsg.
///
/// In en, this message translates to:
/// **'Fail to set auto launch: {msg}'**
String setAutoLaunchErrMsg(Object msg);
/// No description provided for @connectOnOpenMsg.
///
/// In en, this message translates to:
/// **'Connect on open'**
String get connectOnOpenMsg;
/// No description provided for @proxyAllRuleLabel.
///
/// In en, this message translates to:
/// **'Proxy All'**
String get proxyAllRuleLabel;
/// No description provided for @proxyGFWRuleLabel.
///
/// In en, this message translates to:
/// **'Proxy GFW'**
String get proxyGFWRuleLabel;
/// No description provided for @bypassCNRuleLabel.
///
/// In en, this message translates to:
/// **'Bypass CN'**
String get bypassCNRuleLabel;
/// No description provided for @bypassAllRuleLabel.
///
/// In en, this message translates to:
/// **'Bypass All'**
String get bypassAllRuleLabel;
/// No description provided for @goWebDashboardTip.
///
/// In en, this message translates to:
/// **'Open web dashboard'**
String get goWebDashboardTip;
/// No description provided for @tunModeLabel.
///
/// In en, this message translates to:
/// **'Tun'**
String get tunModeLabel;
/// No description provided for @systemModeLabel.
///
/// In en, this message translates to:
/// **'System'**
String get systemModeLabel;
/// No description provided for @mixedModeLabel.
///
/// In en, this message translates to:
/// **'Mixed'**
String get mixedModeLabel;
/// No description provided for @proxyModeTooltip.
///
/// In en, this message translates to:
/// **'System proxy usually only supports TCP and is not accepted by all applications, but Tun can handle all traffic. Mixed enables Tun and System at the same time'**
String get proxyModeTooltip;
/// No description provided for @newVersionMessage.
///
/// In en, this message translates to:
/// **'New available version! Click to Go.'**
String get newVersionMessage;
/// No description provided for @uploadLabel.
///
/// In en, this message translates to:
/// **'upload'**
String get uploadLabel;
/// No description provided for @downloadLabel.
///
/// In en, this message translates to:
/// **'download'**
String get downloadLabel;
/// No description provided for @proxyLabel.
///
/// In en, this message translates to:
/// **'Proxy'**
String get proxyLabel;
/// No description provided for @bypassLabel.
///
/// In en, this message translates to:
/// **'Direct'**
String get bypassLabel;
/// No description provided for @launchAtStartUpMessage.
///
/// In en, this message translates to:
/// **'Running in background'**
String get launchAtStartUpMessage;
/// No description provided for @notElevated.
///
/// In en, this message translates to:
/// **'Not running with elevated permissions.'**
String get notElevated;
/// No description provided for @localServer.
///
/// In en, this message translates to:
/// **'Local Servers'**
String get localServer;
/// No description provided for @coreRunError.
///
/// In en, this message translates to:
/// **'Encounter an error when starting lux_core'**
String get coreRunError;
/// No description provided for @somethingWrong.
///
/// In en, this message translates to:
/// **'Something wrong'**
String get somethingWrong;
/// No description provided for @howToFix.
///
/// In en, this message translates to:
/// **'How to fix'**
String get howToFix;
/// No description provided for @elevateCoreStep.
///
/// In en, this message translates to:
/// **'Lux_core is not elevated successfully. Please try to do it manually: \n 1. Copy the following command and run in terminal \n 2. Restart Lux'**
String get elevateCoreStep;
/// No description provided for @bottomBarTip.
///
/// In en, this message translates to:
/// **'Hover speed and mode text to see more info'**
String get bottomBarTip;
/// No description provided for @edit.
///
/// In en, this message translates to:
/// **'Edit'**
String get edit;
/// No description provided for @delete.
///
/// In en, this message translates to:
/// **'Delete'**
String get delete;
/// No description provided for @qrCode.
///
/// In en, this message translates to:
/// **'QR Code'**
String get qrCode;
/// No description provided for @addProxyTip.
///
/// In en, this message translates to:
/// **'Add new proxy'**
String get addProxyTip;
}
class _AppLocalizationsDelegate
extends LocalizationsDelegate<AppLocalizations> {
const _AppLocalizationsDelegate();
@override
Future<AppLocalizations> load(Locale locale) {
return SynchronousFuture<AppLocalizations>(lookupAppLocalizations(locale));
}
@override
bool isSupported(Locale locale) =>
<String>['en', 'zh'].contains(locale.languageCode);
@override
bool shouldReload(_AppLocalizationsDelegate old) => false;
}
AppLocalizations lookupAppLocalizations(Locale locale) {
// Lookup logic when only language code is specified.
switch (locale.languageCode) {
case 'en':
return AppLocalizationsEn();
case 'zh':
return AppLocalizationsZh();
}
throw FlutterError(
'AppLocalizations.delegate failed to load unsupported locale "$locale". This is likely '
'an issue with the localizations generation tool. Please file an issue '
'on GitHub with a reproducible sample app and the gen-l10n configuration '
'that was used.');
}
================================================
FILE: lib/l10n/app_localizations_en.dart
================================================
// ignore: unused_import
import 'package:intl/intl.dart' as intl;
import 'app_localizations.dart';
// ignore_for_file: type=lint
/// The translations for English (`en`).
class AppLocalizationsEn extends AppLocalizations {
AppLocalizationsEn([String locale = 'en']) : super(locale);
@override
String get trayDashboardLabel => 'Open Dashboard';
@override
String get exit => 'Exit';
@override
String get noConnectionMsg => 'No available network. Disconnected';
@override
String get reconnectedMsg => 'Reconnected';
@override
String connectOnOpenErrMsg(Object msg) {
return 'Fail to connect on open: $msg';
}
@override
String setAutoLaunchErrMsg(Object msg) {
return 'Fail to set auto launch: $msg';
}
@override
String get connectOnOpenMsg => 'Connect on open';
@override
String get proxyAllRuleLabel => 'Proxy All';
@override
String get proxyGFWRuleLabel => 'Proxy GFW';
@override
String get bypassCNRuleLabel => 'Bypass CN';
@override
String get bypassAllRuleLabel => 'Bypass All';
@override
String get goWebDashboardTip => 'Open web dashboard';
@override
String get tunModeLabel => 'Tun';
@override
String get systemModeLabel => 'System';
@override
String get mixedModeLabel => 'Mixed';
@override
String get proxyModeTooltip =>
'System proxy usually only supports TCP and is not accepted by all applications, but Tun can handle all traffic. Mixed enables Tun and System at the same time';
@override
String get newVersionMessage => 'New available version! Click to Go.';
@override
String get uploadLabel => 'upload';
@override
String get downloadLabel => 'download';
@override
String get proxyLabel => 'Proxy';
@override
String get bypassLabel => 'Direct';
@override
String get launchAtStartUpMessage => 'Running in background';
@override
String get notElevated => 'Not running with elevated permissions.';
@override
String get localServer => 'Local Servers';
@override
String get coreRunError => 'Encounter an error when starting lux_core';
@override
String get somethingWrong => 'Something wrong';
@override
String get howToFix => 'How to fix';
@override
String get elevateCoreStep =>
'Lux_core is not elevated successfully. Please try to do it manually: \n 1. Copy the following command and run in terminal \n 2. Restart Lux';
@override
String get bottomBarTip => 'Hover speed and mode text to see more info';
@override
String get edit => 'Edit';
@override
String get delete => 'Delete';
@override
String get qrCode => 'QR Code';
@override
String get addProxyTip => 'Add new proxy';
}
================================================
FILE: lib/l10n/app_localizations_zh.dart
================================================
// ignore: unused_import
import 'package:intl/intl.dart' as intl;
import 'app_localizations.dart';
// ignore_for_file: type=lint
/// The translations for Chinese (`zh`).
class AppLocalizationsZh extends AppLocalizations {
AppLocalizationsZh([String locale = 'zh']) : super(locale);
@override
String get trayDashboardLabel => '管理面板';
@override
String get exit => '退出';
@override
String get noConnectionMsg => '无网络连接,已断开';
@override
String get reconnectedMsg => '已重连';
@override
String connectOnOpenErrMsg(Object msg) {
return '自动连接失败: $msg';
}
@override
String setAutoLaunchErrMsg(Object msg) {
return '设置自启动失败: $msg';
}
@override
String get connectOnOpenMsg => '已自动连接';
@override
String get proxyAllRuleLabel => '代理全部';
@override
String get proxyGFWRuleLabel => '代理 GFW';
@override
String get bypassCNRuleLabel => '绕过 CN';
@override
String get bypassAllRuleLabel => '绕过全部';
@override
String get goWebDashboardTip => '打开 Web 管理面板';
@override
String get tunModeLabel => 'Tun';
@override
String get systemModeLabel => '系统代理';
@override
String get mixedModeLabel => '混合';
@override
String get proxyModeTooltip =>
'System proxy 通常只支持 TCP 而且不是全部应用都支持, 但是 Tun 能够代理全部流量。混合模式同时开启 Tun 和 System';
@override
String get newVersionMessage => '有新版本可用! 点击前往.';
@override
String get uploadLabel => '上传';
@override
String get downloadLabel => '下载';
@override
String get proxyLabel => '代理';
@override
String get bypassLabel => '直连';
@override
String get launchAtStartUpMessage => '正在后台运行';
@override
String get notElevated => '没有以管理员权限运行';
@override
String get localServer => '本地节点';
@override
String get coreRunError => '启动 lux_core 时遇到错误';
@override
String get somethingWrong => '出错了';
@override
String get howToFix => '修复方法';
@override
String get elevateCoreStep =>
'提升 lux_core 的权限失败。 请尝试手动提升: \n 1. 复制以下命令并在终端执行 \n 2. 重启 Lux';
@override
String get bottomBarTip => '鼠标移动到网速和模式文本上以查看更多信息';
@override
String get edit => '编辑';
@override
String get delete => '删除';
@override
String get qrCode => '二维码';
@override
String get addProxyTip => '添加新代理';
}
================================================
FILE: lib/l10n/app_zh.arb
================================================
{
"trayDashboardLabel": "管理面板",
"exit": "退出",
"noConnectionMsg": "无网络连接,已断开",
"reconnectedMsg": "已重连",
"connectOnOpenErrMsg": "自动连接失败: {msg}",
"setAutoLaunchErrMsg": "设置自启动失败: {msg}",
"connectOnOpenMsg": "已自动连接",
"proxyAllRuleLabel": "代理全部",
"proxyGFWRuleLabel": "代理 GFW",
"bypassCNRuleLabel": "绕过 CN",
"bypassAllRuleLabel": "绕过全部",
"goWebDashboardTip":"打开 Web 管理面板",
"tunModeLabel": "Tun",
"systemModeLabel": "系统代理",
"mixedModeLabel": "混合",
"proxyModeTooltip": "System proxy 通常只支持 TCP 而且不是全部应用都支持, 但是 Tun 能够代理全部流量。混合模式同时开启 Tun 和 System",
"newVersionMessage": "有新版本可用! 点击前往.",
"uploadLabel": "上传",
"downloadLabel": "下载",
"proxyLabel": "代理",
"bypassLabel": "直连",
"launchAtStartUpMessage": "正在后台运行",
"notElevated": "没有以管理员权限运行",
"localServer": "本地节点",
"coreRunError": "启动 lux_core 时遇到错误",
"somethingWrong":"出错了",
"howToFix": "修复方法",
"elevateCoreStep":"提升 lux_core 的权限失败。 请尝试手动提升: \n 1. 复制以下命令并在终端执行 \n 2. 重启 Lux",
"bottomBarTip": "鼠标移动到网速和模式文本上以查看更多信息",
"edit": "编辑",
"delete": "删除",
"qrCode": "二维码",
"addProxyTip": "添加新代理"
}
================================================
FILE: lib/main.dart
================================================
import 'dart:io';
import 'dart:ui';
import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:lux/app.dart';
import 'package:lux/const/const.dart';
import 'package:lux/core/core_config.dart';
import 'package:lux/error.dart';
import 'package:lux/tr.dart';
import 'package:lux/util/notifier.dart';
import 'package:lux/util/utils.dart';
import 'package:lux/widget/error/release_mode_error_widget.dart';
import 'package:window_manager/window_manager.dart';
void main(List<String> args) async {
WidgetsFlutterBinding.ensureInitialized();
await notifier.ensureInitialized();
PlatformDispatcher.instance.onError = (error, stack) {
if (error is DioException) {
if (error.response?.data is Map<String, dynamic>) {
final coreHttpError = CoreHttpError.fromJson(error.response?.data);
if (coreHttpError.code == coreHttpErrorNotElevatedCode) {
notifier.show(tr().notElevated);
} else {
notifier.show(coreHttpError.message);
}
return true;
}
}
notifier.show(error.toString());
return true;
};
try {
await windowManager.ensureInitialized();
WindowOptions windowOptions = const WindowOptions(
size: Size(800, 650),
center: true,
skipTaskbar: false,
);
windowManager.waitUntilReadyToShow(windowOptions, () async {
windowManager.center();
var isLaunchFromStartUp =
Platform.isWindows && args.contains(launchFromStartupArg);
if (!isLaunchFromStartUp) {
windowManager.show();
} else {
notifier.show(tr().launchAtStartUpMessage);
}
});
final theme = await readTheme();
final clientMode = await readClientMode();
final defaultLocaleValue = await getLocale();
ErrorWidget.builder = (FlutterErrorDetails details) {
return ReleaseModeErrorWidget(details: details);
};
runApp(App(theme, defaultLocaleValue, clientMode));
} catch (e) {
await notifier.show("$e");
exitApp();
}
}
================================================
FILE: lib/model/app.dart
================================================
import 'package:flutter/material.dart';
class AppStateModel extends ChangeNotifier {
late ThemeMode _theme;
late Locale _locale;
String _selectedProxyId = "";
bool _isStarted = false;
Locale get locale => _locale;
ThemeMode get theme => _theme;
String get selectedProxyId => _selectedProxyId;
bool get isStarted => _isStarted;
AppStateModel(this._theme, this._locale);
void updateTheme(ThemeMode newTheme) {
_theme = newTheme;
notifyListeners();
}
void updateLocale(Locale newLocale) {
_locale = newLocale;
notifyListeners();
}
void updateIsStarted(bool newIsStarted) {
if (newIsStarted == _isStarted) {
return;
}
_isStarted = newIsStarted;
notifyListeners();
}
void updateSelectedProxyId(String newSelectedProxyId) {
if (newSelectedProxyId == _selectedProxyId) {
return;
}
_selectedProxyId = newSelectedProxyId;
notifyListeners();
}
}
================================================
FILE: lib/theme.dart
================================================
import 'package:flex_color_scheme/flex_color_scheme.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
/// The [AppTheme] defines light and dark themes for the app.
///
/// Theme setup for FlexColorScheme package v8.
/// Use same major flex_color_scheme package version. If you use a
/// lower minor version, some properties may not be supported.
/// In that case, remove them after copying this theme to your
/// app or upgrade the package to version 8.3.0.
///
/// Use it in a [MaterialApp] like this:
///
/// MaterialApp(
/// theme: AppTheme.light,
/// darkTheme: AppTheme.dark,
/// );
abstract final class AppTheme {
// The FlexColorScheme defined light mode ThemeData.
static ThemeData light = FlexThemeData.light(
// Using FlexColorScheme built-in FlexScheme enum based colors
scheme: FlexScheme.shadBlue,
// Input color modifiers.
swapLegacyOnMaterial3: true,
// Surface color adjustments.
lightIsWhite: true,
// Convenience direct styling properties.
bottomAppBarElevation: 0.5,
// Component theme configurations for light mode.
subThemesData: const FlexSubThemesData(
interactionEffects: true,
blendOnLevel: 10,
useM2StyleDividerInM3: true,
splashType: FlexSplashType.instantSplash,
splashTypeAdaptive: FlexSplashType.instantSplash,
adaptiveElevationShadowsBack: FlexAdaptive.all(),
adaptiveAppBarScrollUnderOff: FlexAdaptive.all(),
defaultRadius: 6.0,
elevatedButtonSchemeColor: SchemeColor.onPrimaryContainer,
elevatedButtonSecondarySchemeColor: SchemeColor.primaryContainer,
outlinedButtonSchemeColor: SchemeColor.onSurface,
outlinedButtonOutlineSchemeColor: SchemeColor.outlineVariant,
toggleButtonsBorderSchemeColor: SchemeColor.outlineVariant,
segmentedButtonSchemeColor: SchemeColor.primary,
segmentedButtonBorderSchemeColor: SchemeColor.outlineVariant,
switchThumbSchemeColor: SchemeColor.onPrimaryContainer,
switchAdaptiveCupertinoLike: FlexAdaptive.all(),
unselectedToggleIsColored: true,
sliderValueTinted: true,
sliderTrackHeight: 8,
inputDecoratorIsDense: true,
inputDecoratorContentPadding:
EdgeInsetsDirectional.fromSTEB(12, 12, 12, 12),
inputDecoratorBorderSchemeColor: SchemeColor.primary,
inputDecoratorBorderType: FlexInputBorderType.outline,
inputDecoratorRadius: 8.0,
inputDecoratorBorderWidth: 0.5,
inputDecoratorFocusedBorderWidth: 2.0,
fabUseShape: true,
fabAlwaysCircular: true,
chipSchemeColor: SchemeColor.secondaryContainer,
chipSelectedSchemeColor: SchemeColor.primaryContainer,
chipFontSize: 12,
chipIconSize: 16,
chipPadding: EdgeInsetsDirectional.fromSTEB(4, 4, 4, 4),
cardRadius: 12.0,
popupMenuRadius: 6.0,
popupMenuElevation: 4.0,
alignedDropdown: true,
tooltipRadius: 6,
tooltipSchemeColor: SchemeColor.surfaceContainerHigh,
tooltipOpacity: 0.96,
dialogBackgroundSchemeColor: SchemeColor.surfaceContainerHigh,
dialogRadius: 12.0,
snackBarRadius: 6,
snackBarElevation: 6,
snackBarBackgroundSchemeColor: SchemeColor.surfaceContainerLow,
appBarBackgroundSchemeColor: SchemeColor.surfaceContainerLowest,
appBarScrolledUnderElevation: 0.5,
bottomAppBarHeight: 60,
tabBarIndicatorWeight: 4,
tabBarIndicatorTopRadius: 4,
tabBarDividerColor: Color(0x00000000),
drawerRadius: 0.0,
drawerElevation: 2.0,
drawerIndicatorOpacity: 0.5,
bottomSheetBackgroundColor: SchemeColor.surfaceContainerHigh,
bottomSheetModalBackgroundColor: SchemeColor.surfaceContainer,
bottomSheetRadius: 12.0,
bottomSheetElevation: 4.0,
bottomSheetModalElevation: 6.0,
bottomNavigationBarSelectedLabelSchemeColor: SchemeColor.primary,
bottomNavigationBarMutedUnselectedLabel: true,
bottomNavigationBarSelectedIconSchemeColor: SchemeColor.primary,
bottomNavigationBarMutedUnselectedIcon: true,
bottomNavigationBarBackgroundSchemeColor: SchemeColor.surfaceContainer,
bottomNavigationBarElevation: 0.0,
menuRadius: 6.0,
menuElevation: 4.0,
menuSchemeColor: SchemeColor.surfaceContainerLowest,
menuPadding: EdgeInsetsDirectional.fromSTEB(6, 10, 5, 10),
menuBarRadius: 0.0,
menuBarElevation: 0.0,
menuBarShadowColor: Color(0x00000000),
menuIndicatorBackgroundSchemeColor: SchemeColor.surfaceContainerHigh,
menuIndicatorRadius: 6.0,
searchBarElevation: 0.0,
searchViewElevation: 0.0,
navigationBarIndicatorSchemeColor: SchemeColor.secondaryContainer,
navigationBarBackgroundSchemeColor: SchemeColor.surfaceContainer,
navigationBarElevation: 0.0,
navigationBarHeight: 72.0,
navigationRailUseIndicator: true,
navigationRailIndicatorSchemeColor: SchemeColor.secondaryContainer,
navigationRailIndicatorOpacity: 1.00,
navigationRailBackgroundSchemeColor: SchemeColor.surfaceContainer,
scaffoldBackgroundSchemeColor: SchemeColor.surfaceContainerHighest,
cardBackgroundSchemeColor: SchemeColor.white),
// ColorScheme seed generation configuration for light mode.
keyColors: const FlexKeyColors(
useSecondary: true,
useTertiary: true,
useError: true,
keepPrimary: true,
keepSecondary: true,
keepError: true,
keepTertiaryContainer: true,
),
tones: FlexSchemeVariant.chroma
.tones(Brightness.light)
.higherContrastFixed()
.monochromeSurfaces(),
// Direct ThemeData properties.
visualDensity: FlexColorScheme.comfortablePlatformDensity,
materialTapTargetSize: MaterialTapTargetSize.padded,
cupertinoOverrideTheme: const CupertinoThemeData(applyThemeToAll: true),
);
// The FlexColorScheme defined dark mode ThemeData.
static ThemeData dark = FlexThemeData.dark(
// Using FlexColorScheme built-in FlexScheme enum based colors.
scheme: FlexScheme.shadBlue,
// Input color modifiers.
swapLegacyOnMaterial3: true,
// Convenience direct styling properties.
bottomAppBarElevation: 0.5,
// Component theme configurations for dark mode.
subThemesData: const FlexSubThemesData(
interactionEffects: true,
blendOnLevel: 20,
blendOnColors: true,
useM2StyleDividerInM3: true,
splashType: FlexSplashType.instantSplash,
splashTypeAdaptive: FlexSplashType.instantSplash,
adaptiveElevationShadowsBack: FlexAdaptive.all(),
adaptiveAppBarScrollUnderOff: FlexAdaptive.all(),
defaultRadius: 6.0,
elevatedButtonSchemeColor: SchemeColor.onPrimaryContainer,
elevatedButtonSecondarySchemeColor: SchemeColor.primaryContainer,
outlinedButtonSchemeColor: SchemeColor.onSurface,
outlinedButtonOutlineSchemeColor: SchemeColor.outlineVariant,
toggleButtonsBorderSchemeColor: SchemeColor.outlineVariant,
segmentedButtonSchemeColor: SchemeColor.primary,
segmentedButtonBorderSchemeColor: SchemeColor.outlineVariant,
switchThumbSchemeColor: SchemeColor.onPrimaryContainer,
switchAdaptiveCupertinoLike: FlexAdaptive.all(),
unselectedToggleIsColored: true,
sliderValueTinted: true,
sliderTrackHeight: 8,
inputDecoratorIsDense: true,
inputDecoratorContentPadding:
EdgeInsetsDirectional.fromSTEB(12, 12, 12, 12),
inputDecoratorBorderSchemeColor: SchemeColor.primary,
inputDecoratorBorderType: FlexInputBorderType.outline,
inputDecoratorRadius: 8.0,
inputDecoratorBorderWidth: 0.5,
inputDecoratorFocusedBorderWidth: 2.0,
fabUseShape: true,
fabAlwaysCircular: true,
chipSchemeColor: SchemeColor.secondaryContainer,
chipSelectedSchemeColor: SchemeColor.primaryContainer,
chipFontSize: 12,
chipIconSize: 16,
chipPadding: EdgeInsetsDirectional.fromSTEB(4, 4, 4, 4),
cardRadius: 12.0,
popupMenuRadius: 6.0,
popupMenuElevation: 4.0,
alignedDropdown: true,
tooltipRadius: 6,
tooltipSchemeColor: SchemeColor.surfaceContainerHigh,
tooltipOpacity: 0.96,
dialogBackgroundSchemeColor: SchemeColor.surfaceContainerHigh,
dialogRadius: 12.0,
snackBarRadius: 6,
snackBarElevation: 6,
snackBarBackgroundSchemeColor: SchemeColor.surfaceContainerLow,
appBarBackgroundSchemeColor: SchemeColor.surfaceContainerLowest,
appBarScrolledUnderElevation: 2.5,
bottomAppBarHeight: 60,
tabBarIndicatorWeight: 4,
tabBarIndicatorTopRadius: 4,
tabBarDividerColor: Color(0x00000000),
drawerRadius: 0.0,
drawerElevation: 2.0,
drawerIndicatorOpacity: 0.5,
bottomSheetBackgroundColor: SchemeColor.surfaceContainerHigh,
bottomSheetModalBackgroundColor: SchemeColor.surfaceContainer,
bottomSheetRadius: 12.0,
bottomSheetElevation: 4.0,
bottomSheetModalElevation: 6.0,
bottomNavigationBarSelectedLabelSchemeColor: SchemeColor.primary,
bottomNavigationBarMutedUnselectedLabel: true,
bottomNavigationBarSelectedIconSchemeColor: SchemeColor.primary,
bottomNavigationBarMutedUnselectedIcon: true,
bottomNavigationBarBackgroundSchemeColor: SchemeColor.surfaceContainer,
bottomNavigationBarElevation: 0.0,
menuRadius: 6.0,
menuElevation: 4.0,
menuSchemeColor: SchemeColor.surfaceContainerLowest,
menuPadding: EdgeInsetsDirectional.fromSTEB(6, 10, 5, 10),
menuBarRadius: 0.0,
menuBarElevation: 0.0,
menuBarShadowColor: Color(0x00000000),
menuIndicatorBackgroundSchemeColor: SchemeColor.surfaceContainerHigh,
menuIndicatorRadius: 6.0,
searchBarElevation: 0.0,
searchViewElevation: 0.0,
navigationBarIndicatorSchemeColor: SchemeColor.secondaryContainer,
navigationBarBackgroundSchemeColor: SchemeColor.surfaceContainer,
navigationBarElevation: 0.0,
navigationBarHeight: 72.0,
navigationRailUseIndicator: true,
navigationRailIndicatorSchemeColor: SchemeColor.secondaryContainer,
navigationRailIndicatorOpacity: 1.00,
navigationRailBackgroundSchemeColor: SchemeColor.surfaceContainer,
),
// ColorScheme seed configuration setup for dark mode.
keyColors: const FlexKeyColors(
useSecondary: true,
useTertiary: true,
useError: true,
keepPrimary: true,
keepSecondary: true,
keepError: true,
keepTertiaryContainer: true,
),
tones: FlexSchemeVariant.chroma
.tones(Brightness.dark)
.higherContrastFixed()
.monochromeSurfaces(),
// Direct ThemeData properties.
visualDensity: FlexColorScheme.comfortablePlatformDensity,
materialTapTargetSize: MaterialTapTargetSize.padded,
cupertinoOverrideTheme: const CupertinoThemeData(applyThemeToAll: true),
);
}
================================================
FILE: lib/tr.dart
================================================
import 'package:flutter/cupertino.dart';
import 'l10n/app_localizations.dart';
BuildContext? buildContext;
void initTr(BuildContext trContext){
buildContext = trContext;
}
AppLocalizations tr() {
return AppLocalizations.of(buildContext!)!;
}
class LocaleModel extends ChangeNotifier {
Locale _locale= const Locale('zh');
Locale? get locale => _locale;
void set(Locale locale) {
_locale = locale;
notifyListeners();
}
}
================================================
FILE: lib/tray.dart
================================================
import 'dart:io';
import 'package:lux/tr.dart';
import 'package:tray_manager/tray_manager.dart';
Future<void> initSystemTray() async {
await trayManager.setIcon(
Platform.isWindows
? 'assets/app_icon.ico'
: 'assets/tray.icns',
);
Menu menu = Menu(
items: [
MenuItem(
key: 'lux',
label: 'Lux',
disabled: true
),
MenuItem.separator(),
MenuItem(
key: 'open_dashboard',
label: tr().trayDashboardLabel,
),
MenuItem.separator(),
MenuItem(
key: 'exit_app',
label: tr().exit,
),
],
);
await trayManager.setContextMenu(menu);
await trayManager.setToolTip('Lux');
}
================================================
FILE: lib/util/elevate.dart
================================================
import 'dart:convert';
import 'dart:io';
import 'package:flutter/cupertino.dart';
var sudoCommandPath = "/usr/bin/osascript";
Future<String?> getFileOwner(String path) async {
var result = await Process.run("ls", ["-l", path]);
var output = result.stdout.toString().trim();
if (output.isEmpty) {
return null;
} else {
output = output.split("\n").last;
var parts =
output.split(" ").where((element) => element.isNotEmpty).toList();
return parts[2];
}
}
Future<int> elevate(String path, message) async {
var escapedCommand =
"sudo chown root:wheel $path&&sudo chmod 770 $path&&sudo chmod +sx $path";
var messageArg = " with prompt \"$message\"";
var escapedScript =
"tell current application\n activate\n do shell script \"$escapedCommand\"$messageArg with administrator privileges without altering line endings\nend tell";
var process = await Process.start(sudoCommandPath, ["-e", escapedScript]);
process.stdout.transform(utf8.decoder).forEach(debugPrint);
process.stderr.transform(utf8.decoder).forEach(debugPrint);
return await process.exitCode;
}
================================================
FILE: lib/util/notifier.dart
================================================
import 'dart:io';
import 'package:flutter/cupertino.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:lux/const/const.dart';
import 'package:url_launcher/url_launcher.dart';
class Notifier {
final _appName = "Lux";
final flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
var id = 0;
Future<void> ensureInitialized() async {
final DarwinInitializationSettings initializationSettingsDarwin =
DarwinInitializationSettings(
requestAlertPermission: false,
requestBadgePermission: false,
requestSoundPermission: false,
);
WindowsInitializationSettings initializationSettingsWindows =
WindowsInitializationSettings(
iconPath: Paths.appIcon,
appName: _appName,
appUserModelId: 'com.igoogolx.lux',
//keep guid the same as inno setup
guid: '80DF132E-434A-4DAB-9BC8-48A79C8383B9',
);
final InitializationSettings initializationSettings =
InitializationSettings(
macOS: initializationSettingsDarwin,
windows: initializationSettingsWindows,
);
await flutterLocalNotificationsPlugin.initialize(
settings: initializationSettings,
onDidReceiveNotificationResponse: onDidReceiveNotificationResponse);
}
Future<void> show(String body, [String? payload]) async {
NotificationDetails notificationDetails = NotificationDetails(
macOS: DarwinNotificationDetails(
categoryIdentifier: 'plainCategory',
),
windows: WindowsNotificationDetails(),
);
await flutterLocalNotificationsPlugin.show(
id: id++,
title: Platform.isMacOS ? _appName : "",
body: body,
notificationDetails: notificationDetails,
payload: payload);
}
void onDidReceiveNotificationResponse(
NotificationResponse notificationResponse) async {
final String? payload = notificationResponse.payload;
if (notificationResponse.payload != null) {
if (notificationResponse.payload == notifierPayloadNewRelease) {
launchUrl(Uri.parse(latestReleaseUrl));
}
debugPrint('notification payload: $payload');
}
}
}
const notifierPayloadNewRelease = "new_release";
final notifier = Notifier();
================================================
FILE: lib/util/process_manager.dart
================================================
import 'dart:convert';
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:lux/core/checksum.dart';
import 'package:lux/util/utils.dart';
import '../error.dart';
import 'elevate.dart';
class ProcessManager {
Process? process;
final String path;
final List<String> args;
final bool needElevate;
ProcessManager(this.path, this.args, this.needElevate);
Future<void> run() async {
if (Platform.isWindows) {
await verifyCoreBinary(path);
List<String> processArgs = [];
if (needElevate) {
processArgs = [
'-noprofile',
"Start-Process '$path' -Verb RunAs -windowstyle hidden",
"-ArgumentList \"${args.join(' ')}\""
];
} else {
processArgs = [
'-noprofile',
"Start-Process '$path' -windowstyle hidden",
"-ArgumentList \"${args.join(' ')}\""
];
}
process = await Process.start(
'powershell.exe',
processArgs,
runInShell: false,
);
} else {
if (!kDebugMode) {
var owner = await getFileOwner(path);
if (owner != "root") {
await verifyCoreBinary(path);
var i10nLabel = await getInitI10nLabel();
var code = await elevate(path, i10nLabel.macOSElevateServiceInfo);
if (code != 0) {
throw CoreRunError("fail to elevate core, code: $code");
}
}
}
process = await Process.start(path, args);
process?.stdout.transform(utf8.decoder).forEach(debugPrint);
process?.stderr.transform(utf8.decoder).forEach(debugPrint);
}
}
void exit() {
process?.kill();
}
void watchExit() {
// watch process kill
// ref https://github.com/dart-lang/sdk/issues/12170
if (Platform.isMacOS) {
// windows not support https://github.com/dart-lang/sdk/issues/28603
// for macos 任务管理器退出进程
ProcessSignal.sigterm.watch().listen((_) {
stdout.writeln('exit: sigterm');
exit();
});
}
// for macos, windows ctrl+c
ProcessSignal.sigint.watch().listen((_) {
stdout.writeln('exit: sigint');
exit();
});
}
}
================================================
FILE: lib/util/utils.dart
================================================
import 'dart:convert';
import 'dart:io';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:intl/intl.dart';
import 'package:launch_at_startup/launch_at_startup.dart';
import 'package:lux/const/const.dart';
import 'package:lux/core/core_config.dart';
import 'package:lux/core/core_manager.dart';
import 'package:lux/tr.dart';
import 'package:lux/util/notifier.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:path/path.dart' as path;
import 'package:path_provider/path_provider.dart';
import 'package:version/version.dart';
import 'package:win32_registry/win32_registry.dart';
import 'package:yaml/yaml.dart';
Future<String> getHomeDir() async {
PackageInfo packageInfo = await PackageInfo.fromPlatform();
final Directory appDocumentsDir = await getApplicationSupportDirectory();
final Version currentVersion = Version.parse(packageInfo.version);
return path.join(appDocumentsDir.path, '${currentVersion.major}.0');
}
Future<Map<String, dynamic>> readJsonFile(String filePath) async {
var input = await File(filePath).readAsString();
var map = jsonDecode(input);
if (map is Map<String, dynamic>) {
return map;
}
return {};
}
void exitApp() async {
exit(0);
}
Future<void> setAutoConnect(CoreManager? coreManager) async {
var isAutoConnect = await readAutoConnect();
if (isAutoConnect) {
try {
await Future.delayed(const Duration(seconds: 2));
await coreManager?.start();
notifier.show(tr().connectOnOpenMsg);
} catch (e) {
String? msg = e.toString();
if (e is DioException) {
msg = e.message;
}
notifier.show(tr().connectOnOpenErrMsg(msg.toString()));
}
}
}
Future<void> setAutoLaunch(CoreManager? coreManager) async {
try {
var isAutoLaunch = await readAutoLaunch();
PackageInfo packageInfo = await PackageInfo.fromPlatform();
launchAtStartup.setup(
appName: packageInfo.appName,
appPath: Platform.resolvedExecutable,
args: [launchFromStartupArg],
);
var isEnabled = await launchAtStartup.isEnabled();
if (isAutoLaunch && !isEnabled) {
await launchAtStartup.enable();
return;
}
if (isEnabled && !isAutoLaunch) {
await launchAtStartup.disable();
}
} catch (e) {
notifier.show(tr().setAutoLaunchErrMsg(e));
}
}
Locale convertLocale(String locale) {
switch (locale) {
case 'en-US':
{
return const Locale('en');
}
case 'zh-CN':
{
return const Locale('zh');
}
default:
{
var curLocale = Intl.getCurrentLocale();
if (curLocale.startsWith('zh')) {
return const Locale('zh');
} else {
return const Locale('en');
}
}
}
}
Future<Locale> getLocale() async {
var curLanguage = await readLanguage();
return convertLocale(curLanguage);
}
typedef InitI10nLabel = ({
String macOSElevateServiceInfo,
String macOSNotElevatedMsg
});
Future<InitI10nLabel> getInitI10nLabel() async {
var locale = await getLocale();
if (locale == const Locale('zh')) {
return (
macOSElevateServiceInfo: "Lux 权限提升服务",
macOSNotElevatedMsg: "核心没有以 root 身份运行"
);
}
return (
macOSElevateServiceInfo: "Lux elevation service",
macOSNotElevatedMsg: "Lux_core is not run as root"
);
}
Function compareVersion = (String a, String b) {
var versionA = Version.parse(a);
var versionB = Version.parse(b);
return versionA.compareTo(versionB);
};
Future<void> checkForUpdate() async {
try {
final dio = Dio();
var latestReleaseRes = await dio
.get('https://api.github.com/repos/igoogolx/lux/releases/latest');
if (latestReleaseRes.data.containsKey('tag_name') &&
latestReleaseRes.data['tag_name'] is String) {
var latestVersion = latestReleaseRes.data['tag_name'].replaceAll('v', '');
var currentVersion = await getAppVersion();
debugPrint(
'latest version: $latestVersion, current version: $currentVersion');
if (compareVersion(latestVersion, currentVersion) == 1) {
notifier.show(tr().newVersionMessage, notifierPayloadNewRelease);
}
}
} catch (e) {
debugPrint('error checking for updates: $e');
}
}
String formatBytes(int bytes) {
var unit = "";
var value = 0.0;
if (bytes < 1024 * 1024) {
value = bytes / 1024;
unit = "KB";
} else if (bytes < 1024 * 1024 * 1024) {
value = bytes / (1024 * 1024);
unit = "M";
} else {
value = (bytes / (1024 * 1024 * 1024));
unit = "G";
}
final fixedNum = value >= 1000 ? 0 : 1;
return '${value.toStringAsFixed(fixedNum)} $unit';
}
Future<String> getAppVersion() async {
try {
String pubspec = File(Paths.pubspec).readAsStringSync();
final parsed = loadYaml(pubspec);
if (parsed['version'] is String) {
final version = parsed['version'] as String;
return version;
}
throw "invalid version";
} catch (e) {
PackageInfo packageInfo = await PackageInfo.fromPlatform();
return packageInfo.version;
}
}
void resetSystemProxy() {
if (!Platform.isWindows) {
return;
}
const keyPath =
r'Software\Microsoft\Windows\CurrentVersion\Internet Settings';
final key = Registry.openPath(
RegistryHive.currentUser,
path: keyPath,
desiredAccessRights: AccessRights.writeOnly,
);
const dword = RegistryValue.int32('ProxyEnable', 0);
key.createValue(dword);
key.close();
}
================================================
FILE: lib/widget/app_body.dart
================================================
import 'package:flutter/material.dart';
import 'package:lux/const/const.dart';
import 'package:lux/model/app.dart';
import 'package:lux/widget/proxy_list_card.dart';
import 'package:provider/provider.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:window_manager/window_manager.dart';
import '../core/core_config.dart';
import '../core/core_manager.dart';
class AppBody extends StatefulWidget {
final CoreManager coreManager;
final String curProxyInfo;
final String dashboardUrl;
final void Function(String) onCurProxyInfoChange;
const AppBody(
{super.key,
required this.coreManager,
required this.curProxyInfo,
required this.onCurProxyInfoChange,
required this.dashboardUrl});
@override
State<AppBody> createState() => _AppBodyState();
}
class _AppBodyState extends State<AppBody> with WindowListener {
ProxyListGroup proxyListGroup = ProxyListGroup(
allProxies: <ProxyItem>[],
selectedId: "",
subscriptions: <SubscriptionItem>[]);
List<SubscriptionItem> subscriptionList = <SubscriptionItem>[];
bool isLoadingProxyList = false;
bool isLoadingProxyRadio = false;
var isCollapsedMap = <String, bool>{};
Future<void> refreshProxyList() async {
final proxyList = await widget.coreManager.getProxyList();
final subscriptionListValue =
await widget.coreManager.getSubscriptionList();
setState(() {
subscriptionList = subscriptionListValue.value;
proxyListGroup = ProxyListGroup(
allProxies: proxyList.proxies,
subscriptions: subscriptionList,
selectedId: proxyList.id);
Provider.of<AppStateModel>(context, listen: false)
.updateSelectedProxyId(proxyListGroup.selectedId);
for (var group in proxyListGroup.groups) {
var key = group.id;
if (!isCollapsedMap.containsKey(key)) {
setState(() {
isCollapsedMap[key] = true;
});
}
}
});
}
Future<void> refreshData() async {
if (!isLoadingProxyRadio) {
refreshProxyList();
}
}
Future<void> handleSelectProxy(String? id) async {
if (id == null) {
return;
}
try {
setState(() {
isLoadingProxyRadio = true;
});
await widget.coreManager.selectProxy(id);
setState(() {
proxyListGroup.selectedId = id;
Provider.of<AppStateModel>(context, listen: false)
.updateSelectedProxyId(id);
var curProxy = proxyListGroup.allProxies.firstWhere((p) => p.id == id);
var newCurProxyInfo = curProxy.name.isNotEmpty
? curProxy.name
: "${curProxy.server}:${curProxy.port}";
widget.onCurProxyInfoChange(newCurProxyInfo);
});
} finally {
setState(() {
isLoadingProxyRadio = false;
});
}
}
@override
void onWindowFocus() {
refreshData();
}
@override
void initState() {
super.initState();
windowManager.addListener(this);
refreshData();
}
@override
void dispose() {
super.dispose();
windowManager.removeListener(this);
}
bool getIsCollapsed(ProxyList item) {
return isCollapsedMap.containsKey(item.id)
? (isCollapsedMap[item.id] as bool)
: true;
}
void handleCollapse(ProxyList item) {
setState(() {
isCollapsedMap[item.id] = !getIsCollapsed(item);
});
}
void _handleDeleteItem(ProxyItem item) async {
await widget.coreManager.deleteProxies([item.id]);
await refreshData();
if (item.id == proxyListGroup.selectedId) {
widget.onCurProxyInfoChange("");
}
}
void _handleEditItem(ProxyItem item) async {
final editingUrl = "${widget.dashboardUrl}&mode=edit&proxyId=${item.id}";
launchUrl(Uri.parse(editingUrl));
}
void _handleQrCode(ProxyItem item) async {
final editingUrl = "${widget.dashboardUrl}&mode=qrCode&proxyId=${item.id}";
launchUrl(Uri.parse(editingUrl));
}
void _handleItemChange(ProxyItemAction action, ProxyItem item) async {
switch (action) {
case ProxyItemAction.delete:
_handleDeleteItem(item);
case ProxyItemAction.edit:
_handleEditItem(item);
case ProxyItemAction.qrCode:
_handleQrCode(item);
}
}
@override
Widget build(BuildContext context) {
return RadioGroup<String>(
groupValue: proxyListGroup.selectedId,
onChanged: handleSelectProxy,
child: proxyListGroup.groups.isEmpty
? SizedBox()
: ListView.builder(
itemCount: proxyListGroup.groups.length,
itemBuilder: (context, index) {
return ProxyListCard(
proxyList: proxyListGroup.groups[index],
key: Key(proxyListGroup.groups[index].id),
isCollapsed: getIsCollapsed(proxyListGroup.groups[index]),
onCollapse: () =>
{handleCollapse(proxyListGroup.groups[index])},
onItemChange: _handleItemChange,
subscriptionList: subscriptionList,
);
},
));
}
}
================================================
FILE: lib/widget/app_bottom_bar.dart
================================================
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:web_socket_channel/web_socket_channel.dart';
import 'package:window_manager/window_manager.dart';
import '../core/core_config.dart';
import '../core/core_manager.dart';
import '../tr.dart';
import '../util/utils.dart';
class AppBottomBar extends StatefulWidget {
final CoreManager coreManager;
const AppBottomBar(this.coreManager, {super.key});
@override
State<AppBottomBar> createState() => _AppBottomBarState();
}
class _AppBottomBarState extends State<AppBottomBar> with WindowListener {
ProxyMode proxyMode = ProxyMode.tun;
TrafficState? trafficData;
WebSocketChannel? trafficChannel;
bool isWindowHidden = false;
Future<void> refreshMode() async {
final value = await widget.coreManager.getSetting();
setState(() {
proxyMode = value.mode;
});
}
@override
void initState() {
super.initState();
refreshMode();
windowManager.addListener(this);
if (trafficChannel == null) {
widget.coreManager.getTrafficChannel().then((channel) {
trafficChannel = channel;
trafficChannel?.stream.listen((message) {
if (isWindowHidden) {
return;
}
TrafficData value = TrafficData.fromJson(json.decode(message));
setState(() {
trafficData = TrafficState(rawData: value);
});
});
});
}
}
@override
void onWindowFocus() {
isWindowHidden = false;
refreshMode();
}
@override
void onWindowClose() {
isWindowHidden = true;
}
@override
void dispose() {
windowManager.removeListener(this);
super.dispose();
trafficChannel?.sink.close();
}
@override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.only(top: 2, bottom: 2, left: 4, right: 4),
decoration: BoxDecoration(
border: Border(
top: BorderSide(
color: Theme.of(context).dividerColor,
width: 1.0,
),
)),
child: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
Tooltip(
message: tr().bottomBarTip,
child: Icon(
Icons.help_outline,
size: 16,
),
),
SizedBox(width: 4),
Tooltip(
message: trafficData?.totalMsg ?? "",
child: SizedBox(
width: 68,
child: Text(
trafficData?.total != null ? "${trafficData?.total}" : "0 B",
),
),
),
SizedBox(width: 4),
Tooltip(
message: trafficData?.uploadMsg ?? "",
child: Wrap(
crossAxisAlignment: WrapCrossAlignment.center,
children: [
Icon(Icons.arrow_upward_sharp, size: 14),
SizedBox(
width: 76,
child: Text(
trafficData?.upload != null
? "${trafficData?.upload}/s"
: "0 B/s",
),
),
],
),
),
Tooltip(
message: trafficData?.downloadMsg ?? "",
child: Wrap(
crossAxisAlignment: WrapCrossAlignment.center,
children: [
Icon(Icons.arrow_downward_sharp, size: 14),
SizedBox(
width: 76,
child: Text(
trafficData?.download != null
? "${trafficData?.download}/s"
: "0 B/s",
),
),
],
),
),
SizedBox(width: 4),
Tooltip(
message: tr().proxyModeTooltip,
child: Text(
getModeLabel(proxyMode),
),
),
],
),
);
}
}
class TrafficState {
final TrafficData rawData;
TrafficState({required this.rawData});
String get download {
var download = rawData.speed.proxy.download + rawData.speed.direct.download;
return formatBytes(download);
}
String get downloadMsg {
return "${tr().proxyLabel}: ${formatBytes(rawData.speed.proxy.download)}/s\n\n${tr().bypassLabel}: ${formatBytes(rawData.speed.direct.download)}/s";
}
String get upload {
var upload = rawData.speed.proxy.upload + rawData.speed.direct.upload;
return formatBytes(upload);
}
String get uploadMsg {
return "${tr().proxyLabel}: ${formatBytes(rawData.speed.proxy.upload)}/s\n\n${tr().bypassLabel}: ${formatBytes(rawData.speed.direct.upload)}/s";
}
String get total {
var total = rawData.total.proxy.upload +
rawData.total.proxy.download +
rawData.total.direct.upload +
rawData.total.direct.download;
return formatBytes(total);
}
String get totalMsg {
var proxyTotal =
formatBytes(rawData.total.proxy.upload + rawData.total.proxy.download);
var directTotal = formatBytes(
rawData.total.direct.upload + rawData.total.direct.download);
return "${tr().proxyLabel}: $proxyTotal\n\n${tr().bypassLabel}: $directTotal";
}
}
String getModeLabel(ProxyMode value) {
switch (value) {
case ProxyMode.tun:
return tr().tunModeLabel;
case ProxyMode.system:
return tr().systemModeLabel;
default:
return tr().mixedModeLabel;
}
}
================================================
FILE: lib/widget/app_header_bar.dart
================================================
import 'dart:collection';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:lux/model/app.dart';
import 'package:provider/provider.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:web_socket_channel/web_socket_channel.dart';
import 'package:window_manager/window_manager.dart';
import '../core/core_config.dart';
import '../core/core_manager.dart';
import '../tr.dart';
class AppHeaderBar extends StatefulWidget {
final CoreManager coreManager;
final String curProxyInfo;
final void Function(String) onCurProxyInfoChange;
const AppHeaderBar(
{super.key,
required this.coreManager,
required this.urlStr,
required this.curProxyInfo,
required this.onCurProxyInfoChange});
final String urlStr;
@override
State<AppHeaderBar> createState() => _State();
}
class _State extends State<AppHeaderBar> with WindowListener {
bool isStarted = false;
RuleList ruleList = RuleList(<String>[], "");
bool isLoadingSwitch = false;
bool isLoadingRuleList = false;
bool isLoadingRuleDropdown = false;
WebSocketChannel? runtimeStatusChannel;
void openWebDashboard() {
launchUrl(Uri.parse(widget.urlStr));
}
Future<void> refreshData() async {
if (!isLoadingSwitch) {
refreshIsStarted();
}
refreshCurProxyInfo();
if (!isLoadingRuleDropdown) {
refreshRuleList();
}
}
Future<void> refreshIsStarted() async {
final value = await widget.coreManager.getIsStarted();
setState(() {
isStarted = value;
});
}
Future<void> refreshCurProxyInfo() async {
final value = await widget.coreManager.getCurProxyInfo();
setState(() {
widget.onCurProxyInfoChange(value);
});
}
Future<void> refreshRuleList() async {
final value = await widget.coreManager.getRuleList();
setState(() {
ruleList = value;
});
}
void onSwitchChanged(bool value) async {
try {
setState(() {
isLoadingSwitch = true;
});
if (value) {
await widget.coreManager.start();
setState(() {
isStarted = true;
});
} else {
await widget.coreManager.stop();
setState(() {
isStarted = false;
});
}
} finally {
setState(() {
isLoadingSwitch = false;
});
}
}
Future<void> handleSelectRule(String? id) async {
if (id == null) {
return;
}
try {
setState(() {
isLoadingRuleDropdown = true;
});
await widget.coreManager.selectRule(id);
setState(() {
ruleList.selectedId = id;
});
} finally {
setState(() {
isLoadingRuleDropdown = false;
});
}
}
String getRuleLabel(String name) {
switch (name) {
case "proxy_all":
return tr().proxyAllRuleLabel;
case "proxy_gfw":
return tr().proxyGFWRuleLabel;
case "bypass_cn":
return tr().bypassCNRuleLabel;
case "bypass_all":
return tr().bypassAllRuleLabel;
default:
return name;
}
}
@override
void dispose() {
windowManager.removeListener(this);
runtimeStatusChannel?.sink.close();
super.dispose();
}
@override
void initState() {
super.initState();
windowManager.addListener(this);
refreshData();
if (runtimeStatusChannel == null) {
widget.coreManager.getRuntimeStatusChannel().then((channel) {
runtimeStatusChannel = channel;
runtimeStatusChannel?.stream.listen((message) {
RuntimeStatus value = RuntimeStatus.fromJson(json.decode(message));
setState(() {
if (!isLoadingSwitch) {
isStarted = value.isStarted;
Provider.of<AppStateModel>(context, listen: false)
.updateIsStarted(value.isStarted);
}
});
});
});
}
}
@override
void onWindowFocus() {
refreshData();
}
void _handleAdd() async {
final addingUrl = "${widget.urlStr}&mode=add";
launchUrl(Uri.parse(addingUrl));
}
@override
Widget build(BuildContext context) {
final List<DropdownMenuEntry<String>> menuEntries =
UnmodifiableListView<DropdownMenuEntry<String>>(
ruleList.rules.map<DropdownMenuEntry<String>>((String name) {
String label = getRuleLabel(name);
return DropdownMenuEntry(value: name, label: label);
}),
);
final isSwitchDisabled = isLoadingSwitch || widget.curProxyInfo.isEmpty;
return AppBar(
leading: IconButton(
tooltip: tr().goWebDashboardTip,
onPressed: openWebDashboard,
icon: const Icon(
Icons.settings,
)),
title: Row(
children: [
SizedBox(
height: 32,
child: FittedBox(
child: DropdownMenu<String>(
width: 184,
initialSelection: ruleList.selectedId,
onSelected: isLoadingRuleDropdown ? null : handleSelectRule,
dropdownMenuEntries: menuEntries,
textStyle: TextStyle(fontSize: 20),
),
),
),
SizedBox(width: 4),
IconButton(
tooltip: tr().addProxyTip,
onPressed: _handleAdd,
icon: const Icon(
Icons.add,
)),
Spacer(),
Text(
widget.curProxyInfo,
style: TextStyle(fontSize: 14),
),
SizedBox(width: 8),
SizedBox(
width: 48,
child: FittedBox(
child: Switch(
value: isStarted,
onChanged: isSwitchDisabled ? null : onSwitchChanged,
),
),
),
],
));
}
}
================================================
FILE: lib/widget/error/core_run_error_handler.dart
================================================
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:lux/tr.dart';
import 'package:lux/util/elevate.dart';
import 'package:path/path.dart' as path;
import '../../const/const.dart';
import '../../error.dart';
const corePathVar = "LUX_CORE_PATH";
class CoreRunErrorHandler extends StatefulWidget {
final CoreRunError errorDetail;
const CoreRunErrorHandler({
super.key,
required this.errorDetail,
});
@override
State<CoreRunErrorHandler> createState() => _CoreRunErrorHandlerState();
}
class _CoreRunErrorHandlerState extends State<CoreRunErrorHandler> {
var isElevated = false;
var corePath = path.join(Paths.assetsBin.path, LuxCoreName.name);
@override
void initState() {
super.initState();
if (Platform.isMacOS) {
getFileOwner(corePath).then((owner) {
setState(() {
isElevated = owner == "root";
});
});
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SizedBox(
width: double.infinity,
child: Container(
padding: const EdgeInsets.only(top: 32, left: 16, right: 16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
margin: EdgeInsetsGeometry.only(bottom: 40),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Icon(
Icons.warning_amber,
color: Theme.of(context).colorScheme.error,
),
SizedBox(
width: 4,
),
Text(
tr().somethingWrong,
style: TextStyle(
fontSize: 24, fontWeight: FontWeight.bold),
)
],
),
const Divider(),
SelectableText(
"${tr().coreRunError}:",
style: TextStyle(fontSize: 16),
),
Container(
margin: EdgeInsetsGeometry.only(top: 8),
width: double.infinity,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10),
color: Theme.of(context).dividerColor,
),
padding:
const EdgeInsets.symmetric(vertical: 16, horizontal: 4),
child: SelectableText(widget.errorDetail.message),
)
],
),
),
(!Platform.isMacOS || isElevated)
? SizedBox()
: Container(
margin: EdgeInsetsGeometry.only(bottom: 64),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Icon(
Icons.handyman,
color: Theme.of(context).primaryColor,
),
SizedBox(
width: 4,
),
Text(
tr().howToFix,
style: TextStyle(
fontSize: 24, fontWeight: FontWeight.bold),
)
],
),
const Divider(),
SelectableText(
tr().elevateCoreStep,
style: TextStyle(fontSize: 16),
),
Container(
margin: EdgeInsetsGeometry.only(top: 8),
width: double.infinity,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10),
color: Theme.of(context).dividerColor,
),
padding: const EdgeInsets.symmetric(
vertical: 16, horizontal: 4),
child: SelectableText(
"export $corePathVar=$corePath\n\nsudo chown root:wheel \$$corePathVar\n\nsudo chmod 770 \$$corePathVar\n\nsudo chmod +sx \$$corePathVar"),
)
],
),
)
],
),
),
));
}
}
================================================
FILE: lib/widget/error/release_mode_error_widget.dart
================================================
import 'package:flutter/material.dart';
import 'package:lux/widget/error/core_run_error_handler.dart';
import '../../error.dart';
const corePathVar = "LUX_CORE_PATH";
class ReleaseModeErrorWidget extends StatelessWidget {
const ReleaseModeErrorWidget({super.key, required this.details});
final FlutterErrorDetails details;
@override
Widget build(BuildContext context) {
if (details.exception is CoreRunError) {
return CoreRunErrorHandler(
errorDetail: details.exception as CoreRunError);
}
return Center(
child: Text(
details.exception.toString(),
style: const TextStyle(color: Colors.yellow, fontSize: 16),
textAlign: TextAlign.center,
textDirection: TextDirection.ltr,
),
);
}
}
================================================
FILE: lib/widget/progress_indicator.dart
================================================
import 'package:flutter/material.dart';
class AppProgressIndicator extends StatefulWidget {
const AppProgressIndicator({super.key});
@override
State<AppProgressIndicator> createState() => _AppProgressIndicatorState();
}
class _AppProgressIndicatorState extends State<AppProgressIndicator>
with TickerProviderStateMixin {
late AnimationController controller;
@override
void initState() {
controller = AnimationController(
vsync: this,
duration: const Duration(seconds: 1),
)..addListener(() {
setState(() {});
});
controller.repeat(reverse: false);
super.initState();
}
@override
void dispose() {
controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Center(
child: CircularProgressIndicator(
semanticsLabel: 'Circular progress indicator',
),
);
}
}
================================================
FILE: lib/widget/proxy_item_action_menu.dart
================================================
import 'package:flutter/material.dart';
import 'package:lux/const/const.dart';
import 'package:lux/model/app.dart';
import 'package:lux/tr.dart';
import 'package:provider/provider.dart';
class ProxyItemActionMenu extends StatefulWidget {
final void Function(ProxyItemAction action) onClick;
final MenuController controller;
final String id;
final String type;
const ProxyItemActionMenu(
{super.key,
required this.controller,
required this.onClick,
required this.id,
required this.type});
@override
State<ProxyItemActionMenu> createState() => _ProxyItemActionMenuState();
}
class _ProxyItemActionMenuState extends State<ProxyItemActionMenu> {
FocusNode buttonFocusNode = FocusNode(debugLabel: 'Menu Button');
@override
void dispose() {
super.dispose();
buttonFocusNode.dispose();
}
@override
Widget build(BuildContext context) {
return Consumer<AppStateModel>(builder: (context, appState, child) {
final isDeleteDisabled =
appState.isStarted && appState.selectedProxyId == widget.id;
final actionItems = <Widget>[
MenuItemButton(
onPressed: () {
widget.onClick(ProxyItemAction.edit);
},
child: Row(
children: [
Icon(
Icons.edit_outlined,
size: 16,
),
SizedBox(
width: 4,
),
Text(tr().edit)
],
)),
MenuItemButton(
onPressed: isDeleteDisabled
? null
: () => widget.onClick(ProxyItemAction.delete),
child: Row(
children: [
Icon(
Icons.delete_outline,
size: 16,
color: isDeleteDisabled
? null
: Theme.of(context).colorScheme.error,
),
SizedBox(
width: 4,
),
Text(
tr().delete,
style: isDeleteDisabled
? null
: TextStyle(color: Theme.of(context).colorScheme.error),
)
],
)),
];
if (widget.type == "ss") {
actionItems.insert(
1,
MenuItemButton(
onPressed: () {
widget.onClick(ProxyItemAction.qrCode);
},
child: Row(
children: [
Icon(
Icons.qr_code,
size: 16,
),
SizedBox(
width: 4,
),
Text(tr().qrCode)
],
)));
}
return MenuAnchor(
childFocusNode: buttonFocusNode,
controller: widget.controller,
menuChildren: actionItems,
builder: (_, MenuController controller, Widget? child) {
return IconButton(
focusNode: buttonFocusNode,
onPressed: () {
if (controller.isOpen) {
controller.close();
} else {
controller.open();
}
},
icon: const Icon(Icons.more_horiz),
);
});
});
}
}
================================================
FILE: lib/widget/proxy_list_card.dart
================================================
import 'package:flutter/material.dart';
import 'package:lux/const/const.dart';
import 'package:lux/tr.dart';
import 'package:lux/widget/proxy_list_item.dart';
import '../core/core_config.dart';
class ProxyListCard extends StatefulWidget {
final ProxyList proxyList;
final Function onCollapse;
final bool isCollapsed;
final List<SubscriptionItem> subscriptionList;
final void Function(ProxyItemAction action, ProxyItem item) onItemChange;
const ProxyListCard({
super.key,
required this.proxyList,
required this.onCollapse,
required this.isCollapsed,
required this.onItemChange,
required this.subscriptionList,
});
@override
State<ProxyListCard> createState() => _ProxyListCardState();
}
class _ProxyListCardState extends State<ProxyListCard> {
String getTitle() {
if (widget.proxyList.id != localServersGroupKey) {
try {
var filteredSubscriptions = widget.subscriptionList
.where((item) => item.id == widget.proxyList.id);
var curSubscription = filteredSubscriptions.firstOrNull;
if (curSubscription != null) {
if (curSubscription.name.isNotEmpty) {
return curSubscription.name;
}
return Uri.parse(curSubscription.url).host;
}
} catch (e) {
return "invalid proxy group title";
}
}
return tr().localServer;
}
@override
void dispose() {
super.dispose();
}
@override
Widget build(BuildContext context) {
final proxyList = widget.proxyList;
final title = getTitle();
return Card(
margin: EdgeInsetsGeometry.only(left: 6, right: 6, top: 8, bottom: 8),
child: Column(
children: [
Row(
children: [
TextButton(
onPressed: () {
widget.onCollapse();
},
style: ButtonStyle(
backgroundColor: WidgetStateProperty.resolveWith<Color?>(
(Set<WidgetState> states) {
return Colors.transparent;
},
),
overlayColor: WidgetStateProperty.resolveWith<Color?>(
(Set<WidgetState> states) {
return Colors.transparent;
},
),
),
child: Row(
children: [
Icon(widget.isCollapsed
? Icons.keyboard_arrow_up
: Icons.keyboard_arrow_down),
Text(
title,
style: TextStyle(fontSize: 12),
)
],
),
)
],
),
proxyList.proxies.isEmpty || !widget.isCollapsed
? SizedBox()
: ListView.separated(
shrinkWrap: true,
physics: ClampingScrollPhysics(),
padding: EdgeInsetsGeometry.all(0),
itemCount: proxyList.proxies.length,
itemBuilder: (context, index) {
return ProxyListItem(
key: Key(proxyList.proxies[index].id),
item: proxyList.proxies[index],
onChange: (action) =>
widget.onItemChange(action, proxyList.proxies[index]),
);
},
separatorBuilder: (BuildContext context, int index) {
return Divider(
height: 1, // Control the space the divider takes up
thickness: 1, // Control the line's thickness
indent: 20, // Left padding
endIndent: 20, // Right padding
);
},
)
],
),
);
}
}
================================================
FILE: lib/widget/proxy_list_item.dart
================================================
import 'package:flutter/material.dart';
import 'package:lux/widget/proxy_item_action_menu.dart';
import '../const/const.dart';
import '../core/core_config.dart';
class ProxyListItem extends StatefulWidget {
final ProxyItem item;
final void Function(ProxyItemAction action) onChange;
const ProxyListItem({
super.key,
required this.item,
required this.onChange,
});
@override
State<ProxyListItem> createState() => _ProxyListItemState();
}
class _ProxyListItemState extends State<ProxyListItem> {
final menuController = MenuController();
FocusNode buttonFocusNode = FocusNode(debugLabel: 'Menu Button');
@override
void dispose() {
super.dispose();
buttonFocusNode.dispose();
}
@override
Widget build(BuildContext context) {
final item = widget.item;
return RadioListTile<String>(
title: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
item.name.isNotEmpty
? item.name
: "${item.server}:${item.port}",
style: TextStyle(fontSize: 14),
),
Text(
item.type,
style: TextStyle(fontSize: 12),
)
],
),
ProxyItemActionMenu(
onClick: widget.onChange,
controller: menuController,
id: widget.item.id,
type: widget.item.type)
],
),
value: item.id,
);
}
}
================================================
FILE: macos/.gitignore
================================================
# Flutter-related
**/Flutter/ephemeral/
**/Pods/
# Xcode-related
**/dgph
**/xcuserdata/
================================================
FILE: macos/Flutter/Flutter-Debug.xcconfig
================================================
#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig"
#include "ephemeral/Flutter-Generated.xcconfig"
================================================
FILE: macos/Flutter/Flutter-Release.xcconfig
================================================
#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig"
#include "ephemeral/Flutter-Generated.xcconfig"
================================================
FILE: macos/Flutter/GeneratedPluginRegistrant.swift
================================================
//
// Generated file. Do not edit.
//
import FlutterMacOS
import Foundation
import connectivity_plus
import flutter_local_notifications
import package_info_plus
import power_monitor
import screen_retriever_macos
import tray_manager
import url_launcher_macos
import window_manager
func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) {
ConnectivityPlusPlugin.register(with: registry.registrar(forPlugin: "ConnectivityPlusPlugin"))
FlutterLocalNotificationsPlugin.register(with: registry.registrar(forPlugin: "FlutterLocalNotificationsPlugin"))
FPPPackageInfoPlusPlugin.register(with: registry.registrar(forPlugin: "FPPPackageInfoPlusPlugin"))
PowerMonitorPlugin.register(with: registry.registrar(forPlugin: "PowerMonitorPlugin"))
ScreenRetrieverMacosPlugin.register(with: registry.registrar(forPlugin: "ScreenRetrieverMacosPlugin"))
TrayManagerPlugin.register(with: registry.registrar(forPlugin: "TrayManagerPlugin"))
UrlLauncherPlugin.register(with: registry.registrar(forPlugin: "UrlLauncherPlugin"))
WindowManagerPlugin.register(with: registry.registrar(forPlugin: "WindowManagerPlugin"))
}
================================================
FILE: macos/Podfile
================================================
platform :osx, '10.14'
# CocoaPods analytics sends network stats synchronously affecting flutter build latency.
ENV['COCOAPODS_DISABLE_STATS'] = 'true'
project 'Runner', {
'Debug' => :debug,
'Profile' => :release,
'Release' => :release,
}
def flutter_root
generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'ephemeral', 'Flutter-Generated.xcconfig'), __FILE__)
unless File.exist?(generated_xcode_build_settings_path)
raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure \"flutter pub get\" is executed first"
end
File.foreach(generated_xcode_build_settings_path) do |line|
matches = line.match(/FLUTTER_ROOT\=(.*)/)
return matches[1].strip if matches
end
raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Flutter-Generated.xcconfig, then run \"flutter pub get\""
end
require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root)
flutter_macos_podfile_setup
target 'Runner' do
use_frameworks!
use_modular_headers!
flutter_install_all_macos_pods File.dirname(File.realpath(__FILE__))
target 'RunnerTests' do
inherit! :search_paths
end
end
post_install do |installer|
installer.pods_project.targets.each do |target|
flutter_additional_macos_build_settings(target)
end
end
================================================
FILE: macos/Runner/AppDelegate.swift
================================================
import Cocoa
import FlutterMacOS
@main
class AppDelegate: FlutterAppDelegate {
override func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
return false
}
override func applicationSupportsSecureRestorableState(_ app: NSApplication) -> Bool {
return true
}
override func applicationShouldHandleReopen(_ sender: NSApplication, hasVisibleWindows flag: Bool) -> Bool {
if !flag {
for window in NSApp.windows {
if !window.isVisible {
window.setIsVisible(true)
}
window.makeKeyAndOrderFront(self)
NSApp.activate(ignoringOtherApps: true)
}
}
return true
}
}
================================================
FILE: macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json
================================================
{
"info": {
"version": 1,
"author": "xcode"
},
"images": [
{
"size": "16x16",
"idiom": "mac",
"filename": "app_icon_16.png",
"scale": "1x"
},
{
"size": "16x16",
"idiom": "mac",
"filename": "app_icon_32.png",
"scale": "2x"
},
{
"size": "32x32",
"idiom": "mac",
"filename": "app_icon_32.png",
"scale": "1x"
},
{
"size": "32x32",
"idiom": "mac",
"filename": "app_icon_64.png",
"scale": "2x"
},
{
"size": "128x128",
"idiom": "mac",
"filename": "app_icon_128.png",
"scale": "1x"
},
{
"size": "128x128",
"idiom": "mac",
"filename": "app_icon_256.png",
"scale": "2x"
},
{
"size": "256x256",
"idiom": "mac",
"filename": "app_icon_256.png",
"scale": "1x"
},
{
"size": "256x256",
"idiom": "mac",
"filename": "app_icon_512.png",
"scale": "2x"
},
{
"size": "512x512",
"idiom": "mac",
"filename": "app_icon_512.png",
"scale": "1x"
},
{
"size": "512x512",
"idiom": "mac",
"filename": "app_icon_1024.png",
"scale": "2x"
}
]
}
================================================
FILE: macos/Runner/Base.lproj/MainMenu.xib
================================================
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="14490.70" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES" customObjectInstantitationMethod="direct">
<dependencies>
<deployment identifier="macosx"/>
<plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="14490.70"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<objects>
<customObject id="-2" userLabel="File's Owner" customClass="NSApplication">
<connections>
<outlet property="delegate" destination="Voe-Tx-rLC" id="GzC-gU-4Uq"/>
</connections>
</customObject>
<customObject id="-1" userLabel="First Responder" customClass="FirstResponder"/>
<customObject id="-3" userLabel="Application" customClass="NSObject"/>
<customObject id="Voe-Tx-rLC" customClass="AppDelegate" customModule="Runner" customModuleProvider="target">
<connections>
<outlet property="applicationMenu" destination="uQy-DD-JDr" id="XBo-yE-nKs"/>
<outlet property="mainFlutterWindow" destination="QvC-M9-y7g" id="gIp-Ho-8D9"/>
</connections>
</customObject>
<customObject id="YLy-65-1bz" customClass="NSFontManager"/>
<menu title="Main Menu" systemMenu="main" id="AYu-sK-qS6">
<items>
<menuItem title="APP_NAME" id="1Xt-HY-uBw">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="APP_NAME" systemMenu="apple" id="uQy-DD-JDr">
<items>
<menuItem title="About APP_NAME" id="5kV-Vb-QxS">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="orderFrontStandardAboutPanel:" target="-1" id="Exp-CZ-Vem"/>
</connections>
</menuItem>
<menuItem isSeparatorItem="YES" id="VOq-y0-SEH"/>
<menuItem title="Preferences…" keyEquivalent="," id="BOF-NM-1cW"/>
<menuItem isSeparatorItem="YES" id="wFC-TO-SCJ"/>
<menuItem title="Services" id="NMo-om-nkz">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Services" systemMenu="services" id="hz9-B4-Xy5"/>
</menuItem>
<menuItem isSeparatorItem="YES" id="4je-JR-u6R"/>
<menuItem title="Hide APP_NAME" keyEquivalent="h" id="Olw-nP-bQN">
<connections>
<action selector="hide:" target="-1" id="PnN-Uc-m68"/>
</connections>
</menuItem>
<menuItem title="Hide Others" keyEquivalent="h" id="Vdr-fp-XzO">
<modifierMask key="keyEquivalentModifierMask" option="YES" command="YES"/>
<connections>
<action selector="hideOtherApplications:" target="-1" id="VT4-aY-XCT"/>
</connections>
</menuItem>
<menuItem title="Show All" id="Kd2-mp-pUS">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="unhideAllApplications:" target="-1" id="Dhg-Le-xox"/>
</connections>
</menuItem>
<menuItem isSeparatorItem="YES" id="kCx-OE-vgT"/>
<menuItem title="Quit APP_NAME" keyEquivalent="q" id="4sb-4s-VLi">
<connections>
<action selector="terminate:" target="-1" id="Te7-pn-YzF"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem title="Edit" id="5QF-Oa-p0T">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Edit" id="W48-6f-4Dl">
<items>
<menuItem title="Undo" keyEquivalent="z" id="dRJ-4n-Yzg">
<connections>
<action selector="undo:" target="-1" id="M6e-cu-g7V"/>
</connections>
</menuItem>
<menuItem title="Redo" keyEquivalent="Z" id="6dh-zS-Vam">
<connections>
<action selector="redo:" target="-1" id="oIA-Rs-6OD"/>
</connections>
</menuItem>
<menuItem isSeparatorItem="YES" id="WRV-NI-Exz"/>
<menuItem title="Cut" keyEquivalent="x" id="uRl-iY-unG">
<connections>
<action selector="cut:" target="-1" id="YJe-68-I9s"/>
</connections>
</menuItem>
<menuItem title="Copy" keyEquivalent="c" id="x3v-GG-iWU">
<connections>
<action selector="copy:" target="-1" id="G1f-GL-Joy"/>
</connections>
</menuItem>
<menuItem title="Paste" keyEquivalent="v" id="gVA-U4-sdL">
<connections>
<action selector="paste:" target="-1" id="UvS-8e-Qdg"/>
</connections>
</menuItem>
<menuItem title="Paste and Match Style" keyEquivalent="V" id="WeT-3V-zwk">
<modifierMask key="keyEquivalentModifierMask" option="YES" command="YES"/>
<connections>
<action selector="pasteAsPlainText:" target="-1" id="cEh-KX-wJQ"/>
</connections>
</menuItem>
<menuItem title="Delete" id="pa3-QI-u2k">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="delete:" target="-1" id="0Mk-Ml-PaM"/>
</connections>
</menuItem>
<menuItem title="Select All" keyEquivalent="a" id="Ruw-6m-B2m">
<connections>
<action selector="selectAll:" target="-1" id="VNm-Mi-diN"/>
</connections>
</menuItem>
<menuItem isSeparatorItem="YES" id="uyl-h8-XO2"/>
<menuItem title="Find" id="4EN-yA-p0u">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Find" id="1b7-l0-nxx">
<items>
<menuItem title="Find…" tag="1" keyEquivalent="f" id="Xz5-n4-O0W">
<connections>
<action selector="performFindPanelAction:" target="-1" id="cD7-Qs-BN4"/>
</connections>
</menuItem>
<menuItem title="Find and Replace…" tag="12" keyEquivalent="f" id="YEy-JH-Tfz">
<modifierMask key="keyEquivalentModifierMask" option="YES" command="YES"/>
<connections>
<action selector="performFindPanelAction:" target="-1" id="WD3-Gg-5AJ"/>
</connections>
</menuItem>
<menuItem title="Find Next" tag="2" keyEquivalent="g" id="q09-fT-Sye">
<connections>
<action selector="performFindPanelAction:" target="-1" id="NDo-RZ-v9R"/>
</connections>
</menuItem>
<menuItem title="Find Previous" tag="3" keyEquivalent="G" id="OwM-mh-QMV">
<connections>
<action selector="performFindPanelAction:" target="-1" id="HOh-sY-3ay"/>
</connections>
</menuItem>
<menuItem title="Use Selection for Find" tag="7" keyEquivalent="e" id="buJ-ug-pKt">
<connections>
<action selector="performFindPanelAction:" target="-1" id="U76-nv-p5D"/>
</connections>
</menuItem>
<menuItem title="Jump to Selection" keyEquivalent="j" id="S0p-oC-mLd">
<connections>
<action selector="centerSelectionInVisibleArea:" target="-1" id="IOG-6D-g5B"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem title="Spelling and Grammar" id="Dv1-io-Yv7">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Spelling" id="3IN-sU-3Bg">
<items>
<menuItem title="Show Spelling and Grammar" keyEquivalent=":" id="HFo-cy-zxI">
<connections>
<action selector="showGuessPanel:" target="-1" id="vFj-Ks-hy3"/>
</connections>
</menuItem>
<menuItem title="Check Document Now" keyEquivalent=";" id="hz2-CU-CR7">
<connections>
<action selector="checkSpelling:" target="-1" id="fz7-VC-reM"/>
</connections>
</menuItem>
<menuItem isSeparatorItem="YES" id="bNw-od-mp5"/>
<menuItem title="Check Spelling While Typing" id="rbD-Rh-wIN">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="toggleContinuousSpellChecking:" target="-1" id="7w6-Qz-0kB"/>
</connections>
</menuItem>
<menuItem title="Check Grammar With Spelling" id="mK6-2p-4JG">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="toggleGrammarChecking:" target="-1" id="muD-Qn-j4w"/>
</connections>
</menuItem>
<menuItem title="Correct Spelling Automatically" id="78Y-hA-62v">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="toggleAutomaticSpellingCorrection:" target="-1" id="2lM-Qi-WAP"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem title="Substitutions" id="9ic-FL-obx">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Substitutions" id="FeM-D8-WVr">
<items>
<menuItem title="Show Substitutions" id="z6F-FW-3nz">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="orderFrontSubstitutionsPanel:" target="-1" id="oku-mr-iSq"/>
</connections>
</menuItem>
<menuItem isSeparatorItem="YES" id="gPx-C9-uUO"/>
<menuItem title="Smart Copy/Paste" id="9yt-4B-nSM">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="toggleSmartInsertDelete:" target="-1" id="3IJ-Se-DZD"/>
</connections>
</menuItem>
<menuItem title="Smart Quotes" id="hQb-2v-fYv">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="toggleAutomaticQuoteSubstitution:" target="-1" id="ptq-xd-QOA"/>
</connections>
</menuItem>
<menuItem title="Smart Dashes" id="rgM-f4-ycn">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="toggleAutomaticDashSubstitution:" target="-1" id="oCt-pO-9gS"/>
</connections>
</menuItem>
<menuItem title="Smart Links" id="cwL-P1-jid">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="toggleAutomaticLinkDetection:" target="-1" id="Gip-E3-Fov"/>
</connections>
</menuItem>
<menuItem title="Data Detectors" id="tRr-pd-1PS">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="toggleAutomaticDataDetection:" target="-1" id="R1I-Nq-Kbl"/>
</connections>
</menuItem>
<menuItem title="Text Replacement" id="HFQ-gK-NFA">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="toggleAutomaticTextReplacement:" target="-1" id="DvP-Fe-Py6"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem title="Transformations" id="2oI-Rn-ZJC">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Transformations" id="c8a-y6-VQd">
<items>
<menuItem title="Make Upper Case" id="vmV-6d-7jI">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="uppercaseWord:" target="-1" id="sPh-Tk-edu"/>
</connections>
</menuItem>
<menuItem title="Make Lower Case" id="d9M-CD-aMd">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="lowercaseWord:" target="-1" id="iUZ-b5-hil"/>
</connections>
</menuItem>
<menuItem title="Capitalize" id="UEZ-Bs-lqG">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="capitalizeWord:" target="-1" id="26H-TL-nsh"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem title="Speech" id="xrE-MZ-jX0">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Speech" id="3rS-ZA-NoH">
<items>
<menuItem title="Start Speaking" id="Ynk-f8-cLZ">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="startSpeaking:" target="-1" id="654-Ng-kyl"/>
</connections>
</menuItem>
<menuItem title="Stop Speaking" id="Oyz-dy-DGm">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="stopSpeaking:" target="-1" id="dX8-6p-jy9"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem title="View" id="H8h-7b-M4v">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="View" id="HyV-fh-RgO">
<items>
<menuItem title="Enter Full Screen" keyEquivalent="f" id="4J7-dP-txa">
<modifierMask key="keyEquivalentModifierMask" control="YES" command="YES"/>
<connections>
<action selector="toggleFullScreen:" target="-1" id="dU3-MA-1Rq"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem title="Window" id="aUF-d1-5bR">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Window" systemMenu="window" id="Td7-aD-5lo">
<items>
<menuItem title="Minimize" keyEquivalent="m" id="OY7-WF-poV">
<connections>
<action selector="performMiniaturize:" target="-1" id="VwT-WD-YPe"/>
</connections>
</menuItem>
<menuItem title="Zoom" id="R4o-n2-Eq4">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="performZoom:" target="-1" id="DIl-cC-cCs"/>
</connections>
</menuItem>
<menuItem isSeparatorItem="YES" id="eu3-7i-yIM"/>
<menuItem title="Bring All to Front" id="LE2-aR-0XJ">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="arrangeInFront:" target="-1" id="DRN-fu-gQh"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem title="Help" id="EPT-qC-fAb">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Help" systemMenu="help" id="rJ0-wn-3NY"/>
</menuItem>
</items>
<point key="canvasLocation" x="142" y="-258"/>
</menu>
<window title="APP_NAME" allowsToolTipsWhenApplicationIsInactive="NO" autorecalculatesKeyViewLoop="NO" releasedWhenClosed="NO" animationBehavior="default" id="QvC-M9-y7g" customClass="MainFlutterWindow" customModule="Runner" customModuleProvider="target">
<windowStyleMask key="styleMask" titled="YES" closable="YES" miniaturizable="YES" resizable="YES"/>
<rect key="contentRect" x="335" y="390" width="800" height="600"/>
<rect key="screenRect" x="0.0" y="0.0" width="2560" height="1577"/>
<view key="contentView" wantsLayer="YES" id="EiT-Mj-1SZ">
<rect key="frame" x="0.0" y="0.0" width="800" height="600"/>
<autoresizingMask key="autoresizingMask"/>
</view>
</window>
</objects>
</document>
================================================
FILE: macos/Runner/Configs/AppInfo.xcconfig
================================================
// Application-level settings for the Runner target.
//
// This may be replaced with something auto-generated from metadata (e.g., pubspec.yaml) in the
// future. If not, the values below would default to using the project name when this becomes a
// 'flutter create' template.
// The application's name. By default this is also the title of the Flutter window.
PRODUCT_NAME = Lux
// The application's bundle identifier
PRODUCT_BUNDLE_IDENTIFIER = com.github.igoogolx.lux
// The copyright displayed in application information
PRODUCT_COPYRIGHT = Copyright © 2023 com.github.igoogolx. All rights reserved.
================================================
FILE: macos/Runner/Configs/Debug.xcconfig
================================================
#include "../../Flutter/Flutter-Debug.xcconfig"
#include "Warnings.xcconfig"
================================================
FILE: macos/Runner/Configs/Release.xcconfig
================================================
#include "../../Flutter/Flutter-Release.xcconfig"
#include "Warnings.xcconfig"
================================================
FILE: macos/Runner/Configs/Warnings.xcconfig
================================================
WARNING_CFLAGS = -Wall -Wconditional-uninitialized -Wnullable-to-nonnull-conversion -Wmissing-method-return-type -Woverlength-strings
GCC_WARN_UNDECLARED_SELECTOR = YES
CLANG_UNDEFINED_BEHAVIOR_SANITIZER_NULLABILITY = YES
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES
CLANG_WARN_PRAGMA_PACK = YES
CLANG_WARN_STRICT_PROTOTYPES = YES
CLANG_WARN_COMMA = YES
GCC_WARN_STRICT_SELECTOR_MATCH = YES
CLANG_WARN_OBJC_REPEATED_USE_OF_WEAK = YES
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES
GCC_WARN_SHADOW = YES
CLANG_WARN_UNREACHABLE_CODE = YES
================================================
FILE: macos/Runner/DebugProfile.entitlements
================================================
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>com.apple.security.app-sandbox</key>
<false/>
<key>com.apple.security.cs.allow-jit</key>
<true/>
<key>com.apple.security.network.server</key>
<true/>
</dict>
</plist>
================================================
FILE: macos/Runner/Info.plist
================================================
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>$(DEVELOPMENT_LANGUAGE)</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIconFile</key>
<string></string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>$(FLUTTER_BUILD_NAME)</string>
<key>CFBundleVersion</key>
<string>$(FLUTTER_BUILD_NUMBER)</string>
<key>LSMinimumSystemVersion</key>
<string>$(MACOSX_DEPLOYMENT_TARGET)</string>
<key>NSHumanReadableCopyright</key>
<string>$(PRODUCT_COPYRIGHT)</string>
<key>NSMainNibFile</key>
<string>MainMenu</string>
<key>NSPrincipalClass</key>
<string>NSApplication</string>
</dict>
</plist>
================================================
FILE: macos/Runner/MainFlutterWindow.swift
================================================
import Cocoa
import FlutterMacOS
import window_manager
// Add the LaunchAtLogin module
import LaunchAtLogin
class MainFlutterWindow: NSWindow {
override func awakeFromNib() {
let flutterViewController = FlutterViewController()
let windowFrame = self.frame
self.contentViewController = flutterViewController
self.setFrame(windowFrame, display: true)
// Add FlutterMethodChannel platform code
FlutterMethodChannel(
name: "launch_at_startup", binaryMessenger: flutterViewController.engine.binaryMessenger
)
.setMethodCallHandler { (_ call: FlutterMethodCall, result: @escaping FlutterResult) in
switch call.method {
case "launchAtStartupIsEnabled":
result(LaunchAtLogin.isEnabled)
case "launchAtStartupSetEnabled":
if let arguments = call.arguments as? [String: Any] {
LaunchAtLogin.isEnabled = arguments["setEnabledValue"] as! Bool
}
result(nil)
default:
result(FlutterMethodNotImplemented)
}
}
//
RegisterGeneratedPlugins(registry: flutterViewController)
super.awakeFromNib()
}
override public func order(_ place: NSWindow.OrderingMode, relativeTo otherWin: Int) {
super.order(place, relativeTo: otherWin)
hiddenWindowAtLaunch()
}
}
================================================
FILE: macos/Runner/Release.entitlements
================================================
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>com.apple.security.app-sandbox</key>
<false/>
</dict>
</plist>
================================================
FILE: macos/Runner.xcodeproj/project.pbxproj
================================================
// !$*UTF8*$!
{
archiveVersion = 1;
classes = {
};
objectVersion = 54;
objects = {
/* Begin PBXAggregateTarget section */
33CC111A2044C6BA0003C045 /* Flutter Assemble */ = {
isa = PBXAggregateTarget;
buildConfigurationList = 33CC111B2044C6BA0003C045 /* Build configuration list for PBXAggregateTarget "Flutter Assemble" */;
buildPhases = (
33CC111E2044C6BF0003C045 /* ShellScript */,
);
dependencies = (
);
name = "Flutter Assemble";
productName = FLX;
};
/* End PBXAggregateTarget section */
/* Begin PBXBuildFile section */
331C80D8294CF71000263BE5 /* RunnerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 331C80D7294CF71000263BE5 /* RunnerTests.swift */; };
335BBD1B22A9A15E00E9071D /* GeneratedPluginRegistrant.swift in Sources */ = {isa = PBXBuildFile; fileRef = 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */; };
33CC10F12044A3C60003C045 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC10F02044A3C60003C045 /* AppDelegate.swift */; };
33CC10F32044A3C60003C045 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F22044A3C60003C045 /* Assets.xcassets */; };
33CC10F62044A3C60003C045 /* MainMenu.xib in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F42044A3C60003
gitextract_n5skmjta/
├── .github/
│ ├── pull_request_template.md
│ └── workflows/
│ ├── build.yml
│ ├── virusTotal.yml
│ └── winget.yml
├── .gitignore
├── .metadata
├── CHANGELOG.md
├── LICENSE
├── README.md
├── analysis_options.yaml
├── assets/
│ └── tray.icns
├── distribute_options.yaml
├── l10n.yaml
├── lib/
│ ├── app.dart
│ ├── const/
│ │ └── const.dart
│ ├── core/
│ │ ├── checksum.dart
│ │ ├── core_config.dart
│ │ └── core_manager.dart
│ ├── dashboard.dart
│ ├── error.dart
│ ├── home.dart
│ ├── l10n/
│ │ ├── app_en.arb
│ │ ├── app_localizations.dart
│ │ ├── app_localizations_en.dart
│ │ ├── app_localizations_zh.dart
│ │ └── app_zh.arb
│ ├── main.dart
│ ├── model/
│ │ └── app.dart
│ ├── theme.dart
│ ├── tr.dart
│ ├── tray.dart
│ ├── util/
│ │ ├── elevate.dart
│ │ ├── notifier.dart
│ │ ├── process_manager.dart
│ │ └── utils.dart
│ └── widget/
│ ├── app_body.dart
│ ├── app_bottom_bar.dart
│ ├── app_header_bar.dart
│ ├── error/
│ │ ├── core_run_error_handler.dart
│ │ └── release_mode_error_widget.dart
│ ├── progress_indicator.dart
│ ├── proxy_item_action_menu.dart
│ ├── proxy_list_card.dart
│ └── proxy_list_item.dart
├── macos/
│ ├── .gitignore
│ ├── Flutter/
│ │ ├── Flutter-Debug.xcconfig
│ │ ├── Flutter-Release.xcconfig
│ │ └── GeneratedPluginRegistrant.swift
│ ├── Podfile
│ ├── Runner/
│ │ ├── AppDelegate.swift
│ │ ├── Assets.xcassets/
│ │ │ └── AppIcon.appiconset/
│ │ │ └── Contents.json
│ │ ├── Base.lproj/
│ │ │ └── MainMenu.xib
│ │ ├── Configs/
│ │ │ ├── AppInfo.xcconfig
│ │ │ ├── Debug.xcconfig
│ │ │ ├── Release.xcconfig
│ │ │ └── Warnings.xcconfig
│ │ ├── DebugProfile.entitlements
│ │ ├── Info.plist
│ │ ├── MainFlutterWindow.swift
│ │ └── Release.entitlements
│ ├── Runner.xcodeproj/
│ │ ├── project.pbxproj
│ │ ├── project.xcworkspace/
│ │ │ └── xcshareddata/
│ │ │ └── IDEWorkspaceChecks.plist
│ │ └── xcshareddata/
│ │ └── xcschemes/
│ │ └── Runner.xcscheme
│ ├── Runner.xcworkspace/
│ │ ├── contents.xcworkspacedata
│ │ └── xcshareddata/
│ │ ├── IDEWorkspaceChecks.plist
│ │ └── swiftpm/
│ │ └── Package.resolved
│ ├── RunnerTests/
│ │ └── RunnerTests.swift
│ └── packaging/
│ └── dmg/
│ └── make_config.yaml
├── pubspec.yaml
├── scripts/
│ ├── constant.dart
│ ├── init.dart
│ └── update_core_sha256.dart
├── test/
│ └── widget_test.dart
└── windows/
├── .gitignore
├── CMakeLists.txt
├── flutter/
│ ├── CMakeLists.txt
│ ├── generated_plugin_registrant.cc
│ ├── generated_plugin_registrant.h
│ └── generated_plugins.cmake
├── packaging/
│ └── exe/
│ ├── make_config.yaml
│ └── setup.iss
└── runner/
├── CMakeLists.txt
├── Runner.rc
├── flutter_window.cpp
├── flutter_window.h
├── main.cpp
├── resource.h
├── runner.exe.manifest
├── utils.cpp
├── utils.h
├── win32_window.cpp
└── win32_window.h
SYMBOL INDEX (239 symbols across 38 files)
FILE: lib/app.dart
class App (line 12) | class App extends StatefulWidget {
method createState (line 20) | State<App> createState()
class _App (line 23) | class _App extends State<App> {
method initState (line 28) | void initState()
method build (line 33) | Widget build(BuildContext context)
FILE: lib/const/const.dart
class LuxCoreName (line 5) | class LuxCoreName {
class Paths (line 27) | class Paths {
type ProxyItemAction (line 63) | enum ProxyItemAction {
FILE: lib/core/checksum.dart
function verifyCoreBinary (line 11) | Future<void> verifyCoreBinary(String filePath)
FILE: lib/core/core_config.dart
function readConfig (line 7) | Future<Map<String, dynamic>> readConfig()
function readSetting (line 17) | Future<Map<String, dynamic>> readSetting()
function convertTheme (line 30) | ThemeMode convertTheme(String theme)
function readTheme (line 41) | Future<ThemeMode> readTheme()
type ClientMode (line 49) | enum ClientMode {
function readClientMode (line 54) | Future<ClientMode> readClientMode()
function readAutoLaunch (line 65) | Future<bool> readAutoLaunch()
function readAutoConnect (line 73) | Future<bool> readAutoConnect()
function readLanguage (line 81) | Future<String> readLanguage()
type ProxyMode (line 89) | enum ProxyMode { tun, system, mixed }
function readProxyMode (line 91) | Future<ProxyMode> readProxyMode()
function sortProxyList (line 107) | List<ProxyList> sortProxyList(
function convertProxyListToGroup (line 124) | List<ProxyList> convertProxyListToGroup(
class ProxyItem (line 150) | class ProxyItem {
method toJson (line 171) | Map<String, dynamic> toJson()
class ProxyList (line 177) | class ProxyList {
method toJson (line 192) | Map<String, dynamic> toJson()
class SubscriptionItem (line 196) | class SubscriptionItem {
method toJson (line 215) | Map<String, dynamic> toJson()
class SubscriptionList (line 223) | class SubscriptionList {
method toJson (line 237) | Map<String, dynamic> toJson()
class ProxyListGroup (line 240) | class ProxyListGroup {
class RuleList (line 254) | class RuleList {
method toJson (line 266) | Map<String, dynamic> toJson()
class Speed (line 270) | class Speed {
class Total (line 284) | class Total {
class Proxy (line 298) | class Proxy {
class Direct (line 312) | class Direct {
class TrafficData (line 326) | class TrafficData {
class RuntimeStatus (line 340) | class RuntimeStatus {
class Setting (line 357) | class Setting {
FILE: lib/core/core_manager.dart
function findAvailablePort (line 16) | Future<int> findAvailablePort(int startPort, int endPort)
function _parseAndDecode (line 30) | Map<String, dynamic> _parseAndDecode(String response)
function parseJson (line 34) | Future<Map<String, dynamic>> parseJson(String text)
class CoreManager (line 38) | class CoreManager {
method makeRequestUntilSuccess (line 100) | Future<void> makeRequestUntilSuccess(String url)
method ping (line 123) | Future<void> ping()
method stop (line 131) | Future<void> stop()
method start (line 139) | Future<void> start()
method getIsStarted (line 147) | Future<bool> getIsStarted()
method getCurProxyInfo (line 160) | Future<String> getCurProxyInfo()
method getProxyList (line 173) | Future<ProxyList> getProxyList()
method getRuleList (line 178) | Future<RuleList> getRuleList()
method selectProxy (line 183) | Future<void> selectProxy(String id)
method selectRule (line 187) | Future<void> selectRule(String id)
method exitCore (line 191) | Future<void> exitCore()
method safeExit (line 206) | Future<void> safeExit()
method restart (line 215) | Future<void> restart()
method run (line 220) | Future<void> run()
method getTrafficChannel (line 226) | Future<WebSocketChannel?> getTrafficChannel()
method getRuntimeStatusChannel (line 233) | Future<WebSocketChannel?> getRuntimeStatusChannel()
method getEventChannel (line 240) | Future<WebSocketChannel?> getEventChannel()
method getSetting (line 247) | Future<Setting> getSetting()
method deleteProxies (line 256) | Future<void> deleteProxies(List<String> ids)
method getSubscriptionList (line 260) | Future<SubscriptionList> getSubscriptionList()
FILE: lib/dashboard.dart
class Dashboard (line 13) | class Dashboard extends StatefulWidget {
method createState (line 23) | State<Dashboard> createState()
class _DashboardState (line 26) | class _DashboardState extends State<Dashboard> with WindowListener {
method initState (line 32) | void initState()
method dispose (line 39) | void dispose()
method onWindowClose (line 45) | void onWindowClose()
method onCurProxyInfoChange (line 57) | void onCurProxyInfoChange(String info)
method build (line 64) | Widget build(BuildContext context)
FILE: lib/error.dart
class CoreHttpError (line 1) | class CoreHttpError {
class CoreRunError (line 18) | class CoreRunError extends Error {
FILE: lib/home.dart
class Home (line 30) | class Home extends StatefulWidget {
method createState (line 36) | State<Home> createState()
function initClient (line 39) | Future<void> initClient(CoreManager? coreManager)
class _HomeState (line 44) | class _HomeState extends State<Home>
method _init (line 57) | void _init(AppStateModel appState)
method _onCoreReady (line 106) | void _onCoreReady(AppStateModel appState)
method initState (line 177) | void initState()
method _handleExitRequest (line 185) | Future<AppExitResponse> _handleExitRequest()
method dispose (line 193) | void dispose()
method onTrayIconMouseDown (line 202) | void onTrayIconMouseDown()
method onTrayIconRightMouseDown (line 208) | void onTrayIconRightMouseDown()
method onTrayMenuItemClick (line 213) | void onTrayMenuItemClick(MenuItem menuItem)
method build (line 282) | Widget build(BuildContext context)
FILE: lib/l10n/app_localizations.dart
class AppLocalizations (line 64) | abstract class AppLocalizations {
method of (line 70) | AppLocalizations? of(BuildContext context)
method connectOnOpenErrMsg (line 129) | String connectOnOpenErrMsg(Object msg)
method setAutoLaunchErrMsg (line 135) | String setAutoLaunchErrMsg(Object msg)
class _AppLocalizationsDelegate (line 300) | class _AppLocalizationsDelegate
method load (line 305) | Future<AppLocalizations> load(Locale locale)
method isSupported (line 310) | bool isSupported(Locale locale)
method shouldReload (line 314) | bool shouldReload(_AppLocalizationsDelegate old)
function lookupAppLocalizations (line 317) | AppLocalizations lookupAppLocalizations(Locale locale)
FILE: lib/l10n/app_localizations_en.dart
class AppLocalizationsEn (line 8) | class AppLocalizationsEn extends AppLocalizations {
method connectOnOpenErrMsg (line 24) | String connectOnOpenErrMsg(Object msg)
method setAutoLaunchErrMsg (line 29) | String setAutoLaunchErrMsg(Object msg)
FILE: lib/l10n/app_localizations_zh.dart
class AppLocalizationsZh (line 8) | class AppLocalizationsZh extends AppLocalizations {
method connectOnOpenErrMsg (line 24) | String connectOnOpenErrMsg(Object msg)
method setAutoLaunchErrMsg (line 29) | String setAutoLaunchErrMsg(Object msg)
FILE: lib/main.dart
function main (line 17) | void main(List<String> args)
FILE: lib/model/app.dart
class AppStateModel (line 3) | class AppStateModel extends ChangeNotifier {
method updateTheme (line 16) | void updateTheme(ThemeMode newTheme)
method updateLocale (line 21) | void updateLocale(Locale newLocale)
method updateIsStarted (line 26) | void updateIsStarted(bool newIsStarted)
method updateSelectedProxyId (line 34) | void updateSelectedProxyId(String newSelectedProxyId)
FILE: lib/theme.dart
class AppTheme (line 19) | abstract final class AppTheme {
FILE: lib/tr.dart
function initTr (line 7) | void initTr(BuildContext trContext)
function tr (line 11) | AppLocalizations tr()
class LocaleModel (line 16) | class LocaleModel extends ChangeNotifier {
method set (line 19) | void set(Locale locale)
FILE: lib/tray.dart
function initSystemTray (line 5) | Future<void> initSystemTray()
FILE: lib/util/elevate.dart
function getFileOwner (line 7) | Future<String?> getFileOwner(String path)
function elevate (line 24) | Future<int> elevate(String path, message)
FILE: lib/util/notifier.dart
class Notifier (line 8) | class Notifier {
method ensureInitialized (line 13) | Future<void> ensureInitialized()
method show (line 40) | Future<void> show(String body, [String? payload])
method onDidReceiveNotificationResponse (line 56) | void onDidReceiveNotificationResponse(
FILE: lib/util/process_manager.dart
class ProcessManager (line 11) | class ProcessManager {
method run (line 20) | Future<void> run()
method exit (line 62) | void exit()
method watchExit (line 66) | void watchExit()
FILE: lib/util/utils.dart
function getHomeDir (line 20) | Future<String> getHomeDir()
function readJsonFile (line 27) | Future<Map<String, dynamic>> readJsonFile(String filePath)
function exitApp (line 36) | void exitApp()
function setAutoConnect (line 40) | Future<void> setAutoConnect(CoreManager? coreManager)
function setAutoLaunch (line 57) | Future<void> setAutoLaunch(CoreManager? coreManager)
function convertLocale (line 79) | Locale convertLocale(String locale)
function getLocale (line 101) | Future<Locale> getLocale()
type InitI10nLabel (line 106) | typedef InitI10nLabel = ({
function getInitI10nLabel (line 111) | Future<InitI10nLabel> getInitI10nLabel()
function checkForUpdate (line 132) | Future<void> checkForUpdate()
function formatBytes (line 152) | String formatBytes(int bytes)
function getAppVersion (line 169) | Future<String> getAppVersion()
function resetSystemProxy (line 184) | void resetSystemProxy()
FILE: lib/widget/app_body.dart
class AppBody (line 12) | class AppBody extends StatefulWidget {
method createState (line 25) | State<AppBody> createState()
class _AppBodyState (line 28) | class _AppBodyState extends State<AppBody> with WindowListener {
method refreshProxyList (line 42) | Future<void> refreshProxyList()
method refreshData (line 66) | Future<void> refreshData()
method handleSelectProxy (line 72) | Future<void> handleSelectProxy(String? id)
method onWindowFocus (line 100) | void onWindowFocus()
method initState (line 105) | void initState()
method dispose (line 112) | void dispose()
method getIsCollapsed (line 117) | bool getIsCollapsed(ProxyList item)
method handleCollapse (line 123) | void handleCollapse(ProxyList item)
method _handleDeleteItem (line 129) | void _handleDeleteItem(ProxyItem item)
method _handleEditItem (line 137) | void _handleEditItem(ProxyItem item)
method _handleQrCode (line 142) | void _handleQrCode(ProxyItem item)
method _handleItemChange (line 147) | void _handleItemChange(ProxyItemAction action, ProxyItem item)
method build (line 159) | Widget build(BuildContext context)
FILE: lib/widget/app_bottom_bar.dart
class AppBottomBar (line 12) | class AppBottomBar extends StatefulWidget {
method createState (line 18) | State<AppBottomBar> createState()
class _AppBottomBarState (line 21) | class _AppBottomBarState extends State<AppBottomBar> with WindowListener {
method refreshMode (line 27) | Future<void> refreshMode()
method initState (line 35) | void initState()
method onWindowFocus (line 56) | void onWindowFocus()
method onWindowClose (line 62) | void onWindowClose()
method dispose (line 67) | void dispose()
method build (line 74) | Widget build(BuildContext context)
class TrafficState (line 152) | class TrafficState {
function getModeLabel (line 192) | String getModeLabel(ProxyMode value)
FILE: lib/widget/app_header_bar.dart
class AppHeaderBar (line 15) | class AppHeaderBar extends StatefulWidget {
method createState (line 30) | State<AppHeaderBar> createState()
class _State (line 33) | class _State extends State<AppHeaderBar> with WindowListener {
method openWebDashboard (line 41) | void openWebDashboard()
method refreshData (line 45) | Future<void> refreshData()
method refreshIsStarted (line 57) | Future<void> refreshIsStarted()
method refreshCurProxyInfo (line 64) | Future<void> refreshCurProxyInfo()
method refreshRuleList (line 71) | Future<void> refreshRuleList()
method onSwitchChanged (line 78) | void onSwitchChanged(bool value)
method handleSelectRule (line 101) | Future<void> handleSelectRule(String? id)
method getRuleLabel (line 120) | String getRuleLabel(String name)
method dispose (line 136) | void dispose()
method initState (line 143) | void initState()
method onWindowFocus (line 166) | void onWindowFocus()
method _handleAdd (line 170) | void _handleAdd()
method build (line 176) | Widget build(BuildContext context)
FILE: lib/widget/error/core_run_error_handler.dart
class CoreRunErrorHandler (line 13) | class CoreRunErrorHandler extends StatefulWidget {
method createState (line 22) | State<CoreRunErrorHandler> createState()
class _CoreRunErrorHandlerState (line 25) | class _CoreRunErrorHandlerState extends State<CoreRunErrorHandler> {
method initState (line 30) | void initState()
method build (line 42) | Widget build(BuildContext context)
FILE: lib/widget/error/release_mode_error_widget.dart
class ReleaseModeErrorWidget (line 8) | class ReleaseModeErrorWidget extends StatelessWidget {
method build (line 14) | Widget build(BuildContext context)
FILE: lib/widget/progress_indicator.dart
class AppProgressIndicator (line 3) | class AppProgressIndicator extends StatefulWidget {
method createState (line 7) | State<AppProgressIndicator> createState()
class _AppProgressIndicatorState (line 10) | class _AppProgressIndicatorState extends State<AppProgressIndicator>
method initState (line 15) | void initState()
method dispose (line 27) | void dispose()
method build (line 33) | Widget build(BuildContext context)
FILE: lib/widget/proxy_item_action_menu.dart
class ProxyItemActionMenu (line 7) | class ProxyItemActionMenu extends StatefulWidget {
method createState (line 21) | State<ProxyItemActionMenu> createState()
class _ProxyItemActionMenuState (line 24) | class _ProxyItemActionMenuState extends State<ProxyItemActionMenu> {
method dispose (line 27) | void dispose()
method build (line 33) | Widget build(BuildContext context)
FILE: lib/widget/proxy_list_card.dart
class ProxyListCard (line 8) | class ProxyListCard extends StatefulWidget {
method createState (line 26) | State<ProxyListCard> createState()
class _ProxyListCardState (line 29) | class _ProxyListCardState extends State<ProxyListCard> {
method getTitle (line 30) | String getTitle()
method dispose (line 50) | void dispose()
method build (line 55) | Widget build(BuildContext context)
FILE: lib/widget/proxy_list_item.dart
class ProxyListItem (line 7) | class ProxyListItem extends StatefulWidget {
method createState (line 17) | State<ProxyListItem> createState()
class _ProxyListItemState (line 20) | class _ProxyListItemState extends State<ProxyListItem> {
method dispose (line 25) | void dispose()
method build (line 31) | Widget build(BuildContext context)
FILE: scripts/init.dart
function downloadFileWith (line 20) | Future<void> downloadFileWith(String url, String savePath)
function downloadInnoSetupChineseItransFile (line 33) | void downloadInnoSetupChineseItransFile()
function downloadLatestCore (line 43) | Future downloadLatestCore(String arch, String token)
function main (line 74) | void main(List<String> arguments)
FILE: scripts/update_core_sha256.dart
class ReleaseAsset (line 8) | class ReleaseAsset {
method toJson (line 18) | Map<String, dynamic> toJson()
class Release (line 24) | class Release {
method toJson (line 37) | Map<String, dynamic> toJson()
function replaceChecksumSectionInFile (line 41) | Future<void> replaceChecksumSectionInFile(
function getSha256 (line 57) | Future<String> getSha256()
function main (line 84) | Future<void> main()
FILE: windows/flutter/generated_plugin_registrant.cc
function RegisterPlugins (line 16) | void RegisterPlugins(flutter::PluginRegistry* registry) {
FILE: windows/runner/flutter_window.cpp
function LRESULT (line 45) | LRESULT
FILE: windows/runner/flutter_window.h
function class (line 12) | class FlutterWindow : public Win32Window {
FILE: windows/runner/main.cpp
function wWinMain (line 8) | int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev,
FILE: windows/runner/utils.cpp
function CreateAndAttachConsole (line 10) | void CreateAndAttachConsole() {
function GetCommandLineArguments (line 24) | std::vector<std::string> GetCommandLineArguments() {
function Utf8FromUtf16 (line 44) | std::string Utf8FromUtf16(const wchar_t* utf16_string) {
FILE: windows/runner/win32_window.cpp
function Scale (line 38) | int Scale(int source, double scale_factor) {
function EnableFullDpiSupportIfAvailable (line 44) | void EnableFullDpiSupportIfAvailable(HWND hwnd) {
class WindowClassRegistrar (line 61) | class WindowClassRegistrar {
method WindowClassRegistrar (line 66) | static WindowClassRegistrar* GetInstance() {
method WindowClassRegistrar (line 82) | WindowClassRegistrar() = default;
function wchar_t (line 91) | const wchar_t* WindowClassRegistrar::GetWindowClass() {
function LRESULT (line 159) | LRESULT CALLBACK Win32Window::WndProc(HWND const window,
function LRESULT (line 178) | LRESULT
function Win32Window (line 238) | Win32Window* Win32Window::GetThisFromHandle(HWND const window) noexcept {
function RECT (line 254) | RECT Win32Window::GetClientArea() {
function HWND (line 260) | HWND Win32Window::GetHandle() {
FILE: windows/runner/win32_window.h
type Size (line 21) | struct Size {
Condensed preview — 92 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (300K chars).
[
{
"path": ".github/pull_request_template.md",
"chars": 114,
"preview": "## Checklist before merging\n\n- [ ] Upgrade is ok?\n- [ ] First installation is ok?\n- [ ] DOH(Dns-Over-Https) is ok?"
},
{
"path": ".github/workflows/build.yml",
"chars": 3953,
"preview": "name: Build\n\non:\n push:\n # Sequence of patterns matched against refs/tags\n tags:\n - v*.*.* # Push "
},
{
"path": ".github/workflows/virusTotal.yml",
"chars": 396,
"preview": "name: VirusTotal\n\non:\n release:\n types: [published]\n\njobs:\n virustotal:\n runs-on: ubuntu-latest\n steps:\n "
},
{
"path": ".github/workflows/winget.yml",
"chars": 475,
"preview": "name: Publish to WinGet\n\non:\n release:\n types: [published]\n\njobs:\n publish:\n # Action can only be run on windows"
},
{
"path": ".gitignore",
"chars": 800,
"preview": "# Miscellaneous\n*.class\n*.log\n*.pyc\n*.swp\n.DS_Store\n.atom/\n.build/\n.buildlog/\n.history\n.svn/\n.swiftpm/\nmigrate_working_d"
},
{
"path": ".metadata",
"chars": 1078,
"preview": "# This file tracks properties of this Flutter project.\n# Used by Flutter tool to assess capabilities and perform upgrade"
},
{
"path": "CHANGELOG.md",
"chars": 184,
"preview": "## What's Changed\n\n### Bug fixes 🐛\n\n* fix(windows): [high cpu usage](https://github.com/flutter/flutter/issues/182501) o"
},
{
"path": "LICENSE",
"chars": 35149,
"preview": " GNU GENERAL PUBLIC LICENSE\n Version 3, 29 June 2007\n\n Copyright (C) 2007 Free "
},
{
"path": "README.md",
"chars": 5867,
"preview": "<a name=\"readme-top\"></a>\n\n<br />\n<div align=\"center\">\n <a href=\"https://github.com/igoogolx/lux\">\n <img src=\"assets"
},
{
"path": "analysis_options.yaml",
"chars": 1454,
"preview": "# This file configures the analyzer, which statically analyzes Dart code to\n# check for errors, warnings, and lints.\n#\n#"
},
{
"path": "distribute_options.yaml",
"chars": 418,
"preview": "output: dist/\nreleases:\n - name: windows-latest\n jobs:\n - name: release-dev-windows\n package:\n "
},
{
"path": "l10n.yaml",
"chars": 96,
"preview": "arb-dir: lib/l10n\ntemplate-arb-file: app_en.arb\noutput-localization-file: app_localizations.dart"
},
{
"path": "lib/app.dart",
"chars": 1620,
"preview": "import 'package:flutter/material.dart';\nimport 'package:flutter_localizations/flutter_localizations.dart';\nimport 'packa"
},
{
"path": "lib/const/const.dart",
"chars": 1567,
"preview": "import 'dart:io';\n\nimport 'package:path/path.dart' as path;\n\nclass LuxCoreName {\n static String get platform {\n if ("
},
{
"path": "lib/core/checksum.dart",
"chars": 1003,
"preview": "import 'dart:io';\n\nimport 'package:crypto/crypto.dart';\n\n// checksum-start\n const darwinAmd64Checksum = \"6146982cd80750d"
},
{
"path": "lib/core/core_config.dart",
"chars": 9109,
"preview": "import 'package:flutter/material.dart';\nimport 'package:lux/util/utils.dart';\nimport 'package:path/path.dart' as path;\n\n"
},
{
"path": "lib/core/core_manager.dart",
"chars": 7425,
"preview": "import 'dart:async';\nimport 'dart:convert';\nimport 'dart:io';\n\nimport 'package:connectivity_plus/connectivity_plus.dart'"
},
{
"path": "lib/dashboard.dart",
"chars": 2064,
"preview": "import 'dart:async';\nimport 'dart:io';\n\nimport 'package:flutter/material.dart';\nimport 'package:lux/util/utils.dart';\nim"
},
{
"path": "lib/error.dart",
"chars": 542,
"preview": "class CoreHttpError {\n final String message;\n final int code;\n\n CoreHttpError({required this.message, required this.c"
},
{
"path": "lib/home.dart",
"chars": 8257,
"preview": "import 'dart:convert';\nimport 'dart:io';\nimport 'dart:ui';\n\nimport 'package:connectivity_plus/connectivity_plus.dart';\ni"
},
{
"path": "lib/l10n/app_en.arb",
"chars": 1544,
"preview": "{\n \"trayDashboardLabel\": \"Open Dashboard\",\n \"exit\": \"Exit\",\n \"noConnectionMsg\": \"No available network. Disconnected\","
},
{
"path": "lib/l10n/app_localizations.dart",
"chars": 9953,
"preview": "import 'dart:async';\n\nimport 'package:flutter/foundation.dart';\nimport 'package:flutter/widgets.dart';\nimport 'package:f"
},
{
"path": "lib/l10n/app_localizations_en.dart",
"chars": 2679,
"preview": "// ignore: unused_import\nimport 'package:intl/intl.dart' as intl;\nimport 'app_localizations.dart';\n\n// ignore_for_file: "
},
{
"path": "lib/l10n/app_localizations_zh.dart",
"chars": 2224,
"preview": "// ignore: unused_import\nimport 'package:intl/intl.dart' as intl;\nimport 'app_localizations.dart';\n\n// ignore_for_file: "
},
{
"path": "lib/l10n/app_zh.arb",
"chars": 1089,
"preview": "{\n \"trayDashboardLabel\": \"管理面板\",\n \"exit\": \"退出\",\n \"noConnectionMsg\": \"无网络连接,已断开\",\n \"reconnectedMsg\": \"已重连\",\n \"connec"
},
{
"path": "lib/main.dart",
"chars": 2065,
"preview": "import 'dart:io';\nimport 'dart:ui';\n\nimport 'package:dio/dio.dart';\nimport 'package:flutter/foundation.dart';\nimport 'pa"
},
{
"path": "lib/model/app.dart",
"chars": 937,
"preview": "import 'package:flutter/material.dart';\n\nclass AppStateModel extends ChangeNotifier {\n late ThemeMode _theme;\n late Lo"
},
{
"path": "lib/theme.dart",
"chars": 11105,
"preview": "import 'package:flex_color_scheme/flex_color_scheme.dart';\nimport 'package:flutter/cupertino.dart';\nimport 'package:flut"
},
{
"path": "lib/tr.dart",
"chars": 444,
"preview": "import 'package:flutter/cupertino.dart';\n\nimport 'l10n/app_localizations.dart';\n\nBuildContext? buildContext;\n\nvoid initT"
},
{
"path": "lib/tray.dart",
"chars": 701,
"preview": "import 'dart:io';\nimport 'package:lux/tr.dart';\nimport 'package:tray_manager/tray_manager.dart';\n\nFuture<void> initSyste"
},
{
"path": "lib/util/elevate.dart",
"chars": 1123,
"preview": "import 'dart:convert';\nimport 'dart:io';\nimport 'package:flutter/cupertino.dart';\n\nvar sudoCommandPath = \"/usr/bin/osasc"
},
{
"path": "lib/util/notifier.dart",
"chars": 2267,
"preview": "import 'dart:io';\n\nimport 'package:flutter/cupertino.dart';\nimport 'package:flutter_local_notifications/flutter_local_no"
},
{
"path": "lib/util/process_manager.dart",
"chars": 2178,
"preview": "import 'dart:convert';\nimport 'dart:io';\n\nimport 'package:flutter/foundation.dart';\nimport 'package:lux/core/checksum.da"
},
{
"path": "lib/util/utils.dart",
"chars": 5481,
"preview": "import 'dart:convert';\nimport 'dart:io';\n\nimport 'package:dio/dio.dart';\nimport 'package:flutter/cupertino.dart';\nimport"
},
{
"path": "lib/widget/app_body.dart",
"chars": 5165,
"preview": "import 'package:flutter/material.dart';\nimport 'package:lux/const/const.dart';\nimport 'package:lux/model/app.dart';\nimpo"
},
{
"path": "lib/widget/app_bottom_bar.dart",
"chars": 5460,
"preview": "import 'dart:convert';\n\nimport 'package:flutter/material.dart';\nimport 'package:web_socket_channel/web_socket_channel.da"
},
{
"path": "lib/widget/app_header_bar.dart",
"chars": 5904,
"preview": "import 'dart:collection';\nimport 'dart:convert';\n\nimport 'package:flutter/material.dart';\nimport 'package:lux/model/app."
},
{
"path": "lib/widget/error/core_run_error_handler.dart",
"chars": 4792,
"preview": "import 'dart:io';\n\nimport 'package:flutter/material.dart';\nimport 'package:lux/tr.dart';\nimport 'package:lux/util/elevat"
},
{
"path": "lib/widget/error/release_mode_error_widget.dart",
"chars": 772,
"preview": "import 'package:flutter/material.dart';\nimport 'package:lux/widget/error/core_run_error_handler.dart';\n\nimport '../../er"
},
{
"path": "lib/widget/progress_indicator.dart",
"chars": 904,
"preview": "import 'package:flutter/material.dart';\n\nclass AppProgressIndicator extends StatefulWidget {\n const AppProgressIndicato"
},
{
"path": "lib/widget/proxy_item_action_menu.dart",
"chars": 3450,
"preview": "import 'package:flutter/material.dart';\nimport 'package:lux/const/const.dart';\nimport 'package:lux/model/app.dart';\nimpo"
},
{
"path": "lib/widget/proxy_list_card.dart",
"chars": 3905,
"preview": "import 'package:flutter/material.dart';\nimport 'package:lux/const/const.dart';\nimport 'package:lux/tr.dart';\nimport 'pac"
},
{
"path": "lib/widget/proxy_list_item.dart",
"chars": 1683,
"preview": "import 'package:flutter/material.dart';\nimport 'package:lux/widget/proxy_item_action_menu.dart';\n\nimport '../const/const"
},
{
"path": "macos/.gitignore",
"chars": 89,
"preview": "# Flutter-related\n**/Flutter/ephemeral/\n**/Pods/\n\n# Xcode-related\n**/dgph\n**/xcuserdata/\n"
},
{
"path": "macos/Flutter/Flutter-Debug.xcconfig",
"chars": 125,
"preview": "#include? \"Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig\"\n#include \"ephemeral/Flutter-Generated.xccon"
},
{
"path": "macos/Flutter/Flutter-Release.xcconfig",
"chars": 127,
"preview": "#include? \"Pods/Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig\"\n#include \"ephemeral/Flutter-Generated.xcc"
},
{
"path": "macos/Flutter/GeneratedPluginRegistrant.swift",
"chars": 1123,
"preview": "//\n// Generated file. Do not edit.\n//\n\nimport FlutterMacOS\nimport Foundation\n\nimport connectivity_plus\nimport flutter_l"
},
{
"path": "macos/Podfile",
"chars": 1389,
"preview": "platform :osx, '10.14'\n\n# CocoaPods analytics sends network stats synchronously affecting flutter build latency.\nENV['CO"
},
{
"path": "macos/Runner/AppDelegate.swift",
"chars": 803,
"preview": "import Cocoa\nimport FlutterMacOS\n\n@main\nclass AppDelegate: FlutterAppDelegate {\n\n override func applicationShouldTermin"
},
{
"path": "macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json",
"chars": 1582,
"preview": "{\n \"info\": {\n \"version\": 1,\n \"author\": \"xcode\"\n },\n \"images\": [\n {\n \"size\": \"16"
},
{
"path": "macos/Runner/Base.lproj/MainMenu.xib",
"chars": 23723,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<document type=\"com.apple.InterfaceBuilder3.Cocoa.XIB\" version=\"3.0\" toolsVersion"
},
{
"path": "macos/Runner/Configs/AppInfo.xcconfig",
"chars": 608,
"preview": "// Application-level settings for the Runner target.\n//\n// This may be replaced with something auto-generated from metad"
},
{
"path": "macos/Runner/Configs/Debug.xcconfig",
"chars": 77,
"preview": "#include \"../../Flutter/Flutter-Debug.xcconfig\"\n#include \"Warnings.xcconfig\"\n"
},
{
"path": "macos/Runner/Configs/Release.xcconfig",
"chars": 79,
"preview": "#include \"../../Flutter/Flutter-Release.xcconfig\"\n#include \"Warnings.xcconfig\"\n"
},
{
"path": "macos/Runner/Configs/Warnings.xcconfig",
"chars": 580,
"preview": "WARNING_CFLAGS = -Wall -Wconditional-uninitialized -Wnullable-to-nonnull-conversion -Wmissing-method-return-type -Woverl"
},
{
"path": "macos/Runner/DebugProfile.entitlements",
"chars": 349,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/P"
},
{
"path": "macos/Runner/Info.plist",
"chars": 1060,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/P"
},
{
"path": "macos/Runner/MainFlutterWindow.swift",
"chars": 1371,
"preview": "import Cocoa\nimport FlutterMacOS\nimport window_manager\n// Add the LaunchAtLogin module\nimport LaunchAtLogin\n\nclass MainF"
},
{
"path": "macos/Runner/Release.entitlements",
"chars": 241,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/P"
},
{
"path": "macos/Runner.xcodeproj/project.pbxproj",
"chars": 34744,
"preview": "// !$*UTF8*$!\n{\n\tarchiveVersion = 1;\n\tclasses = {\n\t};\n\tobjectVersion = 54;\n\tobjects = {\n\n/* Begin PBXAggregateTarget sec"
},
{
"path": "macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist",
"chars": 238,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/P"
},
{
"path": "macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme",
"chars": 3671,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Scheme\n LastUpgradeVersion = \"1510\"\n version = \"1.3\">\n <BuildAction\n "
},
{
"path": "macos/Runner.xcworkspace/contents.xcworkspacedata",
"chars": 224,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Workspace\n version = \"1.0\">\n <FileRef\n location = \"group:Runner.xcodepr"
},
{
"path": "macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist",
"chars": 238,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/P"
},
{
"path": "macos/Runner.xcworkspace/xcshareddata/swiftpm/Package.resolved",
"chars": 323,
"preview": "{\n \"pins\" : [\n {\n \"identity\" : \"launchatlogin-modern\",\n \"kind\" : \"remoteSourceControl\",\n \"location\" :"
},
{
"path": "macos/RunnerTests/RunnerTests.swift",
"chars": 290,
"preview": "import FlutterMacOS\nimport Cocoa\nimport XCTest\n\nclass RunnerTests: XCTestCase {\n\n func testExample() {\n // If you ad"
},
{
"path": "macos/packaging/dmg/make_config.yaml",
"chars": 138,
"preview": "title: Lux\ncontents:\n - x: 448\n y: 344\n type: link\n path: \"/Applications\"\n - x: 192\n y: 344\n type: file"
},
{
"path": "pubspec.yaml",
"chars": 4776,
"preview": "name: lux\ndescription: A light desktop proxy app.\n# The following line prevents the package from being accidentally publ"
},
{
"path": "scripts/constant.dart",
"chars": 33,
"preview": "const rawCoreVersion = '1.33.1';\n"
},
{
"path": "scripts/init.dart",
"chars": 2858,
"preview": "// ignore_for_file: avoid_print\n\nimport 'dart:io';\n\nimport 'package:args/args.dart';\nimport 'package:dio/dio.dart';\nimpo"
},
{
"path": "scripts/update_core_sha256.dart",
"chars": 2485,
"preview": "import 'dart:io';\n\nimport 'package:dio/dio.dart';\nimport 'package:path/path.dart' as p;\n\nimport 'constant.dart';\n\nclass "
},
{
"path": "test/widget_test.dart",
"chars": 0,
"preview": ""
},
{
"path": "windows/.gitignore",
"chars": 291,
"preview": "flutter/ephemeral/\n\n# Visual Studio user-specific files.\n*.suo\n*.user\n*.userosscache\n*.sln.docstates\n\n# Visual Studio bu"
},
{
"path": "windows/CMakeLists.txt",
"chars": 3893,
"preview": "# Project-level configuration.\ncmake_minimum_required(VERSION 3.14)\nproject(lux LANGUAGES CXX)\n\n# The name of the execut"
},
{
"path": "windows/flutter/CMakeLists.txt",
"chars": 3742,
"preview": "# This file controls Flutter-level build steps. It should not be edited.\ncmake_minimum_required(VERSION 3.14)\n\nset(EPHEM"
},
{
"path": "windows/flutter/generated_plugin_registrant.cc",
"chars": 1197,
"preview": "//\n// Generated file. Do not edit.\n//\n\n// clang-format off\n\n#include \"generated_plugin_registrant.h\"\n\n#include <connect"
},
{
"path": "windows/flutter/generated_plugin_registrant.h",
"chars": 302,
"preview": "//\n// Generated file. Do not edit.\n//\n\n// clang-format off\n\n#ifndef GENERATED_PLUGIN_REGISTRANT_\n#define GENERATED_PLUG"
},
{
"path": "windows/flutter/generated_plugins.cmake",
"chars": 899,
"preview": "#\n# Generated file, do not edit.\n#\n\nlist(APPEND FLUTTER_PLUGIN_LIST\n connectivity_plus\n power_monitor\n screen_retriev"
},
{
"path": "windows/packaging/exe/make_config.yaml",
"chars": 441,
"preview": "# The value of AppId uniquely identifies this application.\n# Do not use the same AppId value in installers for other app"
},
{
"path": "windows/packaging/exe/setup.iss",
"chars": 3951,
"preview": "[Setup]\nAppId={{APP_ID}}\nAppVersion={{APP_VERSION}}\nAppName={{DISPLAY_NAME}}\nAppPublisher={{PUBLISHER_NAME}}\nAppPublishe"
},
{
"path": "windows/runner/CMakeLists.txt",
"chars": 1796,
"preview": "cmake_minimum_required(VERSION 3.14)\nproject(runner LANGUAGES CXX)\n\n# Define the application target. To change its name,"
},
{
"path": "windows/runner/Runner.rc",
"chars": 3105,
"preview": "// Microsoft Visual C++ generated resource script.\n//\n#pragma code_page(65001)\n#include \"resource.h\"\n\n#define APSTUDIO_R"
},
{
"path": "windows/runner/flutter_window.cpp",
"chars": 1860,
"preview": "#include \"flutter_window.h\"\n\n#include <optional>\n\n#include \"flutter/generated_plugin_registrant.h\"\n\nFlutterWindow::Flutt"
},
{
"path": "windows/runner/flutter_window.h",
"chars": 928,
"preview": "#ifndef RUNNER_FLUTTER_WINDOW_H_\n#define RUNNER_FLUTTER_WINDOW_H_\n\n#include <flutter/dart_project.h>\n#include <flutter/f"
},
{
"path": "windows/runner/main.cpp",
"chars": 1460,
"preview": "#include <flutter/dart_project.h>\n#include <flutter/flutter_view_controller.h>\n#include <windows.h>\n\n#include \"flutter_w"
},
{
"path": "windows/runner/resource.h",
"chars": 432,
"preview": "//{{NO_DEPENDENCIES}}\n// Microsoft Visual C++ generated include file.\n// Used by Runner.rc\n//\n#define IDI_APP_ICON "
},
{
"path": "windows/runner/runner.exe.manifest",
"chars": 874,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<assembly xmlns=\"urn:schemas-microsoft-com:asm.v1\" manifestVersi"
},
{
"path": "windows/runner/utils.cpp",
"chars": 1788,
"preview": "#include \"utils.h\"\n\n#include <flutter_windows.h>\n#include <io.h>\n#include <stdio.h>\n#include <windows.h>\n\n#include <iost"
},
{
"path": "windows/runner/utils.h",
"chars": 672,
"preview": "#ifndef RUNNER_UTILS_H_\n#define RUNNER_UTILS_H_\n\n#include <string>\n#include <vector>\n\n// Creates a console for the proce"
},
{
"path": "windows/runner/win32_window.cpp",
"chars": 8628,
"preview": "#include \"win32_window.h\"\n\n#include <dwmapi.h>\n#include <flutter_windows.h>\n\n#include \"resource.h\"\n\nnamespace {\n\n/// Win"
},
{
"path": "windows/runner/win32_window.h",
"chars": 3522,
"preview": "#ifndef RUNNER_WIN32_WINDOW_H_\n#define RUNNER_WIN32_WINDOW_H_\n\n#include <windows.h>\n\n#include <functional>\n#include <mem"
}
]
// ... and 1 more files (download for full content)
About this extraction
This page contains the full source code of the igoogolx/lux GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 92 files (273.9 KB), approximately 70.5k tokens, and a symbol index with 239 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.